用python写一个贪吃蛇小游戏
时间: 2023-12-02 19:02:57 浏览: 87
python写贪吃蛇小游戏
当然可以!以下是一个简单的贪吃蛇小游戏的Python代码示例:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 游戏窗口的尺寸
width = 640
height = 480
# 定义颜色
black = pygame.Color(0, 0, 0)
white = pygame.Color(255, 255, 255)
red = pygame.Color(255, 0, 0)
green = pygame.Color(0, 255, 0)
blue = pygame.Color(0, 0, 255)
# 创建游戏窗口
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇')
# 设置帧率
fps = pygame.time.Clock()
# 贪吃蛇初始位置
snake_pos = [100, 50]
# 贪吃蛇初始长度和速度
snake_body = [[100, 50], [90, 50], [80, 50]]
speed = [10, 0]
# 食物初始位置
food_pos = [random.randrange(1, (width//10)) * 10,
random.randrange(1, (height//10)) * 10]
food_spawn = True
# 初始化分数
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:
speed = [10, 0]
elif event.key == pygame.K_LEFT:
speed = [-10, 0]
elif event.key == pygame.K_UP:
speed = [0, -10]
elif event.key == pygame.K_DOWN:
speed = [0, 10]
# 更新贪吃蛇位置
snake_pos[0] += speed[0]
snake_pos[1] += speed[1]
# 检查是否吃到食物
if snake_pos[0] == food_pos[0] and snake_pos[1] == food_pos[1]:
score += 1
food_spawn = False
else:
snake_body.pop(0)
# 生成新的食物
if not food_spawn:
food_pos = [random.randrange(1, (width//10)) * 10,
random.randrange(1, (height//10)) * 10]
food_spawn = True
# 检查是否撞到墙壁或自身
if snake_pos[0] < 0 or snake_pos[0] > width-10 or snake_pos[1] < 0 or snake_pos[1] > height-10:
game_over = True
for block in snake_body[:-1]:
if block == snake_pos:
game_over = True
# 更新贪吃蛇身体
snake_body.append(list(snake_pos))
# 绘制游戏窗口
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, green, pygame.Rect(
pos[0], pos[1], 10, 10))
pygame.draw.rect(screen, white, pygame.Rect(
food_pos[0], food_pos[1], 10, 10))
# 更新分数
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), True, white)
screen.blit(score_text, (10, 10))
# 更新游戏窗口
pygame.display.flip()
# 控制帧率
fps.tick(20)
# 退出游戏
pygame.quit()
```
你可以在Python环境中运行这段代码,就能够玩到贪吃蛇小游戏了。希望能帮到你!
阅读全文