def main(): gfx = Video() inp = Input() gui = GUI() # Initialize try: gfx.initialize() inp.initialize() gui.initialize() except InitializationError as error: print(error) return 1 # Setup the interface gui.setupInterface() # Main Loop gfx.enterMainLoop() # Done # - We will never actually get here. gfx.shutdown() return 0
def __init__(self): """ Class used to initialize the different arrays Size of arrays depends on the type of mesh Variables: x : variable containing the x position of the nodes y : variable containing the y position of the nodes dom_size : number of nodes in the domain nodes : |id of node|y position of node|x position of node| neig : |id of node|neighbor 1|neighbor 2| ... in neig : -1 = no more neighbors, -2 = wall, -3 = symetry """ Input.__init__(self) self.x = np.linspace(0, self.Lx / 2, self.Nptsx) self.y = np.linspace(self.Lx / 2, self.Ly - self.Lx / 2, self.Nptsy) if (self.mesh_type == 'cart'): self.dom_size = self.Nptsx * self.Nptsy self.nodes = np.zeros((self.dom_size, 3)) self.neig = np.zeros((self.dom_size, 6)) else: self.dom_size = self.Nptsx * self.Nptsy + 2 * (self.Nptsx - 1) * self.ntheta self.nodes = np.zeros((self.dom_size, 3)) self.neig = np.zeros((self.dom_size, 5 + self.ntheta))
def main(): screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("Engine RPG") clock = pygame.time.Clock() #rejilla = load_image('resources/graphics/rejilla.png', True) map_loaded = Map("pruebas.tmx") heroe = Actor(map_loaded) camara = Camera(map_loaded, heroe) inp = Input() while True: time = clock.tick(40) inp.update() salir(inp.get_key_list()) id = heroe.mover(map_loaded, inp) heroe.update(id) camara.update(screen, map_loaded, heroe) camara.show_fps(screen, clock.get_fps()) #screen.blit(rejilla, (0, 0)) pygame.display.flip() return 0
def test_compareresults(self): # os.remove("Output1.txt") keyWordList = [] keyWord = "science" filePath = os.path.join(dirPath, "testcases/Test3/ListOfFiles.in") filePathTitle = os.path.join(dirPath, "testcases/Test3") outputTestPath = os.path.join(dirPath, "testcases/Test3/Output3.txt") flag = False # os.remove("Output1.txt") for i in range(2): if len(keyWordList) == 0: keyWordList.append(keyWord) self.input = Input(filePath, keyWordList, filePathTitle) else: keyWord = "Computer" if keyWord not in keyWordList: keyWordList.append(keyWord) flag = True else: flag = False # keyWordList.append(keyWord) if len(keyWordList) > 1: with open(outputPath, "w") as file: file.close() # self.input = Input(filePath, keyWordList, filePathTitle) if len(keyWordList) > 1 and flag == True: self.input = Input(filePath, keyWordList, filePathTitle) self.assertTrue(filecmp.cmp(outputPath, outputTestPath, shallow=False))
def __init__(self): self.running = True self.UC = Udp_communication(socket, pickle, self.server_ip, self.server_port) self.state = Start(self.UC, bge, ras) #THIS JUST FORWARDS TO LOBBY, UPDATE IT. self.input = Input(bge)
def read_input(self): joystick_input = Input() MULTIPLIER = 1 / 511.5 while True: output = joystick_input.read() x1 = int(output[0]) y1 = int(output[1]) b1 = bool(output[2]) # joystick 2 x2 = int(output[3]) y2 = int(output[4]) b2 = bool(output[5]) x2_float = MULTIPLIER * x1 - 1 y2_float = -(MULTIPLIER * y1 - 1) x1_float = MULTIPLIER * x2 - 1 y1_float = -(MULTIPLIER * y2 - 1) if self.init: # self.joy_display[0].set_pos_inner(x1_float, y1_float) # self.joy_display[0].click = b1 # self.joy_display[1].set_pos_inner(x2_float, y2_float) # self.joy_display[1].click = b2 self.lbl_joy1.setText("Joy1:\t\tX: " + str(x1_float)[:5] + ", Y: " + str(y1_float)[:5]) # time.sleep(0.5) self.lbl_joy2.setText("Joy2:\t\tX: " + str(x2_float)[:5] + ", Y: " + str(y2_float)[:5]) time.sleep(0.5)
def _test(): d = { 'type': 'REST', 'name': 'api_input_test', # I just need it to be unique 'id': 'page', 'location' : { 'url': lambda v: 'https://reqres.in/api/users?page={}'.format(v.get('page')), 'errors' : { 200: "OK", 403: "Bad request params", 404: "File not found... ?", 500: "Permanent fail", }, }, 'data': { 'REMAP': { 'reqres_page' : "page", 'reqres_count': "per_page", 'reqres_total': "total", 'reqres_pages': "total_pages", 'reqres_ids' : ('data', 0, { 'id' : 'id', 'name': lambda v: "{} {}".format(v.get('first_name'), v.get('last_name')), 'avatar': 'avatar', }), }, }, } urlin = Input(**d) rv = urlin.get(1) return search(('reqres_ids', 'name'), rv) == "George Bluth"
def __init__(self): print(protologue) self.inp = Input() self.upd = Update() self.world = World(3,4) self.player1 = Player(self.world) self.out = Output()
def from_json(self, json): required = ['inputs', 'outputs', 'duration', 'timestamp'] if not all(k in json for k in required): logging.warning(f'value missing in {required}') return False if not isinstance(json['inputs'], list) or not isinstance(json['outputs'], list) \ or not isinstance(json['timestamp'], float): logging.warning("inputs and outputs should be both type<list> and timestamp should be type<float>") return False for input in json['inputs']: # print(json['inputs']) i = Input() if not i.from_json(input): return False self.add_input(i) for output in json['outputs']: o = Output() if not o.from_json(output): return False self.add_output(o) if not self._duration.from_json(json['duration']): return False self._timestamp = json['timestamp'] return True
def __init__(self): self.screen = pygame.display.get_surface() GLOBALS.UI = UserInterface() GLOBALS.game_running = False GLOBALS.tile_map = TileMap() GLOBALS.tile_map.map_layer.zoom = 2 # pyscroll supports layered rendering. our map has 3 'under' layers # layers begin with 0, so the layers are 0, 1, and 2. # since we want the sprite to be on top of layer 1, we set the default # layer for sprites as 2 self.group = PyscrollGroup(map_layer=GLOBALS.tile_map.map_layer, default_layer=2) GLOBALS.hero = Hero() GLOBALS.hero.position = GLOBALS.tile_map.map_layer.map_rect.center for tree in GLOBALS.trees: self.group.add(tree) for ground in GLOBALS.ground: self.group.add(ground) self.group.add(GLOBALS.hero) # add player last! self.input = Input()
def replace_matching_key(word): parsed_word = "" diagonal = re.match( "[UDBFudbf][UDBFudbf]", word) # this regex needs more tweaking inputs like ff will get ignored if diagonal: for key, value in Input.items(): while does_key_has_match(key, diagonal.string): result = value for k in key: word.replace(k, "", 1) parsed_word += result result = "" break return parsed_word for letter in word: for key, value in Input.items(): while does_key_has_match(key, letter): result = value for k in key: word = word.replace(k, "", 1) parsed_word += result result = "" break return parsed_word
def train(config): """Prepare input data(train, dev), model and fit """ # build input train and dev data train_file = 'data/train.txt' dev_file = 'data/dev.txt' '''for KOR train_file = 'data/kor.train.txt' dev_file = 'data/kor.dev.txt' ''' '''for CRZ train_file = 'data/cruise.train.txt.in' dev_file = 'data/cruise.dev.txt.in' ''' train_data = Input(train_file, config, build_output=True, do_shuffle=True, reuse=False) dev_data = Input(dev_file, config, build_output=True, reuse=False) tf.logging.debug('loading input data ... done') config.update(train_data) tf.logging.debug('config.num_train_steps = %s' % config.num_train_steps) tf.logging.debug('config.num_warmup_epoch = %s' % config.num_warmup_epoch) tf.logging.debug('config.num_warmup_steps = %s' % config.num_warmup_steps) # create model and compile model = Model(config) model.compile() # do actual training fit(model, train_data, dev_data)
def __init__(self, game): GameState.__init__(self, game) self.input_map = { Input(key=pg.K_ESCAPE): lambda _: self.return_to_menu(), Input(key=pg.K_RETURN): lambda _: self._submit() } self.ip_textentry = UI.TextEntry(pos=(c.screen_size[0] // 2 - 100, c.screen_size[1] // 2), type='ip', font=fonts.main_menu_font_med, label='IP Address', default_text='localhost') self.port_textentry = UI.TextEntry(pos=(c.screen_size[0] // 2 - 100, c.screen_size[1] // 2 + 100), type='port', font=fonts.main_menu_font_med, label='Port', default_text='4141') self.connect_button = UI.Button(pos=(c.screen_size[0] // 2 - 100, c.screen_size[1] // 2 + 200), font=fonts.main_menu_font_med, text='Connect') self.ui_container.add_element(self.ip_textentry) self.ui_container.add_element(self.port_textentry) self.ui_container.add_element(self.connect_button) self.sel = None
def __init__(self, args): """ BoomBoomClient constructor. @param host: Server hostname. @type host: C{str} @param display_port: Server port for "display"/"view" connection. @type display_port: C{int} @param input_port: Server port for "input" connection. @type input_port: C{int} @param verbose: Verbose mode flag. @type verbose: C{bool} @param debug: Debug mode flag. @type debug: C{bool} @param max_fps: Maximal number of frames per second, for optimization. @type max_fps: C{int} """ args["protocol"] = protocol.loadProtocol("protocol.xml") args["features"] = ["game"] # Constant features Happyboom.__init__(self, args) EventListener.__init__(self, prefix="evt_") self.display = Display(args) self.input = Input(args) self.__verbose = args.get("verbose", False) self.registerEvent("happyboom") self.registerEvent("game")
def main(): input = Input() trainX, trainY, testX, testY = input.init() trainNum = trainX.shape[0] testNum = testX.shape[0] T = 200 clfs = list() for i in range(T): print('i = ', i) partX, partY = bootstrap(trainX, trainY) clf = tree.DecisionTreeClassifier(min_samples_split=3, max_features=3) clf = clf.fit(partX, partY) clfs.append(clf) testPredict = np.zeros((T, testNum)) for i in range(T): testPredict[i, :] = clfs[i].predict(testX) aveSum, result = vote(testPredict, T, testNum) correct = compare(result, testY, testNum) print('test correct num = ', correct, ', ratio = ', correct / 16281) auc = roc_auc_score(testY, aveSum) print('auc = ', auc)
def __init__(self, screen, start_state=None, debug=False): self.screen = screen self.card_pool = CardPool() goblin_card_prototype = CreatureCard(name='Goblin', cost=2, base_power=3, max_health=2, visibility=[1]) elf_card_prototype = CreatureCard(name='Elf', cost=1, base_power=2, max_health=1, visibility=[1,0,0,0]) scout_card_prototype = CreatureCard(name='Scout', cost=1, base_power=1, max_health=1, visibility=[3,0,0,0]) drone_card_prototype = BuilderCard(name='Drone', cost=1, base_power=1, max_health=1, visibility=[1]) blacksmith_card_prototype = BuildingCard(name='Blacksmith', cost=1, max_health=4, visibility=[0]) satellite_card_prototype = BuildingCard(name='Satellite', cost=1, max_health=3, visibility=[0], default_action='SCN', active_actions={'SCN': lambda card: ScanAction}) tower_card_prototype = BuildingCard(name='Tower', cost=2, max_health=4, visibility=[3,0,0,0]) self.card_pool.add_card(goblin_card_prototype) self.card_pool.add_card(elf_card_prototype) self.card_pool.add_card(scout_card_prototype) self.card_pool.add_card(drone_card_prototype) self.card_pool.add_card(blacksmith_card_prototype) self.card_pool.add_card(satellite_card_prototype) self.card_pool.add_card(tower_card_prototype) self.network_data_queue = [] self.connection_label = UI.Label( pos=(0,0), font=fonts.main_menu_font_small, text='', text_color=c.green, align=('left','up')) self.chat_window = UI.ChatWindow( name_font=fonts.chat_name_font, message_font=fonts.chat_message_font, name_width=100, message_width=300, log_height=150) self.ui_group = None self.ui_container = UI.Container() self.ui_container.add_element(self.connection_label) #self.ui_container.add_element(self.chat_window) self.input_map = { Input(key='any'): lambda key, mod, unicode_key: self.any_key_pressed(key=key, mod=mod, unicode_key=unicode_key), Input(mouse_button=1): lambda mouse_pos: self.left_mouse_pressed(mouse_pos), Input(mouse_button=1, type='release'): lambda mouse_pos: self.left_mouse_released(mouse_pos) } self._state = None self.state = start_state(self) self.selector = None self.socket = None self.connected_to_address = None self.connection_role = None self._connected = False self._accepting_connections = False if debug is True: d.debugger = d.DebugUI(game=self, active=True)
def __init__(self, port): self.running = False self.pid = 0 self.pids = [] self.nbPlayer = 0 self.players = {} self.entities = {} self.moves = [] self.shoot = False self.shoots = [] self.deads = [] self.killed = [] self.input = Input() self.graphics = Graphics() self.velocity = Constant.VELOCITY self.id = 0 self.port = port self.players_socket = {} self.players_socket_awaiting = {} self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.socket.bind(('', self.port)) self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) self.socket.listen(5)
class Weapon(Emitter, Inputable): def __init__(self, level, **kwargs): super().__init__(**kwargs) self._level = level self._part = None self._s = Surface((20, 10)) self._s.fill((255, 0, 0)) self._input = Input(inputStream=self.getInputStream()) self._input.set(pygame.KEYDOWN, self.createNew, pygame.K_f) def createNew(self): x, y = self._offsetFunc() self._part = Particle((self._anchor.x + x, self._anchor.y + y, 20, 10), (10, 0), self._s, self._level, Behaviors.killAt(150, 150), Behaviors.moveAt(self._anchor.getIntDir() * 10, 0), Behaviors.killOnCollision(exceptions=(self._anchor.getId(),)), Behaviors.cleanupCollision(), altname="bullet") if x < 0: self._part.x -= self._part.w self._part.move.setSpeed(x=self._part.move.getTopSpeed(x=True)) def _emit(self): if self._part: self._children.append(self._part) self._part = None def tick(self): self._input() super().tick()
def __init__(self, level, speed, tileset, **kwargs): super().__init__(dirRule=lambda: { -1: Direction.Left, 0: None, 1: Direction.Right }[self.move.getDir(x=True)], **kwargs) self.collision = Collision(self, level) self.move = Move(self, speed, collision=self.collision) self._gravity = GravityLine(self, 2, h=level.map.h // 2) self.jumping = Jumping(self.move, self._gravity, 2) self._input = Input(inputStream=self.getInputStream()) self.applyInputSettings() self._damageTimer = MinTimeEventStream(duration=2) self._damageTimer.subscribe("self", self._takeDmg, autoInit=False) def _isMoving(): return self.move.getSpeed(x=True) != 0 def _hDir(): return self.move.getDir(x=True) def _vDir(): return {False: -1, True: 1}[self._gravity.positiveDir()] image = Files.loadImage(tileset) self._display = Display(image, self, Animation(image, 11, _isMoving, _hDir, _vDir), True) self._weapon = Weapon(level, anchor=self, offsetFunc=lambda: ((5 * self.getIntDir()), 0), inputStream=self.getInputStream())
def __init__(self, name, inputs, id=None, cache=None, **kwargs): # we can't immediately resolve inputs. Process args when requested. self.name = name if self.name in Doc._all: raise Exception("Doc: name collision: {}".format(self.name)) self.id_name = id try: self.cache = Input(name=self.name, id=self.id_name, ** cache) if cache else None except NotFound: logger.warning("Unable to load cache for {}".format(self.name)) self.cache = None self._query_config = kwargs.get('query') self._input_config = inputs try: # This attempts to build the inputs. # Hopefully any errors will be found now while the file context exists. self.inputs except NotFound: # our inputs are merely named (not defined...yet). As more plugins are built this should resolve. pass self.query_count = 0 self.cache_hits = 0 self.cache_misses = 0 # Api tracks all instances for 'from_url' Doc._all[self.name] = self
class App(object): def __init__(self): self.config = IniParser() self._lastTick = 0 self.deltaTime = 0 try: self.config.read(open('config.cfg')) except: self.config.data['DISPLAY'] = { 'fullscreen': 'false', 'nativemode': 'false', 'opengl': 'false' } self.config.data['PATHS'] = { 'gamelist': './gamelist.csv', 'favorites': './fav.csv', 'sdcard': '.' } self.config.write(open('config.cfg', 'w')) pygame.init() self.input = Input() self.game = Game(self) #end of init def run(self): self.game.start() # start game self.game.active = True self._lastTick = pygame.time.get_ticks() while 1: # main game loop # deltaTime in seconds. t = pygame.time.get_ticks() self.deltaTime = (t - self._lastTick) / 1000.0 self._lastTick = t for event in pygame.event.get(): self.input.collectEvents(event) if event.type == pygame.QUIT: self.game.active = False sys.exit(0) self.game.update(self.deltaTime) self.game.render() #end of run #end of App
def __init__(self): self.grid_size = 100 self.board = [[0 for i in range(self.grid_size)] for j in range(self.grid_size)] self.row_width = 7 self.row_height = 3 self.num_colors = { 0: "white", 2: "red", 4: "yellow", 8: "green", 16: "blue", 32: "magenta", 64: "cyan", 128: "white", 256: "red", 512: "yellow", 1024: "green", 2048: "blue", 4096: "magenta", 8192: "cyan", } self.num_attrs = { 0: ["concealed"], 2: [], 4: [], 8: [], 16: [], 32: [], 64: [], 128: ["bold"], 256: ["bold"], 512: ["bold"], 1024: ["bold"], 2048: ["bold"], 4096: ["bold"], 8192: ["bold"], } self.directions = { "w": 1, "a": 4, "s": 3, "d": 2, } #bind keys self.input = Input(self.keyboard_listen) self.input.bind("w") self.input.bind("a") self.input.bind("s") self.input.bind("d") # start the game self.generate_tile() self.generate_tile() self.input.listen()
def __init__(self) -> None: self.input1 = Input(Device(config.device1)) self.input2 = Input(Device(config.device2)) self.position = 0 self.min_position = 0 self.max_position = 3 self.entered = False
def pacman_die(self): if self.scores.lives >= 1: self.scores.lives -= 1 if self.scores.lives: Music.play('go') self.units.reset() Input.reset() else: self.game_over()
def next_level(self): # type: () -> None """Switch to next level""" self.scores.level += 1 Input.reset() self.field = Field(str(self.scores.level) + '_lvl.txt') self.units.add_pacman(self.field.get_pacman_spawn()) self.units.add_ghosts(self.field.get_ghosts_spawn()) Music.play('bg', .1)
def initGameObjects(self): self.prevGameState = self.gameState self.inp = Input() self.gameBoard = GameBoard(self) self.shipMan = ShipManager(self.screen, GameBoard.BOTTOM) self.hitMan = HitManager(self.screen) self.opponent = Opponent(self.screen, OpponentType.AI) self.helpergui = Helpergui(self) self.sound = Sound(self.screen)
def __init__(self, pyray, font, config): self.pyray = pyray self.font = font self.config = config self.input = Input(self.pyray, self.font) self.device = DeviceIO() self.race_type = None # The config object passed in was modified by the user within the configuration menu self.config_updated = False self.race_timeout_updated = False # Initialize attributes used to select the number of lanes self.num_lanes_selected = False self.num_lanes_pos = False # Initialize attributes used to set servo limits self.servo_down_value_updated = False self.servo_up_value_updated = False self.cursor_pos = MenuState.SINGLE_TRACK # Start at the top of the main menu self.current_func = self.__top_menu # Dispaly loop calls __top_menu function self.config_window_top = MenuState.TRACK_NAME # Initial config menu window top self.config_window_bottom = MenuState.TRACK_NAME # Initial config menu window bottom self.config_menu_pos = self.config_window_top # Initial window position for config menu self.config_menu_first = MenuState.TRACK_NAME # Top of config menu, up wraps self.config_menu_last = MenuState.RESET # Bottom of config menu, down wraps self.last_cursor_pos = MenuState.RESET self.__init_function_pointers() # Initialize attributes used for selecting car images self.car_icons_loaded = False self.car_icon_index = 0 self.car_textures = [] self.car_icon_selected = None background_image = self.pyray.load_image("images/background.png") self.background_texture = self.pyray.load_texture_from_image( background_image) self.pyray.unload_image(background_image) single_track_image = self.pyray.load_image("images/Single-Track.png") self.single_track_texture = self.pyray.load_texture_from_image( single_track_image) self.pyray.unload_image(single_track_image) multi_track_image = self.pyray.load_image("images/Multi-Track.png") self.multi_track_texture = self.pyray.load_texture_from_image( multi_track_image) self.pyray.unload_image(multi_track_image) configure_image = self.pyray.load_image("images/Configure.png") self.configure_texture = self.pyray.load_texture_from_image( configure_image) self.pyray.unload_image(configure_image)
class Game(object): def __init__(self): pygame.mixer.pre_init(44100, 16, 2, 4096) # setup mixer to avoid sound lag pygame.init() pygame.display.set_caption("lakeception") self.world = World("Test World", (100,100), debug=False) # resolution, viewport self.screen = Screen(self.world, (800, 475), (25, 11)) self.screen = Screen(self.world, (800, 475), (99, 99)) # debug res self.input = Input(self) self.fps = 60 self.clock = pygame.time.Clock() self.ANIMATE = pygame.USEREVENT+0 self.animationRate = 1 * 1000 # Temporarily (?) disabled animations, because moving + animating was # an INTENSE visual experience # pygame.time.set_timer(self.ANIMATE, self.animationRate) self.updated = True self.quitting = False self.muted = False self.inspecting = False self.editing = False pygame.mixer.init() # From https://www.freesound.org/people/juskiddink/sounds/60507/ # albeit a bit mixed to allow for looping tracks = [] tracks.append(pygame.mixer.Sound(os.path.join(sys.path[0],'60507__juskiddink__waves2.ogg'))) tracks.append(pygame.mixer.Sound(os.path.join(sys.path[0],'sea-space.ogg'))) # Play & loop crashing waves in the background # Set the volume to an unobtrusive level tracks[0].set_volume(0.1) tracks[0].play(-1) # Play the song at a slightly higher volume # tracks[1].set_volume(0.4) # tracks[1].play() def tick(self): for event in pygame.event.get(): if event.type == pygame.KEYDOWN: self.input.handleKey(event) elif event.type == self.ANIMATE: self.screen.draw() self.updated = False elif event.type == pygame.QUIT: self.quitting = True if self.updated: self.screen.draw(self.inspecting, self.editing) self.updated = False timeDelta = self.clock.tick(self.fps)
def iniciar(self): log.info("iniciar") self._establecer_parametros() # b = self.contexto.base # física self.mundo_fisica.setGravity(Vec3(0, 0, -9.81)) df = BulletDebugNode("debug_fisica") self.mundo_fisica.setDebugNode(df) self.debug_fisica = b.render.attachNewNode(df) self.debug_fisica.hide() self.accept("f11", self._toggle_debug_fisica) # input self.input = Input(self.contexto) if not self.input.iniciar(): return False # terreno if self.cargar_terreno: self.terreno = Terreno(self.contexto, self.mundo_fisica) if not self.terreno.iniciar(): return False # animados (actors) self._iniciar_animados() # atmosfera if self.cargar_atmosfera: self.atmosfera = Atmosfera(self.contexto) if not self.atmosfera.iniciar(): return False # controlador camara self.cntrlcam = ControladorCamara(self.contexto) if not self.cntrlcam.iniciar(): return False # info texto self.info_texto = OnscreenText( text="cámara: f1:libre f2:1ºpers f3:3ºpers\n" "debug física: f11") # debug hud self.debug_hud = OnscreenText(parent=b.a2dTopLeft, text="Debug?", pos=(0, -0.1), scale=0.05, align=TextNode.ALeft, bg=(1, 1, 1, 0.3)) # pelota (ball) pelota = b.loader.loadModel("modelos/items/pelota.egg") pelota.reparentTo(b.render) pelota.setPos(0, 0.5, 15) b.messenger.send("establecer_objetivo", [pelota]) # eventos self.accept("escape-up", self._salir) # tasks b.taskMgr.doMethodLater(0.1, self._update_debug_hud, "Mundo_update_debug_hud") b.taskMgr.add(self._update, "Mundo_update") # return True
def __init__(self, level, **kwargs): super().__init__(**kwargs) self._level = level self._part = None self._s = Surface((20, 10)) self._s.fill((255, 0, 0)) self._input = Input(inputStream=self.getInputStream()) self._input.set(pygame.KEYDOWN, self.createNew, pygame.K_f)
def main(): pygame.init() pygame.font.init() screen = pygame.display.set_mode((1200, 700)) delta_time = 0 views = [] #Create a Game view game = Game(screen) views.append(game) #Create a Menu view menu = Menu(screen, game) views.append(menu) lastTime = time.time() while (True): # Process OS events evt = pygame.event.get() for event in evt: # Checks if the user closed the window if (event.type == pygame.QUIT): # Exits the application immediately return elif (event.type == pygame.KEYDOWN): if (event.key == pygame.K_ESCAPE): return if (event.key == pygame.K_KP_ENTER): game.on_finish_game() #Update mouse inputs Input.update(evt) #Paint Background screen.fill((0, 20, 20)) #Draw views for v in views: v.draw(screen) #Display result on screen pygame.display.flip() #Update delta _time delta_time = time.time() - lastTime lastTime = time.time() #call coroutines Routine.delta_time = delta_time for r in Routine.routines: v = next(r, False) if (v == False): Routine.routines.remove(r)
def _mainloop(self, fps): step = 1. / fps clock = pygame.time.Clock() while not Input.quitflag: Input.update() map(GameObject.update, GameObject._gameobjects) #self.scene.lateupdate() self._renderloop() PhysicsEngine.step(step * Game.scale) delta = clock.tick(fps) Game.delta = delta / 1000.
class Game: def __init__(self): self.inp = Input() self.upd = Update() self.player1 = Player() self.out = Output() def update(self): self.inp.update(self.upd) self.upd.update(self.player1, self.out) self.out.update()
class Game(): '''A class containing all major elements of the game engine. GUI, input, draw functions, current state, save/load, AI, map functions, as well as settings.''' def __init__(self): '''Initializes the Game class.''' self.clock = pygame.time.Clock() # Initialize display, state self.display, self.state = Display(), State(self) # Initialize GUI and scene self.gui, self.scene = Gui(self), Scene(self) # Initialize input self.input = Input(self) self.gui.mainMenu() def events(self): '''Handles events such as input, but also ingame events which raise dialogs.''' # Iterate over new events for event in pygame.event.get(): # Quit if event.type == pygame.QUIT: sys.exit() else: self.input.handle(event) def update(self): '''Goes through updates on the game engine and manages time. :return: ''' # Update each sprite group. self.gui.widgets.update() self.scene.sprites.update() # Refresh pygame's event list. pygame.event.pump() # Keep framerate at 30 fps. self.clock.tick(30) def draw(self): '''Send current sprites to be drawn on the display.''' self.display.draw(self.gui.widgets, self.scene.sprites)
def __init__(self, levels): super().__init__() # --- Inits os.environ["SDL_VIDEO_CENTERED"] = "1" pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() pygame.font.init() pygame.display.set_caption(const.gameName) self._surface = pygame.display.set_mode((const.screenSize[0] * const.res, const.screenSize[1] * const.res)) self._clock = pygame.time.Clock() self._levAttr = levels self._world = None self._paused = False self._menu = Menu(surface=self._surface, pos=(const.screenSize[0] * const.res / 2 - 50, const.screenSize[1] * const.res / 2 - 100), inputStream=self.getInputStream()) self._menu.addItem("resume", (0, 0, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Resume", (0, 255, 0)), MAction(self._resume)) self._menu.addItem("start", (0, 50, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Start", (0, 255, 0)), MAction(self.start)) self._menu.addItem("editor", (0, 100, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Editor", (0, 255, 0)), MAction(self._editor)) self._menu.addItem("exit", (0, 150, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Exit", (0, 255, 0)), MAction(self.setFinished)) self._input = Input(inputStream=self.getInputStream()) self._input.set(pygame.KEYDOWN, self._menuToggle, pygame.K_m) self._input.set(pygame.KEYDOWN, self._pause, pygame.K_p)
def __init__(self, level, speed, tileset, **kwargs): super().__init__( dirRule=lambda: { -1: Direction.Left, 0: None, 1: Direction.Right }[self.move.getDir(x=True)], **kwargs) self.collision = Collision(self, level) self.move = Move(self, speed, collision=self.collision) self._gravity = GravityLine(self, 2, h=level.map.h // 2) self.jumping = Jumping(self.move, self._gravity, 2) self._input = Input(inputStream=self.getInputStream()) self.applyInputSettings() self._damageTimer = MinTimeEventStream(duration=2) self._damageTimer.subscribe("self", self._takeDmg, autoInit=False) def _isMoving(): return self.move.getSpeed(x=True) != 0 def _hDir(): return self.move.getDir(x=True) def _vDir(): return {False: -1, True: 1}[self._gravity.positiveDir()] image = Files.loadImage(tileset) self._display = Display(image, self, Animation(image, 11, _isMoving, _hDir, _vDir), True) self._weapon = Weapon(level, anchor=self, offsetFunc=lambda: ((5 * self.getIntDir()), 0), inputStream=self.getInputStream())
def __init__(self): '''Initializes the Game class.''' self.clock = pygame.time.Clock() # Initialize display, state self.display, self.state = Display(), State(self) # Initialize GUI and scene self.gui, self.scene = Gui(self), Scene(self) # Initialize input self.input = Input(self) self.gui.mainMenu()
def __init__(self, screen, width, height, debug=False, start_level=1): self.target_fps = 60 self.clock = pygame.time.Clock() self.running = False self.test_text = "Hello world" self.font = pygame.font.Font('./assets/font/vcr.ttf', 28) self.screen = screen self.width = width self.height = height self.current_scene = None self.restarting = False self.input = Input(pygame.key, pygame.mouse) self.current_scene = MenuScene(self, start_level) self.next_scene = None self.debug = debug
def __init__(self, id = -1, config = None): self.id = id self.set_config(config) # inner data structure self.input = Input() self.context_database = ContextDatabase() self.assorted_context_database = AssortedContextDatabase() self.output = Output() self.context_history = ContextHistory() # instance variables for debugging purposes self.new_aggregate = None self.filtered_singles = None self.data = None self.average = None
def start(self): self.map.load() self._entity_map = {} self._position_map = {} self._entities = {} self._registered = {} self._enemySpawns = {} for x, y in self.map.getMap().keys(): self._position_map[(x, y)] = [] self._total_surface = Surface((self.map.w, self.map.h)) tid = self.addEntity(register=True, entity=MChar(self, self.map.getType(Tiles.Start)[0], inputStream=self.getInputStream())) self._camera = Viewport(tuple([s * const.res for s in const.screenSize]), lambda: self.map.getAttr("scale"), self.get(tid), (150, 200, 150, 200), self.map) self._background = Parallax(const.backgrounds) self.editor = Editor(self.map, self._surface, enabled=False, inputStream=self.getInputStream()) self._input = Input(inputStream=self.getInputStream()) self._input.set(KEYDOWN, self.editor.toggleEnabled, K_e) self._input.set(KEYDOWN, self.start, K_r) # self._sound = Sound("assets\\music.ogg") # self._sound.play(-1) try: self._healthBar = HealthBar(10, 10, self.get(tid)) except AssertionError: pass for (x, y), val in self.map.enemies.items(): block = self.map.get(x, y) self._enemySpawns[block] = EnemySpawn(level=self, anchor=Object(pos=(block.x, block.y)), maxEmitted=val, timeBetween=2) self._countdown = CountdownTimer(const.screenSize[0] * const.res - 50, 10, self.map.getAttr("timeLim"))
def main(): with open('sample_map.yaml') as f: data = yaml.load(f) map = Map(data) input_object = Input(read_line=input, put_line=print) game = Game(data = map) input_object.put_line(game.start()) while True: read = input_object.next_move() if read: move, args = read response = getattr(game, move)(*args) input_object.put_line(response)
class Game(Enableable, Completable, Inputable): def __init__(self, levels): super().__init__() # --- Inits os.environ["SDL_VIDEO_CENTERED"] = "1" pygame.mixer.pre_init(44100, 16, 2, 4096) pygame.init() pygame.font.init() pygame.display.set_caption(const.gameName) self._surface = pygame.display.set_mode((const.screenSize[0] * const.res, const.screenSize[1] * const.res)) self._clock = pygame.time.Clock() self._levAttr = levels self._world = None self._paused = False self._menu = Menu(surface=self._surface, pos=(const.screenSize[0] * const.res / 2 - 50, const.screenSize[1] * const.res / 2 - 100), inputStream=self.getInputStream()) self._menu.addItem("resume", (0, 0, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Resume", (0, 255, 0)), MAction(self._resume)) self._menu.addItem("start", (0, 50, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Start", (0, 255, 0)), MAction(self.start)) self._menu.addItem("editor", (0, 100, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Editor", (0, 255, 0)), MAction(self._editor)) self._menu.addItem("exit", (0, 150, 100, 48), MColor((255, 0, 0), (0, 0, 255)), MText("Exit", (0, 255, 0)), MAction(self.setFinished)) self._input = Input(inputStream=self.getInputStream()) self._input.set(pygame.KEYDOWN, self._menuToggle, pygame.K_m) self._input.set(pygame.KEYDOWN, self._pause, pygame.K_p) def start(self): self.enable() self._world = World(self._surface, self._levAttr, inputStream=self.getInputStream()) self._world.nextLevel() self._menu.disable() def _pause(self): self._paused = not self._paused def _resume(self): if self._world is not None and not self._world.isComplete(): self.enable() else: self.start() self._menu.disable() def _editor(self): if self._world: self._world.level.editor.enabled() self._menu.disable() def _menuToggle(self): self._menu.toggleEnabled() self.toggleEnabled() def tick(self): self.getEvents() self._input() if self._menu.enabled(): self._menu.tick() self._menu.draw() elif self.enabled: if self._world.isComplete(): if self._world.isFinished(): self._win() elif self._world.isLost(): self._gameOver() else: if not self._paused: self._world.tick() self.clearInputStream() self._clock.tick(const.FPS) pygame.display.flip() def _win(self): self._endGame("YOU WIN!") def _gameOver(self): self._endGame("GAME OVER!") def _endGame(self, text): try: self.__gameOverCount += 1 except AttributeError: self.__gameOverCount = 1 self.__goText = pygame.font.Font(None, 100).render(text, 1, (255, 0, 0)) self.__gameOverX = int(self._surface.get_width() / 2 - self.__goText.get_width() / 2) self.__gameOverY = int(self._surface.get_height() / 2 - self.__goText.get_height() / 2) if self.__gameOverCount < (const.FPS * 5): self._surface.fill((0, 0, 0)) self._surface.blit(self.__goText, (self.__gameOverX, self.__gameOverY)) else: self.__gameOverCount = 0 self._surface.fill((0, 0, 0)) self._menuToggle() Event = namedtuple("Event", "type key pos") def getEvents(self): result = self.getInputStream() for event in pygame.event.get(): if event.type in [pygame.KEYDOWN, pygame.KEYUP]: result.append(Game.Event(event.type, event.key, None)) if event.type in [pygame.MOUSEBUTTONDOWN, pygame.MOUSEBUTTONUP, pygame.MOUSEMOTION]: result.append(Game.Event(event.type, None, event.pos)) if event.type == pygame.QUIT: self.setFinished()
def run(self): graphics = Graphics(units.tileToPixel(SCREEN_WIDTH), units.tileToPixel(SCREEN_HEIGHT)) input = Input() event = SDL_Event() self.player = Player(graphics, units.tileToGame(SCREEN_WIDTH // 2), units.tileToGame(SCREEN_HEIGHT // 2)) self.bat = FirstCaveBat(graphics, units.tileToGame(7), units.tileToGame(SCREEN_HEIGHT // 2 + 1)) self.map = Map.createTestMap(graphics) running = True lastUpdateTime = SDL_GetTicks() # units.MS while running: startTime = SDL_GetTicks() # units.MS input.beginNewFrame() while SDL_PollEvent(ctypes.byref(event)): if event.type == SDL_KEYDOWN: input.keyDownEvent(event) elif event.type == SDL_KEYUP: input.keyUpEvent(event) if input.wasKeyPressed(SDLK_ESCAPE): running = False # Player horizontal movement if input.isKeyHeld(SDLK_LEFT) and input.isKeyHeld(SDLK_RIGHT): self.player.stopMoving() elif input.isKeyHeld(SDLK_LEFT): self.player.startMovingLeft() elif input.isKeyHeld(SDLK_RIGHT): self.player.startMovingRight() else: self.player.stopMoving() # Player look if input.isKeyHeld(SDLK_UP) and input.isKeyHeld(SDLK_DOWN): self.player.lookHorizontal() elif input.isKeyHeld(SDLK_UP): self.player.lookUp() elif input.isKeyHeld(SDLK_DOWN): self.player.lookDown() else: self.player.lookHorizontal() # Player jump if input.wasKeyPressed(SDLK_z): self.player.startJump() elif input.wasKeyReleased(SDLK_z): self.player.stopJump() currentTime = SDL_GetTicks() # units.MS elapsedTime = currentTime - lastUpdateTime # units.MS self.update(min(elapsedTime, MAX_FRAME_TIME)) lastUpdateTime = currentTime self.draw(graphics) # This loop lasts 1/60th of a second, or 1000/60th ms msPerFrame = 1000 // FPS # units.MS elapsedTime = SDL_GetTicks() - startTime # units.MS if elapsedTime < msPerFrame: SDL_Delay(msPerFrame - elapsedTime)
def initInput(self): """ Initializes the input class """ self.input = Input()
class SceneManager(object): _instance2 = None _count2 = 0 def __new__(cls, *args, **kwargs): if not cls._instance2: cls._instance2 = super(SceneManager, cls).__new__( cls, *args, **kwargs) # _count += 1 print "Created new instance of SceneManger" return cls._instance2 def __init__(self): """ Initializes the scenemanager """ # Display some text if SceneManager._count2 == 0: #Init self.initPygame() self.initEventReaders() self.initScreen() self.initClock() self.initInput() self.initGame() SceneManager._count2 += 1 def initGame(self): """ Initializes the first scene """ self.gamemode = GameModes.MENU_MAIN self.scene = None self.running = True def initPygame(self): """ Initializes pygame """ result = pygame.init() return result[1] def initEventReaders(self): """ Initializes the event readers """ self.eventReaders = [] def initScreen(self): """ Initializes the screen """ self.surface = pygame.display.set_mode([Settings.SCREEN_WIDTH, Settings.SCREEN_HEIGHT]) #retourneert Surface pygame.display.set_caption(Settings.GAME_TITLE) def initClock(self): """ Initializes the clock """ self.clock = pygame.time.Clock() def initInput(self): """ Initializes the input class """ self.input = Input() def run(self): """ Run the scene """ while(self.running): self.clock.tick(90) self.input.update() #E Event for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False else: for eventReader in self.eventReaders: eventReader(event) self.scene.update(self.input) self.surface.fill(Settings.SCREEN_COLOR) self.scene.draw(self.surface) pygame.display.flip() self.scene.clean() def setScene(self, scene): """ Change the scene @param scene: The new scene """ if self.scene: self.scene.clean() if not scene == None: self.scene = scene else: self.running = False def registerEventReader(self, callback): """ Register a event reader @param callback: The function that should be called """ self.eventReaders.append(callback) def unregisterEventReader(self, callback): """ Unregisters a event reader @param callback: The function that should be unregistered """ self.eventReaders.remove(callback)
class Client(Happyboom, EventListener): """ The main class of the client of BoomBoom. @ivar display: Display manager of the game. @type display: C{L{BoomBoomDisplay}} @ivar input: Input manager of the game. @type input: C{L{BoomBoomInput}} @ivar __verbose: Verbose mode flag. @type __verbose: C{bool} @ivar __stopped: Stopped game flag. @type __stopped: C{bool} @ivar __stoplock: Mutex for synchronizing __stopped. @type __stoplock: C{thread.lock} """ def __init__(self, args): """ BoomBoomClient constructor. @param host: Server hostname. @type host: C{str} @param display_port: Server port for "display"/"view" connection. @type display_port: C{int} @param input_port: Server port for "input" connection. @type input_port: C{int} @param verbose: Verbose mode flag. @type verbose: C{bool} @param debug: Debug mode flag. @type debug: C{bool} @param max_fps: Maximal number of frames per second, for optimization. @type max_fps: C{int} """ args["protocol"] = protocol.loadProtocol("protocol.xml") args["features"] = ["game"] # Constant features Happyboom.__init__(self, args) EventListener.__init__(self, prefix="evt_") self.display = Display(args) self.input = Input(args) self.__verbose = args.get("verbose", False) self.registerEvent("happyboom") self.registerEvent("game") def start(self): """ Starts the game client.""" if self.__verbose: log.info("[BOOMBOOM] Starting client...") Happyboom.start(self) # Create thread for display thread.start_new_thread(self.displayThread, ()) quit = False while not quit: self.input.process() time.sleep(0.100) quit = self.stopped def stop(self): """ Stops the game client.""" if self.__verbose: log.info("[BOOMBOOM] Stopping client...") Happyboom.stop(self) self.launchEvent("happyboom", "disconnection", self._io, u"Quit.") self.display.stop() def evt_game_stop(self): self.stop() def evt_happyboom_stop(self): """ Stop event handler. """ self.stop() def displayThread(self): """ Thread handler for the "display" part.""" try: self.display.start() except Exception, msg: bt = getBacktrace() log.error("EXCEPTION IN DISPLAY THREAD:\n%s\n%s" % (msg, bt)) try: self.stop() except Exception, msg: bt = getBacktrace() log.error("EXCEPTION (2) IN DISPLAY THREAD:\n%s\n%s" % (msg, bt))
class Game(object): def __init__(self, screen, width, height, debug=False, start_level=1): self.target_fps = 60 self.clock = pygame.time.Clock() self.running = False self.test_text = "Hello world" self.font = pygame.font.Font('./assets/font/vcr.ttf', 28) self.screen = screen self.width = width self.height = height self.current_scene = None self.restarting = False self.input = Input(pygame.key, pygame.mouse) self.current_scene = MenuScene(self, start_level) self.next_scene = None self.debug = debug # self.background = Background((800, 600), 'assets/img/bgs.png') def run(self): self.running = True current_time = 0 previous_time = time.time() while self.running: self.clock.tick( self.target_fps ) self.input.update() if not self.next_scene is None: self.current_scene = copy.copy(self.next_scene) self.next_scene = None for event in pygame.event.get(): if event.type == pygame.QUIT: self.running = False self.restarting = False self.input.handle_event(event) if game.input.is_down(pygame.K_ESCAPE): self.running = False self.restarting = False current_time = time.time() delta_time = (current_time - previous_time) self.update(delta_time) self.draw() if self.debug: fps = round(1.0 / delta_time) fps_text = 'FPS: {0}'.format(fps) fps_w, fps_h = self.font.size(fps_text) fps_text_pos = (self.width - fps_w - 40, 20) self.screen.blit(self.font.render(fps_text, 1, WHITE), fps_text_pos) pygame.display.update() previous_time = current_time if self.restarting: game.run() else: game.quit() def restart(self): self.running = False self.restarting = True def quit(self): pygame.quit() quit() def update(self, dt): self.current_scene.update(dt) def draw(self): self.current_scene.draw()
def test_wrong_input(self): result = [] input = Input(self.__make_input(['dupa']), self.__make_output(result)) self.assertEqual(input.next_move(), None) self.assertEqual(result, ['Wrong move. Try: look.'])
def test_look(self): result = [] input = Input(self.__make_input(['look']), self.__make_output(result)) self.assertEqual(input.next_move(), ("look", []))
def main(): pygame.init() pygame.display.gl_set_attribute(pygame.GL_DEPTH_SIZE, 16) screen = pygame.display.set_mode((800,600), pygame.OPENGL|pygame.DOUBLEBUF) inp = Input() glEnable(GL_DEPTH_TEST) glDepthFunc(GL_LEQUAL) glDisable(GL_CULL_FACE) glBlendFunc(GL_SRC_ALPHA, GL_ONE) glViewport(0,0,800,600) print 'Window: Actual color bits r%d g%d b%d a%d'%( pygame.display.gl_get_attribute(pygame.GL_RED_SIZE), pygame.display.gl_get_attribute(pygame.GL_GREEN_SIZE), pygame.display.gl_get_attribute(pygame.GL_BLUE_SIZE), pygame.display.gl_get_attribute(pygame.GL_ALPHA_SIZE)) print 'Window: Actual depth bits: %d'%( pygame.display.gl_get_attribute(pygame.GL_DEPTH_SIZE),) print 'Window: Actual stencil bits: %d'%( pygame.display.gl_get_attribute(pygame.GL_STENCIL_SIZE),) print 'Window: Actual multisampling samples: %d'%( pygame.display.gl_get_attribute(pygame.GL_MULTISAMPLESAMPLES),) print "Running..." frame = 0 old_t = 0 scene = MainScene() try: scene.init() max_fps = 65.0 frame_ticks = 1000.0 / max_fps while True: glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT) t = pygame.time.get_ticks() inp.process() if (inp.shouldQuit()): break scene.advance(screen, t, inp) #t0 = pygame.time.get_ticks() pygame.display.flip() #t1 = pygame.time.get_ticks() dt = pygame.time.get_ticks() - t pygame.time.delay(max(0,int(frame_ticks - dt))) # be nice and yield some time #------ if 0: frame += 1 if (t - old_t > 1000.0): dt = t - old_t #load = 1.0 - float(t1-t0) / dt #print "%s FPS, LOAD: %s%%"%(1000.0*(float(frame) / dt), int(load*100) ) print "%s FPS"%(1000.0*(float(frame) / dt)) prof.printTotals(frame) frame = 0 old_t = t finally: scene.destroy()
class Level(Completable, Inputable): def __init__(self, surface, level, **kwargs): super().__init__(**kwargs) self._surface = surface self.map = Map(level[0], level[1]) def start(self): self.map.load() self._entity_map = {} self._position_map = {} self._entities = {} self._registered = {} self._enemySpawns = {} for x, y in self.map.getMap().keys(): self._position_map[(x, y)] = [] self._total_surface = Surface((self.map.w, self.map.h)) tid = self.addEntity(register=True, entity=MChar(self, self.map.getType(Tiles.Start)[0], inputStream=self.getInputStream())) self._camera = Viewport(tuple([s * const.res for s in const.screenSize]), lambda: self.map.getAttr("scale"), self.get(tid), (150, 200, 150, 200), self.map) self._background = Parallax(const.backgrounds) self.editor = Editor(self.map, self._surface, enabled=False, inputStream=self.getInputStream()) self._input = Input(inputStream=self.getInputStream()) self._input.set(KEYDOWN, self.editor.toggleEnabled, K_e) self._input.set(KEYDOWN, self.start, K_r) # self._sound = Sound("assets\\music.ogg") # self._sound.play(-1) try: self._healthBar = HealthBar(10, 10, self.get(tid)) except AssertionError: pass for (x, y), val in self.map.enemies.items(): block = self.map.get(x, y) self._enemySpawns[block] = EnemySpawn(level=self, anchor=Object(pos=(block.x, block.y)), maxEmitted=val, timeBetween=2) self._countdown = CountdownTimer(const.screenSize[0] * const.res - 50, 10, self.map.getAttr("timeLim")) def addEntity(self, register=False, entity=None): if not entity: raise Exception("Entity must not be None.") tid = entity.getId() self._entities[tid] = entity if register: self._registered[tid] = entity self._entity_map[tid] = set() return tid def removeEntity(self, entity): del self._entities[entity.id] def get(self, entityId): return self._entities.get(entityId) def process(self): for entity in self._entities.values(): result = entity.tick() if not entity.isAlive(): self._entities.pop(entity.getId()) # This should generally only apply to playable characters. if entity in self._registered.values(): if Tiles.End in result.keys(): self.setFinished() if not entity.isAlive(): self.setLost() for s in self._enemySpawns.values(): s.tick() self._camera.tick() self._countdown.tick() if self._countdown.isFinished(): self.setLost() if self.editor.enabled(): self.editor.tick(self._camera) if self.isComplete(): pass # self._sound.fadeout(3000) def render(self): self._surface.fill((0, 0, 0)) self._background.draw(self._total_surface, self._camera) for s in self._enemySpawns.values(): s.draw(self._total_surface) for entity in self._entities.values(): entity.draw(self._total_surface) self.map.draw(self._total_surface) if self.editor.enabled(): self.editor.draw(self._total_surface) self._camera.draw(self._surface, self._total_surface) self._healthBar.draw(self._surface) self._countdown.draw(self._surface) if self.editor.enabled(): self.editor.menu.draw() def tick(self): self._input() self.process() self.render()
def test_move(self): result = [] input = Input(self.__make_input(['move north']), self.__make_output(result)) self.assertEqual(input.next_move(), ("move", ['north']))
import socket import struct import time from input import Input class piCmd(object): __slots__ = [ 'lMotorVal', 'rMotorVal', 'lMotorBrake', 'rMotorBrake' ] def getVals(self): return (self.lMotorVal, self.rMotorVal, self.lMotorBrake, self.rMotorBrake) controller = Input(12000, 32768, 255) clientsocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) clientsocket.connect(('192.168.0.200', 9595)) running = True while running: #time.sleep(.05) time.sleep(1) state = controller.getState() #print( state ) cmd = piCmd() cmd.lMotorVal = int(state["rtrigger"]) cmd.rMotorVal = int(state["rtrigger"]) cmd.lMotorBrake = 0 cmd.rMotorBrake = 0 data = cmd.getVals() numElements = len(data)
def __init__(self, id, function): Input.__init__(self, id, function)
def initInput(self): self.input = Input(self, self.robots[0], self.robots[1])
class Simulator(object): objects=[] robots=[] images={} # Options and arguments headless=False vision=None pitch=None ai=[] robot1=None robot2=None def __init__(self, **kwargs): logging.debug("Simulator started with the arguments:") for k, v in kwargs.items(): self.__setattr__(k, v) logging.debug("\t%s = %s", k, v) def initVision(self): if self.vision: logging.info("Starting simulator vision bridge") world = self.world if not self.real_world: # Vision must always use the real World world = common.world.World(self.colour) self.vision = Vision(simulator=self, world=world) self.visionFile = tempfile.mktemp(suffix='.bmp') def drawEnts(self): if self.pitch: bg = self.pitch.get() self.screen.blit(bg, (0,0)) self.sprites.draw(self.screen) if self.vision: pygame.image.save(self.screen, self.visionFile) self.vision.processFrame() # Update overlay after we've passed the "raw image" to vision self.screen.blit(self.overlay, (0,0)) # Make the overlay "blank" again. Should be completely # transparent but I don't know how to do that self.overlay.fill( (130,130,130,255)) if not self.headless: pygame.display.flip() def initScreen(self): logging.debug("Creating simulator screen") if self.headless: self.screen = pygame.Surface(World.Resolution) else: pygame.display.set_mode(World.Resolution) pygame.display.set_caption('SDP 9 Simulator') self.screen = pygame.display.get_surface() self.overlay = pygame.Surface(World.Resolution) self.overlay.convert_alpha() self.overlay.set_alpha(100) def makeObjects(self): logging.debug("Creating game objects") colours = ('blue', 'yellow') if random() < 0.5: col1, col2 = colours else: col2, col1 = colours logging.info("Robot 1 is %s. Robot 2 is %s", col1, col2) self.makeRobot(World.LeftStartPos, col1, 0, self.robot1[0]) self.makeRobot(World.RightStartPos, col2, -pi, self.robot2[0]) # Only make a real ball when there are two simulated robots if len(self.robots) == 2: pos = World.Pitch.center logging.info("Creating a ball at %s", pos2string(pos)) self.makeBall(pos) else: logging.info("Not making a simulated ball with real robots") self.sprites = pygame.sprite.RenderPlain(self.objects) def setRobotAI(self, robot, ai): # TODO: just delete the image and reclassify the robot as a # real robot #del robot pass def initAI(self): logging.debug("Initialising AI") ai1, real1 = self.robot1 ai2, real2 = self.robot2 if ai1 and real1: real_interface = RealRobotInterface() #meta_interface = MetaInterface(real_interface, self.robots[0]) ai = ai1(self.world, real_interface) self.ai.append(ai) robotSprite = self.robots[0] #self.robots[0] = ai #del robotSprite self.setRobotAI(self.robots[0], ai) logging.debug("AI 1 started in the real world") elif ai1: self.ai.append( ai1(self.world, self.robots[0]) ) logging.debug("AI 1 started in the simulated world") else: logging.debug("No AI 1 present") if ai2 and real2: # TODO: reverse sides here ai = ai2(self.world, RealRobotInterface()) self.ai.append(ai) robotSprite = self.robots[0] self.robots[1] = ai #del robotSprite self.setRobotAI(self.robots[1], ai) logging.debug("AI 2 started in the real world") elif ai2: self.ai.append( ai2(self.world, self.robots[1]) ) logging.debug("AI 2 started in the simulated world") else: logging.debug("No AI 2 present") def runAI(self): #logging.debug("Running AI players") for ai in self.ai: ai.run() def run(self): pygame.init() self.clock = pygame.time.Clock() self.initVision() self.initScreen() self.loadImages() self.makeObjects() self.world.assignSides() self.initAI() self.initInput() # by initialising the input after the AI, we can control even # AI robots with keyboard self.drawEnts() while True: self.handleInput() self.clock.tick(25) self.drawEnts() self.sprites.update() self.runAI() def initInput(self): self.input = Input(self, self.robots[0], self.robots[1]) def handleInput(self): for event in pygame.event.get(): if event.type == QUIT: sys.exit(0) else: #logging.debug("Got input event: %s", event) self.input.robotInput(event) def makeRobot(self, pos, colour, angle, ai): ent = Robot(self, pos, self.images[colour], angle) ent.side = colour self.world.ents[colour] = ent self.robots.append(ent) self.addEnt(ent) def makeBall(self, pos): ent = Ball(self, pos, self.images['ball']) #ent.v += [1, 7] self.world.ents['ball'] = ent self.addEnt(ent) def addEnt(self, ent): self.objects.append(ent) def loadImages(self): logging.debug("Loading images") for name in World.image_names.keys(): self.images[name] = pygame.image.load(World.image_names[name])