How to create a game for Pygame - Part 1 (Python)

Keywords : Tic Tac Toe, Space shooter, Pynake, Pygame, Game.


Demonstrating :

Tested py3.x, wx4.x and Win10.

Are you ready to use some samples ? ;)

Test, modify, correct, complete, improve and share your discoveries ! (!)


Tic Tac Toe

img_TicTacToe.png

   1 # tic_tac_toe.py
   2 
   3 """
   4 
   5 Author : Dark Soulz
   6 Link : https://thecodezine.com/a-simple-python-tic-tac-toe-game-using-pygame/
   7 
   8 Tested py 3.7.0, Pygame 1.9.6, Windows 10.
   9 
  10 """
  11 
  12 import pygame
  13 import math
  14 
  15 pygame.init()
  16 
  17 #---------------------------------------------------------------------------
  18 
  19 # Screen
  20 WIDTH = 300
  21 ROWS = 3
  22 win = pygame.display.set_mode((WIDTH, WIDTH))
  23 pygame.display.set_caption("TicTacToe")
  24 
  25 # Colors
  26 WHITE = (255, 255, 255)
  27 BLACK = (0, 0, 0)
  28 GRAY = (200, 200, 200)
  29 RED = (255, 0, 0)
  30 BLUE = (0, 0, 255)
  31 
  32 # Images
  33 X_IMAGE = pygame.transform.scale(pygame.image.load("images/x.png"), (80, 80))
  34 O_IMAGE = pygame.transform.scale(pygame.image.load("images/o.png"), (80, 80))
  35 
  36 # Fonts
  37 END_FONT = pygame.font.SysFont('courier', 40)
  38 
  39 #---------------------------------------------------------------------------
  40 
  41 def draw_grid():
  42     gap = WIDTH // ROWS
  43 
  44     # Starting points
  45     x = 0
  46     y = 0
  47 
  48     for i in range(ROWS):
  49         x = i * gap
  50 
  51         pygame.draw.line(win, GRAY, (x, 0), (x, WIDTH), 3)
  52         pygame.draw.line(win, GRAY, (0, x), (WIDTH, x), 3)
  53 
  54 #---------------------------------------------------------------------------
  55 
  56 def initialize_grid():
  57     dis_to_cen = WIDTH // ROWS // 2
  58 
  59     # Initializing the array
  60     game_array = [[None, None, None], [None, None, None], [None, None, None]]
  61 
  62     for i in range(len(game_array)):
  63         for j in range(len(game_array[i])):
  64             x = dis_to_cen * (2 * j + 1)
  65             y = dis_to_cen * (2 * i + 1)
  66 
  67             # Adding centre coordinates
  68             game_array[i][j] = (x, y, "", True)
  69 
  70     return game_array
  71 
  72 #---------------------------------------------------------------------------
  73 
  74 def click(game_array):
  75     global x_turn, o_turn, images
  76 
  77     # Mouse position
  78     m_x, m_y = pygame.mouse.get_pos()
  79 
  80     for i in range(len(game_array)):
  81         for j in range(len(game_array[i])):
  82             x, y, char, can_play = game_array[i][j]
  83 
  84             # Distance between mouse and the centre of the square
  85             dis = math.sqrt((x - m_x) ** 2 + (y - m_y) ** 2)
  86 
  87             # If it's inside the square
  88             if dis < WIDTH // ROWS // 2 and can_play:
  89                 if x_turn:  # If it's X's turn
  90                     images.append((x, y, X_IMAGE))
  91                     x_turn = False
  92                     o_turn = True
  93                     game_array[i][j] = (x, y, 'x', False)
  94 
  95                 elif o_turn:  # If it's O's turn
  96                     images.append((x, y, O_IMAGE))
  97                     x_turn = True
  98                     o_turn = False
  99                     game_array[i][j] = (x, y, 'o', False)
 100 
 101 #---------------------------------------------------------------------------
 102 
 103 # Checking if someone has won
 104 def has_won(game_array):
 105     # Checking rows
 106     for row in range(len(game_array)):
 107         if (game_array[row][0][2] == game_array[row][1][2] == game_array[row][2][2]) and game_array[row][0][2] != "":
 108             display_message(game_array[row][0][2].upper() + " has won!")
 109             return True
 110 
 111     # Checking columns
 112     for col in range(len(game_array)):
 113         if (game_array[0][col][2] == game_array[1][col][2] == game_array[2][col][2]) and game_array[0][col][2] != "":
 114             display_message(game_array[0][col][2].upper() + " has won!")
 115             return True
 116 
 117     # Checking main diagonal
 118     if (game_array[0][0][2] == game_array[1][1][2] == game_array[2][2][2]) and game_array[0][0][2] != "":
 119         display_message(game_array[0][0][2].upper() + " has won!")
 120         return True
 121 
 122     # Checking reverse diagonal
 123     if (game_array[0][2][2] == game_array[1][1][2] == game_array[2][0][2]) and game_array[0][2][2] != "":
 124         display_message(game_array[0][2][2].upper() + " has won!")
 125         return True
 126 
 127     return False
 128 
 129 #---------------------------------------------------------------------------
 130 
 131 def has_drawn(game_array):
 132     for i in range(len(game_array)):
 133         for j in range(len(game_array[i])):
 134             if game_array[i][j][2] == "":
 135                 return False
 136 
 137     display_message("It's a draw!")
 138     return True
 139 
 140 #---------------------------------------------------------------------------
 141 
 142 def display_message(content):
 143     pygame.time.delay(500)
 144     win.fill(WHITE)
 145     end_text = END_FONT.render(content, 1, BLACK)
 146     win.blit(end_text, ((WIDTH - end_text.get_width()) // 2, (WIDTH - end_text.get_height()) // 2))
 147     pygame.display.update()
 148     pygame.time.delay(3000)
 149 
 150 #---------------------------------------------------------------------------
 151 
 152 def render():
 153     win.fill(WHITE)
 154     draw_grid()
 155 
 156     # Drawing X's and O's
 157     for image in images:
 158         x, y, IMAGE = image
 159         win.blit(IMAGE, (x - IMAGE.get_width() // 2, y - IMAGE.get_height() // 2))
 160 
 161     pygame.display.update()
 162 
 163 #---------------------------------------------------------------------------
 164 
 165 def main():
 166     global x_turn, o_turn, images, draw
 167 
 168     images = []
 169     draw = False
 170 
 171     run = True
 172 
 173     x_turn = True
 174     o_turn = False
 175 
 176     game_array = initialize_grid()
 177 
 178     while run:
 179         for event in pygame.event.get():
 180             if event.type == pygame.QUIT:
 181                 pygame.quit()
 182             if event.type == pygame.MOUSEBUTTONDOWN:
 183                 click(game_array)
 184 
 185         render()
 186 
 187         if has_won(game_array) or has_drawn(game_array):
 188             run = False
 189 
 190 #---------------------------------------------------------------------------
 191 
 192 while True:
 193     if __name__ == '__main__':
 194         main()


Space shooter

img_Space_Shooter.png

   1 # space_shooter.py
   2 
   3 """
   4 
   5 Author : Dark Soulz
   6 Link : https://thecodezine.com/easy-learn-python-space-shooter-game-building-using-pygame/
   7 
   8 Tested py 3.7.0, Pygame 1.9.6, Windows 10.
   9 
  10 """
  11 
  12 from __future__ import division
  13 import pygame
  14 import random
  15 from os import path
  16 
  17 # Assets folder
  18 img_dir = path.join(path.dirname(__file__), 'assets')
  19 sound_folder = path.join(path.dirname(__file__), 'sounds')
  20 
  21 # To be placed in "constant.py" later
  22 WIDTH = 480
  23 HEIGHT = 600
  24 FPS = 60
  25 POWERUP_TIME = 5000
  26 BAR_LENGTH = 100
  27 BAR_HEIGHT = 10
  28 
  29 # Define Colors
  30 WHITE = (255, 255, 255)
  31 BLACK = (0, 0, 0)
  32 RED = (255, 0, 0)
  33 GREEN = (0, 255, 0)
  34 BLUE = (0, 0, 255)
  35 YELLOW = (255, 255, 0)
  36 
  37 # To placed in "__init__.py" later
  38 # initialize pygame and create window
  39 pygame.init()
  40 pygame.mixer.init()  # For sound
  41 screen = pygame.display.set_mode((WIDTH, HEIGHT))
  42 pygame.display.set_caption("Space Shooter")
  43 clock = pygame.time.Clock()  # For syncing the FPS
  44 
  45 font_name = pygame.font.match_font('arial')
  46 
  47 #---------------------------------------------------------------------------
  48 
  49 def main_menu():
  50     global screen
  51 
  52     menu_song = pygame.mixer.music.load(path.join(sound_folder, "menu.ogg"))
  53     pygame.mixer.music.play(-1)
  54 
  55     title = pygame.image.load(path.join(img_dir, "main.png")).convert()
  56     title = pygame.transform.scale(title, (WIDTH, HEIGHT), screen)
  57 
  58     screen.blit(title, (0, 0))
  59     pygame.display.update()
  60 
  61     while True:
  62         ev = pygame.event.poll()
  63         if ev.type == pygame.KEYDOWN:
  64             if ev.key == pygame.K_RETURN:
  65                 break
  66             elif ev.key == pygame.K_q:
  67                 pygame.quit()
  68                 quit()
  69         elif ev.type == pygame.QUIT:
  70                 pygame.quit()
  71                 quit()
  72         else:
  73             draw_text(screen, "Press [ENTER] To Begin", 30, WIDTH/2, HEIGHT/2)
  74             draw_text(screen, "or [Q] To Quit", 30, WIDTH/2, (HEIGHT/2)+40)
  75             pygame.display.update()
  76 
  77     #pygame.mixer.music.stop()
  78     ready = pygame.mixer.Sound(path.join(sound_folder, 'getready.ogg'))
  79     ready.play()
  80     screen.fill(BLACK)
  81     draw_text(screen, "GET READY!", 40, WIDTH/2, HEIGHT/2)
  82     pygame.display.update()
  83 
  84 #---------------------------------------------------------------------------
  85 
  86 def draw_text(surf, text, size, x, y):
  87     # selecting a cross platform font to display the score
  88     font = pygame.font.Font(font_name, size)
  89     # True denotes the font to be anti-aliased
  90     text_surface = font.render(text, True, WHITE)
  91     text_rect = text_surface.get_rect()
  92     text_rect.midtop = (x, y)
  93     surf.blit(text_surface, text_rect)
  94 
  95 #---------------------------------------------------------------------------
  96 
  97 def draw_shield_bar(surf, x, y, pct):
  98     # if pct < 0:
  99     #     pct = 0
 100     pct = max(pct, 0)
 101     # moving them to top
 102     # BAR_LENGTH = 100
 103     # BAR_HEIGHT = 10
 104     fill = (pct / 100) * BAR_LENGTH
 105     outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)
 106     fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)
 107     pygame.draw.rect(surf, GREEN, fill_rect)
 108     pygame.draw.rect(surf, WHITE, outline_rect, 2)
 109 
 110 #---------------------------------------------------------------------------
 111 
 112 def draw_lives(surf, x, y, lives, img):
 113     for i in range(lives):
 114         img_rect = img.get_rect()
 115         img_rect.x = x + 30 * i
 116         img_rect.y = y
 117         surf.blit(img, img_rect)
 118 
 119 #---------------------------------------------------------------------------
 120 
 121 def newmob():
 122     mob_element = Mob()
 123     all_sprites.add(mob_element)
 124     mobs.add(mob_element)
 125 
 126 #---------------------------------------------------------------------------
 127 
 128 class Explosion(pygame.sprite.Sprite):
 129     def __init__(self, center, size):
 130         pygame.sprite.Sprite.__init__(self)
 131         self.size = size
 132         self.image = explosion_anim[self.size][0]
 133         self.rect = self.image.get_rect()
 134         self.rect.center = center
 135         self.frame = 0
 136         self.last_update = pygame.time.get_ticks()
 137         self.frame_rate = 75
 138 
 139     def update(self):
 140         now = pygame.time.get_ticks()
 141         if now - self.last_update > self.frame_rate:
 142             self.last_update = now
 143             self.frame += 1
 144             if self.frame == len(explosion_anim[self.size]):
 145                 self.kill()
 146             else:
 147                 center = self.rect.center
 148                 self.image = explosion_anim[self.size][self.frame]
 149                 self.rect = self.image.get_rect()
 150                 self.rect.center = center
 151 
 152 #---------------------------------------------------------------------------
 153 
 154 class Player(pygame.sprite.Sprite):
 155     def __init__(self):
 156         pygame.sprite.Sprite.__init__(self)
 157         # scale the player img down
 158         self.image = pygame.transform.scale(player_img, (50, 38))
 159         self.image.set_colorkey(BLACK)
 160         self.rect = self.image.get_rect()
 161         self.radius = 20
 162         self.rect.centerx = WIDTH / 2
 163         self.rect.bottom = HEIGHT - 10
 164         self.speedx = 0
 165         self.shield = 100
 166         self.shoot_delay = 250
 167         self.last_shot = pygame.time.get_ticks()
 168         self.lives = 3
 169         self.hidden = False
 170         self.hide_timer = pygame.time.get_ticks()
 171         self.power = 1
 172         self.power_timer = pygame.time.get_ticks()
 173 
 174     def update(self):
 175         # time out for powerups
 176         if self.power >= 2 and pygame.time.get_ticks() - self.power_time > POWERUP_TIME:
 177             self.power -= 1
 178             self.power_time = pygame.time.get_ticks()
 179 
 180         # unhide
 181         if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:
 182             self.hidden = False
 183             self.rect.centerx = WIDTH / 2
 184             self.rect.bottom = HEIGHT - 30
 185 
 186         self.speedx = 0  # makes the player static in the screen by default.
 187         # then we have to check whether there is an event hanlding being done for the arrow keys being
 188         # pressed
 189 
 190         # will give back a list of the keys which happen to be pressed down at that moment
 191         keystate = pygame.key.get_pressed()
 192         if keystate[pygame.K_LEFT]:
 193             self.speedx = -5
 194         elif keystate[pygame.K_RIGHT]:
 195             self.speedx = 5
 196 
 197         # Fire weapons by holding spacebar
 198         if keystate[pygame.K_SPACE]:
 199             self.shoot()
 200 
 201         # check for the borders at the left and right
 202         if self.rect.right > WIDTH:
 203             self.rect.right = WIDTH
 204         if self.rect.left < 0:
 205             self.rect.left = 0
 206 
 207         self.rect.x += self.speedx
 208 
 209     def shoot(self):
 210         # to tell the bullet where to spawn
 211         now = pygame.time.get_ticks()
 212         if now - self.last_shot > self.shoot_delay:
 213             self.last_shot = now
 214             if self.power == 1:
 215                 bullet = Bullet(self.rect.centerx, self.rect.top)
 216                 all_sprites.add(bullet)
 217                 bullets.add(bullet)
 218                 shooting_sound.play()
 219             if self.power == 2:
 220                 bullet1 = Bullet(self.rect.left, self.rect.centery)
 221                 bullet2 = Bullet(self.rect.right, self.rect.centery)
 222                 all_sprites.add(bullet1)
 223                 all_sprites.add(bullet2)
 224                 bullets.add(bullet1)
 225                 bullets.add(bullet2)
 226                 shooting_sound.play()
 227 
 228             """ MOAR POWAH """
 229             if self.power >= 3:
 230                 bullet1 = Bullet(self.rect.left, self.rect.centery)
 231                 bullet2 = Bullet(self.rect.right, self.rect.centery)
 232                 # Missile shoots from center of ship
 233                 missile1 = Missile(self.rect.centerx, self.rect.top)
 234                 all_sprites.add(bullet1)
 235                 all_sprites.add(bullet2)
 236                 all_sprites.add(missile1)
 237                 bullets.add(bullet1)
 238                 bullets.add(bullet2)
 239                 bullets.add(missile1)
 240                 shooting_sound.play()
 241                 missile_sound.play()
 242 
 243     def powerup(self):
 244         self.power += 1
 245         self.power_time = pygame.time.get_ticks()
 246 
 247     def hide(self):
 248         self.hidden = True
 249         self.hide_timer = pygame.time.get_ticks()
 250         self.rect.center = (WIDTH / 2, HEIGHT + 200)
 251 
 252 #---------------------------------------------------------------------------
 253 
 254 # defines the enemies
 255 class Mob(pygame.sprite.Sprite):
 256     def __init__(self):
 257         pygame.sprite.Sprite.__init__(self)
 258         self.image_orig = random.choice(meteor_images)
 259         self.image_orig.set_colorkey(BLACK)
 260         self.image = self.image_orig.copy()
 261         self.rect = self.image.get_rect()
 262         self.radius = int(self.rect.width * .90 / 2)
 263         self.rect.x = random.randrange(0, WIDTH - self.rect.width)
 264         self.rect.y = random.randrange(-150, -100)
 265         # for randomizing the speed of the Mob
 266         self.speedy = random.randrange(5, 20)
 267 
 268         # randomize the movements a little more
 269         self.speedx = random.randrange(-3, 3)
 270 
 271         # adding rotation to the mob element
 272         self.rotation = 0
 273         self.rotation_speed = random.randrange(-8, 8)
 274         # time when the rotation has to happen
 275         self.last_update = pygame.time.get_ticks()
 276 
 277     def rotate(self):
 278         time_now = pygame.time.get_ticks()
 279         if time_now - self.last_update > 50:  # in milliseconds
 280             self.last_update = time_now
 281             self.rotation = (self.rotation + self.rotation_speed) % 360
 282             new_image = pygame.transform.rotate(self.image_orig, self.rotation)
 283             old_center = self.rect.center
 284             self.image = new_image
 285             self.rect = self.image.get_rect()
 286             self.rect.center = old_center
 287 
 288     def update(self):
 289         self.rotate()
 290         self.rect.x += self.speedx
 291         self.rect.y += self.speedy
 292         # now what if the mob element goes out of the screen
 293 
 294         if (self.rect.top > HEIGHT + 10) or (self.rect.left < -25) or (self.rect.right > WIDTH + 20):
 295             self.rect.x = random.randrange(0, WIDTH - self.rect.width)
 296             self.rect.y = random.randrange(-100, -40)
 297             # for randomizing the speed of the Mob
 298             self.speedy = random.randrange(1, 8)
 299 
 300 #---------------------------------------------------------------------------
 301 
 302 # defines the sprite for Powerups
 303 class Pow(pygame.sprite.Sprite):
 304     def __init__(self, center):
 305         pygame.sprite.Sprite.__init__(self)
 306         self.type = random.choice(['shield', 'gun'])
 307         self.image = powerup_images[self.type]
 308         self.image.set_colorkey(BLACK)
 309         self.rect = self.image.get_rect()
 310         # place the bullet according to the current position of the player
 311         self.rect.center = center
 312         self.speedy = 2
 313 
 314     def update(self):
 315         """should spawn right in front of the player"""
 316         self.rect.y += self.speedy
 317         # kill the sprite after it moves over the top border
 318         if self.rect.top > HEIGHT:
 319             self.kill()
 320 
 321 #---------------------------------------------------------------------------
 322 
 323 # defines the sprite for bullets
 324 class Bullet(pygame.sprite.Sprite):
 325     def __init__(self, x, y):
 326         pygame.sprite.Sprite.__init__(self)
 327         self.image = bullet_img
 328         self.image.set_colorkey(BLACK)
 329         self.rect = self.image.get_rect()
 330         # place the bullet according to the current position of the player
 331         self.rect.bottom = y
 332         self.rect.centerx = x
 333         self.speedy = -10
 334 
 335     def update(self):
 336         """should spawn right in front of the player"""
 337         self.rect.y += self.speedy
 338         # kill the sprite after it moves over the top border
 339         if self.rect.bottom < 0:
 340             self.kill()
 341 
 342         # now we need a way to shoot
 343         # lets bind it to "spacebar".
 344         # adding an event for it in Game loop
 345 
 346 #---------------------------------------------------------------------------
 347 
 348 # FIRE ZE MISSILES
 349 class Missile(pygame.sprite.Sprite):
 350     def __init__(self, x, y):
 351         pygame.sprite.Sprite.__init__(self)
 352         self.image = missile_img
 353         self.image.set_colorkey(BLACK)
 354         self.rect = self.image.get_rect()
 355         self.rect.bottom = y
 356         self.rect.centerx = x
 357         self.speedy = -10
 358 
 359     def update(self):
 360         """should spawn right in front of the player"""
 361         self.rect.y += self.speedy
 362         if self.rect.bottom < 0:
 363             self.kill()
 364 
 365 
 366 #---------------------------------------------------------------------------
 367 
 368 # Load all game images
 369 
 370 background = pygame.image.load(path.join(img_dir, 'starfield.png')).convert()
 371 background_rect = background.get_rect()
 372 # ^^ draw this rect first
 373 
 374 player_img = pygame.image.load(
 375     path.join(img_dir, 'playerShip1_orange.png')).convert()
 376 player_mini_img = pygame.transform.scale(player_img, (25, 19))
 377 player_mini_img.set_colorkey(BLACK)
 378 bullet_img = pygame.image.load(path.join(img_dir, 'laserRed16.png')).convert()
 379 missile_img = pygame.image.load(
 380     path.join(img_dir, 'missile.png')).convert_alpha()
 381 # meteor_img = pygame.image.load(path.join(img_dir, 'meteorBrown_med1.png')).convert()
 382 meteor_images = []
 383 meteor_list = [
 384     'meteorBrown_big1.png',
 385     'meteorBrown_big2.png',
 386     'meteorBrown_med1.png',
 387     'meteorBrown_med3.png',
 388     'meteorBrown_small1.png',
 389     'meteorBrown_small2.png',
 390     'meteorBrown_tiny1.png'
 391 ]
 392 
 393 for image in meteor_list:
 394     meteor_images.append(pygame.image.load(
 395         path.join(img_dir, image)).convert())
 396 
 397 # meteor explosion
 398 explosion_anim = {}
 399 explosion_anim['lg'] = []
 400 explosion_anim['sm'] = []
 401 explosion_anim['player'] = []
 402 for i in range(9):
 403     filename = 'regularExplosion0{}.png'.format(i)
 404     img = pygame.image.load(path.join(img_dir, filename)).convert()
 405     img.set_colorkey(BLACK)
 406     # resize the explosion
 407     img_lg = pygame.transform.scale(img, (75, 75))
 408     explosion_anim['lg'].append(img_lg)
 409     img_sm = pygame.transform.scale(img, (32, 32))
 410     explosion_anim['sm'].append(img_sm)
 411 
 412     # player explosion
 413     filename = 'sonicExplosion0{}.png'.format(i)
 414     img = pygame.image.load(path.join(img_dir, filename)).convert()
 415     img.set_colorkey(BLACK)
 416     explosion_anim['player'].append(img)
 417 
 418 # load power ups
 419 powerup_images = {}
 420 powerup_images['shield'] = pygame.image.load(
 421     path.join(img_dir, 'shield_gold.png')).convert()
 422 powerup_images['gun'] = pygame.image.load(
 423     path.join(img_dir, 'bolt_gold.png')).convert()
 424 
 425 
 426 ###################################################
 427 
 428 
 429 ###################################################
 430 # Load all game sounds
 431 shooting_sound = pygame.mixer.Sound(path.join(sound_folder, 'pew.wav'))
 432 missile_sound = pygame.mixer.Sound(path.join(sound_folder, 'rocket.ogg'))
 433 expl_sounds = []
 434 for sound in ['expl3.wav', 'expl6.wav']:
 435     expl_sounds.append(pygame.mixer.Sound(path.join(sound_folder, sound)))
 436 # main background music
 437 # pygame.mixer.music.load(path.join(sound_folder, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))
 438 pygame.mixer.music.set_volume(0.2)  # simmered the sound down a little
 439 
 440 player_die_sound = pygame.mixer.Sound(path.join(sound_folder, 'rumble1.ogg'))
 441 ###################################################
 442 
 443 # TODO: make the game music loop over again and again. play(loops=-1) is not working
 444 # Error :
 445 # TypeError: play() takes no keyword arguments
 446 # pygame.mixer.music.play()
 447 
 448 #############################
 449 # Game loop
 450 running = True
 451 menu_display = True
 452 while running:
 453     if menu_display:
 454         main_menu()
 455         pygame.time.wait(3000)
 456 
 457         # Stop menu music
 458         pygame.mixer.music.stop()
 459         # Play the gameplay music
 460         pygame.mixer.music.load(
 461             path.join(sound_folder, 'tgfcoder-FrozenJam-SeamlessLoop.ogg'))
 462         # makes the gameplay sound in an endless loop
 463         pygame.mixer.music.play(-1)
 464 
 465         menu_display = False
 466 
 467         # group all the sprites together for ease of update
 468         all_sprites = pygame.sprite.Group()
 469         player = Player()
 470         all_sprites.add(player)
 471 
 472         # spawn a group of mob
 473         mobs = pygame.sprite.Group()
 474         for i in range(8):  # 8 mobs
 475             # mob_element = Mob()
 476             # all_sprites.add(mob_element)
 477             # mobs.add(mob_element)
 478             newmob()
 479 
 480         # group for bullets
 481         bullets = pygame.sprite.Group()
 482         powerups = pygame.sprite.Group()
 483 
 484         # Score board variable
 485         score = 0
 486 
 487     # 1 Process input/events
 488     clock.tick(FPS)  # will make the loop run at the same speed all the time
 489     # gets all the events which have occured till now and keeps tab of them.
 490     for event in pygame.event.get():
 491         # listening for the the X button at the top
 492         if event.type == pygame.QUIT:
 493             running = False
 494 
 495         # Press ESC to exit game
 496         if event.type == pygame.KEYDOWN:
 497             if event.key == pygame.K_ESCAPE:
 498                 running = False
 499         # ## event for shooting the bullets
 500         # elif event.type == pygame.KEYDOWN:
 501         #     if event.key == pygame.K_SPACE:
 502         #         player.shoot()      # we have to define the shoot()  function
 503 
 504     # 2 Update
 505     all_sprites.update()
 506 
 507     # check if a bullet hit a mob
 508     # now we have a group of bullets and a group of mob
 509     hits = pygame.sprite.groupcollide(mobs, bullets, True, True)
 510     # now as we delete the mob element when we hit one with a bullet, we need to respawn them again
 511     # as there will be no mob_elements left out
 512     for hit in hits:
 513         score += 50 - hit.radius  # give different scores for hitting big and small metoers
 514         random.choice(expl_sounds).play()
 515         # m = Mob()
 516         # all_sprites.add(m)
 517         # mobs.add(m)
 518         expl = Explosion(hit.rect.center, 'lg')
 519         all_sprites.add(expl)
 520         if random.random() > 0.9:
 521             pow = Pow(hit.rect.center)
 522             all_sprites.add(pow)
 523             powerups.add(pow)
 524         newmob()  # spawn a new mob
 525 
 526     # ^^ the above loop will create the amount of mob objects which were killed spawn again
 527     #########################
 528 
 529     # check if the player collides with the mob
 530     # gives back a list, True makes the mob element disappear
 531     hits = pygame.sprite.spritecollide(
 532         player, mobs, True, pygame.sprite.collide_circle)
 533     for hit in hits:
 534         player.shield -= hit.radius * 2
 535         expl = Explosion(hit.rect.center, 'sm')
 536         all_sprites.add(expl)
 537         newmob()
 538         if player.shield <= 0:
 539             player_die_sound.play()
 540             death_explosion = Explosion(player.rect.center, 'player')
 541             all_sprites.add(death_explosion)
 542             # running = False     # GAME OVER 3:D
 543             player.hide()
 544             player.lives -= 1
 545             player.shield = 100
 546 
 547     # if the player hit a power up
 548     hits = pygame.sprite.spritecollide(player, powerups, True)
 549     for hit in hits:
 550         if hit.type == 'shield':
 551             player.shield += random.randrange(10, 30)
 552             if player.shield >= 100:
 553                 player.shield = 100
 554         if hit.type == 'gun':
 555             player.powerup()
 556 
 557     # if player died and the explosion has finished, end game
 558     if player.lives == 0 and not death_explosion.alive():
 559         running = False
 560         # menu_display = True
 561         # pygame.display.update()
 562 
 563     # 3 Draw/render
 564     screen.fill(BLACK)
 565     # draw the stargaze.png image
 566     screen.blit(background, background_rect)
 567 
 568     all_sprites.draw(screen)
 569     # 10px down from the screen
 570     draw_text(screen, str(score), 18, WIDTH / 2, 10)
 571     draw_shield_bar(screen, 5, 5, player.shield)
 572 
 573     # Draw lives
 574     draw_lives(screen, WIDTH - 100, 5, player.lives, player_mini_img)
 575 
 576     # Done after drawing everything to the screen
 577     pygame.display.flip()
 578 
 579 pygame.quit()


Pynake

img_pynake.png

   1 # -*- coding : utf-8 -*-
   2 
   3 # pynake.py
   4 
   5 """
   6 
   7 Clássico Snake em Python.
   8 
   9 Author : ik3k3h
  10 Link : https://github.com/ik3k3h/Snake-in-PyGame
  11 
  12 Tested py 3.7.0, Pygame 1.9.6, Windows 10.
  13 
  14 """
  15 
  16 import pygame
  17 from random import randrange
  18 
  19 pygame.init()
  20 
  21 
  22 #---------------------------------------------------------------------------
  23 
  24 'COLORS (RGB)'
  25 white = (255, 255, 255)
  26 black = (0, 0, 0)
  27 red = (255, 0, 0)
  28 
  29 'WINDOW'
  30 wid = hei = 300
  31 screen = pygame.display.set_mode((wid, hei))
  32 pygame.display.set_caption('Pynake')
  33 icon = pygame.image.load('assets/images/icon/Pynake_Icon.png')
  34 pygame.display.set_icon(icon)
  35 scoreboard = 40
  36 
  37 #---------------------------------------------------------------------------
  38 
  39 def snake(snk_xy, size):
  40 
  41     for xy in snk_xy:
  42         pygame.draw.rect(screen, white, (xy[0], xy[1], size, size))
  43 
  44 #---------------------------------------------------------------------------
  45 
  46 def apple(apl_x, apl_y, size):
  47     pygame.draw.rect(screen, red, (apl_x, apl_y, size, size))
  48 
  49 #---------------------------------------------------------------------------
  50 
  51 def text(txt_msg, txt_clr, txt_x, txt_y, txt_size,):
  52     font = pygame.font.SysFont('arial', txt_size)
  53     txt = font.render(txt_msg, True, txt_clr)
  54     screen.blit(txt, (txt_x, txt_y))
  55 
  56 #---------------------------------------------------------------------------
  57 
  58 'MUSIC'
  59 # pygame.mixer_music.load('assets/sounds/.mp3')
  60 # pygame.mixer_music.play(-1)
  61 # pygame.mixer_music.set_volume(0.3)
  62 
  63 'SOUND EFFECTS'
  64 snake_bite = pygame.mixer.Sound('assets/sounds/sound_effects/Snake_Bite.wav')
  65 pygame.mixer.Sound.set_volume(snake_bite, 0.3)
  66 
  67 #---------------------------------------------------------------------------
  68 
  69 def game():
  70     main = True
  71     game_over = False
  72     clock = pygame.time.Clock()
  73     score = 0
  74 
  75     'SNAKE/APPLE'
  76     snk_x, snk_y = int(wid / 2), int(hei / 2)
  77     snk_xy = []
  78     snk_scale = 0
  79     size = 10
  80     spd_x = spd_y = 0
  81     # --- A maçã aparece em qualquer lugar da tela (menos dentro da scoreboard) e na posição correta --- #
  82     apl_x = randrange(0, wid - size, size)
  83     apl_y = randrange(0, hei - size - scoreboard, size)
  84 
  85     while main:
  86         clock.tick(5)
  87         screen.fill(black)
  88         pygame.draw.rect(screen, white, (0, hei - scoreboard, wid, scoreboard))
  89 
  90         text('Score: ' + str(score), black, 10, wid - scoreboard, 20)
  91 
  92         for event in pygame.event.get():
  93             if event.type == pygame.QUIT:
  94                 main = False
  95 
  96             'CONTROLS'
  97             if event.type == pygame.KEYDOWN:
  98                 if event.key == pygame.K_UP and spd_y != size:
  99                     spd_x = 0
 100                     spd_y = - size
 101                 if event.key == pygame.K_DOWN and spd_y != -size:
 102                     spd_x = 0
 103                     spd_y = size
 104                 if event.key == pygame.K_RIGHT and spd_x != -size:
 105                     spd_y = 0
 106                     spd_x = size
 107                 if event.key == pygame.K_LEFT and spd_x != size:
 108                     spd_y = 0
 109                     spd_x = - size
 110 
 111         'SNAKE SPEED'
 112         snk_x += spd_x
 113         snk_y += spd_y
 114 
 115         'WALL COLISSION'
 116         if snk_x >= hei or snk_x < 0 or snk_y >= wid - scoreboard or snk_y < 0:
 117             game_over = True
 118 
 119         'APPLE COLISSION'
 120         if snk_x == apl_x and snk_y == apl_y:
 121             apl_x = randrange(0, wid - size, size)
 122             apl_y = randrange(0, hei - size - scoreboard, size)
 123             snake_bite.play()
 124             snk_scale += 1
 125             score += 1
 126 
 127         'SNAKE GROW UP'
 128         # --- Faz com que a cobra creça, mas só quando comer a maçã --- #
 129         if len(snk_xy) > snk_scale:
 130             del snk_xy[0]
 131         snk_head = [snk_x, snk_y]
 132         snk_xy.append(snk_head)
 133 
 134         'SNAKE COLISSION'
 135         if any(bloc == snk_head for bloc in snk_xy[: -1]):
 136             game_over = True
 137 
 138         snake(snk_xy, size)
 139         apple(apl_x, apl_y, size)
 140 
 141         pygame.display.update()
 142 
 143         'GAME OVER SCREEN'
 144         while game_over:
 145             screen.fill(black)
 146             pygame.draw.rect(screen, white, (30, 130, 100, 25))
 147             pygame.draw.rect(screen, white, (195, 130, 60, 25))
 148 
 149             text('Game Over', white, 90, 60, 30)
 150             text('Score: ' + str(score), white, 10, wid - scoreboard, 20)
 151             text('[S] Continuar', black, 30, 130, 20)
 152             text('[N] Sair', black, 195, 130, 20)
 153 
 154             for event in pygame.event.get():
 155                 if event.type == pygame.QUIT:
 156                     game_over = False
 157                     main = False
 158 
 159                 'CONTROLS/MOUSE'
 160                 if event.type == pygame.KEYDOWN:
 161                     if event.key == pygame.K_s:
 162                         return game()
 163                     elif event.key == pygame.K_n:
 164                         game_over = False
 165                         main = False
 166                 if event.type == pygame.MOUSEBUTTONDOWN:
 167                     mouse_x = pygame.mouse.get_pos()[0]
 168                     mouse_y = pygame.mouse.get_pos()[1]
 169                     if 30 < mouse_x < 130 < mouse_y < 155:
 170                         return game()
 171                     if 195 < mouse_x < 255 and 130 < mouse_y < 155:
 172                         game_over = False
 173                         main = False
 174 
 175             pygame.display.update()
 176 
 177 #---------------------------------------------------------------------------
 178 
 179 game()
 180 pygame.quit()


Download source

source.zip


Additional Information

Link :

https://wiki.python.org/moin/GameProgramming

http://mientki.ruhosting.nl/data_www/pylab_works/pw_bricks_2d_scene.html

- - - - -

https://wiki.wxpython.org/TitleIndex

https://docs.wxpython.org/


Thanks to

Dark Soulz (tic_tac_toe / space_shooter.py coding), ik3k3h (pynake.py coding), the Pygame community...


About this page

Date(d/m/y) Person (bot) Comments :

07/09/20 - Ecco (Created page for wxPython Phoenix).


Comments

- blah, blah, blah...

How to create a game for Pygame - Part 1 (Python) (last edited 2020-10-25 16:48:47 by Ecco)

NOTE: To edit pages in this wiki you must be a member of the TrustedEditorsGroup.