In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces "how to use the Pygame module to achieve the war alien game". In the daily operation, I believe that many people have doubts about how to use the Pygame module to achieve the war alien game. The editor consulted all kinds of materials and sorted out the simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts about "how to use the Pygame module to achieve the war alien game". Next, please follow the editor to study!
First, introduction
Development environment: Pycharm
Operating system: Windows 10
Pyhon version: 3.9.9
You need to install Pygame 3 (required) and Python (required).
Because the background parameters are referenced many times, it is recommended that you do not change the background parameters in this article. The pictures in this article are relative references, and absolute references need to be set if the position of the picture is different from mine.
Second, the main content
Main code snippet:
Import sysimport pygame # calls pygamefrom settings import Settings # background and some necessary values from ship import Ship # spaceship personal settings import game_function as gf # move and launch # the whole to gf is not from pygame.sprite import Groupfrom game_stats import GameStatsfrom Button import Buttonfrom Scoreboard import Scoreboarddef run_game (): pygame.init () ai_settings = Settings () pygame.display. Set_caption (aircraft Battle 1) stats = GameStats (ai_settings) screen = pygame.display.set_mode ((ai_settings.screen_width) Ai_settings.screen_height) play_button = Button (ai_settings, screen, 'game') sb = Scoreboard (ai_settings, screen, stats) ship = Ship (ai_settings, screen) bullets_left = Group () bullets_down = Group () bullets_right = Group () bullets = Group () aliens = Group () gf.create_fleet (ai_settings, screen, ship,aliens) while True: gf.check_events Stats, play_button,screen,ship, aliens,bullets,bullets_left,bullets_right, bullets_down) if stats.game_active: ship.update () # this sentence is very important. You must call the judgment gf.update_bullets (sb,screen,stats, ship, ai_settings,aliens, bullets,bullets_left,bullets_right) in ship. Bullets_down) # gf.update_aliens (ai_settings, aliens, stats, screen, ship, bullets,bullets_down,bullets_left,bullets_right) gf.update_screen (ai_settings, screen, stats,ship,aliens, bullets,bullets_left,bullets_right,bullets_down,play_button, sb) run_game ()
Some calls about alien spacecraft:
Import pygameimport sysfrom pygame.sprite import Spriteclass Alien (Sprite): def _ _ init__ (self,ai_settings, screen): super (Alien Self). _ init__ () self.screen = screen self.ai_settings = ai_settings self.image = pygame.image.load ('alien spaceship .png') self.rect = self.image.get_rect () self.rect.x = self.rect.width self.rect.y = self.rect.height self.x = float (self.rect.x) # alien Human position def check_edges (self): # check if the ship touches the wall screen_rect = self.screen.get_rect () if self.rect.right > = screen_rect.right: return True elif self.rect.left 0: # greater than 0 self.centerx-= self.ai_settings.ship_speed_factor if self.moving_ on the left side of the screen Up and self.rect.top > self.screen_rect.top: # is greater than 0 self.centery-= self.ai_settings.ship_speed_factor if self.moving_down and self.rect.bottom at the top of the screen
< self.screen_rect.bottom: #小于屏幕底部 self.centery += self.ai_settings.ship_speed_factor self.rect.centerx = self.centerx self.rect.centery = self.centery def center_ship(self): # 让飞船居中 self.centery = self.screen_rect.bottom-70 self.centerx = self.screen_rect.centerx def blitme(self): self.screen.blit(self.image, self.rect) 关于一些基本的文件设置和背景设置: import pygameimport sys class Settings(): def __init__(self): self.screen_width = 1200 self.screen_height = 800 self.bg_color = (230, 230, 230) # 飞船的速度: self.ship_limit = 3 # 子弹设置 self.bullet_width = 3 self.bullet_height = 15 self.bullet_color = (60, 60, 60) self.bullets_allowed = 3 # 限制子弹的数量 self.fleet_drop_speed = 8 self.score_scale = 2 self.speedup_scale = 1.1 self.initialize_dynamic_settings() def initialize_dynamic_settings(self): self.ship_speed_factor = 1.5 self.bullet_speed_factor = 1 # 子弹的速度 self.alien_speed_factor = 1 # 飞船速度 self.fleet_direction = 1 # 方向参数 self.alien_points = 50 def increase_speed(self): 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) 关于按键的一些设置(这部分我将子弹向下向左向右发射的按键也加入进去,如不需要请自行删减): import sysimport pygamefrom time import sleep # 时间?休眠?from bullet import Bulletfrom bulletRIGHT import BulletRightfrom bulletDOWN import BulletDownfrom bulletLEFT import BulletLeftfrom alien import Alien def check_keydown_events(event,ai_settings, screen,ship, bullets,bullets_left,bullets_right,bullets_down): if event.key == pygame.K_d: ship.moving_right = True elif event.key == pygame.K_a: ship.moving_left = True elif event.key == pygame.K_w: ship.moving_up = True elif event.key == pygame.K_q: # p键退出 sys.exit() elif event.key == pygame.K_s: ship.moving_down = True elif event.key == pygame.K_UP: fire_bullet(ai_settings, screen, ship, bullets) elif event.key == pygame.K_DOWN: fire_bullet_down(ai_settings, screen, ship,bullets_down) elif event.key == pygame.K_LEFT: fire_bullet_left(ai_settings, screen, ship,bullets_left) elif event.key == pygame.K_RIGHT: fire_bullet_right(ai_settings, screen, ship,bullets_right) def check_keyup_events(event, ship): if event.key == pygame.K_d: ship.moving_right = False elif event.key == pygame.K_a: ship.moving_left = False elif event.key == pygame.K_w: ship.moving_up = False elif event.key == pygame.K_s: ship.moving_down = False def check_events(ai_settings, stats, play_button,screen,ship, aliens,bullets,bullets_left,bullets_right,bullets_down): for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: # 注意这个位置是type并不是key check_keydown_events(event,ai_settings, screen,ship, bullets,bullets_left,bullets_right,bullets_down) 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, ship, aliens, bullets, bullets_left, bullets_right, bullets_down, play_button, mouse_x, mouse_y)def check_play_button(ai_settings,screen,stats,ship,aliens, bullets,bullets_left,bullets_right,bullets_down, play_button, mouse_x,mouse_y): # if play_button.rect.collidepoint(mouse_x, mouse_y): button_clicked = play_button.rect.collidepoint(mouse_x, mouse_y) if button_clicked and not stats.game_active: ai_settings.initialize_dynamic_settings() # 重置速度 pygame.mouse.set_visible(False) # 隐藏光标 stats.reset_stats() stats.game_active = True aliens.empty() bullets.empty() bullets_down.empty() bullets_left.empty() bullets_right.empty() create_fleet(ai_settings,screen,ship,aliens) ship.center_ship() def update_bullets(sb,screen,stats, ship ,ai_settings,aliens, bullets,bullets_left,bullets_right,bullets_down): bullets.update() for bullet in bullets.copy(): if bullet.rect.bottom = ai_settings.screen_height: bullets_down.remove(bullet_down) print(len(bullets_down)) # 此句显示未删除的子弹数量以确保前几句正确删除子弹 collections = pygame.sprite.groupcollide(bullets_down, aliens, True, True) if collections: stats.score += ai_settings.alien_points sb.prep_score() bullets_left.update() for bullet_left in bullets_left.copy(): if bullet_left.rect.right = ai_settings.screen_width: bullets_right.remove(bullet_right) # print(len(bullets_right)) # 此句显示未删除的子弹数量以确保前几句正确删除子弹 collections = pygame.sprite.groupcollide(bullets_right, aliens, True, True) if collections: stats.score += ai_settings.alien_points sb.prep_score() def update_screen(ai_settings, screen, stats,ship,aliens, bullets,bullets_left,bullets_right,bullets_down,play_button ,sb): # 显示 screen.fill(ai_settings.bg_color) for bullet in bullets.sprites(): bullet.draw_bullet() for bullet in bullets_right.sprites(): bullet.draw_bullet() for bullet in bullets_left.sprites(): bullet.draw_bullet() for bullet in bullets_down.sprites(): bullet.draw_bullet() ship.blitme() aliens.draw(screen) sb.show_score() if not stats.game_active: play_button.draw_button() pygame.display.flip() def create_fleet(ai_settings, screen ,ship,aliens): 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) for row_number in range(number_rows): for alien_number in range(number_aliens_x): create_alien(ai_settings, screen, aliens , alien_number, row_number) def get_number_aliens_x(ai_settings, alien_width): # 外星飞船数量 available_space_x = ai_settings.screen_width - 1* alien_width number_alien_x = int(available_space_x / (2 * alien_width)) return number_alien_xdef create_alien(ai_settings, screen, aliens, alien_number, row_number): 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 get_number_rows(ai_settings, ship_height, alien_height): # 计算可容纳多少外星人 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 check_fleet_edges(ai_settings, aliens): for alien in aliens.sprites(): if alien.check_edges(): change_fleet_direction(ai_settings, aliens) breakdef change_fleet_direction(ai_settings, aliens): for alien in aliens.sprites(): alien.rect.y += ai_settings.fleet_drop_speed ai_settings.fleet_direction *= -1 # 将移动距离变为负def ship_hit(ai_settings, stats, screen, ship , aliens , bullets,bullets_down,bullets_left,bullets_right): # 响应外星人撞击飞船 if stats.ships_left >0: stats.ships_left-= 1 # subtract ship_left from 1 # empty the alien list and bullet list aliens.empty () bullets.empty () bullets_down.empty () bullets_left.empty () bullets_right.empty () create_fleet (ai_settings, screen, ship Aliens) # reset ship and alien ship.center_ship () sleep (0.5) # pause else: stats.game_active = False pygame.mouse.set_visible (True) def check_aliens_bottom (ai_settings, stats, screen, ship, aliens Bullets): screen_rect = screen.get_rect () for alien in aliens.sprites (): if alien.rect.bottom > = screen_rect.bottom: ship_hit (ai_settings, stats,screen, ship, aliens,bullets) break def update_aliens (ai_settings, aliens, stats,screen, ship, bullets,bullets_down,bullets_left,bullets_right): # Update the position of the alien spacecraft check_fleet_edges (ai_settings Aliens) aliens.update () if pygame.sprite.spritecollideany (ship, aliens): print ('GG') ship_hit (ai_settings, stats, screen, ship, aliens, bullets,bullets_down,bullets_left,bullets_right) def fire_bullet (ai_settings, screen, ship, bullets): # forward bullet if len (bullets)
< ai_settings.bullets_allowed: # 已经产生的子弹少于设置的数时发射才有效果 new_bullet = Bullet(ai_settings, screen, ship) bullets.add(new_bullet) # def fire_bullet_down(ai_settings, screen, ship,bullets_down): # 后方子弹 if len(bullets_down) < ai_settings.bullets_allowed: # 已经产生的子弹少于设置的数时发射才有效果 new_bullet_down = BulletDown(ai_settings, screen, ship) bullets_down.add(new_bullet_down) # def fire_bullet_left(ai_settings, screen, ship,bullets_left): # 左方子弹 if len(bullets_left) < ai_settings.bullets_allowed: # 已经产生的子弹少于设置的数时发射才有效果 new_bullet_left = BulletLeft(ai_settings, screen, ship) bullets_left.add(new_bullet_left) # def fire_bullet_right(ai_settings, screen, ship,bullets_right): # 右方子弹 if len(bullets_right) < ai_settings.bullets_allowed: # 已经产生的子弹少于设置的数时发射才有效果 new_bullet_right = BulletRight(ai_settings, screen, ship) bullets_right.add(new_bullet_right) # 关于字体和开始按键的一些设置: import pygame.fontclass Button(): def __init__(self, ai_settings, screen ,msg): self.screen = screen self.screen_rect = screen.get_rect() self.width, self.height = 200,50 self.button_color = (28, 136 ,121) self.text_color = (255, 255, 255) self.font = pygame.font.SysFont(None, 48) self.rect = pygame.Rect(0,0, self.width,self.height) self.rect.center = self.screen_rect.center self.prep_msg(msg) def prep_msg(self,msg): 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): self.screen.fill(self.button_color,self.rect) self.screen.blit(self.msg_image, self.msg_image_rect) 一些分数显示和等级显示代码: from settings import Settingsfrom ship import Shipclass GameStats(): def __init__(self, ai_settings): self.ai_settings = ai_settings self.reset_stats() self.game_active = False def reset_stats(self): self.ships_left = self.ai_settings.ship_limit self.score = 0 self.level = 1 关于等级难度提升的一些设置: import pygame.font # 字体from pygame.sprite import Groupfrom ship import Shipclass Scoreboard(): def __init__(self,ai_settings, screen, stats): self.screen = screen self.screen_rect = screen.get_rect() self.ai_settings = ai_settings self.stats = stats self.text_color = (30, 30, 30) self.font = pygame.font.SysFont(None, 48) self.prep_score() self.prep_level() # 等级 def prep_level(self): level_str = str(self.stats.level) self.level_image = self.font.render(level_str, True, self.text_color,self.ai_settings.bg_color) self.level_rect = self.level_image.get_rect() self.level_rect.right = self.score_rect.right self.level_rect.top = self.score_rect.bottom + 10 def prep_score(self): 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) self.score_rect = self.score_image.get_rect() self.score_rect.right = self.screen_rect.right - 20 self.score_rect.top = 20 def show_score(self): self.screen.blit(self.score_image, self.score_rect) self.screen.blit(self.level_image, self.level_rect)效果展示: 开始状态: 点击Game进行开始(开始后鼠标自动消失) 点击上下左右键发射子弹(设置屏幕同一方向只能存在三颗)Increased difficulty after destroying the ship (cleared from a fresh start after three deaths)
Game introduction:
Press game to play the game, after the start of the game, the mouse automatically disappears, using WSED to control the flight direction of the spaceship, and the arrow up and down to control the design direction of bullets. The alien will fly to the player in the form of S-shaped flight. when the alien encounters the player, he will lose one life. The player's spaceship will lose three lives. After the alien touches the player, the player's position and the alien's position will be reset, and the score will not be reset. When the alien rushes past the player and arrives below, the player will be judged to have lost a life and then the position will be reset. Every extermination of an alien will be scored in the upper right corner, and when all the aliens in the box are eliminated, the aliens will be refreshed. Alien speed and abilities will double their strength, and players will receive more points, and the game will end when all three lives are lost.
At this point, the study on "how to use the Pygame module to achieve a war alien game" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 271
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.