<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
效果展示
簡介
打地鼠的遊戲規則相信大家都知道,這裡就不多介紹了,反正就是不停地拿錘子打洞裡鑽出來的地鼠唄~
首先,讓我們確定一下游戲中有哪些元素。打地鼠打地鼠,地鼠當然得有啦,那我們就寫個地鼠的遊戲精靈類唄:
'''地鼠''' 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()
大功告成~
以上就是基於Python製作打地鼠小遊戲的詳細內容,更多關於Python打地鼠遊戲的資料請關注it145.com其它相關文章!
相關文章
<em>Mac</em>Book项目 2009年学校开始实施<em>Mac</em>Book项目,所有师生配备一本<em>Mac</em>Book,并同步更新了校园无线网络。学校每周进行电脑技术更新,每月发送技术支持资料,极大改变了教学及学习方式。因此2011
2021-06-01 09:32:01
综合看Anker超能充系列的性价比很高,并且与不仅和iPhone12/苹果<em>Mac</em>Book很配,而且适合多设备充电需求的日常使用或差旅场景,不管是安卓还是Switch同样也能用得上它,希望这次分享能给准备购入充电器的小伙伴们有所
2021-06-01 09:31:42
除了L4WUDU与吴亦凡已经多次共事,成为了明面上的厂牌成员,吴亦凡还曾带领20XXCLUB全队参加2020年的一场音乐节,这也是20XXCLUB首次全员合照,王嗣尧Turbo、陈彦希Regi、<em>Mac</em> Ova Seas、林渝植等人全部出场。然而让
2021-06-01 09:31:34
目前应用IPFS的机构:1 谷歌<em>浏览器</em>支持IPFS分布式协议 2 万维网 (历史档案博物馆)数据库 3 火狐<em>浏览器</em>支持 IPFS分布式协议 4 EOS 等数字货币数据存储 5 美国国会图书馆,历史资料永久保存在 IPFS 6 加
2021-06-01 09:31:24
开拓者的车机是兼容苹果和<em>安卓</em>,虽然我不怎么用,但确实兼顾了我家人的很多需求:副驾的门板还配有解锁开关,有的时候老婆开车,下车的时候偶尔会忘记解锁,我在副驾驶可以自己开门:第二排设计很好,不仅配置了一个很大的
2021-06-01 09:30:48
不仅是<em>安卓</em>手机,苹果手机的降价力度也是前所未有了,iPhone12也“跳水价”了,发布价是6799元,如今已经跌至5308元,降价幅度超过1400元,最新定价确认了。iPhone12是苹果首款5G手机,同时也是全球首款5nm芯片的智能机,它
2021-06-01 09:30:45