Python alien intrusion game programming full version, python alien

Source: Internet
Author: User

Python alien intrusion game programming full version, python alien

The complete implementation of PYTHON game programming alien intrusion is as follows:

Preparation: Download python, such as Anaconda3 (64 bit), and import the pygame game package

1. alien settings, alien. py, code:

Import pygamefrom pygame. sprite import Spriteclass Alien (Sprite): "indicates a single Alien class" def _ init _ (self, ai_settings, screen ): "initialize aliens and set other locations" "super (Alien, self ). _ init _ () self. screen = screen self. ai_settings = ai_settings # load the alien image and set its rect attribute self. image = pygame. image. load ('images/alien.bmp ') self. rect = self. image. get_rect () # each alien is initially near self in the upper left corner of the screen. rect. x = self. rect. width self. rect. y = self. rect. height # stores the precise location of aliens self. x = float (self. rect. x) def blitme (self): "Draw aliens in specified locations" self. screen. BITs (self. image, self. rect) def check_edges (self): "returns True" screen_rect = self if aliens are at the edge of the screen. screen. get_rect () if self. rect. right> = screen_rect.right: return True elif self. rect. left <= 0: return True def update (self): "Move aliens to the right" self. x + = (self. ai_settings.alien_speed_factor * self. ai_settings.fleet_direction) self. rect. x = self. x

2. Game main program, alien_invasion.py, code:

Import pygamefrom settings import Settingsfrom game_stats import GameStatsfrom button import Buttonfrom ship import Shipfrom pygame. sprite import Groupimport game_functions as gffrom scoreboard import Scoreboarddef run_game (): pygame. init () # initialize the background Settings ai_settings = Settings () # global Settings screen = pygame. display. set_mode (# create a screen display window (ai_settings.screen_width, ai_settings.screen_height) pygame. display. set_caption ('alien Invasion ') # title # create a Play Button play_button = Button (ai_settings, screen, "Play") # create an instance for storing Game statistics, and create the Scoreboard stats = GameStats (ai_settings) sb = Scoreboard (ai_settings, screen, stats) # create a ship = Ship (ai_settings, screen) # create a bullet Group bullets = Group () # create an alien aliens = Group () # create an alien Group gf. create_fleet (ai_settings, screen, ship, aliens) # Start the main loop of the game while True: # monitor the keyboard and mouse events gf. check_events (ai_settings, screen, stats, sb, play_button, ship, aliens, bullets) if stats. game_active: # mobile spacecraft gf. update_ship (ship) # update the position of the bullet gf. update_bullets (ai_settings, screen, stats, sb, ship, aliens, bullets) # update the alien gf. update_aliens (ai_settings, stats, screen, sb, ship, aliens, bullets) # update screen gf. update_screen (ai_settings, screen, stats, sb, ship, aliens, bullets, play_button) run_game ()

3. Set the bullet, bullet. py, code:

Import pygamefrom pygame. sprite import Spriteimport timeclass Bullet (Sprite): '''ship Bullet management ''' def _ init _ (self, ai_settings, screen, ship): super (Bullet, self ). _ init _ () self. screen = screen # create the initial position (0, 0, 3, 15) of the bullet rectangle corresponding to lef, top, width, and high self respectively. rect = pygame. rect (0, 0, ai_settings.bullet_width, ai_settings.bullet_height) self. rect. centerx = ship. rect. centerx # Set the coordinate of the X axis of the central point to be consistent with that of the ship self. rect. top = ship. rect. top # Set the Y axis coordinates at the top to be the same as that of the ship # set them to decimal places to calculate self. top = float (self. rect. top) self. color = ai_settings.bullet_color self. speed_factor = ai_settings.bullet_speed_factor def update (self): self. top-= self. speed_factor self. rect. top = self. top print (self. rect. top) def draw_bullet (self): pygame. draw. rect (self. screen, self. color, self. rect)

4. Set the Play button, button. py, code:

Import pygame. fontclass Button (): def _ init _ (self, ai_settings, screen, msg): "" initialize Button property "self. screen = screen self. screen_rect = screen. get_rect () # Set the button size and other attributes self. width, self. height = 200,50 self. button_color = (0,255, 0) self. text_color = (255,255,255) self. font = pygame. font. sysFont (None, 48) # create a button's rect object and center it in self. rect = pygame. rect (0, 0, self. width, self. height) self. rect. center = self. the screen_rect.center # button label only needs to be created once. prep_msg (msg) def prep_msg (self, msg): "renders msg as an image and centers it on the button" self. msg_image = self. font. render (msg, True, self. text_color, self. button_color) self. msg_image_rect = self. msg_image.get_rect () self. msg_image_rect.center = self. rect. center def draw_button (self): # Draw a color-filled button and then draw the text self. screen. fill (self. button_color, self. rect) self. screen. BITs (self. msg_image, self. msg_image_rect)

5. Set the game function, game_functions.py, code:

Import sysimport pygamefrom bullet import Bulletfrom alien import Alienfrom time import sleepdef check_events (ai_settings, screen, stats, sb, play_button, ship, aliens, bullets ): # monitoring keyboard and mouse events for event in pygame. event. get (): if event. type = pygame. QUIT: # Close the window and exit sys. exit () elif event. type = pygame. KEYDOWN: check_keydown_events (event, ai_settings, screen, ship, bullets) elif event. type = pygame. KEYUP: check_keyup_events (event, ship) elif event. type = pygame. MOUSEBUTTONDOWN: mouse_x, mouse_y = pygame. mouse. get_pos () check_play_button (ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y) def check_play_button (ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, mouse_x, mouse_y): "" Start the game when the player clicks the Play button "button_clicked = play_button.rect.collidepoint (mouse_x, mouse_y) if button_clicked and not stats. game_active: # reset game settings ai_settings.initialize_dynamic_settings () # Hide the cursor pygame. mouse. set_visible (False) # reset Game statistics stats. reset_stats () stats. game_active = True # reset the score card image sb. prep_score () sb. prep_high_score () sb. prep_level () sb. prep_ships () # Clear the alien list and bullet list aliens. empty () bullets. empty () # create a group of new aliens and center the ship in create_fleet (ai_settings, screen, ship, aliens) ship. center_ship () def update_screen (ai_settings, screen, stats, sb, ship, aliens, bullets, play_button): ''' update the image on the screen, switch to the new screen ''' screen. fill (ai_settings.bg_color) # Set the background color ship. blitme () # Draw the ship aliens. draw (screen) # do not execute for bullet in bullets when the element in the loop bullet Group is drawn as null. sprites (): bullet. draw_bullet () # Draw bullets # Show score sb. show_score () # if the game is inactive, the Play button if not stats is displayed. game_active: play_button.draw_button () # display the latest screen and wipe the old screen pygame. display. flip () # print ('1') def check_keydown_events (event, ai_settings, screen, ship, bullets): if event. key = pygame. k_RIGHT: ship. moving_right = True elif event. key = pygame. k_LEFT: ship. moving_left = True elif event. key = pygame. k_SPACE: fire_bullet (ai_settings, screen, ship, bullets) elif event. key = pygame. k_q: sys. exit () def check_keyup_events (event, ship): if event. key = pygame. k_RIGHT: ship. moving_right = False elif event. key = pygame. k_LEFT: ship. moving_left = Falsedef update_bullets (ai_settings, screen, stats, sb, ship, aliens, bullets): ''' update the bullet position and delete the ''' bullets. update () # execute self. update () operation for bullet in bullets. sprites (): if bullet. rect. bottom <= 0: # Delete bullets from the bullet field. remove (bullet) check_bullet_alien_collisions (ai_settings, screen, stats, sb, ship, aliens, bullets) def evaluate (ai_settings, screen, stats, sb, ship, aliens, bullets ): "Responding to the collision between aliens and bullets" "# Delete the collision bullets and the aliens collisions = pygame. sprite. groupcollide (bullets, aliens, True, True) if collisions: for aliens in collisions. values (): stats. score + = ai_settings.alien_points * len (aliens) sb. prep_score () check_high_score (stats, sb) if len (aliens) = 0: # Delete existing bullets and create a group of aliens to speed up the game bullets. empty () ai_settings.increase_speed () # Raise the stats level. level + = 1 sb. prep_level () create_fleet (ai_settings, screen, ship, aliens) def update_ship (ship): ship. update () def fire_bullet (ai_settings, screen, ship, bullets): # create a bullet object and add it to the bullet group if len (bullets) <ai_settings.bullets_allowed: # generate new_bullet = Bullet (ai_settings, screen, ship) bullets when the number of bullets is less than the allowed value. add (new_bullet) def get_number_aliens_x (ai_settings, alien_width ): "calculate how many aliens each line can hold" available_space_x = bytes-2 * alien_width rows = int (available_space_x/(2 * alien_width) return response get_number_rows (ai_settings, ship_height, alien_height): "how many lines of aliens can the screen accommodate" available_space_y = (ai_settings.screen_height-(3 * alien_height)-ship_height) number_rows = int (available_space_y/(2 * alien_height) return number_rows def create_aliens (ai_settings, screen, aliens, alien_number, row_number ): "Create an alien and place it in the current row" Alien = alien (ai_settings, screen) alien_width = alien. rect. width alien. x = alien_width + 2 * alien_width * alien_number alien. rect. x = alien. x alien. rect. y = alien. rect. height + 2 * alien. rect. height * row_number aliens. add (alien) def create_fleet (ai_settings, screen, ship, aliens): "Create an alien crowd" "# create an alien, calculate how many aliens a row can hold # The distance between aliens is alien = Alien (ai_settings, screen) number_aliens_x = get_number_aliens_x (ai_settings, alien. rect. width) number_rows = get_number_rows (ai_settings, ship. rect. height, alien. rect. height) # create the first line of aliens for row_number in range (number_rows): for alien_number in range (number_aliens_x): # create an alien and add it to the current row create_aliens (ai_settings, screen, aliens, alien_number, row_number) def check_fleet_edges (ai_settings, aliens): "actions taken when aliens reach the edge" for alien in aliens. sprites (): if alien. check_edges (): change_fleet_direction (ai_settings, aliens) break def change_fleet_direction (ai_settings, aliens): "Move down a group of aliens, and change their movement direction "for alien in aliens. sprites (): alien. rect. y + = ai_settings.fleet_drop_speed ai_settings.fleet_direction * =-1def ship_hit (ai_settings, stats, screen, sb, ship, aliens, bullets ): "responding to a ship hit by aliens" if stats. ships_left> 0: # reduce ship_left by 1 stats. ships_left-= 1 # update the score card sb. prep_ships () # Clear the alien list and bullet list aliens. empty () bullets. empty () # create a group of new aliens and place the spacecraft in the center of the low-end of the screen create_fleet (ai_settings, screen, ship, aliens) ship. center_ship () # Pause sleep (0.5) else: stats. game_active = False pygame. mouse. set_visible (True) def check_aliens_bottom (ai_settings, stats, screen, sb, ship, aliens, bullets): "check for aliens arriving at the low end of the screen" screen_rect = screen. get_rect () for alien in aliens. sprites (): if alien. rect. bottom> = screen_rect.bottom: # handle ship_hit (ai_settings, stats, screen, sb, ship, aliens, bullets) break def update_aliens (ai_settings, stats, screen, sb, ship, aliens, bullets): "updates the location of all aliens in the alien crowd" check_fleet_edges (ai_settings, aliens) aliens. update () # detects collisions between aliens and spacecraft if pygame. sprite. spritecollideany (ship, aliens): ship_hit (ai_settings, stats, screen, sb, ship, aliens, bullets) # Check if there are aliens arriving at the low-end check_aliens_bottom (ai_settings, stats, screen, sb, ship, aliens, bullets) def check_high_score (stats, sb): "check if a new highest record is generated" if stats. score> stats. high_score: stats. high_score = stats. score sb. prep_high_score ()

6. Game statistics, game_stats.py, code:

Class GameStats (): "track game Statistics" def _ init _ (self, ai_settings): "initialize Statistics" self. ai_settings = ai_settings self. reset_stats () # self. game_active = False # The highest self score should not be reset under any circumstances. high_score = 0 self. level = 1 def reset_stats (self): "initializes statistics that may change during Game Operation" self. ships_left = self. ai_settings.ship_limit self. score = 0

7. Set the score, scoreboard. py, code:

Import pygame. fontfrom pygame. sprite import Groupfrom ship import Shipclass Scoreboard (): "class for displaying score information" def _ init _ (self, ai_settings, screen, stats ): "initialize the attributes involved in the display score" "self. screen = screen self. screen_rect = screen. get_rect () self. ai_settings = ai_settings self. stats = stats # Set self in the font used to display the score information. text_color = (30, 30, 30) self. font = pygame. font. sysFont (None, 48) # Prepare the initialization score image and the current highest score self. prep_score () self. prep_high_score () self. prep_level () self. prep_ships () def prep_score (self): "converts a score to a rendered image" "rounded_score = int (round (self. stats. score,-1) score_str = "{:,}". format (rounded_score) self. score_image = self. font. render (score_str, True, self. text_color, self. ai_settings.bg_color) # Place the score in the upper right corner of self. score_rect = self. score_image.get_rect () self. score_rect.right = self. screen_rect.right-20 self. score_rect.top = 5 def prep_high_score (self): "converts the highest score to a rendered image" high_score = int (round (self. stats. high_score,-1) high_score_str = "{:,}". format (high_score) self. high_score_image = self. font. render (high_score_str, True, self. text_color, self. ai_settings.bg_color) # place the highest score in the center of the screen self. high_score_rect = self. high_score_image.get_rect () self. high_score_rect.centerx = self. screen_rect.centerx self. high_score_rect.top = 5 def prep_level (self): "Convert level to rendered image" self. level_image = self. font. render (str (self. stats. level), True, self. text_color, self. ai_settings.bg_color) # Place the score in the upper right corner of self. level_rect = self. score_image.get_rect () self. level_rect.right = self. screen_rect.right self. level_rect.top = self. score_rect.bottom def prep_ships (self): "shows how many ships are left" self. ships = Group () for ship_number in range (self. stats. ships_left): ship = Ship (self. ai_settings, self. screen) ship. rect. x = 10 + ship_number * ship. rect. width ship. rect. y = 10 self. ships. add (ship) def show_score (self): "display score and grade on screen" self. screen. BITs (self. score_image, self. score_rect) self. screen. BITs (self. high_score_image, self. high_score_rect) self. screen. BITs (self. level_image, self. level_rect) # Draw the ship self. ships. draw (self. screen)

8. Set, settings. py, code:

Class Settings (): ''' stores all Settings of alien intrusion ''' def _ init _ (self): ''' initialization Settings ''' # Screen Settings self. screen_width = 1200 self. screen_height = 600 self. bg_color = (230,230,230) # Set the background color to gray # Set self for the spacecraft. ship_limit = 3 self. ship_image_path = 'images/ship.bmp '# ship image path # bullet setting self. bullet_width = 3 self. bullet_height = 15 self. bullet_color = 60, 60, 60 self. bullets_allowed = 3 # number of bullets allowed on the screen # Set self by aliens. fleet_drop_speed = 10 # speed up the game's pace self. speedup_scale = 1.1 # increase the speed of alien points self. score_scale = 1.5 self. initialize_dynamic_settings () def initialize_dynamic_settings (self): "" initialization settings that change with the game "self. ship_speed_factor = 1.5 self. bullet_speed_factor = 3 self. alien_speed_factor = 1 # If fleet_direction is 1, it indicates moving to the right, and-1 indicates moving to the left self. fleet_direction = 1 # scoring self. alien_points = 50 def increase_speed (self): "speed up settings, alien points" self. ship_speed_factor * = self. speedup_scale self. bullet_speed_factor * = self. speedup_scale self. alien_speed_factor * = self. speedup_scale self. alien_points = int (self. alien_points * self. score_scale) print (self. alien_points)


9. ship settings, ship. py, code:

Import pygamefrom pygame. sprite import Spriteclass Ship (Sprite): '''ship all information''' def _ init _ (self, ai_settings, screen): "" initialize a Ship, and set its starting position "" super (Ship, self ). _ init _ () self. screen = screen self. ai_settings = ai_settings # attach the spacecraft image and obtain the external Rectangle self. image = pygame. image. load (self. ai_settings.ship_image_path) # load the image self. image = pygame. transform. smoothscale (self. image, (40, 60) self. rect = self. image. get_rect () # obtain the external Rectangle self of the image. screen_rect = screen. get_rect () # obtain the external rectangle of the screen # Place each search ship in the center self at the bottom of the tree. rect. centerx = self. screen_rect.centerx self. rect. bottom = self. screen_rect.bottom # Set to floating point type self. center = float (self. rect. centerx) # self. rect. centerx cannot set floating point numbers. Only one variable can be set for calculation # Move the flag self. moving_right = False self. moving_left = False def blitme (self): ''' draw the ship ''' self at the specified position. screen. BITs (self. image, self. rect) def update (self): # Move the spacecraft to the right if self. moving_right and self. rect. right <self. screen_rect.right: self. center + = self. ai_settings.ship_speed_factor # Move the spacecraft to the left if self. moving_left and self. rect. left> self. screen_rect.left: self. center-= self. ai_settings.ship_speed_factor self. rect. centerx = self. center def center_ship (self): "center a spacecraft on the screen" self. center = self. screen_rect.centerx

Effect display:

Game resources: image resources

The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.