def game(): config = GameConfig() event_handler = EventHandler() screen = pygame.display.set_mode([config.w, config.h]) config.screen = screen render_handler = RenderHandler() scene_handler = SceneHandler() config.scene_handler = scene_handler last_ticks = pygame.time.get_ticks() ticks_since_render = pygame.time.get_ticks() while config.running: for event in pygame.event.get(): if event.type == pygame.QUIT: config.running = False else: event_handler.dispatch(event) current_ticks = pygame.time.get_ticks() dt = current_ticks - last_ticks # Update scene_handler.update(dt) # Render ticks_since_render += dt last_ticks = current_ticks if ticks_since_render > config.min_mspf: screen.fill((0, 0, 0)) render_handler.draw() pygame.display.flip() ticks_since_render = 0
def main(args: ArgumentParser): config = GameConfig(split=StartingSplit.StartingRandomSplit, prosperity=False, num_players=len(args.players), sandbox=args.sandbox, feature_type=args.ftype) players = load_players(args.players, args.models, config, train=True) if not args.predict: X, y = sample_training_batch(args.n, args.p, config, players) if args.reg_cls == PredictorMLP: model = PredictorMLP(config.feature_size, (config.feature_size + 1) // 2, D_out=2) train_mlp(X, y, model, nn.CrossEntropyLoss(), args.epochs, save_epochs=args.save_epochs, path=args.path) acc = test_mlp(X, y, model) print(f'Acc = {acc}') torch.save(model, args.path) else: reg = load_predict_model(args.reg_cls, alpha=args.alpha) score = train_linear_model(X, y, reg) print(f'R_sq = {score}') pickle.dump(reg, open(args.path, 'wb')) np.savez(os.path.join('data', os.path.split(args.path)[-1])) else: if args.reg_cls == PredictorMLP: model = torch.load(args.path) else: reg = pickle.load(open(args.path, 'rb')) X, y = sample_training_batch(args.n, args.p, config, players) if args.reg_cls == PredictorMLP: acc, cl_acc = test_mlp(X, y, model) print(f'Acc = {acc}, {cl_acc}') else: score = reg.score(X, y) print(f'R_sq = {score}')
def __init__(self, T: int, n: int, tau: float, rollout: Rollout, eps: float): # initialize game config self.game_config = GameConfig(StartingSplit.StartingRandomSplit, prosperity=False, num_players=1, sandbox=True) self.supply = Supply(self.game_config) self.game = None # max number of turns in a game self.T = T self.expanded = False self.rollout_model = rollout self.data = MCTSData() self.player = None self.iter = 0 self.iters = n if self.rollout_model == Rollout.Random: self.rollout = RandomRollout() elif rollout == Rollout.HistoryHeuristic: self.rollout_cards = [] self.rollout = HistoryHeuristicRollout(tau=tau, train=True) elif rollout == Rollout.LinearRegression: self.rollout = LinearRegressionRollout(self.iters, self.supply, tau=tau, train=True, eps=eps) self.player = MCTSPlayer(rollout=self.rollout, train=True)
def main(args): config = GameConfig(num_players=2, sandbox=args.sandbox, feature_type=args.ftype, device=args.device) tree = GameTree(train=True) D_in = config.feature_size H = (config.feature_size + 1) // 2 player = MCTSPlayer(rollout=init_rollouts(args.rollout, D_in=D_in, H=H)[0], tree=tree) players = [player, player] env = DefaultEnvironment(config, players) train_mcts(env, tree, args.n, save_epochs=args.save_epochs, train_epochs=args.train_epochs, train_epochs_interval=args.train_epochs_interval, path=args.path, rollout_path=args.rollout_path, capacity=args.buffer_cap)
def setUp(self) -> None: self.config = GameConfig(sandbox=False, splits=[ StartingSplit.Starting34Split, StartingSplit.Starting34Split ]) self.players: List[Player] = init_players(['tdebm', 'tdebm']) self.game = Game(self.config, self.players)
def setUp(self) -> None: self.config = GameConfig(sandbox=False, splits=[ StartingSplit.Starting25Split, StartingSplit.Starting25Split ], feature_type=FeatureType.FullFeature) self.supply = Supply(self.config) self.players = [Mock(), Mock()] self.game = Game(self.config, self.players)
def make_config() -> MuZeroConfig: game_config = GameConfig(name='TicTacToe', environment_class=TicTacToeEnvironment, environment_parameters={}, action_space_size=9, num_players=2, discount=1.0 ) replay_buffer_config = ReplayBufferConfig(window_size=int(1e4), prefetch_buffer_size=10 ) mcts_config = MCTSConfig(max_moves=9, root_dirichlet_alpha=1.0, root_exploration_fraction=0.25, num_simulations=20, temperature=1.0, freezing_moves=9, default_value=Value(0.0) ) network_config = NetworkConfig(network_class=TicTacToeNetwork, regularizer=tf.keras.regularizers.l2(l=1e-4), hidden_state_size=128, hidden_size=128 ) training_config = TrainingConfig(optimizer=tf.keras.optimizers.Adam(), batch_size=128, training_steps=int(5e4), checkpoint_interval=int(5e2), replay_buffer_loginterval=50, num_unroll_steps=2, td_steps=9, steps_per_execution=1 ) reward_config = ScalarConfig(known_bounds=KnownBounds(minv=Value(0.0), maxv=Value(1.0)), support_size=None, loss_decay=0.0) value_config = ScalarConfig(known_bounds=KnownBounds(minv=None, maxv=Value(1.0)), support_size=None, loss_decay=4.0) return MuZeroConfig(game_config=game_config, replay_buffer_config=replay_buffer_config, mcts_config=mcts_config, training_config=training_config, network_config=network_config, value_config=value_config, reward_config=reward_config)
def reset(self, i: int): self.expanded = False self.rollout_cards = [] self.iter = i self.game_config = GameConfig(StartingSplit.StartingRandomSplit, prosperity=False, num_players=1, sandbox=True) self.game = Game(self.game_config, [self.player]) self.game.new_game() self.game.state.advance_next_decision() self.player.reset(self.game.state.player_states[0])
def __init__(self): #pygame pygame.init() self.fnt = pygame.font.Font(pygame.font.get_default_font(), 30) self.smallfnt = pygame.font.Font(pygame.font.get_default_font(), 20) self.window = pygame.display.set_mode((DISP_SIZE, DISP_SIZE)) #entities self.bloons = [] self.towers = [] self.bullets = [] self.effects = [] #load config file self.conf = GameConfig("testlevels.json") self.pathimg = pygame.image.load(self.conf.pathimg) #state self.ticks = 0 self.money = 100 self.life = 100 #gui state self.selectedTowerType = None self.selectedTower = None self.remarkText = None init_bloon_sprites()
def setUp(self) -> None: self.config = GameConfig(sandbox=False, num_players=2, must_include=DEFAULT_KINGDOM) self.tree = GameTree(train=True) self.player = init_players(['UCT'], tree=self.tree, rollout_type='mlog')[0] self.players = [self.player, self.player] self.project_root = '/home/justiny/Documents/Projects/PyDominion' self.model_dir = os.path.join(self.project_root, 'models') self.env = DefaultEnvironment(self.config, self.players) self.tree_name = 'mcts-test' self.rollout_name = 'mlog-test' self.tree_path = os.path.join(self.model_dir, self.tree_name) self.rollout_path = os.path.join(self.model_dir, self.rollout_name)
def distance(save: bool = True): """Create an image for the distance-fitness.""" cfg = GameConfig() diagonal = 10 # Define the function def get_score(d, reached=False): """Get a score for the given distance.""" return 1 if reached else clip( (1 - (d - cfg.target_reached) / diagonal)**2, a_min=0, a_max=1) # Create the figure x = [] y = [] for i in range(0, round(diagonal * 100)): x.append(i / 100) y.append(get_score(i / 100)) plt.figure(figsize=(5, 2)) # Plot the distance function plt.plot(x, y, color=COLORS[D_NEAT], label='distance-based score') plt.axvspan(0, cfg.target_reached, color='#97e08d', label='target reached') # Beautify the plot plt.title('Fitness in function of distance to target') plt.xlabel("Distance to target") plt.xticks([i * 2 for i in range(round(diagonal / 2) + 1)]) plt.xlim(0, 10) plt.ylabel("Fitness") plt.ylim(0) leg = plt.legend() for line in leg.get_lines(): line.set_linewidth(4.0) plt.tight_layout() plt.grid() if save: plt.savefig('population/utils/visualizing/images/distance_fitness.png', bbox_inches='tight', pad_inches=0.02) plt.savefig('population/utils/visualizing/images/distance_fitness.eps', format='eps', bbox_inches='tight', pad_inches=0.02) plt.show() plt.close()
def __init__(self, machine_type): super(FapoGame, self).__init__(machine_type) self.gameConfig = GameConfig.GameConfig() self.ball_start_time = 0 self.midiMap = None self.midiLampMap = None if self.gameConfig.inputKeyboardTest: self.midiMap = self.gameConfig.midiKeyboardMap self.midiLampMap = None if self.gameConfig.inputLaunchpadTest: self.midiLampMap = self.gameConfig.midiLaunchpadMap self.load_config('config/funhouse.yaml') ### ALPHANUMERIC DISPLAY ### self.aux_port = auxport2.AuxPort(self) self.alpha_display = alphanumeric2.AlphanumericDisplay(self.aux_port) # self.scoredisplay = scoredisplay.AlphaScoreDisplay(self,4) # blink text ### MODES ### self.basic_mode = BasicMode.BasicMode(game=self) self.idle_mode = IdleMode.IdleMode(game=self) self.steps_mode = StepsMode.StepsMode(game=self) self.alpha_mode = scoredisplay.AlphaScoreDisplay(game=self, priority=5) self.trough_mode = procgame.modes.trough.Trough( self, ["trough1", "trough2", "trough3"], "trough1", "trough", [], "shooterR", self.ballDrained) ### MIDI HANDLING ### self.midi_in_sol = rtmidi.MidiIn() self.midi_in_sol.open_port(self.gameConfig.inputMidiSolenoids) self.midi_in_lamp = rtmidi.MidiIn() self.midi_in_lamp.open_port(self.gameConfig.inputMidiLamps) self.midi_out = rtmidi.MidiOut() self.midi_out.open_port(self.gameConfig.outputMidiSwitches) self.addSwitchHandlers() ### LAMP SHOWS ### self.lampctrl = procgame.lamps.LampController(self) self.lampctrl.register_show('attract', 'lamps/attract.lampshow') self.lampctrl.register_show('start', 'lamps/start.lampshow') self.lampctrl.register_show('trapdoorOpen', 'lamps/trapdoorOpen.lampshow') print self.lamps
def main(args: ArgumentParser): if args.debug: logging.basicConfig(level=logging.INFO) config = GameConfig(prosperity=args.prosperity, num_players=len(args.players), sandbox=args.sandbox, feature_type=args.ftype, device=args.device) if args.tree_path: tree = GameTree.load(args.tree_path, False) else: tree = None players = load_players(args.players, args.models, tree=tree, train=False, rollout_type=args.rollout_type) logger = logging.getLogger() if args.log_buys: logger.setLevel(BUY) env = DefaultEnvironment(config, players, logger=logger) sim_data = simulate(env, args.n, tree) if args.save_data: save(args.data_path, sim_data)
def __init__(self): self.config = GameConfig() self.renderer = MainMenuScene.MainMenuRenderer(self.config) self.event_handler = EventHandler() super(MainMenuScene, self).__init__(1)
'''start whole app''' import sys from app import app from config import GameConfig from quest_modules.game import Game app.game = Game(GameConfig()) if __name__ == "__main__": arg = sys.argv # get the command line arguments if len(arg) > 1: # if ip written in the command line app.run(host=str(sys.argv[1]), debug=True) # '192.168.31.174' - home else: app.run()
def loadConfigs(self): print("Loading game configs......") _G.setGlobalVarTo_Global("GameConfig", GameConfig()) # 设置配置的全局变量 print("Loaded game configs!") pass
def __init__(self): self.config = GameConfig() self.render_handler = RenderHandler() self.scenes = {}
def setUp(self) -> None: self.config = GameConfig(num_players=2, sandbox=False) self.supply = Supply(self.config)
def __init__(self): self.config = GameConfig() self.info = GameScene.GameInfo(self.config) self.renderer = GameScene.GameRenderer(self.config, self.info) self.event_handler = EventHandler() super(GameScene, self).__init__(2)
def __init__(self): self.config = GameConfig() self.handlers = {}
def make_config(self): board = [0] * 256 for x, y, z, w in product(range(4), range(4), range(4), range(4)): board[w * 64 + z * 16 + y * 4 + x] = self.get_cell(x, y, z, w).player return GameConfig(history=self.history, cpu=self.cpu.value)
def __init__(self, *args, **kwargs): height, width = ui.get_screen_size() super().__init__(frame=(0, 0, width, height), background_color='white', name='4-4-4-4', *args, **kwargs) self.sections = [[Cell.Cells(z, w) for w in range(4)] for z in range(4)] for sections_w in self.sections: for section in sections_w: self.add_subview(section) self.player = 1 self.black, self.white = 0, 0 self.history = [] self.scores = [ Score(player, x=750, y=10 + 85 * i) for i, player in enumerate(['●', '○']) ] for score in self.scores: self.add_subview(score) self.scores[0].border_width = 1.5 self.cpu = ui.Switch(x=750, y=220, value=False, action=self.save_config) self.add_subview(self.cpu) self.add_subview( ui.Label(text='CPU', font=('<system>', 42), x=810, y=185)) self.reset = ui.Button(tint_color='black', frame=(750, 310, 160, 60), font=('Source Code Pro', 42), action=self.clear, border_color='black', border_width=1, corner_radius=5, alignment=ui.ALIGN_CENTER) self.reset.title = 'Clear' self.add_subview(self.reset) self.disable(self.reset) self.undo = ui.Button(background_image=ui.Image('iob:ios7_undo_256'), frame=(800, 400, 60, 60), action=self.backward) self.add_subview(self.undo) self.disable(self.undo) self.saveas = ui.Button(tint_color='black', frame=(750, 500, 160, 40), font=('<system>', 28), action=self.write, border_width=1, corner_radius=5, alignment=ui.ALIGN_CENTER) self.saveas.title = 'Save as' self.add_subview(self.saveas) self.loadfrom = ui.Button(tint_color='black', frame=(750, 550, 160, 40), font=('<system>', 28), action=self.read, border_width=1, corner_radius=5, alignment=ui.ALIGN_CENTER) self.loadfrom.title = 'Load from' self.add_subview(self.loadfrom) self.delete = ui.Button(tint_color='red', frame=(750, 640, 160, 40), font=('<system>', 28), action=GameConfig.delete, border_width=1, corner_radius=5, alignment=ui.ALIGN_CENTER) self.delete.title = 'Delete' self.add_subview(self.delete) self.apply_config(GameConfig().load()) self.save_config()
'''Testing all modules and app''' import time from config import GameConfig from quest_modules.game import Game g = Game(GameConfig()) def mb_test(): print(g.master.sig['count']) for i in range(10): g.master.get_sig() print(g.master.sig['str']) time.sleep(1) g.master.get_bps() print(g.master.bps['str']) def csv_create(): g.stat.c_w.create_csv() def test_set_bps(): for i in range(26): g.master.set_one_bps(i) g.master.get_bps() bps = g.master.bps['str'] print(bps) time.sleep(1)
def __init__(self, handler): self.config = GameConfig() self.renderer = LoadingScene.LoadingRenderer(self.config) self.loading = False self.scene_handler = handler super(LoadingScene, self).__init__(0)
def setUp(self) -> None: self.config = GameConfig(sandbox=False, must_include=[Sentry, Moat, Militia]) self.players = [Mock(), Mock()] self.game = Game(self.config, self.players)
import cv2 from pygame import mixer import pandas as pd from config import GameConfig import time config = GameConfig() def play_music(music_file, time=0.0): # music 함수 mixer.init() mixer.music.load(music_file) mixer.music.play(1, time) # clock = pygame.time.Clock() # clock.tick(10) def play_sound(sound_file): # sound effect 함수 mixer.init() sound = mixer.Sound(sound_file) mixer.Sound.play(sound) # 효과음 sound_effect1 = 'musics/sound1.wav' sound_effect2 = 'musics/sound2.wav' sound_applause = 'musics/applause.wav' sound_disappointed = 'musics/disappointed.wav' def main_menu(config, params):
def setUp(self) -> None: self.config = GameConfig(sandbox=False, num_players=2, must_include=[Merchant]) self.players = [Mock(), Mock()] self.game = Game(self.config, self.players)
class Game: def __init__(self): #pygame pygame.init() self.fnt = pygame.font.Font(pygame.font.get_default_font(), 30) self.smallfnt = pygame.font.Font(pygame.font.get_default_font(), 20) self.window = pygame.display.set_mode((DISP_SIZE, DISP_SIZE)) #entities self.bloons = [] self.towers = [] self.bullets = [] self.effects = [] #load config file self.conf = GameConfig("testlevels.json") self.pathimg = pygame.image.load(self.conf.pathimg) #state self.ticks = 0 self.money = 100 self.life = 100 #gui state self.selectedTowerType = None self.selectedTower = None self.remarkText = None init_bloon_sprites() def draw(self): self.window.blit(self.pathimg, (0, 150)) for bloon in self.bloons: bloon.draw(self.window) for tower in self.towers: tower.draw(self.window) for bullet in self.bullets: bullet.draw(self.window) for effect in self.effects: effect.draw(self.window) if (self.selectedTowerType): self.selectedTowerType.draw_(self.window, *pygame.mouse.get_pos()) self.render_hud() pygame.display.update() def render_hud(self): pygame.draw.rect(self.window, (210, 190, 190), (0, 0, 1000, 150)) x = 200 for tow in tower_types: # draw 'store window' self.window.blit( self.smallfnt.render(f"${tow.price}", False, (0, 0, 0)), (x, 0)) pygame.draw.rect(self.window, tow.color, (x, 20, 30, 30)) x += 50 self.window.blit( self.fnt.render(f"Money: ${self.money}", False, (0, 0, 0)), (0, 0)) self.window.blit( self.fnt.render(f"Life: {self.life}", False, (0, 0, 0)), (0, 30)) #main text display pygame.draw.line(self.window, (0, 0, 0), (0, 75), (1000, 75)) if (self.selectedTowerType): self.window.blit( self.fnt.render(self.selectedTowerType.desc, False, (0, 0, 0)), (0, 80)) elif (self.remarkText): self.window.blit( self.fnt.render(self.remarkText, False, (0, 0, 0)), (0, 80)) #upgrade sidebar pygame.draw.line(self.window, (0, 0, 0), (700, 0), (700, 150)) if (self.selectedTower): y = 0 for up in self.selectedTower.upgrades: if (up): self.window.blit( self.fnt.render(f"{up.name}: ${up.price}", False, (0, 0, 0)), (700, y)) self.window.blit( self.smallfnt.render(f"{up.desc}", False, (0, 0, 0)), (700, y + 30)) else: self.window.blit( self.fnt.render("No upgrade", False, (0, 0, 0)), (700, y)) y += 75 def inputs(self): for event in pygame.event.get(): if event.type == MOUSEBUTTONDOWN: stop_after_first_true([ self.choose_new_tower, self.place_new_tower, self.select_tower, self.choose_upgrade, self.bad_click ], event) if event.type == QUIT: self.stop() def choose_new_tower(self, event): x = 200 for tow in tower_types: if (in_box(event.pos[0], event.pos[1], x, 20, 30, centered=False)): self.selectedTowerType = tow self.selectedTower = None return True x += 50 def place_new_tower(self, event): if (self.selectedTowerType): if (self.money >= self.selectedTowerType.price): if (self.is_good_place_pos(event.pos)): self.towers.append( self.selectedTowerType(event.pos[0], event.pos[1], self.ticks)) self.money -= self.selectedTowerType.price self.selectedTowerType = None return True def is_good_place_pos(self, pos): for tower in self.towers: if (box_collide(pos[0], pos[1], tower.x, tower.y, TOWER_SIZE)): return False return True def select_tower(self, event): for tower in self.towers: if (in_box(event.pos[0], event.pos[1], tower.x, tower.y, TOWER_SIZE, centered=True)): self.selectedTowerType = None self.selectedTower = tower return True def choose_upgrade(self, event): if (self.selectedTower): y = 0 for up in self.selectedTower.upgrades: if (in_rect(event.pos[0], event.pos[1], 700, y, 300, 75)): if (self.money >= up.price): self.money -= up.price up.action(self.selectedTower) self.selectedTower.upgrades.remove(up) if (up.next): self.selectedTower.upgrades.append(up.next) return True y += 75 def bad_click(self, event): self.selectedTowerType = None self.selectedTower = None def update(self): nxt = self.conf.next_bloon() if (self.conf.done and not self.bloons): self.win() if (self.conf.intermission and not self.bloons): self.level_intermission(self.conf.remark, self.conf.reward) if (nxt): self.bloons.append(nxt) for bloon in self.bloons: bloon.update(self) for tower in self.towers: tower.update(self) nb = [] for bullet in self.bullets: bullet.update(self) if (bullet.valid): nb.append(bullet) self.bullets = nb ne = [] for effect in self.effects: effect.update(self) if (effect.valid): ne.append(effect) self.effects = ne def loop(self): clock = pygame.time.Clock() while (self.life > 0): self.ticks += 1 self.draw() self.inputs() self.update() clock.tick_busy_loop(60) self.lose() def level_intermission(self, remark, reward): self.money += reward clock = pygame.time.Clock() self.remarkText = f"{remark} : You got ${reward}!" self.bullets = [] self.effects = [] t = 0 while (t < 60 * 5): self.draw() self.inputs() t += 1 clock.tick_busy_loop(60) self.remarkText = None self.conf.end_intermission() def remove(self, bloon): self.bloons.remove(bloon) def end(self, bloon): # bloon reaches end self.remove(bloon) self.life -= bloon.level + 1 def kill(self, bloon): #bloon is killed self.remove(bloon) self.money += 1 def spawn_bullet(self, bullet): self.bullets.append(bullet) def add_effect(self, effect): self.effects.append(effect) def win(self): self.game_over_text("You win!") self.stop() def lose(self): self.game_over_text("You lose!") self.stop() def game_over_text(self, text): t = 0 clock = pygame.time.Clock() while (t < 60 * 5): for event in pygame.event.get(): if (event.type == QUIT): self.stop() pygame.draw.rect(self.window, (0, 0, 0), (0, 0, 1000, 1000)) self.window.blit(self.fnt.render(text, False, (255, 255, 255)), (400, 400)) pygame.display.update() t += 1 clock.tick_busy_loop(60) def stop(self): pygame.quit() quit()
hand_config = HandConfig( max_hand_cards=10, max_deck_cards=10, hand_embedding_size=256, hidden_size=128, state_size=64) hero_config = HeroConfig( max_attack=10, max_health=30, max_mana=10, state_size=3) minion_config = MinionConfig( max_attack=10, max_health=10) game_config = GameConfig( card_config, hand_config, hero_config, minion_config, action_hidden_size=64, action_state_size=4, targets_hidden_size=64) model_config = ModelConfig( model_name='model1.1', seed=520, epoch=2000, round_num=200, learning_rate=0.001, batch_size=256, optim='Adam', grad_clip=20, grad_norm_type=2) trainer = Trainer(model_config, game_config, player1_mode='model_training', player2_mode='random', model_dir='models') trainer.train()