用python写一个贪吃蛇
时间: 2024-01-06 12:06:36 浏览: 25
如何用Python写一个贪吃蛇AI.docx
好的,下面是一个简单的贪吃蛇游戏的 Python 实现。
```python
import pygame
import random
# 初始化 Pygame
pygame.init()
# 游戏区域的宽度和高度
width = 640
height = 480
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
# 蛇的尺寸
snake_size = 10
# 时钟对象,用于控制游戏帧率
clock = pygame.time.Clock()
# 定义字体
font = pygame.font.SysFont(None, 25)
# 显示游戏分数的函数
def show_score(score):
score_text = font.render("Score: " + str(score), True, white)
screen.blit(score_text, [0, 0])
# 绘制蛇的函数
def draw_snake(snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_size, snake_size])
# 主函数
def game():
# 定义蛇的初始位置和长度
snake_pos = [width / 2, height / 2]
snake_list = [snake_pos]
snake_len = 1
# 定义食物的初始位置
food_pos = [random.randrange(0, width - snake_size), random.randrange(0, height - snake_size)]
food_spawned = True
# 定义蛇的移动方向
direction = 'RIGHT'
change_to = direction
# 定义游戏分数
score = 0
# 游戏循环
game_over = False
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
elif event.key == pygame.K_LEFT:
change_to = 'LEFT'
elif event.key == pygame.K_UP:
change_to = 'UP'
elif event.key == pygame.K_DOWN:
change_to = 'DOWN'
# 改变蛇的移动方向
if change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
elif change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
elif change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
elif change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
# 移动蛇的位置
if direction == 'RIGHT':
snake_pos[0] += snake_size
elif direction == 'LEFT':
snake_pos[0] -= snake_size
elif direction == 'UP':
snake_pos[1] -= snake_size
elif direction == 'DOWN':
snake_pos[1] += snake_size
# 判断蛇是否吃到食物
if snake_pos == food_pos:
food_spawned = False
snake_len += 1
score += 10
# 创建新的食物
if not food_spawned:
food_pos = [random.randrange(0, width - snake_size), random.randrange(0, height - snake_size)]
food_spawned = True
# 绘制游戏界面
screen.fill(black)
pygame.draw.rect(screen, red, [food_pos[0], food_pos[1], snake_size, snake_size])
snake_head = []
snake_head.append(snake_pos[0])
snake_head.append(snake_pos[1])
snake_list.append(snake_head)
if len(snake_list) > snake_len:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over = True
draw_snake(snake_list)
show_score(score)
pygame.display.update()
# 控制游戏帧率
clock.tick(15)
# 退出游戏
pygame.quit()
quit()
# 启动游戏
game()
```
运行代码后,就可以开始玩贪吃蛇游戏了。通过方向键控制蛇的移动方向,吃到食物可以增加分数。当蛇碰到墙壁或自己时,游戏结束。
阅读全文