python实现贪吃鸡

bash 复制代码
import tkinter as tk
import random


class SnakeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("Snake Game")
        self.master.geometry("400x400")

        self.canvas = tk.Canvas(self.master, bg="black")
        self.canvas.pack(fill=tk.BOTH, expand=True)

        self.snake = [(20, 20)]
        self.food = self.create_food()
        self.direction = "Right"
        self.score = 0
        self.speed = 100
        self.game_over = False

        self.draw_snake()
        self.draw_food()

        self.master.bind("<Key>", self.change_direction)
        self.update_snake_position()

    def draw_snake(self):
        self.canvas.delete("snake")
        for segment in self.snake:
            x, y = segment
            self.canvas.create_rectangle(x, y, x + 20, y + 20, fill="green", tags="snake")

    def draw_food(self):
        x, y = self.food
        self.canvas.create_oval(x, y, x + 20, y + 20, fill="red", tags="food")

    def create_food(self):
        while True:
            x = random.randint(0, 19) * 20
            y = random.randint(0, 19) * 20
            if (x, y) not in self.snake:
                return (x, y)

    def move_snake(self):
        head_x, head_y = self.snake[0]

        if self.direction == "Left":
            new_head = (head_x - 20, head_y)
        elif self.direction == "Right":
            new_head = (head_x + 20, head_y)
        elif self.direction == "Up":
            new_head = (head_x, head_y - 20)
        elif self.direction == "Down":
            new_head = (head_x, head_y + 20)

        # Check if new head collides with itself or walls
        if self.check_collision(new_head):
            self.game_over = True
            self.canvas.create_text(200, 200, text=f"Game Over! Score: {self.score}", fill="white",
                                    font=("Helvetica", 24))
            self.canvas.create_text(200, 230, text="Press Space to Restart", fill="white", font=("Helvetica", 16))
            return

        # Insert new head at the beginning of snake list
        self.snake.insert(0, new_head)

        # Check if snake eats food
        if new_head == self.food:
            self.score += 1
            self.canvas.delete("food")
            self.food = self.create_food()
            self.draw_food()
        else:
            # Remove the last segment of snake if it doesn't eat food
            self.snake.pop()

        self.draw_snake()

        # Schedule the next move
        if not self.game_over:
            self.master.after(self.speed, self.move_snake)

    def check_collision(self, head):
        x, y = head
        # Check wall collision
        if x < 0 or x >= 400 or y < 0 or y >= 400:
            return True
        # Check self collision
        if head in self.snake[1:]:
            return True
        return False

    def update_snake_position(self):
        if not self.game_over:
            self.move_snake()

    def change_direction(self, event):
        if event.keysym in ["Left", "Right", "Up", "Down"]:
            if (event.keysym == "Left" and self.direction != "Right") or \
                    (event.keysym == "Right" and self.direction != "Left") or \
                    (event.keysym == "Up" and self.direction != "Down") or \
                    (event.keysym == "Down" and self.direction != "Up"):
                self.direction = event.keysym
        elif event.keysym == "space" and self.game_over:
            self.restart_game()

    def restart_game(self):
        self.snake = [(20, 20)]
        self.food = self.create_food()
        self.direction = "Right"
        self.score = 0
        self.speed = 100
        self.game_over = False
        self.canvas.delete("all")
        self.draw_snake()
        self.draw_food()
        self.update_snake_position()


if __name__ == "__main__":
    root = tk.Tk()
    game = SnakeGame(root)
    root.mainloop()
相关推荐
秃头佛爷32 分钟前
Python学习大纲总结及注意事项
开发语言·python·学习
待磨的钝刨34 分钟前
【格式化查看JSON文件】coco的json文件内容都在一行如何按照json格式查看
开发语言·javascript·json
深度学习lover2 小时前
<项目代码>YOLOv8 苹果腐烂识别<目标检测>
人工智能·python·yolo·目标检测·计算机视觉·苹果腐烂识别
XiaoLeisj3 小时前
【JavaEE初阶 — 多线程】单例模式 & 指令重排序问题
java·开发语言·java-ee
API快乐传递者3 小时前
淘宝反爬虫机制的主要手段有哪些?
爬虫·python
励志成为嵌入式工程师3 小时前
c语言简单编程练习9
c语言·开发语言·算法·vim
捕鲸叉4 小时前
创建线程时传递参数给线程
开发语言·c++·算法
A charmer4 小时前
【C++】vector 类深度解析:探索动态数组的奥秘
开发语言·c++·算法
Peter_chq4 小时前
【操作系统】基于环形队列的生产消费模型
linux·c语言·开发语言·c++·后端
阡之尘埃5 小时前
Python数据分析案例61——信贷风控评分卡模型(A卡)(scorecardpy 全面解析)
人工智能·python·机器学习·数据分析·智能风控·信贷风控