蛇在蟒蛇的蛇游戏中不吃食物

时间:2021-04-27 15:30:48

标签: python tkinter

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

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()

1 个答案:

答案 0 :(得分:2)

您的食物可以在代码中的任何整数坐标处生成。然而,蛇只以SPACE_SIZE的倍数移动。一块食物在蛇实际上可以到达的点被初始化的几率是 1/SPACE_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 语句以允许坐标存在一些小的差异,但这对于原始的蛇游戏来说不太真实。