|
|
发表于 2025-7-10 17:24:46
|
显示全部楼层
import pygame
import time
import random
# 初始化 Pygame
pygame.init()
# 定义颜色
WHITE = (255, 255, 255)
YELLOW = (255, 255, 102)
BLACK = (0, 0, 0)
RED = (213, 50, 80)
GREEN = (0, 255, 0)
BLUE = (50, 153, 213)
# 设置游戏窗口尺寸
WIDTH, HEIGHT = 600, 400
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption('贪吃蛇游戏')
# 设置贪吃蛇的参数
snake_block = 10
snake_speed = 6
# 创建时钟
clock = pygame.time.Clock()
# 设置字体
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
def draw_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, BLACK, [x[0], x[1], snake_block, snake_block])
def show_score(score):
value = score_font.render("分数: " + str(score), True, BLACK)
screen.blit(value, [0, 0])
def message(msg, color):
mesg = font_style.render(msg, True, color)
screen.blit(mesg, [WIDTH / 6, HEIGHT / 3])
def game_loop():
game_over = False
game_close = False
x1 = WIDTH / 2
y1 = HEIGHT / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, WIDTH - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, HEIGHT - snake_block) / 10.0) * 10.0
while not game_over:
while game_close:
screen.fill(BLUE)
message("游戏结束! 按 C 继续或 Q 退出", RED)
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_a: # 按 A 键向左
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_d: # 按 D 键向右
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_w: # 按 W 键向上
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_s: # 按 S 键向下
y1_change = snake_block
x1_change = 0
if x1 >= WIDTH or x1 < 0 or y1 >= HEIGHT or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill(BLUE)
pygame.draw.rect(
screen, GREEN, [foodx, foody, snake_block, snake_block])
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, snake_List)
show_score(Length_of_snake - 1)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(
0, WIDTH - snake_block) / 10.0) * 10.0
foody = round(random.randrange(
0, HEIGHT - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
if __name__ == "__main__":
game_loop() |
|