当前位置:网站首页>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:
            break

import 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 .

原网站

版权声明
本文为[Siege lion Yimu]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/196/202207130916137002.html