用python编译一个贪吃蛇小游戏
时间: 2023-10-20 13:07:47 浏览: 61
好的,下面是一个简单的贪吃蛇小游戏的Python代码:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 设置游戏界面尺寸
size = width, height = 640, 480
screen = pygame.display.set_mode(size)
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 设置颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置字体
font = pygame.font.SysFont(None, 25)
# 设置蛇的初始位置和大小
snake_size = 10
snake_speed = 15
# 定义蛇的移动函数
def snake(snake_size, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_size, snake_size])
# 定义游戏主循环
def gameLoop():
game_exit = False
game_over = False
# 设置蛇的初始位置
lead_x = width / 2
lead_y = height / 2
# 设置蛇的初始移动方向
lead_x_change = 0
lead_y_change = 0
# 定义蛇的身体
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
while not game_exit:
# 游戏结束后显示分数
while game_over == True:
screen.fill(white)
message("游戏结束,按 Q 退出,按 C 重新开始", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
gameLoop()
# 处理游戏事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_exit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
lead_x_change = -snake_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = snake_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -snake_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = snake_size
lead_x_change = 0
# 判断蛇是否撞到边界
if lead_x >= width or lead_x < 0 or lead_y >= height or lead_y < 0:
game_over = True
# 更新蛇的位置
lead_x += lead_x_change
lead_y += lead_y_change
# 画出蛇和食物
screen.fill(white)
pygame.draw.rect(screen, red, [food_x, food_y, snake_size, snake_size])
snake_head = []
snake_head.append(lead_x)
snake_head.append(lead_y)
snake_list.append(snake_head)
if len(snake_list) > snake_length:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_over = True
snake(snake_size, snake_list)
pygame.display.update()
# 判断蛇是否吃到食物
if lead_x == food_x and lead_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
# 设置游戏帧率
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出游戏
pygame.quit()
quit()
# 显示文字
def message(msg, color):
screen_text = font.render(msg, True, color)
screen.blit(screen_text, [width / 6, height / 3])
# 运行游戏
gameLoop()
```
运行上述代码即可玩贪吃蛇小游戏。
阅读全文