首页 > 解决方案 > Python Sense 帽子蛇

问题描述

我正在使用 Sense Hat 模拟器 ( https://trinket.io/sense-hat ),并尝试制作一个简单的蛇游戏。当我吃第一个食物时,这条蛇会长大,但它会无限长。然后它在第二种食物上崩溃。我不知道如何解决这个问题,并且会喜欢任何输入!这是我第一次用 Python 编码。

from sense_hat import SenseHat
from time import sleep
from random import randint

sense = SenseHat()

black = (0, 0, 0)
red = (255, 0, 0)
posy = [4]
posx = [4]
color = (0, 0, 255)
speed = 1
direction = 0
eatcount = 0
exist = 0
tempposx = 0
tempposy = 0
oldposx = 0
oldposy = 0

try:
  while True:
    randposx = randint(0,7)
    randposy = randint(0,7)
    
    if len(posx) == 1:
     sense.set_pixel(posx[len(posx) - 1], posy[len(posy) - 1], (0, 0, 0))
    
    for event in sense.stick.get_events():
      if event.action == "pressed":
        if event.direction == "up":
          if direction != 2:
            direction = 1
        elif event.direction == "down":
          if direction != 1:
            direction = 2
        elif event.direction == "left":
          if direction != 4:
            direction = 3
        elif event.direction == "right":
          if direction != 3:
            direction = 4
        elif event.direction == "middle":
          direction = 5
          
    oldposx = posx[0]
    oldposy = posy[0]
  
    if direction == 1:
      posx[0] -=1
    elif direction == 2:
      posx[0] +=1
    elif direction == 3:
      posy[0] +=1
    elif direction == 4:
      posy[0] -=1
    elif direction == 5:
      posx[0] +=1

    if exist == 1:
      if tempposx == posx[0] and tempposy == posy[0]:
        exist = 0
        eatcount += 1
        posx.append(tempposx)
        posy.append(tempposy)
        if speed > 0.2:
          speed -= 0.05
  
    if exist == 0:
      sense.set_pixel(randposx, randposy, red)
      tempposx = randposx
      tempposy = randposy
      exist = 1
      
    if len(posx) > 1:
      for i in range(1, len(posx) - 1, 1):
        sense.set_pixel(posx[oldposx], posy[oldposy], color)
        sense.set_pixel(posx[i], posy[i], (0, 0, 0))
        oldposx = posx[i]
        oldposy = posy[i]
    
    sense.set_pixel(posx[0], posy[0], color)
    sleep(speed)
    
    
except:
  sense.show_message("Game Over - Score: " + str(eatcount), text_colour=red, back_colour=black, scroll_speed=0.03)

标签: python

解决方案


推荐阅读