Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to make hamster Mini Game with Python

2025-03-29 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly explains "how to use Python to make hamster Mini Game", interested friends may wish to have a look. The method introduced in this paper is simple, fast and practical. Now let the editor take you to learn how to use Python to make hamster Mini Game.

Brief introduction

I believe we all know the rules of the gopher game, so there is no more introduction here. Anyway, it is a gopher drilled out of the hole with a hammer.

First of all, let's determine what elements are in the game. If you beat a gopher, of course you have to have a gopher, so let's write a gopher game genie:

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 (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''set location' 'def setPosition (self, pos): self.rect.left Self.rect.top = pos''setting hit' 'def setBeHammered (self): self.is_hammer = True''is displayed on the screen''def draw (self, screen): if self.is_hammer: self.image = self.images [1] screen.blit (self.image) Self.rect)''reset' 'def reset (self): self.image = self.images [0] self.is_hammer = False

Obviously, the gopher has two states: being hit by a hammer and not being hit by a hammer, so it is necessary to load two pictures. The gopher status chart that the local mole has never been hit when it is hit is switched to the gopher state chart after being hit (the picture I am looking for may not be very similar to the gopher, please forgive me. Then let's define hammer as a game genie. Similar to gophers, hammers have two states: unhammered and hammered, but they need to return to the unhammered state quickly after hammering down. Specifically, the code is implemented as follows:

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 # used to display the special effects of hammering self.hammer_count = 0 self.hammer_last_time = 4 self.is_hammering = False''set position' 'def setPosition (self, pos): self.rect.centerx Self.rect.centery = pos''set hammering''' def setHammering (self): self.is_hammering = True' display on the screen''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, after defining the game wizard, we can start to write the main program. First of all, naturally, the game is initialized:

Def initGame (): pygame.init () pygame.mixer.init () screen = pygame.display.set_mode (cfg.SCREENSIZE) pygame.display.set_caption ("Whac A Mole- Wechat official account: Pikachu of Charles") return screen

Then load the necessary game material and define the necessary game variables (I have annotated them in more detail, so I won't repeat them in the article, just read the notes for myself.)

# 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 font 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) # timing hole_pos = random.choice (cfg.HOLE_POSITIONS) change_hole_event = pygame.USEREVENT pygame.time.set_timer (change_hole_event, 800) # hamster mole = Mole (cfg.MOLE_IMAGEPATHS Hole_pos) # Hammer hammer = Hammer (cfg.HAMMER_IMAGEPATHS, (500,250)) # clock clock = pygame.time.Clock () # Fractional your_score = 0

Then comes the game master cycle:

# the main cycle of the game while True: #-the game time is 60s time_remain = round ((61000-pygame.time.get_ticks ()) / 1000.) #-the game time is reduced, and the speed of the hamster changing position is faster if time_remain = = 40: pygame.time.set_timer (change_hole_event, 650) elif time_remain = = 20: pygame.time.set_timer (change_hole_event) 500) #-countdown sound if time_remain = 10: audios ['count_down'] .play () #-Game end 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 ()

To make the game look more formal, add a start interface and an end interface:

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 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 Return True screen.blit (begin_image, (0,0)) pygame.display.update ()''end interface' '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 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 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 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 () so far I believe you have a deeper understanding of "how to use Python to make hamster Mini Game". You might as well do it in practice. Here is the website, more related content can enter the relevant channels to inquire, follow us, continue to learn!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report