帮我做一个python贪吃蛇的游戏代码
时间: 2023-08-20 20:26:58 浏览: 132
好的,以下是一个简单的Python贪吃蛇游戏代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 640
window_height = 480
game_display = pygame.display.set_mode((window_width, window_height))
pygame.display.set_caption('贪吃蛇游戏')
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 设置游戏时钟
clock = pygame.time.Clock()
# 定义贪吃蛇方块大小
block_size = 10
# 加载字体
font = pygame.font.SysFont(None, 25)
# 定义函数,显示消息
def message(msg, color):
screen_text = font.render(msg, True, color)
game_display.blit(screen_text, [window_width / 6, window_height / 3])
# 定义函数,绘制贪吃蛇
def snake(block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, black, [x[0], x[1], block_size, block_size])
# 定义游戏循环
def game_loop():
game_exit = False
game_over = False
# 定义贪吃蛇初始位置
lead_x = window_width / 2
lead_y = window_height / 2
lead_x_change = 0
lead_y_change = 0
# 定义随机食物位置
rand_food_x = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
rand_food_y = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
# 定义贪吃蛇长度
snake_list = []
snake_length = 1
while not game_exit:
while game_over:
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_q:
game_exit = True
game_over = False
if event.key == pygame.K_c:
game_loop()
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 = -block_size
lead_y_change = 0
elif event.key == pygame.K_RIGHT:
lead_x_change = block_size
lead_y_change = 0
elif event.key == pygame.K_UP:
lead_y_change = -block_size
lead_x_change = 0
elif event.key == pygame.K_DOWN:
lead_y_change = block_size
lead_x_change = 0
# 判断是否超出边界
if lead_x >= window_width or lead_x < 0 or lead_y >= window_height or lead_y < 0:
game_over = True
# 更新贪吃蛇位置
lead_x += lead_x_change
lead_y += lead_y_change
# 绘制游戏窗口
game_display.fill(white)
pygame.draw.rect(game_display, red, [rand_food_x, rand_food_y, block_size, block_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]
# 判断是否吃到食物
if lead_x == rand_food_x and lead_y == rand_food_y:
rand_food_x = round(random.randrange(0, window_width - block_size) / 10.0) * 10.0
rand_food_y = round(random.randrange(0, window_height - block_size) / 10.0) * 10.0
snake_length += 1
# 判断是否碰到自己
for segment in snake_list[:-1]:
if segment == snake_head:
game_over = True
# 绘制贪吃蛇
snake(block_size, snake_list)
# 更新游戏窗口
pygame.display.update()
# 设置游戏时钟
clock.tick(10)
# 退出pygame
pygame.quit()
# 退出程序
quit()
# 启动游戏循环
game_loop()
```
希望可以帮到你!
阅读全文