当前位置:网站首页>[pyGame games] interesting puzzle game: how many hamsters can you play? (source code attached)
[pyGame games] interesting puzzle game: how many hamsters can you play? (source code attached)
2022-06-10 23:59:00 【Programmer pear】
Preface
author :“ Programmer pear ”
** The article brief introduction **: This article is mainly about the use of Pygame I wrote the little game of beating the hamster ~
** The source code of the article is available for free : In order to thank everyone who pays attention to me, the project source code of each article is none
Compensation sharing drop
Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
Text
Hee hee ! I'm classmate pear ~
We must be familiar with the game of beating hamsters , It was all the rage , Whether it's a small game on the computer or a small game you can play in your hand
have , It's not hard to see the figure of the hamster game .
Today we're going to use Pygame modular , Make a code imitation 《 Whac-A-Mole 》 The game is for everyone !

Running environment
The environment used in this article :Python3.6、Pycharm Community Edition 、Pygame What comes with the game module will not be displayed .
pip install -i https://pypi.douban.com/simple/ + Module name Effect display
1) Game interface

2) Game interface

Code display
1) The configuration file
import os
''' The screen size '''
SCREENSIZE = (993, 477)
''' Game material path '''
ROOTDIR = os.getcwd()
HAMMER_IMAGEPATHS = [os.path.join(ROOTDIR, 'resources/images/hammer0.png'), os.path.join(ROOTDIR, 'resources/images/hammer1.png')]
GAME_BEGIN_IMAGEPATHS = [os.path.join(ROOTDIR, 'resources/images/begin.png'), os.path.join(ROOTDIR, 'resources/images/begin1.png')]
GAME_AGAIN_IMAGEPATHS = [os.path.join(ROOTDIR, 'resources/images/again1.png'), os.path.join(ROOTDIR, 'resources/images/again2.png')]
GAME_BG_IMAGEPATH = os.path.join(ROOTDIR, 'resources/images/background.png')
GAME_END_IMAGEPATH = os.path.join(ROOTDIR, 'resources/images/end.png')
MOLE_IMAGEPATHS = [
os.path.join(ROOTDIR, 'resources/images/mole_1.png'),
os.path.join(ROOTDIR, 'resources/images/mole_laugh1.png'),
os.path.join(ROOTDIR, 'resources/images/mole_laugh2.png'),
os.path.join(ROOTDIR, 'resources/images/mole_laugh3.png')
]
BGM_PATH = os.path.join(ROOTDIR, 'resources/audios/bgm.mp3')
COUNT_DOWN_SOUND_PATH = os.path.join(ROOTDIR, 'resources/audios/count_down.wav')
HAMMERING_SOUND_PATH = os.path.join(ROOTDIR, 'resources/audios/hammering.wav')
FONT_PATH = os.path.join(ROOTDIR, 'resources/font/Gabriola.ttf')
''' Game constant parameter setting '''
HOLE_POSITIONS = [(90, -20), (405, -20), (720, -20), (90, 140), (405, 140), (720, 140), (90, 290), (405, 290), (720, 290)]
BROWN = (150, 75, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
RECORD_PATH = 'score.rec'2) The main program
import cfg
import sys
import pygame
import random
from modules import *
''' Game initialization '''
def initGame():
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption(' Whac-A-Mole ')
return screen
''' The main function '''
def main():
# initialization
screen = initGame()
# Load background music and other sound effects
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)
}
# Load Fonts
font = pygame.font.Font(cfg.FONT_PATH, 40)
# Load background image
bg_img = pygame.image.load(cfg.GAME_BG_IMAGEPATH)
# Start interface
startInterface(screen, cfg.GAME_BEGIN_IMAGEPATHS)
# The timing of gopher changing position
hole_pos = random.choice(cfg.HOLE_POSITIONS)
change_hole_event = pygame.USEREVENT
pygame.time.set_timer(change_hole_event, 800)
# Gophers
mole = Mole(cfg.MOLE_IMAGEPATHS, hole_pos)
# The hammer
hammer = Hammer(cfg.HAMMER_IMAGEPATHS, (500, 250))
# The clock
clock = pygame.time.Clock()
# fraction
your_score = 0
flag = False
# Initial time
init_time = pygame.time.get_ticks()
# The main cycle of the game
while True:
# -- The game time is 60s
time_remain = round((61000 - (pygame.time.get_ticks() - init_time)) / 1000.)
# -- Reduced game time , Gophers change position and speed faster
if time_remain == 40 and not flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 650)
flag = True
elif time_remain == 20 and flag:
hole_pos = random.choice(cfg.HOLE_POSITIONS)
mole.reset()
mole.setPosition(hole_pos)
pygame.time.set_timer(change_hole_event, 500)
flag = False
# -- Countdown sound
if time_remain == 10:
audios['count_down'].play()
# -- Game over
if time_remain < 0: break
count_down_text = font.render('Time: '+str(time_remain), True, cfg.WHITE)
# -- Key detection
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)
# -- collision detection
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
# -- fraction
your_score_text = font.render('Score: '+str(your_score), True, cfg.BROWN)
# -- Bind the necessary game elements to the screen ( Order of attention )
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)
# -- to update
pygame.display.flip()
clock.tick(60)
# Read the best score (try Block to avoid the first game without .rec file )
try:
best_score = int(open(cfg.RECORD_PATH).read())
except:
best_score = 0
# If the current score is greater than the best score, the best score will be updated
if your_score > best_score:
f = open(cfg.RECORD_PATH, 'w')
f.write(str(your_score))
f.close()
# End the screen
score_info = {'your_score': your_score, 'best_score': best_score}
is_restart = endInterface(screen, cfg.GAME_END_IMAGEPATH, cfg.GAME_AGAIN_IMAGEPATHS, score_info, cfg.FONT_PATH, [cfg.WHITE, cfg.RED], cfg.SCREENSIZE)
return is_restart
'''run'''
if __name__ == '__main__':
while True:
is_restart = main()
if not is_restart:
breakSummary
An LA ! This is the article , Your support is my biggest motivation , Remember Sanlian ~
Follow Xiaobian for more wonderful content ! Remember to click on the portal
Remember Sanlian ! If you need a complete package Source code + Free sharing of materials ! Portal

边栏推荐
- LabVIEW中NI MAX中缺少串口
- 干货丨MapReduce的工作流程是怎样的?
- 归并排序
- How to generate automatic references (simple drawings)
- 【自动回复or提醒小助手】妈妈再也不用担心我漏掉消息了(10行代码系列)
- Error report of curl import postman
- Method of converting file to multipartfile
- [pyGame games] in the first month, it broke 100 million to download a masterpiece that is highly integrated with "super casual game features"~
- 黑马头条丨腾讯薪酬制度改革引争议;英特尔全国扩招女工程师;黑马100%就业真的吗......
- Deepin20菜单启动选项后自检到iwlwifi停机
猜你喜欢

Easyrecovery15 simple and convenient data recovery tool

基于CenterOS7安装Redis及常见问题解决(带图讲解)

IGBT and third generation semiconductor SiC double pulse test scheme

LeetCode 501 :二叉搜索树中的众数

【Opencv实战】这个印章“神器”够牛,节省了时间提高了效率,厉害~(附完整源码)

【漫天烟花】绚烂烟花点亮夜空也太美了叭、某程序员携带烟花秀给大家拜年啦~

Difference between oscilloscope and spectrum analyzer
![[pyGame games] don't look for it. Here comes the leisure game topic - bubble dragon widget - recommendation for leisure game research and development](/img/fb/a966b4bf52cdab4030578d4595e09b.png)
[pyGame games] don't look for it. Here comes the leisure game topic - bubble dragon widget - recommendation for leisure game research and development

Vs tomato assistant add header comments and usage

Error 1046 when LabVIEW uses MathScript node or matlab script
随机推荐
Exception 0xc00000005 code occurred when LabVIEW called DLL
LeetCode 501 :二叉搜索树中的众数
Deepin20菜单启动选项后自检到iwlwifi停机
[auto reply or remind assistant] Mom doesn't have to worry about me missing messages any more (10 Line Code Series)
Unity script cannot display Chinese comments of C # source code or the script created by vs does not have comments of C # source code
Lambda 学习记录
File转为MultipartFile的方法
上海网上开户是安全的吗?
LabVIEW uses the visa read function to read USB interrupt data
Is it safe to open an account online in Shanghai?
vtk.js中vtp下载
MySQL命令行导入导出数据
长投学堂开户安全吗?靠谱吗?
Error report of curl import postman
Create millisecond time id in LabVIEW
LabVIEW programming specification
启牛学堂理财可靠吗,安全吗
【AI出牌器】第一次见这么“刺激”的斗地主,胜率高的关键因素竟是......
SystemVerilog(十)-用户自定义类型
[new version] new pseudo personal homepage v2.0- starze V Club
