def __init__(self): """ Initialize the game and creates game resources""" pygame.init() self.settings = Settings() # for windowed mode # self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) # for the fullscreen mode self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics and create a scoreboard self.stats = GameStats(self) self.sb = ScoreBoard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.stars = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._populate_sky() self._create_fleet() self.play_button = Button(self, 'Play')
def create_game( campaign_path: Path, blue: str, red: str, supercarrier: bool, auto_procurement: bool, inverted: bool, ) -> Game: campaign = Campaign.from_json(campaign_path) generator = GameGenerator( blue, red, campaign.load_theater(), Settings( supercarrier=supercarrier, automate_runway_repair=auto_procurement, automate_front_line_reinforcements=auto_procurement, automate_aircraft_reinforcements=auto_procurement, ), GeneratorSettings( start_date=datetime.today(), player_budget=DEFAULT_BUDGET, enemy_budget=DEFAULT_BUDGET, midgame=False, inverted=inverted, no_carrier=False, no_lha=False, no_player_navy=False, no_enemy_navy=False, ), ) return generator.generate()
def __init__( self, page: str, section: str, settings: Settings, write_full_settings: Callable[[], None], ) -> None: super().__init__() self.settings = settings self.write_full_settings = write_full_settings for row, (name, description) in enumerate(Settings.fields(page, section)): self.add_label(row, description) if isinstance(description, BooleanOption): self.add_checkbox_for(row, name, description) elif isinstance(description, ChoicesOption): self.add_combobox_for(row, name, description) elif isinstance(description, BoundedFloatOption): self.add_float_spin_slider_for(row, name, description) elif isinstance(description, BoundedIntOption): self.add_spinner_for(row, name, description) elif isinstance(description, MinutesOption): self.add_duration_controls_for(row, name, description) else: raise TypeError(f"Unhandled option type: {description}")
def run_game(): # init game and create screen object pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) pygame.display.set_caption("Alien Invasion") # create a new ship ship = Ship(ai_settings, screen) aliens = Group() # create alien's group gf.create_fleet(ai_settings, screen, ship, aliens) # create a group to store the bullet bullets = Group() # start game's main circulation while True: # listen mouse and keyboard gf.check_events(ai_settings, screen, ship, bullets) ship.update() gf.update_bullets(aliens, bullets) gf.update_aliens(ai_settings, aliens) # redraw screen every circulation # let last screen be visible gf.update_screen(ai_settings, screen, ship, aliens, bullets)
def create_game( campaign_path: Path, blue: str, red: str, supercarrier: bool, auto_procurement: bool, inverted: bool, cheats: bool, ) -> Game: first_start = liberation_install.init() if first_start: sys.exit( "Cannot generate campaign without configuring DCS Liberation. Start the UI " "for the first run configuration.") # This needs to run before the pydcs payload cache is created, which happens # extremely early. It's not a problem that we inject these paths twice because we'll # get the same answers each time. # # Without this, it is not possible to use next turn (or anything that needs to check # for loadouts) without saving the generated campaign and reloading it the normal # way. inject_custom_payloads(Path(persistency.base_path())) campaign = Campaign.from_json(campaign_path) generator = GameGenerator( FACTIONS[blue], FACTIONS[red], campaign.load_theater(), Settings( supercarrier=supercarrier, automate_runway_repair=auto_procurement, automate_front_line_reinforcements=auto_procurement, automate_aircraft_reinforcements=auto_procurement, enable_frontline_cheats=cheats, enable_base_capture_cheat=cheats, ), GeneratorSettings( start_date=datetime.today(), player_budget=DEFAULT_BUDGET, enemy_budget=DEFAULT_BUDGET, midgame=False, inverted=inverted, no_carrier=False, no_lha=False, no_player_navy=False, no_enemy_navy=False, ), ModSettings( a4_skyhawk=False, f22_raptor=False, hercules=False, jas39_gripen=False, su57_felon=False, frenchpack=False, high_digit_sams=False, ), ) return generator.generate()
def run_game(): # 初始化游戏并创建一个屏幕对象 pygame.init() ai_settings = Settings() screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) # screen = pygame.display.set_mode((1200, 800)) pygame.display.set_caption("Alian Invasion") # 创建Play按钮 play_button = Button(ai_settings, screen, "Play") # 设置背景颜色 bg_color = (85, 204, 220) # 创建一艘飞船 ship = Ship(ai_settings, screen) # 创建一个用于存储子弹的编组 bullets = Group() # 创建一艘飞船、一个子弹编组和一个外星人编组 aliens = Group() # 创建一个外星人 alien = Alien(ai_settings, screen) # 开始游戏的主循环 while True: gf.check_events(ai_settings, screen, play_button, ship, bullets) ship.update() # bullets.update() # 删除已消失的子弹 # for bullet in bullets.copy(): # if bullet.rect.bottom <= 0: # bullet.remove(bullet) print(len(bullets)) gf.update_bullets(bullets) gf.update_screen(ai_settings, screen, ship, alien, bullets, play_button) gf.update_screen(ai_settings, screen, ship, aliens, bullets) # 创建外星人群 gf.create_fleet(ai_settings, screen, ship, aliens) # 监视键盘和鼠标事件 for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exeit() # 每次循环时都重绘屏幕 screen.fill(ai_settings.bg_color) # screen.fill(bg_color) ship.blitme() # 让最终绘制的屏幕可见 pygame.display.flip()
def __init__(self): pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, 'Play')
def run_game(): # Inicializa o jogo e cria um objeto para a tela pygame.init() ai_settings = Settings() screen = pygame.display.set_mode(( ai_settings.screen_width, ai_settings.screen_height, )) pygame.display.set_caption('Alien Invasion') # Cria o botão Play play_button = Button(ai_settings, screen, 'Play') # Cria uma instância para armazenar dados estatísticos do jogo stats = GameStats(ai_settings) sb = Scoreboard(ai_settings, screen, stats) # Cria uma espaçonave, um grupo de projéteis e um grupo de alienígenas ship = Ship(ai_settings, screen) bullets = Group() aliens = Group() # Cria a frota de alienígenas gf.create_fleet(ai_settings, screen, ship, aliens) # Inicia o laço principal do jogo while True: gf.check_events( ai_settings, screen, stats, sb, play_button, ship, aliens, bullets, ) if stats.game_active: ship.update() gf.update_bullets(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_aliens(ai_settings, screen, stats, sb, ship, aliens, bullets) gf.update_screen( ai_settings, screen, stats, sb, ship, aliens, bullets, play_button, )
def print_text(screen, text1, text2, color=(255, 0, 0)): ''' 将文字输出到屏幕 ''' font = pygame.font.SysFont("monospace", 80) imgText = font.render(text1, True, color) imgText2 = font.render(text2, True, color) while True: screen.blit(imgText, (350, 230)) screen.blit(imgText2, (200, 330)) for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: global game_settings, zombies, plants, squares, bullets game_settings = Settings() game_settings.level = game_level zombies = Group() plants = Group() bullets = Group() run_game() return pygame.display.update()
def __init__( self, page: str, settings: Settings, write_full_settings: Callable[[], None], ) -> None: super().__init__() self.setAlignment(Qt.AlignTop) for section in Settings.sections(page): self.addWidget( AutoSettingsGroup(page, section, settings, write_full_settings) )
def accept(self): logging.info("New Game Wizard accept") logging.info("======================") campaign = self.field("selectedCampaign") if campaign is None: campaign = self.campaigns[0] if self.field("usePreset"): start_date = db.TIME_PERIODS[list( db.TIME_PERIODS.keys())[self.field("timePeriod")]] else: start_date = self.theater_page.calendar.selectedDate().toPython() settings = Settings( player_income_multiplier=self.field("player_income_multiplier") / 10, enemy_income_multiplier=self.field("enemy_income_multiplier") / 10, automate_runway_repair=self.field("automate_runway_repairs"), automate_front_line_reinforcements=self.field( "automate_front_line_purchases"), automate_aircraft_reinforcements=self.field( "automate_aircraft_purchases"), supercarrier=self.field("supercarrier"), ) generator_settings = GeneratorSettings( start_date=start_date, player_budget=int(self.field("starting_money")), enemy_budget=int(self.field("enemy_starting_money")), # QSlider forces integers, so we use 1 to 50 and divide by 10 to # give 0.1 to 5.0. midgame=False, inverted=self.field("invertMap"), no_carrier=self.field("no_carrier"), no_lha=self.field("no_lha"), no_player_navy=self.field("no_player_navy"), no_enemy_navy=self.field("no_enemy_navy"), ) blue_faction = [c for c in db.FACTIONS][self.field("blueFaction")] red_faction = [c for c in db.FACTIONS][self.field("redFaction")] generator = GameGenerator( blue_faction, red_faction, campaign.load_theater(), settings, generator_settings, ) self.generatedGame = generator.generate() super(NewGameWizard, self).accept()
def run_game(): # Initialize game and create a screen object. pygame.init() settings = Settings() screen = pygame.display.set_mode( (settings.screen_width, settings.screen_heigth)) pygame.display.set_caption("Alien Invasion 3000") ship = Ship(screen) # Start the main loop for the game. while True: gf.check_events(ship) gf.update_screen(settings, screen, ship)
class PluginSettings: def __init__(self, identifier: str, enabled_by_default: bool) -> None: self.identifier = identifier self.enabled_by_default = enabled_by_default self.settings = Settings() self.initialize_settings() def set_settings(self, settings: Settings) -> None: self.settings = settings self.initialize_settings() def initialize_settings(self) -> None: # Plugin options are saved in the game's Settings, but it's possible for # plugins to change across loads. If new plugins are added or new # options added to those plugins, initialize the new settings. self.settings.initialize_plugin_option(self.identifier, self.enabled_by_default) @property def enabled(self) -> bool: return self.settings.plugin_option(self.identifier) def set_enabled(self, enabled: bool) -> None: self.settings.set_plugin_option(self.identifier, enabled)
class Bot(object): """ Bot for http://theaigames.com/competitions/ai-block-battle """ def __init__(self): self._settings = Settings() self._state = State() def run(self): """ Handle the game logic """ while not sys.stdin.closed: try: raw_line = sys.stdin.readline() if len(raw_line) == 0: continue line = raw_line.strip() parts = line.split() command = parts[0] if command == "settings": self._settings.update(setting=parts[1], value=parts[2]) elif command == "update": self._state.update(obj=parts[1], state=parts[2], value=parts[3]) elif command == "action": # Take action Output.write("drop") except EOFError: return
def __init__(self, game: Game): super().__init__() self.game = game self.pluginsPage = None self.pluginsOptionsPage = None self.pages: dict[str, AutoSettingsPage] = {} for page in Settings.pages(): self.pages[page] = AutoSettingsPage(page, game.settings, self.applySettings) self.setModal(True) self.setWindowTitle("Settings") self.setWindowIcon(CONST.ICONS["Settings"]) self.setMinimumSize(600, 250) self.initUi()
def accept(self): logging.info("New Game Wizard accept") logging.info("======================") blueFaction = [c for c in db.FACTIONS][self.field("blueFaction")] redFaction = [c for c in db.FACTIONS][self.field("redFaction")] selectedCampaign = self.field("selectedCampaign") if selectedCampaign is None: selectedCampaign = self.campaigns[0] conflictTheater = selectedCampaign.theater timePeriod = db.TIME_PERIODS[list( db.TIME_PERIODS.keys())[self.field("timePeriod")]] midGame = self.field("midGame") multiplier = self.field("multiplier") no_carrier = self.field("no_carrier") no_lha = self.field("no_lha") supercarrier = self.field("supercarrier") no_player_navy = self.field("no_player_navy") no_enemy_navy = self.field("no_enemy_navy") invertMap = self.field("invertMap") starting_money = int(self.field("starting_money")) player_name = blueFaction enemy_name = redFaction settings = Settings() settings.inverted = invertMap settings.supercarrier = supercarrier settings.do_not_generate_carrier = no_carrier settings.do_not_generate_lha = no_lha settings.do_not_generate_player_navy = no_player_navy settings.do_not_generate_enemy_navy = no_enemy_navy generator = GameGenerator(player_name, enemy_name, conflictTheater, settings, timePeriod, starting_money, multiplier, midGame) self.generatedGame = generator.generate() super(NewGameWizard, self).accept()
def run_game(): # init pygame.init() # config cfg = Settings() screen = pygame.display.set_mode((cfg.screen_width, cfg.screen_height)) pygame.display.set_caption("Alien Invasion") # 创建飞船 ship = Ship(cfg, screen) # 创建子弹 bullets = Group() # 创建外星人 # alien = Alien(cfg, screen) aliens = Group() game_funcs.create_fleet(cfg, screen, aliens, ship) # 游戏统计信息 stats = GameStats(cfg) sb = Scoreboard(cfg, screen, stats) # 按钮控制 play_button = Button(cfg, screen, "Play") over_all = OverAll(cfg, screen, ship, bullets, aliens, stats, sb) # usage print("started game. press keyboard to start playing.") while True: game_funcs.check_events(cfg, screen, ship, bullets, aliens, stats, play_button, sb) if stats.game_active: ship.update() game_funcs.update_bullets(cfg, screen, ship, bullets, aliens, stats, sb) game_funcs.update_aliens(cfg, screen, ship, bullets, aliens, stats, sb) game_funcs.update_screen(cfg, screen, ship, bullets, aliens, stats, play_button, sb)
def run_game(): """运行游戏""" setting = Settings() screen = pygame.display.set_mode([setting.screen_width, setting.screen_height]) # 飞船 ship = Ship(setting, screen) # 子弹 bullets = Group() # 外星人 aliens = Group() gf.create_fleet(setting, screen, ship, aliens) # title pygame.display.set_caption("Alien Invasion") bg_color = (255, 255, 255) while True: gf.check_event(setting, screen, ship, bullets) ship.update() gf.update_aliens(setting, aliens) gf.update_bullets(bullets) gf.update_screen(setting, screen, ship, bullets, aliens)
def accept(self): blueFaction = [c for c in db.FACTIONS][self.field("blueFaction")] redFaction = [c for c in db.FACTIONS][self.field("redFaction")] isTerrainPg = self.field("isTerrainPg") isTerrainNttr = self.field("isTerrainNttr") isTerrainCaucasusSmall = self.field("isTerrainCaucasusSmall") isTerrainRussia = self.field("isTerrainRussia") isTerrainCaucasusNorth = self.field("isTerrainCaucasusNorth") isIranianCampaignTheater = self.field("isIranianCampaignTheater") isTerrainNormandy = self.field("isTerrainNormandy") isTerrainNormandySmall = self.field("isTerrainNormandySmall") isTerrainChannel = self.field("isTerrainChannel") isTerrainChannelComplete = self.field("isTerrainChannelComplete") isTerrainEmirates = self.field("isTerrainEmirates") timePeriod = db.TIME_PERIODS[list( db.TIME_PERIODS.keys())[self.field("timePeriod")]] midGame = self.field("midGame") multiplier = self.field("multiplier") no_carrier = self.field("no_carrier") no_lha = self.field("no_lha") supercarrier = self.field("supercarrier") no_player_navy = self.field("no_player_navy") no_enemy_navy = self.field("no_enemy_navy") invertMap = self.field("invertMap") player_name = blueFaction enemy_name = redFaction if isTerrainPg: conflicttheater = persiangulf.PersianGulfTheater() elif isTerrainNttr: conflicttheater = nevada.NevadaTheater() elif isTerrainCaucasusSmall: conflicttheater = caucasus.WesternGeorgia() elif isTerrainRussia: conflicttheater = caucasus.RussiaSmall() elif isTerrainCaucasusNorth: conflicttheater = caucasus.NorthCaucasus() elif isIranianCampaignTheater: conflicttheater = persiangulf.IranianCampaign() elif isTerrainEmirates: conflicttheater = persiangulf.Emirates() elif isTerrainNormandy: conflicttheater = normandy.NormandyTheater() elif isTerrainNormandySmall: conflicttheater = normandy.NormandySmall() elif isTerrainChannel: conflicttheater = thechannel.ChannelTheater() elif isTerrainChannelComplete: conflicttheater = thechannel.ChannelTheaterComplete() else: conflicttheater = caucasus.CaucasusTheater() settings = Settings() settings.inverted = invertMap settings.supercarrier = supercarrier settings.do_not_generate_carrier = no_carrier settings.do_not_generate_lha = no_lha settings.do_not_generate_player_navy = no_player_navy settings.do_not_generate_enemy_navy = no_enemy_navy self.generatedGame = self.start_new_game(player_name, enemy_name, conflicttheater, midGame, multiplier, timePeriod, settings) super(NewGameWizard, self).accept()
class AlienInvasion: """Класс для управления ресурсами и поведением игры.""" def __init__(self): pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") self.stats = GameStats(self) self.sb = Scoreboard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() self.play_button = Button(self, 'Play') def run_game(self): while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen() def _check_events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: self._exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) def _check_play_button(self, mouse_pos): button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: self._start_game() def _start_game(self): self.settings.initialize_dynamic_settings() self.stats.reset_stats() self.stats.game_active = True self.sb.prep_images() self.aliens.empty() self.bullets.empty() self._create_fleet() self.ship.center_ship() pygame.mouse.set_visible(False) def _check_keydown_events(self, event): if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key in {pygame.K_q, pygame.K_ESCAPE}: self._exit() elif event.key == pygame.K_SPACE: self._fire_bullet() elif event.key == pygame.K_RETURN: # Enter key self._start_game() def _check_keyup_events(self, event): if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False def _fire_bullet(self): if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _update_bullets(self): self.bullets.update() for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) self._check_bullet_alien_collision() def _check_bullet_alien_collision(self): collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() if not self.aliens: self._start_new_level() def _start_new_level(self): self.bullets.empty() self._create_fleet() self.settings.increase_speed() self.stats.level += 1 self.sb.prep_level() def _update_aliens(self): self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() self._check_aliens_bottom() def _check_aliens_bottom(self): screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: self._ship_hit() break def _ship_hit(self): if self.stats.ships_left > 0: self.stats.ships_left -= 1 # 4 attempts. if before the condition, then 3 attempts self.sb.prep_ships() self.aliens.empty() self.bullets.empty() self._create_fleet() self.ship.center_ship() sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _create_fleet(self): alien = Alien(self) alien_width, alien_height = alien.rect.size available_space_x = self.settings.screen_width - (alien_width * 2) number_aliens_x = available_space_x // (2 * alien_width) ship_height = self.ship.rect.height available_space_y = self.settings.screen_height - 3 * alien_height - ship_height number_rows = available_space_y // (2 * alien_height) for row_number in range(number_rows): for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number) def _create_alien(self, alien_number, row_number): alien = Alien(self) alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien_height + 2 * alien_height * row_number self.aliens.add(alien) def _check_fleet_edges(self): for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _update_screen(self): self.screen.fill(self.settings.bg_color) self.ship.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) self.sb.show_score() if not self.stats.game_active: self.play_button.draw_button() pygame.display.flip() def _exit(self): with open('record.txt', 'w') as record: record.write(str(self.stats.high_score)) sys.exit()
def __init__(self): self._settings = Settings() self._state = State()
def __init__(self, dir): main_dir = dir #Get the standard settings self.settings = Settings() self.clock = pg.time.Clock() self.FPS = self.settings.get["FPS"] self.width = self.settings.get["screen_width"] self.height = self.settings.get["screen_height"] self.tile_size = self.settings.get["tile_size"] self.map_width = int(self.width / 10) self.map_height = int(self.height / 10) self.message_x = self.settings.get["message_x"] self.message_width = self.settings.get["message_width"] self.message_height = self.settings.get["message_height"] # get title from settings self.title = self.settings.get["window_title"] self.fov_radius = self.settings.get["fov_radius"] self.fov_algorithm = self.settings.get["fov_algorithm"] self.fov_light_walls = self.settings.get["fov_light_walls"] #initalize game window. pg.init() #initalize game sounds pg.mixer.init() self.display = pg.Surface((self.width, self.height + 100)) icon_path = load_icon() self.icon = pg.image.load(icon_path) pg.display.set_icon(self.icon) #set screen self.window = pg.display.set_mode((self.width, self.height + 100)) #set title of game pg.display.set_caption(self.title) #set clock for FPS self.clock = pg.time.Clock() #set Main Bool if is Game running self.running = True self.playing = False #find font in the client computer self.font_name = self.settings.get["font"] self.max_room = self.settings.get["max_room"] self.room_min_size = self.settings.get["room_min_size"] self.room_max_size = self.settings.get["room_max_size"] self.load_data() #Main Manu self.main_menu = MainMenu(self) self.options = OptionsMenu(self) self.credits = CreditsMenu(self) self.create_char = CreateCharacterMenu(self) self.curr_menu = self.main_menu #Sub Menu self.inventory = InventoryMenu(self) self.sub_menu = None self.pauze_menu = PauzeMenu(self) #NewGame or Load Game self.new_game = False self.load_game = False self.error = False self.temp_player = None self.config = {} self.sprite_sheet = SpriteSheet('TILE_SPRITE_SHEAT') self.show_mini_map = False self.weapon_factory = WeaponFactory()
def accept(self): logging.info("New Game Wizard accept") logging.info("======================") campaign = self.field("selectedCampaign") if campaign is None: campaign = self.theater_page.campaignList.selected_campaign if campaign is None: campaign = self.campaigns[0] logging.info("New campaign selected: %s", campaign.name) if self.field("usePreset"): start_date = TIME_PERIODS[ list(TIME_PERIODS.keys())[self.field("timePeriod")] ] else: start_date = self.theater_page.calendar.selectedDate().toPython() logging.info("New campaign start date: %s", start_date.strftime("%m/%d/%Y")) settings = Settings( player_income_multiplier=self.field("player_income_multiplier") / 10, enemy_income_multiplier=self.field("enemy_income_multiplier") / 10, automate_runway_repair=self.field("automate_runway_repairs"), automate_front_line_reinforcements=self.field( "automate_front_line_purchases" ), desired_player_mission_duration=timedelta( minutes=self.field("desired_player_mission_duration") ), automate_aircraft_reinforcements=self.field("automate_aircraft_purchases"), supercarrier=self.field("supercarrier"), ) generator_settings = GeneratorSettings( start_date=start_date, player_budget=int(self.field("starting_money")), enemy_budget=int(self.field("enemy_starting_money")), # QSlider forces integers, so we use 1 to 50 and divide by 10 to # give 0.1 to 5.0. inverted=self.field("invertMap"), no_carrier=self.field("no_carrier"), no_lha=self.field("no_lha"), no_player_navy=self.field("no_player_navy"), no_enemy_navy=self.field("no_enemy_navy"), ) mod_settings = ModSettings( a4_skyhawk=self.field("a4_skyhawk"), f22_raptor=self.field("f22_raptor"), f104_starfighter=self.field("f104_starfighter"), hercules=self.field("hercules"), uh_60l=self.field("uh_60l"), jas39_gripen=self.field("jas39_gripen"), su57_felon=self.field("su57_felon"), frenchpack=self.field("frenchpack"), high_digit_sams=self.field("high_digit_sams"), ) blue_faction = self.faction_selection_page.selected_blue_faction red_faction = self.faction_selection_page.selected_red_faction logging.info("New campaign blue faction: %s", blue_faction.name) logging.info("New campaign red faction: %s", red_faction.name) theater = campaign.load_theater() logging.info("New campaign theater: %s", theater.terrain.name) generator = GameGenerator( blue_faction, red_faction, theater, campaign.load_air_wing_config(theater), settings, generator_settings, mod_settings, ) self.generatedGame = generator.generate() AirWingConfigurationDialog(self.generatedGame, self).exec_() self.generatedGame.begin_turn_0() super(NewGameWizard, self).accept()
def __init__(self, identifier: str, enabled_by_default: bool) -> None: self.identifier = identifier self.enabled_by_default = enabled_by_default self.settings = Settings() self.initialize_settings()
from pygame.sprite import Group, groupcollide from game.zombie import Zombie, Zombie1, Zombie3, Zombie4, Zombie5 from game.square import Square from game.plant_icon import Plant_Icon from game.button import Button import time from random import randint from cnf.settings import Settings as st import sys from db import db from game.rank import Rank Login_username = '' pygame.init() game_settings = Settings() screen = pygame.display.set_mode(game_settings.screen_size) pygame.display.set_caption("DC PvZ clone") background = Background(game_settings) peashooter_icon = Plant_Icon(game_settings, 'peashooter-icon.png', 1) gatling_icon = Plant_Icon(game_settings, 'gatling-icon.png', 2) sunflower_icon = Plant_Icon(game_settings, 'sunflower.png', 3) icons = [peashooter_icon, gatling_icon, sunflower_icon] # All our groups zombies = Group() plants = Group() squares = Group() bullets = Group() game_level = game_settings.level
import random from game.entities import Food, Level from game.direction import * from game.drawing.windows import * from game.drawing.game_drawing import * from game.settings import Settings import pygame pygame.init() settings = Settings() class Game: clock = pygame.time.Clock() fps = 120 _generate_food_location = None @staticmethod def _get_direction(): for i in pygame.event.get(): if i.type == pygame.QUIT: exit() elif i.type == pygame.KEYDOWN: if i.key in TranslateDirection.direction: return TranslateDirection.direction[i.key] def free_game_loop(self): level = Level('free', 1) tick = 0
from game.game import Game from game.settings import Settings if __name__ == "__main__": settings = Settings( screen_width=1024, screen_height=768, frames_per_second=60, window_caption="Wanna-be-a-game", ) game = Game(settings) game.run()
def accept(self): logging.info("New Game Wizard accept") logging.info("======================") campaign = self.field("selectedCampaign") if campaign is None: campaign = self.campaigns[0] if self.field("usePreset"): start_date = db.TIME_PERIODS[list( db.TIME_PERIODS.keys())[self.field("timePeriod")]] else: start_date = self.theater_page.calendar.selectedDate().toPython() settings = Settings( player_income_multiplier=self.field("player_income_multiplier") / 10, enemy_income_multiplier=self.field("enemy_income_multiplier") / 10, automate_runway_repair=self.field("automate_runway_repairs"), automate_front_line_reinforcements=self.field( "automate_front_line_purchases"), desired_player_mission_duration=timedelta( minutes=self.field("desired_player_mission_duration")), automate_aircraft_reinforcements=self.field( "automate_aircraft_purchases"), supercarrier=self.field("supercarrier"), ) generator_settings = GeneratorSettings( start_date=start_date, player_budget=int(self.field("starting_money")), enemy_budget=int(self.field("enemy_starting_money")), # QSlider forces integers, so we use 1 to 50 and divide by 10 to # give 0.1 to 5.0. midgame=False, inverted=self.field("invertMap"), no_carrier=self.field("no_carrier"), no_lha=self.field("no_lha"), no_player_navy=self.field("no_player_navy"), no_enemy_navy=self.field("no_enemy_navy"), ) mod_settings = ModSettings( a4_skyhawk=self.field("a4_skyhawk"), f22_raptor=self.field("f22_raptor"), hercules=self.field("hercules"), jas39_gripen=self.field("jas39_gripen"), su57_felon=self.field("su57_felon"), frenchpack=self.field("frenchpack"), high_digit_sams=self.field("high_digit_sams"), ) blue_faction = self.faction_selection_page.selected_blue_faction red_faction = self.faction_selection_page.selected_red_faction generator = GameGenerator( blue_faction, red_faction, campaign.load_theater(), settings, generator_settings, mod_settings, ) self.generatedGame = generator.generate() super(NewGameWizard, self).accept()
class AlienInvasion: """ Overall class to manage game assets and behavior """ def __init__(self): """ Initialize the game and creates game resources""" pygame.init() self.settings = Settings() # for windowed mode # self.screen = pygame.display.set_mode((self.settings.screen_width, self.settings.screen_height)) # for the fullscreen mode self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics and create a scoreboard self.stats = GameStats(self) self.sb = ScoreBoard(self) self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.stars = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._populate_sky() self._create_fleet() self.play_button = Button(self, 'Play') def run_game(self): """ Start the main loop for the game """ while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen() def _check_events(self): """ Respond to keypresses and mouse events """ for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) def _check_keydown_events(self, event): """ Respond to keypresses """ if event.key == pygame.K_RIGHT: self.ship.moving_right = True elif event.key == pygame.K_LEFT: self.ship.moving_left = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() elif event.key == pygame.K_p: self._start_game() elif event.key == pygame.K_PAGEUP: self.settings.manual_level += 1 self.stats.level = self.settings.manual_level self.sb.prep_level() elif event.key == pygame.K_PAGEDOWN: self.settings.manual_level -= 1 if self.settings.manual_level < 1: self.settings.manual_level = 1 self.stats.level = self.settings.manual_level self.sb.prep_level() elif event.key == pygame.K_r: self._end_game() def _check_keyup_events(self, event): """ Respond to key releases """ if event.key == pygame.K_RIGHT: self.ship.moving_right = False elif event.key == pygame.K_LEFT: self.ship.moving_left = False def _check_play_button(self, mouse_pos): """ Start a new game if the player clicks Play """ button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: self._start_game() def _check_bullet_alien_collisions(self): """ Respond for bullet-alien collisions """ # Remove any bullet and alien that have collided collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, True) if collisions: for aliens in collisions.values(): self.stats.score += self.settings.alien_points * len(aliens) self.sb.prep_score() self.sb.check_high_score() if not self.aliens: self._start_new_level() def _start_new_level(self): """ Level up the game if all alien ships were destroyed """ # Destroy existing bullets and create new fleet self.bullets.empty() self._create_fleet() self.settings.increase_speed() # Increase level self.stats.level += 1 self.sb.prep_level() def _check_fleet_edges(self): """ Respond appropriately if any aliens have reached the edge """ for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() break def _check_aliens_bottoms(self): """ Check if any aliens have reached the bottom of the screen """ screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: # Treat it the same as if the ship got hit self._ship_hit() break def _change_fleet_direction(self): """ Drop the entire fleet and change the fleet's direction """ for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _create_alien(self, alien_number, row_number): """ Create an alien and place it in the row """ alien = Alien(self) alien_width, alien_height = alien.rect.size # Double indent from left side of the screen for every even row # indent_width = alien_width if row_number % 2 == 0 else 2 * alien_width alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien_height + 2 * alien_height * row_number self.aliens.add(alien) def _create_fleet(self): """ Create the fleet of aliens """ # Create and alien and finds a number of aliens in the row # Spacing between each alien is equal to one alien width alien = Alien(self) alien_width, alien_height = alien.rect.size ship_height = self.ship.rect.height # Defying the number of alien to fill all available space in a row available_space_in_row = self.settings.screen_width - 2 * alien_width number_aliens_in_row = available_space_in_row // (2 * alien_width) # Determine a number of rows of alien to fit the screen available_space_for_rows = self.settings.screen_height - ship_height - (5 * alien_height) number_of_rows = available_space_for_rows // (2 * alien_height) # Creates the fleet of aliens for row_number in range(number_of_rows): for alien_number in range(number_aliens_in_row): self._create_alien(alien_number, row_number) def _end_game(self): """ Set end game conditions """ self.stats.game_active = False self.settings.manual_level = 1 self.sb.store_high_score() pygame.mouse.set_visible(True) def _fire_bullet(self): """ Create a new bullet and add it to the bullets group """ if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _populate_sky(self): """ Place stars on the sky """ for _ in range(self.settings.star_count): star = Star(self) star_width, star_height = star.rect.size star.rect.x = randint(star_width, self.settings.screen_width - star_width) star.rect.y = randint(star_height, self.settings.screen_height - star_height) self.stars.add(star) def _start_game(self): """ Start the game if key pressed or mouse clicked """ # Reset the game stats self.stats.reset_stats() self.settings.initialize_dynamic_settings() self.settings.set_start_speed() self.sb.prep_images() self.stats.game_active = True # Get rid of any remaining aliens and bullets self.aliens.empty() self.bullets.empty() # Create a new fleet and center the ship self._create_fleet() self.ship.center_ship() # Hide the mouse cursor pygame.mouse.set_visible(False) def _ship_hit(self): """ Respond to the ship being hit by an alien """ if self.stats.ships_left > 0: # Decrement ships left and update scoreboard self.stats.ships_left -= 1 self.sb.prep_ships() # Clear the screen from remaining aliens and bullets self.bullets.empty() self.aliens.empty() # Create new fleet and center the ship. self._create_fleet() self.ship.center_ship() # Pause sleep(1) else: self._end_game() def _update_aliens(self): """ Check if the fleet is at an edge, then update the position of all aliens in the fleet """ self._check_fleet_edges() self.aliens.update() if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() # Look for aliens hitting the bottom of the screen self._check_aliens_bottoms() def _update_bullets(self): """ Update position of bullets and get rid of old bullets """ # Update bullet position self.bullets.update() for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) self._check_bullet_alien_collisions() def _update_screen(self): """ Update images on the screen and flip to the new screen """ self.screen.fill(self.settings.bg_color) self.stars.draw(self.screen) self.ship.blit_me() for bullet in self.bullets.sprites(): bullet.draw_bullet() self.aliens.draw(self.screen) # Draw the score information self.sb.show_score() # Draw the play button if the game is inactive if not self.stats.game_active: self.play_button.draw_button() pygame.display.flip()