def main(): args = parser.parse_args() solution = json.loads(args.solution)[0] problem = os.path.join(utils.get_data_dir(), args.problems % solution['problemId']) with open(problem) as f: problem = json.load(f) problem['problemId'] = solution['problemId'] g = game.Game(problem, solution['seed']) try: display(g) prev_states = collections.deque(maxlen=10) prev_states.append(copy.deepcopy(g)) i = 0 for cmd in gamepad(args.delay): if cmd == FWD: prev_states.append(copy.deepcopy(g)) g.execute_char(solution['solution'][i]) i += 1 else: # cmd == BWD if i > 0: if len(prev_states) > 1: g = prev_states[-1] prev_states.pop() i -= 1 display(g) except game.GameEnded as e: print(e)
def main(): args = parser.parse_args() for trace in glob.glob(args.traces): with open(trace) as f: trace = json.load(f) data = os.path.join(utils.get_data_dir(), args.problems % trace[0]["problemId"]) with open(data) as f: data = json.load(f) data["problemId"] = trace[0]["problemId"] g = game.Game(data, trace[0]["seed"]) i = 0 for move in trace[1:]: g.execute_char(move["history"][i]) sys.stdout.write("\x1b\x5b\x48\x1b\x5b\x4a") sys.stdout.write(move["boardState"]) sys.stdout.write("\n\n") try: sys.stdout.write(g.render_grid()) except game.GameEnded: pass assert move["boardState"] == g.render_grid() assert g.game_ended == move["gameEnded"] if g.game_ended is not None: break time.sleep(0.01) i += 1
def main(): random.seed(42) logging.basicConfig(level=logging.DEBUG) print(translate_dfa(interfaces.POWER_PHRASES[:2])) return path = os.path.join(utils.get_data_dir(), 'qualifier/problem_0.json') with open(path) as fin: data = json.load(fin) seeds = data['sourceSeeds'] bsg = BigStepGame.from_json(data, seeds[0]) print(bsg) while not bsg.game_ended: graph = bsg.get_placement_graph() print('locked nodes:', graph.GetLockedNodes()) placement = bsg.get_placement_by_node_index( graph, random.choice(graph.GetLockedNodes())) print(placement) bsg = bsg.lock_unit(placement) print(bsg)
def main(): logging.basicConfig(level=logging.DEBUG) solution = input("Enter solution json:\n") solution = json.loads(solution) path = os.path.join(utils.get_data_dir(), "qualifier/problem_{}.json".format(solution["problemId"])) with open(path) as fin: data = json.load(fin) g = game.Game(data, solution["seed"]) try: g.execute_string(solution["solution"]) except game.GameEnded as e: print("*" * 50) print(e) actual_history = "".join(g.history) supplied_history = solution["solution"] if actual_history != supplied_history: print("it seems game ended prematurely") print("moves that happened: {!r} ({})".format(actual_history, len(actual_history))) print("moves that were supplied: {!r} ({})".format(supplied_history, len(supplied_history))) else: print(g) print("Game have not ended yet")
def get_all_problem_instances(): paths = glob.glob(os.path.join(utils.get_data_dir(), 'qualifier/*.json')) for path in paths: with open(path) as fin: data = json.load(fin) for seed in data['sourceSeeds']: yield ProblemInstance(data, seed)
def load_example(): """ >>> load_example() 'hello, world!' """ with open(os.path.join(utils.get_data_dir(), 'example.txt')) as fin: return fin.read().rstrip()
def smoke_test_with_nonempty_board(self): path = os.path.join(utils.get_data_dir(), 'qualifier/problem_2.json') with open(path) as fin: data = json.load(fin) g = self.make_game(data, data['sourceSeeds'][0]) str(g)
def get_phrase_submission(phrase, problem=24): phrase = phrase.lower() path = os.path.join(utils.get_data_dir(), "qualifier/problem_%d.json" % problem) with open(path) as fin: data = json.load(fin) data["problemId"] = problem g = game.Game(data, data["sourceSeeds"][0]) c = "m" if phrase[0] == "l" else "l" c *= 5 try: g.execute_string(c + phrase) except (GameEnded, KeyError): return None c = "m" if phrase[-1] == "l" else "l" try: while True: g.execute_char(c) except GameEnded as e: solution = utils.gen_output(g, e) result = { "score": e.move_score, "powerScore": e.power_score, "tag": solution["tag"], "problemId": solution["problemId"], "seed": solution["seed"], "solution": solution["solution"], } return (solution, result)
def main(): args = parser.parse_args() game = gen_game(); text = json.dumps(game) if args.out_path: path = os.path.join(utils.get_data_dir(), args.out_path) with open(path) as f: f.write(text) else: print(text)
def main(): problem_id = 7 problem_file_name = 'problem_%d.json' % problem_id path = os.path.join(utils.get_data_dir(), 'qualifier', problem_file_name) game_data = read_json(path) d = {} for seed in game_data['sourceSeeds']: game = big_step_game.BigStepGame.from_json(game_data, seed) game, moves = phase_one(game) d[seed] = game print(game)
def main(): logging.basicConfig(level=logging.DEBUG) path = os.path.join(utils.get_data_dir(), 'qualifier/problem_4.json') with open(path) as fin: data = json.load(fin) #pprint.pprint(data) seeds = data['sourceSeeds'] g = Game(data, seeds[0]) try: g.execute_string('i5' * 100) except GameEnded as e: print(e)
def main(): results = [] for j in range(25): input_file = 'qualifier/problem_' + str(j) + '.json' path = os.path.join(utils.get_data_dir(), input_file) with open(path) as fin: data = json.load(fin) seeds = data['sourceSeeds'] for seed in seeds: #[31314]: #seeds: bsg = big_step_game.BigStepGame.from_json(data, seed) end_bsg, placments = phase_one(bsg) results.append((input_file, seed, end_bsg.move_score)) for result in sorted(results): print("{} - {} : {}".format(*result))
def main(): for j in range(0, 25): output_file = 'result__' + str(j) with open(output_file, "w") as fout: fout.write('') input_file = 'qualifier/problem_' + str(j) + '.json' path = os.path.join(utils.get_data_dir(), input_file) with open(path) as fin: data = json.load(fin) seeds = data['sourceSeeds'] bsg = big_step_game.BigStepGame.from_json(data, seeds[0]) end_bsg, placments = phase_one(bsg) total_score_depthest += end_bsg.move_score print ()
def main(): path = os.path.join(utils.get_data_dir(), 'qualifier/problem_4.json') with open(path) as fin: data = json.load(fin) m = re.match('.*/problem_(\\d+)\\.json', path) assert m data['problemId'] = int(m.group(1)) game = Game(data, data['sourceSeeds'][0]) ui = Gui(game, buttons=Gui.DEFAULT_BUTTONS_INTERACTIVE) while True: cmd = ui.wait_for_action() log.debug('{!r}'.format(cmd)) if cmd is None: log.debug('done') break game.execute_char(CHARS_BY_COMMAND[cmd][0]) ui.update(game)
def main(): paths = glob.glob(os.path.join(utils.get_data_dir(), 'qualifier/*.json')) print(paths) for path in paths: print() print('*' * 50) print(path) with open(path) as fin: data = json.load(fin) g = game.Game(data, data['sourceSeeds'][0]) print('Seeds (%d): %s' % ( len(data['sourceSeeds']), " ".join([str(seed) for seed in data['sourceSeeds']]))) print(g.show_units()) print(g)
def test_is_valid_placement(self): path = os.path.join(utils.get_data_dir(), 'qualifier/problem_3.json') with open(path) as fin: data = json.load(fin) units = CreateUnits(data) graph_builder = CreateGraphBuilder(data) g = game.Game(data, seed=0) eq_(len(units), len(g.units)) for index, unit in enumerate(units): graph_builder.SetCurrentUnit(unit) graph_builder.ComputeValidPlacements() u = g.units[index] for angle, _ in enumerate(u.even_shapes): for pivot_x in range(-g.width, 2 * g.width): for pivot_y in range(-g.height, 2 * g.height): can_place = graph_builder.IsValidPlacement(pivot_x, pivot_y, angle) p = game.Placement(u, pivot_x, pivot_y, angle) eq_(g.can_place(p), can_place)
def test_problem(problem_id): problem_id = problem_id problem_file_name = 'problem_%d.json' % problem_id path = os.path.join(utils.get_data_dir(), 'qualifier', problem_file_name) game_data = read_json(path) def play_dist1_games(): while True: seed = random.randint(0, 10 ** 9) game = big_step_game.BigStepGame.from_json(game_data, seed) game, moves = candidate_solver.phase_one(game) print('played candidate game %d with seed %d scored %d' % (problem_id, seed, game.move_score)) yield game.move_score def play_dist2_games(): while True: seed = random.randint(0, 10 ** 9) game = big_step_game.BigStepGame.from_json(game_data, seed) game, moves = bronze.phase_one(game) print('played production game %d with seed %d scored %d' % (problem_id, seed, game.move_score)) yield game.move_score return solved_cmp.compare_solver(play_dist1_games(), play_dist2_games())
def test_all_solution(): files = os.listdir(os.path.join(utils.get_data_dir(), 'golden_tests')) for make_game in [make_py_game, make_step_adapter_game]: for f in files: yield validate_solution, make_game, f
def main(): random.seed(42) args = parser.parse_args() path = os.path.join(utils.get_data_dir(), args.problem) with open(path) as fin: data = json.load(fin) m = re.match('.*/problem_(\\d+)\\.json', path) assert m data['problemId'] = int(m.group(1)) assert args.seed < len(data['sourceSeeds']), \ "There are only %d seeds" % len(data['sourceSeeds']) g = game.Game(data, data['sourceSeeds'][args.seed]) if args.moves: delay = 0.05 else: delay = 0 moves = itertools.chain(args.moves, gamepad()) try: term_attr = setup_term() if not args.no_gui: display(g) g.trace = [] if args.tracedir: trace(g) prev_states = collections.deque(maxlen=25) prev_states.append(copy.deepcopy(g)) for ch in moves: if ch == UNDO: if len(prev_states) > 1: g = prev_states[-1] prev_states.pop() else: prev_states.append(copy.deepcopy(g)) g.execute_char(ch) if args.tracedir: trace(g) if not args.no_gui: display(g) if args.delay: time.sleep(args.delay) except game.GameEnded as e: restore_term(term_attr) print('\n') print(e) solution = utils.gen_output(g, e) print('Solution: %s' % json.dumps([solution])) if args.tracedir: dump_trace(g, args.tracedir) if args.prompt_for_submit: print('\n') if read_yn('Do you want to submit this solution? [y/n] '): result = { 'score': e.move_score, 'powerScore': e.power_score, 'tag': solution['tag'], 'problemId': solution['problemId'], 'seed': solution['seed'], 'solution': solution['solution'] } from production.golden.utils import http_submit ok = http_submit(os.getenv('USER'), result, solution) if (200, 'Thanks!') == (ok.status_code, ok.text): print("Submission accepted") else: print("Submission rejected") finally: restore_term(term_attr)
def read_json(filename): path = os.path.join(utils.get_data_dir(), filename) with open(path) as f: return json.load(f)
def get_2x2_game(self): path = os.path.join(utils.get_data_dir(), 'test_problems/2x2.json') with open(path) as fin: data = json.load(fin) return self.make_game(data, seed=0)