python和pygame实现捉小兔游戏

python和pygame实现捉小兔游戏

python和pygame实现捉小兔游戏,需要安装使用第三方库pygame,关于Python中pygame游戏模块的安装使用可见 https://blog.csdn.net/cnds123/article/details/119514520

下面是使用Python和Pygame创建的游戏,其中有一个草地背景图片和一个随机移动的小图片——小兔子,玩家要使用鼠标点击小兔子小图片,每次点击成功代表捉到一只小兔子,成绩(Score)加一分。成绩的右边有计时器,以秒为单位来显示游戏的运行时间。

先看效果图:

需要两张图片素材

background.jpg图片如下:

small_image.jpg图片如下:

请注意,上述代码假定背景图片为background.jpg,小图片为small_image.png。请确保将这两个文件与下面给出源码文件放在同一目录下。你可以自行替换这些图片,只需确保文件名正确。

下面给出源码:

import pygame
import random
import time

# 初始化游戏
pygame.init()

# 设置游戏窗口尺寸
WIDTH = 800
HEIGHT = 600
window = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("捉小兔游戏(用鼠标点击)")

# 加载背景图片
background_img = pygame.image.load("background.jpg")

# 加载小图片
small_img = pygame.image.load("small_image.jpg")
small_rect = small_img.get_rect()

# 设置小图片的初始位置
small_rect.x = random.randint(0, WIDTH - small_rect.width)
small_rect.y = random.randint(0, HEIGHT - small_rect.height)

# 初始化得分
score = 0
# 计时器
start_time = time.time()

# 游戏主循环
running = True
clock = pygame.time.Clock()

while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
        elif event.type == pygame.MOUSEBUTTONDOWN:
            # 检查是否点击到了小图片
            if small_rect.collidepoint(event.pos):
                # 点击成功,得分加一
                score += 1
                # 重新设置小图片的位置
                small_rect.x = random.randint(0, WIDTH - small_rect.width)
                small_rect.y = random.randint(0, HEIGHT - small_rect.height)

    # 移动小图片
    small_rect.x += random.randint(-35, 35)  #
    small_rect.y += random.randint(-35, 35)  #
    
    # 确保小图片在窗口内部
    if small_rect.left < 0:
        small_rect.left = 0
    if small_rect.right > WIDTH:
        small_rect.right = WIDTH
    if small_rect.top < 0:
        small_rect.top = 0
    if small_rect.bottom > HEIGHT:
        small_rect.bottom = HEIGHT

    # 更新背景图片
    window.blit(background_img, (0, 0))

    # 更新小图片
    window.blit(small_img, (small_rect.x, small_rect.y))

    # 显示得分
    font = pygame.font.Font(None, 36)
    score_text = font.render("Score: " + str(score), True, (255, 0, 0))  #
    window.blit(score_text, (10, 10))

    # 显示计时器
    elapsed_time = int(time.time() - start_time)
    time_text = font.render("Time: " + str(elapsed_time) + "s", True, (255, 0, 0))
    window.blit(time_text, (WIDTH - 150, 10))

    # 刷新窗口
    pygame.display.flip()

    # 添加延迟时间,处理小图移动太快晃眼
    pygame.time.delay(200)  #200毫秒

    # 控制游戏帧率
    clock.tick(60)

# 退出游戏
pygame.quit()

猜你喜欢

转载自blog.csdn.net/cnds123/article/details/134996061