帮我用Python语言生成一段贪吃蛇游戏代码
时间: 2023-11-05 13:15:24 浏览: 86
好的,以下是一份基于Python的贪吃蛇游戏代码,希望能够帮助到您:
```python
import pygame
import random
# 初始化游戏
pygame.init()
# 定义游戏窗口的大小和标题
window_width = 800
window_height = 600
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)
green = (0, 255, 0)
# 定义蛇的大小和速度
snake_block_size = 10
snake_speed = 15
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 显示分数
def show_score(score):
score_text = font_style.render("分数:" + str(score), True, black)
game_display.blit(score_text, [0, 0])
# 绘制蛇
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(game_display, green, [x[0], x[1], snake_block_size, snake_block_size])
# 游戏运行函数
def game_loop():
game_over = False
game_close = False
x1 = window_width / 2
y1 = window_height / 2
x1_change = 0
y1_change = 0
snake_list = []
length_of_snake = 1
food_x = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
while not game_over:
while game_close == True:
game_display.fill(white)
game_over_text = font_style.render("游戏结束,按Q退出,按C重新开始", True, black)
game_display.blit(game_over_text, [window_width / 6, window_height / 3])
show_score(length_of_snake - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
game_loop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block_size
x1_change = 0
if x1 >= window_width or x1 < 0 or y1 >= window_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
game_display.fill(white)
pygame.draw.rect(game_display, red, [food_x, food_y, snake_block_size, snake_block_size])
snake_head = []
snake_head.append(x1)
snake_head.append(y1)
snake_list.append(snake_head)
if len(snake_list) > length_of_snake:
del snake_list[0]
for x in snake_list[:-1]:
if x == snake_head:
game_close = True
draw_snake(snake_block_size, snake_list)
show_score(length_of_snake - 1)
pygame.display.update()
if x1 == food_x and y1 == food_y:
food_x = round(random.randrange(0, window_width - snake_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - snake_block_size) / 10.0) * 10.0
length_of_snake += 1
clock = pygame.time.Clock()
clock.tick(snake_speed)
pygame.quit()
quit()
game_loop()
```
希望能对您有所帮助!
阅读全文