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 realize the bomber Mini Game with Python

2025-02-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly explains "how to use Python to achieve bomber 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 achieve the bomber Mini Game!

Effect display

Development tools

Python version: 3.6.4

Related modules:

Pygame module

And some modules that come with Python.

Environment building

Install Python and add it to the environment variable, and pip installs the relevant modules you need.

Brief introduction of principle

Rules of the game:

The player controls the character zelda (green) action through the ↑↓←→ key, and when the player presses the spacebar, he can place a bomb in the current position. Other characters (dk and batman) are controlled by computers to act at random. When all characters are burned by the flames generated by bombs (including their own bombs), they will lose a certain amount of health; when all characters eat fruit, they can restore a certain amount of health. In addition, the wall can prevent the further spread of the flames generated by the bomb.

When our character zelda health is 0, the game fails; when all characters on the computer side have 0 health, the game wins and goes to the next level.

Step by step:

First of all, let's clarify which game elves are included in the game:

Bomb type

Role class

Wall class

Background class

Fruits

Main code

Wall class and background class are well defined, as long as you can import the image and bind the image to the specified location:

Class Wall (pygame.sprite.Sprite): def _ init__ (self, imagepath, coordinate, blocksize, * * kwargs): pygame.sprite.Sprite.__init__ (self) self.image = pygame.image.load (imagepath) self.image = pygame.transform.scale (self.image, (blocksize, blocksize)) self.rect = self.image.get_rect () self.rect.left, self.rect.top = coordinate [0] * blocksize Coordinate [1] * blocksize self.coordinate = coordinate self.blocksize = blocksize''draw to the screen def draw (self, screen): screen.blit (self.image, self.rect) return True''' background class' 'class Background (pygame.sprite.Sprite): def _ init__ (self, imagepath, coordinate, blocksize) * * kwargs): pygame.sprite.Sprite.__init__ (self) self.image = pygame.image.load (imagepath) self.image = pygame.transform.scale (self.image, (blocksize, blocksize)) self.rect = self.image.get_rect () self.rect.left, self.rect.top = coordinate [0] * blocksize Coordinate [1] * blocksize self.coordinate = coordinate self.blocksize = blocksize''draw to the screen' 'def draw (self, screen): screen.blit (self.image, self.rect) return True

The definition of fruit is similar, but different fruits can help characters restore health to different values:

Class Fruit (pygame.sprite.Sprite): def _ init__ (self, imagepath, coordinate, blocksize) * * kwargs): pygame.sprite.Sprite.__init__ (self) self.kind = imagepath.split ('/') [- 1] .split ('.) [0] if self.kind = = 'banana': self.value = 5 elif self.kind = =' cherry': self.value = 10 else: raise ValueError ('Unknow fruit...'% self.kind) self.image = pygame.image.load (imagepath) self.image = pygame.transform.scale (self.image (blocksize, blocksize) self.rect = self.image.get_rect () self.rect.left, self.rect.top = coordinate [0] * blocksize, coordinate [1] * blocksize self.coordinate = coordinate self.blocksize = blocksize''draw to the screen def draw (self, screen): screen.blit (self.image, self.rect) return True

The definition of bomb class and role class is a little more complicated. The character class needs to move up and down according to the instructions of the player or the computer, and at the same time it can generate a bomb in its own position and restore a certain amount of health after eating fruit:

Class Hero (pygame.sprite.Sprite): def _ init__ (self, imagepaths, coordinate, blocksize, map_parser, * * kwargs): pygame.sprite.Sprite.__init__ (self) self.imagepaths = imagepaths self.image = pygame.image.load (imagepaths [- 1]) self.image = pygame.transform.scale (self.image, (blocksize, blocksize) self.rect = self.image.get_rect () self.rect.left Self.rect.top = coordinate [0] * blocksize Coordinate [1] * blocksize self.coordinate = coordinate self.blocksize = blocksize self.map_parser = map_parser self.hero_name = kwargs.get ('hero_name') # Health value self.health_value = 50 # bomb cooldown self.bomb_cooling_time = 5000 self.bomb_cooling_count = 0 # Random Mobile cooldown (for AI computers only) self.randommove_cooling_ Time = 100self.randommove_cooling_count = 0''character move' 'def move (self Direction): self.__updateImage (direction) if direction = = 'left': if self.coordinate [0]-1

< 0 or self.map_parser.getElemByCoordinate([self.coordinate[0]-1, self.coordinate[1]]) in ['w', 'x', 'z']: return False self.coordinate[0] = self.coordinate[0] - 1 elif direction == 'right': if self.coordinate[0]+1 >

= self.map_parser.width or self.map_parser.getElemByCoordinate ([self.coordinate [0] + 1, self.coordinate [1]]) in ['wicked,' xtriple,'z']: return False self.coordinate [0] = self.coordinate [0] + 1 elif direction = = 'up': if self.coordinate [1]-1

< 0 or self.map_parser.getElemByCoordinate([self.coordinate[0], self.coordinate[1]-1]) in ['w', 'x', 'z']: return False self.coordinate[1] = self.coordinate[1] - 1 elif direction == 'down': if self.coordinate[1]+1 >

= self.map_parser.height or self.map_parser.getElemByCoordinate ([self.coordinate [0], self.coordinate [1] + 1]) in ['wicked,' xtriple,'z']: return False self.coordinate [1] = self.coordinate [1] + 1 else: raise ValueError ('Unknow direction...'% direction) self.rect.left, self.rect.top = self.coordinate [0] * self.blocksize Self.coordinate [1] * self.blocksize return True''Random Action (for AI computers) def randomAction (self, dt): # cooling countdown if self.randommove_cooling_count > 0: self.randommove_cooling_count-= dt action = random.choice ([' left', 'left',' right', 'right',' up', 'up',' down', 'down' 'dropbomb']) flag = False if action in [' left', 'right',' up', 'down']: if self.randommove_cooling_count 0: return self.__explode (screen, map_parser) else: self.is_being = False return False' 'explosive effect' 'def _ explode (self, screen) Map_parser): explode_area = self.__calcExplodeArea (map_parser.instances_list) for each in explode_area: image = pygame.image.load (self.explode_imagepath) image = pygame.transform.scale (image, (self.blocksize, self.blocksize)) rect = image.get_rect () rect.left, rect.top = each [0] * self.blocksize, each [1] * self.blocksize screen.blit (image Rect) return explode_area''calculate explosion area' 'def _ calcExplodeArea (self, instances_list): explode_area = [] # Zone calculation rule is that the wall can prevent the explosion from spreading, and the explosion range is only within the scope of the game map for ymin in range (self.coordinate [1], self.coordinate [1]-5,-1): if ymin

< 0 or instances_list[ymin][self.coordinate[0]] in ['w', 'x', 'z']: break explode_area.append([self.coordinate[0], ymin]) for ymax in range(self.coordinate[1]+1, self.coordinate[1]+5): if ymax >

= len (instances_list) or instances_ list [ymax] [self.coordinate [0]] in ['wicked,' xtriple,'z']: break explode_area.append ([self.coordinate [0], ymax]) for xmin in range (self.coordinate [0], self.coordinate [0]-5,-1): if xmin

< 0 or instances_list[self.coordinate[1]][xmin] in ['w', 'x', 'z']: break explode_area.append([xmin, self.coordinate[1]]) for xmax in range(self.coordinate[0]+1, self.coordinate[0]+5): if xmax >

= len (instances_list [0]) or instances_list [self.coordinate [1]] [xmax] in ['wicked,' xtriple,'z']: break explode_area.append ([xmax, self.coordinate [1]]) return explode_area

Because bomb and character classes are bound to the game screen every frame, some countdown operations are merged into the draw function, of course, it is best to write a new function to implement this function, so that the code structure will look clearer.

Next, we design our game map in the .map file:

Then parse the .map file through a map parsing class, so that you only need to import a new .map file each time you switch levels, and it is also convenient for the game to expand later:

'.map file parser''class mapParser (): def _ _ init__ (self, mapfilepath, bg_paths, wall_paths, blocksize * * kwargs): self.instances_list = self.__parse (mapfilepath) self.bg_paths = bg_paths self.wall_paths = wall_paths self.blocksize = blocksize self.height = len (self.instances_list) self.width = len (self.instances_list [0]) self.screen_size = (blocksize * self.width, blocksize * self.height)''map to the screen' 'def draw (self Screen): for j in range (self.height): for i in range (self.width): instance = self.instances_ list [j] [I] if instance = = 'wicked: elem = Wall (self.wall_paths [0], [I, j], self.blocksize) elif instance = =' xcow: elem = Wall (self.wall_paths [1], [I, j] Self.blocksize) elif instance = = 'zonal: elem = Wall (self.wall_paths [2], [I, j], self.blocksize) elif instance = =' 0percent: elem = Background (self.bg_paths [0], [I, j], self.blocksize) elif instance = = '1percent: elem = Background (self.bg_paths [1], [I, j] Self.blocksize) elif instance = '2clients: elem = Background (self.bg_paths [2], [I, j], self.blocksize) else: raise ValueError (' instance parse error in mapParser.draw...') Elem.draw (screen)''randomly acquire an open space' 'def randomGetSpace (self, used_spaces=None): while True: I = random.randint (0, self.width-1) j = random.randint (0, self.height-1) coordinate = [I, j] if used_spaces and coordinate in used_spaces: continue instance = self.instances_ list [j] [I] if instance in [' 01' '2']: break return coordinate' 'get element type based on coordinates' 'def getElemByCoordinate (self, coordinate): return self.instances_list [coordinate [1]] [coordinate [0]]' 'parse .map file' def _ parse (self) Mapfilepath): instances_list = [] with open (mapfilepath) as f: for line in f.readlines (): instances_line_list = [] for c in line: if c in ['w','x','z','0','1','2']: instances_line_list.append (c) instances_list.append (instances_line_list) return instances_list

OK, after all this preparatory work, you can start writing the game's main loop:

Def main (cfg): # initialize pygame.init () pygame.mixer.init () pygame.mixer.music.load (cfg.BGMPATH) pygame.mixer.music.play (- 1,0.0) screen = pygame.display.set_mode (cfg.SCREENSIZE) pygame.display.set_caption ('Bomber Man -? ️: apython68') # start interface Interface (screen, cfg) Mode='game_start') # Game main cycle font = pygame.font.SysFont ('Consolas', 15) for gamemap_path in cfg.GAMEMAPPATHS: #-Map map_parser = mapParser (gamemap_path, bg_paths=cfg.BACKGROUNDPATHS, wall_paths=cfg.WALLPATHS Blocksize=cfg.BLOCKSIZE) #-Fruit fruit_sprite_group = pygame.sprite.Group () used_spaces = [] for i in range (5): coordinate= map_parser.randomGetSpace (used_spaces) used_spaces.append (coordinate) fruit_sprite_group.add (Fruit (random.choice (cfg.FRUITPATHS), coordinate=coordinate Blocksize=cfg.BLOCKSIZE) #-our Hero coordinate= map_parser.randomGetSpace (used_spaces) used_spaces.append (coordinate) ourhero = Hero (imagepaths=cfg.HEROZELDAPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser, hero_name='ZELDA') #-computer Hero aihero_sprite_group = pygame.sprite.Group () coordinate= map_parser.randomGetSpace (used_spaces) aihero_sprite_group.add (Hero (imagepaths=cfg.HEROBATMANPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser) Hero_name='BATMAN') used_spaces.append (coordinate) coordinate= map_parser.randomGetSpace (used_spaces) aihero_sprite_group.add (Hero (imagepaths=cfg.HERODKPATHS, coordinate=coordinate, blocksize=cfg.BLOCKSIZE, map_parser=map_parser) Hero_name='DK')) used_spaces.append (coordinate) #-bomb bomb bomb_sprite_group = pygame.sprite.Group () #-flag is_win_flag = False #-main loop screen = pygame.display.set_mode (map_parser.screen_size) clock = pygame.time.Clock () while True: dt = clock.tick ( Cfg.FPS) for event in pygame.event.get (): if event.type = = pygame.QUIT: pygame.quit () sys.exit (- 1) #-- ↑↓←→ key controls up and down Elif event.type = = pygame.KEYDOWN: if event.key = = pygame.K_UP: ourhero.move ('up') elif event.key = = pygame.K_DOWN: ourhero.move (' down') elif event.key = = pygame.K_LEFT: ourhero.move ('left') elif event.key = = Pygame.K_RIGHT: ourhero.move ('right') elif event.key = = pygame.K_SPACE: if ourhero.bomb_cooling_count

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