python - 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)
解决方案
推荐阅读
- react-native - 反应本机传奇获取数据格式问题
- android - 即使路径正确,Unity 也无法选择 Android SDK
- dart - Firestore- Flutter array contains
- django - Django Rest Framework - 对依赖于另一个反向关系的反向相关表的数据进行序列化
- node.js - 节点请求模块未返回正确的 statusCode
- javascript - How To Create a Timestamp In JavaScript
- android - set header and content horizontally in recyclerview android
- android - WindowManager 不允许通过触摸
- node.js - 与 webpack 捆绑时如何使 node.js 在没有 node_modules 的情况下工作?
- ios - One object in multiple sections when sorting with NSFetchedResultsController