def start(self): """ Start the game engine. """ lasttime = time() curtime = 0 frames = 0 # Start the main event loop while 1: # Process the internal event queue Event.handle_events() # Process the SDL event queue for event in SDL.event.get(): if event.type == SDL.QUIT: self.shutdown() elif event.type == SDL.VIDEORESIZE: self.resize(event.w, event.h) elif event.type == SDL.KEYDOWN: StateManager.current.key_pressed(event.key) self.queue_flip() elif event.type == SDL.KEYUP: StateManager.current.key_released(event.key) # Update and draw the current state StateManager.update() self.draw() frames += 1 curtime = time() if curtime - lasttime >= 1: Log.info("FPS: " + str(frames / (curtime - lasttime))) frames = 0 lasttime = curtime
def drawSprites(): #Sprites global car global track #Sprite display scaling global displaycale #### Display track #### pushMatrix() translate(width/2, height/2) rotate(radians(player.rotation-90.0)) translate(-width/2, -height/2) image(track, -(player.posx*displayscale)+(width/2), -(player.posy*displayscale)+(height/2), 1024*displayscale, 1024*displayscale) if (glv.renderTrackmap): image(trackmap, -(player.posx*displayscale)+(width/2), -(player.posy*displayscale)+(height/2), 1024*displayscale, 1024*displayscale) popMatrix() #### Display player car #### pushMatrix() translate(width/2, height/2) rotate(radians(-player.innerce)) translate(-width/2, -height/2) image(car, (width/2)-10*displayscale, (height/2)-22*displayscale, 21*displayscale, 45*displayscale) popMatrix() #### Render collision lines if enabled #### if (glv.renderCollisionLines): pushMatrix() translate(width/2, height/2) rotate(radians(player.rotation-90.0)) translate(-width/2, -height/2) sm.renderTestlines() popMatrix()
def drawSpritesNoScale(): #Sprites global car global track #### Display track #### pushMatrix() translate(width/2, height/2) rotate(radians(player.rotation-90.0)) translate(-width/2, -height/2) image(track, -player.posx+(width/2), -player.posy+(height/2)) if (glv.renderTrackmap): image(trackmap, -player.posx+(width/2), -player.posy+(height/2)) popMatrix() #### Display player car #### pushMatrix() translate(width/2, height/2) rotate(radians(-player.innerce)) translate(-width/2, -height/2) image(car, (width/2)-10, (height/2)-22) popMatrix() #### Render collision lines if enabled #### if (glv.renderCollisionLines): pushMatrix() translate(width/2, height/2) rotate(radians(player.rotation-90.0)) translate(-width/2, -height/2) sm.renderTestlinesNoScale() popMatrix()
def perform_action(action): if (action == 1): controls.turnLeft() if (action == 2): controls.turnRight() timer.run() player.updatePos() player.checkBounds() sm.calcTestpoints() sm.updateState()
def load_level(level): """ A convienience function that will change the game state to playing and load a specified level. @return: The level that was loaded. """ # Change the game state if we need to if StateManager.current == None or StateManager.current.name != "Playing": StateManager.push(StateManager.PlayingState()) # Load the level StateManager.current.load_level(level) return StateManager.current.level
def __init__(self, world, name, image, text): """Base class used to construct a game entity. Returns new GameEntity object with the specified variables world, name,image, text, location, destination, speed, brain and id, this is a super class and should ideally be used via inheritance world: holds a world object. For game entities this should ideally be the world game name: holds the name of the particular entity being constructed e.g. zombie image: holds the location of the image that will be used as the main image for whatever GameEntity is constructed. This image holder will also be used to store the image as a result of rotation for display start_image: holds the location of the image that will be used as the main image for whatever GameEntity is constructed. This one however will not be altered but used as a reference to reset the rotational image when a new rotation is required. text: holds the text that will be displayed in a textual entity; for example the TextBox Entity location: holds a default Vector of (0,0) that will be altered to set the location of the enity that is created destination: holds a default Vector of (0,0) that will be altered to set the destination location of the entity heading: holds a default Vector of (0,0) that will be altered to set the heading; vector between two points with no size. Can be seen as the direction last_heading: holds a default Vector of (0,0), this heading will typically be used to remember the last heading that was used for rotating an entity image, so that rotation does not get caught in an infinite loop speed: holds a number variable default 0. that will be altered to set the speed of the entity that is created brain: holds a StateManager object that is used to manage the states that the entity object will use id: holds the numerial id for the entity object that is being created """ self.world = world self.name = name self.image = image self.start_image = image self.text = text self.location = Vector(0,0) self.destination = Vector(0,0) self.heading = Vector(0,0) self.last_heading = Vector(0,0) self.speed = 0. self.brain = StateManager() self.id = 0
def onWordRecognised(self, *_args): """ This will be called each time a word is recognised. """ # Unsubscribe to the event when talking, # to avoid repetitions memory.unsubscribeToEvent("WordRecognized", "AudioRecognition") # We access to the word recognised in the memory word = memory.getData("WordRecognized") # Debug : Print the word recognised print("Mot :") print(word[0]) print("Indice de confiance :") print(word[1]) print # We acknoledge a word if the trust is high enough if (word[1] > 0.28): self.mot = word[0] #self.tts.say("Le mot reconnu est :"+self.mot) StateManager(self) # Subscribe again to the event memory.subscribeToEvent("WordRecognized", "AudioRecognition", "onWordRecognised")
def updateGame(debug): global base while True: Pygame.update() # Checks job list for available jobs and assigns them to workers. if Agents.jobList: for agent in agents: if agent.getRole( ) == "worker" and agent.getState() != "upgrading": agent.setJob(Agents.jobList[0]) Agents.removeFromJobList() agent.setState(StateManager.upgrading()) if not Agents.jobList: break # Executes the agents current state for agent in agents: agent.state.execute(agent) FogOfWar.updateFogOfWar(agents) Pygame.drawAgents(agents) # Checks if victory requirements have been met. if agents[0].base.getCoal() >= 200 and agents[0].base.getIron() >= 20: print("Victory!") return True if debug: infoPrints()
def draw(self): """ Clear the screen and draw the current state. """ global last_time global tdiff # Calculate the time between frames cur_time = time() tdiff = cur_time - last_time last_time = cur_time # Clear the frame and draw the current state glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT) glLoadIdentity() StateManager.draw() self.flip() sleep(0.001)
def main(): ray.init() smile = StateManager.Smile() logger.info("FSM created FiniteStateMachine") fsm = Machine( smile, states=StateManager.states, transitions=StateManager.transitions, send_event=True, # allows to pass event values to the FSM initial="start") runThreads(source=0, FiniteStateMachine=smile)
def ldTrack(): global selectedTrack global nTracks global track_sprites global trackmap_sprites global initial_posx global initial_posy global initial_dir global initial_velocity global initial_rotation if (selectedTrack >= nTracks): selectedTrack = 0 render.track = loadImage(track_sprites[selectedTrack]) render.trackmap = loadImage(trackmap_sprites[selectedTrack]) player.posx = initial_posx[selectedTrack] player.posy = initial_posy[selectedTrack] player.dir = initial_dir[selectedTrack] player.velocity = initial_velocity[selectedTrack] player.rotation = initial_rotation[selectedTrack] sm.init()
def __init__(self): self.objects = [] self.running = 1 self.checkArgs() self.config = init_config() init_pygame(self) init_opengl(self) if self.args['disableSound']: self.sound = None else: from sound import * self.sound = CSound(self, self.config.getint('Sound','Frequency'), True) self.player = Player(sound = self.sound) self.physics = Physics(self) self.octree = self.physics.octree self.graphics = Graphics(self) self.input = Input(self) self.objects.append(self.player) self.input_thread = InputThread(self.input) self.input_thread.start() self.networkThread = network.NetworkThread(self) self.process_manager = ProcessManager() self.state_manager = StateManager() self.trigger_manager = TriggerManager(self) self.menu = Menu(self) self.state_manager.push(self.quit, None) self.state_manager.push(self.menu.menu_is_open, None) self.state_manager.process(None) self.physics.updateObjects(self.objects) self.fpsTime = time.time() # TODO: Don't ask me, iam an alien self.trigger_manager.Ugly_Function_For_Loading_Main_Keytriggers() self.showPlayerList = False
def main(): pygame.init() pygame.mixer.init() display = Display(WIDTH, HEIGH) stateManager = StateManager(display) stateManager.pushState(MenuState()) lastTime = time.time() frameTimes = [1] while True: # FPS counter deltaTime = time.time() - lastTime lastTime = time.time() frameTimes.append(deltaTime) frameTimes = frameTimes[-20:] fps = len(frameTimes) / sum(frameTimes) textFps = fastCreate.makeText(str(int(fps)),display.font,(0,255,0),0,0) stateManager.handleKeyEvents() stateManager.update(deltaTime) stateManager.render() # Show FPS display.surface.blit(textFps[0],textFps[1]) pygame.display.update()
class GroundStation: #__instance = None # Create instances of our interfaces vulcan2 = Vulcan2() presstable = PressTable() # State of the GSC mgr = StateManager() # Make a singleton later '''def getInstance(): """ Static access method """ if GroundStation.__instance == None: GroundStation() return GroundStation.__instance def __init__(self): if Singleton.__instance != None: raise Exception("This class is a singleton") else: Singleton.__instance = self self.update()''' def start(self): # Start the COSMOS telemetry server #cosmos.connect() # Start threads for Vulcan2 and Pressure Table Data Acquisition, and # state manager checks try: self.vulcan2.vThread = threading.Thread( name='vulcan2', target=self.vulcan2.update()) self.vulcan2.vThread.start() self.presstable.pThread = threading.Thread( name='pressTable', target=self.presstable.update()) self.presstable.pThread.start() self.mgr.sThread = threading.Thread(name='state', target=self.mgr.run()) self.mgr.sTrhead.start() except: print("Threading Failure")
def post(self): StateManager.handleStates(self.request.body)
def __init__( self ): GameController.__init__( self , 'Towers Of Hanoi') self.StateMgr = StateManager.StateManager( self.Screen , self) self.HighScores = {}
#!/usr/bin/python # -*- coding: utf-8 -*- ''' This script starts the python broccoli interface and state manager to work with Bro on Alpha_GlobalKnowledge and Alpha_LocalKnowledge. ''' import StateManager from TestTopologies import initiateTopologyMasterthesis if __name__ == '__main__': StateManager.initializeStateManager(initiateTopologyMasterthesis, "Masterthesis") StateManager.runStateManagerMainLoop()
class CaveOfDanger: def __init__(self): self.objects = [] self.running = 1 self.checkArgs() self.config = init_config() init_pygame(self) init_opengl(self) if self.args['disableSound']: self.sound = None else: from sound import * self.sound = CSound(self, self.config.getint('Sound','Frequency'), True) self.player = Player(sound = self.sound) self.physics = Physics(self) self.octree = self.physics.octree self.graphics = Graphics(self) self.input = Input(self) self.objects.append(self.player) self.input_thread = InputThread(self.input) self.input_thread.start() self.networkThread = network.NetworkThread(self) self.process_manager = ProcessManager() self.state_manager = StateManager() self.trigger_manager = TriggerManager(self) self.menu = Menu(self) self.state_manager.push(self.quit, None) self.state_manager.push(self.menu.menu_is_open, None) self.state_manager.process(None) self.physics.updateObjects(self.objects) self.fpsTime = time.time() # TODO: Don't ask me, iam an alien self.trigger_manager.Ugly_Function_For_Loading_Main_Keytriggers() self.showPlayerList = False def checkArgs(self): self.args = {'disableWater': False, 'disableSound': False, 'host': None, 'port': 30000} if sys.platform == "win32": self.args['disableSound'] = True if len(sys.argv) > 1: for index, arg in enumerate(sys.argv): if arg == "--help" or arg == "-h": print "Arguments: \n"\ " --nowater Disable water\n"\ " --nosound Disable sound\n"\ " --host Connect to host\n"\ " --port Port (Default: 30000)\n" sys.exit(0) elif arg == "--nowater": self.args['disableWater'] = True elif arg == "--nosound": self.args['disableSound'] = True elif arg == "--host": if not len(sys.argv) > index + 1: print "No host specified for --host" continue self.args['host'] = sys.argv[index + 1] elif arg == "--port": if not len(sys.argv) > index + 1: print "No port specified for --port" continue self.args['port'] = int(sys.argv[index + 1]) def run(self): while self.running: self.state_manager.process(None) self.process_manager.process(None) #pygame.time.wait(60) del self.sound self.input.running = False self.networkThread.running = False #test_process() #test_states() def quit(self, caller, purpose): if purpose is "STOP_PURPOSE": print "quit stopping" self.running = 0 elif purpose is "INIT_PURPOSE": pass elif purpose is "FRAME_PURPOSE": self.running = 0 else: print "quit: no purpose" def runGame(self, caller, purpose): if purpose is "STOP_PURPOSE": print "game stopping" elif purpose is "INIT_PURPOSE": print "game starting" self.graphics.initGL() terrain = "data/model/terrain.obj" self.graphics.addSurface(0, terrain, "data/image/grass.jpg") """ self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player().data) self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player(position = (-10.0, 20.0, -20.0)).data) self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player(position = (-15.0, 20.0, -20.0)).data) self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player(position = (-20.0, 20.0, -20.0)).data) self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player(position = (-30.0, 20.0, -20.0)).data) self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player(position = (-35.0, 20.0, -20.0)).data) self.octree.insertNode(self.octree.root, 100.0, self.octree.root, Player(position = (-40.0, 20.0, -20.0)).data) """ self.graphics.loadStaticObject(0.0, 0.0, 0.0, "data/model/cave.obj", \ "data/image/img2.png") if self.args['host'] != None: try: self.networkThread.addr = \ (self.args['host'], self.args['port']) network.Connect(self.args['host'], self.args['port']) self.networkThread.start() except: traceback.print_exc() self.physics.lastTime = time.time() pygame.mouse.set_visible(0) pygame.event.set_grab(0) self.clock = pygame.time.Clock() elif purpose is "FRAME_PURPOSE": if sys.platform == "win32": self.input.handle_mouse() objects = self.physics.update() rel = self.input.yrot - self.player.rotated self.player.rotated += rel if not self.graphics.spectator: self.player.data.orientation = ( self.player.data.orientation[0], (self.player.data.orientation[1] \ - rel) % 360, self.player.data.orientation[2] ) self.networkThread.addNewObjects() if time.time() - self.fpsTime >= 1.0: self.fpsTime = time.time() self.graphics.printFPS() #self.physics.octree.checkCollision(self.octree.root, self.player.data.position) #self.physics.handleCollision() self.physics.updateObjects(objects) #self.sound.Update_Sound(objects) self.graphics.draw(objects) time_passed = self.clock.tick() time_passed_seconds = time_passed / 1000.0 distance_moved = time_passed_seconds * self.input.speed self.distance_moved = distance_moved # I pass the keys, it can figure out the time-triggers and position-triggers itself self.trigger_manager.Check_Triggers(self.input.keys)
def _FullPacketReceived(self, packet, connection): """Decides if the 'protocol', 'version', packet types of the client and the server are in agreement""" if isinstance(packet, Packet.Error): self._shutdown(self._connection, False) return if self._state == 0: if not isinstance(packet, Packet.HS_Version): if self._talk: print( "PACKET IS NOT THE TYPE WE WANT IT TO BE (HS_VERSION)") print(packet) self._shutdown(connection) return_packet = Packet.HS_Version(1.0) connection.Send(return_packet.wrap().encode()) if not packet.version == 1.0: if self._talk: print("Version out of range") print(packet) self._shutdown(connection) self._state = 1 elif self._state == 1: if not isinstance(packet, Packet.HS_Options): if self._talk: print( "PACKET IS NOT THE TYPE WE WANT IT TO BE (HS_OPTIONS)") print(packet) self._shutdown(connection) if not packet.protocol == "TCP": if self._talk: print("TRYING TO USE NON-TCP TRANSPORT, UNSUPPORTED") print(packet) self._shutdown(connection) self._their_options_packet = packet return_packet = Packet.HS_Options(minport=packet.minport, maxport=packet.maxport, portusage=packet.portusage, protocol="TCP", timeout=packet.timeout, payload=packet.payload, key=randint()) self._my_options_packet = return_packet connection.Send(return_packet.wrap().encode()) self._state = 2 elif self._state == 2: if not isinstance(packet, Packet.HS_Options): if self._talk: print( "PACKET IS NOT THE TYPE WE WANT IT TO BE (HS_OPTIONS)(3RD)" ) print(packet) self._shutdown(connection) if not packet.key == self._my_options_packet.key: if self._talk: print("3RD PACKET KEY IS INCORRECT") print(self._my_options_packet) print(packet) self._shutdown(connection) return_packet = self._their_options_packet connection.Send(return_packet.wrap().encode()) stateManager = StateManager.StateManager( self._my_options_packet, self._their_options_packet, connection, self._talk) connection.Dispatcher.setTarget( PacketTranslator.PacketTranslator(stateManager, self._talk))
#!/usr/bin/python # -*- coding: utf-8 -*- ''' This script starts the python broccoli interface and state manager to work with Bro on Alpha_GlobalKnowledge and Alpha_LocalKnowledge. ''' import StateManager from TestTopologies import initiateTopologyAlpha if __name__ == '__main__': StateManager.initializeStateManager(initiateTopologyAlpha, "Alpha") StateManager.runStateManagerMainLoop()
class GameEntity(object): def __init__(self, world, name, image, text): """Base class used to construct a game entity. Returns new GameEntity object with the specified variables world, name,image, text, location, destination, speed, brain and id, this is a super class and should ideally be used via inheritance world: holds a world object. For game entities this should ideally be the world game name: holds the name of the particular entity being constructed e.g. zombie image: holds the location of the image that will be used as the main image for whatever GameEntity is constructed. This image holder will also be used to store the image as a result of rotation for display start_image: holds the location of the image that will be used as the main image for whatever GameEntity is constructed. This one however will not be altered but used as a reference to reset the rotational image when a new rotation is required. text: holds the text that will be displayed in a textual entity; for example the TextBox Entity location: holds a default Vector of (0,0) that will be altered to set the location of the enity that is created destination: holds a default Vector of (0,0) that will be altered to set the destination location of the entity heading: holds a default Vector of (0,0) that will be altered to set the heading; vector between two points with no size. Can be seen as the direction last_heading: holds a default Vector of (0,0), this heading will typically be used to remember the last heading that was used for rotating an entity image, so that rotation does not get caught in an infinite loop speed: holds a number variable default 0. that will be altered to set the speed of the entity that is created brain: holds a StateManager object that is used to manage the states that the entity object will use id: holds the numerial id for the entity object that is being created """ self.world = world self.name = name self.image = image self.start_image = image self.text = text self.location = Vector(0,0) self.destination = Vector(0,0) self.heading = Vector(0,0) self.last_heading = Vector(0,0) self.speed = 0. self.brain = StateManager() self.id = 0 def render(self, surface): """Function to render the entity image to the screen Blit in this particular function places the sepecified image so that it its central point coorespondes to the location specified w,h: holds the width and height of the image used as the visual representation of the game entity new_image_vector: A vector that holds the central point of an image position: holds the value that represents the center of the image at a specified location """ if self.speed != 0: self.rotate_image() w, h = self.image.get_size() w = w/2 h = h/2 new_image_vector = Vector(w, h) position = (self.location - new_image_vector) surface.blit(self.image, (position.get_x(), position.get_y())) def renderText(self, surface): """Function to render the entity text to the screen. Blit in this particular function places the specified text so that it appears in the center of the world it is created for font: holds a new font object, usually using a filename and the size of the font required Font(filename, size) lines: holds the separate lines of the text box so that they can be rendered. A new line is represented by a return character in the StartUpText(textBox) Code center: holds the location of the textbox object, and renders text in relation to this variable antialias: Boolean with value of 1, to ensure that when the font is rendered on screen all of the characters have smooth edges black: holds RGB value for the colour black, used later to set the text colour to black text: draws text on to a new surface. in this case it takes the line of text to be displayed, whether or not the charaters need antialising and what colour the characters should be text_pos: used to store the position of where the text will be rendered center: used in conjunction with self.location and text_pos to calculate the position of where the text will be rendered and then passes the value to the text_pos so that the text can be rendered height: simply the height of the font being used. Used to space one line of text from another """ font = pygame.font.Font(None, font_size) lines = self.text.strip().splitlines() center = (self.location.get_x(), self.location.get_y()) antialias = 1 red = 255,0,0 for line in lines: text = font.render(line.strip(), antialias, red) text_pos = text.get_rect() center_image_x = text_pos.width/2 center_image_y = text_pos.height/2 w, h = center center = ((w - center_image_x),(h - center_image_y)) text_pos = center height = font.get_linesize() surface.blit(text, text_pos) new_y = self.location.get_y() + height center = (self.location.get_x(), new_y) pygame.display.flip() def process(self, time_passed): """Function that plots a new course. Function that determines whether or not the entity can move, if the enity can move then a new course is plotted based on its current location, and its destination vec_to_destination: holds a vector object that determines how to get from the current location to a destination location e.g. A (1,1) B(10,10) vec_to_des(9,9) distance_to_destination: holds the distance between two points. Should be a numeric value heading: holds the heading/direction that leads to the destination, Created by normalising the vec_to_destination. vect_to_destination / magnitude, giving it a magnitude of 1, which provides a heading travel_speed: holds the speed the entity should travel based on its given speed and the amount of time that has passed position: holds the current position of the entity based on its heading and its travel speed. """ self.brain.think() if self.speed > 0 and self.location != self.destination: vec_to_destination = self.destination - self.location distance_to_destination = vec_to_destination.get_magnitude() self.heading = vec_to_destination self.heading.normalise() travel_speed = min(distance_to_destination, time_passed * self.speed) position = self.heading * travel_speed self.location += position def rotate_image(self): """This function is used to rotate the entity image depending on its heading. """ if self.heading.get_x() == 0 and self.heading.get_y() == 0: #or self.heading.compare_to(self.last_heading) == True: self.heading = self.last_heading if self.heading.get_x() >=0 and self.heading.get_y() <=0: value = math.degrees(math.acos(self.heading.get_x())) self.image = self.start_image self.image = pygame.transform.rotate(self.image, value) self.last_heading = self.heading return elif self.heading.get_x() <=0 and self.heading.get_y() <=0: value = math.degrees(math.acos(self.heading.get_x())) self.image = self.start_image self.image = pygame.transform.rotate(self.image, value) self.last_heading = self.heading return elif self.heading.get_x() <=0 and self.heading.get_y() >=0 : value = 180 + math.degrees(math.asin(self.heading.get_y())) self.image = self.start_image self.image = pygame.transform.rotate(self.image, value) self.last_heading = self.heading return elif self.heading.get_x() >=0 and self.heading.get_y() >=0: value = 360 - math.degrees(math.asin(self.heading.get_y())) self.image = self.start_image self.image = pygame.transform.rotate(self.image, value) self.last_heading = self.heading return def handle_click(self, event): return
if P == "Player 1": init_player = Player.PLAYER_1 elif P == "Player 2": init_player = Player.PLAYER_2 elif P == "mix": init_player = random.choice([Player.PLAYER_1, Player.PLAYER_2]) else: raise Exception("Invalid Player Choice") wins = 0 losses = 0 winrate = [] policy = Policy(init_player, c=c) stateman = StateManager() game = stateman.generate_initial_state([N, K], player=init_player) for i in range(G): mcts = MCTS(statemanager=stateman, initial_state=game, policy=policy, default_policy=policy, M=M) winner = play_game(mcts, init_player) # mcts.tree.print_entire_tree() if winner == init_player: wins += 1 else: