写出贪吃蛇游戏python代码
时间: 2023-07-09 17:48:54 浏览: 90
贪吃蛇游戏python代码
5星 · 资源好评率100%
以下是一份简单的贪吃蛇游戏 Python 代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 定义游戏区域大小
width = 640
height = 480
# 创建游戏区域
screen = pygame.display.set_mode((width, height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# 定义贪吃蛇头的初始位置
x = width / 2
y = height / 2
# 定义贪吃蛇头的移动速度
x_speed = 0
y_speed = 0
# 定义贪吃蛇身体的初始长度
snake_size = 10
snake_list = []
snake_length = 1
# 定义食物的初始位置
food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
# 定义字体
font = pygame.font.SysFont(None, 25)
# 定义分数
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_LEFT:
x_speed = -snake_size
y_speed = 0
elif event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
elif event.key == pygame.K_UP:
x_speed = 0
y_speed = -snake_size
elif event.key == pygame.K_DOWN:
x_speed = 0
y_speed = snake_size
# 移动贪吃蛇头
x += x_speed
y += y_speed
# 判断贪吃蛇头是否与食物重合
if x == food_x and y == food_y:
food_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
food_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
score += 10
# 绘制游戏区域
screen.fill(black)
# 绘制食物
pygame.draw.rect(screen, green, [food_x, food_y, snake_size, snake_size])
# 绘制贪吃蛇身体
snake_head = []
snake_head.append(x)
snake_head.append(y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for body_part in snake_list[:-1]:
if body_part == snake_head:
game_over = True
for body_part in snake_list:
pygame.draw.rect(screen, blue, [body_part[0], body_part[1], snake_size, snake_size])
# 绘制分数
score_text = font.render("Score: " + str(score), True, white)
screen.blit(score_text, [0, 0])
# 更新屏幕
pygame.display.update()
# 控制游戏帧率
clock = pygame.time.Clock()
clock.tick(15)
# 关闭pygame
pygame.quit()
```
阅读全文