├── 9781484217894.jpg ├── LICENSE.txt ├── ProgramArcadeGamesCode ├── AliceInWonderLand.txt ├── AliceInWonderLand200.txt ├── alien.png ├── animating_snow.py ├── array_backed_grid.py ├── background_music.py ├── bitmapped_graphics.py ├── bounce_ball_with_paddle.py ├── bouncing_rectangle.py ├── breakout_simple.py ├── bullets.py ├── bullets_aimed.py ├── calculate_kinetic_energy.py ├── calculate_miles_per_gallon.py ├── character.png ├── click.wav ├── dictionary.txt ├── draw_module_example.py ├── exception_handling.py ├── for_loop_examples.py ├── fractal.py ├── functions_and_graphics.py ├── game_class_example.py ├── game_over.py ├── gfxtest.py ├── grid_backed_map.py ├── high_score.py ├── if_statement_examples.py ├── instruction_screen.py ├── joystick_calls.py ├── laser5.ogg ├── maze_runner.py ├── move_game_controller.py ├── move_keyboard.py ├── move_mouse.py ├── move_sprite_game_controller.py ├── move_sprite_keyboard_jump.py ├── move_sprite_keyboard_smooth.py ├── move_sprite_mouse.py ├── move_with_walls_example.py ├── moving_sprites.py ├── moving_sprites_bounce.py ├── mudball.py ├── network_client.py ├── network_server_blocking.py ├── network_server_nonblocking.py ├── number_guessing_game.py ├── opengl_lesson01.py ├── pick_up_blocks.py ├── platform_jumper.py ├── platform_moving.py ├── platform_scroller.py ├── player.jpg ├── player.png ├── playerShip1_orange.jpg ├── playerShip1_orange.png ├── pong.py ├── posting_template.txt ├── property_check_examples.py ├── pygame_base_template.py ├── pygame_base_template_proper.py ├── radar_sweep.py ├── read_from_file.py ├── recursive_rectangles.py ├── saturn_family1.jpg ├── searching_example.py ├── simple_decryption.py ├── simple_encryption.py ├── simple_graphics_demo.py ├── simple_web_server.py ├── snake.py ├── sorting_examples.py ├── sprite_circle_movement.py ├── sprite_collect_blocks.py ├── sprite_collect_blocks_levels.py ├── sprite_collect_circle.py ├── sprite_collect_graphic.py ├── sprite_collect_graphic_direction.py ├── sprite_rotating.py ├── sprite_sheets │ ├── background_01.png │ ├── background_01.tmx │ ├── background_02.png │ ├── background_02.tmx │ ├── constants.py │ ├── levels.py │ ├── p1_walk.png │ ├── platform_scroller.py │ ├── platforms.py │ ├── player.py │ ├── sheet.png │ ├── spritesheet_functions.py │ ├── tiles_spritesheet.png │ └── tiles_spritesheet.xml ├── super_villains.txt ├── text_rotate.py ├── timer.py ├── ufo.png ├── while_loop_examples.py └── word_search.py ├── README.md └── contributing.md /9781484217894.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/9781484217894.jpg -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/LICENSE.txt -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/alien.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/alien.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/animating_snow.py: -------------------------------------------------------------------------------- 1 | """ 2 | Animating multiple objects using a list. 3 | Sample Python/Pygame Programs 4 | Simpson College Computer Science 5 | http://programarcadegames.com/ 6 | http://simpson.edu/computer-science/ 7 | 8 | Explanation video: http://youtu.be/Gkhz3FuhGoI 9 | """ 10 | 11 | # Import a library of functions called 'pygame' 12 | import pygame 13 | import random 14 | 15 | # Initialize the game engine 16 | pygame.init() 17 | 18 | BLACK = [0, 0, 0] 19 | WHITE = [255, 255, 255] 20 | 21 | # Set the height and width of the screen 22 | SIZE = [400, 400] 23 | 24 | screen = pygame.display.set_mode(SIZE) 25 | pygame.display.set_caption("Snow Animation") 26 | 27 | # Create an empty array 28 | snow_list = [] 29 | 30 | # Loop 50 times and add a snow flake in a random x,y position 31 | for i in range(50): 32 | x = random.randrange(0, 400) 33 | y = random.randrange(0, 400) 34 | snow_list.append([x, y]) 35 | 36 | clock = pygame.time.Clock() 37 | 38 | # Loop until the user clicks the close button. 39 | done = False 40 | while not done: 41 | 42 | for event in pygame.event.get(): # User did something 43 | if event.type == pygame.QUIT: # If user clicked close 44 | done = True # Flag that we are done so we exit this loop 45 | 46 | # Set the screen background 47 | screen.fill(BLACK) 48 | 49 | # Process each snow flake in the list 50 | for i in range(len(snow_list)): 51 | 52 | # Draw the snow flake 53 | pygame.draw.circle(screen, WHITE, snow_list[i], 2) 54 | 55 | # Move the snow flake down one pixel 56 | snow_list[i][1] += 1 57 | 58 | # If the snow flake has moved off the bottom of the screen 59 | if snow_list[i][1] > 400: 60 | # Reset it just above the top 61 | y = random.randrange(-50, -10) 62 | snow_list[i][1] = y 63 | # Give it a new x position 64 | x = random.randrange(0, 400) 65 | snow_list[i][0] = x 66 | 67 | # Go ahead and update the screen with what we've drawn. 68 | pygame.display.flip() 69 | clock.tick(20) 70 | 71 | # Be IDLE friendly. If you forget this line, the program will 'hang' 72 | # on exit. 73 | pygame.quit() 74 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/array_backed_grid.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example program to show using an array to back a grid on-screen. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/mdTeqiWyFnc 10 | """ 11 | import pygame 12 | 13 | # Define some colors 14 | BLACK = (0, 0, 0) 15 | WHITE = (255, 255, 255) 16 | GREEN = (0, 255, 0) 17 | RED = (255, 0, 0) 18 | 19 | # This sets the WIDTH and HEIGHT of each grid location 20 | WIDTH = 20 21 | HEIGHT = 20 22 | 23 | # This sets the margin between each cell 24 | MARGIN = 5 25 | 26 | # Create a 2 dimensional array. A two dimensional 27 | # array is simply a list of lists. 28 | grid = [] 29 | for row in range(10): 30 | # Add an empty array that will hold each cell 31 | # in this row 32 | grid.append([]) 33 | for column in range(10): 34 | grid[row].append(0) # Append a cell 35 | 36 | # Set row 1, cell 5 to one. (Remember rows and 37 | # column numbers start at zero.) 38 | grid[1][5] = 1 39 | 40 | # Initialize pygame 41 | pygame.init() 42 | 43 | # Set the HEIGHT and WIDTH of the screen 44 | WINDOW_SIZE = [255, 255] 45 | screen = pygame.display.set_mode(WINDOW_SIZE) 46 | 47 | # Set title of screen 48 | pygame.display.set_caption("Array Backed Grid") 49 | 50 | # Loop until the user clicks the close button. 51 | done = False 52 | 53 | # Used to manage how fast the screen updates 54 | clock = pygame.time.Clock() 55 | 56 | # -------- Main Program Loop ----------- 57 | while not done: 58 | for event in pygame.event.get(): # User did something 59 | if event.type == pygame.QUIT: # If user clicked close 60 | done = True # Flag that we are done so we exit this loop 61 | elif event.type == pygame.MOUSEBUTTONDOWN: 62 | # User clicks the mouse. Get the position 63 | pos = pygame.mouse.get_pos() 64 | # Change the x/y screen coordinates to grid coordinates 65 | column = pos[0] // (WIDTH + MARGIN) 66 | row = pos[1] // (HEIGHT + MARGIN) 67 | # Set that location to one 68 | grid[row][column] = 1 69 | print("Click ", pos, "Grid coordinates: ", row, column) 70 | 71 | # Set the screen background 72 | screen.fill(BLACK) 73 | 74 | # Draw the grid 75 | for row in range(10): 76 | for column in range(10): 77 | color = WHITE 78 | if grid[row][column] == 1: 79 | color = GREEN 80 | pygame.draw.rect(screen, 81 | color, 82 | [(MARGIN + WIDTH) * column + MARGIN, 83 | (MARGIN + HEIGHT) * row + MARGIN, 84 | WIDTH, 85 | HEIGHT]) 86 | 87 | # Limit to 60 frames per second 88 | clock.tick(60) 89 | 90 | # Go ahead and update the screen with what we've drawn. 91 | pygame.display.flip() 92 | 93 | # Be IDLE friendly. If you forget this line, the program will 'hang' 94 | # on exit. 95 | pygame.quit() 96 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/background_music.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to run background music in Pygame. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | import pygame 10 | 11 | # Define some colors 12 | black = (0, 0, 0) 13 | white = (255, 255, 255) 14 | green = (0, 255, 0) 15 | red = (255, 0, 0) 16 | 17 | pygame.init() 18 | 19 | # Set the width and height of the screen [width,height] 20 | size = [700, 500] 21 | screen = pygame.display.set_mode(size) 22 | 23 | pygame.display.set_caption("My Game") 24 | 25 | # Loop until the user clicks the close button. 26 | done = False 27 | 28 | # Used to manage how fast the screen updates 29 | clock = pygame.time.Clock() 30 | 31 | # Play "O Fortuna" by MIT Choir 32 | # Available from: 33 | # http://freemusicarchive.org/music/MIT_Concert_Choir/Carmina_Burana_Carl_Orff/01_1355 34 | pygame.mixer.music.load('MIT_Concert_Choir_O_Fortuna.ogg') 35 | pygame.mixer.music.set_endevent(pygame.constants.USEREVENT) 36 | pygame.mixer.music.play() 37 | 38 | # -------- Main Program Loop ----------- 39 | while not done: 40 | # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT 41 | for event in pygame.event.get(): # User did something 42 | if event.type == pygame.QUIT: # If user clicked close 43 | done = True # Flag that we are done so we exit this loop 44 | elif event.type == pygame.constants.USEREVENT: 45 | # This event is triggered when the song stops playing. 46 | # 47 | # Next, play "Alone" by Saito Koji 48 | # Available from: 49 | # http://freemusicarchive.org/music/Saito_Koji/Again/01-Alone 50 | pygame.mixer.music.load('Saito_Koji_-_01_-_Alone.ogg') 51 | pygame.mixer.music.play() 52 | 53 | # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT 54 | 55 | # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT 56 | 57 | # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT 58 | 59 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 60 | 61 | # First, clear the screen to white. Don't put other drawing commands 62 | # above this, or they will be erased with this command. 63 | screen.fill(white) 64 | 65 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 66 | 67 | # Go ahead and update the screen with what we've drawn. 68 | pygame.display.flip() 69 | 70 | # Limit frames per second 71 | clock.tick(60) 72 | 73 | # Close the window and quit. 74 | # If you forget this line, the program will 'hang' 75 | # on exit if running from IDLE. 76 | pygame.quit() 77 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/bitmapped_graphics.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | 7 | Explanation video: http://youtu.be/4YqIKncMJNs 8 | Explanation video: http://youtu.be/ONAK8VZIcI4 9 | Explanation video: http://youtu.be/_6c4o41BIms 10 | """ 11 | 12 | import pygame 13 | 14 | # Define some colors 15 | WHITE = (255, 255, 255) 16 | BLACK = (0, 0, 0) 17 | 18 | # Call this function so the Pygame library can initialize itself 19 | pygame.init() 20 | 21 | # Create an 800x600 sized screen 22 | screen = pygame.display.set_mode([800, 600]) 23 | 24 | # This sets the name of the window 25 | pygame.display.set_caption('CMSC 150 is cool') 26 | 27 | clock = pygame.time.Clock() 28 | 29 | # Before the loop, load the sounds: 30 | click_sound = pygame.mixer.Sound("laser5.ogg") 31 | 32 | # Set positions of graphics 33 | background_position = [0, 0] 34 | 35 | # Load and set up graphics. 36 | background_image = pygame.image.load("saturn_family1.jpg").convert() 37 | player_image = pygame.image.load("playerShip1_orange.png").convert() 38 | player_image.set_colorkey(BLACK) 39 | 40 | done = False 41 | 42 | while not done: 43 | for event in pygame.event.get(): 44 | if event.type == pygame.QUIT: 45 | done = True 46 | elif event.type == pygame.MOUSEBUTTONDOWN: 47 | click_sound.play() 48 | 49 | # Copy image to screen: 50 | screen.blit(background_image, background_position) 51 | 52 | # Get the current mouse position. This returns the position 53 | # as a list of two numbers. 54 | player_position = pygame.mouse.get_pos() 55 | x = player_position[0] 56 | y = player_position[1] 57 | 58 | # Copy image to screen: 59 | screen.blit(player_image, [x, y]) 60 | 61 | pygame.display.flip() 62 | 63 | clock.tick(60) 64 | 65 | pygame.quit() 66 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/bouncing_rectangle.py: -------------------------------------------------------------------------------- 1 | """ 2 | Bounces a rectangle around the screen. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/-GmKoaX2iMs 10 | """ 11 | 12 | import pygame 13 | 14 | # Define some colors 15 | BLACK = (0, 0, 0) 16 | WHITE = (255, 255, 255) 17 | GREEN = (0, 255, 0) 18 | RED = (255, 0, 0) 19 | 20 | pygame.init() 21 | 22 | # Set the height and width of the screen 23 | size = [700, 500] 24 | screen = pygame.display.set_mode(size) 25 | 26 | pygame.display.set_caption("Bouncing Rectangle") 27 | 28 | # Loop until the user clicks the close button. 29 | done = False 30 | 31 | # Used to manage how fast the screen updates 32 | clock = pygame.time.Clock() 33 | 34 | # Starting position of the rectangle 35 | rect_x = 50 36 | rect_y = 50 37 | 38 | # Speed and direction of rectangle 39 | rect_change_x = 2 40 | rect_change_y = 2 41 | 42 | # -------- Main Program Loop ----------- 43 | while not done: 44 | # --- Event Processing 45 | for event in pygame.event.get(): 46 | if event.type == pygame.QUIT: 47 | done = True 48 | 49 | # --- Logic 50 | # Move the rectangle starting point 51 | rect_x += rect_change_x 52 | rect_y += rect_change_y 53 | 54 | # Bounce the ball if needed 55 | if rect_y > 450 or rect_y < 0: 56 | rect_change_y = rect_change_y * -1 57 | if rect_x > 650 or rect_x < 0: 58 | rect_change_x = rect_change_x * -1 59 | 60 | # --- Drawing 61 | # Set the screen background 62 | screen.fill(BLACK) 63 | 64 | # Draw the rectangle 65 | pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50, 50]) 66 | pygame.draw.rect(screen, RED, [rect_x + 10, rect_y + 10, 30, 30]) 67 | 68 | # --- Wrap-up 69 | # Limit to 60 frames per second 70 | clock.tick(60) 71 | 72 | # Go ahead and update the screen with what we've drawn. 73 | pygame.display.flip() 74 | 75 | # Close everything down 76 | pygame.quit() 77 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/bullets.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to fire bullets. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/PpdJjaiLX6A 10 | """ 11 | import pygame 12 | import random 13 | 14 | # Define some colors 15 | BLACK = (0, 0, 0) 16 | WHITE = (255, 255, 255) 17 | RED = (255, 0, 0) 18 | BLUE = (0, 0, 255) 19 | 20 | # --- Classes 21 | 22 | 23 | class Block(pygame.sprite.Sprite): 24 | """ This class represents the block. """ 25 | def __init__(self, color): 26 | # Call the parent class (Sprite) constructor 27 | super().__init__() 28 | 29 | self.image = pygame.Surface([20, 15]) 30 | self.image.fill(color) 31 | 32 | self.rect = self.image.get_rect() 33 | 34 | 35 | class Player(pygame.sprite.Sprite): 36 | """ This class represents the Player. """ 37 | 38 | def __init__(self): 39 | """ Set up the player on creation. """ 40 | # Call the parent class (Sprite) constructor 41 | super().__init__() 42 | 43 | self.image = pygame.Surface([20, 20]) 44 | self.image.fill(RED) 45 | 46 | self.rect = self.image.get_rect() 47 | 48 | def update(self): 49 | """ Update the player's position. """ 50 | # Get the current mouse position. This returns the position 51 | # as a list of two numbers. 52 | pos = pygame.mouse.get_pos() 53 | 54 | # Set the player x position to the mouse x position 55 | self.rect.x = pos[0] 56 | 57 | 58 | class Bullet(pygame.sprite.Sprite): 59 | """ This class represents the bullet . """ 60 | def __init__(self): 61 | # Call the parent class (Sprite) constructor 62 | super().__init__() 63 | 64 | self.image = pygame.Surface([4, 10]) 65 | self.image.fill(BLACK) 66 | 67 | self.rect = self.image.get_rect() 68 | 69 | def update(self): 70 | """ Move the bullet. """ 71 | self.rect.y -= 3 72 | 73 | 74 | # --- Create the window 75 | 76 | # Initialize Pygame 77 | pygame.init() 78 | 79 | # Set the height and width of the screen 80 | screen_width = 700 81 | screen_height = 400 82 | screen = pygame.display.set_mode([screen_width, screen_height]) 83 | 84 | # --- Sprite lists 85 | 86 | # This is a list of every sprite. All blocks and the player block as well. 87 | all_sprites_list = pygame.sprite.Group() 88 | 89 | # List of each block in the game 90 | block_list = pygame.sprite.Group() 91 | 92 | # List of each bullet 93 | bullet_list = pygame.sprite.Group() 94 | 95 | # --- Create the sprites 96 | 97 | for i in range(50): 98 | # This represents a block 99 | block = Block(BLUE) 100 | 101 | # Set a random location for the block 102 | block.rect.x = random.randrange(screen_width) 103 | block.rect.y = random.randrange(350) 104 | 105 | # Add the block to the list of objects 106 | block_list.add(block) 107 | all_sprites_list.add(block) 108 | 109 | # Create a red player block 110 | player = Player() 111 | all_sprites_list.add(player) 112 | 113 | # Loop until the user clicks the close button. 114 | done = False 115 | 116 | # Used to manage how fast the screen updates 117 | clock = pygame.time.Clock() 118 | 119 | score = 0 120 | player.rect.y = 370 121 | 122 | # -------- Main Program Loop ----------- 123 | while not done: 124 | # --- Event Processing 125 | for event in pygame.event.get(): 126 | if event.type == pygame.QUIT: 127 | done = True 128 | 129 | elif event.type == pygame.MOUSEBUTTONDOWN: 130 | # Fire a bullet if the user clicks the mouse button 131 | bullet = Bullet() 132 | # Set the bullet so it is where the player is 133 | bullet.rect.x = player.rect.x 134 | bullet.rect.y = player.rect.y 135 | # Add the bullet to the lists 136 | all_sprites_list.add(bullet) 137 | bullet_list.add(bullet) 138 | 139 | # --- Game logic 140 | 141 | # Call the update() method on all the sprites 142 | all_sprites_list.update() 143 | 144 | # Calculate mechanics for each bullet 145 | for bullet in bullet_list: 146 | 147 | # See if it hit a block 148 | block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True) 149 | 150 | # For each block hit, remove the bullet and add to the score 151 | for block in block_hit_list: 152 | bullet_list.remove(bullet) 153 | all_sprites_list.remove(bullet) 154 | score += 1 155 | print(score) 156 | 157 | # Remove the bullet if it flies up off the screen 158 | if bullet.rect.y < -10: 159 | bullet_list.remove(bullet) 160 | all_sprites_list.remove(bullet) 161 | 162 | # --- Draw a frame 163 | 164 | # Clear the screen 165 | screen.fill(WHITE) 166 | 167 | # Draw all the spites 168 | all_sprites_list.draw(screen) 169 | 170 | # Go ahead and update the screen with what we've drawn. 171 | pygame.display.flip() 172 | 173 | # --- Limit to 20 frames per second 174 | clock.tick(60) 175 | 176 | pygame.quit() 177 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/bullets_aimed.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to fire bullets at the mouse. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | import pygame 10 | import random 11 | import math 12 | 13 | # Define some colors 14 | BLACK = (0, 0, 0) 15 | WHITE = (255, 255, 255) 16 | RED = (255, 0, 0) 17 | BLUE = (0, 0, 255) 18 | 19 | SCREEN_WIDTH = 700 20 | SCREEN_HEIGHT = 400 21 | # --- Classes 22 | 23 | 24 | class Block(pygame.sprite.Sprite): 25 | """ This class represents the block. """ 26 | def __init__(self, color): 27 | # Call the parent class (Sprite) constructor 28 | super().__init__() 29 | 30 | self.image = pygame.Surface([20, 15]) 31 | self.image.fill(color) 32 | 33 | self.rect = self.image.get_rect() 34 | 35 | 36 | class Player(pygame.sprite.Sprite): 37 | """ This class represents the Player. """ 38 | 39 | def __init__(self): 40 | """ Set up the player on creation. """ 41 | # Call the parent class (Sprite) constructor 42 | super().__init__() 43 | 44 | self.image = pygame.Surface([20, 20]) 45 | self.image.fill(RED) 46 | 47 | self.rect = self.image.get_rect() 48 | 49 | 50 | class Bullet(pygame.sprite.Sprite): 51 | """ This class represents the bullet. """ 52 | 53 | def __init__(self, start_x, start_y, dest_x, dest_y): 54 | """ Constructor. 55 | It takes in the starting x and y location. 56 | It also takes in the destination x and y position. 57 | """ 58 | 59 | # Call the parent class (Sprite) constructor 60 | super().__init__() 61 | 62 | # Set up the image for the bullet 63 | self.image = pygame.Surface([4, 10]) 64 | self.image.fill(BLACK) 65 | 66 | self.rect = self.image.get_rect() 67 | 68 | # Move the bullet to our starting location 69 | self.rect.x = start_x 70 | self.rect.y = start_y 71 | 72 | # Because rect.x and rect.y are automatically converted 73 | # to integers, we need to create different variables that 74 | # store the location as floating point numbers. Integers 75 | # are not accurate enough for aiming. 76 | self.floating_point_x = start_x 77 | self.floating_point_y = start_y 78 | 79 | # Calculation the angle in radians between the start points 80 | # and end points. This is the angle the bullet will travel. 81 | x_diff = dest_x - start_x 82 | y_diff = dest_y - start_y 83 | angle = math.atan2(y_diff, x_diff); 84 | 85 | # Taking into account the angle, calculate our change_x 86 | # and change_y. Velocity is how fast the bullet travels. 87 | velocity = 5 88 | self.change_x = math.cos(angle) * velocity 89 | self.change_y = math.sin(angle) * velocity 90 | 91 | def update(self): 92 | """ Move the bullet. """ 93 | 94 | # The floating point x and y hold our more accurate location. 95 | self.floating_point_y += self.change_y 96 | self.floating_point_x += self.change_x 97 | 98 | # The rect.x and rect.y are converted to integers. 99 | self.rect.y = int(self.floating_point_y) 100 | self.rect.x = int(self.floating_point_x) 101 | 102 | # If the bullet flies of the screen, get rid of it. 103 | if self.rect.x < 0 or self.rect.x > SCREEN_WIDTH or self.rect.y < 0 or self.rect.y > SCREEN_HEIGHT: 104 | self.kill() 105 | 106 | 107 | 108 | # --- Create the window 109 | 110 | # Initialize Pygame 111 | pygame.init() 112 | 113 | # Set the height and width of the screen 114 | 115 | screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) 116 | 117 | # --- Sprite lists 118 | 119 | # This is a list of every sprite. All blocks and the player block as well. 120 | all_sprites_list = pygame.sprite.Group() 121 | 122 | # List of each block in the game 123 | block_list = pygame.sprite.Group() 124 | 125 | # List of each bullet 126 | bullet_list = pygame.sprite.Group() 127 | 128 | # --- Create the sprites 129 | 130 | for i in range(50): 131 | # This represents a block 132 | block = Block(BLUE) 133 | 134 | # Set a random location for the block 135 | block.rect.x = random.randrange(SCREEN_WIDTH) 136 | block.rect.y = random.randrange(SCREEN_HEIGHT - 50) 137 | 138 | # Add the block to the list of objects 139 | block_list.add(block) 140 | all_sprites_list.add(block) 141 | 142 | # Create a red player block 143 | player = Player() 144 | all_sprites_list.add(player) 145 | 146 | # Loop until the user clicks the close button. 147 | done = False 148 | 149 | # Used to manage how fast the screen updates 150 | clock = pygame.time.Clock() 151 | 152 | score = 0 153 | 154 | player.rect.x = SCREEN_WIDTH / 2 155 | player.rect.y = SCREEN_HEIGHT / 2 156 | 157 | # -------- Main Program Loop ----------- 158 | while not done: 159 | # --- Event Processing 160 | for event in pygame.event.get(): 161 | if event.type == pygame.QUIT: 162 | done = True 163 | 164 | elif event.type == pygame.MOUSEBUTTONDOWN: 165 | # Fire a bullet if the user clicks the mouse button 166 | 167 | # Get the mouse position 168 | pos = pygame.mouse.get_pos() 169 | 170 | mouse_x = pos[0] 171 | mouse_y = pos[1] 172 | 173 | # Create the bullet based on where we are, and where we want to go. 174 | bullet = Bullet(player.rect.x, player.rect.y, mouse_x, mouse_y) 175 | 176 | # Add the bullet to the lists 177 | all_sprites_list.add(bullet) 178 | bullet_list.add(bullet) 179 | 180 | # --- Game logic 181 | 182 | # Call the update() method on all the sprites 183 | all_sprites_list.update() 184 | 185 | # Calculate mechanics for each bullet 186 | for bullet in bullet_list: 187 | 188 | # See if it hit a block 189 | block_hit_list = pygame.sprite.spritecollide(bullet, block_list, True) 190 | 191 | # For each block hit, remove the bullet and add to the score 192 | for block in block_hit_list: 193 | bullet_list.remove(bullet) 194 | all_sprites_list.remove(bullet) 195 | score += 1 196 | print(score) 197 | 198 | # Remove the bullet if it flies up off the screen 199 | if bullet.rect.y < -10: 200 | bullet_list.remove(bullet) 201 | all_sprites_list.remove(bullet) 202 | 203 | # --- Draw a frame 204 | 205 | # Clear the screen 206 | screen.fill(WHITE) 207 | 208 | # Draw all the spites 209 | all_sprites_list.draw(screen) 210 | 211 | # Go ahead and update the screen with what we've drawn. 212 | pygame.display.flip() 213 | 214 | # --- Limit to 20 frames per second 215 | clock.tick(60) 216 | 217 | pygame.quit() 218 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/calculate_kinetic_energy.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # Calculate Kinetic Energy 7 | 8 | print("This program calculates the kinetic energy of a moving object.") 9 | m_string = input("Enter the object's mass in kilograms: ") 10 | m = float(m_string) 11 | v_string = input("Enter the object's speed in meters per second: ") 12 | v = float(v_string) 13 | 14 | e = 0.5 * m * v * v 15 | print("The object has " + str(e) + " joules of energy.") 16 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/calculate_miles_per_gallon.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # Explanation video: http://youtu.be/JK5ht5_m6Mk 7 | 8 | # Calculate Miles Per Gallon 9 | print("This program calculates mpg.") 10 | 11 | # Get miles driven from the user 12 | miles_driven = input("Enter miles driven:") 13 | # Convert text entered to a 14 | # floating point number 15 | miles_driven = float(miles_driven) 16 | 17 | # Get gallons used from the user 18 | gallons_used = input("Enter gallons used:") 19 | # Convert text entered to a 20 | # floating point number 21 | gallons_used = float(gallons_used) 22 | 23 | # Calculate and print the answer 24 | mpg = miles_driven / gallons_used 25 | print("Miles per gallon:", mpg) 26 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/character.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/character.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/click.wav: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/click.wav -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/draw_module_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample use of drawing commands. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | 10 | # Import a library of functions called 'pygame' 11 | import pygame 12 | 13 | # Initialize the game engine 14 | pygame.init() 15 | 16 | # Define the colors we will use in RGB format 17 | black = (0, 0, 0) 18 | white = (255, 255, 255) 19 | blue = (0, 0, 255) 20 | green = (0, 255, 0) 21 | red = (255, 0, 0) 22 | 23 | pi = 3.141592653 24 | 25 | # Set the height and width of the screen 26 | size = [400, 300] 27 | screen = pygame.display.set_mode(size) 28 | 29 | pygame.display.set_caption("Example code for the draw module") 30 | 31 | # Loop until the user clicks the close button. 32 | done = False 33 | clock = pygame.time.Clock() 34 | 35 | while not done: 36 | 37 | for event in pygame.event.get(): 38 | if event.type == pygame.QUIT: 39 | done = True 40 | 41 | # All drawing code happens after the for loop and but 42 | # inside the main while done==False loop. 43 | 44 | # Clear the screen and set the screen background 45 | screen.fill(white) 46 | 47 | # Draw on the screen a green line from (0,0) to (50.75) 48 | # 5 pixels wide. 49 | pygame.draw.line(screen, green, [0, 0], [50, 30], 5) 50 | 51 | # Draw on the screen a green line from (0,0) to (50.75) 52 | # 5 pixels wide. 53 | pygame.draw.lines(screen, black, False, [[0, 80], [50, 90], [200, 80], [220, 30]], 5) 54 | 55 | # Draw on the screen a green line from (0,0) to (50.75) 56 | # 5 pixels wide. 57 | pygame.draw.aaline(screen, green, [0, 50], [50, 80], True) 58 | 59 | # Draw a rectangle outline 60 | pygame.draw.rect(screen, black, [75, 10, 50, 20], 2) 61 | 62 | # Draw a solid rectangle 63 | pygame.draw.rect(screen, black, [150, 10, 50, 20]) 64 | 65 | # Draw an ellipse outline, using a rectangle as the outside boundaries 66 | pygame.draw.ellipse(screen, red, [225, 10, 50, 20], 2) 67 | 68 | # Draw an solid ellipse, using a rectangle as the outside boundaries 69 | pygame.draw.ellipse(screen, red, [300, 10, 50, 20]) 70 | 71 | # This draws a triangle using the polygon command 72 | pygame.draw.polygon(screen, black, [[100, 100], [0, 200], [200, 200]], 5) 73 | 74 | # Draw an arc as part of an ellipse. 75 | # Use radians to determine what angle to draw. 76 | pygame.draw.arc(screen, black, [210, 75, 150, 125], 0, pi / 2, 2) 77 | pygame.draw.arc(screen, green, [210, 75, 150, 125], pi / 2, pi, 2) 78 | pygame.draw.arc(screen, blue, [210, 75, 150, 125], pi, 3 * pi / 2, 2) 79 | pygame.draw.arc(screen, red, [210, 75, 150, 125], 3 * pi / 2, 2 * pi, 2) 80 | 81 | # Draw a circle 82 | pygame.draw.circle(screen, blue, [60, 250], 40) 83 | 84 | # Go ahead and update the screen with what we've drawn. 85 | # This MUST happen after all the other drawing commands. 86 | pygame.display.flip() 87 | 88 | # This limits the while loop to a max of 10 times per second. 89 | # Leave this out and we will use all CPU we can. 90 | clock.tick(60) 91 | 92 | # Be IDLE friendly 93 | pygame.quit() 94 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/exception_handling.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | import sys 7 | 8 | # Divide by zero 9 | try: 10 | x = 5 / 0 11 | except: 12 | print("Error dividing by zero") 13 | print(sys.exc_info()[0]) 14 | 15 | # Invalid number conversion 16 | try: 17 | x = int("fred") 18 | except: 19 | print("Error converting fred to a number") 20 | print(sys.exc_info()[0]) 21 | 22 | numberEntered = False 23 | while not numberEntered: 24 | numberString = input("Enter an integer: ") 25 | try: 26 | n = int(numberString) 27 | numberEntered = True 28 | except: 29 | print("Error, invalid integer") 30 | 31 | # Error opening file 32 | try: 33 | f = open('myfile.txt') 34 | except: 35 | print("Error opening file") 36 | 37 | # Multiple errors 38 | try: 39 | f = open('myfile.txt') 40 | s = f.readline() 41 | i = int(s.strip()) 42 | x = 101/i 43 | except IOError: 44 | print("I/O error") 45 | except ValueError: 46 | print("Could not convert data to an integer.") 47 | except ZeroDivisionError: 48 | print("Division by zero error") 49 | except: 50 | print("Unexpected error:", sys.exc_info()[0]) 51 | 52 | 53 | # Generating exceptions 54 | def get_input(): 55 | user_input = input("Enter something: ") 56 | if len(user_input) == 0: 57 | raise IOError("User entered nothing") 58 | 59 | get_input() 60 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/for_loop_examples.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # Print 'Hi' 10 times 7 | for i in range(10): 8 | print("Hi") 9 | 10 | # Print 'Hello' 5 times and 'There' once 11 | for i in range(5): 12 | print("Hello") 13 | print("There") 14 | 15 | # Print 'Hello' 'There' 5 times 16 | for i in range(5): 17 | print("Hello") 18 | print("There") 19 | 20 | # Print the numbers 0 to 9 21 | for i in range(10): 22 | print(i) 23 | 24 | # Two ways to print the numbers 1 to 10 25 | for i in range(1, 11): 26 | print(i) 27 | 28 | for i in range(10): 29 | print(i + 1) 30 | 31 | # Two ways to print the even numbers 2 to 10 32 | for i in range(2, 12, 2): 33 | print(i) 34 | 35 | for i in range(5): 36 | print((i + 1) * 2) 37 | 38 | # Count down from 10 down to 1 (not zero) 39 | for i in range(10, 0, -1): 40 | print(i) 41 | 42 | # Print numbers out of a list 43 | for i in [2, 6, 4, 2, 4, 6, 7, 4]: 44 | print(i) 45 | 46 | # What does this print? Why? 47 | for i in range(3): 48 | print("a") 49 | for j in range(3): 50 | print("b") 51 | 52 | # What is the value of a? 53 | a = 0 54 | for i in range(10): 55 | a = a + 1 56 | print(a) 57 | 58 | # What is the value of a? 59 | a = 0 60 | for i in range(10): 61 | a = a + 1 62 | for j in range(10): 63 | a = a + 1 64 | print(a) 65 | 66 | # What is the value of a? 67 | a = 0 68 | for i in range(10): 69 | a = a + 1 70 | for j in range(10): 71 | a = a + 1 72 | print(a) 73 | 74 | # What is the value of sum? 75 | sum = 0 76 | for i in range(1, 101): 77 | sum = sum + i 78 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/fractal.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample fractal using recursion. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | 10 | import pygame 11 | 12 | # Define some colors 13 | black = (0, 0, 0) 14 | white = (255, 255, 255) 15 | green = (0, 255, 0) 16 | red = (255, 0, 0) 17 | 18 | 19 | def recursive_draw(x, y, width, height, count): 20 | # Draw the rectangle 21 | # pygame.draw.rect(screen,black,[x,y,width,height],1) 22 | pygame.draw.line(screen, 23 | black, 24 | [x + width*.25, height // 2 + y], 25 | [x + width*.75, height // 2 + y], 26 | 3) 27 | pygame.draw.line(screen, 28 | black, 29 | [x + width * .25, (height * .5) // 2 + y], 30 | [x + width * .25, (height * 1.5) // 2 + y], 31 | 3) 32 | pygame.draw.line(screen, 33 | black, 34 | [x + width * .75, (height * .5) // 2 + y], 35 | [x + width * .75, (height * 1.5) // 2 + y], 36 | 3) 37 | 38 | if count > 0: 39 | count -= 1 40 | # Top left 41 | recursive_draw(x, y, width // 2, height // 2, count) 42 | # Top right 43 | recursive_draw(x + width // 2, y, width // 2, height // 2, count) 44 | # Bottom left 45 | recursive_draw(x, y + width // 2, width // 2, height // 2, count) 46 | # Bottom right 47 | recursive_draw(x + width // 2, y + width // 2, width // 2, height // 2, count) 48 | 49 | 50 | pygame.init() 51 | 52 | # Set the height and width of the screen 53 | size = [700, 700] 54 | screen = pygame.display.set_mode(size) 55 | 56 | pygame.display.set_caption("My Game") 57 | 58 | # Loop until the user clicks the close button. 59 | done = False 60 | 61 | # Used to manage how fast the screen updates 62 | clock = pygame.time.Clock() 63 | 64 | # -------- Main Program Loop ----------- 65 | while not done: 66 | for event in pygame.event.get(): 67 | if event.type == pygame.QUIT: 68 | done = True 69 | 70 | # Set the screen background 71 | screen.fill(white) 72 | 73 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 74 | fractal_level = 3 75 | recursive_draw(0, 0, 700, 700, fractal_level) 76 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 77 | 78 | # Go ahead and update the screen with what we've drawn. 79 | pygame.display.flip() 80 | 81 | # Limit to 20 frames per second 82 | clock.tick(20) 83 | 84 | # Be IDLE friendly. If you forget this line, the program will 'hang' 85 | # on exit. 86 | pygame.quit() 87 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/functions_and_graphics.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | 7 | Explanation video: http://youtu.be/_XdrKSDmzqA 8 | 9 | """ 10 | 11 | # Import a library of functions called 'pygame' 12 | import pygame 13 | 14 | 15 | def draw_snowman(screen, x, y): 16 | """ --- Function for a snowman --- 17 | Define a function that will draw a snowman at a certain location. 18 | """ 19 | pygame.draw.ellipse(screen, WHITE, [35 + x, 0 + y, 25, 25]) 20 | pygame.draw.ellipse(screen, WHITE, [23 + x, 20 + y, 50, 50]) 21 | pygame.draw.ellipse(screen, WHITE, [0 + x, 65 + y, 100, 100]) 22 | 23 | # Initialize the game engine 24 | pygame.init() 25 | 26 | # Define the colors we will use in RGB format 27 | BLACK = [0, 0, 0] 28 | WHITE = [255, 255, 255] 29 | 30 | # Set the height and width of the screen 31 | size = [400, 500] 32 | screen = pygame.display.set_mode(size) 33 | 34 | # Loop until the user clicks the close button. 35 | done = False 36 | clock = pygame.time.Clock() 37 | 38 | while not done: 39 | 40 | for event in pygame.event.get(): 41 | if event.type == pygame.QUIT: 42 | done = True 43 | 44 | # Clear the screen and set the screen background 45 | screen.fill(BLACK) 46 | 47 | # Snowman in upper left 48 | draw_snowman(screen, 10, 10) 49 | 50 | # Snowman in upper right 51 | draw_snowman(screen, 300, 10) 52 | 53 | # Snowman in lower left 54 | draw_snowman(screen, 10, 300) 55 | 56 | # Go ahead and update the screen with what we've drawn. 57 | # This MUST happen after all the other drawing commands. 58 | pygame.display.flip() 59 | 60 | # This limits the while loop to a max of 60 times per second. 61 | # Leave this out and we will use all CPU we can. 62 | clock.tick(60) 63 | 64 | 65 | # Be IDLE friendly 66 | pygame.quit() 67 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/game_class_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show the proper way to organize a game using the a game class. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/O4Y5KrNgP_c 10 | """ 11 | 12 | import pygame 13 | import random 14 | 15 | # --- Global constants --- 16 | BLACK = (0, 0, 0) 17 | WHITE = (255, 255, 255) 18 | GREEN = (0, 255, 0) 19 | RED = (255, 0, 0) 20 | 21 | SCREEN_WIDTH = 700 22 | SCREEN_HEIGHT = 500 23 | 24 | # --- Classes --- 25 | 26 | 27 | class Block(pygame.sprite.Sprite): 28 | """ This class represents a simple block the player collects. """ 29 | 30 | def __init__(self): 31 | """ Constructor, create the image of the block. """ 32 | super().__init__() 33 | self.image = pygame.Surface([20, 20]) 34 | self.image.fill(BLACK) 35 | self.rect = self.image.get_rect() 36 | 37 | def reset_pos(self): 38 | """ Called when the block is 'collected' or falls off 39 | the screen. """ 40 | self.rect.y = random.randrange(-300, -20) 41 | self.rect.x = random.randrange(SCREEN_WIDTH) 42 | 43 | def update(self): 44 | """ Automatically called when we need to move the block. """ 45 | self.rect.y += 1 46 | 47 | if self.rect.y > SCREEN_HEIGHT + self.rect.height: 48 | self.reset_pos() 49 | 50 | 51 | class Player(pygame.sprite.Sprite): 52 | """ This class represents the player. """ 53 | def __init__(self): 54 | super().__init__() 55 | self.image = pygame.Surface([20, 20]) 56 | self.image.fill(RED) 57 | self.rect = self.image.get_rect() 58 | 59 | def update(self): 60 | """ Update the player location. """ 61 | pos = pygame.mouse.get_pos() 62 | self.rect.x = pos[0] 63 | self.rect.y = pos[1] 64 | 65 | 66 | class Game(object): 67 | """ This class represents an instance of the game. If we need to 68 | reset the game we'd just need to create a new instance of this 69 | class. """ 70 | 71 | def __init__(self): 72 | """ Constructor. Create all our attributes and initialize 73 | the game. """ 74 | 75 | self.score = 0 76 | self.game_over = False 77 | 78 | # Create sprite lists 79 | self.block_list = pygame.sprite.Group() 80 | self.all_sprites_list = pygame.sprite.Group() 81 | 82 | # Create the block sprites 83 | for i in range(50): 84 | block = Block() 85 | 86 | block.rect.x = random.randrange(SCREEN_WIDTH) 87 | block.rect.y = random.randrange(-300, SCREEN_HEIGHT) 88 | 89 | self.block_list.add(block) 90 | self.all_sprites_list.add(block) 91 | 92 | # Create the player 93 | self.player = Player() 94 | self.all_sprites_list.add(self.player) 95 | 96 | def process_events(self): 97 | """ Process all of the events. Return a "True" if we need 98 | to close the window. """ 99 | 100 | for event in pygame.event.get(): 101 | if event.type == pygame.QUIT: 102 | return True 103 | if event.type == pygame.MOUSEBUTTONDOWN: 104 | if self.game_over: 105 | self.__init__() 106 | 107 | return False 108 | 109 | def run_logic(self): 110 | """ 111 | This method is run each time through the frame. It 112 | updates positions and checks for collisions. 113 | """ 114 | if not self.game_over: 115 | # Move all the sprites 116 | self.all_sprites_list.update() 117 | 118 | # See if the player block has collided with anything. 119 | blocks_hit_list = pygame.sprite.spritecollide(self.player, self.block_list, True) 120 | 121 | # Check the list of collisions. 122 | for block in blocks_hit_list: 123 | self.score += 1 124 | print(self.score) 125 | # You can do something with "block" here. 126 | 127 | if len(self.block_list) == 0: 128 | self.game_over = True 129 | 130 | def display_frame(self, screen): 131 | """ Display everything to the screen for the game. """ 132 | screen.fill(WHITE) 133 | 134 | if self.game_over: 135 | # font = pygame.font.Font("Serif", 25) 136 | font = pygame.font.SysFont("serif", 25) 137 | text = font.render("Game Over, click to restart", True, BLACK) 138 | center_x = (SCREEN_WIDTH // 2) - (text.get_width() // 2) 139 | center_y = (SCREEN_HEIGHT // 2) - (text.get_height() // 2) 140 | screen.blit(text, [center_x, center_y]) 141 | 142 | if not self.game_over: 143 | self.all_sprites_list.draw(screen) 144 | 145 | pygame.display.flip() 146 | 147 | 148 | def main(): 149 | """ Main program function. """ 150 | # Initialize Pygame and set up the window 151 | pygame.init() 152 | 153 | size = [SCREEN_WIDTH, SCREEN_HEIGHT] 154 | screen = pygame.display.set_mode(size) 155 | 156 | pygame.display.set_caption("My Game") 157 | pygame.mouse.set_visible(False) 158 | 159 | # Create our objects and set the data 160 | done = False 161 | clock = pygame.time.Clock() 162 | 163 | # Create an instance of the Game class 164 | game = Game() 165 | 166 | # Main game loop 167 | while not done: 168 | 169 | # Process events (keystrokes, mouse clicks, etc) 170 | done = game.process_events() 171 | 172 | # Update object positions, check for collisions 173 | game.run_logic() 174 | 175 | # Draw the current frame 176 | game.display_frame(screen) 177 | 178 | # Pause for the next frame 179 | clock.tick(60) 180 | 181 | # Close window and exit 182 | pygame.quit() 183 | 184 | # Call the main function, start up the game 185 | if __name__ == "__main__": 186 | main() 187 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/game_over.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample code shows "Game Over" message. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | 10 | import pygame 11 | 12 | # Define some colors 13 | BLACK = (0, 0, 0) 14 | WHITE = (255, 255, 255) 15 | GREEN = (0, 255, 0) 16 | 17 | pygame.init() 18 | 19 | # Set the height and width of the screen 20 | size = [700, 500] 21 | screen = pygame.display.set_mode(size) 22 | 23 | pygame.display.set_caption("Game Over Example") 24 | 25 | # Loop until the user clicks the close button. 26 | done = False 27 | 28 | # Used to manage how fast the screen updates 29 | clock = pygame.time.Clock() 30 | 31 | # Starting position of the rectangle 32 | rect_x = 50 33 | rect_y = 50 34 | 35 | # Speed and direction of rectangle 36 | rect_change_x = 5 37 | rect_change_y = 5 38 | 39 | # This is a font we use to draw text on the screen (size 36) 40 | font = pygame.font.Font(None, 36) 41 | 42 | # Use this boolean variable to trigger if the game is over. 43 | game_over = False 44 | 45 | # -------- Main Program Loop ----------- 46 | while not done: 47 | 48 | # --- Event Processing 49 | for event in pygame.event.get(): 50 | if event.type == pygame.QUIT: 51 | done = True 52 | 53 | # We will use a mouse-click to signify when the game is 54 | # over. Replace this, and set game_over to true in your 55 | # own game when you know the game is over. (Like lives==0) 56 | elif event.type == pygame.MOUSEBUTTONDOWN: 57 | game_over = True 58 | 59 | # --- Game Logic 60 | 61 | # Only move and process game logic if the game isn't over. 62 | if not game_over: 63 | # Move the rectangle starting point 64 | rect_x += rect_change_x 65 | rect_y += rect_change_y 66 | 67 | # Bounce the ball if needed 68 | if rect_y > 450 or rect_y < 0: 69 | rect_change_y = rect_change_y * -1 70 | if rect_x > 650 or rect_x < 0: 71 | rect_change_x = rect_change_x * -1 72 | 73 | # --- Draw the frame 74 | 75 | # Set the screen background 76 | screen.fill(BLACK) 77 | 78 | # Draw the rectangle 79 | pygame.draw.rect(screen, GREEN, [rect_x, rect_y, 50, 50]) 80 | 81 | if game_over: 82 | # If game over is true, draw game over 83 | text = font.render("Game Over", True, WHITE) 84 | text_rect = text.get_rect() 85 | text_x = screen.get_width() / 2 - text_rect.width / 2 86 | text_y = screen.get_height() / 2 - text_rect.height / 2 87 | screen.blit(text, [text_x, text_y]) 88 | 89 | else: 90 | # If game isn't over, draw this stuff. 91 | text = font.render("Click to end game", True, WHITE) 92 | text_rect = text.get_rect() 93 | text_x = screen.get_width() / 2 - text_rect.width / 2 94 | text_y = screen.get_height() / 2 - text_rect.height / 2 95 | screen.blit(text, [text_x, text_y]) 96 | 97 | # Limit frames per second 98 | clock.tick(60) 99 | 100 | # Go ahead and update the screen with what we've drawn. 101 | pygame.display.flip() 102 | 103 | # Be IDLE friendly. If you forget this line, the program will 'hang' 104 | # on exit. 105 | pygame.quit() 106 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/gfxtest.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # http://cprogramtutorials.blogspot.com/2011/09/bresenhams-ellipse-drawing-algorithm-c.html 7 | # http://www.gamedev.sk/files/programming/bresenham/ellipse.as 8 | import pygame 9 | import pygame.gfxdraw 10 | 11 | def drawEllipse(surface, x0, y0, a, b, color, width=1): 12 | if (a == 0 or b == 0): 13 | return; 14 | a = abs(a); 15 | b = abs(b); 16 | a2 = 2*a * a; 17 | b2 = 2*b * b; 18 | error = a*a*b; 19 | x = 0; 20 | y = b; 21 | stopy = 0; 22 | stopx = a2 * b ; 23 | while (stopy <= stopx): 24 | if width > 1: 25 | pygame.gfxdraw.filled_circle(surface,x0 + x, y0 + y,width,color); 26 | pygame.gfxdraw.filled_circle(surface,x0 - x, y0 + y,width,color); 27 | pygame.gfxdraw.filled_circle(surface,x0 - x, y0 - y,width,color); 28 | pygame.gfxdraw.filled_circle(surface,x0 + x, y0 - y,width,color); 29 | else: 30 | pygame.gfxdraw.pixel(surface,x0 + x, y0 + y,color); 31 | pygame.gfxdraw.pixel(surface,x0 - x, y0 + y,color); 32 | pygame.gfxdraw.pixel(surface,x0 - x, y0 - y,color); 33 | pygame.gfxdraw.pixel(surface,x0 + x, y0 - y,color); 34 | 35 | x += 1 36 | error -= b2 * (x - 1); 37 | stopy += b2; 38 | if (error <= 0): 39 | error += a2 * (y - 1); 40 | y -= 1 41 | stopx -= a2; 42 | 43 | error = b*b*a; 44 | x = a; 45 | y = 0; 46 | stopy = b2*a; 47 | stopx = 0; 48 | while (stopy >= stopx): 49 | if width > 1: 50 | pygame.gfxdraw.filled_circle(surface,x0 + x, y0 + y,width,color) 51 | pygame.gfxdraw.filled_circle(surface,x0 - x, y0 + y,width,color) 52 | pygame.gfxdraw.filled_circle(surface,x0 - x, y0 - y,width,color) 53 | pygame.gfxdraw.filled_circle(surface,x0 + x, y0 - y,width,color) 54 | else: 55 | pygame.gfxdraw.pixel(surface,x0 + x, y0 + y,color) 56 | pygame.gfxdraw.pixel(surface,x0 - x, y0 + y,color) 57 | pygame.gfxdraw.pixel(surface,x0 - x, y0 - y,color) 58 | pygame.gfxdraw.pixel(surface,x0 + x, y0 - y,color) 59 | 60 | y += 1; 61 | error -= a2 * (y - 1); 62 | stopx += a2; 63 | if (error < 0): 64 | error += b2 * (x - 1); 65 | x -= 1 66 | stopy -= b2; 67 | 68 | 69 | # Define some colors 70 | black = ( 0, 0, 0) 71 | white = ( 255, 255, 255) 72 | green = ( 0, 255, 0) 73 | red = ( 255, 0, 0) 74 | 75 | pygame.init() 76 | 77 | # Set the width and height of the screen [width,height] 78 | size=[700,500] 79 | screen=pygame.display.set_mode(size) 80 | 81 | pygame.display.set_caption("My Game") 82 | 83 | #Loop until the user clicks the close button. 84 | done=False 85 | 86 | # Used to manage how fast the screen updates 87 | clock=pygame.time.Clock() 88 | 89 | # -------- Main Program Loop ----------- 90 | while done==False: 91 | # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT 92 | for event in pygame.event.get(): # User did something 93 | if event.type == pygame.QUIT: # If user clicked close 94 | done=True # Flag that we are done so we exit this loop 95 | # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT 96 | 97 | 98 | # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT 99 | 100 | # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT 101 | 102 | 103 | 104 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 105 | 106 | # First, clear the screen to white. Don't put other drawing commands 107 | # above this, or they will be erased with this command. 108 | screen.fill(white) 109 | alpha=0 110 | for x in range(75,401,10): 111 | alpha +=2 112 | pygame.gfxdraw.filled_circle(screen,x,100,50,(255,0,0,alpha)) 113 | 114 | y=50 115 | alpha=0 116 | for x in range(75,401,5): 117 | y+=2 118 | alpha +=1 119 | pygame.gfxdraw.box(screen,(x,y,50,50),(0,0,255,alpha)) 120 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 121 | 122 | drawEllipse(screen,200,200,130,130,(0,64,64),20) 123 | #drawEllipse(screen,60,60,50,50,(0,64,64)) 124 | 125 | x_radius=5 126 | for x in range(100,700,50): 127 | 128 | #drawEllipse(screen,x,400,x_radius,30,(0,64,64)) 129 | x_radius += 2 130 | 131 | # Go ahead and update the screen with what we've drawn. 132 | pygame.display.flip() 133 | 134 | # Limit to 20 frames per second 135 | clock.tick(20) 136 | 137 | # Close the window and quit. 138 | # If you forget this line, the program will 'hang' 139 | # on exit if running from IDLE. 140 | pygame.quit () -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/grid_backed_map.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to use an array backed grid in a graphics game. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | import pygame 10 | 11 | # Define some colors 12 | BLACK = (0, 0, 0) 13 | WHITE = (255, 255, 255) 14 | GREEN = (0, 255, 0) 15 | RED = (255, 0, 0) 16 | 17 | WIDTH = 20 18 | HEIGHT = 20 19 | MARGIN = 5 20 | 21 | # --- Create grid of numbers 22 | # Create an empty list 23 | grid = [] 24 | # Loop for each row 25 | for row in range(10): 26 | # For each row, create a list that will 27 | # represent an entire row 28 | grid.append([]) 29 | # Loop for each column 30 | for column in range(10): 31 | # Add a number to the current row 32 | grid[row].append(0) 33 | 34 | # Set row 1, column 5 to zero 35 | grid[1][5] = 1 36 | 37 | pygame.init() 38 | 39 | screen_size = [255, 255] 40 | screen = pygame.display.set_mode(screen_size) 41 | 42 | pygame.display.set_caption("My Game") 43 | 44 | # Loop until the user clicks the close button. 45 | done = False 46 | 47 | # Used to manage how fast the screen updates 48 | clock = pygame.time.Clock() 49 | 50 | # -------- Main Program Loop ----------- 51 | while not done: 52 | 53 | for event in pygame.event.get(): 54 | if event.type == pygame.QUIT: 55 | done = True 56 | elif event.type == pygame.MOUSEBUTTONDOWN: 57 | pos = pygame.mouse.get_pos() 58 | column_clicked = pos[0] // (WIDTH + MARGIN) 59 | row_clicked = pos[1] // (HEIGHT + MARGIN) 60 | print("Row:", row_clicked, "Column:", column_clicked) 61 | grid[row_clicked][column_clicked] = 1 62 | 63 | # Set the screen background 64 | screen.fill(BLACK) 65 | 66 | for row in range(10): 67 | for column in range(10): 68 | if grid[row][column] == 0: 69 | color = WHITE 70 | else: 71 | color = GREEN 72 | pygame.draw.rect(screen, 73 | color, 74 | [MARGIN + (WIDTH + MARGIN) * column, 75 | MARGIN + (HEIGHT + MARGIN) * row, 76 | WIDTH, 77 | HEIGHT]) 78 | 79 | # Limit to 60 frames per second 80 | clock.tick(60) 81 | 82 | # Go ahead and update the screen with what we've drawn. 83 | pygame.display.flip() 84 | 85 | # Be IDLE friendly. If you forget this line, the program will 'hang' 86 | # on exit. 87 | pygame.quit() 88 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/high_score.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to use exceptions to save a high score for a game. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | 10 | 11 | def get_high_score(): 12 | # Default high score 13 | high_score = 0 14 | 15 | # Try to read the high score from a file 16 | try: 17 | high_score_file = open("high_score.txt", "r") 18 | high_score = int(high_score_file.read()) 19 | high_score_file.close() 20 | print("The high score is", high_score) 21 | except IOError: 22 | # Error reading file, no high score 23 | print("There is no high score yet.") 24 | except ValueError: 25 | # There's a file there, but we don't understand the number. 26 | print("I'm confused. Starting with no high score.") 27 | 28 | return high_score 29 | 30 | 31 | def save_high_score(new_high_score): 32 | try: 33 | # Write the file to disk 34 | high_score_file = open("high_score.txt", "w") 35 | high_score_file.write(str(new_high_score)) 36 | high_score_file.close() 37 | except IOError: 38 | # Hm, can't write it. 39 | print("Unable to save the high score.") 40 | 41 | 42 | def main(): 43 | """ Main program is here. """ 44 | # Get the high score 45 | high_score = get_high_score() 46 | 47 | # Get the score from the current game 48 | current_score = 0 49 | try: 50 | # Ask the user for his/her score 51 | current_score = int(input("What is your score? ")) 52 | except ValueError: 53 | # Error, can't turn what they typed into a number 54 | print("I don't understand what you typed.") 55 | 56 | # See if we have a new high score 57 | if current_score > high_score: 58 | # We do! Save to disk 59 | print("Yea! New high score!") 60 | save_high_score(current_score) 61 | else: 62 | print("Better luck next time.") 63 | 64 | # Call the main function, start up the game 65 | if __name__ == "__main__": 66 | main() 67 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/if_statement_examples.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # Explanation video: http://youtu.be/pDpNSck2aXQ 7 | 8 | # Variables used in the example if statements 9 | a = 4 10 | b = 5 11 | c = 6 12 | 13 | # Basic comparisons 14 | if a < b: 15 | print("a is less than b") 16 | 17 | if a > b: 18 | print("a is greater than than b") 19 | 20 | if a <= b: 21 | print("a is less than or equal to b") 22 | 23 | if a >= b: 24 | print("a is greater than or equal to b") 25 | 26 | # NOTE: It is very easy to mix when to use == and =. 27 | # Use == if you are asking if they are equal, use = 28 | # if you are assigning a value. 29 | if a == b: 30 | print("a is equal to b") 31 | 32 | # Not equal 33 | if a != b: 34 | print("a and b are not equal") 35 | 36 | # And 37 | if a < b and a < c: 38 | print("a is less than b and c") 39 | 40 | # Non-exclusive or 41 | if a < b or a < c: 42 | print("a is less than either a or b (or both)") 43 | 44 | 45 | # Boolean data type. This is legal! 46 | a = True 47 | if a: 48 | print("a is true") 49 | 50 | if not a: 51 | print("a is false") 52 | 53 | a = True 54 | b = False 55 | 56 | if a and b: 57 | print("a and b are both true") 58 | 59 | a = 3 60 | b = 3 61 | c = a == b 62 | print(c) 63 | 64 | # These are also legal and will trigger as being true because 65 | # the values are not zero: 66 | if 1: 67 | print("1") 68 | if "A": 69 | print("A") 70 | 71 | # This will not trigger as true because it is zero. 72 | if 0: 73 | print("Zero") 74 | 75 | # Comparing variables to multiple values. 76 | # The first if statement appears to work, but it will always 77 | # trigger as true even if the variable a is not equal to b. 78 | # This is because "b" by itself is considered true. 79 | a = "c" 80 | if a == "B" or "b": 81 | print("a is equal to b. Maybe.") 82 | 83 | # This is the proper way to do the if statement. 84 | if a == "B" or a == "b": 85 | print("a is equal to b.") 86 | 87 | # Example 1: If statement 88 | temperature = int(input("What is the temperature in Fahrenheit? ")) 89 | if temperature > 90: 90 | print("It is hot outside") 91 | print("Done") 92 | 93 | # Example 2: Else statement 94 | temperature = int(input("What is the temperature in Fahrenheit? ")) 95 | if temperature > 90: 96 | print("It is hot outside") 97 | else: 98 | print("It is not hot outside") 99 | print("Done") 100 | 101 | # Example 3: Else if statement 102 | temperature = int(input("What is the temperature in Fahrenheit? ")) 103 | if temperature > 90: 104 | print("It is hot outside") 105 | elif temperature < 30: 106 | print("It is cold outside") 107 | else: 108 | print("It is not hot outside") 109 | print("Done") 110 | 111 | # Example 4: Ordering of statements 112 | # Something with this is wrong. What? 113 | temperature = int(input("What is the temperature in Fahrenheit? ")) 114 | if temperature > 90: 115 | print("It is hot outside") 116 | elif temperature > 110: 117 | print("Oh man, you could fry eggs on the pavement!") 118 | elif temperature < 30: 119 | print("It is cold outside") 120 | else: 121 | print("It is ok outside") 122 | print("Done") 123 | 124 | # Comparisons using string/text 125 | # Note, this example does not work when running under Eclipse 126 | # because the input will contain an extra carriage return at the 127 | # end. It works fine under IDLE. 128 | userName = input("What is your name? ") 129 | if userName == "Paul": 130 | print("You have a nice name.") 131 | else: 132 | print("Your name is ok.") 133 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/instruction_screen.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example program to show how to do an instruction screen. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | 10 | import pygame 11 | 12 | # Define some colors 13 | BLACK = (0, 0, 0) 14 | WHITE = (255, 255, 255) 15 | GREEN = (0, 255, 0) 16 | RED = (255, 0, 0) 17 | 18 | pygame.init() 19 | 20 | # Set the height and width of the screen 21 | size = [700, 500] 22 | screen = pygame.display.set_mode(size) 23 | 24 | pygame.display.set_caption("Instruction Screen") 25 | 26 | # Loop until the user clicks the close button. 27 | done = False 28 | 29 | # Used to manage how fast the screen updates 30 | clock = pygame.time.Clock() 31 | 32 | # Starting position of the rectangle 33 | rect_x = 50 34 | rect_y = 50 35 | 36 | # Speed and direction of rectangle 37 | rect_change_x = 5 38 | rect_change_y = 5 39 | 40 | # This is a font we use to draw text on the screen (size 36) 41 | font = pygame.font.Font(None, 36) 42 | 43 | display_instructions = True 44 | instruction_page = 1 45 | 46 | # -------- Instruction Page Loop ----------- 47 | while not done and display_instructions: 48 | for event in pygame.event.get(): 49 | if event.type == pygame.QUIT: 50 | done = True 51 | if event.type == pygame.MOUSEBUTTONDOWN: 52 | instruction_page += 1 53 | if instruction_page == 3: 54 | display_instructions = False 55 | 56 | # Set the screen background 57 | screen.fill(BLACK) 58 | 59 | if instruction_page == 1: 60 | # Draw instructions, page 1 61 | # This could also load an image created in another program. 62 | # That could be both easier and more flexible. 63 | 64 | text = font.render("Instructions", True, WHITE) 65 | screen.blit(text, [10, 10]) 66 | 67 | text = font.render("Page 1", True, WHITE) 68 | screen.blit(text, [10, 40]) 69 | 70 | if instruction_page == 2: 71 | # Draw instructions, page 2 72 | text = font.render("This program bounces a rectangle", True, WHITE) 73 | screen.blit(text, [10, 10]) 74 | 75 | text = font.render("Page 2", True, WHITE) 76 | screen.blit(text, [10, 40]) 77 | 78 | # Limit to 60 frames per second 79 | clock.tick(60) 80 | 81 | # Go ahead and update the screen with what we've drawn. 82 | pygame.display.flip() 83 | 84 | # -------- Main Program Loop ----------- 85 | while not done: 86 | for event in pygame.event.get(): 87 | if event.type == pygame.QUIT: 88 | done = True 89 | 90 | # Set the screen background 91 | screen.fill(BLACK) 92 | 93 | # Draw the rectangle 94 | pygame.draw.rect(screen, WHITE, [rect_x, rect_y, 50, 50]) 95 | 96 | # Move the rectangle starting point 97 | rect_x += rect_change_x 98 | rect_y += rect_change_y 99 | 100 | # Bounce the ball if needed 101 | if rect_y > 450 or rect_y < 0: 102 | rect_change_y = rect_change_y * -1 103 | if rect_x > 650 or rect_x < 0: 104 | rect_change_x = rect_change_x * -1 105 | 106 | # Limit to 60 frames per second 107 | clock.tick(60) 108 | 109 | # Go ahead and update the screen with what we've drawn. 110 | pygame.display.flip() 111 | 112 | # Be IDLE friendly. If you forget this line, the program will 'hang' 113 | # on exit. 114 | pygame.quit() 115 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/joystick_calls.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | 7 | Show everything we can pull off the joystick 8 | """ 9 | import pygame 10 | 11 | # Define some colors 12 | BLACK = (0, 0, 0) 13 | WHITE = (255, 255, 255) 14 | 15 | 16 | class TextPrint(object): 17 | """ 18 | This is a simple class that will help us print to the screen 19 | It has nothing to do with the joysticks, just outputting the 20 | information. 21 | """ 22 | def __init__(self): 23 | """ Constructor """ 24 | self.reset() 25 | self.x_pos = 10 26 | self.y_pos = 10 27 | self.font = pygame.font.Font(None, 20) 28 | 29 | def print(self, my_screen, text_string): 30 | """ Draw text onto the screen. """ 31 | text_bitmap = self.font.render(text_string, True, BLACK) 32 | my_screen.blit(text_bitmap, [self.x_pos, self.y_pos]) 33 | self.y_pos += self.line_height 34 | 35 | def reset(self): 36 | """ Reset text to the top of the screen. """ 37 | self.x_pos = 10 38 | self.y_pos = 10 39 | self.line_height = 15 40 | 41 | def indent(self): 42 | """ Indent the next line of text """ 43 | self.x_pos += 10 44 | 45 | def unindent(self): 46 | """ Unindent the next line of text """ 47 | self.x_pos -= 10 48 | 49 | 50 | pygame.init() 51 | 52 | # Set the width and height of the screen [width,height] 53 | size = [500, 700] 54 | screen = pygame.display.set_mode(size) 55 | 56 | pygame.display.set_caption("My Game") 57 | 58 | # Loop until the user clicks the close button. 59 | done = False 60 | 61 | # Used to manage how fast the screen updates 62 | clock = pygame.time.Clock() 63 | 64 | # Initialize the joysticks 65 | pygame.joystick.init() 66 | 67 | # Get ready to print 68 | textPrint = TextPrint() 69 | 70 | # -------- Main Program Loop ----------- 71 | while not done: 72 | # EVENT PROCESSING STEP 73 | for event in pygame.event.get(): 74 | if event.type == pygame.QUIT: 75 | done = True 76 | 77 | # Possible joystick actions: JOYAXISMOTION JOYBALLMOTION JOYBUTTONDOWN 78 | # JOYBUTTONUP JOYHATMOTION 79 | if event.type == pygame.JOYBUTTONDOWN: 80 | print("Joystick button pressed.") 81 | if event.type == pygame.JOYBUTTONUP: 82 | print("Joystick button released.") 83 | 84 | # DRAWING STEP 85 | # First, clear the screen to white. Don't put other drawing commands 86 | # above this, or they will be erased with this command. 87 | screen.fill(WHITE) 88 | textPrint.reset() 89 | 90 | # Get count of joysticks 91 | joystick_count = pygame.joystick.get_count() 92 | 93 | textPrint.print(screen, "Number of joysticks: {}".format(joystick_count)) 94 | textPrint.indent() 95 | 96 | # For each joystick: 97 | for i in range(joystick_count): 98 | joystick = pygame.joystick.Joystick(i) 99 | joystick.init() 100 | 101 | textPrint.print(screen, "Joystick {}".format(i)) 102 | textPrint.indent() 103 | 104 | # Get the name from the OS for the controller/joystick 105 | name = joystick.get_name() 106 | textPrint.print(screen, "Joystick name: {}".format(name)) 107 | 108 | # Usually axis run in pairs, up/down for one, and left/right for 109 | # the other. 110 | axes = joystick.get_numaxes() 111 | textPrint.print(screen, "Number of axes: {}".format(axes)) 112 | textPrint.indent() 113 | 114 | for i in range(axes): 115 | axis = joystick.get_axis(i) 116 | textPrint.print(screen, "Axis {} value: {:>6.3f}".format(i, axis)) 117 | textPrint.unindent() 118 | 119 | buttons = joystick.get_numbuttons() 120 | textPrint.print(screen, "Number of buttons: {}".format(buttons)) 121 | textPrint.indent() 122 | 123 | for i in range(buttons): 124 | button = joystick.get_button(i) 125 | textPrint.print(screen, "Button {:>2} value: {}".format(i, button)) 126 | textPrint.unindent() 127 | 128 | # Hat switch. All or nothing for direction, not like joysticks. 129 | # Value comes back in an array. 130 | hats = joystick.get_numhats() 131 | textPrint.print(screen, "Number of hats: {}".format(hats)) 132 | textPrint.indent() 133 | 134 | for i in range(hats): 135 | hat = joystick.get_hat(i) 136 | textPrint.print(screen, "Hat {} value: {}".format(i, str(hat))) 137 | textPrint.unindent() 138 | 139 | textPrint.unindent() 140 | 141 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 142 | 143 | # Go ahead and update the screen with what we've drawn. 144 | pygame.display.flip() 145 | 146 | # Limit to 60 frames per second 147 | clock.tick(60) 148 | 149 | # Close the window and quit. 150 | # If you forget this line, the program will 'hang' 151 | # on exit if running from IDLE. 152 | pygame.quit() 153 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/laser5.ogg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/laser5.ogg -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_game_controller.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | """ 7 | 8 | import pygame 9 | 10 | # Define some colors 11 | BLACK = (0, 0, 0) 12 | WHITE = (255, 255, 255) 13 | GREEN = (0, 255, 0) 14 | RED = (255, 0, 0) 15 | 16 | 17 | def draw_stick_figure(screen, x, y): 18 | """ Draw a stickfigure at x, y """ 19 | # Head 20 | pygame.draw.ellipse(screen, BLACK, [1 + x, y, 10, 10], 0) 21 | 22 | # Legs 23 | pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2) 24 | pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [x, 27 + y], 2) 25 | 26 | # Body 27 | pygame.draw.line(screen, RED, [5 + x, 17 + y], [5 + x, 7 + y], 2) 28 | 29 | # Arms 30 | pygame.draw.line(screen, RED, [5 + x, 7 + y], [9 + x, 17 + y], 2) 31 | pygame.draw.line(screen, RED, [5 + x, 7 + y], [1 + x, 17 + y], 2) 32 | 33 | pygame.init() 34 | 35 | # Set the width and height of the screen [width, height] 36 | size = [700, 500] 37 | screen = pygame.display.set_mode(size) 38 | 39 | pygame.display.set_caption("My Game") 40 | 41 | # Loop until the user clicks the close button. 42 | done = False 43 | 44 | # Used to manage how fast the screen updates 45 | clock = pygame.time.Clock() 46 | 47 | # Current position 48 | x_coord = 10 49 | y_coord = 10 50 | 51 | # Count the joysticks the computer has 52 | joystick_count = pygame.joystick.get_count() 53 | if joystick_count == 0: 54 | # No joysticks! 55 | print("Error, I didn't find any joysticks.") 56 | else: 57 | # Use joystick #0 and initialize it 58 | my_joystick = pygame.joystick.Joystick(0) 59 | my_joystick.init() 60 | 61 | while not done: 62 | 63 | # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT 64 | for event in pygame.event.get(): 65 | if event.type == pygame.QUIT: 66 | done = True 67 | # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT 68 | 69 | # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT 70 | 71 | # As long as there is a joystick 72 | if joystick_count != 0: 73 | 74 | # This gets the position of the axis on the game controller 75 | # It returns a number between -1.0 and +1.0 76 | horiz_axis_pos = my_joystick.get_axis(0) 77 | vert_axis_pos = my_joystick.get_axis(1) 78 | 79 | # Move x according to the axis. We multiply by 10 80 | # to speed up the movement. 81 | x_coord = x_coord + int(horiz_axis_pos * 10) 82 | y_coord = y_coord + int(vert_axis_pos * 10) 83 | 84 | # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT 85 | 86 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 87 | 88 | # First, clear the screen to WHITE. Don't put other drawing commands 89 | # above this, or they will be erased with this command. 90 | screen.fill(WHITE) 91 | 92 | # Draw the item at the proper coordinates 93 | draw_stick_figure(screen, x_coord, y_coord) 94 | 95 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 96 | 97 | pygame.display.flip() 98 | clock.tick(60) 99 | 100 | pygame.quit() 101 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_keyboard.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | """ 7 | 8 | import pygame 9 | 10 | # Define some colors 11 | BLACK = (0, 0, 0) 12 | WHITE = (255, 255, 255) 13 | GREEN = (0, 255, 0) 14 | RED = (255, 0, 0) 15 | 16 | 17 | def draw_stick_figure(screen, x, y): 18 | # Head 19 | pygame.draw.ellipse(screen, BLACK, [1 + x, y, 10, 10], 0) 20 | 21 | # Legs 22 | pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2) 23 | pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [x, 27 + y], 2) 24 | 25 | # Body 26 | pygame.draw.line(screen, RED, [5 + x, 17 + y], [5 + x, 7 + y], 2) 27 | 28 | # Arms 29 | pygame.draw.line(screen, RED, [5 + x, 7 + y], [9 + x, 17 + y], 2) 30 | pygame.draw.line(screen, RED, [5 + x, 7 + y], [1 + x, 17 + y], 2) 31 | 32 | # Setup 33 | pygame.init() 34 | 35 | # Set the width and height of the screen [width,height] 36 | size = [700, 500] 37 | screen = pygame.display.set_mode(size) 38 | 39 | pygame.display.set_caption("My Game") 40 | 41 | # Loop until the user clicks the close button. 42 | done = False 43 | 44 | # Used to manage how fast the screen updates 45 | clock = pygame.time.Clock() 46 | 47 | # Hide the mouse cursor 48 | pygame.mouse.set_visible(0) 49 | 50 | # Speed in pixels per frame 51 | x_speed = 0 52 | y_speed = 0 53 | 54 | # Current position 55 | x_coord = 10 56 | y_coord = 10 57 | 58 | # -------- Main Program Loop ----------- 59 | while not done: 60 | # --- Event Processing 61 | for event in pygame.event.get(): 62 | if event.type == pygame.QUIT: 63 | done = True 64 | # User pressed down on a key 65 | 66 | elif event.type == pygame.KEYDOWN: 67 | # Figure out if it was an arrow key. If so 68 | # adjust speed. 69 | if event.key == pygame.K_LEFT: 70 | x_speed = -3 71 | elif event.key == pygame.K_RIGHT: 72 | x_speed = 3 73 | elif event.key == pygame.K_UP: 74 | y_speed = -3 75 | elif event.key == pygame.K_DOWN: 76 | y_speed = 3 77 | 78 | # User let up on a key 79 | elif event.type == pygame.KEYUP: 80 | # If it is an arrow key, reset vector back to zero 81 | if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: 82 | x_speed = 0 83 | elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: 84 | y_speed = 0 85 | 86 | # --- Game Logic 87 | 88 | # Move the object according to the speed vector. 89 | x_coord = x_coord + x_speed 90 | y_coord = y_coord + y_speed 91 | 92 | # --- Drawing Code 93 | 94 | # First, clear the screen to WHITE. Don't put other drawing commands 95 | # above this, or they will be erased with this command. 96 | screen.fill(WHITE) 97 | 98 | draw_stick_figure(screen, x_coord, y_coord) 99 | 100 | 101 | # Go ahead and update the screen with what we've drawn. 102 | pygame.display.flip() 103 | 104 | # Limit frames per second 105 | clock.tick(60) 106 | 107 | # Close the window and quit. 108 | pygame.quit() 109 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_mouse.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | """ 7 | 8 | import pygame 9 | 10 | # Define some colors 11 | BLACK = (0, 0, 0) 12 | WHITE = (255, 255, 255) 13 | GREEN = (0, 255, 0) 14 | RED = (255, 0, 0) 15 | 16 | 17 | def draw_stick_figure(screen, x, y): 18 | # Head 19 | pygame.draw.ellipse(screen, BLACK, [1 + x, y, 10, 10], 0) 20 | 21 | # Legs 22 | pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [10 + x, 27 + y], 2) 23 | pygame.draw.line(screen, BLACK, [5 + x, 17 + y], [x, 27 + y], 2) 24 | 25 | # Body 26 | pygame.draw.line(screen, RED, [5 + x, 17 + y], [5 + x, 7 + y], 2) 27 | 28 | # Arms 29 | pygame.draw.line(screen, RED, [5 + x, 7 + y], [9 + x, 17 + y], 2) 30 | pygame.draw.line(screen, RED, [5 + x, 7 + y], [1 + x, 17 + y], 2) 31 | 32 | # Setup 33 | pygame.init() 34 | 35 | # Set the width and height of the screen [width,height] 36 | size = [700, 500] 37 | screen = pygame.display.set_mode(size) 38 | 39 | pygame.display.set_caption("My Game") 40 | 41 | # Loop until the user clicks the close button. 42 | done = False 43 | 44 | # Used to manage how fast the screen updates 45 | clock = pygame.time.Clock() 46 | 47 | # Hide the mouse cursor 48 | pygame.mouse.set_visible(0) 49 | 50 | # -------- Main Program Loop ----------- 51 | while not done: 52 | # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT 53 | for event in pygame.event.get(): 54 | if event.type == pygame.QUIT: 55 | done = True 56 | # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT 57 | 58 | # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT 59 | 60 | # Call draw stick figure function 61 | pos = pygame.mouse.get_pos() 62 | x = pos[0] 63 | y = pos[1] 64 | 65 | # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT 66 | 67 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 68 | 69 | # First, clear the screen to white. Don't put other drawing commands 70 | # above this, or they will be erased with this command. 71 | screen.fill(WHITE) 72 | draw_stick_figure(screen, x, y) 73 | 74 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 75 | 76 | # Go ahead and update the screen with what we've drawn. 77 | pygame.display.flip() 78 | 79 | # Limit to 20 frames per second 80 | clock.tick(60) 81 | 82 | # Close the window and quit. 83 | # If you forget this line, the program will 'hang' 84 | # on exit if running from IDLE. 85 | pygame.quit() 86 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_sprite_game_controller.py: -------------------------------------------------------------------------------- 1 | """ 2 | Example program to show move a sprite with a game controller. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | """ 9 | 10 | import pygame 11 | 12 | # Define some colors 13 | BLACK = (0, 0, 0) 14 | WHITE = (255, 255, 255) 15 | 16 | 17 | class Player(pygame.sprite.Sprite): 18 | """ 19 | This class represents the player. 20 | It derives from the "Sprite" class in Pygame. 21 | """ 22 | 23 | def __init__(self): 24 | """ 25 | Constructor. Pass in the color of the block, and its x and y position. 26 | """ 27 | 28 | # Call the parent class (Sprite) constructor 29 | super().__init__() 30 | 31 | # Variables to hold the height and width of the block 32 | width = 20 33 | height = 15 34 | 35 | # Create an image of the ball, and fill it with a color. 36 | # This could also be an image loaded from the disk. 37 | self.image = pygame.Surface([width, height]) 38 | self.image.fill(BLACK) 39 | 40 | # Fetch the rectangle object that has the dimensions of the image 41 | self.rect = self.image.get_rect() 42 | 43 | # Set initial position of sprite to 100,100 44 | self.rect.x = 100 45 | self.rect.y = 100 46 | 47 | # Count the joysticks the computer has 48 | self.joystick_count = pygame.joystick.get_count() 49 | if self.joystick_count == 0: 50 | # No joysticks! 51 | print("Error, I didn't find any joysticks.") 52 | else: 53 | # Use joystick #0 and initialize it 54 | self.my_joystick = pygame.joystick.Joystick(0) 55 | self.my_joystick.init() 56 | 57 | def update(self): 58 | """ Update the position of the ball """ 59 | 60 | # As long as there is a joystick 61 | if self.joystick_count != 0: 62 | 63 | # This gets the position of the axis on the game controller 64 | # It returns a number between -1.0 and +1.0 65 | horiz_axis_pos = self.my_joystick.get_axis(0) 66 | vert_axis_pos = self.my_joystick.get_axis(1) 67 | 68 | # Move x according to the axis. We multiply by 10 to speed up the 69 | # movement. 70 | self.rect.x = self.rect.x+horiz_axis_pos*10 71 | self.rect.y = self.rect.y+vert_axis_pos*10 72 | 73 | 74 | pygame.init() 75 | 76 | # Set the height and width of the screen 77 | WINDOW_SIZE = [700, 500] 78 | screen = pygame.display.set_mode(WINDOW_SIZE) 79 | 80 | # Loop until the user clicks the close button. 81 | done = False 82 | 83 | # Used to manage how fast the screen updates 84 | clock = pygame.time.Clock() 85 | 86 | # This is a list of 'sprites.' Each ball in the program (there is only 1) is 87 | # added to this list. The list is managed by a class called 'Group.' 88 | all_sprites_list = pygame.sprite.Group() 89 | 90 | # This represents the ball controlled by the player 91 | player = Player() 92 | 93 | # Add the ball to the list of player-controlled objects 94 | all_sprites_list.add(player) 95 | 96 | # -------- Main Program Loop ----------- 97 | while not done: 98 | for event in pygame.event.get(): 99 | if event.type == pygame.QUIT: 100 | done = True 101 | 102 | # Clear the screen 103 | screen.fill(WHITE) 104 | 105 | # Update the position of the ball (using the mouse) and draw the ball 106 | all_sprites_list.update() 107 | all_sprites_list.draw(screen) 108 | 109 | # Limit to 60 frames per second 110 | clock.tick(60) 111 | 112 | # Go ahead and update the screen with what we've drawn. 113 | pygame.display.flip() 114 | 115 | # Be IDLE friendly 116 | pygame.quit() 117 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_sprite_keyboard_jump.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | """ 7 | 8 | import pygame 9 | 10 | BLACK = (0, 0, 0) 11 | WHITE = (255, 255, 255) 12 | 13 | 14 | class Player(pygame.sprite.Sprite): 15 | """ The class is the player-controlled sprite. """ 16 | 17 | def __init__(self, x, y): 18 | """Constructor function""" 19 | # Call the parent's constructor 20 | super().__init__() 21 | 22 | # Set height, width 23 | self.image = pygame.Surface([15, 15]) 24 | self.image.fill(BLACK) 25 | 26 | # Make our top-left corner the passed-in location. 27 | self.rect = self.image.get_rect() 28 | self.rect.x = x 29 | self.rect.y = y 30 | 31 | # Call this function so the Pygame library can initialize itself 32 | pygame.init() 33 | 34 | # Create an 800x600 sized screen 35 | screen = pygame.display.set_mode([800, 600]) 36 | 37 | # Set the title of the window 38 | pygame.display.set_caption('Move Sprite With Keyboard') 39 | 40 | # Create the player paddle object 41 | player = Player(50, 50) 42 | all_sprites_list = pygame.sprite.Group() 43 | all_sprites_list.add(player) 44 | 45 | clock = pygame.time.Clock() 46 | done = False 47 | 48 | while not done: 49 | 50 | for event in pygame.event.get(): 51 | if event.type == pygame.QUIT: 52 | done = True 53 | 54 | elif event.type == pygame.KEYDOWN: 55 | if event.key == pygame.K_LEFT: 56 | player.rect.x -= player.rect.width 57 | elif event.key == pygame.K_RIGHT: 58 | player.rect.x += player.rect.width 59 | elif event.key == pygame.K_UP: 60 | player.rect.y -= player.rect.height 61 | elif event.key == pygame.K_DOWN: 62 | player.rect.y += player.rect.height 63 | 64 | # -- Draw everything 65 | # Clear screen 66 | screen.fill(WHITE) 67 | 68 | # Draw sprites 69 | all_sprites_list.draw(screen) 70 | 71 | # Flip screen 72 | pygame.display.flip() 73 | 74 | # Pause 75 | clock.tick(40) 76 | 77 | pygame.quit() 78 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_sprite_keyboard_smooth.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | """ 7 | 8 | import pygame 9 | 10 | BLACK = (0, 0, 0) 11 | WHITE = (255, 255, 255) 12 | 13 | 14 | class Player(pygame.sprite.Sprite): 15 | """ The class is the player-controlled sprite. """ 16 | 17 | # -- Methods 18 | def __init__(self, x, y): 19 | """Constructor function""" 20 | # Call the parent's constructor 21 | super().__init__() 22 | 23 | # Set height, width 24 | self.image = pygame.Surface([15, 15]) 25 | self.image.fill(BLACK) 26 | 27 | # Make our top-left corner the passed-in location. 28 | self.rect = self.image.get_rect() 29 | self.rect.x = x 30 | self.rect.y = y 31 | 32 | # -- Attributes 33 | # Set speed vector 34 | self.change_x = 0 35 | self.change_y = 0 36 | 37 | def changespeed(self, x, y): 38 | """ Change the speed of the player""" 39 | self.change_x += x 40 | self.change_y += y 41 | 42 | def update(self): 43 | """ Find a new position for the player""" 44 | self.rect.x += self.change_x 45 | self.rect.y += self.change_y 46 | 47 | 48 | # Call this function so the Pygame library can initialize itself 49 | pygame.init() 50 | 51 | # Create an 800x600 sized screen 52 | screen = pygame.display.set_mode([800, 600]) 53 | 54 | # Set the title of the window 55 | pygame.display.set_caption('Test') 56 | 57 | # Create the player object 58 | player = Player(50, 50) 59 | all_sprites_list = pygame.sprite.Group() 60 | all_sprites_list.add(player) 61 | 62 | clock = pygame.time.Clock() 63 | done = False 64 | 65 | while not done: 66 | 67 | for event in pygame.event.get(): 68 | if event.type == pygame.QUIT: 69 | done = True 70 | 71 | # Set the speed based on the key pressed 72 | elif event.type == pygame.KEYDOWN: 73 | if event.key == pygame.K_LEFT: 74 | player.changespeed(-3, 0) 75 | elif event.key == pygame.K_RIGHT: 76 | player.changespeed(3, 0) 77 | elif event.key == pygame.K_UP: 78 | player.changespeed(0, -3) 79 | elif event.key == pygame.K_DOWN: 80 | player.changespeed(0, 3) 81 | 82 | # Reset speed when key goes up 83 | elif event.type == pygame.KEYUP: 84 | if event.key == pygame.K_LEFT: 85 | player.changespeed(3, 0) 86 | elif event.key == pygame.K_RIGHT: 87 | player.changespeed(-3, 0) 88 | elif event.key == pygame.K_UP: 89 | player.changespeed(0, 3) 90 | elif event.key == pygame.K_DOWN: 91 | player.changespeed(0, -3) 92 | 93 | # --- Game logic 94 | 95 | # This calls update on all the sprites 96 | all_sprites_list.update() 97 | 98 | # -- Draw everything 99 | # Clear screen 100 | screen.fill(WHITE) 101 | 102 | # Draw sprites 103 | all_sprites_list.draw(screen) 104 | 105 | # Flip screen 106 | pygame.display.flip() 107 | 108 | # Pause 109 | clock.tick(60) 110 | 111 | pygame.quit() 112 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_sprite_mouse.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | import pygame 7 | 8 | # Define some colors 9 | BLACK = (0, 0, 0) 10 | WHITE = (255, 255, 255) 11 | GREEN = (0, 255, 0) 12 | RED = (255, 0, 0) 13 | BLUE = (50, 50, 255) 14 | DKGREEN = (0, 100, 0) 15 | 16 | 17 | # This class represents the player 18 | # It derives from the "Sprite" class in Pygame 19 | class Player(pygame.sprite.Sprite): 20 | # Constructor. Pass in the color of the block, and its x and y position 21 | def __init__(self): 22 | # Call the parent class (Sprite) constructor 23 | super().__init__() 24 | 25 | # Variables to hold the height and width of the block 26 | width = 20 27 | height = 15 28 | 29 | # Create an image of the player, and fill it with a color. 30 | # This could also be an image loaded from the disk. 31 | self.image = pygame.Surface([width, height]) 32 | self.image.fill(BLACK) 33 | 34 | # Fetch the rectangle object that has the dimensions of the image 35 | self.rect = self.image.get_rect() 36 | 37 | # Update the position of the player 38 | def update(self): 39 | # Get the current mouse position. This returns the position 40 | # as a list of two numbers. 41 | pos = pygame.mouse.get_pos() 42 | 43 | # Fetch the x and y out of the list, just like we'd fetch letters out 44 | # of a string. 45 | # NOTE: If you want to keep the mouse at the bottom of the screen, just 46 | # set y = 380, and not update it with the mouse position stored in 47 | # pos[1] 48 | x = pos[0] 49 | y = pos[1] 50 | 51 | # Set the attribute for the top left corner where this object is 52 | # located 53 | self.rect.x = x 54 | self.rect.y = y 55 | 56 | pygame.init() 57 | 58 | # Set the height and width of the screen 59 | size = [700, 500] 60 | screen = pygame.display.set_mode(size) 61 | 62 | # Don't display the mouse pointer 63 | pygame.mouse.set_visible(False) 64 | 65 | # Loop until the user clicks the close button. 66 | done = False 67 | 68 | # Used to manage how fast the screen updates 69 | clock = pygame.time.Clock() 70 | 71 | # This is a list of 'sprites.' Each sprite in the program (there is only 1) is 72 | # added to this list. The list is managed by a class called 'Group.' 73 | all_sprites_list = pygame.sprite.Group() 74 | 75 | # This represents the ball controlled by the player 76 | player = Player() 77 | 78 | # Add the ball to the list of player-controlled objects 79 | all_sprites_list.add(player) 80 | 81 | # -------- Main Program Loop ----------- 82 | while not done: 83 | for event in pygame.event.get(): 84 | if event.type == pygame.QUIT: 85 | done = True 86 | 87 | # --- Game logic 88 | all_sprites_list.update() 89 | 90 | # --- Display / Drawing code 91 | 92 | # Clear the screen 93 | screen.fill(WHITE) 94 | 95 | # Update the position of the ball (using the mouse) and draw the ball 96 | all_sprites_list.draw(screen) 97 | 98 | # Limit to 60 frames per second 99 | clock.tick(60) 100 | 101 | # Go ahead and update the screen with what we've drawn. 102 | pygame.display.flip() 103 | 104 | pygame.quit() 105 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/move_with_walls_example.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | 7 | From: 8 | http://programarcadegames.com/python_examples/f.php?file=move_with_walls_example 9 | 10 | Explanation video: http://youtu.be/8IRyt7ft7zg 11 | 12 | Part of a series: 13 | http://programarcadegames.com/python_examples/f.php?file=move_with_walls_example.py 14 | http://programarcadegames.com/python_examples/f.php?file=maze_runner.py 15 | http://programarcadegames.com/python_examples/f.php?file=platform_jumper.py 16 | http://programarcadegames.com/python_examples/f.php?file=platform_scroller.py 17 | http://programarcadegames.com/python_examples/f.php?file=platform_moving.py 18 | http://programarcadegames.com/python_examples/sprite_sheets/ 19 | """ 20 | 21 | import pygame 22 | 23 | # -- Global constants 24 | 25 | # Colors 26 | BLACK = (0, 0, 0) 27 | WHITE = (255, 255, 255) 28 | BLUE = (50, 50, 255) 29 | 30 | # Screen dimensions 31 | SCREEN_WIDTH = 800 32 | SCREEN_HEIGHT = 600 33 | 34 | 35 | class Player(pygame.sprite.Sprite): 36 | """ This class represents the bar at the bottom that the player 37 | controls. """ 38 | 39 | # Constructor function 40 | def __init__(self, x, y): 41 | # Call the parent's constructor 42 | super().__init__() 43 | 44 | # Set height, width 45 | self.image = pygame.Surface([15, 15]) 46 | self.image.fill(WHITE) 47 | 48 | # Make our top-left corner the passed-in location. 49 | self.rect = self.image.get_rect() 50 | self.rect.y = y 51 | self.rect.x = x 52 | 53 | # Set speed vector 54 | self.change_x = 0 55 | self.change_y = 0 56 | self.walls = None 57 | 58 | def changespeed(self, x, y): 59 | """ Change the speed of the player. """ 60 | self.change_x += x 61 | self.change_y += y 62 | 63 | def update(self): 64 | """ Update the player position. """ 65 | # Move left/right 66 | self.rect.x += self.change_x 67 | 68 | # Did this update cause us to hit a wall? 69 | block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) 70 | for block in block_hit_list: 71 | # If we are moving right, set our right side to the left side of 72 | # the item we hit 73 | if self.change_x > 0: 74 | self.rect.right = block.rect.left 75 | else: 76 | # Otherwise if we are moving left, do the opposite. 77 | self.rect.left = block.rect.right 78 | 79 | # Move up/down 80 | self.rect.y += self.change_y 81 | 82 | # Check and see if we hit anything 83 | block_hit_list = pygame.sprite.spritecollide(self, self.walls, False) 84 | for block in block_hit_list: 85 | 86 | # Reset our position based on the top/bottom of the object. 87 | if self.change_y > 0: 88 | self.rect.bottom = block.rect.top 89 | else: 90 | self.rect.top = block.rect.bottom 91 | 92 | 93 | class Wall(pygame.sprite.Sprite): 94 | """ Wall the player can run into. """ 95 | def __init__(self, x, y, width, height): 96 | """ Constructor for the wall that the player can run into. """ 97 | # Call the parent's constructor 98 | super().__init__() 99 | 100 | # Make a blue wall, of the size specified in the parameters 101 | self.image = pygame.Surface([width, height]) 102 | self.image.fill(BLUE) 103 | 104 | # Make our top-left corner the passed-in location. 105 | self.rect = self.image.get_rect() 106 | self.rect.y = y 107 | self.rect.x = x 108 | 109 | 110 | # Call this function so the Pygame library can initialize itself 111 | pygame.init() 112 | 113 | # Create an 800x600 sized screen 114 | screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) 115 | 116 | # Set the title of the window 117 | pygame.display.set_caption('Test') 118 | 119 | # List to hold all the sprites 120 | all_sprite_list = pygame.sprite.Group() 121 | 122 | # Make the walls. (x_pos, y_pos, width, height) 123 | wall_list = pygame.sprite.Group() 124 | 125 | wall = Wall(0, 0, 10, 600) 126 | wall_list.add(wall) 127 | all_sprite_list.add(wall) 128 | 129 | wall = Wall(10, 0, 790, 10) 130 | wall_list.add(wall) 131 | all_sprite_list.add(wall) 132 | 133 | wall = Wall(10, 200, 100, 10) 134 | wall_list.add(wall) 135 | all_sprite_list.add(wall) 136 | 137 | # Create the player paddle object 138 | player = Player(50, 50) 139 | player.walls = wall_list 140 | 141 | all_sprite_list.add(player) 142 | 143 | clock = pygame.time.Clock() 144 | 145 | done = False 146 | 147 | while not done: 148 | 149 | for event in pygame.event.get(): 150 | if event.type == pygame.QUIT: 151 | done = True 152 | 153 | elif event.type == pygame.KEYDOWN: 154 | if event.key == pygame.K_LEFT: 155 | player.changespeed(-3, 0) 156 | elif event.key == pygame.K_RIGHT: 157 | player.changespeed(3, 0) 158 | elif event.key == pygame.K_UP: 159 | player.changespeed(0, -3) 160 | elif event.key == pygame.K_DOWN: 161 | player.changespeed(0, 3) 162 | 163 | elif event.type == pygame.KEYUP: 164 | if event.key == pygame.K_LEFT: 165 | player.changespeed(3, 0) 166 | elif event.key == pygame.K_RIGHT: 167 | player.changespeed(-3, 0) 168 | elif event.key == pygame.K_UP: 169 | player.changespeed(0, 3) 170 | elif event.key == pygame.K_DOWN: 171 | player.changespeed(0, -3) 172 | 173 | all_sprite_list.update() 174 | 175 | screen.fill(BLACK) 176 | 177 | all_sprite_list.draw(screen) 178 | 179 | pygame.display.flip() 180 | 181 | clock.tick(60) 182 | 183 | pygame.quit() 184 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/moving_sprites.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | 7 | Explanation video: http://youtu.be/qbEEcQXw8aw 8 | """ 9 | 10 | import pygame 11 | import random 12 | 13 | # Define some colors 14 | BLACK = (0, 0, 0) 15 | WHITE = (255, 255, 255) 16 | GREEN = (0, 255, 0) 17 | RED = (255, 0, 0) 18 | 19 | 20 | class Block(pygame.sprite.Sprite): 21 | """ 22 | This class represents the ball 23 | It derives from the "Sprite" class in Pygame 24 | """ 25 | def __init__(self, color, width, height): 26 | """ Constructor. Pass in the color of the block, 27 | and its x and y position. """ 28 | # Call the parent class (Sprite) constructor 29 | super().__init__() 30 | 31 | # Create an image of the block, and fill it with a color. 32 | # This could also be an image loaded from the disk. 33 | self.image = pygame.Surface([width, height]) 34 | self.image.fill(color) 35 | 36 | # Fetch the rectangle object that has the dimensions of the image 37 | # image. 38 | # Update the position of this object by setting the values 39 | # of rect.x and rect.y 40 | self.rect = self.image.get_rect() 41 | 42 | def reset_pos(self): 43 | """ Reset position to the top of the screen, at a random x location. 44 | Called by update() or the main program loop if there is a collision. 45 | """ 46 | self.rect.y = random.randrange(-300, -20) 47 | self.rect.x = random.randrange(0, screen_width) 48 | 49 | def update(self): 50 | """ Called each frame. """ 51 | 52 | # Move block down one pixel 53 | self.rect.y += 1 54 | 55 | # If block is too far down, reset to top of screen. 56 | if self.rect.y > 410: 57 | self.reset_pos() 58 | 59 | 60 | class Player(Block): 61 | """ The player class derives from Block, but overrides the 'update' 62 | functionality with new a movement function that will move the block 63 | with the mouse. """ 64 | def update(self): 65 | # Get the current mouse position. This returns the position 66 | # as a list of two numbers. 67 | pos = pygame.mouse.get_pos() 68 | 69 | # Fetch the x and y out of the list, 70 | # just like we'd fetch letters out of a string. 71 | # Set the player object to the mouse location 72 | self.rect.x = pos[0] 73 | self.rect.y = pos[1] 74 | 75 | # Initialize Pygame 76 | pygame.init() 77 | 78 | # Set the height and width of the screen 79 | screen_width = 700 80 | screen_height = 400 81 | screen = pygame.display.set_mode([screen_width, screen_height]) 82 | 83 | # This is a list of 'sprites.' Each block in the program is 84 | # added to this list. The list is managed by a class called 'Group.' 85 | block_list = pygame.sprite.Group() 86 | 87 | # This is a list of every sprite. All blocks and the player block as well. 88 | all_sprites_list = pygame.sprite.Group() 89 | 90 | for i in range(50): 91 | # This represents a block 92 | block = Block(BLACK, 20, 15) 93 | 94 | # Set a random location for the block 95 | block.rect.x = random.randrange(screen_width) 96 | block.rect.y = random.randrange(screen_height) 97 | 98 | # Add the block to the list of objects 99 | block_list.add(block) 100 | all_sprites_list.add(block) 101 | 102 | # Create a red player block 103 | player = Player(RED, 20, 15) 104 | all_sprites_list.add(player) 105 | 106 | # Loop until the user clicks the close button. 107 | done = False 108 | 109 | # Used to manage how fast the screen updates 110 | clock = pygame.time.Clock() 111 | 112 | score = 0 113 | 114 | # -------- Main Program Loop ----------- 115 | while not done: 116 | for event in pygame.event.get(): 117 | if event.type == pygame.QUIT: 118 | done = True 119 | 120 | # Clear the screen 121 | screen.fill(WHITE) 122 | 123 | # Calls update() method on every sprite in the list 124 | all_sprites_list.update() 125 | 126 | # See if the player block has collided with anything. 127 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False) 128 | 129 | # Check the list of collisions. 130 | for block in blocks_hit_list: 131 | score += 1 132 | print(score) 133 | 134 | # Reset block to the top of the screen to fall again. 135 | block.reset_pos() 136 | 137 | # Draw all the spites 138 | all_sprites_list.draw(screen) 139 | 140 | # Limit to 20 frames per second 141 | clock.tick(20) 142 | 143 | # Go ahead and update the screen with what we've drawn. 144 | pygame.display.flip() 145 | 146 | pygame.quit() 147 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/moving_sprites_bounce.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | """ 7 | 8 | import pygame 9 | import random 10 | 11 | # Define some colors 12 | BLACK = (0, 0, 0) 13 | WHITE = (255, 255, 255) 14 | RED = (255, 0, 0) 15 | 16 | 17 | class Block(pygame.sprite.Sprite): 18 | """ 19 | This class represents the ball 20 | It derives from the "Sprite" class in Pygame 21 | """ 22 | 23 | def __init__(self, color, width, height): 24 | """ Constructor. Pass in the color of the block, 25 | and its x and y position. """ 26 | # Call the parent class (Sprite) constructor 27 | super().__init__() 28 | 29 | # Create an image of the block, and fill it with a color. 30 | # This could also be an image loaded from the disk. 31 | self.image = pygame.Surface([width, height]) 32 | self.image.fill(color) 33 | 34 | # Fetch the rectangle object that has the dimensions of the image 35 | # image. 36 | # Update the position of this object by setting the values 37 | # of rect.x and rect.y 38 | self.rect = self.image.get_rect() 39 | 40 | # Instance variables that control the edges of where we bounce 41 | self.left_boundary = 0 42 | self.right_boundary = 0 43 | self.top_boundary = 0 44 | self.bottom_boundary = 0 45 | 46 | # Instance variables for our current speed and direction 47 | self.change_x = 0 48 | self.change_y = 0 49 | 50 | def update(self): 51 | """ Called each frame. """ 52 | self.rect.x += self.change_x 53 | self.rect.y += self.change_y 54 | 55 | if self.rect.right >= self.right_boundary or self.rect.left <= self.left_boundary: 56 | self.change_x *= -1 57 | 58 | if self.rect.bottom >= self.bottom_boundary or self.rect.top <= self.top_boundary: 59 | self.change_y *= -1 60 | 61 | 62 | class Player(Block): 63 | """ The player class derives from Block, but overrides the 'update' 64 | functionality with new a movement function that will move the block 65 | with the mouse. """ 66 | def update(self): 67 | # Get the current mouse position. This returns the position 68 | # as a list of two numbers. 69 | pos = pygame.mouse.get_pos() 70 | 71 | # Fetch the x and y out of the list, 72 | # just like we'd fetch letters out of a string. 73 | # Set the player object to the mouse location 74 | self.rect.x = pos[0] 75 | self.rect.y = pos[1] 76 | 77 | # Initialize Pygame 78 | pygame.init() 79 | 80 | # Set the height and width of the screen 81 | screen_width = 700 82 | screen_height = 400 83 | screen = pygame.display.set_mode([screen_width, screen_height]) 84 | 85 | # This is a list of 'sprites.' Each block in the program is 86 | # added to this list. The list is managed by a class called 'Group.' 87 | block_list = pygame.sprite.Group() 88 | 89 | # This is a list of every sprite. All blocks and the player block as well. 90 | all_sprites_list = pygame.sprite.Group() 91 | 92 | for i in range(50): 93 | # This represents a block 94 | block = Block(BLACK, 20, 15) 95 | 96 | # Set a random location for the block 97 | block.rect.x = random.randrange(screen_width) 98 | block.rect.y = random.randrange(screen_height) 99 | 100 | block.change_x = random.randrange(-3, 4) 101 | block.change_y = random.randrange(-3, 4) 102 | block.left_boundary = 0 103 | block.top_boundary = 0 104 | block.right_boundary = screen_width 105 | block.bottom_boundary = screen_height 106 | 107 | # Add the block to the list of objects 108 | block_list.add(block) 109 | all_sprites_list.add(block) 110 | 111 | # Create a red player block 112 | player = Player(RED, 20, 15) 113 | all_sprites_list.add(player) 114 | 115 | # Loop until the user clicks the close button. 116 | done = False 117 | 118 | # Used to manage how fast the screen updates 119 | clock = pygame.time.Clock() 120 | 121 | score = 0 122 | 123 | # -------- Main Program Loop ----------- 124 | while not done: 125 | for event in pygame.event.get(): 126 | if event.type == pygame.QUIT: 127 | done = True 128 | 129 | # Clear the screen 130 | screen.fill(WHITE) 131 | 132 | # Calls update() method on every sprite in the list 133 | all_sprites_list.update() 134 | 135 | # See if the player block has collided with anything. 136 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 137 | 138 | # Check the list of collisions. 139 | for block in blocks_hit_list: 140 | score += 1 141 | print(score) 142 | 143 | # Draw all the spites 144 | all_sprites_list.draw(screen) 145 | 146 | # Limit to 60 frames per second 147 | clock.tick(60) 148 | 149 | # Go ahead and update the screen with what we've drawn. 150 | pygame.display.flip() 151 | 152 | pygame.quit() 153 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/mudball.py: -------------------------------------------------------------------------------- 1 | """ 2 | This is a sample text-only game that demonstrates the use of functions. 3 | The game is called "Mudball" and the players take turns lobbing mudballs 4 | at each other until someone gets hit. 5 | """ 6 | 7 | import math 8 | import random 9 | 10 | 11 | def print_instructions(): 12 | """ This function prints the instructions. """ 13 | 14 | # You can use the triple-quote string in a print statement to 15 | # print multiple lines. 16 | print(""" 17 | Welcome to Mudball! The idea is to hit the other player with a mudball. 18 | Enter your angle (in degrees) and the amount of PSI to charge your gun 19 | with. 20 | """) 21 | 22 | 23 | def calculate_distance(psi, angle_in_degrees): 24 | """ Calculate the distance the mudball flies. """ 25 | angle_in_radians = math.radians(angle_in_degrees) 26 | distance = .5 * psi ** 2 * math.sin(angle_in_radians) * math.cos(angle_in_radians) 27 | return distance 28 | 29 | 30 | def get_user_input(name): 31 | """ Get the user input for psi and angle. Return as a list of two 32 | numbers. """ 33 | # Later on in the 'exceptions' chapter, we will learn how to modify 34 | # this code to not crash the game if the user types in something that 35 | # isn't a valid number. 36 | psi = float(input(name + " charge the gun with how many psi? ")) 37 | angle = float(input(name + " move the gun at what angle? ")) 38 | return psi, angle 39 | 40 | 41 | def get_player_names(): 42 | """ Get a list of names from the players. """ 43 | print("Enter player names. Enter as many players as you like.") 44 | done = False 45 | players = [] 46 | while not done: 47 | player = input("Enter player (hit enter to quit): ") 48 | if len(player) > 0: 49 | players.append(player) 50 | else: 51 | done = True 52 | 53 | print() 54 | return players 55 | 56 | 57 | def process_player_turn(player_name, distance_apart): 58 | """ The code runs the turn for each player. 59 | If it returns False, keep going with the game. 60 | If it returns True, someone has won, so stop. """ 61 | psi, angle = get_user_input(player_name) 62 | 63 | distance_mudball = calculate_distance(psi, angle) 64 | difference = distance_mudball - distance_apart 65 | 66 | # By looking ahead to the chapter on print formatting, these 67 | # lines could be made to print the numbers is a nice formatted 68 | # manner. 69 | if difference > 1: 70 | print("You went", difference, "yards too far!") 71 | elif difference < -1: 72 | print("You were", difference * -1, "yards too short!") 73 | else: 74 | print("Hit!", player_name, "wins!") 75 | return True 76 | 77 | print() 78 | return False 79 | 80 | 81 | def main(): 82 | """ Main program. """ 83 | 84 | # Get the game started. 85 | print_instructions() 86 | player_names = get_player_names() 87 | distance_apart = random.randrange(50, 150) 88 | 89 | # Keep looking until someone wins 90 | done = False 91 | while not done: 92 | # Loop for each player 93 | for player_name in player_names: 94 | # Process their turn 95 | done = process_player_turn(player_name, distance_apart) 96 | # If someone won, 'break' out of this loop and end the game. 97 | if done: 98 | break 99 | 100 | if __name__ == "__main__": 101 | main() 102 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/network_client.py: -------------------------------------------------------------------------------- 1 | # Connect to port 12345 2 | import socket 3 | 4 | port = 12345 5 | host = socket.gethostname() 6 | # host = '10.1.21.1' 7 | 8 | message_string = "I've connected!" 9 | message_data = message_string.encode("utf-8") 10 | 11 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 12 | s.connect((host, port)) 13 | s.send(message_data) 14 | s.close() 15 | print("Received") 16 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/network_server_blocking.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import time 3 | 4 | host = '' 5 | port = 12345 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | s.bind((host, port)) 9 | s.listen(1) 10 | 11 | print("Listening") 12 | 13 | while True: 14 | conn, addr = s.accept() 15 | print("Connected by: ", addr) 16 | data = conn.recv(1024) 17 | if data: 18 | data_string = data.decode("utf-8") 19 | print(data_string) 20 | conn.close() 21 | 22 | print("End Listening") 23 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/network_server_nonblocking.py: -------------------------------------------------------------------------------- 1 | import socket 2 | import time 3 | 4 | host = '' 5 | port = 12345 6 | 7 | s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | s.setblocking(0) 9 | s.bind((host, port)) 10 | s.listen(1) 11 | 12 | print("Listening") 13 | 14 | while True: 15 | try: 16 | time.sleep(.1) 17 | conn, addr = s.accept() 18 | print("Connected by: ", addr) 19 | data = conn.recv(1024) 20 | if data: 21 | data_string = data.decode("utf-8") 22 | print(data_string) 23 | conn.close() 24 | 25 | except BlockingIOError: 26 | """ Do Nothing """ 27 | 28 | except KeyboardInterrupt: 29 | break 30 | 31 | print("End Listening") 32 | input("Press any key to exit...") 33 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/number_guessing_game.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | secret_number = random.randrange(1, 129) 4 | 5 | guess = 0 6 | while guess != secret_number: 7 | guess = (int)(input("Guess a number 1 to 128: ")) 8 | if guess < secret_number: 9 | print("Too low.") 10 | elif guess > secret_number: 11 | print("Too high.") 12 | else: 13 | print("Correct!") 14 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/opengl_lesson01.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to open a window for OpenGL graphics 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | This program is based off the ideas in the excellent tutorials 10 | at http://nehe.gamedev.net/ 11 | """ 12 | 13 | import OpenGL.GL 14 | import OpenGL.GLU 15 | import pygame 16 | 17 | def resize_gl_scene(size): 18 | height = size[1] 19 | width = size[0] 20 | 21 | OpenGL.GL.glViewport(0, 0, width, height) 22 | OpenGL.GL.glMatrixMode(OpenGL.GL.GL_PROJECTION) 23 | OpenGL.GL.glLoadIdentity() 24 | OpenGL.GLU.gluPerspective(45, 1.0 * width / height, 0.1, 100.0) 25 | OpenGL.GL.glMatrixMode(OpenGL.GL.GL_MODELVIEW) 26 | OpenGL.GL.glLoadIdentity() 27 | 28 | def init_gl(): 29 | OpenGL.GL.glShadeModel(OpenGL.GL.GL_SMOOTH) 30 | OpenGL.GL.glClearColor(0.0, 0.0, 0.0, 0.0) 31 | OpenGL.GL.glClearDepth(1.0) 32 | OpenGL.GL.glEnable(OpenGL.GL.GL_DEPTH_TEST) 33 | OpenGL.GL.glDepthFunc(OpenGL.GL.GL_LEQUAL) 34 | OpenGL.GL.glHint(OpenGL.GL.GL_PERSPECTIVE_CORRECTION_HINT, OpenGL.GL.GL_NICEST) 35 | 36 | def draw_gl_scene(): 37 | OpenGL.GL.glClear(OpenGL.GL.GL_COLOR_BUFFER_BIT | OpenGL.GL.GL_DEPTH_BUFFER_BIT) 38 | OpenGL.GL.glLoadIdentity() 39 | 40 | def main(): 41 | """ Main function for the game. """ 42 | 43 | # Get Pygame ready 44 | pygame.init() 45 | 46 | # Set the width and height of the screen [width,height] 47 | size = (640,480) 48 | video_flags = pygame.OPENGL | pygame.DOUBLEBUF 49 | screen = pygame.display.set_mode(size, video_flags) 50 | 51 | # Create an OpenGL viewport 52 | resize_gl_scene(size) 53 | init_gl() 54 | 55 | # These are for calculating FPS 56 | frames = 0 57 | ticks = pygame.time.get_ticks() 58 | 59 | done = False 60 | 61 | while not done: 62 | event = pygame.event.poll() 63 | if event.type == pygame.QUIT: 64 | done = True 65 | 66 | draw_gl_scene() 67 | pygame.display.flip() 68 | frames = frames + 1 69 | 70 | total_ticks = pygame.time.get_ticks() - ticks 71 | print("Average of {:.1f} fps".format((frames * 1000) / total_ticks)) 72 | 73 | pygame.quit() 74 | 75 | if __name__ == "__main__": 76 | main() 77 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/pick_up_blocks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Use sprites to pick up blocks 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/iwLj7iJCFQM 10 | """ 11 | import pygame 12 | import random 13 | 14 | # Define some colors 15 | BLACK = (0, 0, 0) 16 | WHITE = (255, 255, 255) 17 | RED = (255, 0, 0) 18 | 19 | 20 | class Block(pygame.sprite.Sprite): 21 | """ 22 | This class represents the block to be picked up. 23 | It derives from the "Sprite" class in Pygame. 24 | """ 25 | 26 | def __init__(self, color, width, height): 27 | """ Constructor. Pass in the color of the block, 28 | and its x and y position. """ 29 | 30 | # Call the parent class (Sprite) constructor 31 | super().__init__() 32 | 33 | # Create an image of the block, and fill it with a color. 34 | # This could also be an image loaded from the disk. 35 | self.image = pygame.Surface([width, height]) 36 | self.image.fill(color) 37 | 38 | # Fetch the rectangle object that has the dimensions of the image 39 | # image. 40 | # Update the position of this object by setting the values 41 | # of rect.x and rect.y 42 | self.rect = self.image.get_rect() 43 | 44 | 45 | class Player(Block): 46 | """ This class represents the player. It derives from block and thus gets 47 | the same ___init___ method we defined above. """ 48 | 49 | # List of all the blocks we are carrying 50 | carry_block_list = [] 51 | 52 | def update(self): 53 | """ Method called when updating a sprite. """ 54 | 55 | # Get the current mouse position. This returns the position 56 | # as a list of two numbers. 57 | pos = pygame.mouse.get_pos() 58 | 59 | # Now see how the mouse position is different from the current 60 | # player position. (How far did we move?) 61 | diff_x = self.rect.x - pos[0] 62 | diff_y = self.rect.y - pos[1] 63 | 64 | # Loop through each block that we are carrying and adjust 65 | # it by the amount we moved. 66 | for block in self.carry_block_list: 67 | block.rect.x -= diff_x 68 | block.rect.y -= diff_y 69 | 70 | # Now wet the player object to the mouse location 71 | self.rect.x = pos[0] 72 | self.rect.y = pos[1] 73 | 74 | # Initialize Pygame 75 | pygame.init() 76 | 77 | # Set the height and width of the screen 78 | screen_width = 700 79 | screen_height = 400 80 | screen = pygame.display.set_mode([screen_width, screen_height]) 81 | 82 | # This is a list of 'sprites.' Each block in the program is 83 | # added to this list. The list is managed by a class called 'Group.' 84 | block_list = pygame.sprite.Group() 85 | 86 | # This is a list of every sprite. 87 | # All blocks and the player block as well. 88 | all_sprites_list = pygame.sprite.Group() 89 | 90 | for i in range(50): 91 | # This represents a block 92 | block = Block(BLACK, 20, 15) 93 | 94 | # Set a random location for the block 95 | block.rect.x = random.randrange(screen_width) 96 | block.rect.y = random.randrange(screen_height) 97 | 98 | # Add the block to the list of objects 99 | block_list.add(block) 100 | all_sprites_list.add(block) 101 | 102 | # Create a RED player block 103 | player = Player(RED, 20, 15) 104 | all_sprites_list.add(player) 105 | 106 | # Loop until the user clicks the close button. 107 | done = False 108 | 109 | # Used to manage how fast the screen updates 110 | clock = pygame.time.Clock() 111 | 112 | # Hide the mouse cursor 113 | pygame.mouse.set_visible(False) 114 | 115 | # -------- Main Program Loop ----------- 116 | while not done: 117 | for event in pygame.event.get(): 118 | if event.type == pygame.QUIT: 119 | done = True 120 | 121 | elif event.type == pygame.MOUSEBUTTONDOWN: 122 | # When the mouse button is pressed, see if we are in contact with 123 | # other sprites: 124 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, False) 125 | 126 | # Set the list of blocks we are in contact with as the list of 127 | # blocks being carried. 128 | player.carry_block_list = blocks_hit_list 129 | 130 | elif event.type == pygame.MOUSEBUTTONUP: 131 | # When we let up on the mouse, set the list of blocks we are 132 | # carrying as empty. 133 | player.carry_block_list = [] 134 | 135 | all_sprites_list.update() 136 | 137 | # Clear the screen 138 | screen.fill(WHITE) 139 | 140 | # Draw all the spites 141 | all_sprites_list.draw(screen) 142 | 143 | # Limit to 60 frames per second 144 | clock.tick(60) 145 | 146 | # Go ahead and update the screen with what we've drawn. 147 | pygame.display.flip() 148 | 149 | pygame.quit() 150 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/player.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/player.jpg -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/player.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/player.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/playerShip1_orange.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/playerShip1_orange.jpg -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/playerShip1_orange.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/playerShip1_orange.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/posting_template.txt: -------------------------------------------------------------------------------- 1 | '; 8 | ?> 9 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/property_check_examples.py: -------------------------------------------------------------------------------- 1 | class Alien: 2 | """ Class that defines an alien""" 3 | def __init__(self, color, weight): 4 | """ Constructor. Set name and color""" 5 | self.color = color 6 | self.weight = weight 7 | 8 | def has_property(my_alien): 9 | """ Check to see if an item has a property. 10 | In this case, is the alien green? """ 11 | if my_alien.color.upper() == "GREEN": 12 | return True 13 | else: 14 | return False 15 | 16 | def check_if_one_item_has_property_v1(my_list): 17 | """ Return true if at least one item has a 18 | property. """ 19 | i = 0 20 | while i < len(my_list) and not has_property(my_list[i]): 21 | i += 1 22 | 23 | if i < len(my_list): 24 | # Found an item with the property 25 | return True 26 | else: 27 | # There is no item with the property 28 | return False 29 | 30 | def check_if_one_item_has_property_v2(my_list): 31 | """ Return true if at least one item has a 32 | property. Works the same as v1, but less code. """ 33 | for item in my_list: 34 | if has_property(item): 35 | return True 36 | return False 37 | 38 | def check_if_all_items_have_property(my_list): 39 | """ Return true if at ALL items have a property. """ 40 | for item in my_list: 41 | if not has_property(item): 42 | return False 43 | return True 44 | 45 | def get_matching_items(list): 46 | """ Build a brand new list that holds all the items 47 | that match our property. """ 48 | matching_list = [] 49 | for item in list: 50 | if has_property(item): 51 | matching_list.append(item) 52 | return matching_list 53 | 54 | def main(): 55 | """ Test everything out. """ 56 | alien_list = [] 57 | alien_list.append(Alien("Green", 42)) 58 | alien_list.append(Alien("Red", 40)) 59 | alien_list.append(Alien("Blue", 41)) 60 | alien_list.append(Alien("Purple", 40)) 61 | 62 | result = check_if_one_item_has_property_v1(alien_list) 63 | print("Result of test check_if_one_item_has_property_v1:", result) 64 | 65 | result = check_if_one_item_has_property_v2(alien_list) 66 | print("Result of test check_if_one_item_has_property_v2:", result) 67 | 68 | result = check_if_all_items_have_property(alien_list) 69 | print("Result of test check_if_all_items_have_property:", result) 70 | 71 | result = get_matching_items(alien_list) 72 | print("Number of items returned from test get_matching_items:", len(result)) 73 | 74 | if __name__ == "__main__": 75 | main() 76 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/pygame_base_template.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pygame base template for opening a window 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/vRB_983kUMc 10 | """ 11 | 12 | import pygame 13 | 14 | # Define some colors 15 | BLACK = (0, 0, 0) 16 | WHITE = (255, 255, 255) 17 | GREEN = (0, 255, 0) 18 | RED = (255, 0, 0) 19 | 20 | pygame.init() 21 | 22 | # Set the width and height of the screen [width, height] 23 | size = (700, 500) 24 | screen = pygame.display.set_mode(size) 25 | 26 | pygame.display.set_caption("My Game") 27 | 28 | # Loop until the user clicks the close button. 29 | done = False 30 | 31 | # Used to manage how fast the screen updates 32 | clock = pygame.time.Clock() 33 | 34 | # -------- Main Program Loop ----------- 35 | while not done: 36 | # --- Main event loop 37 | for event in pygame.event.get(): 38 | if event.type == pygame.QUIT: 39 | done = True 40 | 41 | # --- Game logic should go here 42 | 43 | # --- Screen-clearing code goes here 44 | 45 | # Here, we clear the screen to white. Don't put other drawing commands 46 | # above this, or they will be erased with this command. 47 | 48 | # If you want a background image, replace this clear with blit'ing the 49 | # background image. 50 | screen.fill(WHITE) 51 | 52 | # --- Drawing code should go here 53 | 54 | # --- Go ahead and update the screen with what we've drawn. 55 | pygame.display.flip() 56 | 57 | # --- Limit to 60 frames per second 58 | clock.tick(60) 59 | 60 | # Close the window and quit. 61 | pygame.quit() 62 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/pygame_base_template_proper.py: -------------------------------------------------------------------------------- 1 | """ 2 | Pygame base template for opening a window, done with functions 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | 11 | import pygame 12 | 13 | # The use of the main function is described in Chapter 9. 14 | 15 | # Define some colors as global constants 16 | BLACK = (0, 0, 0) 17 | WHITE = (255, 255, 255) 18 | GREEN = (0, 255, 0) 19 | RED = (255, 0, 0) 20 | 21 | 22 | def main(): 23 | """ Main function for the game. """ 24 | pygame.init() 25 | 26 | # Set the width and height of the screen [width,height] 27 | size = [700, 500] 28 | screen = pygame.display.set_mode(size) 29 | 30 | pygame.display.set_caption("My Game") 31 | 32 | # Loop until the user clicks the close button. 33 | done = False 34 | 35 | # Used to manage how fast the screen updates 36 | clock = pygame.time.Clock() 37 | 38 | # -------- Main Program Loop ----------- 39 | while not done: 40 | # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT 41 | for event in pygame.event.get(): 42 | if event.type == pygame.QUIT: 43 | done = True 44 | # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT 45 | 46 | # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT 47 | 48 | # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT 49 | 50 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 51 | 52 | # First, clear the screen to white. Don't put other drawing commands 53 | # above this, or they will be erased with this command. 54 | screen.fill(WHITE) 55 | 56 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 57 | 58 | # Go ahead and update the screen with what we've drawn. 59 | pygame.display.flip() 60 | 61 | # Limit to 60 frames per second 62 | clock.tick(60) 63 | 64 | # Close the window and quit. 65 | # If you forget this line, the program will 'hang' 66 | # on exit if running from IDLE. 67 | pygame.quit() 68 | 69 | if __name__ == "__main__": 70 | main() 71 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/radar_sweep.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to do a radar sweep. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | # Import a library of functions called 'pygame' 11 | import pygame 12 | import math 13 | 14 | # Initialize the game engine 15 | pygame.init() 16 | 17 | # Colors 18 | BLACK = (0, 0, 0) 19 | WHITE = (255, 255, 255) 20 | GREEN = (0, 255, 0) 21 | RED = (255, 0, 0) 22 | BLUE = (0, 0, 255) 23 | 24 | PI = 3.141592653 25 | 26 | # Set the height and width of the screen 27 | size = [400, 400] 28 | screen = pygame.display.set_mode(size) 29 | 30 | my_clock = pygame.time.Clock() 31 | 32 | # Loop until the user clicks the close button. 33 | done = False 34 | 35 | angle = 0 36 | 37 | while not done: 38 | for event in pygame.event.get(): 39 | if event.type == pygame.QUIT: 40 | done = True 41 | 42 | # Set the screen background 43 | screen.fill(WHITE) 44 | 45 | # Dimensions of radar sweep 46 | # Start with the top left at 20,20 47 | # Width/height of 250 48 | box_dimensions = [20, 20, 250, 250] 49 | 50 | # Draw the outline of a circle to 'sweep' the line around 51 | pygame.draw.ellipse(screen, GREEN, box_dimensions, 2) 52 | 53 | # Draw a black box around the circle 54 | pygame.draw.rect(screen, BLACK, box_dimensions, 2) 55 | 56 | # Calculate the x,y for the end point of our 'sweep' based on 57 | # the current angle 58 | x = 125 * math.sin(angle) + 145 59 | y = 125 * math.cos(angle) + 145 60 | 61 | # Draw the line from the center at 145, 145 to the calculated 62 | # end spot 63 | pygame.draw.line(screen, GREEN, [145, 145], [x, y], 2) 64 | 65 | # Increase the angle by 0.03 radians 66 | angle = angle + .03 67 | 68 | # If we have done a full sweep, reset the angle to 0 69 | if angle > 2 * PI: 70 | angle = angle - 2 * PI 71 | 72 | # Flip the display, wait out the clock tick 73 | pygame.display.flip() 74 | my_clock.tick(60) 75 | 76 | # Be IDLE friendly. If you forget this line, the program will 'hang' 77 | # on exit. 78 | pygame.quit() 79 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/read_from_file.py: -------------------------------------------------------------------------------- 1 | file = open("example_sorted_names.txt") 2 | line_list = file.readlines() 3 | file.close() 4 | 5 | print("There were", len(line_list), "lines in the file.") 6 | for line in line_list: 7 | print(line) 8 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/recursive_rectangles.py: -------------------------------------------------------------------------------- 1 | """ 2 | Recursively draw rectangles. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | import pygame 11 | 12 | # Colors 13 | BLACK = (0, 0, 0) 14 | WHITE = (255, 255, 255) 15 | 16 | 17 | def recursive_draw(x, y, width, height): 18 | """ Recursive rectangle function. """ 19 | pygame.draw.rect(screen, BLACK, 20 | [x, y, width, height], 21 | 1) 22 | 23 | # Is the rectangle wide enough to draw again? 24 | if(width > 14): 25 | # Scale down 26 | x += width * .1 27 | y += height * .1 28 | width *= .8 29 | height *= .8 30 | # Recursively draw again 31 | recursive_draw(x, y, width, height) 32 | 33 | pygame.init() 34 | 35 | # Set the height and width of the screen 36 | size = [700, 500] 37 | screen = pygame.display.set_mode(size) 38 | 39 | pygame.display.set_caption("My Game") 40 | 41 | # Loop until the user clicks the close button. 42 | done = False 43 | 44 | # Used to manage how fast the screen updates 45 | clock = pygame.time.Clock() 46 | 47 | # -------- Main Program Loop ----------- 48 | while not done: 49 | for event in pygame.event.get(): 50 | if event.type == pygame.QUIT: 51 | done = True 52 | 53 | # Set the screen background 54 | screen.fill(WHITE) 55 | 56 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 57 | recursive_draw(0, 0, 700, 500) 58 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 59 | 60 | # Go ahead and update the screen with what we've drawn. 61 | pygame.display.flip() 62 | 63 | # Limit to 60 frames per second 64 | clock.tick(60) 65 | 66 | # Be IDLE friendly. If you forget this line, the program will 'hang' 67 | # on exit. 68 | pygame.quit() 69 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/saturn_family1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/saturn_family1.jpg -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/searching_example.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # --- Read in a file from disk and put it in an array. 7 | file = open("super_villains.txt") 8 | 9 | name_list = [] 10 | for line in file: 11 | line = line.strip() 12 | name_list.append(line) 13 | 14 | file.close() 15 | 16 | # --- Linear search 17 | key = "Morgiana the Shrew" 18 | 19 | i = 0 20 | while i < len(name_list) and name_list[i] != key: 21 | i += 1 22 | 23 | if i < len(name_list): 24 | print( "The name is at position", i) 25 | else: 26 | print( "The name was not in the list." ) 27 | 28 | # --- Binary search 29 | key = "Morgiana the Shrew"; 30 | lower_bound = 0 31 | upper_bound = len(name_list)-1 32 | found = False 33 | 34 | # Loop until we find the item, or our upper/lower bounds meet 35 | while lower_bound <= upper_bound and not found: 36 | 37 | # Find the middle position 38 | middle_pos = (lower_bound + upper_bound) // 2 39 | 40 | # Figure out if we: 41 | # move up the lower bound, or 42 | # move down the upper bound, or 43 | # we found what we are looking for 44 | if name_list[middle_pos] < key: 45 | lower_bound = middle_pos + 1 46 | elif name_list[middle_pos] > key: 47 | upper_bound = middle_pos - 1 48 | else: 49 | found = True 50 | 51 | if found: 52 | print( "The name is at position", middle_pos) 53 | else: 54 | print( "The name was not in the list." ) 55 | 56 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/simple_decryption.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # Explanation video: http://youtu.be/sxFIxD8Gd3A 7 | 8 | encrypted_text = "Uijt!jt!b!uftu/!BCD!bcd" 9 | 10 | plain_text = "" 11 | for c in encrypted_text: 12 | x = ord(c) 13 | x = x - 1 14 | c2 = chr(x) 15 | plain_text = plain_text + c2 16 | print(plain_text) 17 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/simple_encryption.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # Explanation video: http://youtu.be/sxFIxD8Gd3A 7 | 8 | plain_text = "This is a test. ABC abc" 9 | 10 | encrypted_text = "" 11 | for c in plain_text: 12 | x = ord(c) 13 | x = x + 1 14 | c2 = chr(x) 15 | encrypted_text = encrypted_text + c2 16 | print(encrypted_text) 17 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/simple_graphics_demo.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple graphics demo 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | 11 | # Import a library of functions called 'pygame' 12 | import pygame 13 | 14 | # Initialize the game engine 15 | pygame.init() 16 | 17 | # Define some colors 18 | BLACK = (0, 0, 0) 19 | WHITE = (255, 255, 255) 20 | BLUE = (0, 0, 255) 21 | GREEN = (0, 255, 0) 22 | RED = (255, 0, 0) 23 | 24 | PI = 3.141592653 25 | 26 | # Set the height and width of the screen 27 | size = (400, 500) 28 | screen = pygame.display.set_mode(size) 29 | 30 | pygame.display.set_caption("Professor Craven's Cool Game") 31 | 32 | # Loop until the user clicks the close button. 33 | done = False 34 | clock = pygame.time.Clock() 35 | 36 | # Loop as long as done == False 37 | while not done: 38 | 39 | for event in pygame.event.get(): # User did something 40 | if event.type == pygame.QUIT: # If user clicked close 41 | done = True # Flag that we are done so we exit this loop 42 | 43 | # All drawing code happens after the for loop and but 44 | # inside the main while not done loop. 45 | 46 | # Clear the screen and set the screen background 47 | screen.fill(WHITE) 48 | 49 | # Draw on the screen a line from (0,0) to (100,100) 50 | # 5 pixels wide. 51 | pygame.draw.line(screen, GREEN, [0, 0], [100, 100], 5) 52 | 53 | # Draw on the screen several lines from (0,10) to (100,110) 54 | # 5 pixels wide using a loop 55 | for y_offset in range(0, 100, 10): 56 | pygame.draw.line(screen, RED, [0, 10 + y_offset], [100, 110 + y_offset], 5) 57 | 58 | 59 | # Draw a rectangle 60 | pygame.draw.rect(screen, BLACK, [20, 20, 250, 100], 2) 61 | 62 | # Draw an ellipse, using a rectangle as the outside boundaries 63 | pygame.draw.ellipse(screen, BLACK, [20, 20, 250, 100], 2) 64 | 65 | # Draw an arc as part of an ellipse. 66 | # Use radians to determine what angle to draw. 67 | pygame.draw.arc(screen, BLACK, [20, 220, 250, 200], 0, PI / 2, 2) 68 | pygame.draw.arc(screen, GREEN, [20, 220, 250, 200], PI / 2, PI, 2) 69 | pygame.draw.arc(screen, BLUE, [20, 220, 250, 200], PI, 3 * PI / 2, 2) 70 | pygame.draw.arc(screen, RED, [20, 220, 250, 200], 3 * PI / 2, 2 * PI, 2) 71 | 72 | # This draws a triangle using the polygon command 73 | pygame.draw.polygon(screen, BLACK, [[100, 100], [0, 200], [200, 200]], 5) 74 | 75 | # Select the font to use, size, bold, italics 76 | font = pygame.font.SysFont('Calibri', 25, True, False) 77 | 78 | # Render the text. "True" means anti-aliased text. 79 | # Black is the color. This creates an image of the 80 | # letters, but does not put it on the screen 81 | text = font.render("My text", True, BLACK) 82 | 83 | # Put the image of the text on the screen at 250x250 84 | screen.blit(text, [250, 250]) 85 | 86 | # Go ahead and update the screen with what we've drawn. 87 | # This MUST happen after all the other drawing commands. 88 | pygame.display.flip() 89 | 90 | # This limits the while loop to a max of 60 times per second. 91 | # Leave this out and we will use all CPU we can. 92 | clock.tick(60) 93 | 94 | # Be IDLE friendly 95 | pygame.quit() 96 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/simple_web_server.py: -------------------------------------------------------------------------------- 1 | import socket 2 | 3 | s = socket.socket() 4 | host = "127.0.0.1" 5 | port = 80 6 | s.bind((host, port)) 7 | 8 | s.listen(5) 9 | 10 | while True: 11 | print("Waiting for connection") 12 | c, addr = s.accept() 13 | print ('Got connection from', addr) 14 | data = c.recv(1024) 15 | data_string = data.decode("utf-8") 16 | print(data_string) 17 | c.send(b'HTTP/1.1 200 OK\r\n\r\nHi') 18 | c.close() 19 | 20 | print("Done") -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/snake.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple snake example. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | 11 | import pygame 12 | 13 | # --- Globals --- 14 | # Colors 15 | BLACK = (0, 0, 0) 16 | WHITE = (255, 255, 255) 17 | 18 | # Set the width and height of each snake segment 19 | segment_width = 15 20 | segment_height = 15 21 | # Margin between each segment 22 | segment_margin = 3 23 | 24 | # Set initial speed 25 | x_change = segment_width + segment_margin 26 | y_change = 0 27 | 28 | 29 | class Segment(pygame.sprite.Sprite): 30 | """ Class to represent one segment of the snake. """ 31 | # -- Methods 32 | # Constructor function 33 | def __init__(self, x, y): 34 | # Call the parent's constructor 35 | super().__init__() 36 | 37 | # Set height, width 38 | self.image = pygame.Surface([segment_width, segment_height]) 39 | self.image.fill(WHITE) 40 | 41 | # Make our top-left corner the passed-in location. 42 | self.rect = self.image.get_rect() 43 | self.rect.x = x 44 | self.rect.y = y 45 | 46 | # Call this function so the Pygame library can initialize itself 47 | pygame.init() 48 | 49 | # Create an 800x600 sized screen 50 | screen = pygame.display.set_mode([800, 600]) 51 | 52 | # Set the title of the window 53 | pygame.display.set_caption('Snake Example') 54 | 55 | allspriteslist = pygame.sprite.Group() 56 | 57 | # Create an initial snake 58 | snake_segments = [] 59 | for i in range(15): 60 | x = 250 - (segment_width + segment_margin) * i 61 | y = 30 62 | segment = Segment(x, y) 63 | snake_segments.append(segment) 64 | allspriteslist.add(segment) 65 | 66 | 67 | clock = pygame.time.Clock() 68 | done = False 69 | 70 | while not done: 71 | 72 | for event in pygame.event.get(): 73 | if event.type == pygame.QUIT: 74 | done = True 75 | 76 | # Set the speed based on the key pressed 77 | # We want the speed to be enough that we move a full 78 | # segment, plus the margin. 79 | if event.type == pygame.KEYDOWN: 80 | if event.key == pygame.K_LEFT: 81 | x_change = (segment_width + segment_margin) * -1 82 | y_change = 0 83 | if event.key == pygame.K_RIGHT: 84 | x_change = (segment_width + segment_margin) 85 | y_change = 0 86 | if event.key == pygame.K_UP: 87 | x_change = 0 88 | y_change = (segment_height + segment_margin) * -1 89 | if event.key == pygame.K_DOWN: 90 | x_change = 0 91 | y_change = (segment_height + segment_margin) 92 | 93 | # Get rid of last segment of the snake 94 | # .pop() command removes last item in list 95 | old_segment = snake_segments.pop() 96 | allspriteslist.remove(old_segment) 97 | 98 | # Figure out where new segment will be 99 | x = snake_segments[0].rect.x + x_change 100 | y = snake_segments[0].rect.y + y_change 101 | segment = Segment(x, y) 102 | 103 | # Insert new segment into the list 104 | snake_segments.insert(0, segment) 105 | allspriteslist.add(segment) 106 | 107 | # -- Draw everything 108 | # Clear screen 109 | screen.fill(BLACK) 110 | 111 | allspriteslist.draw(screen) 112 | 113 | # Flip screen 114 | pygame.display.flip() 115 | 116 | # Pause 117 | clock.tick(5) 118 | 119 | pygame.quit() 120 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sorting_examples.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | import random 7 | 8 | 9 | def selection_sort(list): 10 | """ Sort a list using the selection sort """ 11 | 12 | # Loop through the entire array 13 | for cur_pos in range(len(list)): 14 | # Find the position that has the smallest number 15 | # Start with the current position 16 | min_pos = cur_pos 17 | 18 | # Scan left to right (end of the list) 19 | for scan_pos in range(cur_pos + 1, len(list)): 20 | 21 | # Is this position smallest? 22 | if list[scan_pos] < list[min_pos]: 23 | 24 | # It is, mark this position as the smallest 25 | min_pos = scan_pos 26 | 27 | # Swap the two values 28 | temp = list[min_pos] 29 | list[min_pos] = list[cur_pos] 30 | list[cur_pos] = temp 31 | 32 | 33 | def insertion_sort(list): 34 | """ Sort a list using the insertion sort """ 35 | 36 | # Start at the second element (pos 1). 37 | # Use this element to insert into the 38 | # list. 39 | for key_pos in range(1, len(list)): 40 | 41 | # Get the value of the element to insert 42 | key_value = list[key_pos] 43 | 44 | # Scan from right to the left (start of list) 45 | scan_pos = key_pos - 1 46 | 47 | # Loop each element, moving them up until 48 | # we reach the position the 49 | while (scan_pos >= 0) and (list[scan_pos] > key_value): 50 | list[scan_pos + 1] = list[scan_pos] 51 | scan_pos = scan_pos - 1 52 | 53 | # Everything's been moved out of the way, insert 54 | # the key into the correct location 55 | list[scan_pos + 1] = key_value 56 | 57 | 58 | # This will point out a list 59 | # For more information on the print formatting {:3} 60 | # see the chapter on print formatting. 61 | def print_list(list): 62 | for item in list: 63 | print("{:3}".format(item), end="") 64 | print() 65 | 66 | # Create two lists of the same random numbers 67 | list1 = [] 68 | list2 = [] 69 | list_size = 10 70 | for i in range(list_size): 71 | new_number = random.randrange(100) 72 | list1.append(new_number) 73 | list2.append(new_number) 74 | 75 | # Print the original list 76 | print_list(list1) 77 | 78 | # Use the selection sort and print the result 79 | print("Selection Sort") 80 | selection_sort(list1) 81 | print_list(list1) 82 | 83 | # Use the insertion sort and print the result 84 | print("Insertion Sort") 85 | insertion_sort(list2) 86 | print_list(list2) 87 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_circle_movement.py: -------------------------------------------------------------------------------- 1 | """ 2 | Move a sprite in a circle. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | 11 | import pygame 12 | import random 13 | import math 14 | 15 | # Colors 16 | BLACK = (0, 0, 0) 17 | WHITE = (255, 255, 255) 18 | GREEN = (0, 255, 0) 19 | RED = (255, 0, 0) 20 | BLUE = (0, 0, 255) 21 | 22 | 23 | class Block(pygame.sprite.Sprite): 24 | """ This class represents the ball that moves in a circle. """ 25 | 26 | def __init__(self, color, width, height): 27 | """ Constructor that create's the ball's image. """ 28 | super().__init__() 29 | self.image = pygame.Surface([width, height]) 30 | self.image.fill(color) 31 | self.rect = self.image.get_rect() 32 | 33 | # The "center" the sprite will orbit 34 | self.center_x = 0 35 | self.center_y = 0 36 | 37 | # Current angle in radians 38 | self.angle = 0 39 | 40 | # How far away from the center to orbit, in pixels 41 | self.radius = 0 42 | 43 | # How fast to orbit, in radians per frame 44 | self.speed = 0.05 45 | 46 | def update(self): 47 | """ Update the ball's position. """ 48 | # Calculate a new x, y 49 | self.rect.x = self.radius * math.sin(self.angle) + self.center_x 50 | self.rect.y = self.radius * math.cos(self.angle) + self.center_y 51 | 52 | # Increase the angle in prep for the next round. 53 | self.angle += self.speed 54 | 55 | 56 | class Player(pygame.sprite.Sprite): 57 | """ Class to represent the player. """ 58 | def __init__(self, color, width, height): 59 | """ Create the player image. """ 60 | super().__init__() 61 | self.image = pygame.Surface([width, height]) 62 | self.image.fill(color) 63 | self.rect = self.image.get_rect() 64 | 65 | def update(self): 66 | """Set the user to be where the mouse is. """ 67 | pos = pygame.mouse.get_pos() 68 | self.rect.x = pos[0] 69 | self.rect.y = pos[1] 70 | 71 | # Initialize Pygame 72 | pygame.init() 73 | 74 | # Set the height and width of the screen 75 | SCREEN_WIDTH = 700 76 | SCREEN_HEIGHT = 400 77 | screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) 78 | 79 | # This is a list of 'sprites.' Each block in the program is 80 | # added to this list. The list is managed by a class called 'Group.' 81 | block_list = pygame.sprite.Group() 82 | 83 | # This is a list of every sprite. All blocks and the player block as well. 84 | all_sprites_list = pygame.sprite.Group() 85 | 86 | for i in range(50): 87 | # This represents a block 88 | block = Block(BLACK, 20, 15) 89 | 90 | # Set a random center location for the block to orbit 91 | block.center_x = random.randrange(SCREEN_WIDTH) 92 | block.center_y = random.randrange(SCREEN_HEIGHT) 93 | # Random radius from 10 to 200 94 | block.radius = random.randrange(10, 200) 95 | # Random start angle from 0 to 2pi 96 | block.angle = random.random() * 2 * math.pi 97 | # radians per frame 98 | block.speed = 0.008 99 | # Add the block to the list of objects 100 | block_list.add(block) 101 | all_sprites_list.add(block) 102 | 103 | # Create a RED player block 104 | player = Player(RED, 20, 15) 105 | all_sprites_list.add(player) 106 | 107 | # Loop until the user clicks the close button. 108 | done = False 109 | 110 | # Used to manage how fast the screen updates 111 | clock = pygame.time.Clock() 112 | 113 | score = 0 114 | 115 | # -------- Main Program Loop ----------- 116 | while not done: 117 | for event in pygame.event.get(): 118 | if event.type == pygame.QUIT: 119 | done = True 120 | 121 | all_sprites_list.update() 122 | 123 | # Clear the screen 124 | screen.fill(WHITE) 125 | 126 | # See if the player block has collided with anything. 127 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 128 | 129 | # Check the list of collisions. 130 | for block in blocks_hit_list: 131 | score += 1 132 | print( score ) 133 | 134 | # Draw all the spites 135 | all_sprites_list.draw(screen) 136 | 137 | # Go ahead and update the screen with what we've drawn. 138 | pygame.display.flip() 139 | 140 | # Limit to 60 frames per second 141 | clock.tick(60) 142 | 143 | pygame.quit() 144 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_collect_blocks.py: -------------------------------------------------------------------------------- 1 | """ 2 | Use sprites to collect blocks. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | Explanation video: http://youtu.be/4W2AqUetBi4 10 | """ 11 | import pygame 12 | import random 13 | 14 | # Define some colors 15 | BLACK = ( 0, 0, 0) 16 | WHITE = (255, 255, 255) 17 | RED = (255, 0, 0) 18 | 19 | class Block(pygame.sprite.Sprite): 20 | """ 21 | This class represents the ball. 22 | It derives from the "Sprite" class in Pygame. 23 | """ 24 | 25 | def __init__(self, color, width, height): 26 | """ Constructor. Pass in the color of the block, 27 | and its x and y position. """ 28 | 29 | # Call the parent class (Sprite) constructor 30 | super().__init__() 31 | 32 | # Create an image of the block, and fill it with a color. 33 | # This could also be an image loaded from the disk. 34 | self.image = pygame.Surface([width, height]) 35 | self.image.fill(color) 36 | 37 | # Fetch the rectangle object that has the dimensions of the image 38 | # image. 39 | # Update the position of this object by setting the values 40 | # of rect.x and rect.y 41 | self.rect = self.image.get_rect() 42 | 43 | # Initialize Pygame 44 | pygame.init() 45 | 46 | # Set the height and width of the screen 47 | screen_width = 700 48 | screen_height = 400 49 | screen = pygame.display.set_mode([screen_width, screen_height]) 50 | 51 | # This is a list of 'sprites.' Each block in the program is 52 | # added to this list. The list is managed by a class called 'Group.' 53 | block_list = pygame.sprite.Group() 54 | 55 | # This is a list of every sprite. 56 | # All blocks and the player block as well. 57 | all_sprites_list = pygame.sprite.Group() 58 | 59 | for i in range(50): 60 | # This represents a block 61 | block = Block(BLACK, 20, 15) 62 | 63 | # Set a random location for the block 64 | block.rect.x = random.randrange(screen_width) 65 | block.rect.y = random.randrange(screen_height) 66 | 67 | # Add the block to the list of objects 68 | block_list.add(block) 69 | all_sprites_list.add(block) 70 | 71 | # Create a RED player block 72 | player = Block(RED, 20, 15) 73 | all_sprites_list.add(player) 74 | 75 | # Loop until the user clicks the close button. 76 | done = False 77 | 78 | # Used to manage how fast the screen updates 79 | clock = pygame.time.Clock() 80 | 81 | score = 0 82 | 83 | # -------- Main Program Loop ----------- 84 | while not done: 85 | for event in pygame.event.get(): 86 | if event.type == pygame.QUIT: 87 | done = True 88 | 89 | # Clear the screen 90 | screen.fill(WHITE) 91 | 92 | # Get the current mouse position. This returns the position 93 | # as a list of two numbers. 94 | pos = pygame.mouse.get_pos() 95 | 96 | # Fetch the x and y out of the list, 97 | # just like we'd fetch letters out of a string. 98 | # Set the player object to the mouse location 99 | player.rect.x = pos[0] 100 | player.rect.y = pos[1] 101 | 102 | # See if the player block has collided with anything. 103 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 104 | 105 | # Check the list of collisions. 106 | for block in blocks_hit_list: 107 | score += 1 108 | print(score) 109 | 110 | # Draw all the spites 111 | all_sprites_list.draw(screen) 112 | 113 | # Go ahead and update the screen with what we've drawn. 114 | pygame.display.flip() 115 | 116 | # Limit to 60 frames per second 117 | clock.tick(60) 118 | 119 | pygame.quit() 120 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_collect_blocks_levels.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | import pygame 7 | import random 8 | 9 | # Define some colors 10 | BLACK = ( 0, 0, 0) 11 | WHITE = ( 255, 255, 255) 12 | RED = ( 255, 0, 0) 13 | 14 | # This class represents the ball 15 | # It derives from the "Sprite" class in Pygame 16 | class Block(pygame.sprite.Sprite): 17 | 18 | # Constructor. Pass in the color of the block, 19 | # and its x and y position 20 | def __init__(self, color, width, height): 21 | # Call the parent class (Sprite) constructor 22 | super().__init__() 23 | 24 | # Create an image of the block, and fill it with a color. 25 | # This could also be an image loaded from the disk. 26 | self.image = pygame.Surface([width, height]) 27 | self.image.fill(color) 28 | 29 | # Fetch the rectangle object that has the dimensions of the image 30 | # image. 31 | # Update the position of this object by setting the values 32 | # of rect.x and rect.y 33 | self.rect = self.image.get_rect() 34 | 35 | # Initialize Pygame 36 | pygame.init() 37 | 38 | # Set the height and width of the screen 39 | SCREEN_WIDTH = 700 40 | SCREEN_HEIGHT = 400 41 | screen = pygame.display.set_mode([SCREEN_WIDTH, SCREEN_HEIGHT]) 42 | 43 | # This is a list of 'sprites.' Each block in the program is 44 | # added to this list. The list is managed by a class called 'Group.' 45 | block_list = pygame.sprite.Group() 46 | 47 | # This is a list of every sprite. All blocks and the player block as well. 48 | all_sprites_list = pygame.sprite.Group() 49 | 50 | for i in range(10): 51 | # This represents a block 52 | block = Block(BLACK, 20, 15) 53 | 54 | # Set a random location for the block 55 | block.rect.x = random.randrange(SCREEN_WIDTH) 56 | block.rect.y = random.randrange(SCREEN_HEIGHT) 57 | 58 | # Add the block to the list of objects 59 | block_list.add(block) 60 | all_sprites_list.add(block) 61 | 62 | # Create a RED player block 63 | player = Block(RED, 20, 15) 64 | all_sprites_list.add(player) 65 | 66 | #Loop until the user clicks the close button. 67 | done = False 68 | 69 | # Used to manage how fast the screen updates 70 | clock = pygame.time.Clock() 71 | 72 | # This is a font we use to draw text on the screen (size 36) 73 | font = pygame.font.Font(None, 36) 74 | 75 | # Current score 76 | score = 0 77 | 78 | # Current level 79 | level = 1 80 | 81 | # -------- Main Program Loop ----------- 82 | while not done: 83 | # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT 84 | 85 | for event in pygame.event.get(): # User did something 86 | if event.type == pygame.QUIT: # If user clicked close 87 | done = True # Flag that we are done so we exit this loop 88 | 89 | # Get the current mouse position. This returns the position 90 | # as a list of two numbers. 91 | pos = pygame.mouse.get_pos() 92 | 93 | # ALL EVENT PROCESSING SHOULD GO ABOVE THIS COMMENT 94 | 95 | # ALL GAME LOGIC SHOULD GO BELOW THIS COMMENT 96 | 97 | # Fetch the x and y out of the list, 98 | # just like we'd fetch letters out of a string. 99 | # Set the player object to the mouse location 100 | player.rect.x = pos[0] 101 | player.rect.y = pos[1] 102 | 103 | # See if the player block has collided with anything. 104 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 105 | 106 | # Check the list of collisions. 107 | for block in blocks_hit_list: 108 | score += 1 109 | print( score ) 110 | 111 | # Check to see if all the blocks are gone. 112 | # If they are, level up. 113 | if len(block_list) == 0: 114 | # Add one to the level 115 | level += 1 116 | 117 | # Add more blocks. How many depends on the level. 118 | # Also, an 'if' statement could be used to change what 119 | # happens customized to levels 2, 3, 4, etc. 120 | for i in range(level * 10): 121 | # This represents a block 122 | block = Block(BLACK, 20, 15) 123 | 124 | # Set a random location for the block 125 | block.rect.x = random.randrange(SCREEN_WIDTH) 126 | block.rect.y = random.randrange(SCREEN_HEIGHT) 127 | 128 | # Add the block to the list of objects 129 | block_list.add(block) 130 | all_sprites_list.add(block) 131 | 132 | # ALL GAME LOGIC SHOULD GO ABOVE THIS COMMENT 133 | 134 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 135 | 136 | # Clear the screen 137 | screen.fill(WHITE) 138 | 139 | # Draw all the spites 140 | all_sprites_list.draw(screen) 141 | 142 | text = font.render("Score: "+str(score), True, BLACK) 143 | screen.blit(text, [10, 10]) 144 | 145 | text = font.render("Level: "+str(level), True, BLACK) 146 | screen.blit(text, [10, 40]) 147 | 148 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 149 | 150 | # Go ahead and update the screen with what we've drawn. 151 | pygame.display.flip() 152 | 153 | # Limit to 60 frames per second 154 | clock.tick(60) 155 | 156 | 157 | pygame.quit() 158 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_collect_circle.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | import pygame 7 | import random 8 | 9 | # Define some colors 10 | BLACK = ( 0, 0, 0) 11 | WHITE = ( 255, 255, 255) 12 | RED = ( 255, 0, 0) 13 | 14 | # This class represents the ball 15 | # It derives from the "Sprite" class in Pygame 16 | class Block(pygame.sprite.Sprite): 17 | 18 | # Constructor. Pass in the color of the block, 19 | # and its x and y position 20 | def __init__(self, color, width, height): 21 | # Call the parent class (Sprite) constructor 22 | super().__init__() 23 | 24 | # Create an image of the block, and fill it with a color. 25 | # This could also be an image loaded from the disk. 26 | self.image = pygame.Surface([width, height]) 27 | self.image.fill(WHITE) 28 | self.image.set_colorkey(WHITE) 29 | pygame.draw.ellipse(self.image,color, [0,0,width,height]) 30 | 31 | # Fetch the rectangle object that has the dimensions of the image 32 | # image. 33 | # Update the position of this object by setting the values 34 | # of rect.x and rect.y 35 | self.rect = self.image.get_rect() 36 | 37 | # Initialize Pygame 38 | pygame.init() 39 | 40 | # Set the height and width of the screen 41 | screen_width = 700 42 | screen_height = 400 43 | screen = pygame.display.set_mode([screen_width,screen_height]) 44 | 45 | # This is a list of 'sprites.' Each block in the program is 46 | # added to this list. The list is managed by a class called 'Group.' 47 | block_list = pygame.sprite.Group() 48 | 49 | # This is a list of every sprite. All blocks and the player block as well. 50 | all_sprites_list = pygame.sprite.Group() 51 | 52 | for i in range(50): 53 | # This represents a block 54 | block = Block(BLACK, 20, 15) 55 | 56 | # Set a random location for the block 57 | block.rect.x = random.randrange(screen_width) 58 | block.rect.y = random.randrange(screen_height) 59 | 60 | # Add the block to the list of objects 61 | block_list.add(block) 62 | all_sprites_list.add(block) 63 | 64 | # Create a RED player block 65 | player = Block(RED, 20, 15) 66 | all_sprites_list.add(player) 67 | 68 | #Loop until the user clicks the close button. 69 | done = False 70 | 71 | # Used to manage how fast the screen updates 72 | clock = pygame.time.Clock() 73 | 74 | score = 0 75 | 76 | # -------- Main Program Loop ----------- 77 | while done == False: 78 | for event in pygame.event.get(): # User did something 79 | if event.type == pygame.QUIT: # If user clicked close 80 | done = True # Flag that we are done so we exit this loop 81 | 82 | # Clear the screen 83 | screen.fill(WHITE) 84 | 85 | # Get the current mouse position. This returns the position 86 | # as a list of two numbers. 87 | pos = pygame.mouse.get_pos() 88 | 89 | # Fetch the x and y out of the list, 90 | # just like we'd fetch letters out of a string. 91 | # Set the player object to the mouse location 92 | player.rect.x = pos[0] 93 | player.rect.y = pos[1] 94 | 95 | # See if the player block has collided with anything. 96 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 97 | 98 | # Check the list of collisions. 99 | for block in blocks_hit_list: 100 | score +=1 101 | print( score ) 102 | 103 | # Draw all the spites 104 | all_sprites_list.draw(screen) 105 | 106 | # Go ahead and update the screen with what we've drawn. 107 | pygame.display.flip() 108 | 109 | # Limit to 60 frames per second 110 | clock.tick(60) 111 | 112 | pygame.quit() 113 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_collect_graphic.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to use a sprite backed by a graphic. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | import pygame 11 | import random 12 | 13 | # Define some colors 14 | BLACK = ( 0, 0, 0) 15 | WHITE = ( 255, 255, 255) 16 | RED = ( 255, 0, 0) 17 | 18 | # This class represents the ball 19 | # It derives from the "Sprite" class in Pygame 20 | class Block(pygame.sprite.Sprite): 21 | 22 | # READ BEFORE USING: 23 | # This constructor lets you use any graphic: 24 | # my_sprite = Block("any_graphic.png") 25 | # But if you DON'T want any graphic, use the following instead: 26 | ''' 27 | def __init__(self): 28 | super().__init__() 29 | 30 | self.image = pygame.image.load("my_graphic.png").convert() 31 | 32 | # Set background color to be transparent. Adjust to WHITE if your 33 | # background is WHITE. 34 | self.image.set_colorkey(BLACK) 35 | 36 | self.rect = self.image.get_rect() 37 | ''' 38 | def __init__(self, filename): 39 | # Call the parent class (Sprite) constructor 40 | super().__init__() 41 | 42 | # Create an image of the block, and fill it with a color. 43 | # This could also be an image loaded from the disk. 44 | self.image = pygame.image.load(filename).convert() 45 | 46 | # Set background color to be transparent. Adjust to WHITE if your 47 | # background is WHITE. 48 | self.image.set_colorkey(BLACK) 49 | 50 | # Fetch the rectangle object that has the dimensions of the image 51 | # image. 52 | # Update the position of this object by setting the values 53 | # of rect.x and rect.y 54 | self.rect = self.image.get_rect() 55 | 56 | # Initialize Pygame 57 | pygame.init() 58 | 59 | # Set the height and width of the screen 60 | screen_width = 700 61 | screen_height = 400 62 | screen = pygame.display.set_mode([screen_width, screen_height]) 63 | 64 | # This is a list of 'sprites.' Each block in the program is 65 | # added to this list. The list is managed by a class called 'Group.' 66 | block_list = pygame.sprite.Group() 67 | 68 | # This is a list of every sprite. All blocks and the player block as well. 69 | all_sprites_list = pygame.sprite.Group() 70 | 71 | for i in range(50): 72 | # This represents a block 73 | block = Block("alien.png") 74 | 75 | # Set a random location for the block 76 | block.rect.x = random.randrange(screen_width) 77 | block.rect.y = random.randrange(screen_height) 78 | 79 | # Add the block to the list of objects 80 | block_list.add(block) 81 | all_sprites_list.add(block) 82 | 83 | # Create a RED player block 84 | player = Block("ufo.png") 85 | all_sprites_list.add(player) 86 | 87 | #Loop until the user clicks the close button. 88 | done = False 89 | 90 | # Used to manage how fast the screen updates 91 | clock = pygame.time.Clock() 92 | 93 | score = 0 94 | 95 | # -------- Main Program Loop ----------- 96 | while not done: 97 | for event in pygame.event.get(): # User did something 98 | if event.type == pygame.QUIT: # If user clicked close 99 | done = True # Flag that we are done so we exit this loop 100 | 101 | # Clear the screen 102 | screen.fill(WHITE) 103 | 104 | # Get the current mouse position. This returns the position 105 | # as a list of two numbers. 106 | pos = pygame.mouse.get_pos() 107 | 108 | # Fetch the x and y out of the list, 109 | # just like we'd fetch letters out of a string. 110 | # Set the player object to the mouse location 111 | player.rect.x = pos[0] 112 | player.rect.y = pos[1] 113 | 114 | # See if the player block has collided with anything. 115 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 116 | 117 | # Check the list of collisions. 118 | for block in blocks_hit_list: 119 | score += 1 120 | print( score ) 121 | 122 | # Draw all the spites 123 | all_sprites_list.draw(screen) 124 | 125 | # Limit to 60 frames per second 126 | clock.tick(60) 127 | 128 | # Go ahead and update the screen with what we've drawn. 129 | pygame.display.flip() 130 | 131 | pygame.quit() 132 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_collect_graphic_direction.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to use a sprite backed by a graphic. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | import pygame 11 | import random 12 | 13 | # Define some colors 14 | BLACK = ( 0, 0, 0) 15 | WHITE = ( 255, 255, 255) 16 | RED = ( 255, 0, 0) 17 | 18 | class Player(pygame.sprite.Sprite): 19 | """ The class is the player-controlled sprite. """ 20 | 21 | # -- Methods 22 | def __init__(self, x, y): 23 | """Constructor function""" 24 | # Call the parent's constructor 25 | super().__init__() 26 | 27 | # Load the image looking to the right 28 | self.image_right = pygame.image.load("character.png").convert() 29 | self.image_right.set_colorkey(WHITE) 30 | 31 | # Load the image again, flipping it, so it points left 32 | self.image_left = pygame.transform.flip(pygame.image.load("character.png").convert(), True, False) 33 | self.image_left.set_colorkey(WHITE) 34 | 35 | # By default, point right 36 | self.image = self.image_right 37 | 38 | self.rect = self.image.get_rect() 39 | 40 | # Make our top-left corner the passed-in location. 41 | self.rect.x = x 42 | self.rect.y = y 43 | 44 | # -- Attributes 45 | # Set speed vector 46 | self.change_x = 0 47 | self.change_y = 0 48 | 49 | def changespeed(self, x, y): 50 | """ Change the speed of the player""" 51 | self.change_x += x 52 | self.change_y += y 53 | 54 | # Select if we want the left or right image based on the direction 55 | # we are moving. 56 | if self.change_x > 0: 57 | self.image = self.image_right 58 | elif self.change_x < 0: 59 | self.image = self.image_left 60 | 61 | def update(self): 62 | """ Find a new position for the player""" 63 | self.rect.x += self.change_x 64 | self.rect.y += self.change_y 65 | 66 | # This class represents the ball 67 | # It derives from the "Sprite" class in Pygame 68 | class Block(pygame.sprite.Sprite): 69 | 70 | def __init__(self): 71 | super().__init__() 72 | 73 | self.image = pygame.image.load("alien.png").convert() 74 | 75 | # Set background color to be transparent. Adjust to WHITE if your 76 | # background is WHITE. 77 | self.image.set_colorkey(BLACK) 78 | 79 | self.rect = self.image.get_rect() 80 | 81 | 82 | # Initialize Pygame 83 | pygame.init() 84 | 85 | # Set the height and width of the screen 86 | screen_width = 700 87 | screen_height = 400 88 | screen = pygame.display.set_mode([screen_width, screen_height]) 89 | 90 | # This is a list of 'sprites.' Each block in the program is 91 | # added to this list. The list is managed by a class called 'Group.' 92 | block_list = pygame.sprite.Group() 93 | 94 | # This is a list of every sprite. All blocks and the player block as well. 95 | all_sprites_list = pygame.sprite.Group() 96 | 97 | for i in range(50): 98 | # This represents a block 99 | block = Block() 100 | 101 | # Set a random location for the block 102 | block.rect.x = random.randrange(screen_width) 103 | block.rect.y = random.randrange(screen_height) 104 | 105 | # Add the block to the list of objects 106 | block_list.add(block) 107 | all_sprites_list.add(block) 108 | 109 | # Create a RED player block 110 | player = Player(50, 50) 111 | all_sprites_list.add(player) 112 | 113 | #Loop until the user clicks the close button. 114 | done = False 115 | 116 | # Used to manage how fast the screen updates 117 | clock = pygame.time.Clock() 118 | 119 | score = 0 120 | 121 | # -------- Main Program Loop ----------- 122 | while not done: 123 | for event in pygame.event.get(): # User did something 124 | if event.type == pygame.QUIT: # If user clicked close 125 | done = True # Flag that we are done so we exit this loop 126 | # Set the speed based on the key pressed 127 | elif event.type == pygame.KEYDOWN: 128 | if event.key == pygame.K_LEFT: 129 | player.changespeed(-3, 0) 130 | elif event.key == pygame.K_RIGHT: 131 | player.changespeed(3, 0) 132 | elif event.key == pygame.K_UP: 133 | player.changespeed(0, -3) 134 | elif event.key == pygame.K_DOWN: 135 | player.changespeed(0, 3) 136 | 137 | # Reset speed when key goes up 138 | elif event.type == pygame.KEYUP: 139 | if event.key == pygame.K_LEFT: 140 | player.changespeed(3, 0) 141 | elif event.key == pygame.K_RIGHT: 142 | player.changespeed(-3, 0) 143 | elif event.key == pygame.K_UP: 144 | player.changespeed(0, 3) 145 | elif event.key == pygame.K_DOWN: 146 | player.changespeed(0, -3) 147 | 148 | # Clear the screen 149 | screen.fill(WHITE) 150 | 151 | all_sprites_list.update() 152 | 153 | # See if the player block has collided with anything. 154 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 155 | 156 | # Check the list of collisions. 157 | for block in blocks_hit_list: 158 | score += 1 159 | print( score ) 160 | 161 | # Draw all the spites 162 | all_sprites_list.draw(screen) 163 | 164 | # Limit to 60 frames per second 165 | clock.tick(60) 166 | 167 | # Go ahead and update the screen with what we've drawn. 168 | pygame.display.flip() 169 | 170 | pygame.quit() 171 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_rotating.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to use a sprite backed by a graphic. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | import pygame 11 | import random 12 | 13 | # Define some colors 14 | BLACK = ( 0, 0, 0) 15 | WHITE = ( 255, 255, 255) 16 | RED = ( 255, 0, 0) 17 | 18 | # This class represents the ball 19 | # It derives from the "Sprite" class in Pygame 20 | class Block(pygame.sprite.Sprite): 21 | 22 | # READ BEFORE USING: 23 | # This constructor lets you use any graphic: 24 | # my_sprite = Block("any_graphic.png") 25 | # But if you DON'T want any graphic, use the following instead: 26 | ''' 27 | def __init__(self): 28 | super().__init__() 29 | 30 | self.image = pygame.image.load("my_graphic.png").convert() 31 | 32 | # Set background color to be transparent. Adjust to WHITE if your 33 | # background is WHITE. 34 | self.image.set_colorkey(BLACK) 35 | 36 | self.rect = self.image.get_rect() 37 | ''' 38 | def __init__(self, filename, colorkey): 39 | # Call the parent class (Sprite) constructor 40 | super().__init__() 41 | 42 | # Create an image of the block, and fill it with a color. 43 | # This could also be an image loaded from the disk. 44 | self.original_image = pygame.image.load(filename).convert() 45 | self.image = self.original_image 46 | 47 | # Set background color to be transparent. Adjust to WHITE if your 48 | # background is WHITE. 49 | self.image.set_colorkey(colorkey) 50 | 51 | # Fetch the rectangle object that has the dimensions of the image 52 | # image. 53 | # Update the position of this object by setting the values 54 | # of rect.x and rect.y 55 | self.rect = self.image.get_rect() 56 | 57 | self.angle = 0 58 | self.angle_change = 0 59 | 60 | def update(self): 61 | self.image = pygame.transform.rotate(self.original_image, self.angle) 62 | self.angle += self.angle_change 63 | self.angle = self.angle % 360 64 | 65 | # Initialize Pygame 66 | pygame.init() 67 | 68 | # Set the height and width of the screen 69 | screen_width = 700 70 | screen_height = 400 71 | screen = pygame.display.set_mode([screen_width, screen_height]) 72 | 73 | # This is a list of 'sprites.' Each block in the program is 74 | # added to this list. The list is managed by a class called 'Group.' 75 | block_list = pygame.sprite.Group() 76 | 77 | # This is a list of every sprite. All blocks and the player block as well. 78 | all_sprites_list = pygame.sprite.Group() 79 | 80 | for i in range(50): 81 | # This represents a block 82 | block = Block("alien.png", BLACK) 83 | 84 | # Set a random location for the block 85 | block.rect.x = random.randrange(screen_width) 86 | block.rect.y = random.randrange(screen_height) 87 | block.angle = random.randrange(360) 88 | block.angle_change = random.randrange(-1, 2) 89 | # Add the block to the list of objects 90 | block_list.add(block) 91 | all_sprites_list.add(block) 92 | 93 | # Create a RED player block 94 | player = Block("ufo.png", BLACK) 95 | player.angle_change = 0 96 | all_sprites_list.add(player) 97 | 98 | #Loop until the user clicks the close button. 99 | done = False 100 | 101 | # Used to manage how fast the screen updates 102 | clock = pygame.time.Clock() 103 | 104 | score = 0 105 | 106 | # -------- Main Program Loop ----------- 107 | while not done: 108 | for event in pygame.event.get(): # User did something 109 | if event.type == pygame.QUIT: # If user clicked close 110 | done = True # Flag that we are done so we exit this loop 111 | 112 | # Clear the screen 113 | screen.fill(WHITE) 114 | 115 | # Get the current mouse position. This returns the position 116 | # as a list of two numbers. 117 | pos = pygame.mouse.get_pos() 118 | 119 | # Fetch the x and y out of the list, 120 | # just like we'd fetch letters out of a string. 121 | # Set the player object to the mouse location 122 | player.rect.x = pos[0] 123 | player.rect.y = pos[1] 124 | 125 | all_sprites_list.update() 126 | 127 | # See if the player block has collided with anything. 128 | blocks_hit_list = pygame.sprite.spritecollide(player, block_list, True) 129 | 130 | # Check the list of collisions. 131 | for block in blocks_hit_list: 132 | score += 1 133 | print( score ) 134 | 135 | # Draw all the spites 136 | all_sprites_list.draw(screen) 137 | 138 | # Limit to 60 frames per second 139 | clock.tick(60) 140 | 141 | # Go ahead and update the screen with what we've drawn. 142 | pygame.display.flip() 143 | 144 | pygame.quit() 145 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/background_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/sprite_sheets/background_01.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/background_01.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | eJzt0DcOgCAAhWF7W+xlsZcTeAJ3I/c/jW9gMAZQNG6+5NsIf0BR/v2TWwoZR/5h1waHw5W8K4KYIbnZJQ+7BhRgnliC7iTo+hBQ4UX33Lzqiv5ZBY3SJbvLy+4M3oOu7HvJoVtCRdWwMazQQMvQMbo9DBwjPbMDEeEJaQ== 12 | 13 | 14 | 15 | 16 | eJxjYBgFo2DwgJiBdsAgBC4E+MjAG4+cOg4aFwgiwDcF4mgCZpADEgjwSQW8RKjho9AObEAah3gclF4MxDIEzAAANcYE7A== 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/background_02.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/sprite_sheets/background_02.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/background_02.tmx: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | eJxjYBh5YDUQr8GC19LY3rlAfAGIlwHxPCj7Ap3sXTbA9sLsnEcney8gYZj99LB3HhQjhzW9/DsPCdPaXgCP4yHp 12 | 13 | 14 | 15 | 16 | eJxjYBhY8BkHPVjBRiDehAdvppG9i4F4CRAfguIlaPyldLL3DRKb1va+YUD4k572ItsHY8PcQWt7kcMaOa5x2fsaC36FRewlDv37gfgAHnwQhz4AiyQ6LA== 17 | 18 | 19 | 20 | 21 | eJxjYBgF9ASHcdDEgCNEsAcboMS/j4hg0wJ8IMB+gUcvsj9XMZDm339o7BVYxIkBO0hUjw62EaEGAImLFUA= 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/constants.py: -------------------------------------------------------------------------------- 1 | """ 2 | Global constants 3 | """ 4 | 5 | # Colors 6 | BLACK = ( 0, 0, 0) 7 | WHITE = ( 255, 255, 255) 8 | BLUE = ( 0, 0, 255) 9 | 10 | # Screen dimensions 11 | SCREEN_WIDTH = 800 12 | SCREEN_HEIGHT = 600 -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/levels.py: -------------------------------------------------------------------------------- 1 | import pygame 2 | 3 | import constants 4 | import platforms 5 | 6 | class Level(): 7 | """ This is a generic super-class used to define a level. 8 | Create a child class for each level with level-specific 9 | info. """ 10 | 11 | def __init__(self, player): 12 | """ Constructor. Pass in a handle to player. Needed for when moving platforms 13 | collide with the player. """ 14 | 15 | # Lists of sprites used in all levels. Add or remove 16 | # lists as needed for your game. 17 | self.platform_list = None 18 | self.enemy_list = None 19 | 20 | # Background image 21 | self.background = None 22 | 23 | # How far this world has been scrolled left/right 24 | self.world_shift = 0 25 | self.level_limit = -1000 26 | self.platform_list = pygame.sprite.Group() 27 | self.enemy_list = pygame.sprite.Group() 28 | self.player = player 29 | 30 | # Update everythign on this level 31 | def update(self): 32 | """ Update everything in this level.""" 33 | self.platform_list.update() 34 | self.enemy_list.update() 35 | 36 | def draw(self, screen): 37 | """ Draw everything on this level. """ 38 | 39 | # Draw the background 40 | # We don't shift the background as much as the sprites are shifted 41 | # to give a feeling of depth. 42 | screen.fill(constants.BLUE) 43 | screen.blit(self.background,(self.world_shift // 3,0)) 44 | 45 | # Draw all the sprite lists that we have 46 | self.platform_list.draw(screen) 47 | self.enemy_list.draw(screen) 48 | 49 | def shift_world(self, shift_x): 50 | """ When the user moves left/right and we need to scroll everything: """ 51 | 52 | # Keep track of the shift amount 53 | self.world_shift += shift_x 54 | 55 | # Go through all the sprite lists and shift 56 | for platform in self.platform_list: 57 | platform.rect.x += shift_x 58 | 59 | for enemy in self.enemy_list: 60 | enemy.rect.x += shift_x 61 | 62 | # Create platforms for the level 63 | class Level_01(Level): 64 | """ Definition for level 1. """ 65 | 66 | def __init__(self, player): 67 | """ Create level 1. """ 68 | 69 | # Call the parent constructor 70 | Level.__init__(self, player) 71 | 72 | self.background = pygame.image.load("background_01.png").convert() 73 | self.background.set_colorkey(constants.WHITE) 74 | self.level_limit = -2500 75 | 76 | # Array with type of platform, and x, y location of the platform. 77 | level = [ [platforms.GRASS_LEFT, 500, 500], 78 | [platforms.GRASS_MIDDLE, 570, 500], 79 | [platforms.GRASS_RIGHT, 640, 500], 80 | [platforms.GRASS_LEFT, 800, 400], 81 | [platforms.GRASS_MIDDLE, 870, 400], 82 | [platforms.GRASS_RIGHT, 940, 400], 83 | [platforms.GRASS_LEFT, 1000, 500], 84 | [platforms.GRASS_MIDDLE, 1070, 500], 85 | [platforms.GRASS_RIGHT, 1140, 500], 86 | [platforms.STONE_PLATFORM_LEFT, 1120, 280], 87 | [platforms.STONE_PLATFORM_MIDDLE, 1190, 280], 88 | [platforms.STONE_PLATFORM_RIGHT, 1260, 280], 89 | ] 90 | 91 | 92 | # Go through the array above and add platforms 93 | for platform in level: 94 | block = platforms.Platform(platform[0]) 95 | block.rect.x = platform[1] 96 | block.rect.y = platform[2] 97 | block.player = self.player 98 | self.platform_list.add(block) 99 | 100 | # Add a custom moving platform 101 | block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) 102 | block.rect.x = 1350 103 | block.rect.y = 280 104 | block.boundary_left = 1350 105 | block.boundary_right = 1600 106 | block.change_x = 1 107 | block.player = self.player 108 | block.level = self 109 | self.platform_list.add(block) 110 | 111 | 112 | # Create platforms for the level 113 | class Level_02(Level): 114 | """ Definition for level 2. """ 115 | 116 | def __init__(self, player): 117 | """ Create level 1. """ 118 | 119 | # Call the parent constructor 120 | Level.__init__(self, player) 121 | 122 | self.background = pygame.image.load("background_02.png").convert() 123 | self.background.set_colorkey(constants.WHITE) 124 | self.level_limit = -1000 125 | 126 | # Array with type of platform, and x, y location of the platform. 127 | level = [ [platforms.STONE_PLATFORM_LEFT, 500, 550], 128 | [platforms.STONE_PLATFORM_MIDDLE, 570, 550], 129 | [platforms.STONE_PLATFORM_RIGHT, 640, 550], 130 | [platforms.GRASS_LEFT, 800, 400], 131 | [platforms.GRASS_MIDDLE, 870, 400], 132 | [platforms.GRASS_RIGHT, 940, 400], 133 | [platforms.GRASS_LEFT, 1000, 500], 134 | [platforms.GRASS_MIDDLE, 1070, 500], 135 | [platforms.GRASS_RIGHT, 1140, 500], 136 | [platforms.STONE_PLATFORM_LEFT, 1120, 280], 137 | [platforms.STONE_PLATFORM_MIDDLE, 1190, 280], 138 | [platforms.STONE_PLATFORM_RIGHT, 1260, 280], 139 | ] 140 | 141 | 142 | # Go through the array above and add platforms 143 | for platform in level: 144 | block = platforms.Platform(platform[0]) 145 | block.rect.x = platform[1] 146 | block.rect.y = platform[2] 147 | block.player = self.player 148 | self.platform_list.add(block) 149 | 150 | # Add a custom moving platform 151 | block = platforms.MovingPlatform(platforms.STONE_PLATFORM_MIDDLE) 152 | block.rect.x = 1500 153 | block.rect.y = 300 154 | block.boundary_top = 100 155 | block.boundary_bottom = 550 156 | block.change_y = -1 157 | block.player = self.player 158 | block.level = self 159 | self.platform_list.add(block) 160 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/p1_walk.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/sprite_sheets/p1_walk.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/platform_scroller.py: -------------------------------------------------------------------------------- 1 | """ 2 | Sample Python/Pygame Programs 3 | Simpson College Computer Science 4 | http://programarcadegames.com/ 5 | http://simpson.edu/computer-science/ 6 | 7 | Main module for platform scroller example. 8 | 9 | From: 10 | http://programarcadegames.com/python_examples/sprite_sheets/ 11 | 12 | Explanation video: http://youtu.be/czBDKWJqOao 13 | 14 | Part of a series: 15 | http://programarcadegames.com/python_examples/f.php?file=move_with_walls_example.py 16 | http://programarcadegames.com/python_examples/f.php?file=maze_runner.py 17 | http://programarcadegames.com/python_examples/f.php?file=platform_jumper.py 18 | http://programarcadegames.com/python_examples/f.php?file=platform_scroller.py 19 | http://programarcadegames.com/python_examples/f.php?file=platform_moving.py 20 | http://programarcadegames.com/python_examples/sprite_sheets/ 21 | 22 | Game art from Kenney.nl: 23 | http://opengameart.org/content/platformer-art-deluxe 24 | 25 | """ 26 | 27 | import pygame 28 | 29 | import constants 30 | import levels 31 | 32 | from player import Player 33 | 34 | def main(): 35 | """ Main Program """ 36 | pygame.init() 37 | 38 | # Set the height and width of the screen 39 | size = [constants.SCREEN_WIDTH, constants.SCREEN_HEIGHT] 40 | screen = pygame.display.set_mode(size) 41 | 42 | pygame.display.set_caption("Platformer with sprite sheets") 43 | 44 | # Create the player 45 | player = Player() 46 | 47 | # Create all the levels 48 | level_list = [] 49 | level_list.append(levels.Level_01(player)) 50 | level_list.append(levels.Level_02(player)) 51 | 52 | # Set the current level 53 | current_level_no = 0 54 | current_level = level_list[current_level_no] 55 | 56 | active_sprite_list = pygame.sprite.Group() 57 | player.level = current_level 58 | 59 | player.rect.x = 340 60 | player.rect.y = constants.SCREEN_HEIGHT - player.rect.height 61 | active_sprite_list.add(player) 62 | 63 | #Loop until the user clicks the close button. 64 | done = False 65 | 66 | # Used to manage how fast the screen updates 67 | clock = pygame.time.Clock() 68 | 69 | # -------- Main Program Loop ----------- 70 | while not done: 71 | for event in pygame.event.get(): # User did something 72 | if event.type == pygame.QUIT: # If user clicked close 73 | done = True # Flag that we are done so we exit this loop 74 | 75 | if event.type == pygame.KEYDOWN: 76 | if event.key == pygame.K_LEFT: 77 | player.go_left() 78 | if event.key == pygame.K_RIGHT: 79 | player.go_right() 80 | if event.key == pygame.K_UP: 81 | player.jump() 82 | 83 | if event.type == pygame.KEYUP: 84 | if event.key == pygame.K_LEFT and player.change_x < 0: 85 | player.stop() 86 | if event.key == pygame.K_RIGHT and player.change_x > 0: 87 | player.stop() 88 | 89 | # Update the player. 90 | active_sprite_list.update() 91 | 92 | # Update items in the level 93 | current_level.update() 94 | 95 | # If the player gets near the right side, shift the world left (-x) 96 | if player.rect.right >= 500: 97 | diff = player.rect.right - 500 98 | player.rect.right = 500 99 | current_level.shift_world(-diff) 100 | 101 | # If the player gets near the left side, shift the world right (+x) 102 | if player.rect.left <= 120: 103 | diff = 120 - player.rect.left 104 | player.rect.left = 120 105 | current_level.shift_world(diff) 106 | 107 | # If the player gets to the end of the level, go to the next level 108 | current_position = player.rect.x + current_level.world_shift 109 | if current_position < current_level.level_limit: 110 | player.rect.x = 120 111 | if current_level_no < len(level_list)-1: 112 | current_level_no += 1 113 | current_level = level_list[current_level_no] 114 | player.level = current_level 115 | 116 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 117 | current_level.draw(screen) 118 | active_sprite_list.draw(screen) 119 | 120 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 121 | 122 | # Limit to 60 frames per second 123 | clock.tick(60) 124 | 125 | # Go ahead and update the screen with what we've drawn. 126 | pygame.display.flip() 127 | 128 | # Be IDLE friendly. If you forget this line, the program will 'hang' 129 | # on exit. 130 | pygame.quit() 131 | 132 | if __name__ == "__main__": 133 | main() 134 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/platforms.py: -------------------------------------------------------------------------------- 1 | """ 2 | Module for managing platforms. 3 | """ 4 | import pygame 5 | 6 | from spritesheet_functions import SpriteSheet 7 | 8 | # These constants define our platform types: 9 | # Name of file 10 | # X location of sprite 11 | # Y location of sprite 12 | # Width of sprite 13 | # Height of sprite 14 | 15 | GRASS_LEFT = (576, 720, 70, 70) 16 | GRASS_RIGHT = (576, 576, 70, 70) 17 | GRASS_MIDDLE = (504, 576, 70, 70) 18 | STONE_PLATFORM_LEFT = (432, 720, 70, 40) 19 | STONE_PLATFORM_MIDDLE = (648, 648, 70, 40) 20 | STONE_PLATFORM_RIGHT = (792, 648, 70, 40) 21 | 22 | class Platform(pygame.sprite.Sprite): 23 | """ Platform the user can jump on """ 24 | 25 | def __init__(self, sprite_sheet_data): 26 | """ Platform constructor. Assumes constructed with user passing in 27 | an array of 5 numbers like what's defined at the top of this 28 | code. """ 29 | super().__init__() 30 | 31 | sprite_sheet = SpriteSheet("tiles_spritesheet.png") 32 | # Grab the image for this platform 33 | self.image = sprite_sheet.get_image(sprite_sheet_data[0], 34 | sprite_sheet_data[1], 35 | sprite_sheet_data[2], 36 | sprite_sheet_data[3]) 37 | 38 | self.rect = self.image.get_rect() 39 | 40 | 41 | class MovingPlatform(Platform): 42 | """ This is a fancier platform that can actually move. """ 43 | 44 | def __init__(self, sprite_sheet_data): 45 | 46 | super().__init__(sprite_sheet_data) 47 | 48 | self.change_x = 0 49 | self.change_y = 0 50 | 51 | self.boundary_top = 0 52 | self.boundary_bottom = 0 53 | self.boundary_left = 0 54 | self.boundary_right = 0 55 | 56 | self.level = None 57 | self.player = None 58 | 59 | def update(self): 60 | """ Move the platform. 61 | If the player is in the way, it will shove the player 62 | out of the way. This does NOT handle what happens if a 63 | platform shoves a player into another object. Make sure 64 | moving platforms have clearance to push the player around 65 | or add code to handle what happens if they don't. """ 66 | 67 | 68 | # Move left/right 69 | self.rect.x += self.change_x 70 | 71 | # See if we hit the player 72 | hit = pygame.sprite.collide_rect(self, self.player) 73 | if hit: 74 | # We did hit the player. Shove the player around and 75 | # assume he/she won't hit anything else. 76 | 77 | # If we are moving right, set our right side 78 | # to the left side of the item we hit 79 | if self.change_x < 0: 80 | self.player.rect.right = self.rect.left 81 | else: 82 | # Otherwise if we are moving left, do the opposite. 83 | self.player.rect.left = self.rect.right 84 | 85 | # Move up/down 86 | self.rect.y += self.change_y 87 | 88 | # Check and see if we the player 89 | hit = pygame.sprite.collide_rect(self, self.player) 90 | if hit: 91 | # We did hit the player. Shove the player around and 92 | # assume he/she won't hit anything else. 93 | 94 | # Reset our position based on the top/bottom of the object. 95 | if self.change_y < 0: 96 | self.player.rect.bottom = self.rect.top 97 | else: 98 | self.player.rect.top = self.rect.bottom 99 | 100 | # Check the boundaries and see if we need to reverse 101 | # direction. 102 | if self.rect.bottom > self.boundary_bottom or self.rect.top < self.boundary_top: 103 | self.change_y *= -1 104 | 105 | cur_pos = self.rect.x - self.level.world_shift 106 | if cur_pos < self.boundary_left or cur_pos > self.boundary_right: 107 | self.change_x *= -1 108 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/player.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module is used to hold the Player class. The Player represents the user- 3 | controlled sprite on the screen. 4 | """ 5 | import pygame 6 | 7 | import constants 8 | 9 | from platforms import MovingPlatform 10 | from spritesheet_functions import SpriteSheet 11 | 12 | class Player(pygame.sprite.Sprite): 13 | """ This class represents the bar at the bottom that the player 14 | controls. """ 15 | 16 | 17 | # -- Methods 18 | def __init__(self): 19 | """ Constructor function """ 20 | 21 | # Call the parent's constructor 22 | super().__init__() 23 | 24 | # -- Attributes 25 | # Set speed vector of player 26 | self.change_x = 0 27 | self.change_y = 0 28 | 29 | # This holds all the images for the animated walk left/right 30 | # of our player 31 | self.walking_frames_l = [] 32 | self.walking_frames_r = [] 33 | 34 | # What direction is the player facing? 35 | self.direction = "R" 36 | 37 | # List of sprites we can bump against 38 | self.level = None 39 | 40 | sprite_sheet = SpriteSheet("p1_walk.png") 41 | # Load all the right facing images into a list 42 | image = sprite_sheet.get_image(0, 0, 66, 90) 43 | self.walking_frames_r.append(image) 44 | image = sprite_sheet.get_image(66, 0, 66, 90) 45 | self.walking_frames_r.append(image) 46 | image = sprite_sheet.get_image(132, 0, 67, 90) 47 | self.walking_frames_r.append(image) 48 | image = sprite_sheet.get_image(0, 93, 66, 90) 49 | self.walking_frames_r.append(image) 50 | image = sprite_sheet.get_image(66, 93, 66, 90) 51 | self.walking_frames_r.append(image) 52 | image = sprite_sheet.get_image(132, 93, 72, 90) 53 | self.walking_frames_r.append(image) 54 | image = sprite_sheet.get_image(0, 186, 70, 90) 55 | self.walking_frames_r.append(image) 56 | 57 | # Load all the right facing images, then flip them 58 | # to face left. 59 | image = sprite_sheet.get_image(0, 0, 66, 90) 60 | image = pygame.transform.flip(image, True, False) 61 | self.walking_frames_l.append(image) 62 | image = sprite_sheet.get_image(66, 0, 66, 90) 63 | image = pygame.transform.flip(image, True, False) 64 | self.walking_frames_l.append(image) 65 | image = sprite_sheet.get_image(132, 0, 67, 90) 66 | image = pygame.transform.flip(image, True, False) 67 | self.walking_frames_l.append(image) 68 | image = sprite_sheet.get_image(0, 93, 66, 90) 69 | image = pygame.transform.flip(image, True, False) 70 | self.walking_frames_l.append(image) 71 | image = sprite_sheet.get_image(66, 93, 66, 90) 72 | image = pygame.transform.flip(image, True, False) 73 | self.walking_frames_l.append(image) 74 | image = sprite_sheet.get_image(132, 93, 72, 90) 75 | image = pygame.transform.flip(image, True, False) 76 | self.walking_frames_l.append(image) 77 | image = sprite_sheet.get_image(0, 186, 70, 90) 78 | image = pygame.transform.flip(image, True, False) 79 | self.walking_frames_l.append(image) 80 | 81 | # Set the image the player starts with 82 | self.image = self.walking_frames_r[0] 83 | 84 | # Set a reference to the image rect. 85 | self.rect = self.image.get_rect() 86 | 87 | def update(self): 88 | """ Move the player. """ 89 | # Gravity 90 | self.calc_grav() 91 | 92 | # Move left/right 93 | self.rect.x += self.change_x 94 | pos = self.rect.x + self.level.world_shift 95 | if self.direction == "R": 96 | frame = (pos // 30) % len(self.walking_frames_r) 97 | self.image = self.walking_frames_r[frame] 98 | else: 99 | frame = (pos // 30) % len(self.walking_frames_l) 100 | self.image = self.walking_frames_l[frame] 101 | 102 | # See if we hit anything 103 | block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False) 104 | for block in block_hit_list: 105 | # If we are moving right, 106 | # set our right side to the left side of the item we hit 107 | if self.change_x > 0: 108 | self.rect.right = block.rect.left 109 | elif self.change_x < 0: 110 | # Otherwise if we are moving left, do the opposite. 111 | self.rect.left = block.rect.right 112 | 113 | # Move up/down 114 | self.rect.y += self.change_y 115 | 116 | # Check and see if we hit anything 117 | block_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False) 118 | for block in block_hit_list: 119 | 120 | # Reset our position based on the top/bottom of the object. 121 | if self.change_y > 0: 122 | self.rect.bottom = block.rect.top 123 | elif self.change_y < 0: 124 | self.rect.top = block.rect.bottom 125 | 126 | # Stop our vertical movement 127 | self.change_y = 0 128 | 129 | if isinstance(block, MovingPlatform): 130 | self.rect.x += block.change_x 131 | 132 | def calc_grav(self): 133 | """ Calculate effect of gravity. """ 134 | if self.change_y == 0: 135 | self.change_y = 1 136 | else: 137 | self.change_y += .35 138 | 139 | # See if we are on the ground. 140 | if self.rect.y >= constants.SCREEN_HEIGHT - self.rect.height and self.change_y >= 0: 141 | self.change_y = 0 142 | self.rect.y = constants.SCREEN_HEIGHT - self.rect.height 143 | 144 | def jump(self): 145 | """ Called when user hits 'jump' button. """ 146 | 147 | # move down a bit and see if there is a platform below us. 148 | # Move down 2 pixels because it doesn't work well if we only move down 1 149 | # when working with a platform moving down. 150 | self.rect.y += 2 151 | platform_hit_list = pygame.sprite.spritecollide(self, self.level.platform_list, False) 152 | self.rect.y -= 2 153 | 154 | # If it is ok to jump, set our speed upwards 155 | if len(platform_hit_list) > 0 or self.rect.bottom >= constants.SCREEN_HEIGHT: 156 | self.change_y = -10 157 | 158 | # Player-controlled movement: 159 | def go_left(self): 160 | """ Called when the user hits the left arrow. """ 161 | self.change_x = -6 162 | self.direction = "L" 163 | 164 | def go_right(self): 165 | """ Called when the user hits the right arrow. """ 166 | self.change_x = 6 167 | self.direction = "R" 168 | 169 | def stop(self): 170 | """ Called when the user lets off the keyboard. """ 171 | self.change_x = 0 172 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/sheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/sprite_sheets/sheet.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/spritesheet_functions.py: -------------------------------------------------------------------------------- 1 | """ 2 | This module is used to pull individual sprites from sprite sheets. 3 | """ 4 | import pygame 5 | 6 | import constants 7 | 8 | class SpriteSheet(object): 9 | """ Class used to grab images out of a sprite sheet. """ 10 | 11 | def __init__(self, file_name): 12 | """ Constructor. Pass in the file name of the sprite sheet. """ 13 | 14 | # Load the sprite sheet. 15 | self.sprite_sheet = pygame.image.load(file_name).convert() 16 | 17 | 18 | def get_image(self, x, y, width, height): 19 | """ Grab a single image out of a larger spritesheet 20 | Pass in the x, y location of the sprite 21 | and the width and height of the sprite. """ 22 | 23 | # Create a new blank image 24 | image = pygame.Surface([width, height]).convert() 25 | 26 | # Copy the sprite from the large sheet onto the smaller image 27 | image.blit(self.sprite_sheet, (0, 0), (x, y, width, height)) 28 | 29 | # Assuming black works as the transparent color 30 | image.set_colorkey(constants.BLACK) 31 | 32 | # Return the image 33 | return image 34 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/sprite_sheets/tiles_spritesheet.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/sprite_sheets/tiles_spritesheet.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/super_villains.txt: -------------------------------------------------------------------------------- 1 | Adolphus of Helborne 2 | Aldric Foxe 3 | Amanita Maleficant 4 | Aphra the Vicious 5 | Arachne the Gruesome 6 | Astarte Hellebore 7 | Brutus the Gruesome 8 | Cain of Avernus 9 | Claude Avernus 10 | Claude del Winter 11 | Claudia the Siren 12 | Cornelius Frostheim 13 | Cornelius Rackham 14 | Damian Loveless 15 | Draco Frostheim 16 | Draco of Viridian 17 | Draco the Unpleasant 18 | Edgar the Grim 19 | Editha the Festering 20 | Edric von Corvidus 21 | Elvira the Blasphemous 22 | Emelda la Garvel 23 | Eustace the Unclean 24 | Gaspard the Blasphemous 25 | Gitana Regan 26 | Goneril the Spider 27 | Griselda von Tempest 28 | Hagar Bloodcrow 29 | Helga of Loveless 30 | Hildegarde the Shrew 31 | Hugo Cromwell 32 | Hugo Frostheim 33 | Hugo the Repellent 34 | Huldah Harloch 35 | Humbert the Grotesque 36 | Isadora Cygne 37 | Jezebelle the Hellcat 38 | Jezebelle the Vile 39 | Kali la Mauvaise 40 | Kyril Helborne 41 | Kyril the Obscene 42 | Lavinia Nyx 43 | Lavinia the Vile 44 | Lilith the Hellcat 45 | Maudetta la Helborne 46 | Maudetta von Drear 47 | Medusa von Harloch 48 | Morgiana Darkstar 49 | Morgiana Malheur 50 | Morgiana the Shrew 51 | Narcissa de Bloodcrow 52 | Narcissa Falkwing 53 | Narcissa the Fury 54 | Natasha the Manic 55 | Natasha the Shrivelled 56 | Octavia the Siren 57 | Octavian Falkwing 58 | Octavian the Lecherous 59 | Odile Helborne 60 | Portia the Bilious 61 | Ravenna von Malheur 62 | Renard the Torturer 63 | Rodolphus the Vicious 64 | Rodrigo Loveless 65 | Rudolf the Savage 66 | Rufina Loveless 67 | Rufus Hades 68 | Rufus Sangria 69 | Rufus von Wynter 70 | Rupert Corvidus 71 | Rupert Helborne 72 | Rupert the Enchanter 73 | Scarletina of Grimoire 74 | Severin de Helborne 75 | Severin the Black 76 | Severin the Unpleasant 77 | Severina Helborne 78 | The Barbarous Harlot 79 | The Branded Shadow 80 | The Deadly Raven 81 | The Dire Hellspawn 82 | The Forsaken Succubus 83 | The Ill-Mannered Fury 84 | The Infamous Devourer 85 | The Obscene Libertine 86 | The Putrid Cannibal 87 | The Putrid Ogress 88 | The Soulless Toad 89 | The Vindictive Fury 90 | Theodora the Wicked 91 | Titania the Banshee 92 | Ulysses de Darkmoon 93 | Ulysses de Nyx 94 | Ulysses Falkwing 95 | Varvara Tempest 96 | Victor Livingston 97 | Vidar the Manic 98 | Vidar the Ogre 99 | Vladimir Noire 100 | Yasmin del Corvida 101 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/text_rotate.py: -------------------------------------------------------------------------------- 1 | """ 2 | Simple graphics demo 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | 11 | # Import a library of functions called 'pygame' 12 | import pygame 13 | 14 | # Initialize the game engine 15 | pygame.init() 16 | 17 | # Define some colors 18 | BLACK = (0, 0, 0) 19 | WHITE = (255, 255, 255) 20 | BLUE = (0, 0, 255) 21 | GREEN = (0, 255, 0) 22 | RED = (255, 0, 0) 23 | 24 | PI = 3.141592653 25 | 26 | # Set the height and width of the screen 27 | size = (400, 500) 28 | screen = pygame.display.set_mode(size) 29 | 30 | pygame.display.set_caption("Rotate Text") 31 | 32 | # Loop until the user clicks the close button. 33 | done = False 34 | clock = pygame.time.Clock() 35 | 36 | text_rotate_degrees = 0 37 | 38 | # Loop as long as done == False 39 | while not done: 40 | 41 | for event in pygame.event.get(): # User did something 42 | if event.type == pygame.QUIT: # If user clicked close 43 | done = True # Flag that we are done so we exit this loop 44 | 45 | # All drawing code happens after the for loop and but 46 | # inside the main while not done loop. 47 | 48 | # Clear the screen and set the screen background 49 | screen.fill(WHITE) 50 | 51 | # Draw some borders 52 | pygame.draw.line(screen, BLACK, [100,50], [200, 50]) 53 | pygame.draw.line(screen, BLACK, [100,50], [100, 150]) 54 | 55 | # Select the font to use, size, bold, italics 56 | font = pygame.font.SysFont('Calibri', 25, True, False) 57 | 58 | # Sideways text 59 | text = font.render("Sideways text", True, BLACK) 60 | text = pygame.transform.rotate(text, 90) 61 | screen.blit(text, [0, 0]) 62 | 63 | # Sideways text 64 | text = font.render("Upside down text", True, BLACK) 65 | text = pygame.transform.rotate(text, 180) 66 | screen.blit(text, [30, 0]) 67 | 68 | # Flipped text 69 | text = font.render("Flipped text", True, BLACK) 70 | text = pygame.transform.flip(text, False, True) 71 | screen.blit(text, [30, 20]) 72 | 73 | # Animated rotation 74 | text = font.render("Rotating text", True, BLACK) 75 | text = pygame.transform.rotate(text, text_rotate_degrees) 76 | text_rotate_degrees += 1 77 | screen.blit(text, [100, 50]) 78 | 79 | # Go ahead and update the screen with what we've drawn. 80 | # This MUST happen after all the other drawing commands. 81 | pygame.display.flip() 82 | 83 | # This limits the while loop to a max of 60 times per second. 84 | # Leave this out and we will use all CPU we can. 85 | clock.tick(60) 86 | 87 | # Be IDLE friendly 88 | pygame.quit() 89 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/timer.py: -------------------------------------------------------------------------------- 1 | """ 2 | Show how to put a timeer on the screen. 3 | 4 | Sample Python/Pygame Programs 5 | Simpson College Computer Science 6 | http://programarcadegames.com/ 7 | http://simpson.edu/computer-science/ 8 | 9 | """ 10 | 11 | import pygame 12 | 13 | # Define some colors 14 | BLACK = (0, 0, 0) 15 | WHITE = (255, 255, 255) 16 | 17 | pygame.init() 18 | 19 | # Set the height and width of the screen 20 | size = [700, 500] 21 | screen = pygame.display.set_mode(size) 22 | 23 | pygame.display.set_caption("My Game") 24 | 25 | # Loop until the user clicks the close button. 26 | done = False 27 | 28 | # Used to manage how fast the screen updates 29 | clock = pygame.time.Clock() 30 | 31 | font = pygame.font.Font(None, 25) 32 | 33 | frame_count = 0 34 | frame_rate = 60 35 | start_time = 90 36 | 37 | # -------- Main Program Loop ----------- 38 | while not done: 39 | for event in pygame.event.get(): # User did something 40 | if event.type == pygame.QUIT: # If user clicked close 41 | done = True # Flag that we are done so we exit this loop 42 | 43 | # Set the screen background 44 | screen.fill(WHITE) 45 | 46 | # ALL CODE TO DRAW SHOULD GO BELOW THIS COMMENT 47 | 48 | # --- Timer going up --- 49 | # Calculate total seconds 50 | total_seconds = frame_count // frame_rate 51 | 52 | # Divide by 60 to get total minutes 53 | minutes = total_seconds // 60 54 | 55 | # Use modulus (remainder) to get seconds 56 | seconds = total_seconds % 60 57 | 58 | # Use python string formatting to format in leading zeros 59 | output_string = "Time: {0:02}:{1:02}".format(minutes, seconds) 60 | 61 | # Blit to the screen 62 | text = font.render(output_string, True, BLACK) 63 | screen.blit(text, [250, 250]) 64 | 65 | # --- Timer going down --- 66 | # --- Timer going up --- 67 | # Calculate total seconds 68 | total_seconds = start_time - (frame_count // frame_rate) 69 | if total_seconds < 0: 70 | total_seconds = 0 71 | 72 | # Divide by 60 to get total minutes 73 | minutes = total_seconds // 60 74 | 75 | # Use modulus (remainder) to get seconds 76 | seconds = total_seconds % 60 77 | 78 | # Use python string formatting to format in leading zeros 79 | output_string = "Time left: {0:02}:{1:02}".format(minutes, seconds) 80 | 81 | # Blit to the screen 82 | text = font.render(output_string, True, BLACK) 83 | 84 | screen.blit(text, [250, 280]) 85 | 86 | # ALL CODE TO DRAW SHOULD GO ABOVE THIS COMMENT 87 | frame_count += 1 88 | 89 | # Limit frames per second 90 | clock.tick(frame_rate) 91 | 92 | # Go ahead and update the screen with what we've drawn. 93 | pygame.display.flip() 94 | 95 | # Be IDLE friendly. If you forget this line, the program will 'hang' 96 | # on exit. 97 | pygame.quit() 98 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/ufo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Apress/program-arcade-games-w-python/55691099ae0413d01b7604e834a5368cfac4dae6/ProgramArcadeGamesCode/ufo.png -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/while_loop_examples.py: -------------------------------------------------------------------------------- 1 | # Sample Python/Pygame Programs 2 | # Simpson College Computer Science 3 | # http://programarcadegames.com/ 4 | # http://simpson.edu/computer-science/ 5 | 6 | # A while loop can be used anywhere a for loop is used: 7 | i = 0 8 | while i < 10: 9 | print(i) 10 | i = i + 1 11 | 12 | # This is the same as: 13 | for i in range(10): 14 | print(i) 15 | 16 | # It is possible to short hand the code: 17 | # i = i + 1 18 | # With the following: 19 | # i += 1 20 | # This can be done with subtraction, and multiplication as well. 21 | i = 0 22 | while i < 10: 23 | print(i) 24 | i += 1 25 | 26 | # What would this print? 27 | i = 1 28 | while i <= 2**32: 29 | print(i) 30 | i *= 2 31 | 32 | # A very common operation is to loop until the user performs 33 | # a request to quit 34 | quit = "n" 35 | while quit == "n": 36 | quit = input("Do you want to quit? ") 37 | 38 | # There may be several ways for a loop to quit. Using a boolean 39 | # to trigger the event is a way of handling that. 40 | done = False 41 | while not done: 42 | quit = input("Do you want to quit? ") 43 | if quit == "y": 44 | done = True 45 | 46 | attack = input("Does your elf attach the dragon? ") 47 | if attack == "y": 48 | print("Bad choice, you died.") 49 | done = True 50 | 51 | value = 0 52 | increment = 0.5 53 | while value < 0.999: 54 | value += increment 55 | increment *= 0.5 56 | print(value) 57 | 58 | # -- Common problems with while loops -- 59 | 60 | # The programmer wants to count down from 10 61 | # What is wrong and how to fix it? 62 | i = 10 63 | while i == 0: 64 | print(i) 65 | i -= 1 66 | 67 | # What is wrong with this loop that tries 68 | # to count to 10? What will happen when it is run? 69 | i = 1 70 | while i < 10: 71 | print(i) 72 | -------------------------------------------------------------------------------- /ProgramArcadeGamesCode/word_search.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # Create a grid filled with "." representing a blank 4 | def createGrid(): 5 | grid=[] 6 | for row in range(15): 7 | grid.append([]) 8 | for column in range(50): 9 | grid[row].append(".") 10 | return grid 11 | 12 | # Print the grid to the screen 13 | def printGrid(grid): 14 | for row in range(len(grid)): 15 | for column in range(len(grid[row])): 16 | print(grid[row][column],end="") 17 | print() 18 | 19 | # Try to place the word. Return True if successful 20 | # False if it failed and we need to try again. 21 | def tryToPlaceWord(grid,word): 22 | # Figure out the direction of the work. 23 | # Change the 8 to a 7 if you don't want backwards 24 | # words. 25 | direction=random.randrange(0,8) 26 | if( direction == 0 ): 27 | x_change=-1 28 | y_change=-1 29 | if( direction == 1 ): 30 | x_change=0 31 | y_change=1 32 | if( direction == 2 ): 33 | x_change=1 34 | y_change=-1 35 | if( direction == 3 ): 36 | x_change=1 37 | y_change=0 38 | if( direction == 4 ): 39 | x_change=1 40 | y_change=1 41 | if( direction == 5 ): 42 | x_change=0 43 | y_change=1 44 | if( direction == 6 ): 45 | x_change=-1 46 | y_change=1 47 | if( direction == 7 ): 48 | x_change=-1 49 | y_change=0 50 | 51 | # Find the length and height of the grid 52 | height=len(grid) 53 | width=len(grid[0]) 54 | 55 | # Create a random start point 56 | column=random.randrange(width) 57 | row=random.randrange(height) 58 | 59 | # Check to make sure the word won't run off the edge of the grid. 60 | # If it does, return False. We failed. 61 | if( x_change < 0 and column < len(word) ): 62 | return False 63 | if( x_change > 0 and column > width-len(word) ): 64 | return False 65 | if( y_change < 0 and row < len(word) ): 66 | return False 67 | if( y_change > 0 and row > height-len(word) ): 68 | return False 69 | 70 | # Now check to make sure there isn't another letter in our way 71 | current_column=column 72 | current_row=row 73 | for letter in word: 74 | # Make sure it is blank, or already the correct letter. 75 | if grid[current_row][current_column]==letter or grid[current_row][current_column]=='.': 76 | current_row += y_change 77 | current_column += x_change 78 | else: 79 | # Oh! A different letter is already here. Fail. 80 | return False 81 | 82 | # Everything is good so far, actually place the letters. 83 | current_column=column 84 | current_row=row 85 | for letter in word: 86 | grid[current_row][current_column]=letter 87 | current_row += y_change 88 | current_column += x_change 89 | return True 90 | 91 | # This just calls tryToPlaceWord until we succeed. It could 92 | # repeat forever if there is no possible place to put the word. 93 | def placeWord(grid,word): 94 | success=False 95 | 96 | while not(success): 97 | success=tryToPlaceWord(grid,word) 98 | 99 | # Create an empty grid 100 | grid = createGrid() 101 | 102 | # Place some words 103 | placeWord(grid,"pandabear") 104 | placeWord(grid,"fish") 105 | placeWord(grid,"snake") 106 | placeWord(grid,"porcupine") 107 | placeWord(grid,"dog") 108 | placeWord(grid,"cat") 109 | placeWord(grid,"tiger") 110 | placeWord(grid,"bird") 111 | placeWord(grid,"alligator") 112 | placeWord(grid,"ant") 113 | placeWord(grid,"camel") 114 | placeWord(grid,"dolphin") 115 | 116 | # Print it out 117 | printGrid(grid) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Apress Source Code 2 | 3 | This repository accompanies [*Program Arcade Games: With Python and Pygame*](http://www.apress.com/9781484217894) by Paul Craven (Apress, 2016). 4 | 5 | ![Cover image](9781484217894.jpg) 6 | 7 | Download the files as a zip using the green button, or clone the repository to your machine using Git. 8 | 9 | ## Releases 10 | 11 | Release v1.0 corresponds to the code in the published book, without corrections or updates. 12 | 13 | ## Contributions 14 | 15 | See the file Contributing.md for more information on how you can contribute to this repository. 16 | -------------------------------------------------------------------------------- /contributing.md: -------------------------------------------------------------------------------- 1 | # Contributing to Apress Source Code 2 | 3 | Copyright for Apress source code belongs to the author(s). However, under fair use you are encouraged to fork and contribute minor corrections and updates for the benefit of the author(s) and other readers. 4 | 5 | ## How to Contribute 6 | 7 | 1. Make sure you have a GitHub account. 8 | 2. Fork the repository for the relevant book. 9 | 3. Create a new branch on which to make your change, e.g. 10 | `git checkout -b my_code_contribution` 11 | 4. Commit your change. Include a commit message describing the correction. Please note that if your commit message is not clear, the correction will not be accepted. 12 | 5. Submit a pull request. 13 | 14 | Thank you for your contribution! --------------------------------------------------------------------------------