用tkinter库实现贪吃蛇
时间: 2024-05-18 19:09:18 浏览: 11
使用tkinter库实现贪吃蛇,可以按照以下步骤进行:
1. 导入tkinter和random库
```python
import tkinter as tk
import random
```
2. 创建游戏窗口
```python
# 创建一个窗口对象
window = tk.Tk()
# 设置窗口标题
window.title('贪吃蛇')
# 设置窗口大小和位置
window.geometry('500x500+500+200')
# 禁止调整窗口大小
window.resizable(False, False)
```
3. 创建画布
```python
# 创建画布对象
canvas = tk.Canvas(window, bg='white', width=400, height=400)
# 将画布放置到窗口中
canvas.pack()
```
4. 创建贪吃蛇
```python
# 贪吃蛇的坐标列表,初始时有3个小方块
snake = [(100, 100), (90, 100), (80, 100)]
# 创建贪吃蛇的小方块对象,并添加到画布中
for x, y in snake:
canvas.create_rectangle(x, y, x+10, y+10, fill='blue')
```
5. 创建食物
```python
# 随机生成一个食物的坐标
food = (random.randint(0, 39) * 10, random.randint(0, 39) * 10)
# 创建食物的小方块对象,并添加到画布中
canvas.create_rectangle(food, food, food+10, food+10, fill='red')
```
6. 控制贪吃蛇移动
```python
# 定义控制贪吃蛇移动的函数
def move():
# 获取贪吃蛇头部的坐标
x, y = snake
# 根据当前方向计算新的头部坐标
if direction == 'Up':
y -= 10
elif direction == 'Down':
y += 10
elif direction == 'Left':
x -= 10
else:
x += 10
# 添加新的头部坐标到列表中
snake.insert(0, (x, y))
# 判断是否吃到了食物
if snake == food:
# 随机生成一个新的食物的坐标
food = (random.randint(0, 39) * 10, random.randint(0, 39) * 10)
# 在画布中移动食物的小方块对象到新的位置
canvas.coords(food_rect, food, food, food+10, food+10)
else:
# 移除尾部的小方块对象,并从列表中删除尾部坐标
canvas.delete(snake_rects.pop())
snake.pop()
# 创建新的头部小方块对象,并添加到画布中
snake_rects.insert(0, canvas.create_rectangle(x, y, x+10, y+10, fill='blue'))
# 判断游戏是否结束,如果结束则停止移动
if x < 0 or x > 390 or y < 0 or y > 390 or (x, y) in snake[1:]:
return
# 通过after函数定时调用move函数,实现贪吃蛇的移动效果
window.after(100, move)
```
7. 处理键盘事件
```python
# 定义处理键盘事件的函数,改变贪吃蛇移动的方向
def change_direction(event):
global direction
if event.keysym in ['Up', 'Down', 'Left', 'Right']:
if event.keysym == 'Up' and direction != 'Down':
direction = 'Up'
elif event.keysym == 'Down' and direction != 'Up':
direction = 'Down'
elif event.keysym == 'Left' and direction != 'Right':
direction = 'Left'
elif event.keysym == 'Right' and direction != 'Left':
direction = 'Right'
# 绑定键盘事件和处理函数
window.bind('<KeyPress>', change_direction)
```
8. 启动游戏
```python
# 初始化贪吃蛇移动的方向为向右
direction = 'Right'
# 创建贪吃蛇每个小方块的对象列表
snake_rects = [canvas.create_rectangle(x, y, x+10, y+10, fill='blue') for x, y in snake]
# 获取食物小方块的对象,用于后面移动食物时修改位置
food_rect = canvas.find_withtag('food')
# 启动游戏,开始贪吃蛇的移动
move()
# 进入主循环,等待用户操作或者退出程序
window.mainloop()
```