用python写一段贪吃蛇游戏的代码
时间: 2023-06-03 17:03:49 浏览: 89
好的,以下是Python实现的简单贪吃蛇游戏代码:
```python
import pygame
import time
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
width = 600
height = 400
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption('贪吃蛇游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (200, 0, 0)
light_red = (255, 0, 0)
yellow = (200, 200, 0)
light_yellow = (255, 255, 0)
# 设置时钟
clock = pygame.time.Clock()
# 定义蛇的大小
snake_size = 10
# 设置字体
font = pygame.font.SysFont(None, 25)
# 定义text函数,支持在游戏窗口上输出文字
def text_objects(text, color):
text_surface = font.render(text, True, color)
return text_surface, text_surface.get_rect()
# 输出消息
def message(msg, color):
text_surf, text_rect = text_objects(msg, color)
text_rect.center = (width/2, height/2)
game_display.blit(text_surf, text_rect)
pygame.display.update()
# 定义贪吃蛇函数
def snake(snake_size, snake_list):
for rect in snake_list:
pygame.draw.rect(game_display, yellow, [rect[0], rect[1], snake_size, snake_size])
# 定义主程序
def game_loop():
game_exit = False
game_over = False
x = width/2
y = height/2
x_change = 0
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:
game_display.fill(white)
message("游戏结束,按 C 重玩,按 Q 退出游戏", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_c:
game_loop()
elif event.key == pygame.K_q:
game_exit = True
game_over = False
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:
x_change = -snake_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -snake_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = snake_size
x_change = 0
# 边界判断
if x >= width or x < 0 or y >= height or y < 0:
game_over = True
# 改变移动方向
x += x_change
y += y_change
# 填充白色背景
game_display.fill(white)
# 绘制食物
pygame.draw.rect(game_display, red, [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 rect in snake_list[:-1]:
if rect == snake_head:
game_over = True
snake(snake_size, snake_list)
pygame.display.update()
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
# 设置帧率
clock.tick(20)
# 关闭pygame
pygame.quit()
quit()
game_loop()
```
希望能够满足你的需求。
阅读全文