pygame game game development

Posted by HairyScotsman on Tue, 30 Nov 2021 23:28:49 +0100

pygame game development source: https://github.com/MakerChen66/pygame2d

Originality is not easy. Copying and reprinting are prohibited in this article. The experience of many years of crawler development is summarized, so infringement must be investigated!

I. Game Creation and Settings

1.1 Game Ideas

  • The game is based on the creative background of the Winter Olympic Games in Zhangjiakou in 2022. The two mascots, pictures and pictures, are designed with the theme of winning 24 emblems in battle
  • Provides UI, Bgm, rich game material and supports rich functions such as dynamic interaction, battle explosion, random props, life bar control, etc.


1.2 Game Settings

Because the logos of previous Winter Olympic Games were stolen by aliens, heroes (Ice Piers or Snowmelt) were in danger to seize the logo. With the help of the space station (navigation, tracking and other functions), they set off on the road of Ice and Snow Heroes'Meeting. When 24 logos were assembled, the Ice Piers and Snowmelt Heroes successfully joined the divisions, the task ended successfully. Ice piers or snow melting gloriously return to the Beijing Winter Olympic Games. But the stories of ice and snow heroes are far from over... so that players can understand the history of the Winter Games while playing games


2. Introduction of Functions

The main functions are as follows:

  • Game Start Interface: The Start Interface contains five function options: hero selection, difficulty selection, start, exit, about game
  • Prepare interface: Click "Play" to jump to the game preparation page, click "Space" to start the game, click "ESC" to exit the game interface
  • Game interface: The top of the game interface shows information such as "life value", "blood volume", "number of logos collected"; In the game, heroes avoid obstacles such as ice cones and stones. Large ice cones disperse small ice cones. Move heroes up, down, left, right. Spacebar launches an attack. Hitting an obstacle destroys the obstacle and drops the logo randomly. A hero can pick up props when he encounters the logo or a life orange gem that falls randomly in the background
  • Game Winning Interface: The game loses, a black page appears, click Replay to play the game again, click Quit to exit the game
  • Game Failure Interface: Success, white interface, click Replay to play the game again, Quit to exit the game

3. Technical Routes

The basic functions are as follows, showing only part of the code:

  • Store logo pictures in a list, and drop logos randomly using for loops and random methods
huihui_images = []
for i in range(1,25):
  huihui_images_dir = path.join(img_dir,'{}.jpg'.format(i))
  huihui_image = pygame.image.load(huihui_images_dir).convert()
  huihui_images.append(huihui_image)
  • Using Pygame_menu implements dynamic menus
def show_beign_menu():
    menu = pygame_menu.Menu(600,
            800,
            'Welcome',
            theme=pygame_menu.themes.THEME_ORANGE)

    # menu.add_text_input('Player', default='John')
    menu.add_selector('Hero', [('Bing dundun', 1), ('Xue rongrong', 2)],
            onchange=set_difficulty)
    menu.add_selector('Difficulty', [('Easy', 1), ('Hard', 2)],
            onchange=set_difficulty)
    menu.add_button('Play', main)
    menu.add_button('Quit', pygame_menu.events.EXIT)
    menu.add_button('About')
    menu.mainloop(screen)
  • Use Pygame's game wizards to load pictures and bgm
img_dir = path.join(path.dirname(__file__),'img')
background_dir = path.join(img_dir,'space.png')
background_img1 = pygame.image.load(background_dir).convert()
background_img2 = pygame.image.load(background_dir).convert()
background_img3 = pygame.image.load('img/lantian.jpg').convert()
background_rect = background_img1.get_rect()
player_dir = path.join(img_dir,'hero_bingdundun.jpg')
player_img = pygame.image.load(player_dir).convert()
player_img_small = pygame.transform.scale(player_img,(35,40))
player_img_small.set_colorkey((0,0,0))
  • Batch game elf generation with Pygame's spriteGroup and collision elf detection to determine if game elves interact
hits = pygame.sprite.spritecollide(player,powerups,True)
        for hit in hits:
          if hit.type == 'add_hp':
            player.hp += 50
            if player.hp > 100:
              player.hp = 100
          elif hit.type == 'add_life':
            player.lives += 1
            if player.lives > 3:
              player.lives = 3
          else:
            player.fire_missile()

        hits = pygame.sprite.spritecollide(player,huihuis,True)
        for hit in hits:
          player.huihui += 1
          if player.huihui == 24:
            game_over == True
            show_success_menu()
  • Use Pygame drawing function to achieve life progress, logo number, life progress
def draw_ui():
  pygame.draw.rect(screen,(0,255,0),(10,10,player.hp,15))
  if player.hp < 50:
    pygame.draw.rect(screen,(255,0,0),(10,10,player.hp,15)) 
  pygame.draw.rect(screen,(255,255,255),(10,10,100,15),2)
 
  # draw_text('scores:' + str(player.score),screen,(0,255,0),20,WIDTH/2,10)
  draw_text('Emblem:' + str(player.huihui),screen,(0,255,0),20,WIDTH/2,10)

  img_rect = player_img_small.get_rect()
  img_rect.right = WIDTH - 10
  img_rect.top = 10
  for _ in range(player.lives):
    screen.blit(player_img_small,img_rect)
    img_rect.x -= img_rect.width + 10
  • Recursive Background Picture Loop Playback for Dynamic Background
class Dynamic_Background1(pygame.sprite.Sprite):

  def __init__(self):
    pygame.sprite.Sprite.__init__(self)
    self.image = pygame.transform.flip(background_img1,False,False)
    self.rect = self.image.get_rect()
    self.speed = 3
    self.last_time = pygame.time.get_ticks()

  def update(self):
    now = pygame.time.get_ticks()
    if now - self.last_time > 5:
      self.rect.y += self.speed
      self.last_time = now
      while self.rect.y >= HEIGHT:
        self.rect.y = -self.rect.height
        dynamic_background2.update()


    for event in pygame.event.get():
      if event.type == pygame.QUIT:
        game_over == True
      if event.type == pygame.KEYDOWN:
        if event.type == pygame.K_ESCAPE:
          game_over == True
  • Use Pygame's drawing functions blit() or draw() to place all picture material on the game screen
screen.blit(dynamic_background1.image,dynamic_background1.rect)
screen.blit(dynamic_background2.image,dynamic_background2.rect)
screen.blit(player.image,player.rect)
screen.blit(spaceship_zhan_shiwu.image,spaceship_zhan_shiwu.rect)
# screen.blit(space_plant_entity.image,space_plant_entity.rect)
enemys.draw(screen)
xuehuas.draw(screen)
bullets.draw(screen)
missiles.draw(screen)
explosions.draw(screen)
powerups.draw(screen)
huihuis.draw(screen)
spaceships.draw(screen)
spaceship_bullets.draw(screen)
  • Use for loop, rotation function to play the static picture continuously to achieve a series of dynamic effects, such as snowflakes, explosions, and so on.
explosion_animation = []
for i in range(9):
  explosion_dir = path.join(img_dir,'regularExplosion0{}.png'.format(i))
  explosion_img = pygame.image.load(explosion_dir).convert()
  explosion_animation.append(explosion_img)
  • Algorithms are used to calculate the dropping probability of items (blood, life, logo, etc.) based on the Icelandic blood volume
if self.hidden and now - self.hide_time > 1000:
      self.hidden = False
      self.rect.bottom = HEIGHT
      self.hp = 100
      if self.hp < 50:
        pygame.draw.rect(screen,(255,0,0),(10,10,player.hp,15))


    if self.is_missile_firing:
      if now - self.start_missile_time <= MISSILE_LIFETIME:
        if now - self.last_missile_time > MISSILE_INTERVAL:
          missile = Missile(self.rect.center)
          missiles.add(missile)
          self.last_missile_time = now
      else:
        self.is_missile_firing = False



4. Game effects

The Game Effects section shows:

5. Source Download

pygame game development source download:

The original is not easy, if it feels a little useful, I hope you can give it a compliment at will, thank you old fellow!

6. Author Info

Author: Xiaohong's fishing routine, Goal: Make programming more fun!

Origin WeChat Public Number:'Xiao Hong Star Sky Technology', focusing on algorithms, crawlers, websites, game development, data analysis, natural language processing, AI and so on, look forward to your attention, let's grow together, Coding!

Reproduction Note: Copying and reproducing are prohibited in this article, so infringement must be investigated!

Topics: Python Game Development pygame