在Python游戏中蛇不吃食物

tf7tbtn2  于 2021-07-13  发布在  Java
关注(0)|答案(1)|浏览(342)

运行代码时,当蛇和食物坐标相等时,食物应该被删除,分数应该增加1,要添加到snake的另一个正方形和要创建的新食物对象,但即使snake对象和食物对象的坐标重叠,下一个\u turn函数中的if语句也不起作用,snake只是在没有任何所需更改的情况下从食物对象上跑过。

from tkinter import *
import random

# Constants

GAME_WIDTH = 700
GAME_HEIGHT = 700
SPEED = 50
SPACE_SIZE = 50
BODY_PARTS = 2
SNAKE_COLOR = '#00FF00'
FOOD_COLOR = '#FF0000'
BG_COLOR = '#000000'

class Snake:

    def __init__(self):
        self.body_size = BODY_PARTS
        self.coordinates = []
        self.squares = []

        for i in range(BODY_PARTS):
            self.coordinates.append([0, 0])

        for x, y in self.coordinates:
            square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill = SNAKE_COLOR, tag = 'snake')
        self.squares.append(square)

class Food:

    def __init__(self):

        x = random.randint(0, ((GAME_WIDTH/SPACE_SIZE)-1)*SPACE_SIZE)
        y = random.randint(0, ((GAME_HEIGHT/SPACE_SIZE)-1)*SPACE_SIZE)

        self.coordinates = [x, y]

        self.some = canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill = FOOD_COLOR, tag = 'foodtherealdeal')

def next_turn(snake, food):

    x, y = snake.coordinates[0]

    if direction == 'up':
        y -= SPACE_SIZE

    elif direction == 'down':
        y += SPACE_SIZE

    elif direction == 'left':
        x -= SPACE_SIZE

    elif direction == 'right':
        x += SPACE_SIZE

    snake.coordinates.insert(0, (x, y))

    square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill = SNAKE_COLOR)

    snake.squares.insert(0, square)

    if [x, y] == food.coordinates :

        global score

        score += 1

        label.config(text=f'Score : {score}')

        canvas.delete('foodtherealdeal')

        food = Food()

    else:
        del snake.coordinates[-1]

        canvas.delete(snake.squares[-1])

        del snake.squares[-1]

    window.after(SPEED, next_turn, snake, food)

def change_dir(new_dir):

    global direction

    if new_dir == 'left':
        if direction != 'right':
            direction = new_dir

    elif new_dir == 'right':
        if direction != 'left':
            direction = new_dir

    elif new_dir == 'up':
        if direction != 'down':
            direction = new_dir    

    elif new_dir == 'down':
        if direction != 'up':
            direction = new_dir

def check_collision():
    pass

def gameOver():
    pass

window = Tk()
window.title("Snake Game")
window.resizable(False, False)
score = 0
direction = 'down'

label = Label(window, text=f"Score : {score}", font=('consolas', 40))
label.pack()

canvas = Canvas(window, bg = BG_COLOR, height = GAME_HEIGHT, width = GAME_WIDTH)
canvas.pack()

window.update()

window_width = window.winfo_width()
window_height = window.winfo_height()
screen_width = window.winfo_screenwidth()
screen_height = window.winfo_screenheight()

x = int((screen_width/2) - (window_width/2))
y = int((screen_height/2) - (window_height/2))

window.geometry(f"{window_width}x{window_height}+{x}+{y}")

# Controls

window.bind('<Left>', lambda event: change_dir('left'))
window.bind('<Right>', lambda event: change_dir('right'))
window.bind('<Up>', lambda event: change_dir('up'))
window.bind('<Down>', lambda event: change_dir('down'))

window.bind('A', lambda event: change_dir('left'))
window.bind('D', lambda event: change_dir('right'))
window.bind('W', lambda event: change_dir('up'))
window.bind('S', lambda event: change_dir('down'))

window.bind('a', lambda event: change_dir('left'))
window.bind('d', lambda event: change_dir('right'))
window.bind('w', lambda event: change_dir('up'))
window.bind('s', lambda event: change_dir('down'))

snake = Snake()

food = Food()

next_turn(snake, food)

window.mainloop()
c9qzyr3d

c9qzyr3d1#

你的食物可以在你的代码中的任何整数坐标下产卵。但是,蛇只会以倍数的速度移动 SPACE_SIZE . 一块食物被初始化的几率是1/space\u size**2==1/2500,蛇实际上可以到达它。要解决这个问题,需要对移动括号进行细微的更改:

def __init__(self):
    x = random.randint(0, (GAME_WIDTH / SPACE_SIZE) - 1) * SPACE_SIZE
    y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE

这就产生了食物的坐标是 SPACE_SIZE 所以蛇总是可以接近它们。
或者,您可以更改if语句以允许坐标中存在一些小的差异,但这对于snake的原始游戏来说就不那么正确了。

相关问题