如何用python制作五子棋游戏_Python制作打地鼠小游戏

原文链接

Python制作小游戏(二十一)​mp.weixin.qq.com
46782723760f2ffd743007546fe414bd.png

效果展示

1f7de229b9f1d80a4be58d3312949915.png
打地鼠小游戏https://www.zhihu.com/video/1200492442610450432

简介

打地鼠的游戏规则相信大家都知道,这里就不多介绍了,反正就是不停地拿锤子打洞里钻出来的地鼠呗~

首先,让我们确定一下游戏中有哪些元素。打地鼠打地鼠,地鼠当然得有啦,那我们就写个地鼠的游戏精灵类呗:

'''地鼠'''
class Mole(pygame.sprite.Sprite):
    def __init__(self, image_paths, position, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.transform.scale(pygame.image.load(image_paths[0]), (101, 103)), 
                       pygame.transform.scale(pygame.image.load(image_paths[-1]), (101, 103))]
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)
        self.setPosition(position)
        self.is_hammer = False
    '''设置位置'''
    def setPosition(self, pos):
        self.rect.left, self.rect.top = pos
    '''设置被击中'''
    def setBeHammered(self):
        self.is_hammer = True
    '''显示在屏幕上'''
    def draw(self, screen):
        if self.is_hammer: self.image = self.images[1]
        screen.blit(self.image, self.rect)
    '''重置'''
    def reset(self):
        self.image = self.images[0]
        self.is_hammer = False

显然,地鼠有被锤子击中和未被锤子击中这两种状态,所以需要加载两张图,当地鼠被击中时从未被击中的地鼠状态图切换到被击中后的地鼠状态图(我找的图可能不太像地鼠,请各位老哥见谅)。然后我们再来定义一下锤子这个游戏精灵类,和地鼠类似,锤子也有未锤下去和已锤下去两种状态,只不过锤下去之后需要迅速恢复回未锤下去的状态,具体而言,代码实现如下:

class Hammer(pygame.sprite.Sprite):
    def __init__(self, image_paths, position, **kwargs):
        pygame.sprite.Sprite.__init__(self)
        self.images = [pygame.image.load(image_paths[0]), pygame.image.load(image_paths[1])]
        self.image = self.images[0]
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.images[1])
        self.rect.left, self.rect.top = position
        # 用于显示锤击时的特效
        self.hammer_count = 0
        self.hammer_last_time = 4
        self.is_hammering = False
    '''设置位置'''
    def setPosition(self, pos):
        self.rect.centerx, self.rect.centery = pos
    '''设置hammering'''
    def setHammering(self):
        self.is_hammering = True
    '''显示在屏幕上'''
    def draw(self, screen):
        if self.is_hammering:
            self.image = self.images[1]
            self.hammer_count += 1
            if self.hammer_count > self.hammer_last_time:
                self.is_hammering = False
                self.hammer_count = 0
        else:
            self.image = self.images[0]
        screen.blit(self.image, self.rect)

OK,定义完游戏精灵之后,我们就可以开始写主程序啦。首先自然是游戏初始化:

'''游戏初始化'''
def initGame():
  pygame.init()
  pygame.mixer.init()
  screen = pygame.display.set_mode(cfg.SCREENSIZE)
  pygame.display.set_caption('Whac A Mole-微信公众号:Charles的皮卡丘')
  return screen

然后加载必要的游戏素材和定义必要的游戏变量(我都注释的比较详细了,就不在文章里赘述一遍了,自己看注释呗~)

  # 加载背景音乐和其他音效
  pygame.mixer.music.load(cfg.BGM_PATH)
  pygame.mixer.music.play(-1)
  audios = {
        'count_down': pygame.mixer.Sound(cfg.COUNT_DOWN_SOUND_PATH),
        'hammering': pygame.mixer.Sound(cfg.HAMMERING_SOUND_PATH)
      }
  # 加载字体
  font = pygame.font.Font(cfg.FONT_PATH, 40)
  # 加载背景图片
  bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
  # 开始界面
  startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
  # 地鼠改变位置的计时
  hole_pos = random.choice(cfg.HOLE_POSITIONS)
  change_hole_event = pygame.USEREVENT
  pygame.time.set_timer(change_hole_event, 800)
  # 地鼠
  mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
  # 锤子
  hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
  # 时钟
  clock = pygame.time.Clock()
  # 分数
  your_score = 0

接着就是游戏主循环啦:

# 游戏主循环
while True:
  # --游戏时间为60s
  time_remain = round((61000 - pygame.time.get_ticks()) / 1000.)
  # --游戏时间减少, 地鼠变位置速度变快
  if time_remain == 40:
    pygame.time.set_timer(change_hole_event, 650)
  elif time_remain == 20:
    pygame.time.set_timer(change_hole_event, 500)
  # --倒计时音效
  if time_remain == 10:
    audios['count_down'].play()
  # --游戏结束
  if time_remain < 0: break
  count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
  # --按键检测
  for event in pygame.event.get():
    if event.type == pygame.QUIT:
      pygame.quit()
      sys.exit()
    elif event.type == pygame.MOUSEMOTION:
      hammer.setPosition(pygame.mouse.get_pos())
    elif event.type == pygame.MOUSEBUTTONDOWN:
      if event.button == 1:
        hammer.setHammering()
    elif event.type == change_hole_event:
      hole_pos = random.choice(cfg.HOLE_POSITIONS)
      mole.reset()
      mole.setPosition(hole_pos)
  # --碰撞检测
  if hammer.is_hammering and not mole.is_hammer:
    is_hammer = pygame.sprite.collide_mask(hammer, mole)
    if is_hammer:
      audios['hammering'].play()
      mole.setBeHammered()
      your_score += 10
  # --分数
  your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
  # --绑定必要的游戏元素到屏幕(注意顺序)
  screen.blit(bg_img, (0, 0))
  screen.blit(count_down_text, (875, 8))
  screen.blit(your_score_text, (800, 430))
  mole.draw(screen)
  hammer.draw(screen)
  # --更新
  pygame.display.flip()
  clock.tick(60)

每一部分我也都做了注释,逻辑很简单,就不多废话了。60s后,游戏结束,我们就可以统计分数以及和历史最高分做对比了:

# 读取最佳分数(try块避免第一次游戏无.rec文件)
try:
  best_score = int(open(cfg.RECORD_PATH).read())
except:
  best_score = 0
# 若当前分数大于最佳分数则更新最佳分数
if your_score > best_score:
  f = open(cfg.RECORD_PATH, 'w')
  f.write(str(your_score))
  f.close()

为了使游戏看起来更“正式”,再随手添个开始界面和结束界面呗:

'''游戏开始界面'''
def startInterface(screen, begin_image_paths):
    begin_images = [pygame.image.load(begin_image_paths[0]), pygame.image.load(begin_image_paths[1])]
    begin_image = begin_images[0]
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                mouse_pos = pygame.mouse.get_pos()
                if mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    begin_image = begin_images[1]
                else:
                    begin_image = begin_images[0]
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    return True
        screen.blit(begin_image, (0, 0))
        pygame.display.update()


'''结束界面'''
def endInterface(screen, end_image_path, again_image_paths, score_info, font_path, font_colors, screensize):
    end_image = pygame.image.load(end_image_path)
    again_images = [pygame.image.load(again_image_paths[0]), pygame.image.load(again_image_paths[1])]
    again_image = again_images[0]
    font = pygame.font.Font(font_path, 50)
    your_score_text = font.render('Your Score: %s' % score_info['your_score'], True, font_colors[0])
    your_score_rect = your_score_text.get_rect()
    your_score_rect.left, your_score_rect.top = (screensize[0] - your_score_rect.width) / 2, 215
    best_score_text = font.render('Best Score: %s' % score_info['best_score'], True, font_colors[1])
    best_score_rect = best_score_text.get_rect()
    best_score_rect.left, best_score_rect.top = (screensize[0] - best_score_rect.width) / 2, 275
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                sys.exit()
            elif event.type == pygame.MOUSEMOTION:
                mouse_pos = pygame.mouse.get_pos()
                if mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    again_image = again_images[1]
                else:
                    again_image = again_images[0]
            elif event.type == pygame.MOUSEBUTTONDOWN:
                if event.button == 1 and mouse_pos[0] in list(range(419, 574)) and mouse_pos[1] in list(range(374, 416)):
                    return True
        screen.blit(end_image, (0, 0))
        screen.blit(again_image, (416, 370))
        screen.blit(your_score_text, your_score_rect)
        screen.blit(best_score_text, best_score_rect)
        pygame.display.update()

大功告成~

完整源代码

https://github.com/CharlesPikachu/Games

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 好的,下面是一个简单的Python地鼠小游戏示例: ```python import random import time # 打印游戏说明 print("欢迎来到打地鼠游戏!") print("你需要在规定时间内打中尽可能多的地鼠。") print("每打中一个地鼠会得到1分,时间到了游戏结束。") print("祝你好运!") # 定义游戏时间和得分 game_time = 30 score = 0 # 开始游戏 start_time = time.time() while time.time() - start_time < game_time: # 生成地鼠位置 hole = random.randint(1, 9) # 打印地鼠洞 print("====" * 3) print("|{} {} {}|".format("O" if hole==1 else " ", "O" if hole==2 else " ", "O" if hole==3 else " ")) print("|{} {} {}|".format("O" if hole==4 else " ", "O" if hole==5 else " ", "O" if hole==6 else " ")) print("|{} {} {}|".format("O" if hole==7 else " ", "O" if hole==8 else " ", "O" if hole==9 else " ")) print("====" * 3) # 玩家输入猜测的地鼠位置 guess = int(input("请输入你猜测的地鼠位置(1-9):")) if guess == hole: print("恭喜你,打中了地鼠!") score += 1 else: print("很遗憾,你没有打中地鼠。") # 等待一段时间再继续游戏 time.sleep(1) # 游戏结束,输出得分 print("时间到了,游戏结束!你的得分是:{}".format(score)) ``` 这个游戏会在9个洞口中随机生成一个地鼠,玩家需要猜测地鼠躲在哪个洞口,如果猜中了就得到1分。游戏时间为30秒,时间到了游戏结束,输出得分。你可以根据自己的需求修改游戏的时间、难度等参数,让游戏更加有趣。 ### 回答2: Python地鼠小游戏是一款简单而有趣的游戏,可以让玩家通过控制鼠标点击地鼠图片来获得分数。实现这款游戏的方法如下: 首先,需要导入pygame模块和random模块。 ```python import pygame import random ``` 接下来,创建游戏窗口,并设置窗口的大小和标题。 ```python pygame.init() width, height = 800, 600 screen = pygame.display.set_mode((width, height)) pygame.display.set_caption("打地鼠游戏") ``` 然后,定义地鼠类。地鼠类中包含地鼠的图片和位置坐标,以及一个方法用于更新地鼠的位置。 ```python class Mole(pygame.sprite.Sprite): def __init__(self, image, pos): pygame.sprite.Sprite.__init__(self) self.image = pygame.image.load(image) self.rect = self.image.get_rect() self.rect.topleft = pos def update(self): self.rect.topleft = pos ``` 再定义一个方法用于生成随机的地鼠出现位置。 ```python def generate_mole_pos(): x = random.randint(0, width - 100) y = random.randint(0, height - 100) return (x, y) ``` 接着,初始化分数和地鼠列表。 ```python score = 0 mole_list = pygame.sprite.Group() ``` 然后,创建游戏循环。 ```python running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: running = False screen.fill((255, 255, 255)) if random.randint(1, 100) < 5: mole = Mole('mole.png', generate_mole_pos()) mole_list.add(mole) for mole in mole_list: screen.blit(mole.image, mole.rect) mole.update() pygame.display.flip() pygame.quit() ``` 最后,按照需求添加玩家点击地鼠得分以及游戏结束的逻辑即可。 这就是使用Python实现打地鼠小游戏的基本步骤,你可以根据自己的需要进行更多的定制和添加更多的功能。希望对你有帮助! ### 回答3: Python地鼠小游戏可以通过使用Pygame模块来实现。首先,我们需要创建一个游戏窗口,并设置窗口的标题、尺寸和背景色。接下来,我们可以使用Pygame的精灵类来创建地鼠和锤子的精灵对象,并设置它们的初始位置和动画。然后,使用Pygame的事件循环来监测玩家的输入,当玩家点击地鼠时,我们可以通过判断鼠标点击位置和地鼠精灵对象的碰撞来判断是否成功捕捉到地鼠。如果捕捉成功,我们可以增加得分并更新得分显示。最后,我们可以设置一个时间限制,当时间到达后游戏结束,并显示最终得分。 在游戏过程中,我们可以通过调整地鼠的出现位置和速度,增加游戏的难度。此外,我们还可以设置一个倒计时计时器,提醒玩家剩余的时间。如果玩家想要重新开始游戏,我们可以通过添加一个"重新开始"按钮来实现。 Python地鼠小游戏不仅可以提供娱乐,还可以帮助玩家提高反应和手眼协调能力。它也是一个很好的示例,可以用来学习Python编程和游戏开发。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值