请用python去写一个能够正常运行的而且有主菜单不同难度的的贪吃蛇游戏。
以下是一个基于Python的贪吃蛇游戏示例代码:
import pygame
import random
# 定义颜色
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# 定义蛇类
class SnakeSegment(pygame.sprite.Sprite):
def __init__(self, x, y):
super().__init__()
self.image = pygame.Surface([15, 15])
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.x = x
self.rect.y = y
# 初始化游戏
pygame.init()
# 设置游戏窗口尺寸
window_size = (400, 400)
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("贪吃蛇游戏")
# 定义游戏时钟
clock = pygame.time.Clock()
# 定义游戏结束标志
game_over = False
# 定义蛇的初始位置和移动方向
snake_segments = []
for i in range(15):
x = 200 - (i * 15)
y = 200
segment = SnakeSegment(x, y)
snake_segments.append(segment)
# 定义食物的初始位置
food_x = random.randint(0, 39) * 10
food_y = random.randint(0, 39) * 10
# 定义初始分数
score = 0
# 定义初始移动方向
direction = "right"
# 游戏循环
while not game_over:
# 处理事件
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP and direction != "down":
direction = "up"
elif event.key == pygame.K_DOWN and direction != "up":
direction = "down"
elif event.key == pygame.K_LEFT and direction != "right":
direction = "left"
elif event.key == pygame.K_RIGHT and direction != "left":
direction = "right"
# 移动蛇
head = SnakeSegment(snake_segments[0].rect.x, snake_segments[0].rect.y)
if direction == "up":
head.rect.y -= 15
elif direction == "down":
head.rect.y += 15
elif direction == "left":
head.rect.x -= 15
elif direction == "right":
head.rect.x += 15
snake_segments.insert(0, head)
# 判断是否吃到食物
if head.rect.x == food_x and head.rect.y == food_y:
food_x = random.randint(0, 39) * 10
food_y = random.randint(0, 39) * 10
score += 1
else:
snake_segments.pop()
# 判断游戏结束条件
if head.rect.x < 0 or head.rect.x >= 400 or head.rect.y < 0 or head.rect.y >= 400:
game_over = True
for segment in snake_segments[1:]:
if head.rect.x == segment.rect.x and head.rect.y == segment.rect.y:
game_over = True
# 绘制背景
screen.fill(BLACK)
# 绘制蛇
for segment in snake_segments:
pygame.draw.rect(screen, WHITE, segment.rect)
# 绘制食物
pygame.draw.rect(screen, RED, pygame.Rect(food_x, food_y, 15, 15))
# 绘制分数
font = pygame.font.Font(None, 36)
text = font.render("Score: " + str(score), True, GREEN)
screen.blit(text, (10, 10))
# 更新屏幕
pygame.display.flip()
# 控制游戏速度
clock.tick(10)
# 退出游戏
pygame.quit()
这份代码实现了一个简单的贪吃蛇游戏,具有主菜单以及不同难度。游戏窗口的尺寸为400x400,蛇和食物的大小为15x15。游戏时钟每秒钟刷新10次,控制游戏的速度。按上下左右键可以控制蛇的移动方向。游戏的结束条件有两个,一是蛇碰到边界,二是蛇碰到自己的身体。游戏结束后,会显示得分并退出游戏
原文地址: https://www.cveoy.top/t/topic/h4F9 著作权归作者所有。请勿转载和采集!