如何使我的蛇更长的蛇游戏对我的树莓皮感官

2024-04-16 04:20:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在SenseHat上做一个蛇游戏,我正在学习的网站告诉我,我需要使用mod操作符,以便让我的蛇每次吃东西都长得更长。但我的蛇却开始永远长高,即使它什么也不吃

以下是我一直在使用的网站(链接会将您直接发送到我所停留的部分): https://projects.raspberrypi.org/en/projects/slug/9

虽然我已经看了一段时间了,但我不知道在我的剧本里应该把这个放在哪里,怎么放

这是我整个游戏的剧本。你知道吗

import random
from random import randint
import time
from sense_hat import SenseHat
sense = SenseHat()


vegetables = []
direction = "right"
colx = randint(0,255)
coly = randint(0,255)
colz = randint(0,255)
food_col = (colx, coly, colz)
blank = (0, 0, 0)
white = (255, 255, 255)
green = (0, 255, 0)
snake =[ [2,4], [3,4], [4,4] ]
score = (0)

def move():
  global score
  last = snake[-1]
  first = snake[0]
  next = list(last)     
  remove = True

  if direction == "right":
    if last[0] + 1 == 8:
     next[0] = 0
    else:
     next[0] = last[0] + 1

  elif direction == "left":
    if last[0] - 1 == -1: 
      next[0] = 7
    else:
      next[0] = last[0] - 1

  elif direction == "down":
    if last[1] + 1 == 8: 
      next[1] = 0
    else:
      next[1] = last[1] + 1

  elif direction == "up":
    if last[1] - 1 == -1: 
      next[1] = 7
    else: 
      next[1] = last[1] - 1

  if next in vegetables:
    vegetables.remove(next)
    score == 1

  if next in vegetables:
    if remove == True:
      sense.set_pixel(first[0], first[1], blank)
      snake.remove(first)
    if score % 5 == 0:
      remove = False
  snake.append(next)
  sense.set_pixel(next[0], next[1], green)
def draw_snake():
  for segment in snake: 
    sense.set_pixel(segment[0], segment[1], green)

def joystick_moved(event):
  global direction
  direction = event.direction

def make_food():
  new = snake[0]
  while new in snake:
    x = randint(0,7)
    y = randint(0,7)
    new = [x,y]
    for segment in new: 
      sense.set_pixel(x, y, food_col)
  vegetables.append(new)



sense.clear()
draw_snake()
while True: 
  if len(vegetables) < 3: 
    make_food()
  move()
  time.sleep(0.5)
  sense.stick.direction_any = joystick_moved

我想让我的蛇每次吃东西的时候都能长出来,但它只是从一开始就长出来了。这是一个模拟器,如果你想尝试我的脚本上的感觉帽子 https://trinket.io/sense-hat

谢谢


Tags: inimportnewiffooddefremovenext
1条回答
网友
1楼 · 发布于 2024-04-16 04:20:20

move中的snake.append(next)不在条件中。还有两个if next in vegetables条件,第一个条件将其从列表中删除,这意味着第二个条件将始终为false。你可能想把两者合并。你知道吗

相关问题 更多 >