def randomize_players(self): self.set_switching_lock(settings.LOCK_LINEUP_ON_DECISION) players_copy = self.players[:] while players_copy == self.players: randomhelper.shuffle(players_copy) self.players = players_copy SoundManager.play(Trigger.PLAYERS_SHUFFLE)
def main(): # create the managers eMngr = EventManager() gMngr = GraphicManager(eMngr) iMngr = InputManager(eMngr, gMngr) uMngr = UpdateManager(eMngr) sMngr = SoundManager(eMngr) nMngr = NetworkManager(eMngr) print "starting game" # create file with input playFile = open(sys.argv[1], 'r') # start the managers eMngr.start() gMngr.start() iMngr.start() uMngr.start() sMngr.start() nMngr.start() # create game and start it # FIXME playfile should be passed to the updateManager game = Game(iMngr, uMngr, gMngr, sMngr, nMngr, playFile) game.run() # close the managers eMngr.stop() uMngr.stop() iMngr.stop() gMngr.stop() sMngr.stop() nMngr.stop()
def set_player(self, player): # check if player has already been set before try: idx_already_set = self.players.index(player) except ValueError, e: # player is not in any team yet self.players[self.current_player_slot] = player self.highlight_player(self.current_player_slot) SoundManager.play(Trigger.PLAYER_JOINED, player)
def __fetch_players_list_thread(self): # fetch players list from remote server players = ServerCom.fetch_players() if players.__len__() > 0: PlayerData.setPlayers(players) self.__updatenum_players() # generate missing player names for player in players: SoundManager.create_player_sound(player)
def equalize_players(self): self.set_switching_lock(settings.LOCK_LINEUP_ON_DECISION) # get min team elo lineup permutations = list(itertools.permutations(self.players)) team_elo_list = [[i, abs(a['attacker']['elo'] + b['defender']['elo'] - c['attacker']['elo'] - d['defender']['elo'])] for i, (a, b, c, d) in enumerate(permutations)] team_elo_list = sorted(team_elo_list, key=lambda x: x[1]) equal_lineup = list(permutations[team_elo_list[0][0]]) # check positions self.players = self.check_positions(equal_lineup) SoundManager.play(Trigger.PLAYERS_EQUALIZE)
def __init__(self): """Initialize the game, and create game resources.""" pygame.init() self.settings = Settings() self.screen = pygame.display.set_mode((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics, # and create a scoreboard. self.stats = GameStats(self, self.settings) self.sb = Scoreboard(self) # Sprites self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.explosions = pygame.sprite.Group() self.bunkers = pygame.sprite.Group() self.alienbullets = pygame.sprite.Group() # UFO variables self.ufo = None self.display_ufo_score = False self.ufo_score = None self.ufo_rect = None self._create_fleet() self._create_bunker_wall() self._soundmananger = SoundManager() # TODO: Use wait function to display ufo value on screen """ DEFINITION OF EVENTS: a) '_update_frame_event': EVENTID=25, how often alien animations should be updated b) '_update_explosion_frame_event': EVENTID=26, how often explosion animations should be updated c) '_alien_shoot_event': EVENTID=27, how often the aliens have an opportunity to shoot d) '_ufo_summon_event': EVENTID=28, how often the ufo has an opportunity to spawn """ self._update_frame_event = pygame.USEREVENT + 1 self._update_explosion_frame_event = pygame.USEREVENT + 2 self._alien_shoot_event = pygame.USEREVENT + 3 self._ufo_summon_event = pygame.USEREVENT + 4 pygame.time.set_timer(self._update_frame_event, 1000) pygame.time.set_timer(self._update_explosion_frame_event, 200) pygame.time.set_timer(self._alien_shoot_event, self.settings.current_fire_interval) pygame.time.set_timer(self._ufo_summon_event, 10000) # Make the Play button. self.play_button = Button(self, "Play", (0, -50)) self.score_button = Button(self, "High Scores", (0, 50)) self.back_button = Button(self, "Main Menu", (0, 50))
def __handle_goal(self, data): # 0 : home, 1: away if data in ["0", "1"]: team_id = int(data) GameData.add_goal(team_id) # play goal sound SoundManager.play(Trigger.GOAL) # update local match data self.update_match() # highlight score board HighlightOverlay(orig_obj=self.score_objects[team_id], parent=self).animate(font_size=500, color=(1, 1, 1, 0), d=2.0)
def __handle_goal(self, team): if team == '1': GameData.add_goal(0) obj = self.ids.labelHome else: GameData.add_goal(1) obj = self.ids.labelAway self.score = GameData.get_score() HighlightOverlay(orig_obj=obj, parent=self).animate(font_size=500, color=(1, 1, 1, 0), d=2.0) SoundManager.play(Trigger.GOAL)
def on_score(self, instance, value): # update kickoff information self.handle_kickoff(False) # check max goal during match if self.state == 'running': if GameData.is_match_finished(): self.state = 'finished' SoundManager.play(Trigger.GAME_END) # manual swiping can resume a finished match elif self.state == 'finished': self.state = 'running' SoundManager.play(Trigger.GAME_RESUME)
def __handle_rfid(self, rfid): self.current_rfid = rfid SoundManager.play(Trigger.RFID) # RFID --> player ID player_id = PlayerData.get_player_by_rfid(rfid) # player ID --> player dict player = PlayerData.get_player_by_id(player_id) if player: time.sleep(0.5) self.current_player = player else: self.current_player = {}
def update_match(self): # fetch score from GameData self.score = GameData.get_score() # update kickoff information self.handle_kickoff(False) # check max goal during match if self.state == 'running': if GameData.is_match_finished(): self.state = 'finished' self.stop_time = self.get_time() SoundManager.play(Trigger.GAME_END) # manual swiping can resume a finished match elif self.state == 'finished' and not GameData.is_match_finished(): self.state = 'running' SoundManager.play(Trigger.GAME_RESUME)
def __fetch_players_list_thread(self): # fetch players list from remote server players = ServerCom.fetch_players() if players: PlayerData.set_players(players) self.__updatenum_players() # generate missing player names for player in players: SoundManager.create_player_sound(player) # fetch ranking ranking_attacker = ServerCom.fetch_ranking('attacker') if ranking_attacker: PlayerData.set_ranking('attacker', ranking_attacker) ranking_defender = ServerCom.fetch_ranking('defender') if ranking_defender: PlayerData.set_ranking('defender', ranking_defender)
def on_back(self): # game still running, ask for user confirmation if self.state == 'running': SoundManager.play(Trigger.GAME_PAUSE) view = ModalView(size_hint=(None, None), size=(600, 400), auto_dismiss=False) content = Factory.STModalView(title='Spiel abbrechen', text='Das Spiel ist noch nicht beendet.\nWirklich abbrechen?', cb_yes=self.cancel_match, cb_no=self.resume_match) view.add_widget(content) view.open() # game not running anymore elif self.state in ['finished', 'submitting', 'submit_failed']: view = ModalView(size_hint=(None, None), size=(600, 400), auto_dismiss=False) content = Factory.STModalView(title='Spiel abbrechen', text='Das Ergebnis wurde noch nicht hochgeladen.\nWirklich abbrechen?', cb_yes=self.cancel_match) view.add_widget(content) view.open() else: self.manager.current = 'lounge'
def __init__(self, **kwargs): super(BackgroundScreenManager, self).__init__(**kwargs) self.transition = FadeTransition(duration=0.2) # setup hardware listener self.hwlistener = HardwareListener() self.hwlistener.register(self.receive_msg) # setup network status NetworkInfo.start_polling() # setup screens self.add_widget(MenuScreen(name='menu')) self.add_widget(RfidSetupScreen(name='rfid-setup')) self.add_widget(SettingsScreen(name='settings')) self.add_widget(LoungeScreen(name='lounge')) self.add_widget(MatchScreen(name='match')) SoundManager.play(Trigger.INTRO)
def __init__(self): pygame.init() self.screen = pygame.display.set_mode(size) self.soundmanager = SoundManager() self.imagemanager = ImageManager() self.plane = Plane(self.screen) self.STATE = 'waiting' self.enemykingexist = False self.parachuteexist = False self.enemylist = [] self.bulletlist = [] self.enemybulletlist = [] self.score = 0 self.level = 0 self.chance = 5 self.chioce = 0 #select difficulty self.degree = DEGREE[self.chioce] self.speed = self.degree['initspeed'] self.enemykingtimes = 0 self.clock = 0
def handle_score_touch_up(self, event): if self.state not in ['running', 'finished']: return if self.score_touch: score_id = self.score_touch['id'] dist = event.pos[1] - self.score_touch['startPos'] if abs(dist) > settings.SCORE_SWIPE_DISTANCE: goal_up = dist > 0 if goal_up: swipe_allowed = GameData.add_goal(score_id) else: swipe_allowed = GameData.revoke_goal(score_id) if swipe_allowed: self.update_match() HighlightOverlay(orig_obj=self.score_objects[score_id], parent=self).animate(font_size=500, color=(1, 1, 1, 0)) if goal_up: SoundManager.play(Trigger.GOAL) else: SoundManager.play(Trigger.OFFSIDE) else: self.denied() self.score_objects[score_id].color = (1, 1, 1, 1) self.score_touch = None
def handle_score_touch_up(self, event): if self.state not in ['running', 'finished']: return if self.score_touch: score_id = self.score_touch['id'] dist = event.pos[1] - self.score_touch['startPos'] if abs(dist) > self.MIN_SCORE_MOVE_PX: goal_up = dist > 0 if goal_up: swipe_allowed = GameData.add_goal(score_id) else: swipe_allowed = GameData.revoke_goal(score_id) if swipe_allowed: self.score = GameData.get_score() HighlightOverlay(orig_obj=self.score_objects[score_id], parent=self).animate(font_size=500, color=(1, 1, 1, 0)) if goal_up: SoundManager.play(Trigger.GOAL) else: SoundManager.play(Trigger.OFFSIDE) else: # TODO: "Rote Karte" pass self.score_objects[score_id].color = (1, 1, 1, 1) self.score_touch = None
def __init__(self, eventMgr): self.em = eventMgr self.em.register(self) pygame.init() self.game_over = False self.screen = pygame.display.set_mode((Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT)) self.view = pygame.Surface((Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT)) self.viewport = self.view.get_rect() pygame.display.set_caption("Game") self.sm = SoundManager("media/skeptic.mp3") try: self.world = World(self, eventMgr) self.world.loadLevel("levels/mappi.txt") except: pygame.quit() raise # continue catched exception self.em.tell("GameStart")
class PlayState: """ The PlayState class. Maintains a list of all entity groups, can update them all, draw them all, return a list of all their sprites, and run the collision system.""" def __init__(self): self.cfg = ConfigHandler('thm.cfg') self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = (0.0, 0.0) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler(1, 2, callSpeshulEffect) self.space.add_collision_handler(2, 2, callSpeshulEffect) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager(self) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder = {} self.curInputDict = {} self.playersGroup = None self.namedGroups = {'playersGroup': self.playersGroup} self.lineVisualiser = LineVisualiser(self) self.rerenderEverything = False self.soundManager = SoundManager(self) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None def initNetworking(self): if not self.networkingStarted: #pygnetic.init(logging_lvl=logging.DEBUG) pygnetic.init(logging_lvl=logging.ERROR) self.networkingStarted = True registerMessages() def hostGame(self): if self.isHost: del self.networkNode._server gc.collect() else: self.isHost = True self.initNetworking() self.networkNode = NetworkServer(self, "", int(self.cfg.getVal("port")), networkingMode=1) self.addGroup(EntityGroup('networkPlayers'), name='networkPlayers') print "Beginning hosting..." def connectToGame(self, addr, port): if self.isClient: del self.networkNode._client gc.collect() else: self.isClient = True self.initNetworking() self.networkNode = NetworkClient(self, networkingMode=1) self.networkNode.connect(addr, port) self.addGroup(EntityGroup('networkPlayers'), name='networkPlayers') print "Connecting..." def addBoundary(self, point1, point2): newSeg = pymunk.Segment(self.boundaryBody, point1, point2, 1) self.boundaries.append(newSeg) self.space.add(newSeg) def removeBoundary(self, givenSeg): self.boundaries.remove(givenSeg) self.space.remove(givenSeg) def swap(self, newState): self.stateToSwap = newState def addInterweaveGroup(self, group, index): if self.interweaveOrder.get(index, None) is None: self.interweaveOrder[index] = [group] else: self.interweaveOrder[index].append(group) def addGroup(self, group, indexValue=None, isPlayerGroupBool=False, name=None, interweaveWithFloor=False): """Add's an entity group to the PlayState. If indexValue specifies the draw-order, defaults to last. isPlayerGroupBool specifies if the group is a group of players (ie, a group that will be sent input dictionaries). If a "name" is given, set PlayState.name = group. interweaveWithFloor means that the entityGroup is drawn with the floor layers instead, drawn after the layer of it's index. Multiple entgroups can share a interweave number, and they'll be drawn according to order of their addition. an interweave index of 0 means it will be drawn AFTER layer 1, the first layer above the background floor""" group.playState = self self.groups.append(group) if not interweaveWithFloor: newIndex = len(self.groups) - 1 if indexValue is None: self.drawOrder.append(newIndex) else: self.drawOrder.insert(indexValue, newIndex) else: newIndex = len(self.floor.layers) - 1 if indexValue is None: self.addInterweaveGroup(group, newIndex) else: self.addInterweaveGroup(group, indexValue) if isPlayerGroupBool: self.namedGroups['playersGroup'] = group self.playersGroup = group if name is not None: self.namedGroups[name] = group setattr(self, name, group) def checkForFocus(self): lostFocus = (not pygame.mouse.get_focused()) and self.checkFocus self.pausedByFocus = lostFocus def pause(self): self.paused = True def unpause(self): self.paused = False def togglePaused(self): self.paused = not self.paused def processNetworkEvents(self, dt): self.gameLogicManager.preNetworkTick(dt) if self.isHost or self.isClient: if self.networkTicker >= int(60.0 / self.networkRate): self.networkNode.update(dt) self.networkTicker = -1 self.networkNode.updateTime(dt) self.networkTicker += 1 self.gameLogicManager.postNetworkTick(dt) def update(self, dt): """A generic update function. Sends input dictionaries to playerGroups. Updates all the child groups, runs the collision system.""" self.floor.update(self.panX, self.panY) self.checkForFocus() if self.paused or self.pausedByFocus: self.processNetworkEvents(dt) return None #Game logic self.gameLogicManager.preTick(dt) if not self.hardBlockInput: #I'm doing the same thing even if the host or client is the same, to force identical player behaviour for either. if self.isClient or self.isHost: self.inputDictLog.append(self.curInputDict) if self.networkTicker >= int(60.0 / self.networkRate): for eachDict in self.inputDictLog: if self.playersGroup is not None and len(eachDict) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput(eachDict) for eachElement in self.hudList: eachElement.sendInput(eachDict) self.inputDictLog = [] if self.isClient: self.networkNode.sendInput(self.curInputDict) else: if self.playersGroup is not None and len( self.curInputDict) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput(self.curInputDict) for eachElement in self.hudList: eachElement.sendInput(self.curInputDict) self.curInputDict = {} self.space.step(1.0 / 60.0) for eachTriplet in self.postStepQueue: eachTriplet[0](eachTriplet[1], eachTriplet[2]) self.postStepQueue = [] for eachGroup in self.groups: eachGroup.update(dt) for eachElement in self.hudList: eachElement.update(dt) self.soundManager.update(dt) self.processNetworkEvents(dt) self.gameLogicManager.postTick(dt) def setPan(self, x, y): screenW, screenH = getResolution() if self.limitX1 is not None: x = min(-self.limitX1, x) if self.limitX2 is not None: x = max(-(self.limitX2 - screenW), x) if self.limitY1 is not None: y = min(-(self.limitY1), y) if self.limitY2 is not None: y = max(-(self.limitY2 - screenH), y) self.panX, self.panY = x, y def sendInput(self, inputDict): """Simply sets PlayState.curInputDict to a given input dictionary, for use in PlayState.update()""" self.curInputDict = inputDict def sprites(self): """Returns a list of all the sprites in all the entity groups in the PlayState.""" sumList = [] for eachSpriteList in [ someGroup.sprites() for someGroup in self.groups ]: sumList.extend(eachSpriteList) return sumList def draw(self, surface): """Draw all the child entity groups in PlayState, returning changed area rects""" changeRects = [] changeRects.append( surface.blit(self.floor.layers[0].image, self.floor.layers[0].rect.topleft)) if not self.drawByFeet: for eachVal in self.drawOrder: changeRects.extend(self.groups[eachVal].draw(surface)) allInterweaveGroups = self.interweaveOrder.values() for eachVal in range(1, len(self.floor.layers)): eachLayer = self.floor.layers[eachVal] changeRects.append( surface.blit(eachLayer.image, eachLayer.rect.topleft)) groupsToDraw = self.interweaveOrder.get(eachVal - 1, None) if groupsToDraw is not None: allInterweaveGroups.remove(groupsToDraw) [ changeRects.extend(each.draw(surface)) for each in groupsToDraw ] #Draw anything left over for eachGroupSet in allInterweaveGroups: [ changeRects.extend(eachGroup.draw(surface)) for eachGroup in eachGroupSet ] else: yTuples = [] for eachSprite in self.sprites(): if eachSprite.flatInDrawByFeet: y = eachSprite.rect.top else: y = eachSprite.rect.bottom yTuples.append((y, eachSprite)) yTuples.extend([(each.rect.bottom, each) for each in self.floor.layers[1:]]) renderList = [ each[1] for each in sorted(yTuples, lambda x, y: cmp(x[0], y[0])) ] #I probably shouldn't be doing this. tmpDrawGroup = pygame.sprite.LayeredDirty(self.floor.layers[0], renderList) changeRects.extend(tmpDrawGroup.draw(surface)) tmpDrawGroup.empty() del tmpDrawGroup changeRects.extend( self.lineVisualiser.draw(surface, (self.panX, self.panY))) if len(self.gameLogicManager.lasers) > 0: pt1, pt2 = self.gameLogicManager.getCurAimLine() pygame.draw.line(surface, darkGreen, pt1, pt2) for eachShot in self.gameLogicManager.preparedShots: pygame.draw.line(surface, green, eachShot[1][0], eachShot[1][1]) #for eachMissile in [ each for each in self.genericStuffGroup.sprites() if each.__class__.__name__ == "Missile" ]: #pygame.draw.line( surface, darkRed, eachMissile.getPosition(), eachMissile.startPos, 4 ) for eachElement in self.hudList: eachElement.draw(surface) changeRects.extend([each.rect for each in self.hudList]) if self.rerenderEverything: w, h = surface.get_width(), surface.get_height() changeRects.extend([pygame.Rect(0, 0, w, h)]) self.rerenderEverything = False return changeRects # # # This function, __getitem__, takes a value, if that value is a string, it looks for a group in PlayState.groups that has that string as entityGroup.name. # If that value is an int, it returns the group at that index value in self.groups. # def __getitem__(self, value): if type(value) == str: for eachGroup in self.groups: if eachGroup.name == value: return eachGroup raise Exception("No group in PlayState by name: " + value) elif type(value) == int: return self.groups[value] else: raise Exception( "PlayState.__getitem__ only takes strs or ints, got: " + str(type(value)))
def say_connection_status(self): if self.connected: SoundManager.play(Trigger.HOTSPOT_CONNECT, self.player) else: SoundManager.play(Trigger.HOTSPOT_DISCONNECT)
import sys from time import sleep from udmx import uDMX from soundmanager import SoundManager from ultrasonic import UltraSonic from controller import Controller #initialize all submodules dx = uDMX() print("uDMX loaded") sm = SoundManager() print("SoundManager loaded") us = UltraSonic() print("UltraSonic rangefinder loaded") ctrl = Controller(dx, sm, us) print("Scare-controller loaded") # Waiting fir victims... try: while True: ctrl.handle_fear() ctrl.kill_non_current_us_stage_threads() sys.stdout.flush() sleep(0.5) except KeyboardInterrupt: # when 'Ctrl+C' is pressed, the program will exit pass
def _load_theme(self): SoundManager.init(self.theme)
def on_current_player(self, instance, value): self.ids.btnPlayer.iconText = self.current_player.get('name', u'---') SoundManager.play(Trigger.PLAYER_SELECTED, self.current_player) # enable "accept" button if current player is set and was not stored before self.ids.btnAccept.disabled = not (self.current_player.has_key('id') and self.current_player.get('id') != PlayerData.get_rfid_map().get(self.current_rfid))
class Game: def __init__(self): pygame.init() self.screen = pygame.display.set_mode(size) self.soundmanager = SoundManager() self.imagemanager = ImageManager() self.plane = Plane(self.screen) self.STATE = 'waiting' self.enemykingexist = False self.parachuteexist = False self.enemylist = [] self.bulletlist = [] self.enemybulletlist = [] self.score = 0 self.level = 0 self.chance = 5 self.chioce = 0 #select difficulty self.degree = DEGREE[self.chioce] self.speed = self.degree['initspeed'] self.enemykingtimes = 0 self.clock = 0 def play(self): #self.draw() while True: for event in pygame.event.get(): if event.type == KEYDOWN: if event.key == K_ESCAPE: sys.exit() if self.STATE == 'waiting': self.drawmenu() if event.key in (K_DOWN, K_s): self.chioce = (self.chioce + 1) % 3 if event.key in (K_UP, K_w): self.chioce = (self.chioce + 2) % 3 if event.key == K_RETURN: self.init_game() if self.STATE == 'playing': if event.key in (K_LEFT, K_a): self.plane.move('left') elif event.key in (K_RIGHT, K_d): self.plane.move('right') if self.STATE == 'gameover': self.soundmanager.play_fail_sound() if event.key == K_RETURN: self.init_game() if event.key == K_SPACE: self.STATE = 'waiting' if event.type == QUIT: sys.exit() if self.STATE == 'playing': #shoot if self.clock % self.degree['shoot period'] == 0: self.bulletlist.append(self.plane.shoot()) for bullet in self.bulletlist: bullet.move() if len(self.bulletlist) > 0: if self.bulletlist[0].site[1] <= 0: self.bulletlist.pop(0) #enemy assault if self.clock % self.degree['enemy period'] == 0: temp_x = random.randint(1, CLOUMNS - 2) temp_enemy = Enemy(self.screen, [temp_x, 0]) self.enemylist.append(temp_enemy) for enemy in self.enemylist: enemy.move() if len(self.enemylist ) > 0 and self.enemylist[0].site[1] > ROWS - 3: self.enemylist.pop(0) self.chance -= 1 if self.chance <= 0: self.STATE = 'gameover' #enemyking assault if self.score % self.degree[ 'enemyking period'] == 0 and self.enemykingexist == False: self.enemyking = EnemyKing( self.screen, [random.randint(1, CLOUMNS - 4), 0]) self.enemykingtimes = 0 self.enemykingexist = True if self.enemykingexist == True: self.enemyking.move() if self.enemyking.site[1] > ROWS - 3: self.STATE = 'gameover' if self.clock % ( self.degree['enemyking period'] - self.level ) == 0: #enemy shooting frequency is related to the level self.enemybulletlist.append(self.enemyking.shoot()) if len(self.enemybulletlist) > 0: if abs(self.enemybulletlist[0].site[0]-self.plane.site[0]-0.8)<=1 and \ abs(self.enemybulletlist[0].site[1]-0.8-self.plane.site[1])<=1: self.chance -= 1 self.enemybulletlist.pop(0) if self.chance <= 0: self.STATE = 'gameover' if len(self.enemybulletlist) > 0: if self.enemybulletlist[0].site[1] > ROWS - 2: self.enemybulletlist.pop(0) for enemybullet in self.enemybulletlist: enemybullet.move() #shoot successfully for bullet in self.bulletlist: for enemy in self.enemylist: if abs(bullet.site[0]-enemy.site[0]-0.8)<=0.8 and \ abs(bullet.site[1]-enemy.site[1]-0.8)<=0.8: self.bulletlist.remove(bullet) self.enemylist.remove(enemy) self.score += 1 for bullet in self.bulletlist: if abs(bullet.site[0]-self.enemyking.site[0]-3)<=2 and \ abs(bullet.site[1]-self.enemyking.site[1]-3)<=2: self.enemykingtimes += 0.7 self.bulletlist.remove(bullet) if self.enemykingtimes > 3: self.soundmanager.play_shoot_sound() self.enemykingexist = False #if enemyking is shooted more than three times,it will disappear #parachute if random.randint(500, 500 + self.degree['parachute period'] ) == 520 and self.parachuteexist == False: self.parachute = Parachute( self.screen, [random.randint(1, ROWS - 3), 0]) self.parachuteexist = True if self.parachuteexist == True: self.parachute.move() if abs(self.plane.site[0]-self.parachute.site[0]+0.3)<1.5 and \ abs(self.plane.site[1]-self.parachute.site[1]-0.5)<1.5: self.chance += 1 self.parachuteexist = False if self.parachuteexist == True: if self.parachute.site[1] > ROWS - 2: self.parachuteexist = False #accelerate level_temp = self.level self.level = int((self.score + 1)**0.5 / 3) if self.level > level_temp: self.soundmanager.play_cheer_sound() self.speed = self.degree['initspeed'] + self.speed self.draw() self.clock += 1 if self.STATE == 'gameover': self.drawfinal() if self.STATE == 'waiting': self.drawmenu() pygame.display.update() pygame.time.Clock().tick(self.speed) def init_game(self): self.plane = Plane(self.screen) self.STATE = 'playing' self.enemykingexist = False self.parachuteexist = False self.enemylist = [] self.bulletlist = [] self.enemybulletlist = [] self.score = 0 self.level = 0 self.chance = 5 self.degree = DEGREE[self.chioce] self.speed = self.degree['initspeed'] self.enemykingtimes = 0 self.clock = 0 def draw(self): self.screen.blit(self.imagemanager.background, (0, 0)) self.plane.show1() for bullet in self.bulletlist: bullet.show() for enemy in self.enemylist: enemy.show() if self.enemykingexist == True: self.enemyking.show(int(self.enemykingtimes)) for enemybullet in self.enemybulletlist: enemybullet.show() if self.parachuteexist == True: self.parachute.show() scoreText=pygame.font.SysFont('楷体',30).render \ ('SCORE:'+str(self.score),True,(10,20,200)) self.screen.blit(scoreText, (0, 0)) levelText=pygame.font.SysFont('楷体',30).render \ ('LEVEL:'+str(self.level),True,(10,20,200)) self.screen.blit(levelText, (0, 20)) chanceText=pygame.font.SysFont('楷体',30).render \ ('CHANCE:'+str(self.chance),True,(10,20,200)) self.screen.blit(chanceText, (0, 40)) degreeText=pygame.font.SysFont('楷体',30).render \ ('DEGREE:'+Degree[self.chioce],True,(10,20,200)) self.screen.blit(degreeText, (0, 60)) def drawfinal(self): f = open('score.csv', 'r') score_hign = f.read().split(',') f.close() if int(score_hign[self.chioce]) < self.score: score_hign[self.chioce] = str(self.score) f = open('score.csv', 'w') f.write(score_hign[0] + ',' + score_hign[1] + ',' + score_hign[2]) f.close() self.screen.blit(self.imagemanager.background, (0, 0)) overText = pygame.font.SysFont('楷体', 30).render(u'GAMEOVER!', True, (0, 0, 255)) scoreText = pygame.font.SysFont('楷体', 30).render(u'SCORE:' + str(self.score), True, (0, 0, 255)) againText = pygame.font.SysFont('楷体', 30).render(u'press enter to try again', True, (0, 0, 255)) menuText = pygame.font.SysFont('楷体', 30).render( u'press space and trun to the menu', True, (0, 0, 255)) hignsocreText = pygame.font.SysFont('楷体', 30).render( u'hignest score:' + score_hign[self.chioce], True, (0, 0, 255)) self.screen.blit(overText, (150, 200)) self.screen.blit(scoreText, (150, 230)) self.screen.blit(hignsocreText, (150, 260)) self.screen.blit(againText, (150, 290)) self.screen.blit(menuText, (150, 320)) def drawmenu(self): self.screen.blit(self.imagemanager.background, (0, 0)) easyText = pygame.font.SysFont('楷体', 40).render(u'EASY', True, (0, 0, 255)) mediumText = pygame.font.SysFont('楷体', 40).render(u'MEDIUM', True, (0, 0, 255)) difficultText = pygame.font.SysFont('楷体', 40).render(u'DIFFICULT', True, (0, 0, 255)) if self.chioce == 0: easyText = pygame.font.SysFont('楷体', 40).render(u'EASY', True, (255, 0, 0)) elif self.chioce == 1: mediumText = pygame.font.SysFont('楷体', 40).render( u'MEDIUM', True, (255, 0, 0)) elif self.chioce == 2: difficultText = pygame.font.SysFont('楷体', 40).render( u'DIFFICULT', True, (255, 0, 0)) self.screen.blit(easyText, (180, 250)) self.screen.blit(mediumText, (180, 300)) self.screen.blit(difficultText, (180, 350))
def cancel_match(self): SoundManager.play(Trigger.MENU) self.manager.get_screen('lineup').set_switching_lock(False) self.manager.current = 'lineup'
class AlienInvasion: """Overall 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((0, 0), pygame.FULLSCREEN) self.settings.screen_width = self.screen.get_rect().width self.settings.screen_height = self.screen.get_rect().height pygame.display.set_caption("Alien Invasion") # Create an instance to store game statistics, # and create a scoreboard. self.stats = GameStats(self, self.settings) self.sb = Scoreboard(self) # Sprites self.ship = Ship(self) self.bullets = pygame.sprite.Group() self.aliens = pygame.sprite.Group() self.explosions = pygame.sprite.Group() self.bunkers = pygame.sprite.Group() self.alienbullets = pygame.sprite.Group() # UFO variables self.ufo = None self.display_ufo_score = False self.ufo_score = None self.ufo_rect = None self._create_fleet() self._create_bunker_wall() self._soundmananger = SoundManager() # TODO: Use wait function to display ufo value on screen """ DEFINITION OF EVENTS: a) '_update_frame_event': EVENTID=25, how often alien animations should be updated b) '_update_explosion_frame_event': EVENTID=26, how often explosion animations should be updated c) '_alien_shoot_event': EVENTID=27, how often the aliens have an opportunity to shoot d) '_ufo_summon_event': EVENTID=28, how often the ufo has an opportunity to spawn """ self._update_frame_event = pygame.USEREVENT + 1 self._update_explosion_frame_event = pygame.USEREVENT + 2 self._alien_shoot_event = pygame.USEREVENT + 3 self._ufo_summon_event = pygame.USEREVENT + 4 pygame.time.set_timer(self._update_frame_event, 1000) pygame.time.set_timer(self._update_explosion_frame_event, 200) pygame.time.set_timer(self._alien_shoot_event, self.settings.current_fire_interval) pygame.time.set_timer(self._ufo_summon_event, 10000) # Make the Play button. self.play_button = Button(self, "Play", (0, -50)) self.score_button = Button(self, "High Scores", (0, 50)) self.back_button = Button(self, "Main Menu", (0, 50)) def run_game(self): """Start the main loop for the game.""" # Game stats == false is here while True: self._check_events() if self.stats.game_active: self.ship.update() self._update_bullets() self._update_aliens() self._update_screen() else: self._draw_main_menu() def _check_events(self): """Respond to keypresses and mouse events.""" for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: self._check_keydown_events(event) elif event.type == pygame.KEYUP: self._check_keyup_events(event) elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() self._check_play_button(mouse_pos) self._check_score_button(mouse_pos) elif event.type == self._update_frame_event: self._update_frames() elif event.type == self._update_explosion_frame_event: self._update_explosion_frames() elif event.type == self._alien_shoot_event: self._alien_shoot() elif event.type == self._ufo_summon_event: self._create_ufo() # Game start function 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.initialize_dynamic_settings() # Make sure all sprites are destroyed if there was a previous game self.bullets.empty() self.bunkers.empty() self.alienbullets.empty() self.aliens.empty() if self.ufo is not None: self.ufo.kill() if self._soundmananger.getinstance().getufosoundactive: self._soundmananger.getinstance().stopufosound() self.ufo = None # Reset the game statistics. self.stats.reset_stats(self.settings) self.stats.game_active = True self.sb.prep_score() self.sb.prep_level() self.sb.prep_ships() # Get rid of any remaining aliens and bullets. self.aliens.empty() self.bullets.empty() # Create a new fleet and center the ship. self._create_fleet() self._create_bunker_wall() self.ship.center_ship() # Update events pygame.time.set_timer(self._alien_shoot_event, self.settings.current_fire_interval) # Hide the mouse cursor. pygame.mouse.set_visible(False) # Start background music self._soundmananger.getinstance().startgame() def _check_score_button(self, mouse_pos): button_clicked = self.score_button.rect.collidepoint(mouse_pos) if button_clicked and not self.stats.game_active: self.screen.fill(self.settings.bg_color) self.screen.blit(self.settings.screenbackground, self.settings.screenbackgroundrect) self.stats.display_scores() self.back_button.rect = self.score_button.rect self.back_button.prep_msg() self.back_button.draw_button() pygame.display.flip() while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q or event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() elif event.type == pygame.MOUSEBUTTONDOWN: mouse_pos = pygame.mouse.get_pos() button_clicked = self.score_button.rect.collidepoint(mouse_pos) if button_clicked: return def _check_keydown_events(self, event): """Respond to keypresses.""" if event.key == pygame.K_RIGHT or event.key == pygame.K_d: self.ship.moving_right = True elif event.key == pygame.K_LEFT or event.key == pygame.K_a: self.ship.moving_left = True elif event.key == pygame.K_q or event.key == pygame.K_ESCAPE: sys.exit() elif event.key == pygame.K_SPACE: self._fire_bullet() def _check_keyup_events(self, event): """Respond to key releases.""" if event.key == pygame.K_RIGHT or event.key == pygame.K_d: self.ship.moving_right = False elif event.key == pygame.K_LEFT or event.key == pygame.K_a: self.ship.moving_left = False def _fire_bullet(self): """Create a new bullet and add it to the bullets group.""" if len(self.bullets) < self.settings.bullets_allowed: new_bullet = Bullet(self) self.bullets.add(new_bullet) def _alien_shoot(self): for alien in self.aliens: if random.randint(0, self.settings.current_fire_chance) == self.settings.fire_chance_key: self._alien_fire_bullet(alien) def _alien_fire_bullet(self, alien): new_bullet = AlienBullet(self, alien) self.alienbullets.add(new_bullet) def _update_bullets(self): """Update position of bullets and get rid of old bullets.""" # Update bullet positions. self.bullets.update() # Update alien bullet positions self.alienbullets.update() # Get rid of bullets that have disappeared. for bullet in self.bullets.copy(): if bullet.rect.bottom <= 0: self.bullets.remove(bullet) for bullet in self.alienbullets.copy(): if bullet.rect.bottom >= self.settings.screen_height: self.bullets.remove(bullet) self._check_bullet_alien_collisions() self._check_alienbullet_collisions() def _check_bullet_alien_collisions(self): """Respond to bullet-UFO collisions.""" if self.ufo is not None: collisions = pygame.sprite.spritecollide(self.ufo, self.bullets, False) if collisions: self.stats.score += self.ufo.score self.sb.prep_score() self.sb.check_high_score() score_str = "{:,}".format(self.ufo.score) font = pygame.font.SysFont(None, 36) self.ufo_score = font.render(score_str, True, (255, 255, 0), self.settings.bg_color) self.ufo_rect = self.ufo_score.get_rect() self.ufo_rect.center = self.ufo.rect.center self.display_ufo_score = True thread = threading.Thread(target=self._ufo_score_duration, args=[3000], daemon=True) thread.start() self.ufo.kill() if self._soundmananger.getinstance().getufosoundactive(): self._soundmananger.getinstance().stopufosound() self.ufo = None """Respond to bullet-alien collisions.""" # Remove any bullets and aliens that have collided. collisions = pygame.sprite.groupcollide(self.bullets, self.aliens, True, False) if collisions: for aliens in collisions.values(): for alien in aliens: self.stats.score += alien.score explosion = AlienExplosion(self, alien) self.explosions.add(explosion) alien.kill() self.sb.prep_score() self.sb.check_high_score() if not self.aliens: # New level created here # Destroy existing bullets and create new fleet. self.bullets.empty() self.bunkers.empty() self.alienbullets.empty() if self.ufo is not None: self.ufo.kill() if self._soundmananger.getinstance().getufosoundactive: self._soundmananger.getinstance().stopufosound() self.ufo = None # Create new objects self._create_fleet() self._create_bunker_wall() # Adjust stats & increase level self.stats.level += 1 self.settings.increase_speed(self.stats.level) pygame.time.set_timer(self._alien_shoot_event, self.settings.current_fire_interval) self._soundmananger.getinstance().newlevel() self.sb.prep_level() # Get a list of collisions between all bunkers and bullets # Don't kill bullets, as we need the coordinates for bunker pixel destruction collisions = pygame.sprite.groupcollide(self.bunkers, self.bullets, False, False) if collisions: for bunker in collisions: for bullet in collisions[bunker]: if bunker.validhit(bullet): bullet.kill() def _check_alienbullet_collisions(self): """Check to see if ship was hit by a bullet""" collisions = pygame.sprite.spritecollide(self.ship, self.alienbullets, False) if collisions: self._ship_hit() collisions = pygame.sprite.groupcollide(self.bunkers, self.alienbullets, False, False) if collisions: for bunker in collisions: for bullet in collisions[bunker]: if bunker.validhit(bullet, True): bullet.kill() def _update_aliens(self): """ Check if the fleet is at an edge, then update the positions of all aliens in the fleet. """ self._check_fleet_edges() self.aliens.update() self.explosions.update() if self.ufo is not None: self.ufo.update() # Look for alien-ship collisions. if pygame.sprite.spritecollideany(self.ship, self.aliens): self._ship_hit() # Look for aliens hitting the bottom of the screen. self._check_aliens_bottom() # Check how many aliens are left remaining = len(self.aliens) speeds = [0.75, 0.5, 0.25] # As more aliens are killed, increase the speed of the music for index in range(len(speeds)): if remaining < int(self.settings.max_aliens * speeds[index])\ and self._soundmananger.getinstance().musicindex < index + 1: self._soundmananger.getinstance().increasemusicspeed() def _update_frames(self): for alien in self.aliens: alien.nextframe() def _update_explosion_frames(self): for explosion in self.explosions: explosion.nextframe() if explosion.finished: explosion.kill() def _check_aliens_bottom(self): """Check if any aliens have reached the bottom of the screen.""" screen_rect = self.screen.get_rect() for alien in self.aliens.sprites(): if alien.rect.bottom >= screen_rect.bottom: # Treat this the same as if the ship got hit. self._ship_hit() break """Also check for bunker collisions""" collisions = pygame.sprite.groupcollide(self.bunkers, self.aliens, False, False) if collisions: for bunker in collisions: for alien in collisions[bunker]: alien.kill() bunker.kill() break def _ship_explosion(self): for image in self.ship.explosion_frames: self.ship.setexplosionframe(image) self._update_screen() pygame.time.wait(175) self.ship.resetimage() self._update_screen() pygame.time.wait(500) def _ship_hit(self): """Respond to the ship being hit by an alien.""" thread = threading.Thread(target=self._ship_explosion, args=(), daemon=True) thread.start() # Threading the explosion function to allow exiting of the game # pygame.time.wait() locks the window, preventing exiting while thread.is_alive(): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_q or event.key == pygame.K_ESCAPE: pygame.quit() sys.exit() if self.stats.ships_left > 0: # Decrement ships_left, and update scoreboard. self.stats.ships_left -= 1 self.sb.prep_ships() # Get rid of any remaining aliens, bunkers, and all bullets self.aliens.empty() self.bullets.empty() self.bunkers.empty() self.alienbullets.empty() if self.ufo is not None: self.ufo.kill() if self._soundmananger.getinstance().getufosoundactive: self._soundmananger.getinstance().stopufosound() self.ufo = None # Create a new fleet and center the ship. self._create_fleet() self._create_bunker_wall() self.ship.center_ship() self._soundmananger.getinstance().newlevel() # Pause. sleep(0.5) # Game ending control goes here else: self.stats.game_active = False if self._soundmananger.getinstance().getmusicplaying(): self._soundmananger.getinstance().stopmusic() pygame.mouse.set_visible(True) if self.stats.checkfornewhighscore(): self._check_score_button(self.score_button.rect.center) def _create_fleet(self): """Create the fleet of aliens.""" # Create an alien and find the number of aliens in a row. # Spacing between each alien is equal to one alien width. alien = Alien(self, ['images/alien1frame1.png', 'images/alien1frame2.png'], 0) alien_width, alien_height = alien.rect.size available_space_x = self.settings.screen_width - (2 * alien_width) number_aliens_x = available_space_x // (2 * alien_width) # Determine the number of rows of aliens that fit on the screen. # ship_height = self.ship.rect.height # Available rows # available_space_y = (self.settings.screen_height - (5 * alien_height) - ship_height) # number_rows = available_space_y // (2 * alien_height) number_rows = self.settings.number_of_rows alienimages = [ ['images/alien1frame1.png', 'images/alien1frame2.png'], ['images/alien2frame1.png', 'images/alien2frame2.png'], ['images/alien3frame1.png', 'images/alien3frame2.png'] ] alienimageindex = 0 # Create the full fleet of aliens. for row_number in range(number_rows): if row_number % 2 == 0 and row_number is not 0: alienimageindex += 1 for alien_number in range(number_aliens_x): self._create_alien(alien_number, row_number, alienimages[alienimageindex], self.settings.score_values[alienimageindex], alien_number % 2) self.settings.max_aliens = len(self.aliens) def _create_alien(self, alien_number, row_number, images, score, offset): """Create an alien and place it in the row.""" alien = Alien(self, images, score, offset) alien_width, alien_height = alien.rect.size alien.x = alien_width + 2 * alien_width * alien_number alien.rect.x = alien.x alien.rect.y = alien.rect.height + 1.25 * alien.rect.height * row_number self.aliens.add(alien) def _create_ufo(self): if not self.stats.game_active: return if self.ufo is None and random.randint(0, 5) == 2: self.ufo = UFO(self, int(self.settings.score_values[2] * random.randint(3, 9) / 1.5)) self.ufo.rect.y = int(self.settings.screen_height * random.randint(15, 75) / 100) if not self._soundmananger.getinstance().getufosoundactive(): self._soundmananger.getinstance().playufosound() def _ufo_score_duration(self, duration): pygame.time.wait(duration) self.display_ufo_score = False def _create_bunker_wall(self): """Create the row of bunkers.""" # Create an bunker and find the number of bunkers in a row. # Spacing between each bunker is equal to one alien width. bunker = Bunker(self) bunker_width, bunker_height = bunker.rect.size available_space_x = self.settings.screen_width number_bunkers_x = (available_space_x // bunker_width) // 2 # Create the full wall of bunkers. for bunker_number in range(number_bunkers_x): self._create_bunker(bunker_number) def _create_bunker(self, bunker_number): """Create an bunker and place it in the row.""" bunker = Bunker(self) bunker_width, bunker_height = bunker.rect.size bunker.x = (bunker_width // 2) + 2 * bunker_width * bunker_number bunker.rect.x = bunker.x bunker.rect.y = int(self.settings.screen_height * 0.80) self.bunkers.add(bunker) def _check_fleet_edges(self): """Respond appropriately if any aliens have reached an edge.""" for alien in self.aliens.sprites(): if alien.check_edges(): self._change_fleet_direction() return for explosion in self.explosions.sprites(): if explosion.check_edges(): self._change_fleet_direction() return if self.ufo is not None: if self.ufo.check_edges(): self.ufo.kill() if self._soundmananger.getinstance().getufosoundactive: self._soundmananger.getinstance().stopufosound() self.ufo = None def _change_fleet_direction(self): """Drop the entire fleet and change the fleet's direction.""" # They do drop down for alien in self.aliens.sprites(): alien.rect.y += self.settings.fleet_drop_speed self.settings.fleet_direction *= -1 def _draw_main_menu(self): self.screen.fill(self.settings.bg_color) self.screen.blit(self.settings.screenbackground, self.settings.screenbackgroundrect) height = self.sb.show_main_menu() self.play_button.rect.bottom = self.play_button.rect.height + height + 75 self.score_button.rect.top = self.play_button.rect.bottom + 50 self.play_button.prep_msg() self.score_button.prep_msg() self.play_button.draw_button() self.score_button.draw_button() pygame.display.flip() def _update_screen(self): """Update images on the screen, and flip to the new screen.""" self.screen.fill(self.settings.bg_color) self.screen.blit(self.settings.screenbackground, self.settings.screenbackgroundrect) self.ship.blitme() if self.ufo is not None: self.ufo.blitme() for bullet in self.bullets.sprites(): bullet.draw_bullet() for bullet in self.alienbullets.sprites(): bullet.draw_bullet() # Draw the aliens self.aliens.draw(self.screen) # Draw the bunkers self.bunkers.draw(self.screen) # Draw the explosions self.explosions.draw(self.screen) # Draw the score information. self.sb.show_score() if self.display_ufo_score: self.screen.blit(self.ufo_score, self.ufo_rect) pygame.display.flip()
def denied(self): SoundManager.play(Trigger.DENIED)
class Game(object): def __init__(self, eventMgr): self.em = eventMgr self.em.register(self) pygame.init() self.game_over = False self.screen = pygame.display.set_mode((Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT)) self.view = pygame.Surface((Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT)) self.viewport = self.view.get_rect() pygame.display.set_caption("Game") self.sm = SoundManager("media/skeptic.mp3") try: self.world = World(self, eventMgr) self.world.loadLevel("levels/mappi.txt") except: pygame.quit() raise # continue catched exception self.em.tell("GameStart") def notify(self, event): if event.name == "Tick": if not self.game_over: self.screen.fill((0, 0, 0)) self.view.fill((0, 0, 0)) dt = event.time # deltatime # if dt != 0: # print "FPS:",1000/dt speed = 0 if self.world.player.has_pickup("no_hurry") else 1 speed += ( 15 if self.world.player.rect.top - self.viewport.centery < -int(0.3 * Settings.SCREEN_HEIGHT) else 0 ) center_y = self.viewport.centery - speed self.viewport.center = (400, center_y) # print self.viewport.center if self.viewport.center[ 1 ] < self.world.player.rect.top + self.world.player.rect.height - self.world.player.trampoline_height and self.world.player.has_pickup( "trampoline" ): self.world.player.jump() elif self.viewport.center[1] < self.world.player.rect.top - 300: self.game_over = True self.em.tell(PointEvent(int(self.world.player.score + abs(self.world.player.max_height * 0.1)))) return keys = pygame.key.get_pressed() if keys[pygame.K_w]: self.viewport.top -= 10 elif keys[pygame.K_s]: self.viewport.top += 10 if keys[pygame.K_d]: self.viewport.left += 4 elif keys[pygame.K_a]: self.viewport.left -= 4 # self.viewport # all the drawing stuff... self.world.update(dt) # The player is considered dead if the players y-coordinate is bigger # than the y-coordinate of the bottom of the view # if (self.world.player.rect.topleft[1] > self.viewport.bottomleft[1]): # self.endGame() self.screen.fill((0, 0, 0)) self.view.fill((0, 0, 0)) dt = event.time # deltatime # if dt != 0: # print "FPS:",1000/dt # self.viewport # all the drawing stuff... self.world.update(dt) self.sm.update(dt) font = pygame.font.Font(None, 25) text = font.render( "Score: " + str(int(self.world.player.score + abs(self.world.player.max_height * 0.1))), True, (255, 255, 255), ) self.screen.blit(text, (70, 0)) pygame.display.flip() elif event.name == "Destroy": pygame.quit() return True if event.name == "Point": self.sm.fadeout(3000) done = False scores = [] name = "" get_name = False try: f = open("scores", "r") for line in f: x = line.strip().split(",") scores.append((x[0], int(x[1]))) f.close() except IOError: pass scores.sort(key=itemgetter(1), reverse=True) if (len(scores) < 10) or (int(scores[9][1]) < int(event.points)): get_name = True while not done: for events in pygame.event.get(): if events.type == pygame.QUIT: done = True if events.type == pygame.KEYDOWN: if events.key == pygame.K_ESCAPE: done = True if get_name and 126 > events.key > 64: name += chr(events.key) if get_name and events.key == 32: name += " " if get_name and events.key == 8: name = name[0:-1] if get_name and events.key == 13: get_name = False try: f = open("scores", "a") f.write(name + "," + str(event.points) + "\n") f.close() except IOError: pass scores.append((name, event.points)) scores.sort(key=itemgetter(1), reverse=True) pygame.time.wait(1) self.screen.fill((0, 0, 0)) if get_name: font = pygame.font.Font(None, 50) font2 = pygame.font.Font(None, 100) text = font.render(name, True, (255, 255, 255)) text2 = font2.render("Game over", True, (255, 255, 255)) text3 = font.render("Please enter your name:", True, (255, 255, 255)) self.screen.blit(text, (20, 300)) self.screen.blit(text3, (20, 150)) self.screen.blit(text2, (20, 20)) else: font = pygame.font.Font(None, 100) font2 = pygame.font.Font(None, 50) text = font.render("High scores", True, (255, 255, 255)) self.screen.blit(text, (20, 20)) for i in range(len(scores)): if i >= 10: break text2 = font2.render(str(i + 1) + ". " + scores[i][0][0:20], True, (255, 255, 255)) text3 = font2.render(str(scores[i][1]), True, (255, 255, 255)) self.screen.blit(text2, (20, 100 + 50 * i)) self.screen.blit(text3, (600, 100 + 50 * i)) pygame.display.flip()
def __init__( self ): self.cfg = ConfigHandler( 'thm.cfg' ) self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = ( 0.0, 0.0 ) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler( 1, 2, callSpeshulEffect ) self.space.add_collision_handler( 2, 2, callSpeshulEffect ) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager( self ) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder={} self.curInputDict = {} self.playersGroup = None self.namedGroups = { 'playersGroup':self.playersGroup } self.lineVisualiser = LineVisualiser( self ) self.rerenderEverything = False self.soundManager = SoundManager( self ) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None
def __init__(self): self.cfg = ConfigHandler('thm.cfg') self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = (0.0, 0.0) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler(1, 2, callSpeshulEffect) self.space.add_collision_handler(2, 2, callSpeshulEffect) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager(self) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder = {} self.curInputDict = {} self.playersGroup = None self.namedGroups = {'playersGroup': self.playersGroup} self.lineVisualiser = LineVisualiser(self) self.rerenderEverything = False self.soundManager = SoundManager(self) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None
def switch_players(self, slot_id_1, slot_id_2): self.players[slot_id_1], self.players[slot_id_2] = self.players[slot_id_2], self.players[slot_id_1] for player_id in [slot_id_1, slot_id_2]: self.highlight_player(player_id) SoundManager.play(Trigger.PLAYERS_SWITCHED)
def __init__(self, **kwargs): super(MenuScreen, self).__init__(**kwargs) # initial fade in self.fadeopacity = 0.0 NetworkInfo.register(self.__update_network_info) SoundManager.play(Trigger.INTRO)
def handle_kickoff(self, say_player): if not GameData.is_match_finished(): delay = 1.0 Clock.schedule_once(self.__animate_kickoff, delay) if say_player: SoundManager.play(Trigger.GAME_START, self.players[GameData.get_kickoff_team() * 2])
class PlayState: """ The PlayState class. Maintains a list of all entity groups, can update them all, draw them all, return a list of all their sprites, and run the collision system.""" def __init__( self ): self.cfg = ConfigHandler( 'thm.cfg' ) self.cfg.readConfig() self.groups = [] self.floor = None self.space = pymunk.Space() self.space.gravity = ( 0.0, 0.0 ) self.space.damping = 0.0 #self.space.set_default_collision_handler() self.space.add_collision_handler( 1, 2, callSpeshulEffect ) self.space.add_collision_handler( 2, 2, callSpeshulEffect ) self.speshulCaller = callSpeshulEffect self.postStepQueue = [] self.gameLogicManager = ActualManager( self ) self.justEditing = False self.spaceGhost = None #If this is true, devtools will class update EVERYTHING. self.forceUpdateEverything = False self.boundaryBody = pymunk.Body() self.boundaries = [] #A list of int values that represent the index values of a #group in self.groups, each group is drawn in order of the # values in this list. Use addGroup() to add one, by default # it puts the group in the last index of self.drawOrder, # unless passed a index value. self.drawOrder = [] self.interweaveOrder={} self.curInputDict = {} self.playersGroup = None self.namedGroups = { 'playersGroup':self.playersGroup } self.lineVisualiser = LineVisualiser( self ) self.rerenderEverything = False self.soundManager = SoundManager( self ) self.hudList = [] self.fileName = "Untitled" self.amountOfEntsOnLoad = None self.hardBlockInput = False self.inputDictLog = [] #These to variables are the displacement from the state's (0,0) and the screen's (0,0), so they can be used for panning. self.panX, self.panY = 0, 0 self.limitX1, self.limitX2, self.limitY1, self.limitY2 = None, None, None, None #This is the idSource, I use it for give ids to Entitys. self.idSource = IdSource() self.isClient = False self.isHost = False self.networkRate = 20.0 self.networkTicker = 0 self.networkNode = None self.networkingStarted = False #This is set by the DevMenu init self.devMenuRef = None self.paused = False self.keyboardInputEnabled = False self.deleteLastChar = False self.checkFocus = False self.pausedByFocus = False #So this is quite an important boolean. #If this is true everything in the PlayState will be drawn in order of the bottom of it's bounding rect, which I will refer #to as 'the foot'. If the foot is higher up the screen, the item will be drawn sooner. #If this is False, everything will be drawn according to the drawOrder and interweaveOrder system. #DrawByFeet is more suitable for some topdown/isometric games. self.drawByFeet = False self.useSuggestedGravityEntityPhysics = False self.stateToSwap = None def initNetworking( self ): if not self.networkingStarted: #pygnetic.init(logging_lvl=logging.DEBUG) pygnetic.init(logging_lvl=logging.ERROR) self.networkingStarted = True registerMessages() def hostGame( self ): if self.isHost: del self.networkNode._server gc.collect() else: self.isHost = True self.initNetworking() self.networkNode = NetworkServer( self, "", int( self.cfg.getVal("port") ), networkingMode=1 ) self.addGroup( EntityGroup( 'networkPlayers' ), name='networkPlayers' ) print "Beginning hosting..." def connectToGame( self, addr, port ): if self.isClient: del self.networkNode._client gc.collect() else: self.isClient = True self.initNetworking() self.networkNode = NetworkClient( self, networkingMode=1 ) self.networkNode.connect( addr, port ) self.addGroup( EntityGroup( 'networkPlayers' ), name='networkPlayers' ) print "Connecting..." def addBoundary( self, point1, point2 ): newSeg = pymunk.Segment( self.boundaryBody, point1, point2, 1 ) self.boundaries.append( newSeg ) self.space.add( newSeg ) def removeBoundary( self, givenSeg ): self.boundaries.remove( givenSeg ) self.space.remove( givenSeg ) def swap( self, newState ): self.stateToSwap = newState def addInterweaveGroup( self, group, index ): if self.interweaveOrder.get( index, None ) is None: self.interweaveOrder[index] = [group] else: self.interweaveOrder[index].append( group ) def addGroup(self, group, indexValue=None, isPlayerGroupBool=False, name=None, interweaveWithFloor=False): """Add's an entity group to the PlayState. If indexValue specifies the draw-order, defaults to last. isPlayerGroupBool specifies if the group is a group of players (ie, a group that will be sent input dictionaries). If a "name" is given, set PlayState.name = group. interweaveWithFloor means that the entityGroup is drawn with the floor layers instead, drawn after the layer of it's index. Multiple entgroups can share a interweave number, and they'll be drawn according to order of their addition. an interweave index of 0 means it will be drawn AFTER layer 1, the first layer above the background floor""" group.playState = self self.groups.append( group ) if not interweaveWithFloor: newIndex = len( self.groups ) - 1 if indexValue is None: self.drawOrder.append( newIndex ) else: self.drawOrder.insert( indexValue, newIndex ) else: newIndex = len( self.floor.layers ) - 1 if indexValue is None: self.addInterweaveGroup( group, newIndex ) else: self.addInterweaveGroup( group, indexValue ) if isPlayerGroupBool: self.namedGroups['playersGroup'] = group self.playersGroup = group if name is not None: self.namedGroups[name] = group setattr( self, name, group ) def checkForFocus( self ): lostFocus = ( not pygame.mouse.get_focused() ) and self.checkFocus self.pausedByFocus = lostFocus def pause( self ): self.paused = True def unpause( self ): self.paused = False def togglePaused( self ): self.paused = not self.paused def processNetworkEvents( self, dt ): self.gameLogicManager.preNetworkTick( dt ) if self.isHost or self.isClient: if self.networkTicker >= int(60.0/self.networkRate): self.networkNode.update( dt ) self.networkTicker = -1 self.networkNode.updateTime( dt ) self.networkTicker += 1 self.gameLogicManager.postNetworkTick( dt ) def update( self, dt ): """A generic update function. Sends input dictionaries to playerGroups. Updates all the child groups, runs the collision system.""" self.floor.update( self.panX, self.panY ) self.checkForFocus() if self.paused or self.pausedByFocus: self.processNetworkEvents( dt ) return None #Game logic self.gameLogicManager.preTick( dt ) if not self.hardBlockInput: #I'm doing the same thing even if the host or client is the same, to force identical player behaviour for either. if self.isClient or self.isHost: self.inputDictLog.append( self.curInputDict ) if self.networkTicker >= int(60.0/self.networkRate): for eachDict in self.inputDictLog: if self.playersGroup is not None and len( eachDict ) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput( eachDict ) for eachElement in self.hudList: eachElement.sendInput( eachDict ) self.inputDictLog = [] if self.isClient: self.networkNode.sendInput( self.curInputDict ) else: if self.playersGroup is not None and len( self.curInputDict ) > 0: for eachPlayer in self.playersGroup.sprites(): eachPlayer.sendInput( self.curInputDict ) for eachElement in self.hudList: eachElement.sendInput( self.curInputDict ) self.curInputDict = {} self.space.step( 1.0/60.0 ) for eachTriplet in self.postStepQueue: eachTriplet[0]( eachTriplet[1], eachTriplet[2] ) self.postStepQueue = [] for eachGroup in self.groups: eachGroup.update( dt ) for eachElement in self.hudList: eachElement.update( dt ) self.soundManager.update( dt ) self.processNetworkEvents( dt ) self.gameLogicManager.postTick( dt ) def setPan( self, x, y ): screenW, screenH = getResolution() if self.limitX1 is not None: x = min( -self.limitX1, x ) if self.limitX2 is not None: x = max( -(self.limitX2-screenW), x ) if self.limitY1 is not None: y = min( -(self.limitY1), y ) if self.limitY2 is not None: y = max( -(self.limitY2-screenH), y ) self.panX, self.panY = x, y def sendInput( self, inputDict ): """Simply sets PlayState.curInputDict to a given input dictionary, for use in PlayState.update()""" self.curInputDict = inputDict def sprites( self ): """Returns a list of all the sprites in all the entity groups in the PlayState.""" sumList = [] for eachSpriteList in [ someGroup.sprites() for someGroup in self.groups ]: sumList.extend( eachSpriteList ) return sumList def draw( self, surface ): """Draw all the child entity groups in PlayState, returning changed area rects""" changeRects = [] changeRects.append( surface.blit( self.floor.layers[0].image, self.floor.layers[0].rect.topleft ) ) if not self.drawByFeet: for eachVal in self.drawOrder: changeRects.extend( self.groups[eachVal].draw( surface ) ) allInterweaveGroups = self.interweaveOrder.values() for eachVal in range( 1, len( self.floor.layers ) ): eachLayer = self.floor.layers[eachVal] changeRects.append( surface.blit( eachLayer.image, eachLayer.rect.topleft ) ) groupsToDraw = self.interweaveOrder.get( eachVal-1, None ) if groupsToDraw is not None: allInterweaveGroups.remove( groupsToDraw ) [ changeRects.extend( each.draw( surface ) ) for each in groupsToDraw ] #Draw anything left over for eachGroupSet in allInterweaveGroups: [ changeRects.extend( eachGroup.draw( surface ) ) for eachGroup in eachGroupSet ] else: yTuples = [] for eachSprite in self.sprites(): if eachSprite.flatInDrawByFeet: y = eachSprite.rect.top else: y = eachSprite.rect.bottom yTuples.append( (y, eachSprite) ) yTuples.extend( [ (each.rect.bottom, each) for each in self.floor.layers[1:] ] ) renderList = [ each[1] for each in sorted( yTuples, lambda x, y: cmp( x[0], y[0] ) ) ] #I probably shouldn't be doing this. tmpDrawGroup = pygame.sprite.LayeredDirty( self.floor.layers[0], renderList ) changeRects.extend( tmpDrawGroup.draw( surface ) ) tmpDrawGroup.empty() del tmpDrawGroup changeRects.extend( self.lineVisualiser.draw( surface, (self.panX, self.panY) ) ) if len( self.gameLogicManager.lasers ) > 0: pt1, pt2 = self.gameLogicManager.getCurAimLine() pygame.draw.line( surface, darkGreen, pt1, pt2 ) for eachShot in self.gameLogicManager.preparedShots: pygame.draw.line( surface, green, eachShot[1][0], eachShot[1][1] ) #for eachMissile in [ each for each in self.genericStuffGroup.sprites() if each.__class__.__name__ == "Missile" ]: #pygame.draw.line( surface, darkRed, eachMissile.getPosition(), eachMissile.startPos, 4 ) for eachElement in self.hudList: eachElement.draw( surface ) changeRects.extend( [ each.rect for each in self.hudList ] ) if self.rerenderEverything: w, h = surface.get_width(), surface.get_height() changeRects.extend( [ pygame.Rect( 0, 0, w, h ) ] ) self.rerenderEverything = False return changeRects # # # This function, __getitem__, takes a value, if that value is a string, it looks for a group in PlayState.groups that has that string as entityGroup.name. # If that value is an int, it returns the group at that index value in self.groups. # def __getitem__( self, value ): if type( value ) == str: for eachGroup in self.groups: if eachGroup.name == value: return eachGroup raise Exception("No group in PlayState by name: " + value) elif type( value ) == int: return self.groups[value] else: raise Exception("PlayState.__getitem__ only takes strs or ints, got: " + str(type( value )) )
def cancel_match(self): SoundManager.play(Trigger.MENU) self.manager.current = 'lounge'
def resume_match(self): SoundManager.play(Trigger.GAME_RESUME)
except ValueError, e: # player is not in any team yet self.players[self.current_player_slot] = player self.highlight_player(self.current_player_slot) SoundManager.play(Trigger.PLAYER_JOINED, player) else: # only switch position if new player is not already in current slot if idx_already_set != self.current_player_slot: # switch slots self.players[idx_already_set] = self.players[self.current_player_slot] self.players[self.current_player_slot] = player self.highlight_player(self.current_player_slot) # check if target slot was empty if self.players[idx_already_set] == {}: # player is moved to empty slot SoundManager.play(Trigger.PLAYER_MOVED) else: # player switches position with another player SoundManager.play(Trigger.PLAYERS_SWITCHED) self.highlight_player(idx_already_set) # advance to next player block self.current_player_slot = (self.current_player_slot + 1) % 4 def process_message(self, msg): if msg['trigger'] == 'rfid': self.__handle_rfid(msg['data']) else: self.denied() class STModalView(BoxLayout): title = StringProperty("")