当前位置:网站首页>[pyGame] this "groundhog" game is going to be popular (come on, come on)
[pyGame] this "groundhog" game is going to be popular (come on, come on)
2022-06-10 23:59:00 【Programmer pear】
Preface
author :“ Programmer pear ”
** The article brief introduction **: This article mainly uses pygame Make a hamster game .
** Article source code access **: In order to thank everyone who pays attention to me, the project source code of each article is distributed free of charge
Enjoy drops
Welcome friends give the thumbs-up 、 Collection 、 Leaving a message.
Text
Play with hamsters ?
Hee hee , You still remember the games you played when you were a child !《 snake 》、《 Card 》......
A few days ago, I happened to see that the children at home were still playing with hamsters , see , Today's material is coming , Teach you to make a simple and good
Playful 《Python Version of the hamster game 》 Give it to everyone !

1) Effect display
Start interface : Happy

Game interface :

2) Code implementation
Start interface
import sys
import pygame
''' Game start screen '''
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:
mouse_pos = pygame.mouse.get_pos()
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()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:
breakEnd the screen
import sys
import pygame
''' End the screen '''
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:
mouse_pos = pygame.mouse.get_pos()
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()summary
Hee hee , This little game , If you like, find me Naha !
Note: Xiaobian can get more wonderful content ! Remember to click on the portal
Remember Sanlian ! If you need packaged source code + Free sharing of materials !! Portal
边栏推荐
猜你喜欢

Hyperleger fabric installation

Ilruntime hotfix framework installation and breakpoint debugging

Serial port missing in Ni Max in LabVIEW
![[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

【颜值检测神器】来,请拿出你们的绝活(这颜值,对得起观众么?)

Exception 0xc00000005 code occurred when LabVIEW called DLL

Fiddler filtering sessions

Create millisecond time id in LabVIEW

LabVIEW中创建毫秒时间标识

High speed data stream disk for LabVIEW
随机推荐
LabVIEW编程规范
LeetCode 501 :二叉搜索樹中的眾數
Dark horse headlines - Tencent's salary system reform has caused controversy; Intel expanded the recruitment of female engineers nationwide; Black horse is 100% employed really
B 树的简单认识
都说验证码是爬虫中的一道坎,看我只用五行代码就突破它。
[pyGame games] don't look for it. Here comes the leisure game topic - bubble dragon widget - recommendation for leisure game research and development
LabVIEW中创建毫秒时间标识
curl导入postman报错小记
OSS stores and exports related content
Simple impedance matching circuit and formula
MySQL命令行导入导出数据
High speed data stream disk for LabVIEW
Interview questions - written examination
【无标题】
【LaTex】latex VS Code snippets(代码片段)
Is it safe for changtou school to open an account? Is it reliable?
怎么生成自动参考文献(简单 有图)
Error report of curl import postman
干货丨MapReduce的工作流程是怎样的?
【Turtle表白合集】“海底月是天上月,眼前人是心上人。”余生多喜乐,长平安~(附3款源码)
