📜  蛇游戏 (1)

📅  最后修改于: 2023-12-03 15:27:52.646000             🧑  作者: Mango

蛇游戏

简介

蛇游戏是一款经典的游戏,目标是控制一条蛇在游戏区域中移动并吃掉食物,每吃到一块食物,蛇的长度会增加。游戏结束的条件为蛇头碰到边界或者蛇的身体。

实现方法
游戏界面

游戏界面可以通过 Python 中的 tkinter 模块来实现,具体实现方法可参考 tkinter 官方文档

游戏逻辑
  • 控制蛇的移动:通过设置一个方向变量,不断根据方向变量更新蛇的位置,并且在更新蛇位置时判断是否吃到食物,是否碰到身体或者边界。
  • 生成随机食物:在游戏区域内生成随机位置的食物,保证食物不会出现在蛇的位置上。
  • 更新游戏分数:每吃到一块食物,分数会加一,并显示在游戏界面上。
代码实现

下面是一个简单的蛇游戏实现,其中 Snake 类封装了游戏的逻辑实现,main 函数为游戏的入口。

import tkinter as tk
import random

class Snake:
    def __init__(self, canvas):
        self.canvas = canvas
        self.snake = [(80, 80), (100, 80), (120, 80)]
        self.direction = 'Right'
        self.food = self.create_food()
        self.score = 0
        self.delay = 100
        self.is_game_over = False

    def create_food(self):
        food = None
        while food is None:
            x = random.randint(1, 29) * 20
            y = random.randint(1, 29) * 20
            if (x, y) not in self.snake:
                food = self.canvas.create_oval(x, y, x + 20, y + 20, fill='blue')
        return food

    def move_snake(self):
        head = self.snake[-1]
        if self.direction == 'Right':
            new_head = (head[0] + 20, head[1])
        elif self.direction == 'Left':
            new_head = (head[0] - 20, head[1])
        elif self.direction == 'Up':
            new_head = (head[0], head[1] - 20)
        elif self.direction == 'Down':
            new_head = (head[0], head[1] + 20)
        self.snake.append(new_head)

        if new_head == self.food:
            self.canvas.delete(self.food)
            self.food = self.create_food()
            self.score += 1
        else:
            self.snake.pop(0)

        self.canvas.delete('snake')
        for x, y in self.snake:
            self.canvas.create_rectangle(x, y, x + 20, y + 20, fill='green', tag='snake')
        self.canvas.itemconfig(self.canvas.find_withtag('score'), text='Score: {}'.format(self.score))

        if self.check_game_over():
            self.is_game_over = True

        if not self.is_game_over:
            self.canvas.after(self.delay, self.move_snake)

    def check_game_over(self):
        head = self.snake[-1]
        if not (0 <= head[0] <= 580 and 0 <= head[1] <= 580):
            return True
        if head in self.snake[:-1]:
            return True
        return False

    def on_key_press(self, event):
        if event.keysym == 'Right':
            self.direction = 'Right'
        elif event.keysym == 'Left':
            self.direction = 'Left'
        elif event.keysym == 'Up':
            self.direction = 'Up'
        elif event.keysym == 'Down':
            self.direction = 'Down'

def main():
    root = tk.Tk()
    root.title('Snake Game')
    root.resizable(False, False)

    canvas = tk.Canvas(root, width=600, height=600, bg='white')
    canvas.pack()

    canvas.create_text(150, 20, text='Score: 0', tag='score')

    snake = Snake(canvas)

    canvas.bind_all('<KeyPress>', snake.on_key_press)

    snake.move_snake()

    root.mainloop()

if __name__ == '__main__':
    main()
运行效果

snake_game_demo