基于python和pygame库实现刮刮乐游戏

 更新时间:2024年03月04日 10:07:50   作者:软件技术爱好者  
这篇文章主要介绍了如何基于python和pygame库实现刮刮乐游戏,文中通过代码示例和图文给大家讲解的非常详细,对大家的学习或工作有一定的帮助,需要的朋友可以参考下

用python和pygame库实现刮刮乐游戏

首先,确保你已经安装了pygame库。如果没有安装,可以通过以下命令安装:

pip install pygame

示例有两个。

一、简单刮刮乐游戏

准备两张图片,一张作为背景bottom_image.png,一张作为刮开的图片top_image.png:

请将bottom_image.png和top_image.png图片文件与游戏代码文件(.py文件)放在在同一目录下。

以下是简单刮刮乐游戏的代码:

import pygame
import os
 
# 初始化pygame
pygame.init()
 
# 设置游戏窗口
width, height = 356, 358
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('刮刮乐游戏')
 
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
 
# 确保图片文件存在
if not os.path.isfile('bottom_image.png') or not os.path.isfile('top_image.png'):
    raise Exception("图片文件未找到,请确保bottom_image.png和top_image.png文件在同一目录下。")
 
# 加载图片
bottom_image = pygame.image.load('bottom_image.png').convert()
top_image = pygame.image.load('top_image.png').convert_alpha()
 
# 调整图片大小以适应窗口
bottom_image = pygame.transform.scale(bottom_image, (width, height))
top_image = pygame.transform.scale(top_image, (width, height))
 
# 创建一个与顶层图片相同大小的透明表面
scratch_surface = pygame.Surface((width, height), pygame.SRCALPHA)
 
# 将顶层图片绘制到透明表面上
scratch_surface.blit(top_image, (0, 0))
 
# 游戏主循环
running = True
while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False
 
    # 获取鼠标位置和状态
    mouse_pos = pygame.mouse.get_pos()
    mouse_pressed = pygame.mouse.get_pressed()
 
    # 如果按下鼠标左键,则在透明表面上绘制透明圆形,模拟刮开效果
    if mouse_pressed[0]:  # 检测鼠标左键是否按下
        pygame.draw.circle(scratch_surface, (0, 0, 0, 0), mouse_pos, 20)
 
    # 绘制背景图片
    screen.blit(bottom_image, (0, 0))
 
    # 绘制刮开的透明表面
    screen.blit(scratch_surface, (0, 0))
 
    # 更新屏幕
    pygame.display.flip()
 
# 退出游戏
pygame.quit()
 

运行效果:

二、多对图片的刮刮乐游戏

使用多对图片,准备了好了多对图片,如bottom1.png和top1.png 、 bottom2.png和top2.png 、 bottom2.png和top3.png,并将它们放到了img文件夹中。用户可以选择图对游戏,游戏过程中可按下ESC 键返回到菜单页开始重玩。

项目的目录(project_directory)结构如下:

源码如下:

import pygame
import os
import sys
 
# 初始化pygame
pygame.init()
 
# 设置游戏窗口
width, height = 356, 358
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('刮刮乐游戏(可选择图片对)')
 
# 定义颜色
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
RED = (255, 0, 0)
 
# 图片对列表
image_pairs = [
    ("img/bottom1.png", "img/top1.png"),
    ("img/bottom2.png", "img/top2.png"),
    ("img/bottom3.png", "img/top3.png")
]
 
# 加载图片
def load_images(pair_index):
    bottom_image_path, top_image_path = image_pairs[pair_index]
    bottom_image = pygame.image.load(bottom_image_path).convert()
    top_image = pygame.image.load(top_image_path).convert_alpha()
    bottom_image = pygame.transform.scale(bottom_image, (width, height))
    top_image = pygame.transform.scale(top_image, (width, height))
    return bottom_image, top_image
 
# 游戏主函数
def run_game(bottom_image, top_image):
    scratch_surface = pygame.Surface((width, height), pygame.SRCALPHA)
    scratch_surface.blit(top_image, (0, 0))
    running = True
    while running:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                running = False
            # 检测键盘事件以返回菜单
            elif event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:  # 按下ESC键
                    return  # 返回到菜单,而不是退出游戏
        mouse_pos = pygame.mouse.get_pos()
        mouse_pressed = pygame.mouse.get_pressed()
        if mouse_pressed[0]:
            pygame.draw.circle(scratch_surface, (0, 0, 0, 0), mouse_pos, 20)
        screen.blit(bottom_image, (0, 0))
        screen.blit(scratch_surface, (0, 0))
        pygame.display.flip()
 
# 菜单函数
def menu():
    font = pygame.font.Font(None, 26)    
    menu_running = True
    text_surfaces = []
    text_rects = []
    
    for i, pair in enumerate(image_pairs):
        text = font.render(f"[ Image {i+1} ]", True, RED)
        text_rect = text.get_rect(topleft=(10, 40 + i * 30))
        text_surfaces.append(text)
        text_rects.append(text_rect)
    
    while menu_running:
        screen.fill(WHITE)
        text = font.render(f"Press Esc to return to the menu:", True, BLACK)
        text_rect = text.get_rect(topleft=(10, 5))
        screen.blit(text, text_rect)
        
        for i, text in enumerate(text_surfaces):
            screen.blit(text, text_rects[i])
        pygame.display.flip()
        
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:  # Left click
                for i, rect in enumerate(text_rects):
                    if rect.collidepoint(event.pos):
                        bottom_image, top_image = load_images(i)
                        run_game(bottom_image, top_image)
                        # 在这里不需要设置menu_running = False,因为我们希望在游戏结束后自动返回菜单
 
# 运行菜单
menu()

运行效果如下图所示:

用户可以单击菜单项选择图对游戏,游戏过程中可按下ESC 键返回到菜单页开始重玩。

以上就是基于python和pygame库实现刮刮乐游戏的详细内容,更多关于python pygame刮刮乐的资料请关注脚本之家其它相关文章!

相关文章

  • Python多线程爬虫实战_爬取糗事百科段子的实例

    Python多线程爬虫实战_爬取糗事百科段子的实例

    下面小编就为大家分享一篇Python多线程爬虫实战_爬取糗事百科段子的实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2017-12-12
  • 使用Python将Markdown格式转为EPUB电子书格式的代码实现

    使用Python将Markdown格式转为EPUB电子书格式的代码实现

    我们每天都会接触到大量的文本内容,无论是收藏的技术文档、自己撰写的笔记,还是网络上的优质文章,都可能面临阅读体验不佳的问题,所以本文给大家介绍了使用Python将Markdown格式转为EPUB电子书格式的实现方法,需要的朋友可以参考下
    2025-04-04
  • Python Flask RESTful使用demo演示

    Python Flask RESTful使用demo演示

    这篇文章主要为大家介绍了Python Flask RESTful使用demo演示,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪
    2023-03-03
  • Numpy 改变数组维度的几种方法小结

    Numpy 改变数组维度的几种方法小结

    今天小编就为大家分享一篇Numpy 改变数组维度的几种方法小结,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-08-08
  • Python Log文件大小设置及备份的方法

    Python Log文件大小设置及备份的方法

    这篇文章主要介绍了Python Log文件大小设置及备份的方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2021-11-11
  • python常用的各种排序算法原理与实现方法小结

    python常用的各种排序算法原理与实现方法小结

    这篇文章主要介绍了python常用的各种排序算法原理与实现方法,结合实例形式总结分析了冒泡排序、插入排序、选择排序、快速排序等排序算法的相关原理与实现方法,需要的朋友可以参考下
    2023-04-04
  • python爬取免费代理并验证代理是否可用

    python爬取免费代理并验证代理是否可用

    这篇文章主要介绍了python爬取免费代理并验证是否可用,通过本文给大家介绍了在什么情况下会用到代理并分享脚本的完整代码,需要的朋友可以参考下
    2022-01-01
  • Python cx_freeze打包工具处理问题思路及解决办法

    Python cx_freeze打包工具处理问题思路及解决办法

    这篇文章主要介绍了Python cx_freeze打包工具处理问题思路及解决办法的相关资料,需要的朋友可以参考下
    2016-02-02
  • Python time.time()方法

    Python time.time()方法

    这篇文章主要介绍了详解Python中time.time()方法的使用的教程,是Python入门学习中的基础知识,需要的朋友可以参考下,希望能给你带来帮助
    2021-08-08
  • Django 通过JS实现ajax过程详解

    Django 通过JS实现ajax过程详解

    这篇文章主要介绍了Django 通过JS实现ajax过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2019-07-07

最新评论