def test_player_incoming_miss(): player1 = Player(1) assert player1.incoming(2, 2) == { 'hit': False, 'sunk': False, 'winner': False }
def initialize_players(self): if self.lan_mode and len(self.players) < self.play_num: self.master.master.after(1000, self.initialize_players) else: # Play num in joined mode is 0 for i in range(self.play_num): pl = Player(self.players[i]) pl.draw_letters(self.bag) self.players.append(pl) # If the game is against a computer, no need for the second # iteration because its class is different if self.comp_mode: self.opponent = AIOpponent() self.opponent.draw_letters(self.bag) self.players.append(self.opponent) break # Deletes the name strings del self.players[:self.play_num] if self.lan_mode: self.queue.put(self.players) self.init_turn()
def reset(self): self.level = 1 self.xp = 1 self.hp = 10 self.max_hp = 10 self.attack = 1 self.prev_level = 1 self.high_score_current = self.score_display.score_read() self.player = Player(self.hp, self.attack, self.max_hp, self.display_width, self.display_height, self.health_bar, pygame) self.crashed = False self.enemies = [] self.point = 0 self.xp_new = 100 self.enemy_spawn_time = 5 self.multiplier = 1 self.items = [] for count in range(0, 5): test_enemy = Enemy(random.randint(0, self.display_width), random.randint(0, self.display_height), self.health_bar, pygame, self.multiplier) self.enemies.append(test_enemy) self.add_enemy()
class Controller: def __init__(self): self.status = '' self.monsters = [ Spider, Ghoul ] self.player_dead = False def start_game(self): self.player = Player() def fight(self): monster = self.create_monster(self.player.level) while True: print("player health: {0} player mana: {1}\n{2} health: {3}".format( self.player.curr_stats['health'], self.player.curr_stats['mana'], monster.name, monster.curr_stats['health'] )) player_move = self.player.choose_move() self.apply_status_changes(player_move, self.player, monster) if monster.curr_stats['health'] <= 0: self.display_success_message(monster) self.player.gain_exp(monster.exp) break self.apply_status_changes(monster.choose_move(), monster, self.player) if self.player.curr_stats['health'] <= 0: self.display_death_message(monster) self.player_dead = True raise PlayerDeath() return monster def regain(self): print('Regained HP and Mana!') self.player.curr_stats['health'] = self.player.max_stats['health'] self.player.curr_stats['mana'] = self.player.max_stats['mana'] def display_death_message(self, monster): print(monster.player_death_msg) def display_success_message(self, monster): print(monster.monster_death_msg) def apply_status_changes(self, modifiers, action_doer, action_enemy): action_doer.curr_stats['health'] += modifiers['health'] action_doer.curr_stats['mana'] -= modifiers['mana'] action_doer.curr_stats['defense'] += modifiers['defense'] action_enemy.curr_stats['health'] -= modifiers['attack'] + action_enemy.curr_stats['defense'] def create_monster(self, level): possible_monsters = [] for monster in self.monsters: if abs(monster().level_spawn - level) <= 5: possible_monsters.append(monster) monster_klass = random.choice(possible_monsters) return monster_klass()
class App: def __init__(self, is_prod=False): pygame.init() inf = pygame.display.Info() pygame.mouse.set_visible(False) flags = pygame.FULLSCREEN if is_prod else pygame.RESIZABLE window = pygame.display.set_mode([inf.current_w, inf.current_h], flags) self.player = Player() self.text = MirrorText('', window) self.is_running = False def start(self): if not self.is_running: self.player.play() self.text.run() self.is_running = True def stop(self): if self.is_running: try: Player.stop() self.text.stop() self.is_running = False except Exception as err: print("[App.stop(self)] threw an exception %d" % err) def exit(self): self.stop() while self.text.thr.isAlive(): pygame.time.delay(10) pygame.quit()
def on_scene_enter(self): #glEnable(GL_POINT_SMOOTH) #glEnable(GL_TEXTURE_2D) self.player = Player() self.players = [self.player] self.dynamic.append(self.player) self.last_lead = self.player.position = self.campos = self.cam_spline.get_point(0) clock.schedule(self.update)
def setUp(self): card_one = Card("Heart", "5", 5) card_two = Card("Diamond", "Jack", 11) card_three = Card("Spade", "7", 7) card_four = Card("Spade", "Ace", 14) cards = [card_one, card_two, card_three, card_four] self.deck = Deck(cards) self.player = Player("John", self.deck)
def stop(self): if self.is_running: try: Player.stop() self.text.stop() self.is_running = False except Exception as err: print("[App.stop(self)] threw an exception %d" % err)
def test_player_incoming_hit(): player1 = Player(1) player1.board.place_ship(player1.ships[0], 2, 2) assert player1.incoming(2, 2) == { 'hit': True, 'sunk': False, 'winner': False }
def test_player_updates_play_state(self): player = Player() # assert default player state assert player.in_game is True # assert we can set player to inactive player.in_game = False # assert that the player state has changed assert player.in_game is False
def __init__(self, is_prod=False): pygame.init() inf = pygame.display.Info() pygame.mouse.set_visible(False) flags = pygame.FULLSCREEN if is_prod else pygame.RESIZABLE window = pygame.display.set_mode([inf.current_w, inf.current_h], flags) self.player = Player() self.text = MirrorText('', window) self.is_running = False
def startGame(self): self.player = Player() self.enemies = [] self.amountOfEnemies = 0 self.spawnEnemy() self.clock = pygame.time.Clock() self.timer = 0 self.enemyTimer = 0 self.timeUntilEnemySpawns = 2000 self.gameState = "GAME"
def __init__(self): app_builder = ApplicationWindow.builder app_builder.add_from_file("gui.glade") app_builder.connect_signals(Player()) _switch_status = app_builder.get_object('switch_status') if Player().is_server_active(): _switch_status.set_active(True) window = app_builder.get_object("mainWindow") window.show_all()
def __init__(self): deck = Deck.shuffle() self.trump = deck[-1] hand1 = deck[:HAND_SIZE] deck = deck[HAND_SIZE:] hand2 = deck[:HAND_SIZE] self.deck = deck[HAND_SIZE:] self.ai = AIPlayer(self, hand1) self.player = Player(self, hand2) self.set_first_turn()
def main(self): pygame.init() self.DISPLAYSURF = pygame.display.set_mode( (WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption('Hello World!') self.playerImg = pygame.image.load('./pics/player.png') self.appleImg = pygame.image.load('./pics/apple.png') self.player = Player() self.apple = Apple() self.score = 0 self.clock = pygame.time.Clock() # Text self.font = pygame.font.Font('freesansbold.ttf', 16) self.text = self.font.render('Score: ' + str(self.score), True, white, black) self.textRect = self.text.get_rect() self.textRect.x = 1200 self.textRect.y = 700 while True: # Event Handler for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: self.player.moveLeft() if event.key == pygame.K_UP: self.player.moveUp() if event.key == pygame.K_DOWN: self.player.moveDown() if event.key == pygame.K_RIGHT: self.player.moveRight() if event.key == pygame.K_ESCAPE: self.die() if event.type == QUIT: self.die() self.player.update() self.checkCollision() self.draw() pygame.display.update() time.sleep(50.0 / 1000.0)
def addSummaries(urlGen, queue, players, gender,friends): # read number of records to pull numScrape = 10 if len(sys.argv) == 2: numScrape = int(sys.argv[1]) while (numScrape > 0): pid = queue.next() print pid try: player = Player(getPlayerInfo(urlGen, pid), players.connection) if not player.isPrivate(): player.addPlayerInfoToDB() player.addGender(gender) friendsList = getFriendIds(urlGen, pid) if friendsList != "none": player.addNumFriends(friendsList) print queue.count, "|",player.steamid, player.firstName, player.gender, player.genderConf, player.loccountrycode, player.locstatecode,"friends",player.numFriends, " remaining: ", numScrape if player.loccountrycode == "US" and player.locstatecode != "CA": # we are targeting americans friends.addFriends(pid, friendsList) print "\tadding friends from player from ", player.loccountrycode for friend in friendsList: if not (queue.inQueue(friend) or players.inPlayers(friend)): queue.push(friend) queue.free(player.steamid) except UnicodeEncodeError : print "UnicodeEncodeError" queue.free(pid) numScrape -= 1
def train(): env = Environment() player = Player() for episode in range(2): env.start() while True: actions = player.act(env.state) reverd = env.apply(actions) player.learn(reverd) if env.done: break return
def __init__(self): pygame.init() self.display_width = 790 self.display_height = 740 self.level = 1 self.xp = 1 self.hp = 10 self.max_hp = 10 self.attack = 1 self.talent_point = 0 self.prev_level = 1 self.name = "test name" self.score_display = ScoreScreen() self.high_score_current = self.score_display.score_read() self.is_paused = False pygame.display.set_caption('Taemasu v0.1') self.health_bar = pygame.image.load('lib/img/healthbar.png') self.player = Player(self.hp, self.attack, self.max_hp, self.display_width, self.display_height, self.health_bar, pygame) self.game_display = pygame.display.set_mode((1200, 1200)) self.white = (255, 255, 255) self.clock = pygame.time.Clock() self.crashed = False self.game_display.fill(self.white) self.enemies = [] self.sword = pygame.image.load('lib/img/sword.png') self.map = Map('maptest.txt', self.display_width, self.display_height, pygame) pygame.font.init() # you have to call this at the start, # if you want to use this module. self.myfont = pygame.font.SysFont('Comic Sans MS', 30) self.point = 0 self.xp_new = 100 self.background = pygame.image.load('lib/img/background4.png') self.enemy_spawn_time = 2 self.multiplier = 1 self.start = True self.items = [] self.exiting = False for count in range(0, 5): test_enemy = Enemy(random.randint(0, self.display_width), random.randint(0, self.display_height), self.health_bar, pygame, self.multiplier) self.enemies.append(test_enemy) self.add_enemy()
def setup_game(self): player1_letter = input( "What letter would Player 1 like to user? (X or O)?: ").upper() if player1_letter not in ['X', 'O']: #NOTE the player won't see this as is print( 'Invalid input! Automatically selecting X for Player 1 and O for Player 2' ) player1_letter = 'X' player2_letter = 'O' else: print('Assigned %s to Player 1' % player1_letter) player2_letter = 'O' if player1_letter == 'X' else 'X' print('Assigned %s to Player 2' % player2_letter) self.p1 = Player('Player 1', player1_letter, self.size) self.p2 = Player('Player 2', player2_letter, self.size)
def _configure_default_features(self): ''' Import dependencies and configure default features. ''' self._log.warning('configure default features...') from lib.button import Button self._log.info('configuring button...') self._ros._button = Button(self._ros._config, self._ros.get_message_queue(), self._ros._mutex) from lib.bumpers import Bumpers self._log.info('configuring bumpers...') self._ros._bumpers = Bumpers(self._ros._config, self._ros.get_message_queue(), None, Level.INFO) from lib.infrareds import Infrareds self._log.info('configuring infrared trio...') self._ros._infrareds = Infrareds(self._ros._config, self._ros.get_message_queue(), Level.INFO) from lib.player import Sound, Player self._log.info('configuring player...') self._ros._player = Player(Level.INFO) self._log.warning('default features ready.')
def setUp(self): card_one = Card("Heart", "5", 5) card_two = Card("Diamond", "Jack",11) card_three = Card("Spade", "7", 7) card_four = Card("Spade", "Ace", 14) cards = [card_one, card_two, card_three, card_four] self.deck = Deck(cards) self.player1 = Player("John", self.deck) card_five = Card("Heart", "8", 8) card_six = Card("Diamond", "Jack",11) card_seven = Card("Spade", "3", 3) card_eight = Card("Club", "Queen", 12) cards2 = [card_five, card_six, card_seven, card_eight] self.deck2 = Deck(cards2) self.player2 = Player("John", self.deck2) self.turn = Turn(self.player1, self.player2)
def __init__(self): pygame.init() self.options = Options(self) self.screen = pygame.display.set_mode(self.options.window_size) self.icon = Image("game_icon.png") self.caption = "Sunni (Alpha 3.0.0)" self.keys = Keys(self) self.page = None self.file_directory = os.getcwd()[:-3] self.mouse = Mouse() self.clock = pygame.time.Clock() self.fps = 30 self.start_time = time.time() self.current_time = 0 # The amount of time the program as been running self.music = Music(self) self.saves = [Save(n) for n in range(4)] self.selected_save = None self.is_running = True self.next_battle = None self.main_menu = MainMenu(self) self.opening_sequence = OpeningSequence(self) self.opening_sequence.visit() self.new_game_page = NewGamePage(self) self.load_game_page = LoadGamePage(self) self.player = None self.opponent = None self.initialise() OpeningSequence.initialise() NewGamePage.initialise() LoadGamePage.initialise() Surface.initialise(self) Options.initialise() Move.initialise(self) Character.initialise() Player.initialise() MainMenu.initialise() MemeDog.initialise() Battle.initialise() self.opponents = OrderedDict() self.opponents["Meme Dog"] = MemeDog self.opponents["Kanye Snake"] = KanyeSnake self.opponents["Spook Dog"] = SpookDog self.opponents["Evil Cloud"] = EvilCloud
def __init__(self): """ Initiates a Game object with the necessary features """ self.dealer = Dealer(self) # The dealer self.player = Player( self ) # The players: eventually change this to a list of players to allow for more than one
def __init__(self): """Starts the game""" # Create the window and register the draw handler self.window = pyglet.window.Window(caption='Pysteroids', width=WINDOW_WIDTH, height=WINDOW_HEIGHT) self.window.on_draw = self.on_draw # Add key handler to keep track of key presses self.keys = key.KeyStateHandler() self.window.push_handlers(self.keys) # Grab an absolute directory name for the game path # This helps when loading resources on an installed version # of Pysteroids game_path = os.path.dirname(os.path.abspath(__file__)) pyglet.resource.path = [game_path + '/lib/res', game_path + '/lib/res/sounds'] pyglet.resource.reindex() # Grab the game's effect player self.effect_player = EffectPlayer.instance() # Create the player self.player = Player() # Create game rules and an asteroid manager to generate # asteroids self.asteroid_manager = AsteroidManager(self.on_level_change) # Create a label for displaying the number of lives left self.lives_left_label = \ pyglet.text.Label('Lives Left: ' + str(self.player.lives_left), font_name='Droid Sans Mono', font_size=12, x=70, y=WINDOW_HEIGHT-15, anchor_x='center', anchor_y='center') # Create a score label self.score_label = \ pyglet.text.Label('Score: ' + str(self.player.score), font_name='Droid Sans Mono', font_size=12, x=WINDOW_WIDTH-70, y=WINDOW_HEIGHT-15, anchor_x='center', anchor_y='center') # Create a lable for displaying the current level self.level_label = \ pyglet.text.Label('Level: ' + str(self.asteroid_manager .curr_level_num), font_name='Droid Sans Mono', font_size=12, x=WINDOW_WIDTH // 2, y=WINDOW_HEIGHT-15, anchor_x='center', anchor_y='center') # Register and schedule the update function pyglet.clock.schedule(self.update)
def test_player_take_turn_miss(): player1 = Player(1) player2 = Player(2) player1.add_opponent(player2) player2.board.place_ship(player2.ships[0], 2, 2) assert player2.ships[0].length == 2 player1.take_turn(2, 4, 2) assert player2.ships[0].length == 2
def reset(self): """Reset the game""" self.player = Player() self.asteroid_manager = AsteroidManager(self.on_level_change) # Reset the level number label self.level_label.text = ('Level: ' + str(self.asteroid_manager .curr_level_num)) # Reset score label self.score_label.text = 'Score: ' + str(self.player.score)
def __init__(self, pnames): """ :param pnames: An Array. Name of the players as Strings """ self.board = Board() self.players = tuple([Player(pn, self.board, self) for pn in pnames]) self.plookup = {p.getId(): p for p in self.players} self.lastRoll = None self.p = None self.getFirstPlayer() self.state = 0
def new_player(session, game_id): game = get_game(session, game_id) num = len(get_players(session, game_id)) new_player = Player(game_id=game_id, player_id=num) print(new_player.__dict__) session.add(new_player) session.flush() pid = new_player.player_id game.ac += 1 session.commit() return pid
def main(): skills = Skills() skills.combative = SkillRatings.superior skills.social = SkillRatings.average skills.kinetic = SkillRatings.above_average skills.technical = SkillRatings.average chris = Player(skills) print(chris.skills) playerdeck = Deck() playerdeck.shuffle() chris.hand = playerdeck.draw(3) print(chris.hand) card_index = int(input('Please Select Card to Play:\n[0] {0}\n[1] {1}\n[2] {2}\n'.format(chris.hand[0], chris.hand[1], chris.hand[2]))) play_card = chris.play(card_index) print(play_card) print(chris.hand)
def test_player_sink_an_opponent_ship(): player1 = Player(1) player2 = Player(2) player1.add_opponent(player2) player2.board.place_ship(player2.ships[0], 2, 2) assert player1.take_turn(2, 2, 2)['sunk'] == False assert player1.take_turn(2, 3, 2)['sunk'] == True
def main(): signal.signal(signal.SIGINT, signal_handler) _log = Logger('play_test', Level.INFO) try: _log.info('executing player tests...') _player = Player(Level.INFO) _player.play(Sound.BLIP) time.sleep(3.0) _player.play(Sound.ALARM) time.sleep(3.0) _log.info('test complete.') except KeyboardInterrupt: _log.warning('Ctrl-C caught: complete.') except Exception as e: _log.error('error in test: {}'.format(e)) traceback.print_exc(file=sys.stdout) sys.exit(1) finally: sys.exit(0)
def on_scene_enter(self): clock.schedule(self.update) self.player = Player() self.players = [self.player] self.generate_level() # set up collision detection self.coll_detector = collision.CollisionDetector() # collisions between: # flock-player, player-bullets, player-objstacles, bulltets-obstacles, bullets-flock #self.coll_detector.register_once(self, group_name1, group_name2, group1, group2, coll_strategy, type_tuple, func): self.coll_detector.register_group('player', self.players) self.coll_detector.register_group('flocks', self.flocks) self.coll_detector.register_group('obstacles', self.obstacles) self.coll_detector.register_group('enemies', self.enemies) self.coll_detector.register_group('bullets', self.bullets) self.coll_detector.register_pair('player', 'flocks', PlayerFlockCollisionStrategy(self)) self.coll_detector.register_pair('player', 'bullets', PlayerBulletsCollisionStrategy(self)) self.coll_detector.register_pair('player', 'obstacles', PlayerObstaclesCollisionStrategy(self)) self.coll_detector.register_pair('bullets', 'obstacles', BulletsObstaclesCollisionStrategy(self)) self.coll_detector.register_pair('flocks', 'bullets', FlockBulletsCollisionStrategy(self)) #self.coll_detector.register_once('player', 'flocks', self.players, self.flocks, PlayerFlockCollisionStrategy(self), tuple(), None): # enemy #scene, fire_rate, position, orientation) self.enemies.append( Enemy(self, 1, Vec3(300, 10), Vec3(0, 1) * 100.0) ) self.enemies.append( Enemy(self, 0.1, Vec3(10, 200), Vec3(1, -0.1) * 300.0) ) self.enemies.append( Enemy(self, 1, Vec3(500, 10), Vec3(0, 1) * 200) ) p = Polygon() p.add_vertex(400, 400) p.add_vertex(550, 400) p.add_vertex(550, 420) p.add_vertex(400, 450) self.obstacles.append(p)
class TestPlayer(unittest.TestCase): def setUp(self): card_one = Card("Heart", "5", 5) card_two = Card("Diamond", "Jack", 11) card_three = Card("Spade", "7", 7) card_four = Card("Spade", "Ace", 14) cards = [card_one, card_two, card_three, card_four] self.deck = Deck(cards) self.player = Player("John", self.deck) def test_it_exists(self): assert type(self.player) == Player assert self.player.name == 'John' assert self.player.deck == self.deck def test_has_lost(self): assert self.player.has_lost() == False self.player.deck.remove_card() self.player.deck.remove_card() assert self.player.has_lost() == False self.player.deck.remove_card() self.player.deck.remove_card() assert self.player.has_lost() == True
def main(): skills = Skills() skills.combative = SkillRatings.superior skills.social = SkillRatings.average skills.kinetic = SkillRatings.above_average skills.technical = SkillRatings.average chris = Player(skills) print(chris.skills) playerdeck = Deck() playerdeck.shuffle() chris.hand = playerdeck.draw(3) print(chris.hand) card_index = int( input( 'Please Select Card to Play:\n[0] {0}\n[1] {1}\n[2] {2}\n'.format( chris.hand[0], chris.hand[1], chris.hand[2]))) play_card = chris.play(card_index) print(play_card) print(chris.hand)
def __init__(self, size_x, size_y, resize): super(Window, self).__init__(resizable = resize, visible = True, vsync = False) self.set_size(size_x, size_y) self.set_caption('SpaceCow') self.maximize() self.player = Player((self.width / 2), (self.height / 2), 0, "resources/ship.png") for enemies in range(self.enemy_qty): self.enemy.append(Enemy((self.width / 2), (self.height / 2), 0, "resources/cow.png")) for e in self.enemy: e.x_pos = randint(0, self.width) e.y_pos = randint(0, self.height) e.rotation = randint(0, 360) self.player.x_pos = self.width / 2 self.player.y_pos = self.height / 2 self.label_mouse_xy = pyglet.text.Label("Mouse Location") self.play_bg_music()
class Pysteroids(object): """Runs the game and manages game variables Attributes: window: the game window keys: the key state ship: the player's ship asteroids: a list of the currently active asteroids effect_player: the EffectPlayer used to play animations and sounds fps_display: a display to show the current FPS of the application game_rules: the current set of game rules, defining how many asteroids can be on the screen per type asteroid_manager: the AsteroidManager responsible for generating new asteroids based on the game rules lives_left_label: a label for displaying the number of lives the player has left score_label: a label for displaying the player's score level_label: a label for displaying the current level the player is on """ def __init__(self): """Starts the game""" # Create the window and register the draw handler self.window = pyglet.window.Window(caption='Pysteroids', width=WINDOW_WIDTH, height=WINDOW_HEIGHT) self.window.on_draw = self.on_draw # Add key handler to keep track of key presses self.keys = key.KeyStateHandler() self.window.push_handlers(self.keys) # Grab an absolute directory name for the game path # This helps when loading resources on an installed version # of Pysteroids game_path = os.path.dirname(os.path.abspath(__file__)) pyglet.resource.path = [game_path + '/lib/res', game_path + '/lib/res/sounds'] pyglet.resource.reindex() # Grab the game's effect player self.effect_player = EffectPlayer.instance() # Create the player self.player = Player() # Create game rules and an asteroid manager to generate # asteroids self.asteroid_manager = AsteroidManager(self.on_level_change) # Create a label for displaying the number of lives left self.lives_left_label = \ pyglet.text.Label('Lives Left: ' + str(self.player.lives_left), font_name='Droid Sans Mono', font_size=12, x=70, y=WINDOW_HEIGHT-15, anchor_x='center', anchor_y='center') # Create a score label self.score_label = \ pyglet.text.Label('Score: ' + str(self.player.score), font_name='Droid Sans Mono', font_size=12, x=WINDOW_WIDTH-70, y=WINDOW_HEIGHT-15, anchor_x='center', anchor_y='center') # Create a lable for displaying the current level self.level_label = \ pyglet.text.Label('Level: ' + str(self.asteroid_manager .curr_level_num), font_name='Droid Sans Mono', font_size=12, x=WINDOW_WIDTH // 2, y=WINDOW_HEIGHT-15, anchor_x='center', anchor_y='center') # Register and schedule the update function pyglet.clock.schedule(self.update) def update(self, dt): """Updates the game entities Args: dt: time since the last update """ # Update the asteroids self.asteroid_manager.update(dt) # Update any animation data self.effect_player.update(dt) # If the player is dead, we don't have to update # the ship or check for collisions if self.player.is_dead: # If the player hits R, reset if (self.keys[key.R]): self.reset() return self.player.update(self.keys, dt) # Check for bullet hits for asteroid in self.asteroid_manager.asteroids: # We only need to check collisions if the player is # vulnerable, so if the player is not this will # short-circuit if self.player.is_vulnerable and asteroid.collides(self.player .ship): self.player.kill() # Update the display to reflect the new number of lives self.lives_left_label.text = ('Lives Left: ' + str(self.player.lives_left)) # Play explosion sound self.effect_player.play_sound('EXPLOSION') break # Check bullet collisions for bullet in self.player.bullets: if bullet.collides(asteroid): # Remove the current asteroid and add the asteroids # that result from the destruction, if there are any self.asteroid_manager.asteroids.remove(asteroid) self.asteroid_manager.asteroids.extend(asteroid.destroy()) # For scoring, we only add to the player's score if # the asteroid that was destroyed was small. This # is easier than assigning a point value to each # size of asteroid, because bigger asteroids will # automatically be worth more since they 'contain' # many small asteroids if asteroid.size == Asteroid.Size.SMALL: self.player.score += 10 self.score_label.text = 'Score: ' + str(self.player .score) # Remove the bullet from the screen self.player.bullets.remove(bullet) # Play explosion sound self.effect_player.play_sound('EXPLOSION') def on_draw(self): """Handler for the on_draw event of the game window""" self.window.clear() # Reset to the identity view matrix glLoadIdentity() # Draw the game over screen if the player is out of lives, # otherwise draw the lives left and the player (if not dead) if self.player.game_over: self.draw_game_over() else: self.score_label.draw() self.level_label.draw() self.draw_player_status() if not self.player.is_dead: self.player.draw() # Draw animation stuff self.effect_player.draw_animations() # Always draw the asteroids self.asteroid_manager.draw_asteroids() def on_level_change(self, level_num): """Callback for AsteroidManager, invoked when the player completes a level Parameters: level_num: the new level number the player is on """ self.level_label.text = ('Level: ' + str(self.asteroid_manager .curr_level_num)) # Give the player some bonus points for completing a level self.player.score += 50 def draw_player_status(self): """Draws an indicator showing how many lives the player has left and whether his teleport ability is up. Lives left are drawn as ships. """ # Get the player's teleport status teleport_status = ['Down', 'Up'][self.player.teleport_up] # Draw the label teleport_status_label = pyglet.text.Label('Tele: ' + teleport_status, font_name='Droid Sans Mono', font_size=10, anchor_x='center', anchor_y='center', x=100, y=WINDOW_HEIGHT-30) teleport_status_label.draw() # Is the player invulnerable? if not self.player.is_vulnerable: invuln_label = pyglet.text.Label('INVULN', font_name='Droid Sans Mono', font_size=12, anchor_x='center', anchor_y='center', x=200, y=WINDOW_HEIGHT-15) invuln_label.draw() # Label the lives indicator lives_left_label = pyglet.text.Label('Lives:', font_name='Droid Sans Mono', font_size=10, anchor_x='center', anchor_y='center', x=70, y=WINDOW_HEIGHT-15) lives_left_label.draw() # Some variables which we will use to draw the ships scale = 0.25 y = WINDOW_HEIGHT - 15 # The first ship will be drawn at x, and then # the we will increment by dx for each ship we # draw to get the new x position x = 110 dx = 20 # Draw one ship for each life left for i in range(0, self.player.lives_left): ship_shape = Shape((20, 0, -30, 20, -30, -20), Vector(x, y), 90, scale) ship_shape.draw() x += dx def draw_game_over(self): """Draws the game over screen""" # Create a game over label and draw it game_over_label = pyglet.text.Label('GAME OVER!', font_name='Droid Sans Mono', font_size=32, x=WINDOW_WIDTH//2, y=WINDOW_HEIGHT//2, anchor_x='center', anchor_y='center') # Display the player's final score final_score_label = pyglet.text.Label(('Your Score: ' + str(self.player.score)), font_name='Droid Sans Mono', font_size=26, x=WINDOW_WIDTH//2, y=WINDOW_HEIGHT//2 - 35, anchor_x='center', anchor_y='center') # Display option to restart reset_label = pyglet.text.Label('Press \'R\' to reset', font_name='Droid Sans Mono', font_size=20, x=WINDOW_WIDTH//2, y=WINDOW_HEIGHT//2 - 70, anchor_x='center', anchor_y='center') game_over_label.draw() final_score_label.draw() reset_label.draw() def reset(self): """Reset the game""" self.player = Player() self.asteroid_manager = AsteroidManager(self.on_level_change) # Reset the level number label self.level_label.text = ('Level: ' + str(self.asteroid_manager .curr_level_num)) # Reset score label self.score_label.text = 'Score: ' + str(self.player.score)
class WinScene(scenes.Scene): def __init__(self, app): super(WinScene, self).__init__(app) self.space = Space((400, 400)) def f(a, b): if __debug__: pass#print "missing collision function tuple type (%s, %s)" % (a.__class__.__name__, b.__class__.__name__) #self.coll_funcs = coolections.defaultdict(lambda: lambda *args, **kwargs: None) # {(type1, type2): func} self.coll_funcs = collections.defaultdict(lambda: f) # {(type1, type2): func} self.coll_funcs[(Bullet, Player)] = self.coll_player_bullet #self.coll_funcs[(Player, Polygon)] = self.coll_player_obstacle self.coll_funcs[(Bullet, Polygon)] = self.coll_bullet_obstacle self.coll_funcs[(Flock, Polygon)] = self.coll_flock_obstacle self.coll_funcs[(Flock, Bullet)] = self.coll_flock_bullet self.coll_funcs[(Bullet, Flock)] = self.coll_bullet_flock self.coll_funcs[(Player, Flock)] = self.coll_player_flock self.coll_funcs[(Player, Trigger)] = self.coll_player_trigger self.splines = [] self.flocks = [] self.obstacles = [] self.enemies = [] self.triggers = [] self.bullets = [] self.dynamic = [] self.static = [] self.winlabel = None self.winmsg = "You win!" self.campos = Vec3(0.0, 0.0) self.last_lead = Vec3(0.0, 0.0) self.bg_image = pyglet.image.load("data/textures/background.png") self.bg_texture = pyglet.image.TileableTexture.create_for_image(self.bg_image) self.level_file = None #self.app.level_file self.load_level() self.cam_spline = None for spl in self.splines: if spl.kind == 2: # camera spline self.cam_spline = spl if self.cam_spline is None: print "wtf mate" self.t = 0 def lookat(self, pos): self.campos = pos - CAMOFF #-- collision function --# def coll_flock_obstacle(self, flock, obst): for boid in flock.boids: if obst.is_point_in(boid.position.x, boid.position.y): flock.boids.remove(boid) def coll_player_bullet(self, bullet, player): player.alive -= 10 bullet.destroy() if __debug__: print 'collision player - bullet' pass def coll_player_obstacle(self, player, obst): if obst.is_point_in(player.position.x, player.position.y): d = obst.position - player.position minval = 0 for vertex in obst.vertices: value = d.dot(vertex) if value < min: vert = vertex minval = value d.normalize() player.position += vertex.project_onto(d) * 0.1 #if __debug__: print player.velocity, player.position, vertex.project_onto(d) #if __debug__: print 'collision, player - obstacle!' def coll_bullet_obstacle(self, bullet, obst): if obst.is_point_in(bullet.position.x, bullet.position.y): bullet.destroy() #if __debug__: print 'collision, bullet - obstacle!' def coll_bullet_flock(self, bul, flock): self.coll_flock_bullet(flock, bul) def coll_flock_bullet(self, flock, bullet): if flock.boids: boid = min([((boid.position - bullet.position).lengthSQ, boid) for boid in flock.boids]) if boid[0] < 20: flock.boids.remove(boid[1]) bullet.destroy() if __debug__: print 'collision, flcok - bullet!' def coll_player_flock(self, player, flock): if player.color != flock.color: player.alive -= 1 if __debug__: print 'collision, player - flock!' def coll_player_trigger(self, player, trigger): trigger.fire() def have_level(self, level_number): pass def load_level(self): self.level_file = "data/WinLevel.lvl" level = None fobj = open(self.level_file, "rb") level = cerealizer.load(fobj) if level: self.splines = [Spline(self, serial=s) for s in level.splines] self.triggers = [Trigger(0, 0, serial=t) for t in level.triggers] self.obstacles = [Polygon(self, serial=o) for o in level.obstacles] self.enemies = [Enemy(self, s.fire_rate, s.position, s.orientation) for s in level.enemies] # connect triggers for spl in self.splines: for trigger_uuid in spl.trigger_uuids: for trigger in self.triggers: if trigger.uuid == trigger_uuid: trigger += spl.on_trigger self.static.extend( self.triggers + self.obstacles + self.enemies ) self.space.add(self.static) #-- state funcs --# def on_scene_enter(self): #glEnable(GL_POINT_SMOOTH) #glEnable(GL_TEXTURE_2D) self.player = Player() self.players = [self.player] self.dynamic.append(self.player) self.last_lead = self.player.position = self.campos = self.cam_spline.get_point(0) clock.schedule(self.update) def on_scene_leave(self): #glDisable(GL_POINT_SMOOTH) #glDisable(GL_TEXTURE_2D) clock.unschedule(self.update) def add_dynamic(self, bullet): self.dynamic.append(bullet) def remove_dynamic(self, bullet): try: self.dynamic.remove(bullet) except: pass def update(self, dt): # update spline and get position self.t += dt * 0.45 self.winlabel = pyglet.text.Label(self.winmsg, font_name='System', font_size=42, x=self.app.width / 2, y=self.app.height / 2, anchor_x='center', anchor_y='center', color=(86,10,10, 255)) lead_point = self.cam_spline.get_point(self.t) if lead_point: camdelta = lead_point - self.last_lead self.last_lead = lead_point self.lookat(lead_point) self.player.position += camdelta else: pass dynamics = self.dynamic #[dyn for dyn in self.dynamic if dyn.position.get_distanceSQ(self.campos) < 800*800] for dynamic in dynamics: dynamic.update(dt) # collision for item, bhits in self.space.add(dynamics): if bhits: for bitem in bhits: r = item.bounding_radius + bitem.bounding_radius if r * r > item.position.get_distanceSQ(bitem.position): self.coll_funcs[item.__class__, bitem.__class__](item, bitem) self.space.remove(dynamics) if self.player.alive < 0: pass def on_draw(self): self.app.clear() glLoadIdentity() glColor4f(1.0, 1.0, 1.0, 1.0) # Background self.bg_texture.blit_tiled(0, 0, 0, 800, 600) # Camera translation glTranslatef(-self.campos.x, -self.campos.y, 0.0) for dyn in self.dynamic: dyn.draw() self.player.draw() for stat in self.static: stat.draw() glTranslatef(self.campos.x, self.campos.y, 0.0) if self.winlabel: self.winlabel.draw() def on_mouse_press(self, x, y, button, modifiers): pass def on_mouse_drag(self, x, y, dx, dy, button, modifiers): if pyglet.window.mouse.MIDDLE == button and __debug__: self.campos += Vec3(dx, dy) def on_key_press(self, symbol, mod): if symbol == UP: self.player.movey += 1 elif symbol == DOWN: self.player.movey -= 1 elif symbol == RIGHT: self.player.movex += 1 elif symbol == LEFT: self.player.movex -= 1 elif symbol == SPACE: self.player.switchcolor() def on_key_release(self, symbol, mod): if symbol == UP: self.player.movey -= 1 elif symbol == DOWN: self.player.movey += 1 elif symbol == RIGHT: self.player.movex -= 1 elif symbol == LEFT: self.player.movex += 1 def on_scene_leave(self): clock.unschedule(self.update)
class Window(pyglet.window.Window): player = None enemy_qty = 100 enemy = [] label_mouse_xy = None mouse_x = 0 mouse_y = 0 # Class initializer def __init__(self, size_x, size_y, resize): super(Window, self).__init__(resizable = resize, visible = True, vsync = False) self.set_size(size_x, size_y) self.set_caption('SpaceCow') self.maximize() self.player = Player((self.width / 2), (self.height / 2), 0, "resources/ship.png") for enemies in range(self.enemy_qty): self.enemy.append(Enemy((self.width / 2), (self.height / 2), 0, "resources/cow.png")) for e in self.enemy: e.x_pos = randint(0, self.width) e.y_pos = randint(0, self.height) e.rotation = randint(0, 360) self.player.x_pos = self.width / 2 self.player.y_pos = self.height / 2 self.label_mouse_xy = pyglet.text.Label("Mouse Location") self.play_bg_music() def play_bg_music(self): bg_music = pyglet.media.Player() music = pyglet.media.load('resources/635964_A-Heros-Destiny.mp3') bg_music.queue(music) bg_music.eos_action = pyglet.media.Player.EOS_LOOP bg_music.play() def follow_mouse(self, player, timer, speed): player.c_val = sqrt((self.mouse_x - player.x_pos) ** 2 + \ (self.mouse_y - player.y_pos) ** 2) player.x_pos -= ((player.x_pos - self.mouse_x) / player.c_val * speed * timer) player.y_pos -= ((player.y_pos - self.mouse_y) / player.c_val * speed * timer) delta_x = player.x_pos - self.mouse_x delta_y = player.y_pos - self.mouse_y if player.c_val > 1.0: player.rotation = atan2(delta_y, delta_x) / pi * 180 * -1 def follow(self, enemy, timer, speed): enemy.c_val = sqrt((enemy.x_pos - self.player.x_pos) ** 2 + \ (enemy.y_pos - self.player.y_pos) ** 2) enemy.x_pos -= ((enemy.x_pos - self.player.x_pos) / enemy.c_val * speed * timer) enemy.y_pos -= ((enemy.y_pos - self.player.y_pos) / enemy.c_val * speed * timer) delta_x = enemy.x_pos - self.player.x_pos delta_y = enemy.y_pos - self.player.y_pos if enemy.c_val > 1.0: enemy.rotation = atan2(delta_y, delta_x) / pi * 180 * -1 def update(self, dt): self.label_mouse_xy.text = \ "mouse_x: %d mouse_y: %d | player_x: %d player_y: %d | delta: %f | rotation: %f" % \ (self.mouse_x, self.mouse_y, self.player.x_pos, self.player.y_pos, self.player.c_val, self.player.rotation) self.follow_mouse(self.player, dt, self.player.speed) for e in self.enemy: self.follow(e, dt, 10) def on_draw(self): self.clear() self.player.draw_player() for e in self.enemy: e.draw_player() self.label_mouse_xy.draw() def on_mouse_motion(self, x, y, dx, dy): self.label_mouse_xy.x = 10.0 self.label_mouse_xy.y = 10.0 self.mouse_x = x self.mouse_y = y
class PlayGroundScene(scenes.Scene): def __init__(self, app): super(PlayGroundScene, self).__init__(app) spline = Spline(self) spline.add_guide(100, 100) spline.add_guide(100, 200) spline.add_guide(100, 250) spline.add_guide(300, 50) spline.add_guide(400, 150) spline.add_guide(400, 400) spline.add_guide(200, 300) spline.add_guide(100, 100) self.flocks = [Flock(spline, 30, position=Vec3(100,100), color="black")] spline = Spline(self) spline.add_guide(750, 500) spline.add_guide(100, 480) spline.add_guide(150, 50) spline.add_guide(200, 100) spline.add_guide(500, 25) spline.add_guide(700, 300) spline.add_guide(750, 500) self.flocks.append(Flock(spline, 30, position=Vec3(200,200), action="reset")) self.obstacles = [] self.player = None self.enemies = [] self.bullets = [] self.coll_detector = None def add_dynamic(self, entity): if isinstance(entity, enemies.Bullet): self.bullets.append(entity) elif isinstance(entity, flock.Flock): self.flocks.append(entity) else: print 'UNKNOWN entity type to add', entity.__class__.__name__ def remove_dynamic(self, entity): try: if isinstance(entity, enemies.Bullet): self.bullets.remove(entity) elif isinstance(entity, flock.Flock): self.flocks.remove(entity) else: print 'UNKNOWN entity type to remove', entity.__class__.__name__ except: pass def on_scene_enter(self): clock.schedule(self.update) self.player = Player() self.players = [self.player] self.generate_level() # set up collision detection self.coll_detector = collision.CollisionDetector() # collisions between: # flock-player, player-bullets, player-objstacles, bulltets-obstacles, bullets-flock #self.coll_detector.register_once(self, group_name1, group_name2, group1, group2, coll_strategy, type_tuple, func): self.coll_detector.register_group('player', self.players) self.coll_detector.register_group('flocks', self.flocks) self.coll_detector.register_group('obstacles', self.obstacles) self.coll_detector.register_group('enemies', self.enemies) self.coll_detector.register_group('bullets', self.bullets) self.coll_detector.register_pair('player', 'flocks', PlayerFlockCollisionStrategy(self)) self.coll_detector.register_pair('player', 'bullets', PlayerBulletsCollisionStrategy(self)) self.coll_detector.register_pair('player', 'obstacles', PlayerObstaclesCollisionStrategy(self)) self.coll_detector.register_pair('bullets', 'obstacles', BulletsObstaclesCollisionStrategy(self)) self.coll_detector.register_pair('flocks', 'bullets', FlockBulletsCollisionStrategy(self)) #self.coll_detector.register_once('player', 'flocks', self.players, self.flocks, PlayerFlockCollisionStrategy(self), tuple(), None): # enemy #scene, fire_rate, position, orientation) self.enemies.append( Enemy(self, 1, Vec3(300, 10), Vec3(0, 1) * 100.0) ) self.enemies.append( Enemy(self, 0.1, Vec3(10, 200), Vec3(1, -0.1) * 300.0) ) self.enemies.append( Enemy(self, 1, Vec3(500, 10), Vec3(0, 1) * 200) ) p = Polygon() p.add_vertex(400, 400) p.add_vertex(550, 400) p.add_vertex(550, 420) p.add_vertex(400, 450) self.obstacles.append(p) def generate_level(self): # TODO: implement level generation here pass def update(self, dt): for flock in self.flocks: flock.update(dt) for obst in self.obstacles: obst.update(dt) for enemy in self.enemies: enemy.update(dt) for bullet in self.bullets: bullet.update(dt) self.player.update(dt) self.coll_detector.check() #print self.player.alive if self.player.alive < 0: print 'dead!' pass def on_draw(self): self.app.clear() glMatrixMode(GL_MODELVIEW) glLoadIdentity() for flock in self.flocks: flock.draw() glColor4f(1,1,1,1) for obst in self.obstacles: obst.draw() for enemy in self.enemies: enemy.draw() for bullet in self.bullets: bullet.draw() self.player.draw() self.app.draw_fps() def on_mouse_press(self, x, y, button, modifiers): pass def on_key_press(self, symbol, mod): if symbol == UP: self.player.movey += 1 elif symbol == DOWN: self.player.movey -= 1 elif symbol == RIGHT: self.player.movex += 1 elif symbol == LEFT: self.player.movex -= 1 elif symbol == SPACE: self.player.switchcolor() def on_key_release(self, symbol, mod): if symbol == UP: self.player.movey -= 1 elif symbol == DOWN: self.player.movey += 1 elif symbol == RIGHT: self.player.movex -= 1 elif symbol == LEFT: self.player.movex += 1 def on_scene_leave(self): clock.unschedule(self.update)
names = [] for mode in modes: names.append(mode.name) return { 'modes': names, 'currentSong': {} } cherrypy.tree.mount(BasicWeb(), '/info') cherrypy.engine.start() # the player player = Player() logger.info("Entering Main-Loop") current_mode = None # main loop while True: for mode in modes: mode.invalidate() # give them the chance to update priority modes.sort(key=lambda x: x.priority, reverse=False) if current_mode is not None: current_mode.on_stop()