我的解释器是Python3.9,帮我写个贪吃蛇的游戏
时间: 2023-05-18 18:03:50 浏览: 73
当然可以!以下是一个简单的贪吃蛇游戏的代码:
```python
import pygame
import random
# 初始化pygame
pygame.init()
# 设置游戏窗口大小
window_width = 500
window_height = 500
window = pygame.display.set_mode((window_width, window_height))
# 设置游戏标题
pygame.display.set_caption("贪吃蛇")
# 定义颜色
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
# 定义蛇的初始位置和大小
snake_block_size = 10
snake_speed = 15
snake_list = []
snake_length = 1
snake_x = window_width / 2
snake_y = window_height / 2
# 定义食物的初始位置和大小
food_block_size = 10
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
# 定义蛇的移动方向
direction = "right"
# 定义字体
font_style = pygame.font.SysFont(None, 30)
# 定义显示分数的函数
def show_score(score):
score_text = font_style.render("Score: " + str(score), True, black)
window.blit(score_text, [0, 0])
# 定义画蛇的函数
def draw_snake(snake_block_size, snake_list):
for x in snake_list:
pygame.draw.rect(window, black, [x[0], x[1], snake_block_size, snake_block_size])
# 开始游戏循环
game_over = False
score = 0
while not game_over:
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:
direction = "left"
elif event.key == pygame.K_RIGHT:
direction = "right"
elif event.key == pygame.K_UP:
direction = "up"
elif event.key == pygame.K_DOWN:
direction = "down"
# 移动蛇的位置
if direction == "right":
snake_x += snake_block_size
elif direction == "left":
snake_x -= snake_block_size
elif direction == "up":
snake_y -= snake_block_size
elif direction == "down":
snake_y += snake_block_size
# 判断蛇是否吃到了食物
if snake_x == food_x and snake_y == food_y:
food_x = round(random.randrange(0, window_width - food_block_size) / 10.0) * 10.0
food_y = round(random.randrange(0, window_height - food_block_size) / 10.0) * 10.0
snake_length += 1
score += 10
# 更新蛇的位置
snake_head = []
snake_head.append(snake_x)
snake_head.append(snake_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
if snake_x < 0 or snake_x >= window_width or snake_y < 0 or snake_y >= window_height:
game_over = True
# 绘制游戏界面
window.fill(white)
pygame.draw.rect(window, red, [food_x, food_y, food_block_size, food_block_size])
draw_snake(snake_block_size, snake_list)
show_score(score)
pygame.display.update()
# 控制游戏速度
clock = pygame.time.Clock()
clock.tick(snake_speed)
# 退出pygame
pygame.quit()
quit()
```
希望这个代码能够帮到你!
阅读全文