def __init__(self, manager): """manager is required to be a child of GameManager with these functions: -kill_player() -next_level() -add_score(amount) -give_energy(amount) -spend_energy(amount) -give_life() """ GameState.__init__(self, manager) self.player = Ship(*opt.player_args) self.enemy = EnemyBase(opt.mover_args, opt.spinner_args, opt.shooter_args, self.player) self.shield = EnemyShield(self.enemy, opt.shield_filename, formation, formation_center) self.hbullet = HomingBullet(opt.homer_filename, self.player, opt.homer_speed) self.cannon = Cannon(opt.deactivated_cannon_args, opt.standby_cannon_args, opt.firing_cannon_args, self.player) self.ion_field = IonField(*opt.ion_field_args) self.player_bullets = Group() self.reset_positions()
def __init__(self): """Initialize the game and create game resources""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) self.background = self.settings.background_image pygame.display.set_caption("Pirate Invasion") #Create an instance to store game statistics #and create a score # board self.cannon = Cannon(self) self.stats = GameStats(self) self.sb = Scoreboard(self) self.cannonballs = pygame.sprite.Group() self.pirates = pygame.sprite.Group() self._create_fleet() #Make the Play button self.play_button = Button(self, "Start Fight!") #Set the background color self.bg_color = (62, 164, 236) #Set background song mixer.music.load( 'C:/Users/Khyr/Desktop/CIT228/Sideways_Shooter/music/music.wav') mixer.music.play(-1) mixer.music.set_volume(0.2)
def create_cannon(self): """Creates a digimon to control""" sprite_group = pygame.sprite.Group() for i in range(0, 10): cannon = Cannon(randint(0, 1000) + i * 1000, 50) sprite_group.add(cannon) return sprite_group
def __init__(self, screen, angle, x, y, sizey, team, flags, strength, play=True, defense=False): super().__init__() if team == "green": file1, file2, fileFlag, fileBall = greenCannon elif team == "blue": file1, file2, fileFlag, fileBall = blueCannon coords = np.array([x, y], dtype=float) self.troops = [] for i in range(sizey): """ x displacement from center of Battery based on count shiftx increases with count with a period of sizey, creating a row of soldiers with a length of sizey """ shifty = C_GAPY * ((i % sizey) - sizey // 2) shiftx = 0 self.troops.append(Cannon(screen, angle, shiftx, shifty, strength, file1, file2, fileBall, team, coords, defense)) self.flag = Flag(screen, (x, y), angle, fileFlag, play) flags.append(self.flag) # 0,1=click,release to show buttons, 2,3=click,release to select self.showOrders = 0 # self.bayonetButton = Button(screen, "Bayonets") self.healthDisp = Button(screen, str(self.health)) self.play = play self.team = team self.oldUnits = [] # used to id object for testing, not meant to be seen/used self.id = file1
def prep_cannons(self): """Show how many cannons are left""" self.cannons = Group() for cannon_number in range(self.stats.cannons_left): cannon = Cannon(self.ai_game) cannon.rect.x = 1000 + cannon_number * cannon.rect.width cannon.rect.y = 10 self.cannons.add(cannon)
def btnNewGameClicked(self): # target 위치 지정 self.targetColumn = random.randint(40, 60) self.targetRow = random.randint(18, 21) self.target = (self.targetRow, self.targetColumn) # 게임 시작시 초기화 self.cannon = Cannon(self.target) self.fire = Fire() self.gameOver = False self.boulet = ["●", "●", "●", "●"] self.turn = -1 self.txWindow.setText(self.cannon.initialMap()) self.lnResult.setText('Start!') self.lnBoulet.setText(" ".join(self.boulet)) self.slAngle.setValue(55) self.slPower.setValue(40)
def init_modules(): right_eye = Eye(list(range(12)), (100, 0, 0)) left_eye = Eye(list(range(12, 24)), (100, 0, 0)) left_eye.eye_time = right_eye.eye_time # Pretty hacky but syncronizes the pulse # gills gills = Gills([Gill(list(range(24, 69)), color=(0, 0, 20), intensity=1.0)], [Gill(list(range(71, 131)), color=(0, 0, 20), intensity=1.0)]) # treat all as lefties for now... cannon = Cannon() return {'gills': gills, 'left_eye': left_eye, 'right_eye': right_eye, 'cannon': cannon, 'compass': Compass()}
def btnFireClicked(self): self.cannon = Cannon(self.target) # 각도 와 파워 설정 try: angle = int(self.slAngle.value()) power = int(self.slPower.value()) except: self.lnResult.setText('Not integer') return # 게임 완료 시 if self.gameOver == True: self.lnResult.setText('Game Over') return # 현재 맵 출력 for point in self.fire.parabola(angle, power): shape = self.cannon.currentMap(point)[0] hit = self.cannon.currentMap(point)[1] self.txWindow.setText(shape) if hit: self.lnResult.setText('Hit!') self.gameOver = True break else: self.lnResult.setText('Miss!') # 에니메이션 효과 구현 loop = QEventLoop() QTimer.singleShot(100, loop.quit) loop.exec_() if self.boulet[0] == "○": self.lnResult.setText('Fail!') self.gameOver = True return del (self.boulet[self.turn]) self.turn -= 1 self.boulet.append("○") self.lnBoulet.setText(" ".join(self.boulet))
def start(): global score, lives, level, stage, bomb_rate, cannon bomb_rate = starting_bomb_rate score = 0 lives = 3 level = 1 stage = START cannon = Cannon(480, 530) setup()
def generate_cannon(self): if self._ground.get_x() < ARENA_W: actors = self._arena.actors() cannon_available = True rand_cannon_x = randint(ARENA_W, ARENA_W*2) for a in self._obstacles: if isinstance(a, Cannon) or rand_cannon_x == a.get_x(): cannon_available = False if cannon_available: self._obstacles.append(Cannon(self._arena, (rand_cannon_x, 570)))
def calculate_percentile(duration, max_qps, cannon: Cannon): df = create_dataframe() for i in range(100, max_qps, 10): latency_list = cannon.start_shoot(max_qps, duration, threads=int(max_qps / 10)) df.loc[i] = [duration, duration*(i+1), i+1, calc_percentile(.5, latency_list), calc_percentile(.9, latency_list), calc_percentile(.99, latency_list), 100*latency_list.count(None)/len(latency_list)] return df
class PirateInvasion: """Class to manage game assets and behavior""" def __init__(self): """Initialize the game and create game resources""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode( (self.settings.screen_width, self.settings.screen_height)) self.background = self.settings.background_image pygame.display.set_caption("Pirate Invasion") #Create an instance to store game statistics #and create a score # board self.cannon = Cannon(self) self.stats = GameStats(self) self.sb = Scoreboard(self) self.cannonballs = pygame.sprite.Group() self.pirates = pygame.sprite.Group() self._create_fleet() #Make the Play button self.play_button = Button(self, "Start Fight!") #Set the background color self.bg_color = (62, 164, 236) #Set background song mixer.music.load( 'C:/Users/Khyr/Desktop/CIT228/Sideways_Shooter/music/music.wav') mixer.music.play(-1) mixer.music.set_volume(0.2) def run_game(self): """Start the main loop for game""" while True: self._check_events() if self.stats.game_active: self.cannon.update() self._update_cannonballs() self._update_pirates() self._update_screen() def _check_events(self): """Respond to keypresses & mouse events""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN or event.type == ord('s'): self._check_keydown_events(event) elif event.type == pygame.KEYUP or event.type == ord('w'): 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""" #Set the cannonball sound cannonballSound = pygame.mixer.Sound( 'C:/Users/Khyr/Desktop/CIT228/Sideways_Shooter/music/sound.wav') mixer.music.set_volume(0.2) if event.key == pygame.K_UP or event.key == ord('w'): self.cannon.moving_up = True elif event.key == pygame.K_DOWN or event.key == ord('s'): self.cannon.moving_down = True elif event.key == pygame.K_q: sys.exit() elif event.key == pygame.K_SPACE: self._fire_cannonball() cannonballSound.play() def _check_keyup_events(self, event): if event.key == pygame.K_UP or event.key == ord('w'): self.cannon.moving_up = False elif event.key == pygame.K_DOWN or event.key == ord('s'): self.cannon.moving_down = False def _check_play_button(self, mouse_pos): """Start a new game when the player clicks Play""" button_clicked = self.play_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: #Reset the game settings self.settings.intitalize_dynamic_settings() #Reset the game statistics self.stats.reset_stats() self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_cannons() #Get rid of any remaining pirates and cannonballs self.pirates.empty() self.cannonballs.empty() #Create a new fleet and center the cannon self._create_fleet() self.cannon.center_cannon() #Hide the mouse cursor pygame.mouse.set_visible(False) def _fire_cannonball(self): """Create a new cannonball and add to the cannonball group""" if len(self.cannonballs) < self.settings.cannonballs_allowed: new_cannonball = Cannonball(self) self.cannonballs.add(new_cannonball) def _update_cannonballs(self): """Update the position of cannonballs and get rid of old cannonballs""" #Update cannonball positions self.cannonballs.update() #Get rid of cannonballs off screen for cannonball in self.cannonballs.copy(): if cannonball.rect.bottom <= 0: self.cannonballs.remove(cannonball) self._check_cannonball_pirate_collisions() def _check_cannonball_pirate_collisions(self): """Respond to cannonball-pirate collisions""" #Remove any cannonballs and pirates that have collided collisions = pygame.sprite.groupcollide(self.cannonballs, self.pirates, True, True) if collisions: for pirates in collisions.values(): self.stats.score += self.settings.pirate_points * len(pirates) self.sb.prep_score() self.sb.check_high_score() if not self.pirates: #Destroy existing cannonballs and create new fleet self.cannonballs.empty() self._create_fleet() self.settings.increase_speed() #Increase level self.stats.level += 1 self.sb.prep_level() def _update_pirates(self): """Check if the fleet is at an edge, then update the positions of all the pirates in fleet""" self._check_fleet_edges() self.pirates.update() #Look for pirate-cannon collisions if pygame.sprite.spritecollideany(self.cannon, self.pirates): self._cannon_hit() #Look for pirates hitting the bottom of the screen self._check_pirates_bottom() def _cannon_hit(self): """Respond to cannon being hit by a pirate""" if self.stats.cannons_left > 0: #Decrement cannons_left, and update scoreboard self.stats.cannons_left -= 1 self.sb.prep_cannons() #Get rid of any remaining pirates and cannonballs self.pirates.empty() self.cannonballs.empty() #Create a new fleet and center the cannon self._create_fleet() self.cannon.center_cannon() #Pause sleep(0.5) else: self.stats.game_active = False pygame.mouse.set_visible(True) def _check_pirates_bottom(self): """Check if any pirates have reached the bottom of the screen""" screen_rect = self.screen.get_rect() for pirate in self.pirates.sprites(): if pirate.rect.bottom >= screen_rect.bottom: #Treat this the same as if teh cannon got hit self._cannon_hit() break def _update_screen(self): """Updates images on the screen, flip to the new screen""" self.screen.blit(self.background, [0, 0]) self.cannon.blitme() for cannonball in self.cannonballs.sprites(): cannonball.draw_cannonball() self.pirates.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() #Make the most recent drawn screen visible pygame.display.flip() def _create_fleet(self): """Make a fleet of pirates""" #Create a pirate ship and find the number of pirates in a row #Spacing between each pirate is equal to one pirate width pirate = Pirate(self) pirate_width, pirate_height = pirate.rect.size available_space_x = self.settings.screen_width - (2 * pirate_width) number_pirates_x = available_space_x // (2 * pirate_width) #Determine the number of rows of pirates that fit on screen cannon_height = self.cannon.rect.height available_space_y = (self.settings.screen_height - (3 * pirate_height) - cannon_height) number_rows = available_space_y // (2 * pirate_height) #Create a full fleet of pirates for row_number in range(number_rows): for pirate_number in range(number_pirates_x): self._create_alien(pirate_number, row_number) def _create_alien(self, pirate_number, row_number): #Create pirate and place in row pirate = Pirate(self) pirate_width, pirate_height = pirate.rect.size pirate.x = pirate_width + 2 * pirate_width * pirate_number pirate.rect.x = pirate.x pirate.rect.y = pirate.rect.height + 2 * pirate.rect.height * row_number self.pirates.add(pirate) def _check_fleet_edges(self): """Respond if any pirates have reached an edge""" for pirate in self.pirates.sprites(): if pirate.check_edges(): self._change_fleet_direction() break def _change_fleet_direction(self): """Drop the entire fleet and change the fleet direction""" for pirate in self.pirates.sprites(): pirate.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1
def main(): fps = 30 clock = pygame.time.Clock() screen = pygame.display.set_mode((config.WIDTH, config.HEIGHT)) pygame.font.init() font = pygame.font.Font("DejaVuSans.ttf", 24) if TYPE == 'HOST': s, game_map, conn = hostOptions(screen, font) elif TYPE == 'JOIN': s, game_map = joinOptions(screen, font) else: textOnMiddle(screen, 'Generating map...', font) pygame.display.flip() game_map = GameMap().generate(config.WIDTH, config.HEIGHT, 2500) #icon = pygame.image.load("pygame-icon.png") #icon = icon.convert_alpha() #icon_w, icon_h = icon.get_size() shooting_force = -1 bullets = [] cannon1 = Cannon(screen, game_map, 100, (0, 255, 0), 0) cannon2 = Cannon(screen, game_map, config.WIDTH - 100, (255, 0, 0), 180) gameEnded = False while True: msg = {"cannon": {}} recv_msg = {} shooting_force, quitGame = getInputEvents(screen, cannon1, cannon2, bullets, game_map, shooting_force, msg) if quitGame: if TYPE == 'HOST': conn.close() if TYPE == 'JOIN' or TYPE == 'HOST': print('Closing Server...') return s return ping = time.time() if TYPE == 'HOST': try: conn.send(encodeDict(msg)) recv_msg = conn.recv(1024) recv_msg = decodeDict(recv_msg) except ConnectionResetError: print('Connection closed by client') conn.close() return s except json.decoder.JSONDecodeError: print('Connection closed by client') conn.close() return s elif TYPE == 'JOIN': try: recv_msg = s.recv(1024) s.send(encodeDict(msg)) recv_msg = decodeDict(recv_msg) except json.decoder.JSONDecodeError: print('Connection closed by host') return s except ConnectionResetError: print('Connection closed by host') return s if 'shoot' in recv_msg: if TYPE == 'JOIN': rot = cannon1.rot center = cannon1.base.rect.center else: rot = cannon2.rot center = cannon2.base.rect.center bullets.append( Bullet(screen, game_map, center[0], center[1], recv_msg['shoot']['shooting_force'], rot)) if 'cannon' in recv_msg: if 'rotation' in recv_msg['cannon']: rotation = recv_msg['cannon']['rotation'] if TYPE == 'JOIN': cannon1.rotating = rotation if TYPE == 'HOST': cannon2.rotating = rotation ping = time.time() - ping #reset drawing screen.fill((0, 0, 0)) #draw background game_map.printBackground(screen) #draw top info text = font.render('10uv >>', True, (255, 255, 255)) fps_text = font.render( str(round(clock.get_fps(), 2)) + ' fps', True, (255, 255, 255)) ping_text = font.render('ping ' + str(int(ping * 1000)) + 'ms', True, (255, 255, 255)) text_w, text_h = fps_text.get_size() ping_text_w, _ = ping_text.get_size() screen.blit(text, (0, 0)) screen.blit(fps_text, (config.WIDTH - text_w, 0)) screen.blit(ping_text, (config.WIDTH - ping_text_w, text_h)) #draw map ground game_map.printGround(screen) #draw shoot bar if shooting_force != -1: if shooting_force < 50: shooting_force += 1 hud.drawShootForce(screen, shooting_force) #draw shoot bar ruler hud.drawShootForceRuler(screen) #update and draw bullets for bullet in bullets[:]: if not bullet.update(): if bullet.collide: x = int(bullet.x) collision_range = range(x - 15, x + 15) for i in collision_range: #TODO: send this to game map if len(game_map.map_curve) > i >= 0: game_map.map_curve[i] += 10 if not cannon1.isAlive(collision_range): winnerText = font.render('Cannon 2 won.', True, (255, 255, 255)) gameEnded = True break if not cannon2.isAlive(collision_range): winnerText = font.render('Cannon 1 won.', True, (255, 255, 255)) gameEnded = True break bullets.remove(bullet) del bullet else: bullet.draw() #update and draw cannons cannon1.update() cannon1.draw(screen) cannon2.update() cannon2.draw(screen) if gameEnded: while len(bullets) > 0: bullets.pop() winnerText_w, winnerText_h = winnerText.get_size() screen.blit(winnerText, (config.WIDTH / 2 - winnerText_w / 2, config.HEIGHT / 2 - winnerText_h / 2)) #end drawing pygame.display.flip() clock.tick(fps)
def __init__(self): """ This constructor instantiates a game board, instantiates and adds the game piece objects to the board, initializes the game state to "unfinished", initializes the current turn as the red players, and initializes the in-check status of the players. """ self._board = self._board = { "a1": None, "b1": None, "c1": None, "d1": None, "e1": None, "f1": None, "g1": None, "h1": None, "i1": None, # row 2 "a2": None, "b2": None, "c2": None, "d2": None, "e2": None, "f2": None, "g2": None, "h2": None, "i2": None, # row 3 "a3": None, "b3": None, "c3": None, "d3": None, "e3": None, "f3": None, "g3": None, "h3": None, "i3": None, # row 4 "a4": None, "b4": None, "c4": None, "d4": None, "e4": None, "f4": None, "g4": None, "h4": None, "i4": None, # row 5 "a5": None, "b5": None, "c5": None, "d5": None, "e5": None, "f5": None, "g5": None, "h5": None, "i5": None, # row 6 "a6": None, "b6": None, "c6": None, "d6": None, "e6": None, "f6": None, "g6": None, "h6": None, "i6": None, # row 7 "a7": None, "b7": None, "c7": None, "d7": None, "e7": None, "f7": None, "g7": None, "h7": None, "i7": None, # row 8 "a8": None, "b8": None, "c8": None, "d8": None, "e8": None, "f8": None, "g8": None, "h8": None, "i8": None, # row 9 "a9": None, "b9": None, "c9": None, "d9": None, "e9": None, "f9": None, "g9": None, "h9": None, "i9": None, # row 10 "a10": None, "b10": None, "c10": None, "d10": None, "e10": None, "f10": None, "g10": None, "h10": None, "i10": None, } self._red_pieces = [] self._black_pieces = [] red_char_1 = Chariot("red", "a1") self.update_board("a1", red_char_1) self._red_pieces.append(red_char_1) black_char_1 = Chariot("Black", "a10") self.update_board("a10", black_char_1) self._black_pieces.append(black_char_1) red_horse_1 = Horse("red", "b1") self.update_board("b1", red_horse_1) self._red_pieces.append(red_horse_1) black_horse_1 = Horse("black", "b10") self.update_board("b10", black_horse_1) self._black_pieces.append(black_horse_1) red_ele_1 = Elephant("red", "c1") self.update_board("c1", red_ele_1) self._red_pieces.append(red_ele_1) black_ele_1 = Elephant("black", "c10") self.update_board("c10", black_ele_1) self._black_pieces.append(black_ele_1) red_adv_1 = Advisor("red", "d1") self.update_board("d1", red_adv_1) self._red_pieces.append(red_adv_1) black_adv_1 = Advisor("black", "d10") self.update_board("d10", black_adv_1) self._black_pieces.append(black_adv_1) red_gen = General("red", "e1") self.update_board("e1", red_gen) self._red_pieces.append(red_gen) black_gen = General("Black", "e10") self.update_board("e10", black_gen) self._black_pieces.append(black_gen) red_adv_2 = Advisor("Red", "f1") self.update_board("f1", red_adv_2) self._red_pieces.append(red_adv_2) black_adv_2 = Advisor("black", "f10") self.update_board("f10", black_adv_2) self._black_pieces.append(black_adv_2) red_ele_2 = Elephant("red", "g1") self.update_board("g1", red_ele_2) self._red_pieces.append(red_ele_2) black_ele_2 = Elephant("black", "g10") self.update_board("g10", black_ele_2) self._black_pieces.append(black_ele_2) red_horse_2 = Horse("red", "h1") self.update_board("h1", red_horse_2) self._red_pieces.append(red_horse_2) black_horse_2 = Horse("black", "h10") self.update_board("h10", black_horse_2) self._black_pieces.append(black_horse_2) red_char_2 = Chariot("red", "i1") self.update_board("i1", red_char_2) self._red_pieces.append(red_char_2) black_char_2 = Chariot("black", "i10") self.update_board("i10", black_char_2) self._black_pieces.append(black_char_2) red_can_1 = Cannon("red", "b3") self.update_board("b3", red_can_1) self._red_pieces.append(red_can_1) black_can_1 = Cannon("black", "b8") self.update_board("b8", black_can_1) self._black_pieces.append(black_can_1) red_can_2 = Cannon("red", "h3") self.update_board("h3", red_can_2) self._red_pieces.append(red_can_2) black_can_2 = Cannon("black", "h8") self.update_board("h8", black_can_2) self._black_pieces.append(black_can_2) red_sol_1 = Soldier("red", "a4") self.update_board("a4", red_sol_1) self._red_pieces.append(red_sol_1) red_sol_2 = Soldier("red", "c4") self.update_board("c4", red_sol_2) self._red_pieces.append(red_sol_2) red_sol_3 = Soldier("red", "e4") self.update_board("e4", red_sol_3) self._red_pieces.append(red_sol_3) red_sol_4 = Soldier("red", "g4") self.update_board("g4", red_sol_4) self._red_pieces.append(red_sol_4) red_sol_5 = Soldier("red", "i4") self.update_board("i4", red_sol_5) self._red_pieces.append(red_sol_5) black_sol_1 = Soldier("black", "a7") self.update_board("a7", black_sol_1) self._black_pieces.append(black_sol_1) black_sol_2 = Soldier("black", "c7") self.update_board("c7", black_sol_2) self._black_pieces.append(black_sol_2) black_sol_3 = Soldier("black", "e7") self.update_board("e7", black_sol_3) self._black_pieces.append(black_sol_3) black_sol_4 = Soldier("black", "g7") self.update_board("g7", black_sol_4) self._black_pieces.append(black_sol_4) black_sol_5 = Soldier("black", "i7") self.update_board("i7", black_sol_5) self._black_pieces.append(black_sol_5) self._game_state = "UNFINISHED" self._turn = True self.generate_moves() self._red_in_check = {"red": False} self._black_in_check = {"black": False}
class Level(GameState): """Level is a GameState with behavior for one full game level. Contains Sprites player, enemy, shield, hbullet, cannon, and Group player_bullets """ def __init__(self, manager): """manager is required to be a child of GameManager with these functions: -kill_player() -next_level() -add_score(amount) -give_energy(amount) -spend_energy(amount) -give_life() """ GameState.__init__(self, manager) self.player = Ship(*opt.player_args) self.enemy = EnemyBase(opt.mover_args, opt.spinner_args, opt.shooter_args, self.player) self.shield = EnemyShield(self.enemy, opt.shield_filename, formation, formation_center) self.hbullet = HomingBullet(opt.homer_filename, self.player, opt.homer_speed) self.cannon = Cannon(opt.deactivated_cannon_args, opt.standby_cannon_args, opt.firing_cannon_args, self.player) self.ion_field = IonField(*opt.ion_field_args) self.player_bullets = Group() self.reset_positions() def update(self): self.player.update() self.enemy.update() self.shield.update() self.hbullet.update() self.cannon.update() self.player_bullets.update() self.ion_field.update() self.collisions() def handle_events(self, events, keys): return (event_handlers.check_quit(events, keys) and event_handlers.check_shoot_button(events, keys, self.shoot) and event_handlers.move_player(events, keys, self.player)) def draw(self, screen): self.ion_field.draw(screen) self.enemy.draw(screen) self.shield.draw(screen) self.player.draw(screen) self.hbullet.draw(screen) self.cannon.draw(screen) self.player_bullets.draw(screen) def collisions(self): """Handles collisions """ player = self.player enemy = self.enemy shield = self.shield hbullet = self.hbullet cannon = self.cannon ion_field = self.ion_field player_bullets = self.player_bullets #player with homing bullet if collide_mask(player, hbullet) and not collide_mask(player, ion_field): self.kill_player() #player with enemy base if collide_mask(player, enemy): #if base in moving phase, give player energy if enemy.get_state_number() == EnemyBase.MOVING: self.manager.give_energy(opt.energy_from_enemy) #if base in spinning or shooting phase, kill player elif enemy.get_state_number() == EnemyBase.SPINNING: self.kill_player() elif enemy.get_state_number() == EnemyBase.SHOOTING: self.kill_player() #player with cell #-hitting a cell will bounce the player a bit to the left #-if the player hit the cell twice in a short enough span, # the cell is eaten and the player gets energy #-in case of multiple collisions, deal with cell closest to player's center # #TODO: This still isn't quite right. #Should be able to eat top/bottom rows with diagonal movement. #(vertical movement should still move player all the way left) pc_collides = spritecollide(player, shield, False, collide_mask) center_cell = self.find_centermost_cell(pc_collides) if center_cell is not None: player.rect.right = center_cell.rect.left - opt.cell_bounceback if not center_cell.marked: center_cell.mark() elif shield.can_eat(): center_cell.kill() self.manager.give_energy(opt.energy_from_cell) self.manager.add_score(opt.score_cell_eat) shield.start_delay(opt.frames_to_eat_cell) #player with cannon if collide_mask(player, cannon): #if in deactivated phase, try spending required energy to activate if (cannon.get_state_number() == Cannon.DEACTIVATED and self.manager.spend_energy(opt.cannon_energy_cost)): cannon.start_standby() #if in firing phase, kill player if cannon.get_state_number() == Cannon.FIRING: self.kill_player() #if in returning phase, give energy and deactivate cannon if cannon.get_state_number() == Cannon.RETURNING: cannon.start_transition(Cannon.DEACTIVATED) self.manager.give_energy(opt.energy_from_cannon) #cannon with cell #kill one cell and reverse cannon direction #assuming this is only possible if cannon in firing state if cannon.get_state_number() == Cannon.FIRING: cannon_collides = spritecollide(cannon, shield, False, collide_mask) if len(cannon_collides) > 0: cannon_collides[0].kill() self.manager.add_score(opt.score_cell_shoot) cannon.start_transition(Cannon.RETURNING) #cannon with enemy base -- only if cannon in firing state #give points corresponding to enemy state and end level #if enemy base is in shooting state, player also gets a life if cannon.get_state_number() == Cannon.FIRING and collide_mask( cannon, enemy): if enemy.get_state_number() == EnemyBase.MOVING: self.manager.add_score(opt.score_mover_destroy) elif enemy.get_state_number() == EnemyBase.SPINNING: self.manager.add_score(opt.score_spinner_destroy) elif enemy.get_state_number() == EnemyBase.SHOOTING: self.manager.add_score(opt.score_shooter_destroy) self.manager.give_life() self.end_level() #player's bullet with cell #kill player bullet but remove cells in a cross pattern #if somehow one bullet hits multiple cells one is arbitrarily selected bc_collides = groupcollide(player_bullets, shield, True, False, collide_mask) for current_bullet in bc_collides.keys(): self.manager.add_score(opt.score_cell_shoot) shield.remove_cross(bc_collides[current_bullet][0]) def find_centermost_cell(self, cells): """Given a list of Cell sprites, returns the one whose rect.centery is closest to the player's rect.centery Returns None if list is empty """ closest_cell = None for current_cell in cells: current_dist = abs(current_cell.rect.centery - self.player.rect.centery) if closest_cell is None or current_dist < closest_dist: closest_cell = current_cell closest_dist = current_dist return closest_cell def shoot(self): """If cannon can be fired, fires cannon. Otherwise creates bullet moving from player's center along player's direction as long as options.max_player_bullets won't be exeeded """ if collide_mask(self.player, self.ion_field): return if self.cannon.start_transition(Cannon.FIRING): return if len(self.player_bullets) < opt.max_player_bullets: new_bullet = Bullet(opt.bullet_filename, opt.bullet_speed, self.player.get_rect().center, self.player.get_direction()) self.player_bullets.add(new_bullet) def reset_positions(self): """Moves sprites to their initial locations: player starts in left center facing south and with 0 energy player bullets are removed enemy bullet starts on enemy base enemy base is in moving state cannon is in deactivated state Note: shield configuration is not reset """ self.player.rect.midleft = (20, int(opt.height / 2)) self.player.set_direction(vector.SOUTH) self.player_bullets.empty() self.enemy.resume_mover_state() self.cannon.start_deactivated() self.hbullet.rect.center = self.enemy.rect.center def kill_player(self): death_animation = DeathAnimation(self.manager, self.player, (self.enemy, self.shield), self, opt.death_animation_delay, opt.death_animation_total_runtime) self.manager.change_state(death_animation) def end_level(self): win_animation = WinAnimation(self.manager, self.player, opt.win_animation_total_runtime, opt.exp_field_args) self.manager.change_state(win_animation)
class Level(GameState): """Level is a GameState with behavior for one full game level. Contains Sprites player, enemy, shield, hbullet, cannon, and Group player_bullets """ def __init__(self, manager): """manager is required to be a child of GameManager with these functions: -kill_player() -next_level() -add_score(amount) -give_energy(amount) -spend_energy(amount) -give_life() """ GameState.__init__(self, manager) self.player = Ship(*opt.player_args) self.enemy = EnemyBase(opt.mover_args, opt.spinner_args, opt.shooter_args, self.player) self.shield = EnemyShield(self.enemy, opt.shield_filename, formation, formation_center) self.hbullet = HomingBullet(opt.homer_filename, self.player, opt.homer_speed) self.cannon = Cannon(opt.deactivated_cannon_args, opt.standby_cannon_args, opt.firing_cannon_args, self.player) self.ion_field = IonField(*opt.ion_field_args) self.player_bullets = Group() self.reset_positions() def update(self): self.player.update() self.enemy.update() self.shield.update() self.hbullet.update() self.cannon.update() self.player_bullets.update() self.ion_field.update() self.collisions() def handle_events(self, events, keys): return (event_handlers.check_quit(events, keys) and event_handlers.check_shoot_button(events, keys, self.shoot) and event_handlers.move_player(events, keys, self.player)) def draw(self, screen): self.ion_field.draw(screen) self.enemy.draw(screen) self.shield.draw(screen) self.player.draw(screen) self.hbullet.draw(screen) self.cannon.draw(screen) self.player_bullets.draw(screen) def collisions(self): """Handles collisions """ player = self.player enemy = self.enemy shield = self.shield hbullet = self.hbullet cannon = self.cannon ion_field = self.ion_field player_bullets = self.player_bullets #player with homing bullet if collide_mask(player, hbullet) and not collide_mask(player, ion_field): self.kill_player() #player with enemy base if collide_mask(player, enemy): #if base in moving phase, give player energy if enemy.get_state_number() == EnemyBase.MOVING: self.manager.give_energy(opt.energy_from_enemy) #if base in spinning or shooting phase, kill player elif enemy.get_state_number() == EnemyBase.SPINNING: self.kill_player() elif enemy.get_state_number() == EnemyBase.SHOOTING: self.kill_player() #player with cell #-hitting a cell will bounce the player a bit to the left #-if the player hit the cell twice in a short enough span, # the cell is eaten and the player gets energy #-in case of multiple collisions, deal with cell closest to player's center # #TODO: This still isn't quite right. #Should be able to eat top/bottom rows with diagonal movement. #(vertical movement should still move player all the way left) pc_collides = spritecollide(player, shield, False, collide_mask) center_cell = self.find_centermost_cell(pc_collides) if center_cell is not None: player.rect.right = center_cell.rect.left - opt.cell_bounceback if not center_cell.marked: center_cell.mark() elif shield.can_eat(): center_cell.kill() self.manager.give_energy(opt.energy_from_cell) self.manager.add_score(opt.score_cell_eat) shield.start_delay(opt.frames_to_eat_cell) #player with cannon if collide_mask(player, cannon): #if in deactivated phase, try spending required energy to activate if (cannon.get_state_number() == Cannon.DEACTIVATED and self.manager.spend_energy(opt.cannon_energy_cost)): cannon.start_standby() #if in firing phase, kill player if cannon.get_state_number() == Cannon.FIRING: self.kill_player() #if in returning phase, give energy and deactivate cannon if cannon.get_state_number() == Cannon.RETURNING: cannon.start_transition(Cannon.DEACTIVATED) self.manager.give_energy(opt.energy_from_cannon) #cannon with cell #kill one cell and reverse cannon direction #assuming this is only possible if cannon in firing state if cannon.get_state_number() == Cannon.FIRING: cannon_collides = spritecollide(cannon, shield, False, collide_mask) if len(cannon_collides) > 0: cannon_collides[0].kill() self.manager.add_score(opt.score_cell_shoot) cannon.start_transition(Cannon.RETURNING) #cannon with enemy base -- only if cannon in firing state #give points corresponding to enemy state and end level #if enemy base is in shooting state, player also gets a life if cannon.get_state_number() == Cannon.FIRING and collide_mask(cannon, enemy): if enemy.get_state_number() == EnemyBase.MOVING: self.manager.add_score(opt.score_mover_destroy) elif enemy.get_state_number() == EnemyBase.SPINNING: self.manager.add_score(opt.score_spinner_destroy) elif enemy.get_state_number() == EnemyBase.SHOOTING: self.manager.add_score(opt.score_shooter_destroy) self.manager.give_life() self.end_level() #player's bullet with cell #kill player bullet but remove cells in a cross pattern #if somehow one bullet hits multiple cells one is arbitrarily selected bc_collides = groupcollide(player_bullets, shield, True, False, collide_mask) for current_bullet in bc_collides.keys(): self.manager.add_score(opt.score_cell_shoot) shield.remove_cross(bc_collides[current_bullet][0]) def find_centermost_cell(self, cells): """Given a list of Cell sprites, returns the one whose rect.centery is closest to the player's rect.centery Returns None if list is empty """ closest_cell = None for current_cell in cells: current_dist = abs(current_cell.rect.centery - self.player.rect.centery) if closest_cell is None or current_dist < closest_dist: closest_cell = current_cell closest_dist = current_dist return closest_cell def shoot(self): """If cannon can be fired, fires cannon. Otherwise creates bullet moving from player's center along player's direction as long as options.max_player_bullets won't be exeeded """ if collide_mask(self.player, self.ion_field): return if self.cannon.start_transition(Cannon.FIRING): return if len(self.player_bullets) < opt.max_player_bullets: new_bullet = Bullet(opt.bullet_filename, opt.bullet_speed, self.player.get_rect().center, self.player.get_direction()) self.player_bullets.add(new_bullet) def reset_positions(self): """Moves sprites to their initial locations: player starts in left center facing south and with 0 energy player bullets are removed enemy bullet starts on enemy base enemy base is in moving state cannon is in deactivated state Note: shield configuration is not reset """ self.player.rect.midleft = (20, int(opt.height/2)) self.player.set_direction(vector.SOUTH) self.player_bullets.empty() self.enemy.resume_mover_state() self.cannon.start_deactivated() self.hbullet.rect.center = self.enemy.rect.center def kill_player(self): death_animation = DeathAnimation(self.manager, self.player, (self.enemy, self.shield), self, opt.death_animation_delay, opt.death_animation_total_runtime) self.manager.change_state(death_animation) def end_level(self): win_animation = WinAnimation(self.manager, self.player, opt.win_animation_total_runtime, opt.exp_field_args) self.manager.change_state(win_animation)
import matplotlib.pyplot as plt from calc_percentile import calculate_percentile import logging from cannon import Cannon logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) URL = "http://localhost:8080" if __name__ == '__main__': cannon = Cannon(URL) duration = 30 max_qps = 300 df = calculate_percentile(duration, max_qps, cannon) df.plot(x="QPS(queries per second)", y="Latency, 50%", kind='line') df.plot(x="QPS(queries per second)", y="Latency, 90%", kind='line') df.plot(x="QPS(queries per second)", y="Latency, 99%", kind='line') df.plot(x="QPS(queries per second)", y="Error rate", kind='line') plt.show()
def run_game_loop(self): player_mouse_pos = [0, 0] button_clicked = False dragging = False game_over = False waves_allowed = True button = Button(15, 540, 50, 50) drag_cannon = Cannon([25, 552]) cannon_display = Cannon_Display(self.scoreboard) cannon_sprite = pygame.sprite.Group(cannon_display) zombie_health = 110 delta = 0.9 zombies_sprite = self.make_zombie_herd(self.herd_size, zombie_health, delta) cannons = pygame.sprite.Group() score_sprite = pygame.sprite.Group(self.scoreboard) button_sprite = pygame.sprite.Group(button) wave_count = 0 kills_per_cannon = 50 # Game loop while self.running: # Event detection for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False elif event.type == pygame.MOUSEBUTTONDOWN: button_clicked = True elif event.type == pygame.MOUSEBUTTONUP: player_mouse_pos[0] = event.pos[0] player_mouse_pos[1] = event.pos[1] if button_clicked and dragging and self.scoreboard.cannons > 0: self.scoreboard.cannons -= 1 cannon = Cannon([player_mouse_pos[0]-45, player_mouse_pos[1]-45]) cannons.add(cannon) button_clicked = False dragging = False cannons.update() cannon_sprite.update() score_sprite.update() button_sprite.update("null") self.game_display.blit(self.background_img, (0, 0)) # Get mouse position cannon_pos = pygame.mouse.get_pos() if 10 <= cannon_pos[0] <= 60 and 540 <= cannon_pos[1] <= 590 and button_clicked: button_sprite.update("shrink") dragging = True elif dragging: button_sprite.update("shrink") if button_clicked and dragging and self.scoreboard.cannons > 0: drag_cannon.display(self.game_display, cannon_pos[0]-45, cannon_pos[1]-45) # Check if the wave of zombies is empty, start the timer, don't allow waves # increment size of herd, and create a new herd to send as next wave if not zombies_sprite: waves_allowed = False self.herd_size += random.randint(9, 13) self.scoreboard.increment_wave() wave_count += 1 if wave_count != 0 and wave_count % 5 == 0: zombie_health += 60 delta += 0.1 kills_per_cannon = kills_per_cannon + 25 else: zombie_health += 20 zombies_sprite = self.make_zombie_herd(self.herd_size, zombie_health, delta) if not game_over: cannons.draw(self.game_display) score_sprite.draw(self.game_display) button_sprite.draw(self.game_display) cannon_sprite.draw(self.game_display) # If 10 secs passed since last wave, then release the next zombie wave if not waves_allowed: if self.tick_count == 300: self.scoreboard.cannons += (self.scoreboard.cannon_cash // kills_per_cannon) self.scoreboard.cannon_cash = (self.scoreboard.cannon_cash % kills_per_cannon) self.display_warning(self.tick_count) self.tick_count -= 1 if self.tick_count == 0: waves_allowed = True self.tick_count = 300 # If zombie waves are allowed to attack AND the game is not over, # then move the zombie wave across the screen if waves_allowed and not game_over: self.move_zombie_herd(zombies_sprite) if self.scoreboard.score >= self.ZOMBIE_THRESH: game_over = True # If game over is true, draw Game Over and display player's stats if game_over: self.display_game_over() # Check if zombie is within radius of any cannon if not game_over and waves_allowed: for cannon in cannons: zombies_in_radius = pygame.sprite.spritecollide(cannon, zombies_sprite, False, collided=pygame.sprite.collide_circle) if zombies_in_radius: for zombie in zombies_in_radius: cannon.shoot(zombie.rect.centerx, zombie.rect.centery, self.game_display) # Now check for bullet - zombie collisions hit_list = pygame.sprite.spritecollide(zombie, cannon.bullets, False) if hit_list: for bullet in hit_list: if zombie.health <= 0: self.scoreboard.zombies_killed += 1 self.scoreboard.cannon_cash += 1 zombies_sprite.remove(zombie) else: zombie.health -= 10 cannon.bullets.remove(bullet) cannon.bullets.empty() pygame.display.update() self.clock.tick(self.FRAMES_PER_SEC)
class CannonGame(QWidget): def __init__(self, parent=None): super().__init__(parent) # Button Widget self.btnNewGame = QToolButton() self.btnNewGame.setText('New Game!') self.btnNewGame.clicked.connect(self.btnNewGameClicked) self.btnFire = QToolButton() self.btnFire.setText('Fire!') self.btnFire.clicked.connect(self.btnFireClicked) # Label Widget self.lbResult = QLabel('Status:') self.lbAngle = QLabel('Angle(40 ~ 70):') self.lbPower = QLabel('Power(30 ~ 50):') self.lbBoulet = QLabel('Boulet: ') # LineEdit Widget self.lnResult = QLineEdit() self.lnResult.setReadOnly(True) self.lnResult.setAlignment(Qt.AlignCenter) self.lnBoulet = QLineEdit() self.lnBoulet.setReadOnly(True) self.lnBoulet.setAlignment(Qt.AlignCenter) # QSlider Widget self.slAngle = QSlider(Qt.Horizontal) self.slAngle.setMinimum(40) self.slAngle.setMaximum(70) self.slAngle.setValue(55) self.slAngle.setTickPosition(QSlider.TicksBelow) self.slAngle.setTickInterval(5) self.slAngle.setFixedWidth(250) self.slPower = QSlider(Qt.Horizontal) self.slPower.setMinimum(30) self.slPower.setMaximum(50) self.slPower.setValue(55) self.slPower.setTickPosition(QSlider.TicksBelow) self.slPower.setTickInterval(5) self.slPower.setFixedWidth(250) # TextEdit Widget self.txWindow = QTextEdit() self.txWindow.setFixedSize(850, 670) self.txWindow.setReadOnly(True) self.txWindow.setAlignment(Qt.AlignLeft) font = self.txWindow.font() font.setPointSize(font.pointSize() + 4) font.setFamily('Courier New') self.txWindow.setFont(font) # Layout hLayout1 = QHBoxLayout() hLayout2 = QHBoxLayout() hLayout1.addWidget(self.btnNewGame) hLayout1.addStretch(1) hLayout1.addWidget(self.lbBoulet) hLayout1.addWidget(self.lnBoulet) hLayout1.addWidget(self.lbResult) hLayout1.addWidget(self.lnResult) hLayout2.addWidget(self.lbAngle) hLayout2.addWidget(self.slAngle) hLayout2.addWidget(self.lbPower) hLayout2.addWidget(self.slPower) hLayout2.addStretch(1) hLayout2.addWidget(self.btnFire) mainLayout = QVBoxLayout() mainLayout.setSizeConstraint(QLayout.SetFixedSize) mainLayout.addLayout(hLayout1) mainLayout.addWidget(self.txWindow) mainLayout.addLayout(hLayout2) self.setLayout(mainLayout) self.setWindowTitle('Cannon Game') # Start Game self.btnNewGameClicked() def btnNewGameClicked(self): # target 위치 지정 self.targetColumn = random.randint(40, 60) self.targetRow = random.randint(18, 21) self.target = (self.targetRow, self.targetColumn) # 게임 시작시 초기화 self.cannon = Cannon(self.target) self.fire = Fire() self.gameOver = False self.boulet = ["●", "●", "●", "●"] self.turn = -1 self.txWindow.setText(self.cannon.initialMap()) self.lnResult.setText('Start!') self.lnBoulet.setText(" ".join(self.boulet)) self.slAngle.setValue(55) self.slPower.setValue(40) def btnFireClicked(self): self.cannon = Cannon(self.target) # 각도 와 파워 설정 try: angle = int(self.slAngle.value()) power = int(self.slPower.value()) except: self.lnResult.setText('Not integer') return # 게임 완료 시 if self.gameOver == True: self.lnResult.setText('Game Over') return # 현재 맵 출력 for point in self.fire.parabola(angle, power): shape = self.cannon.currentMap(point)[0] hit = self.cannon.currentMap(point)[1] self.txWindow.setText(shape) if hit: self.lnResult.setText('Hit!') self.gameOver = True break else: self.lnResult.setText('Miss!') # 에니메이션 효과 구현 loop = QEventLoop() QTimer.singleShot(100, loop.quit) loop.exec_() if self.boulet[0] == "○": self.lnResult.setText('Fail!') self.gameOver = True return del (self.boulet[self.turn]) self.turn -= 1 self.boulet.append("○") self.lnBoulet.setText(" ".join(self.boulet)) # 단축키 설정 def keyPressEvent(self, e): if e.key() == Qt.Key_Escape: self.close() elif e.key() == Qt.Key_N: self.btnNewGameClicked() elif e.key() == Qt.Key_Enter or Qt.Key_Return: self.btnFireClicked()
import logging from cannon import Cannon logging.basicConfig(format='%(levelname)s:%(message)s', level=logging.DEBUG) URL = "http://localhost:8080" if __name__ == '__main__': cannon = Cannon(URL) latencies = cannon.start_shoot(qps=100, duration=15, threads=80) print(latencies)
import pygame from pygame.locals import * from OpenGL.GL import * from OpenGL.GLU import * from cannon import Cannon; from objects import *; screen_size = (800, 600); clock = pygame.time.Clock(); delta_time = clock.tick() / 1000; goal = Goal(screen_size); obstacle_list = []; cannon = Cannon(20, 0, obstacle_list, goal); player_points = 0; def init_game(): pygame.display.init(); pygame.display.set_mode((screen_size[0], screen_size[1]), DOUBLEBUF | OPENGL); glClearColor(1.0, 1.0, 1.0, 1.0); def update(): global delta_time; delta_time = clock.tick() / 1000;
from cannon import Cannon # Build some cannons cannon_1 = Cannon(25) cannon_2 = Cannon(10) cannon_3 = Cannon(1) # Start firing cannon_1.fire_ball() cannon_2.fire_multiple(4) cannon_3.fire_multiple(6) # Keep firing cannon_1.fire_multiple(cannon_2.ammunition + cannon_3.ammunition) # Quiz print("Cannon1: {}".format(cannon_1.ammunition)) print("Cannon2: {}".format(cannon_2.ammunition)) print("Cannon3: {}".format(cannon_3.ammunition))
win = window.Window(width=500, height=500, vsync=True, resizable=True) glEnable(GL_BLEND) glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) # needed so that egi knows where to draw egi.InitWithPyglet(win) # prep the fps display fps_display = clock.ClockDisplay() # register key and mouse event handlers win.push_handlers(on_key_press) win.push_handlers(on_mouse_press) win.push_handlers(on_resize) # create a world for agents world = World(500, 500) world.hunter = Hunter(world) world.cannon = Cannon(Vector2D(250, 20), world) # unpause the world ready for movement world.paused = False while not win.has_exit: win.dispatch_events() glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) # show nice FPS bottom right (default) delta = clock.tick() world.update(delta) world.render() fps_display.draw() # swap the double buffer win.flip()