当前位置:网站首页>Let's learn the game of beating hamsters
Let's learn the game of beating hamsters
2022-07-28 16:15:00 【Siege lion Yimu】
Let's interpret this game of Groundhog ........
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 —— A wood ')
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:
breakimport cfg: cfg The library file is the address library file of gopher pictures , Learn this file again .....
''' Game initialization '''
def initGame():
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode(cfg.SCREENSIZE)
pygame.display.set_caption(' Whac-A-Mole —— Jiakun ')
return screen
pygame.init() What we're doing , In fact, it's inspection , Some required hardware call interfaces on the computer 、 Whether there is a problem with the basic function . If there is , He will give you feedback before the program runs , It is convenient for you to check and avoid .
pygame.mixer.init()
Initialize mixer module
init(frequency=22050, size=-16, channels=2, buffer=4096) -> None
Initialize the mixer module for sound loading and playback . The default parameters can be changed to provide a specific audio mix . Allow keyword parameters . For backward compatibility with parameter set to zero , Use the default value ( Maybe by pre_init Call change ).
- pygame.display.init() — initialization display modular
- pygame.display.quit() — end display modular
- pygame.display.get_init() — If display The module has already been initialized , return True
- pygame.display.set_mode() — Initializes a window or screen to be displayed
- pygame.display.get_surface() — Get the currently displayed Surface object
- pygame.display.flip() — Update the entire... To be displayed Surface Object to screen
- pygame.display.update() — Update some software interface display
- pygame.display.get_driver() — obtain Pygame Displays the name of the backend
- pygame.display.Info() — Create an information object about the display interface
- pygame.display.get_wm_info() — Gets information about the current window system
- pygame.display.list_modes() — Gets the resolution available in full screen mode
- pygame.display.mode_ok() — Select the most appropriate color depth for the display mode
- pygame.display.gl_get_attribute() — Get the current display interface OpenGL The attribute value
- pygame.display.gl_set_attribute() — For the current display mode OpenGL Property value
- pygame.display.get_active() — Return when the current display interface is displayed on the screen True
- pygame.display.iconify() — Minimize displayed Surface object
- pygame.display.toggle_fullscreen() — Switch between full screen mode and window mode
- pygame.display.set_gamma() — Modify hardware display gamma gradient
- pygame.display.set_gamma_ramp() — Custom modify hardware display gamma gradient
- pygame.display.set_icon() — Modify the icon of the display window
- pygame.display.set_caption() — Set the title of the current window
- pygame.display.get_caption() — Get the title of the current window
- pygame.display.set_palette() — Display palette for current display settings .
边栏推荐
- MLX90640 红外热成像仪测温传感器模块开发笔记(八)
- 太阳能路灯的根本结构及作业原理
- One channel encoder, two channels Di speed measurement, RS485 serial port connected to one channel do alarm module ibf151
- NTC,PT100热电阻转4-20mA温度信号转换器
- LabVIEW Linx toolkit controls Arduino equipment (expansion-1)
- How to measure the vibrating wire sensor by vibrating wire acquisition module?
- 1路编码器2路DI转速测量RS485串口连接1路DO报警模块IBF151
- 带你来浅聊一下!单商户功能模块汇总
- 跳表的实现
- Food safety | these two kinds of melons and fruits should be improved, especially for pregnant women with constipation
猜你喜欢

远距离串口服务器( 适配器)UART/I2C/1-Wire/SPI PS304常见问题及注意事项

Duty cycle switch output high speed pulse counter rtumodbus module ibf63

Ethernet to RS485 serial port counter WiFi module LED light controller ibf165

动态规划 --- 数位统计DP

12V pulse speed measurement to 24V level signal conversion transmitter

低成本/小体积模块RS485/232转模拟信号的原理以及应用IBF33

Open light input / relay output rs485/232 remote data acquisition IO module ibf70

光学雨量计对比翻斗式雨量计的优势

Shell编程规范与变量

Advantages of optical rain gauge over tipping bucket rain gauge
随机推荐
为什么学编程的人大多数都去了深圳和北京?
Writing of factorial
Ethernet to RS485 serial port counter WiFi module LED light controller ibf165
Open light input / relay output rs485/232 remote data acquisition IO module ibf70
VM501开发套件开发版单振弦式传感器采集模块岩土工程监测
深入理解Istio流量管理的熔断配置
Data real-time feedback technology
Transformation principle of voltage and frequency
带你来浅聊一下!单商户功能模块汇总
js 双向链表 01
多用型混合信号8AI/4DI/DO转串口RS485/232MODBUS采集模块IBF30
2021 Kent interview question 1
JS array (summary)
Set static IP in NAT mode of virtual machine
Rust Getting Started Guide (rustup, cargo)
Ask if you don't understand, and quickly become an advanced player of container service!
High speed counter to rs485modbus RTU module ibf150
【Multisim仿真】LM339过零电路仿真
Stm32f103c8t6 + 0.96 "I2C OLED display 3d_cube
Food safety | these two kinds of melons and fruits should be improved, especially for pregnant women with constipation