Example #1
0
 def on_change(dialog):
     dialog.close()
     self.filename = dialog.filename
     # GameWidget(board=dialog.map, bots=dialog.bots)
     self.game = game.Game(board=core.Board(dialog.map),
                           bots=dialog.bots)
     # self.game.open()
     self.game.start()
Example #2
0
 def init(self, level=0, bw=core.EMPTY, token=None, board=None):
     self._reset()
     assert bool(token) == bool(board)
     assert (level == 0) == bool(board)
     self.level = level
     self.bw = bw
     self.token = token
     self.board = board or core.Board()
Example #3
0
def getBoardFromSequence(sequence):
	# Recreate a game board by replaying the sequence that leads to it
##########################################
	gameBoard=core.Board(8,16)
	tempSequence=sequence[:]

	while 1:
		if len(tempSequence)==0:
			return gameBoard	

		chosenBox=tempSequence.pop(0)
		core.makeMove(gameBoard,chosenBox)	
Example #4
0
def create(token):
    global _games
    assert token, token not in _games

    with _lock:
        board = core.Board()
        _games[token] = {
            Items.BOARD: board,
            Items.TURN: core.EMPTY,
            Items.LOCKED: False
        }
        return board
Example #5
0
    def __init__(self, wh):
        super(Window, self).__init__(resizable=True, width=wh[0], height=wh[1])
        self.batch = pyglet.graphics.Batch()
        self.board = core.Board(self, self.batch, wh)
        self.collisions = core.mouse.Collisions(self, self.board._sprites)
        self.input = core.lib.Input(self)

        self.input.register_hold([
            pyglet.window.key.UP, pyglet.window.key.DOWN,
            pyglet.window.key.RIGHT, pyglet.window.key.LEFT
        ], self.key)
        self.input.register_press(pyglet.window.key.F11, self.f_fullscreen)

        self.scroll_directions = [0, 0]
        self.autoscroll = False
        self.active = True
Example #6
0
    def do_GET(self):
        parsed_path = urlparse.urlparse(self.path)
        params = {}
        name_values = parsed_path.query.split(u'&')
        for name_value in name_values:
            index = name_value.find(u'=')
            name = name_value[:index]
            value = name_value[index + 1:]
            params[name] = value
        stones = [int(i) if i != "2" else -1 for i in params["stones"][:]]
        pos = int(params["pos"])
        stone = int(params["stone"])

        board = core.Board(stones=stones)
        board.move(pos, stone)
        pre_stones = "".join([str(i) if i >= 0 else "2" for i in board.stones])
        print pre_stones
        epos = player.move(board, -stone)
        print epos
        movable_pos = board.calc_movable_pos(stone)
        res = json.dumps(
            {
                "movables":
                "".join(
                    ["1" if i in movable_pos else "0" for i in xrange(0, 64)]),
                "stones":
                "".join([str(i) if i >= 0 else "2" for i in board.stones]),
                "pre_stones":
                pre_stones,
                "pos":
                epos,
                "gameover":
                board.check_gameover()
            },
            sort_keys=False,
            indent=4)

        self.send_response(200)
        self.send_header('Content-type', 'text/json')
        self.send_header('Access-Control-Allow-Origin', '*')
        self.end_headers()
        self.wfile.write(res)
        return
Example #7
0
    prefs['console_debug'] = console_debug

    # Load map
    world = core.World(prefs['map_path'])

    # Set players
    players = []
    available_players = agent.all_agents
    for p, n in zip(prefs['players'], prefs['players_names']):
        ag = available_players[p](n)
        ag.console_debug = console_debug and False
        players.append(ag)

    # Set board
    board = core.Board(world, players)
    board.setPreferences(prefs)

    #%% Draw the board
    # Draw game as a simple graph
    # Screen size and country box size
    WIDTH = prefs['screen_W']
    HEIGHT = prefs['screen_H']
    SQ_RADIUS = prefs['sq_radius']
    CONTINENT_BOX_PAD = prefs['continent_box_pad']

    # Position and size of info box (buttons and messages)
    INFO_BOX_X = prefs['info_box_x']
    INFO_BOX_Y = prefs['info_box_y']
    BUTTON_W = prefs['button_w']
    BUTTON_H = prefs['button_h']
Example #8
0
def play_games(nn_version,j,titer):
	"""
	Given a NN version, plays 1000 games of SPLT from start to finish and records their states, using a MCTS guided by nn_version.
	Saves the states in memory.

	Parameters:
	----------
	nn_version - NN object
		NN object that will be playing the game

	Returns:
	----------
	memory - deque object
		Effectively a list of states. Each state is a list of the form [gameBoard, search_probs, splits]
	"""
	global new_max_splits, memory, lck

	timedf_dict = {}

	for game_num in range(int(nn_config.NUM_SELFTRAIN_GAMES/cpu_count())):
		print("PLAYING GAME NUM "+str(game_num)+" ON CORE "+str(j))
		gameBoard = core.Board()
		core.makeMove(gameBoard,0) #makes first trivial split
		split = 1

		split_sequence = [0] #in case this ends up being a next best sequence
		states = [] #stores each state in the game
		
		nn_times = []
		splt_times = []
		total_times = []

		while len(gameBoard.getMoveOptions()) != 0:
			if split>=30: choose_best = True
			else: choose_best = False
			#print("-------------")
			print("Game "+str(game_num) + ", Split "+str(split)+" on core "+str(j))
			move, search_probs, nn_time, splt_time, rollout_time =\
				make_move_MCTS(gameBoard,nn_version,choose_best,split)

			nn_times.append(nn_time)
			splt_times.append(splt_time)
			total_times.append(rollout_time)

			split_sequence.append(move)
			gameState = np.squeeze(gameBoard.get_input_array())
			states.append([gameState,search_probs])

			core.makeMove(gameBoard,move)

			split += 1
		
		#add final split amount to state information, then save it in memory
		for state in states:
			state.append(split/1000)
		
		lck.acquire()
		memory.extend(states) #add the new states to memory

		if split >= new_max_splits: #save a sequence of new maximum length
			new_max_splits = split
			pth = os.path.join(os.getcwd(),args.run_name,"highest_splits.txt")
			with open(pth,'a') as f:
				f.write(str(split)+": " + str(split_sequence)+'\n')

		lck.release()

		game_df = pd.DataFrame(data={'nn_time':nn_times,'splt_time':splt_times,'total_time':total_times})
		timedf_dict[game_num] = game_df
	
	time_df = pd.concat(timedf_dict,axis=1)
	time_path = args.run_name+'/trainiter'+str(titer)+'_core'+str(j)+'_timedata_df.pkl'
	with open(time_path,'wb') as f:
		pickle.dump(time_df,f)