IDLE贪吃蛇游戏代码
时间: 2023-07-03 10:12:59 浏览: 94
以下是一个简单的贪吃蛇游戏代码示例,使用 Python 的 Tkinter 库实现游戏界面和交互:
```python
import tkinter as tk
import random
class Snake:
def __init__(self, size):
self.size = size
self.body = [(size // 2, size // 2)]
self.direction = (0, 1)
def move(self, food):
head = self.body[-1]
new_head = (head[0] + self.direction[0], head[1] + self.direction[1])
if new_head == food:
self.body.append(new_head)
return True
elif new_head in self.body or not (0 <= new_head[0] < self.size and 0 <= new_head[1] < self.size):
return False
else:
self.body.append(new_head)
self.body.pop(0)
return True
def change_direction(self, direction):
if (direction[0] + self.direction[0], direction[1] + self.direction[1]) != (0, 0):
self.direction = direction
class Game:
def __init__(self, size):
self.size = size
self.snake = Snake(size)
self.food = self.generate_food()
self.root = tk.Tk()
self.canvas = tk.Canvas(self.root, width=480, height=480)
self.canvas.pack()
self.canvas.bind("<KeyPress>", self.on_keypress)
self.draw_board()
self.root.after(1000, self.update)
self.root.mainloop()
def draw_board(self):
self.canvas.delete("all")
for i in range(self.size):
self.canvas.create_line(40, 40 + i * 30, 440, 40 + i * 30)
self.canvas.create_line(40 + i * 30, 40, 40 + i * 30, 440)
for i, j in self.snake.body:
self.canvas.create_rectangle(35 + j * 30, 35 + i * 30, 65 + j * 30, 65 + i * 30, fill="black")
i, j = self.food
self.canvas.create_oval(35 + j * 30, 35 + i * 30, 65 + j * 30, 65 + i * 30, fill="red")
def generate_food(self):
while True:
i, j = random.randint(0, self.size - 1), random.randint(0, self.size - 1)
if (i, j) not in self.snake.body:
return i, j
def on_keypress(self, event):
if event.keysym == "Up":
self.snake.change_direction((-1, 0))
elif event.keysym == "Down":
self.snake.change_direction((1, 0))
elif event.keysym == "Left":
self.snake.change_direction((0, -1))
elif event.keysym == "Right":
self.snake.change_direction((0, 1))
def update(self):
if not self.snake.move(self.food):
print("Game over!")
self.root.destroy()
else:
if self.snake.body[-1] == self.food:
self.food = self.generate_food()
self.draw_board()
self.root.after(100, self.update)
game = Game(15)
```
运行代码后,将出现一个 15x15 的游戏界面,玩家可通过方向键控制贪吃蛇的移动,吃到红色的食物后贪吃蛇会变长。当贪吃蛇碰到边界或自身时,游戏结束。可以通过关闭窗口来结束游戏。
阅读全文