Ejemplo n.º 1
0
 def __int__(self):
     self.board = Board(10, 10)
     self.board.countNeighbords()
Ejemplo n.º 2
0
def test_available_moves():
    r = Records(8, [0, 0], Board(8))
    assert (r.available_moves(8,
                              [[3, 4, 'white'], [4, 4, 'black'],
                               [3, 3, 'black'], [4, 3, 'white']]) == [[0, 0],
                                                                      [0, 1],
                                                                      [0, 2],
                                                                      [0, 3],
                                                                      [0, 4],
                                                                      [0, 5],
                                                                      [0, 6],
                                                                      [0, 7],
                                                                      [1, 0],
                                                                      [1, 1],
                                                                      [1, 2],
                                                                      [1, 3],
                                                                      [1, 4],
                                                                      [1, 5],
                                                                      [1, 6],
                                                                      [1, 7],
                                                                      [2, 0],
                                                                      [2, 1],
                                                                      [2, 2],
                                                                      [2, 3],
                                                                      [2, 4],
                                                                      [2, 5],
                                                                      [2, 6],
                                                                      [2, 7],
                                                                      [3, 0],
                                                                      [3, 1],
                                                                      [3, 2],
                                                                      [3, 5],
                                                                      [3, 6],
                                                                      [3, 7],
                                                                      [4, 0],
                                                                      [4, 1],
                                                                      [4, 2],
                                                                      [4, 5],
                                                                      [4, 6],
                                                                      [4, 7],
                                                                      [5, 0],
                                                                      [5, 1],
                                                                      [5, 2],
                                                                      [5, 3],
                                                                      [5, 4],
                                                                      [5, 5],
                                                                      [5, 6],
                                                                      [5, 7],
                                                                      [6, 0],
                                                                      [6, 1],
                                                                      [6, 2],
                                                                      [6, 3],
                                                                      [6, 4],
                                                                      [6, 5],
                                                                      [6, 6],
                                                                      [6, 7],
                                                                      [7, 0],
                                                                      [7, 1],
                                                                      [7, 2],
                                                                      [7, 3],
                                                                      [7, 4],
                                                                      [7, 5],
                                                                      [7, 6],
                                                                      [7, 7]])
Ejemplo n.º 3
0
def test_removes_blanks():
    r = Records(8, [0, 0], Board(8))
    assert (r.removes_blanks([[], [1, 2]]) == [[1, 2]])
    assert (r.removes_blanks([[1, 2]]) == [[1, 2]])
Ejemplo n.º 4
0
class Main:

    board = Board()
    hmnPlayer = Player('Human')
    cmpPlayer = Player('Computer')
    ruleManager = RuleManager()
    ui = UI()

# Begin game
    def initializeGame(self):

        initInput = self.ui.promptBeginGame()

        if initInput == 1:
            self.ui.renderBoard(self.board.boardGraphic)
            self.beginHmnTurn(self.hmnPlayer)
            self.ui.renderBoard(self.board.boardGraphic)

        while True:
            self.beginCmpTurn(self.cmpPlayer)
            self.ui.computerMoveDialogue()
            self.ui.renderBoard(self.board.boardGraphic)
            self.beginHmnTurn(self.hmnPlayer)
            self.ui.renderBoard(self.board.boardGraphic)


# Second half could be abstracted out but I am out of time.
    def beginHmnTurn(self, player):
        currentRect = -1

        while True:
            column = int(self.ui.promptUserMove())

            if not self.board.checkColumnFull(column):
                currentRect = self.board.findColumnTopRect(column)
                self.board.fillCoordinate(currentRect, player)

                break
            else:
                self.ui.fullColumnPrompt()
        if self.ruleManager.locatePossibleConnects(self.board, player, currentRect):
            self.ui.renderBoard(self.board.boardGraphic)
            self.ui.promptEndGame(player)

# Almost identical to beginHmnTurn save for the fourth line of code
    def beginCmpTurn(self, player):
        currentRect = -1

        while True:
            column = randint(0,6)

            if not self.board.checkColumnFull(column):
                currentRect = self.board.findColumnTopRect(column)
                self.board.fillCoordinate(currentRect, player)

                break
            
    
        if self.ruleManager.locatePossibleConnects(self.board, player, currentRect):
            self.ui.renderBoard(self.board.boardGraphic)
            self.ui.promptEndGame(player)
Ejemplo n.º 5
0
 def setUp(self):
     self.my_board = Board()
Ejemplo n.º 6
0
 def __init__(self, name):
     self.name = name
     self.board = Board()
Ejemplo n.º 7
0
import numpy as np
import chainer
import chainerrl
from humanPlayer import HumanPlayer
from board import Board
from randomAct import RandomActor
from dqn import QFunction

if __name__ == "__main__":
    # ボードの準備
    board = Board()
    ra = RandomActor(board)

    # 環境と行動の次元数
    obs_size = 9
    n_actions = 9

    # Q-functionとオプティマイザのセットアップ
    q_func = QFunction(obs_size, n_actions)
    optimizer = chainer.optimizers.Adam(eps=1e-2)
    optimizer.setup(q_func)

    # 報酬の割引率
    gamma = 0.95

    # Epsilon-greedyを使ってたまに冒険。50000ステップでend_epsilonとなる
    explorer = chainerrl.explorers.LinearDecayEpsilonGreedy(
        start_epsilon=1.0,
        end_epsilon=0.3,
        decay_steps=50000,
        random_action_func=ra.random_action_func)
Ejemplo n.º 8
0
 def new(self):
     self.board = Board()
     drawBoard(self.win)
     self.run()
Ejemplo n.º 9
0
 def __init__(self):
     """create a new Game"""
     self.end = False
     self.board = Board()
Ejemplo n.º 10
0
# Standard Imports
import time

# 3rd Party Imports
import pyautogui as pg
import numpy as np

#from main import *
from board import Board

time.sleep(3)
board = Board((16, 16), 40)

window = board.find_window()

board.test_click()

# Game loop
while True:

    # Read board and construct score distribution
    board.read_board(window)

    board.take_turn()

    if len(board.bombs) == 40:
        break
Ejemplo n.º 11
0
board_params = inputs["board_params"]
path_board = board_params["path_board"]

# ---------------- Model -------------------------

print("Creating board")

world = World(path_board)

# Set players
pR1, pR2, pR3 = RandomAgent('Red'), RandomAgent('Blue'), RandomAgent('Green')
players = [pR1, pR2]
# Set board
prefs = board_params

board_orig = Board(world, players)
board_orig.setPreferences(prefs)

num_nodes = board_orig.world.map_graph.number_of_nodes()
num_edges = board_orig.world.map_graph.number_of_edges()

##### Create the net

print("Creating model")
net = GCN_risk(num_nodes, num_edges, model_args['board_input_dim'],
               model_args['global_input_dim'], model_args['hidden_global_dim'],
               model_args['num_global_layers'], model_args['hidden_conv_dim'],
               model_args['num_conv_layers'], model_args['hidden_pick_dim'],
               model_args['num_pick_layers'], model_args['out_pick_dim'],
               model_args['hidden_place_dim'], model_args['num_place_layers'],
               model_args['out_place_dim'], model_args['hidden_attack_dim'],
Ejemplo n.º 12
0
 def __init__(self):
     self.num_cols = 3
     self.num_rows = 3
     self.board = Board(self.num_rows, self.num_cols)
     self.picture = Picture(self.num_rows, self.num_cols)
Ejemplo n.º 13
0
from board import Board

if __name__ == '__main__':
    hill_climb = Board(5)
    hill_climb.fitness()
    hill_climb.hill_climb_solver()

Ejemplo n.º 14
0
        while game_continue:
            if not self.board.end and not self.need_to_choose_color() and  not self.this_turn_clickable():
                move = self.agent.get_move()
                if move is None:
                    self.show_result(winner=opponent(self.agent_color))
                    self.board.end = True
                else:
                    self.play_move(move)
            game_continue = self.wait_event()

    def this_turn_clickable(self):
        return self.agent is None or (self.agent_color is not None and self.agent_color != self.board.current_player)

    def play_move(self,move):
        player = self.board.play_stone(move)
        self.draw_stone(self.coord_to_pos(move), player)
        if self.board.end:
            self.show_result(self.board.winner)

def opponent(color):
    return Color.WHITE.value + Color.BLACK.value - color

if __name__ == '__main__':
    board = Board(11)
    agent = AlphaGomoku(board = board)
    game = Game(board=board,wait_click=True,agent=agent)
    game.run()
    # game_continue = True
    # while game_continue:
    #     game_continue = game.wait_event()
Ejemplo n.º 15
0
 def test_calls_super_in_init(self, init):
     bishop = Bishop(Board(), Square(4, 2), WHITE)
     assert init.called
Ejemplo n.º 16
0
from board import Board,Player,Point
from config import *
from client import client
import sys
Size = 5
ring = 5


gameDisplay = pygame.display.set_mode((display_size[Size],display_size[Size]))
gameDisplay.fill(backgroundColor)
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
crashed = False


board = Board(Size,ring,gameDisplay)

plays = []

playerExes = []
if len(sys.argv) == 2 or len(sys.argv) == 3:
	playerExes = sys.argv
	playerExes.pop(0)


def killPlayers():
	global plays
	for player in plays:
		player.closeChild()
	plays = []
	
Ejemplo n.º 17
0
 def reset(self):
     self.board = Board()
Ejemplo n.º 18
0
    def do_server_connection(self,
                             ai,
                             connection_index,
                             verbose=False,
                             size=18,
                             username=1,
                             opponent=2,
                             depth=5):
        """
        Connects to the server and plays a game from the point of one player
        :param ai: the heuristic to use
        :param connection_index: unique identifier used in logging output (all connections should have different indices)
        :param verbose: true for loud, false for silent
        :param size: size of the board to use
        :param username: username and password
        :param opponent: opponent name
        :param depth: the depth of the minimax search
        :return: (player number of this connection i.e. 1 or -1, winning player, final board state, remaining time)
        """
        log = (lambda x: print("Connection %d: [%s]" %
                               (connection_index, x))) if verbose else (
                                   lambda x: x)

        try:
            self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        except socket.error as err:
            print("Socket error: %s" % str(err))
            return None

        try:
            host_ip = socket.gethostbyname(ArtemisClient.HOST)
        except socket.gaierror:
            print("There was an error resolving the host")
            return None

        # connecting to the server
        self.s.connect((host_ip, ArtemisClient.PORT))
        version_message = self.get_message_from_socket()
        log("Connected to server version %s" % version_message.split("v")[-1])

        board = Board(size=size)
        my_player = 0
        game_num = -1
        winner = 0
        remaining_time = 180
        log("Using AI: " + str(ai))
        pool = Pool()

        if not verbose:
            print("Turn\tTime")

        last_response = None
        while winner == 0:
            message = self.get_message_from_socket()
            # time.sleep(1)
            messages = message.split('\n')
            log("message: " + str(messages))

            try:
                for message in messages:
                    if "?" in message:
                        # It is a request:
                        request = message[message.index("?") + 1:]

                        if request.startswith("Username"):
                            response = username

                        elif request.startswith("Password"):
                            response = username

                        elif request.startswith("Opponent"):
                            response = opponent

                        elif request.startswith("Move") or request.startswith(
                                "Remove"):
                            if "(" in message:
                                remaining_time = message[message.index("(") +
                                                         1:message.index(")")]
                                remaining_time = int(remaining_time) / 1000
                                log("Time Left: " + str(remaining_time))

                            h, move = parallel_minimax_pool(board,
                                                            my_player,
                                                            ai,
                                                            depth,
                                                            pool=pool)
                            response = ArtemisClient.my_move_to_server_move(
                                move, size)
                            if self.graphics:
                                self.graphics_obj.graphics_move(move)
                        else:
                            print("Unknown request: " + str(request))
                            continue

                        log("Response:" + response)
                        self.send_response_to_socket(response)
                        last_response = response
                    else:
                        if message.startswith("Move"):
                            server_move = message[4:]
                            my_move = ArtemisClient.server_move_to_my_move(
                                server_move, size)
                            log("Doing Move: " + str(my_move))
                            board.do_move(my_move)
                            if verbose:
                                board.print()
                            elif board.get_move_number() % 5 == 0:
                                print(board.get_move_number(),
                                      "\t",
                                      remaining_time,
                                      sep="")
                            if self.graphics:
                                self.graphics_obj.graphics_move(my_move)

                        elif message.startswith("Removed"):
                            server_move = str(message[8:])
                            my_move = ArtemisClient.server_move_to_my_move(
                                server_move, size)
                            log("Doing Initial Move: " + str(my_move))
                            board.do_move(my_move)
                            if self.graphics:
                                self.graphics_obj.graphics_move(my_move)

                        elif message.startswith("Player:"):
                            log("I won the coin toss" if message[7:] ==
                                "1" else "I lost the coin toss")

                        elif message.startswith("Color:"):
                            my_player = 1 if message[6:] == "BLACK" else -1
                            log("My player is " + str(my_player))

                        elif message.startswith("Game:"):
                            game_num = message[5:]
                            log("Game Number: " + str(game_num))

                        elif message.startswith(
                                "Opponent wins!") or message.startswith(
                                    "You win!"):
                            log(message)
                            winner = my_player if message.startswith(
                                "You") else -my_player
                            break
                        elif message.startswith("Error"):
                            raise ValueError(message + " | Last response: " +
                                             last_response)
                        else:
                            print("Unknown message: " + str(message))
                            raise ValueError(message, "Opponent Crashed")
            except Exception as e:
                print("Other messages: " + str(messages) + " " + str(e))
        self.s.close()
        pool.close()
        return my_player, winner, board, remaining_time
Ejemplo n.º 19
0
def learn(epsilon, gamma, alpha, nGames, getAvgs):
    tetrominos = createTetrominos()
    board = Board(5, 3)
    tShapeRows, tShapeCols = tuple(
        map(operator.add, tetrominos[0].shape.shape, (1, 1)))
    inputLayerDim = (board.nrows * board.ncols) + (tShapeRows * tShapeCols)
    actionsDim = board.ncols * 4

    # Tensorflow network initialisation
    tf.reset_default_graph()

    # These lines establish the feed-forward part of the network used
    # to choose actions
    inputs1 = tf.placeholder(shape=[1, inputLayerDim], dtype=tf.float32)
    W = tf.Variable(tf.zeros([inputLayerDim, actionsDim]))
    p = tf.placeholder(tf.bool, [1, actionsDim])
    Qout = tf.matmul(inputs1, W)
    invalidMoves = tf.constant(-100., shape=[1, actionsDim])
    validMoves = tf.where(
        p, Qout, invalidMoves)  # Replace invalid moves in Qout by -100
    predict = tf.argmax(validMoves, 1)

    # Below we obtain the loss by taking the sum of squares difference between
    # the target and prediction Q values.
    nextQ = tf.placeholder(shape=[1, actionsDim], dtype=tf.float32)
    loss = tf.reduce_sum(tf.square(nextQ - Qout))
    trainer = tf.train.GradientDescentOptimizer(learning_rate=0.1)
    updateModel = trainer.minimize(loss)

    init = tf.global_variables_initializer()

    # create lists to contain total rewards and steps per episode
    jList = []
    rList = []

    totalLinesCleared = 0
    col = 0
    rot = 0
    avgs = []
    s = []
    a = []
    allQ = []

    with tf.Session() as sess:
        sess.run(init)
        for i in range(nGames):
            print(i)
            board.reset()
            tetromino = util.randChoice(tetrominos)

            while (True):
                # Moves come in the format [columnIndex, rotationIndex]
                possibleMoves = tetromino.getPossibleMoves(board)

                # Game over condition
                if len(possibleMoves) == 0:
                    break

                if np.random.rand(1) < epsilon:
                    a = util.randChoice(possibleMoves)
                else:
                    boolMoves = [(x in possibleMoves)
                                 for x in range(actionsDim)]
                    s = util.networkState(board.board,
                                          tetromino.paddedRotations[0])
                    a, allQ = sess.run([predict, Qout],
                                       feed_dict={
                                           inputs1: s,
                                           p: [boolMoves]
                                       })
                    a = a[0]

                rot, col = divmod(a, board.ncols)

                # Perform action and collect reward
                r = board.act(tetromino, col, rot)

                # Random Tetromino for next state
                nextTetromino = util.randChoice(tetrominos)
                s1 = util.networkState(board.board,
                                       nextTetromino.paddedRotations[0])

                Q1 = sess.run(Qout, feed_dict={inputs1: s1})
                #Obtain maxQ' and set our target value for chosen action.
                maxQ1 = np.max(Q1)
                targetQ = allQ
                targetQ[0, a] = r + alpha * maxQ1

                #Train our network using target and predicted Q values
                _, W1 = sess.run([updateModel, W],
                                 feed_dict={
                                     inputs1: s,
                                     nextQ: targetQ
                                 })

                tetromino = nextTetromino

            totalLinesCleared += board.linesCleared

            if (i + 1) % 10 == 0:
                avgs.append(totalLinesCleared / (i + 1))

        # print("Lines cleared: ", board.linesCleared)
    avg = totalLinesCleared / nGames
    avgs.append(avg)
    # print("Average lines cleared:", avg)
    return avgs
Ejemplo n.º 20
0
 def test_populate_grid(self):
     board = Board(tk.Toplevel())
     board.populate_grid()
     self.assertNotEqual(board.squares, {})
Ejemplo n.º 21
0
 def test_init(self):
     board = Board(2, 3, 1)
     np.testing.assert_array_equal(
         board.abstractLayer,
         np.array([[1, 0, 0, 0, 1], [1, 0, 0, 0, 1], [1, 0, 0, 0, 1],
                   [1, 1, 1, 1, 1]]))
Ejemplo n.º 22
0
 def test_handle_piece_movimentation(self):
     board = Board(tk.Toplevel())
     k = board.squares[(0, 4)]['piece']
     k.selected = True
     board.handle_piece_movimentation(k, 0, 3, (0, 4))
     self.assertEqual(GameState.blackcoord, (0, 3))
Ejemplo n.º 23
0
 def __init__(self):
     self.panel = Board()
     self.human_player = Player(random.choice(Game.SIGNS))
     self.computer_player = Player(Game.SIGNS[0] if self.human_player.sign == Game.SIGNS[1] else Game.SIGNS[1])
Ejemplo n.º 24
0
 def test_clear_square(self):
     board = Board(tk.Toplevel())
     p = board.squares[(1, 1)]['piece']
     board.clear_square(p, p.get_possible_moves((1, 1), board.squares))
     self.assertEqual([], board.selsquare)
Ejemplo n.º 25
0
def test_score_counter():
    r = Records(2, [0, 0], Board(2))
    r.plays_used = [[0, 0, "white"], [0, 1, "black"], [1, 1, "white"]]
    assert (r.score_counter("white") == 2)
    assert (r.score_counter("black") == 1)
    assert (r.score_counter("red") == 0)
Ejemplo n.º 26
0
 def setUp(self) -> None:
     self.b = Board()
     self.p = HumanPlayer(self.b, 'test-name')
Ejemplo n.º 27
0
def test_moves_outcomes():
    r = Records(8, [0, 0], Board(8))
    r.color = "black"
    assert (r.moves_outcomes([], []) == [[]])
    assert (r.moves_outcomes([[1, 1]], [[3, 4, "white"]]) == [])
    assert (r.moves_outcomes([[1, 0]], [[3, 4, "white"]]) == [[3, 4, "white"]])
Ejemplo n.º 28
0
 def test_empty(self):
     self.assertEqual(Board().get_universal_id(),
                      Board().get_universal_id())
Ejemplo n.º 29
0
def test_can_play():
    r = Records(8, [0, 0], Board(8))
    r.legal_moves_avail = []
    assert (r.can_play() is False)
    r.legal_moves_avail = [[1, 2, "white"]]
    assert (r.can_play() is True)
Ejemplo n.º 30
0
 def start_game(self, player, size):
     self.players.append(player)
     self.board = Board(size)
     print 'beginning game as player %d' % player
     self.make_display()
     self.gui.start_game()