def test_die_encodings(): """Test the dice are encoded correctly in the attack state.""" agent = RandomAgent() attacker = ship.Ship(name="Attacker", template=ship_templates["Attacker"], upgrades=[], player_number=1) template_front_dice = 0 for color in ['Red', 'Blue', 'Black']: if 0 < len(ship_templates["Attacker"][f"Armament Front {color}"]): template_front_dice += int( ship_templates["Attacker"][f"Armament Front {color}"]) dice_begin = ArmadaTypes.hull_zones.index('front') * len( ArmadaDice.die_colors) dice_end = dice_begin + len(ArmadaDice.die_colors) front_dice = int(attacker.get_range('dice')[dice_begin:dice_end].sum()) # The ship encoding should have the same dice as the template assert front_dice == template_front_dice defender = ship.Ship(name="Defender", template=ship_templates["All Defense Tokens"], upgrades=[], player_number=2) encoding, world_state = make_encoding(attacker, defender, "short", agent) attack_state_encoding = Encodings.encodeAttackState(world_state) die_offset = Encodings.getAttackDiceOffset() # The attack state should have a roll with as many dice as the ship has. dice_encoding = attack_state_encoding[die_offset:die_offset + Encodings.dieEncodingSize()] assert int(dice_encoding.sum().item()) == front_dice
def get_enemy_boats(self, boats): """Create enemy boats off of data connected game has sent.""" self.enemy_placed = True tiles = self.resize_grids.enemy_grid.tiles self.boatgroup.begin() # When game gets reset, old enemy boats are kept to avoid deletion problems # So need to add to list and not reset if self.enemy_boats is None: self.enemy_boats = [ ship.Ship(b[0], tiles[b[2]][b[1]], b[3]) for b in boats ] else: self.enemy_boats.extend( [ship.Ship(b[0], tiles[b[2]][b[1]], b[3]) for b in boats]) for b in self.enemy_boats: b.valid = True b.placed = True x, y = b.tile.x_ind, b.tile.y_ind b.locations = [(x + i, y) if b.horizontal else (x, y + i) for i in range(b.length)] self.boatgroup.end() # Start the game if self boats placed as well if self.placed: self.start_game()
def test_brace(): """Test that brace increases the number of attacks required to destroy a ship.""" attacker = ship.Ship(name="Attacker", template=ship_templates["Attacker"], upgrades=[], player_number=1) no_brace = ship.Ship(name="No Defense Tokens", template=ship_templates["No Defense Tokens"], upgrades=[], player_number=2) one_brace = ship.Ship(name="Single Brace", template=ship_templates["Single Brace"], upgrades=[], player_number=2) two_brace = ship.Ship(name="Double Brace", template=ship_templates["Double Brace"], upgrades=[], player_number=2) # Test with 1000 trials to compensate for the natural variability in rolls for attack_range in ['long', 'medium']: no_brace_attacks = a_vs_b(attacker, no_brace, 1000, attack_range) one_brace_attacks = a_vs_b(attacker, one_brace, 1000, attack_range) two_brace_attacks = a_vs_b(attacker, two_brace, 1000, attack_range) # Only test brace vs no brace at short range since with the test setup the ships reaches 0 hull # before spending all of the brace tokens. for attack_range in ['short']: no_brace_attacks = a_vs_b(attacker, no_brace, 1000, attack_range) one_brace_attacks = a_vs_b(attacker, one_brace, 1000, attack_range) assert (no_brace_attacks < one_brace_attacks) assert (one_brace_attacks < two_brace_attacks)
def setUp(self): self.ship_object = ship.Ship() self.battleship = ship.Ship(position=[2, 2]) self.cruiser = ship.Ship(position=[3, 2], length=4, letter="C") self.destroyer = ship.Ship(position=[4, 2], length=3, letter="D") self.ships = [self.battleship, self.cruiser, self.destroyer] self.shooting_range = {"45": "o", "23": "x", "11": "o"}
def setUp(self): self.player_object = player.Player() self.human_object = player.Human() self.AI_object = player.AI() self.battleship = ship.Ship(position=[2, 2]) self.cruiser = ship.Ship(position=[3, 2], length=4, letter="C") self.player_object.ships = [self.battleship, self.cruiser] self.shooting_range = {"45": "o", "23": "x", "11": "o"}
def test_accuracy_encodings(): """Test that the encoding is correct for dice targetted by an accuracy.""" agent = LearningAgent() attacker = ship.Ship(name="Attacker", template=ship_templates["Attacker"], upgrades=[], player_number=1) three_brace = ship.Ship(name="Double Brace", template=ship_templates["Triple Brace"], upgrades=[], player_number=2) # Make a brace token red three_brace.spend_token('brace', ArmadaTypes.green) enc_three_brace, world_state = make_encoding(attacker, three_brace, "short", agent) # Define the offsets for convenience token_begin = Encodings.getAttackTokenOffset() token_end = token_begin + ArmadaTypes.max_defense_tokens # Verify that no tokens are targeted at first assert 0.0 == enc_three_brace[token_begin:token_end].sum() # Now make a token red and target it three_brace.spend_token('brace', ArmadaTypes.green) green_acc_begin = Encodings.getAttackTokenOffset() green_acc_end = green_acc_begin + len(ArmadaTypes.defense_tokens) red_acc_begin = Encodings.getAttackTokenOffset() + len( ArmadaTypes.defense_tokens) red_acc_end = red_acc_begin + len(ArmadaTypes.defense_tokens) world_state.attack.accuracy_defender_token( ArmadaTypes.defense_tokens.index('brace'), ArmadaTypes.red) encoding = Encodings.encodeAttackState(world_state) # Verify that only the red token has the accuracy flag set assert encoding[red_acc_begin + ArmadaTypes.defense_tokens.index('brace')].item() == 1. assert encoding[red_acc_begin:red_acc_end].sum().item() == 1. assert encoding[green_acc_begin:green_acc_end].sum().item() == 0. # Target both remaining green tokens world_state.attack.accuracy_defender_token( ArmadaTypes.defense_tokens.index('brace'), ArmadaTypes.green) world_state.attack.accuracy_defender_token( ArmadaTypes.defense_tokens.index('brace'), ArmadaTypes.green) encoding = Encodings.encodeAttackState(world_state) # Verify that two green and one red brace have the accuracy flag assert encoding[red_acc_begin + ArmadaTypes.defense_tokens.index('brace')].item() == 1. assert encoding[red_acc_begin:red_acc_end].sum().item() == 1. assert encoding[green_acc_begin + ArmadaTypes.defense_tokens.index('brace')].item() == 2. assert encoding[green_acc_begin:green_acc_end].sum().item() == 2.
def setUp(self): self.start_x = 1 self.start_y = 1 self.size = 3 self.orientation = 'H' self.testShip1 = ship.Ship(self.start_x, self.start_y, self.size, self.orientation) self.testShip2 = ship.Ship(self.start_x + 1, self.start_y + 1, self.size, 'V') self.testBoard = board.Board(10) self.testShip1.place(self.testBoard) self.testShip2.place(self.testBoard)
def playBattleship(): ''' Function controlling the gameplay ''' ## Create the board main_board = B.Board(10) main_board.display() pc_board = B.Board(10) ## Get each of the ships and place them on the board recon = S.Ship(2, 'reconnaissance ship', pc_board) destroyer = S.Ship(3, 'destroyer ship', pc_board) submarine = S.Ship(3, 'submarine', pc_board) battle = S.Ship(4, 'battle ship', pc_board) carrier = S.Ship(5, 'carrier', pc_board) ## Start the main game loop, playing until all the ships are sunk hit_count = 0 recon_count, dest_count, sub_count, batt_count, carr_count = 0, 0, 0, 0, 0 n_hits = recon._length + destroyer._length + submarine._length + battle._length + carrier._length while hit_count < n_hits: guess = [ main_board.convertX(raw_input("Guess Column: ")), main_board.convertY(raw_input("Guess Row: ")) ] if main_board.legalGuess(guess): if guess in recon._location: hit_count, recon_count = recon.hit(guess, hit_count, main_board, recon_count) elif guess in destroyer._location: hit_count, dest_count = destroyer.hit(guess, hit_count, main_board, dest_count) elif guess in submarine._location: hit_count, sub_count = submarine.hit(guess, hit_count, main_board, sub_count) elif guess in battle._location: hit_count, batt_count = battle.hit(guess, hit_count, main_board, batt_count) elif guess in carrier._location: hit_count, carr_count = carrier.hit(guess, hit_count, main_board, carr_count) else: print 'MISS!' main_board.fill(guess, 'M') else: continue main_board.display() else: print 'Congratualtions! You sank the fleet'
def test_random_agent(): """Test all possible defense tokens are used and accuracy target everything.""" attacker = ship.Ship(name="Attacker", template=ship_templates["Attacker"], upgrades=[], player_number=1) ship_a = ship.Ship(name="Ship A", template=ship_templates["All Defense Tokens"], upgrades=[], player_number=1) ship_b = ship.Ship(name="Ship B", template=ship_templates["All Defense Tokens"], upgrades=[], player_number=2) # Verify that all of the defense tokens are being used and accuracied. use_counts = torch.zeros(len(ArmadaTypes.defense_tokens)) accuracy_targets = torch.zeros(2 * len(ArmadaTypes.defense_tokens)) # Test with 10 trials at each range to compensate for the natural variability in rolls attacks = [] for attack_range in ['long', 'medium', 'short']: attacks = attacks + a_vs_b(ship_a, ship_b, 100, attack_range) # Loop through all attacks and increment the used tokens for attack in attacks: if 'state' == attack[0] and attack[ 1].sub_phase == "attack - resolve damage": # Check the spent token types use_counts += torch.Tensor(attack[1].attack.spent_types) # We aren't handling the salvo token yet, but check that the others are being spent. for tidx, token in enumerate(ArmadaTypes.defense_tokens): if 'salvo' != ArmadaTypes.defense_tokens[tidx]: assert 0 < use_counts[tidx].item() # Check accuracy usage for attack in attacks: if 'state' == attack[0] and attack[ 1].sub_phase == "attack - spend defense tokens": # Check the spent tokens from the previous resolve attack effects phase tokens_left = len(attack[1].attack.accuracy_tokens) accuracy_targets[:tokens_left] += torch.Tensor( attack[1].attack.accuracy_tokens) # Check that accuracies are used against any of the tokens. print("accuracy targets are {}".format(accuracy_targets)) for tidx, token in enumerate(ArmadaTypes.defense_tokens): if 'salvo' != ArmadaTypes.defense_tokens[tidx]: assert 0 < accuracy_targets[tidx]
def test_spent_encodings(): """Test that the encoding is correct for different defense tokens.""" agent = LearningAgent() attacker = ship.Ship(name="Attacker", template=ship_templates["Attacker"], upgrades=[], player_number=1) defender = ship.Ship(name="Defender", template=ship_templates["All Defense Tokens"], upgrades=[], player_number=2) encoding, world_state = make_encoding(attacker, defender, "short", agent) # The defender and attacker come first, then the accuracied tokens, then the spent tokens spent_begin = 2 * ship.Ship.encodeSize() + 2 * len( ArmadaTypes.defense_tokens) spent_end = spent_begin + len(ArmadaTypes.defense_tokens) # Verify that no tokens are marked spent by default assert torch.sum(encoding[spent_begin:spent_end]) == 0. # Spend all of the tokens for tidx, ttype in enumerate(ArmadaTypes.defense_tokens): world_state.attack.defender_spend_token(ttype, 'green') encoding = Encodings.encodeAttackState(world_state) assert torch.sum(encoding[spent_begin:spent_end]).item() == len( ArmadaTypes.defense_tokens) # Try spending the tokens at different indices for tidx, ttype in enumerate(ArmadaTypes.defense_tokens): # Re-encode and then set the token to spent. attacker = ship.Ship(name="Attacker", template=ship_templates["Attacker"], upgrades=[], player_number=1) defender = ship.Ship(name="Defender", template=ship_templates["All Defense Tokens"], upgrades=[], player_number=2) encoding, world_state = make_encoding(attacker, defender, "short", agent) world_state.attack.defender_spend_token(ttype, 'green') encoding = Encodings.encodeAttackState(world_state) assert torch.sum(encoding[spent_begin:spent_end]).item() == 1.0 assert encoding[spent_begin:spent_end][tidx].item() == 1.0
def __init__(self, width, height): self.mWorldWidth = width self.mWorldHeight = height shipx = random.randint(0, self.mWorldWidth) shipy = random.randint(0, self.mWorldHeight) self.mShip = ship.Ship(shipx, shipy, self.mWorldWidth, self.mWorldHeight) self.mBullet = [] NUM_ROCKS = random.randint(10, 20) self.mRocks = [] for i in range(NUM_ROCKS): rockx = random.randint(0, self.mWorldWidth) rocky = random.randint(0, self.mWorldHeight) rocks = rock.Rock(rockx, rocky, self.mWorldWidth, self.mWorldHeight) self.mRocks.append(rocks) NUM_STARS = 20 self.mStars = [] for i in range(NUM_STARS): starsx = random.randint(0, self.mWorldWidth) starsy = random.randint(0, self.mWorldHeight) stars = star.Star(starsx, starsy, self.mWorldWidth, self.mWorldHeight) self.mStars.append(stars) self.mObjects = self.mRocks[:] + [self.mShip] + self.mStars[:]
def __init__(self): # Variables for game state self.score = 0 self.state = 1 self.multiplier = 1 self.gas = 0 self.playing = True # Used to see if there is no collision (0), a crash (1), or a potential landing (2) self.collided = 0 # Variables for physics self.dt = .01 self.xVel = 0 self.yVel = 0 self.x = 0 self.y = 0 self.ang = 0 # Used to see what kind of landing: good landing (1), hard landing (2), or a crash (3) self.landingType = 0 # Ship and terrain objects self.ship = lander.Ship() self.terrain = land.Terrain() self.xTerrain = [] self.yTerrain = [] # Used to schedule a life reset after the landing/crash screen self.resetScheduled = False
def __init__(self, ship_obj): self.track = Soundtrack() self.scene = ship_obj.scene self.ship = ship.Ship(ship_obj) self.ship.on_end.append(self.end_game) self.hud = None if not os.path.exists(hud.SCREENSHOT_PATH): os.mkdir(hud.SCREENSHOT_PATH) for file_name in os.listdir(hud.SCREENSHOT_PATH): os.remove(os.path.join(hud.SCREENSHOT_PATH, file_name)) self.loaded = False self._fallen_message = False self._logbook_message = False self.areas = {o['AREA']: o for o in self.scene.objects if 'AREA' in o} self.messages = { o['MESSAGE']: o for o in self.scene.objects if 'MESSAGE' in o } self.been_areas = [] self.heard_messages = [] self.finished = False
def __init__(self): # INITIALIZE if self.fullscreen: self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) else: self.screen = pygame.display.set_mode(self.resolution) pygame.font.init() # RUN LEVEL VARIABLES self.my_ship = ship.Ship() self.crew = [crew.Crew()] self.mood = mood.Mood() self.states = [Encounter()] # LOAD GRAPHICS self.myfont = pygame.font.SysFont('Courier New', self.font_scale) self.bar_gui = pygame.image.load("bitmaps/bar_gui.bmp") self.cursor = pygame.image.load("bitmaps/cursor.bmp").convert() self.cursor.set_colorkey(self.black) paths_red_img = pygame.image.load("bitmaps/pathsRed.bmp").convert() self.pathsRed = [''] * 6 for i in range(6): rect = pygame.Rect((12 * i, 0, 12, 12)) self.pathsRed[i] = pygame.Surface(rect.size).convert() self.pathsRed[i].blit(paths_red_img, (0, 0), rect) self.pathsRed[i].set_colorkey((0, 0, 0)) # UPDATE self.update()
def run_game(): # 初始化pygame所有模块 pygame.init() # 构建窗口,大小为 800 * 600 #screen = pygame.display.set_mode((800, 600)) # 设置窗口名称未alien_invasion #pygame.display.set_caption('alien_invasion') # 背景设置为一种浅灰色。 #bc_color = (230, 230, 230) # 实例化Settings类 ai_settings = bs.Settings() # 构建窗口,大小为 800 * 600 screen = pygame.display.set_mode( (ai_settings.screen_width, ai_settings.screen_height)) # 设置窗口名称未alien_invasion pygame.display.set_caption('alien_invasion') # 创建一艘飞船 ship = sp.Ship(ai_settings, screen) # dog = dg.Dog(screen) bullets = Group() # 开始游戏循环 while True: # 监听键盘和鼠标事件 gf.check_events(ai_settings, screen, ship, bullets) # 执行循环时都调用飞船的方法 update ship.update() # 执行循环时都调用bullet的方法 update_bullets gf.update_bullets(bullets) # 更新屏幕状态 # gf.update_screen(ai_settings, screen, ship, dog) gf.update_screen(ai_settings, screen, ship, bullets)
def addPlayer(self, x, y): self.ship = ship.Ship(x, y) self.ship.load(self.drawManager) self.camera.setTarget(self.ship) # when we get the player from the server, we unpause :D self.paused = False
def prep_ships(self): self.ships = pygame.sprite.Group() for ship_number in range(self.stats.ships): ship_init = ship.Ship(self.screen, self.settings) ship_init.rect.x = 10 + ship_number * ship_init.rect.width ship_init.rect.y = 10 self.ships.add(ship_init)
def __init__(self, world_width, world_height): self.mWorldWidth = world_width self.mWorldHeight = world_height shipX = self.mWorldWidth / 2 shipY = self.mWorldHeight / 2 self.mShip = ship.Ship(shipX, shipY, self.mWorldWidth, self.mWorldHeight) self.mRocks = [] self.mObjects = [self.mShip] # rocks for x in range(10): rockX = random.randrange(0, self.mWorldWidth) rockY = random.randrange(0 , self.mWorldHeight) rock1 = rock.Rock(rockX, rockY, world_width, world_height) self.mRocks.append(rock1) self.mObjects.append(rock1) #stars self.mStars = [] for x in range(20): starX = random.randrange(0, self.mWorldWidth) starY = random.randrange(0, self.mWorldHeight) star1 = star.Star(starX, starY, self.mWorldWidth, self.mWorldHeight ) self.mStars.append(star1) self.mObjects.append(star1) self.mBullets = [] self.mGameLost = False self.mGameWon = False
def on_init(self): pygame.init() pygame.font.init() self._display_surf = pygame.display.set_mode( self.size, pygame.HWSURFACE | pygame.DOUBLEBUF) self.player = ship.Ship(self.width / 1.5, self.height / 1.5) self.keyboard = keyboard.Keyboard() self.mainMenuFont = basic_font.basic_Text() self.mainMenuFont.setCenter(self.width / 2 - 50, self.height / 3) self.mainMenuFont.setText("Main Menu") self.playFont = basic_font.basic_Text() self.playFont.setCenter(self.width / 2 - 20, self.height / 2) self.playFont.setColor((0, 0, 0)) self.playFont.setText("Play") self.playAstroid = astroid.Astroid(self.width / 2, self.height / 2, 0) self.playAstroid.changeAngles([[67, 22.5], [35, 67.5], [42, 112.5], [60, 157.5], [52, 202.5], [31, 247.5], [33, 292.5], [62, 337.5]]) self.playAstroid.calculateRectangle()
def __init__(self, asteroids_amnt): """ Initialize a new Game object. :param asteroids_amnt (int): the amount of asteroids in the start of the game. The function will set a new screen object. The function will set a new ship object. The function will create asrteroids and will make sure that the starting point is different that the ship's. :return: A new Game object. """ self._screen = Screen() self.screen_max_x = Screen.SCREEN_MAX_X self.screen_max_y = Screen.SCREEN_MAX_Y self.screen_min_x = Screen.SCREEN_MIN_X self.screen_min_y = Screen.SCREEN_MIN_Y board_size = (self.screen_max_x, self.screen_max_y, self.screen_min_x, self.screen_min_y) self.board_size = board_size self.ship = ship.Ship(board_size) self.score = STARTING_SCORE self.torpedos = [] self.asteroids = [] for i in range(asteroids_amnt): new_asteroid = asteroid.Asteroid(board_size) #making sure asteroids aren't created on the ship while new_asteroid.get_x_pos() == self.ship.get_x_pos() and \ new_asteroid.get_y_pos() == self.ship.get_y_pos(): new_asteroid = asteroid.Asteroid(board_size) self.asteroids.append(new_asteroid) self._screen.register_asteroid(self.asteroids[i], self.asteroids[i].get_size())
def __init__(self, asteroids_amnt): """ A constructor for a gamerunner object :param asteroids_amnt = the amount of asteroids the game will start with. """ self._screen = Screen() self.screen_max_x = Screen.SCREEN_MAX_X self.screen_max_y = Screen.SCREEN_MAX_Y self.screen_min_x = Screen.SCREEN_MIN_X self.screen_min_y = Screen.SCREEN_MIN_Y self._ship = ship.Ship() self._screen.draw_ship(self._ship.x(), self._ship.y(), self._ship.get_direction()) self.asteroid_list = [] for i in range(asteroids_amnt): self.asteroid_list.append(asteroid.Asteroid(self._ship)) registered_asteroid_list = [] for an_asteroid in self.asteroid_list: self._screen.register_asteroid(an_asteroid, an_asteroid.size) self._screen.draw_asteroid(an_asteroid, an_asteroid.x(), an_asteroid.y()) self.torpedo_list = [] self.score = 0
def runGame(): pygame.init() cfg = config.Config() # config 实例 screen = pygame.display.set_mode( (cfg.screen_width, cfg.screen_height)) # 设置背景 stats = state.Stats(cfg) player_ship = ship.Ship(screen) # ship 实例 common_bullets = Group() # 创建子弹编组 super_bullets = Group() targets = Group() # function.createTargets(cfg, screen, player_ship, targets) pygame.display.set_caption(cfg.title) pygame.display.set_icon(pygame.image.load('resource/ship.bmp')) # print('InitSuccess') start_button = ui.UI(screen, 'Start') while True: function.checkEvent(cfg, screen, player_ship, common_bullets, super_bullets, stats, start_button, targets) if stats.game_activate: player_ship.update() # 玩家ship位置刷新 function.updateBullets(cfg, common_bullets, targets, super_bullets, screen, player_ship, stats) function.updateTargets(cfg, targets, player_ship, stats, common_bullets, screen) function.updateScreen(screen, cfg, player_ship, common_bullets, targets, super_bullets, start_button, stats)
def simulate_player(self, possibilities, sunk_ships): sunk_ships_copy = copy.deepcopy(sunk_ships) ship_sizes = [5, 4, 3, 3, 2] random.shuffle(ship_sizes) temp_grid = grid.Grid() for size in ship_sizes: if size in sunk_ships_copy: possible_locations = [sunk_ships_copy[size]] sunk_ships_copy.pop(size) else: possible_locations = list(possibilities[size]) random.shuffle(possible_locations) ship_added = False for location in possible_locations: square, direction = location col, row = square ship_str = ' '.join([str(size), col, row, direction]) new_ship = ship.Ship(ship_str) if temp_grid.add_ship(new_ship): ship_added = True break if not ship_added: # ran out of locations return [] if self.shots_hit <= temp_grid.occupied_squares(): return list(temp_grid.occupied_squares()) return []
def run_game(): pygame.init() # 初始化 set = settings.Settings() # 创建对象set获取Settings中的info screen = pygame.display.set_mode( (set.screen_width, set.screen_height)) # 这里填的是元组 pygame.display.set_caption("Chenlicheng") # 设置标题 ship_1 = ship.Ship(screen, set) # 创建了一艘船的实例 bullets = pygame.sprite.Group() # 创建了一个精灵的编组 aliens = pygame.sprite.Group() # 创建了一个外星人的编组 stats = game_stats.GameStats(set) sb = scoreboard.Scoreboard(stats, set, screen) #创建一个积分的实例 play_button = button.Button(screen, "play") game_functions.create_fleet(screen, set, aliens, ship_1) # 创建了一些外星人,并且把它放到编组里 while True: # 检查必须保持活跃,不然无法回到游戏中 game_functions.check_events(ship_1, screen, bullets, set, play_button, stats) # 位置实参 if stats.game_active: # 飞船,子弹,外星人不再刷新,但是保持屏幕active ship_1.update() # 更新ship的位置 game_functions.update_bullets(bullets, aliens, set, screen, ship_1, stats, sb) game_functions.update_aliens(aliens, set, ship_1, stats, bullets, screen, sb) game_functions.update_screen(set, screen, ship_1, bullets, aliens, stats, play_button, sb)
def __init__(self): """Initialize the game, and create game resources.""" pygame.init() self.settings = settings.Settings() # Start game in an inactive state. self.game_active = False self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height) ) # 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 = game_stats.GameStats(self) self.sb = scoreboard.Scoreboard(self) self.ship = ship.Ship(self) self.background = background.Background(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self._create_fleet() # Make the Play button. self.play_button = button.Button(self, "Play")
def __init__(self, worldwidth, worldheight): self.mWorldWidth = worldwidth self.mWorldHeight = worldheight self.mTurret = turret.Turret(self.mWorldWidth, self.mWorldHeight) self.mBunkers = [] self.mBullet = None self.mBombs = [] self.mLives = 3 self.mScore = 0 self.mFont = pygame.font.SysFont('arial',30,True) self.mText ="" self.mShipStartHeight = 40 self.mShipStartSpeed = 8 self.mDisplayGameOverText = False self.mFireRate = 1 for i in range(4): bunk = bunker.Bunker((self.mWorldWidth//4) - 60 + i * 140, self.mWorldHeight - 150, self.mWorldWidth, self.mWorldHeight) self.mBunkers.append(bunk) self.mShips = [] for i in range(11): shipColumn = [] for j in range(5): s = ship.Ship(40 + i*50, self.mShipStartHeight + (j * 50), self.mWorldWidth, self.mWorldHeight, self.mShipStartSpeed, 0) shipColumn.append(s) self.mShips.append(shipColumn)
def generate_field(): """ None -> list(list(str)) Generates random field. """ ships = [] field = [[None for i in range(10)] for i in range(10)] number_of_ships = [i for i in range(1, 5)] possible_coordinates = [(i, j) for i in range(10) for j in range(10)] for ship_type in range(len(number_of_ships)): for g_ship in range(number_of_ships[ship_type]): while True: bow = random.choice(possible_coordinates) length = tuple(random.sample([1, 4 - ship_type], 2)) new_ship = ship.Ship(bow, length) if not new_ship.is_valid(possible_coordinates): continue # Calculating new possible coordinates for next ships new_ship_area = new_ship.covered_area() for coordinates in new_ship_area: if coordinates in possible_coordinates: possible_coordinates.remove(coordinates) ships.append(new_ship) for line in range(new_ship.bow[0], new_ship.bow[0] + new_ship._length[0]): for column in range(new_ship.bow[1], new_ship.bow[1] + new_ship._length[1]): field[line][column] = new_ship break return ships, field
def run_game(): pygame.init() ai_setting = setting.Setting() #创建配置对象 screen = pygame.display.set_mode( (ai_setting.screen_width, ai_setting.screen_hight)) #设置屏幕大小 pygame.display.set_caption("Alien Invasion") #设置标题 #创建存储统计信息的对象 stats = GameStats(ai_setting) sb = Scoreboard(ai_setting, screen, stats) play_button = Button(screen, 'PLAY') ships = ship.Ship(screen, ai_setting) #创建飞船 bullets = Group() aliens = Group() #game_functions.create_fleet(ai_setting,screen,ships,aliens)#创建外星人群 while True: game_functions.check_events(ai_setting, stats, sb, play_button, aliens, screen, ships, bullets) #监控按键和视窗 if stats.game_active: ships.update() #飞船状态更新 game_functions.update_bullets(ai_setting, screen, sb, stats, ships, aliens, bullets) #子弹状态更新 game_functions.update_aliens(ai_setting, screen, sb, stats, ships, aliens, bullets) #外星人状态更新 game_functions.update_screen(ai_setting, stats, sb, screen, ships, aliens, bullets, play_button) #屏幕物体刷新
def game(): pygame.init() game_settings = settings.Settings() screen = pygame.display.set_mode( (game_settings.width, game_settings.height)) pygame.display.set_caption("Space Invaders") play_button = play.Button(settings, screen, "Play") stats = statistics.GameStats(game_settings) scoreboard = score.Score(game_settings, screen, stats) player_render = ship.Ship(screen, game_settings) bullets = pygame.sprite.Group() alien_group = pygame.sprite.Group() functions.alien_fleet(game_settings, screen, alien_group) while True: functions.check_events(game_settings, screen, player_render, bullets, play_button, stats, alien_group, scoreboard) if stats.game_active: player_render.update() functions.update_bullets(alien_group, bullets, screen, game_settings, scoreboard, stats) functions.update_aliens(game_settings, stats, player_render, alien_group, screen, bullets, scoreboard) functions.update_screen(game_settings, screen, player_render, alien_group, bullets, play_button, stats, scoreboard)
def test_message(self): self.site.post_msg( message.Message(self.ship0, message.Message.LEAVING, "Goodbye")) msg = next(self.site.get_msg()) self.assertEquals(message.Message.LEAVING, msg.type) self.assertEqual("Goodbye", msg.content) self.site.post_msg( message.Message(self.ship0, message.Message.LANDING_REQUEST)) self.site.run() self.assertIs(self.site.slots[0], self.ship0) # We don't accept a same ship two times self.site.post_msg( message.Message(self.ship0, message.Message.LANDING_REQUEST)) self.site.run() self.assertEquals(1, len(self.site.slots)) # On surcharge l'arrivée for it in range(5): tmp_ship = ship.Ship( universe.Universe.get_universe().get_planet("Planet_0")) self.site.post_msg( message.Message(tmp_ship, message.Message.LANDING_REQUEST)) self.site.run() # 5 slots, one ship already present if (it < 4): self.assertEquals(message.Message.LANDING_ACCEPTED, next(tmp_ship.get_msg()).type) else: self.assertEquals(message.Message.LANDING_REFUSED, next(tmp_ship.get_msg()).type)