python 代码设计贪吃蛇

复制代码
代码:
# -*- codeing = utf-8 -*-
import tkinter as tk
import random
from tkinter import messagebox

class Snake:
    def __init__(self, master):
        self.master = master
        self.master.title("Snake")

        # 创建画布
        self.canvas = tk.Canvas(self.master, width=400, height=400, bg="white")
        self.canvas.pack()

        # 初始化游戏数据
        self.snake = [(0, 0), (0, 1), (0, 2)]
        self.food = (5, 5)
        self.direction = "Right"
        self.score = 0

        # 绑定键盘事件
        self.master.bind("<Key>", self.on_key_press)

        # 开始游戏
        self.start_game()

    def start_game(self):
        # 绘制贪吃蛇和食物
        self.draw_snake()
        self.draw_food()

        # 更新游戏状态
        self.update_game()

    def draw_snake(self):
        # 清空画布
        self.canvas.delete("all")

        # 绘制贪吃蛇
        for x, y in self.snake:
            x1 = x * 20
            y1 = y * 20
            x2 = x1 + 20
            y2 = y1 + 20
            self.canvas.create_rectangle(x1, y1, x2, y2, fill="green")

    def draw_food(self):
        # 绘制食物
        x1 = self.food[0] * 20
        y1 = self.food[1] * 20
        x2 = x1 + 20
        y2 = y1 + 20
        self.canvas.create_oval(x1, y1, x2, y2, fill="red")

    def update_game(self):
        # 更新贪吃蛇位置
        head_x, head_y = self.snake[-1]
        if self.direction == "Left":
            new_head = (head_x - 1, head_y)
        elif self.direction == "Right":
            new_head = (head_x + 1, head_y)
        elif self.direction == "Up":
            new_head = (head_x, head_y - 1)
        else:
            new_head = (head_x, head_y + 1)
        self.snake.append(new_head)
        del self.snake[0]

        # 检查游戏是否结束
        if new_head[0] < 0 or new_head[0] >= 20 or new_head[1] < 0 or new_head[1] >= 20 or new_head in self.snake[:-1]:
            tk.messagebox.showinfo("Game Over", f"Score: {self.score}")
            return

        # 检查贪吃蛇是否吃掉食物
        if new_head == self.food:
            while True:
                food_x = random.randint(0, 19)
                food_y = random.randint(0, 19)
                if (food_x, food_y) not in self.snake:
                    break
            self.food = (food_x, food_y)
            tail_x, tail_y = self.snake[0]
            if self.direction == "Left":
                new_tail = (tail_x + 1, tail_y)
            elif self.direction == "Right":
                new_tail = (tail_x - 1, tail_y)
            elif self.direction == "Up":
                new_tail = (tail_x, tail_y + 1)
            else:
                new_tail = (tail_x, tail_y - 1)
            self.snake.insert(0, new_tail)
            self.score += 1

        # 绘制贪吃蛇和食物
        self.draw_snake()
        self.draw_food()

        # 定时更新游戏状态
        self.master.after(200, self.update_game)

    def on_key_press(self, event):
        if event.keysym in ["Left", "Right", "Up", "Down"]:
            self.direction = event.keysym

if __name__ == "__main__":
    root = tk.Tk()
    snake = Snake(root)
    root.mainloop()

结果图:

相关推荐
松仔log10 分钟前
Java多线程——对象的组合
java·开发语言·jvm
深蓝海拓10 分钟前
基于深度学习的视觉检测小项目(十六) 用户管理界面的组态
人工智能·python·深度学习·qt·pyqt
Qhumaing13 分钟前
Python学习——函数参数详解
开发语言·python·学习
Icomi_25 分钟前
【PyTorch】7.自动微分模块:开启神经网络 “进化之门” 的魔法钥匙
c语言·c++·人工智能·pytorch·python·机器学习·计算机视觉
ElvInR40 分钟前
【C语言】动态内存管理
c语言·开发语言
加油,旭杏1 小时前
【go语言】grpc 快速入门
开发语言·后端·golang
行路见知1 小时前
1.4 Go 数组
开发语言
2501_903238651 小时前
Java 9模块开发:Eclipse实战指南
java·开发语言·eclipse·个人开发
ahardstone1 小时前
【CS61A 2024秋】Python入门课,全过程记录P5(Week8 Inheritance开始,更新于2025/2/2)
开发语言·python
阿豪学编程1 小时前
c++ string类 +底层模拟实现
开发语言·c++