Python小游戏19——滑雪小游戏

时间:2024-11-03 22:38:51

import pygame

import random

 

# 初始化Pygame

pygame.init()

 

# 设置屏幕尺寸

screen_width = 800

screen_height = 600

screen = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption("滑雪小游戏")

 

# 定义颜色

WHITE = (255, 255, 255)

BLACK = (0, 0, 0)

RED = (255, 0, 0)

 

# 滑雪者类

class Skier(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        self.image = pygame.Surface((50, 50))

        self.image.fill(WHITE)

        self.rect = self.image.get_rect()

        self.rect.centerx = screen_width // 2

        self.rect.bottom = screen_height - 10

        self.speed_x = 0

 

    def update(self):

        self.speed_x = 0

        keystate = pygame.key.get_pressed()

        if keystate[pygame.K_LEFT]:

            self.speed_x = -5

        if keystate[pygame.K_RIGHT]:

            self.speed_x = 5

        self.rect.x += self.speed_x

        if self.rect.right > screen_width:

            self.rect.right = screen_width

        if self.rect.left < 0:

            self.rect.left = 0

 

# 障碍物类

class Obstacle(pygame.sprite.Sprite):

    def __init__(self):

        super().__init__()

        self.image = pygame.Surface((50, 50))

        self.image.fill(RED)

        self.rect = self.image.get_rect()

        self.rect.x = random.randint(0, screen_width - self.rect.width)

        self.rect.y = -50

        self.speed_y = random.randint(1, 5)

 

    def update(self):

        self.rect.y += self.speed_y

        if self.rect.bottom > screen_height:

            self.rect.x = random.randint(0, screen_width - self.rect.width)

            self.rect.y = -50

            self.speed_y = random.randint(1, 5)

 

# 创建游戏对象

skier = Skier()

obstacles = pygame.sprite.Group()

for _ in range(8): # 初始创建8个障碍物

    obstacle = Obstacle()

    obstacles.add(obstacle)

 

# 创建精灵组

all_sprites = pygame.sprite.Group()

all_sprites.add(skier)

all_sprites.add(obstacles)

 

# 游戏主循环

running = True

clock = pygame.time.Clock()

while running:

    clock.tick(60) # 设置帧率

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            running = False

 

    # 更新游戏对象

    all_sprites.update()

 

    # 检测碰撞

    hits = pygame.sprite.spritecollide(skier, obstacles, False)

    if hits:

        running = False # 如果滑雪者碰到障碍物,游戏结束

 

    # 绘制游戏

    screen.fill(BLACK)

    all_sprites.draw(screen)

    pygame.display.flip()

 

# 游戏结束

pygame.quit()