如何在树莓派SenseHat上为我的蛇游戏加长蛇

时间:2019-04-03 12:50:05

标签: python raspberry-pi

我正在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

谢谢

1 个答案:

答案 0 :(得分:1)

snake.append(next)中的

move处于无状态。另外,您有两个if next in vegetables条件,第一个条件将其从列表中删除,这意味着第二个条件始终为false。您可能想将两者合并。