用pyrhon写一个贪吃蛇游戏
时间: 2023-07-01 16:21:36 浏览: 72
Python编写一个贪吃蛇游戏
好的,我可以帮你写一个简单的贪吃蛇游戏。这里使用Python的pygame库实现。
代码如下:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 游戏界面大小
SCREEN_WIDTH = 480
SCREEN_HEIGHT = 480
# 颜色定义
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
# 创建游戏界面
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption('贪吃蛇')
# 定义蛇的初始位置和大小
snake_pos = [(240, 240), (260, 240), (280, 240)]
snake_size = 20
# 定义蛇移动的方向
snake_direction = 'left'
# 生成食物的位置
food_pos = (random.randint(0, SCREEN_WIDTH//snake_size)*snake_size,
random.randint(0, SCREEN_HEIGHT//snake_size)*snake_size)
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义分数
score = 0
# 游戏循环
while True:
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
exit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and snake_direction != 'down':
snake_direction = 'up'
elif event.key == pygame.K_DOWN and snake_direction != 'up':
snake_direction = 'down'
elif event.key == pygame.K_LEFT and snake_direction != 'right':
snake_direction = 'left'
elif event.key == pygame.K_RIGHT and snake_direction != 'left':
snake_direction = 'right'
# 移动蛇的位置
if snake_direction == 'up':
snake_pos = [(snake_pos[0][0], snake_pos[0][1]-snake_size)] + snake_pos[:-1]
elif snake_direction == 'down':
snake_pos = snake_pos[1:] + [(snake_pos[-1][0], snake_pos[-1][1]+snake_size)]
elif snake_direction == 'left':
snake_pos = [(snake_pos[0][0]-snake_size, snake_pos[0][1])] + snake_pos[:-1]
elif snake_direction == 'right':
snake_pos = snake_pos[1:] + [(snake_pos[-1][0]+snake_size, snake_pos[-1][1])]
# 判断蛇是否吃到了食物
if snake_pos[-1] == food_pos:
score += 10
snake_pos.insert(0, snake_pos[0])
food_pos = (random.randint(0, SCREEN_WIDTH//snake_size)*snake_size,
random.randint(0, SCREEN_HEIGHT//snake_size)*snake_size)
# 判断蛇是否碰到了边界
if snake_pos[-1][0] < 0 or snake_pos[-1][0] >= SCREEN_WIDTH \
or snake_pos[-1][1] < 0 or snake_pos[-1][1] >= SCREEN_HEIGHT:
pygame.quit()
exit()
# 判断蛇是否碰到了自己
if snake_pos[-1] in snake_pos[:-1]:
pygame.quit()
exit()
# 绘制游戏界面
screen.fill(WHITE)
for pos in snake_pos:
pygame.draw.rect(screen, GREEN, (pos[0], pos[1], snake_size, snake_size))
pygame.draw.rect(screen, RED, (food_pos[0], food_pos[1], snake_size, snake_size))
font = pygame.font.Font(None, 30)
score_text = font.render('分数:%d' % score, True, BLACK)
screen.blit(score_text, (10, 10))
pygame.display.update()
# 控制游戏帧率
clock.tick(5)
```
这个贪吃蛇游戏使用方向键来控制蛇的移动方向。蛇吃到食物后会增加分数,并在随机位置生成新的食物。如果蛇碰到了边界或自己,游戏结束。游戏界面会在每次循环中重新绘制,包括蛇、食物和分数等信息。
阅读全文