用python写贪吃蛇小游戏代码
时间: 2023-09-05 14:10:00 浏览: 218
100行Python代码的贪吃蛇小游戏源码.zip
5星 · 资源好评率100%
以下是一个简单的贪吃蛇小游戏的Python代码,使用了Pygame库:
```python
import pygame
import random
# 初始化Pygame
pygame.init()
# 定义游戏区域大小
screen_width = 800
screen_height = 600
# 创建游戏窗口
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('贪吃蛇')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义游戏区域大小和格子大小
grid_size = 20
grid_width = screen_width // grid_size
grid_height = screen_height // grid_size
# 定义蛇的初始位置和长度
snake_position = [grid_width // 2, grid_height // 2]
snake_body = [[snake_position[0], snake_position[1]],
[snake_position[0] - 1, snake_position[1]],
[snake_position[0] - 2, snake_position[1]]]
# 定义食物的初始位置
food_position = [random.randint(0, grid_width - 1), random.randint(0, grid_height - 1)]
# 定义蛇的初始移动方向和速度
direction = 'RIGHT'
change_to = direction
snake_speed = 10
# 定义游戏结束函数
def game_over():
font = pygame.font.SysFont('Arial', 72)
text = font.render('Game Over', True, red)
screen.blit(text, ((screen_width - text.get_width()) // 2, (screen_height - text.get_height()) // 2))
pygame.display.update()
pygame.time.delay(2000)
pygame.quit()
# 游戏循环
while True:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
change_to = 'LEFT'
elif event.key == pygame.K_RIGHT:
change_to = 'RIGHT'
elif event.key == pygame.K_UP:
change_to = 'UP'
elif event.key == pygame.K_DOWN:
change_to = 'DOWN'
# 判断是否撞到墙或自己
if snake_position[0] < 0 or snake_position[0] >= grid_width or snake_position[1] < 0 or snake_position[1] >= grid_height:
game_over()
for body in snake_body[1:]:
if snake_position == body:
game_over()
# 判断是否吃到食物
if snake_position == food_position:
food_position = [random.randint(0, grid_width - 1), random.randint(0, grid_height - 1)]
else:
snake_body.pop()
# 移动蛇
if change_to == 'LEFT' and direction != 'RIGHT':
direction = 'LEFT'
snake_position[0] -= 1
elif change_to == 'RIGHT' and direction != 'LEFT':
direction = 'RIGHT'
snake_position[0] += 1
elif change_to == 'UP' and direction != 'DOWN':
direction = 'UP'
snake_position[1] -= 1
elif change_to == 'DOWN' and direction != 'UP':
direction = 'DOWN'
snake_position[1] += 1
snake_body.insert(0, list(snake_position))
# 绘制游戏界面
screen.fill(black)
for pos in snake_body:
pygame.draw.rect(screen, white, pygame.Rect(pos[0] * grid_size, pos[1] * grid_size, grid_size, grid_size))
pygame.draw.rect(screen, red, pygame.Rect(food_position[0] * grid_size, food_position[1] * grid_size, grid_size, grid_size))
pygame.display.update()
# 控制游戏速度
pygame.time.wait(1000 // snake_speed)
```
阅读全文