ChatGPT与我们玩游戏_贪吃蛇
作者:顾翔import tkinter as tk
import random
           
class SnakeGame:
    def __init__(self, master):
        self.master = master
        self.master.title("贪吃蛇")
        self.board_size = 400  # 游戏画布大小
        self.cell_size = 20  # 每个格子的大小
        self.rows = self.board_size // self.cell_size
        self.cols = self.board_size // self.cell_size
           
        # 初始化游戏状态
        self.snake = [(5, 5), (5, 4), (5, 3)]  # 蛇的初始位置(用格子坐标表示)    
        self.food = None
        self.direction = "Right"  # 蛇的初始方向
        self.running = True
           
        # 创建画布
        self.canvas = tk.Canvas(self.master, width=self.board_size, height=self.board_size, bg="black")
        self.canvas.pack()
           
        # 绑定键盘事件
        self.master.bind("", self.change_direction)
           
        # 放置食物
        self.place_food()
           
        # 开始游戏循环
        self.update_game()
           
    def place_food(self):
        """随机放置食物"""
        while True:
            food = (random.randint(0, self.rows - 1), random.randint(0, self.cols - 1))    
            if food not in self.snake:  # 确保食物不会出现在蛇的身体上
                self.food = food
                break
           
    def change_direction(self, event):
        """更改蛇的移动方向"""
        new_direction = event.keysym
        # 防止蛇直接反向移动
        if (new_direction == "Up" and self.direction != "Down") or 
           (new_direction == "Down" and self.direction != "Up") or 
           (new_direction == "Left" and self.direction != "Right") or 
           (new_direction == "Right" and self.direction != "Left"):
            self.direction = new_direction
           
    def update_game(self):
        """更新游戏状态"""
        if not self.running:
            return
           
        # 移动蛇
        head_x, head_y = self.snake[0]    
        if self.direction == "Up":
            head_x -= 1
        elif self.direction == "Down":
            head_x += 1
        elif self.direction == "Left":
            head_y -= 1
        elif self.direction == "Right":
            head_y += 1
           
        # 新的蛇头位置
        new_head = (head_x, head_y)
           
        # 检查游戏结束条件
        if (new_head in self.snake or  # 撞到自己
            head_x < 0 or head_x >= self.rows or  # 撞到上/下边界
            head_y < 0 or head_y >= self.cols):  # 撞到左/右边界
            self.running = False
            self.game_over()
            return
           
        # 更新蛇的身体
        self.snake.insert(0, new_head)    
        if new_head == self.food:
            # 吃到食物,放置新的食物
            self.place_food()
        else:
            # 没有吃到食物,移除蛇尾
            self.snake.pop()
           
        # 更新画布
        self.update_canvas()
           
        # 设置游戏循环的速度(100毫秒更新一次)
        self.master.after(300, self.update_game)
           
    def update_canvas(self):
        """更新画布内容"""
        self.canvas.delete("all")  # 清空画布
           
        # 绘制蛇
        for x, y in self.snake:
            x1 = y * self.cell_size
            y1 = x * self.cell_size
            x2 = x1 + self.cell_size    
            y2 = y1 + self.cell_size
            self.canvas.create_rectangle(x1, y1, x2, y2, fill="green", outline="")
           
        # 绘制食物
        if self.food:
            fx, fy = self.food
            x1 = fy * self.cell_size
            y1 = fx * self.cell_size
            x2 = x1 + self.cell_size
            y2 = y1 + self.cell_size
            self.canvas.create_oval(x1, y1, x2, y2, fill="red", outline="")
           
    def game_over(self):
        """游戏结束"""
        self.canvas.create_text(self.board_size // 2, self.board_size // 2,
                                text="游戏结束", fill="white", font=("Arial", 24))
           
if __name__ == "__main__":
    root = tk.Tk()
    game = SnakeGame(root)    
    root.mainloop()