Exemplo n.º 1
0
 def test_get_live_neighbours(self):
     b = Board([[1] * 4] * 4)
     self.assertEqual(b.get_live_neighbours(0, 0), 3)
     self.assertEqual(b.get_live_neighbours(0, 1), 4)
     self.assertEqual(b.get_live_neighbours(1, 1), 8)
     self.assertEqual(b.get_live_neighbours(3, 3), 3)
     self.assertEqual(b.get_live_neighbours(3, 2), 4)
Exemplo n.º 2
0
 def test_upadate(self):
     b = Board([[1] * 4] * 4)
     b.update()
     print(b.render())
     print()
     b.update()
     print(b.render())
     return
Exemplo n.º 3
0
 def setUp(self):
     """
     initialize board
     :return:
     """
     self.set_variables()
     self.board = Board(self.x_max, self.y_max)
Exemplo n.º 4
0
def doMove(move, board):
    # blackList = board.list_black
    # redList = board.list_red
    blackList = []
    redList = []

    for piece in board.list_black:
        blackList.append(Piece(piece.type, piece.position))
    for piece in board.list_red:
        redList.append(Piece(piece.type, piece.position))

    piece, nextPos = move

    # Find piece in board
    thePiece = None
    for x in blackList:
        if x.type == piece.type and x.position == piece.position:
            thePiece = x

    if thePiece is None:
        for x in redList:
            if x.type == piece.type and x.position == piece.position:
                thePiece = x

    # Check if any piece at next pos
    theOtherPiece = None
    for x in blackList:
        if x.position == nextPos:
            theOtherPiece = x
            blackList.remove(theOtherPiece)

    if theOtherPiece is None:
        for x in redList:
            if x.position == nextPos:
                theOtherPiece = x
                redList.remove(theOtherPiece)

    # Move the Piece to next Pos
    thePiece.position = nextPos

    newState = Board(blackList, redList)

    return newState
Exemplo n.º 5
0
from main import Board, Chip
import time

if __name__ == "__main__":
    #'''
    board = Board([[0, 0, 0], [0, 0, 0], [0, 0, 0]])

    chip1 = Chip([[1]])
    chip2 = Chip([[0, 1], [1, 1]])
    chip3 = Chip([[1, 1, 1], [0, 0, 1], [0, 0, 1]])
    '''
    board = Board([
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0], 
        [0, 0, 0, 0, 0, 0, 0]
        ])

    chip1 = Chip([
        [1, 0], 
        [1, 1]
    ])
    chip2 = Chip([
        [1, 1, 1], 
        [1, 1, 1], 
        [1, 0, 0]
    ])
    chip3 = Chip([
Exemplo n.º 6
0
        cnt += 1
    # since theres an even number of squares go back one value
    cnt -= 1
# Add a nice boarder
next = pygame.Rect(97, 736, 174, 50)
prev = pygame.Rect(445, 736, 174, 50)
pygame.draw.rect(gameDisplay, black,
                 [10, 10, boardLength * size, boardLength * size], 1)
pygame.draw.rect(gameDisplay, button, next)
pygame.draw.rect(gameDisplay, button, prev)
gameDisplay.blit(text, textRect)
gameDisplay.blit(text1, textRect1)
pygame.display.update()

if __name__ == '__main__':
    board = Board()
    board.place_queen(0)
    solutions = board.boards
    solution = 0
    while not gameExit:
        for event in pygame.event.get():
            if event.type == pygame.MOUSEBUTTONDOWN:
                pos = event.pos
                if next.collidepoint(pos):
                    if solution < 91:
                        solution += 1
                if prev.collidepoint(pos):
                    if solution > -1:
                        solution -= 1
            if event.type == pygame.QUIT:
                gameExit = True
Exemplo n.º 7
0
state1 = [['X', 'X', 'X'], ['-', 'O', 'X'], ['-', '-', '-']]

state2 = [['X', 'O', 'X'], ['-', 'O', 'X'], ['-', 'O', '-']]

state3 = [['X', 'X', 'O'], ['X', 'O', 'X'], ['X', '-', '-']]

state4 = [['X', 'X', 'O'], ['-', 'O', 'X'], ['O', '-', '-']]

state5 = [['X', 'O', 'X'], ['-', 'O', 'X'], ['-', '-', 'X']]

state6 = [['-', 'O', 'X'], ['-', 'O', '-'], ['-', '-', 'X']]

state7 = [['O', 'O', 'X'], ['-', 'O', '-'], ['-', '-', 'O']]

state8 = [['O', 'O', 'X'], ['-', 'X', '-'], ['X', '-', 'O']]

state9 = [['O', 'O', 'X'], ['X', 'X', 'X'], ['X', '-', 'O']]

state10 = [['X', 'O', 'X'], ['O', 'O', 'O'], ['X', '-', '-']]

assert Board(state1).check_state() == X_WIN
assert Board(state2).check_state() == O_WIN
assert Board(state3).check_state() == X_WIN
assert Board(state4).check_state() == O_WIN
assert Board(state5).check_state() == X_WIN
assert Board(state6).check_state() == NO_WINNER
assert Board(state8).check_state() == X_WIN
assert Board(state9).check_state() == X_WIN
assert Board(state10).check_state() == O_WIN
Exemplo n.º 8
0
class BoardTest(unittest.TestCase):
    def setUp(self):
        self.board = Board()

    def test_get_empty_spots(self):
        grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", " "]]
        expected_empty = [[0, 0], [2, 0], [2, 1], [2, 2]]
        self.assertEqual(self.board.get_empty_spots(grid), expected_empty)

    def test_get_new_state_player_turn(self):
        grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", " "]]
        move = [2, 2]
        new_grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", "O"]]
        self.assertListEqual(self.board.get_new_state(grid, move), new_grid)

    def test_get_new_state_ai_turn(self):
        grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", " "]]
        move = [2, 2]
        new_grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", "X"]]
        self.board.player_turn, self.board.ai_turn = self.board.ai_turn, self.board.player_turn
        self.assertListEqual(self.board.get_new_state(grid, move), new_grid)

    def test_game_win_at_row(self):
        grid = [[" ", " ", " "], ["O", "O", "O"], [" ", " ", " "]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_game_win_at_col(self):
        grid = [[" ", "O", " "], [" ", "O", " "], [" ", "O", " "]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_game_win_at_main_diagonal(self):
        grid = [["O", " ", " "], [" ", "O", " "], [" ", " ", "O"]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_game_win_at_other_diagonal(self):
        grid = [[" ", " ", "O"], [" ", "O", " "], ["O", " ", " "]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_have_winner_winner_no_winner(self):
        grid = [[" ", " ", " "], ["X", "O", "O"], [" ", " ", " "]]
        self.assertFalse(self.board.game_win(grid, Board.PLAYER))

    def test_score_player_wins(self):
        grid = [[" ", " ", " "], ["O", "O", "O"], [" ", " ", " "]]
        self.assertEqual(self.board.score(grid, 3), 7)

    def test_score_ai_wins(self):
        grid = [[" ", " ", " "], ["X", "X", "X"], [" ", " ", " "]]
        self.assertEqual(self.board.score(grid, 3), -7)

    def test_score_nobody_wins(self):
        grid = [[" ", " ", " "], ["X", "O", "O"], [" ", " ", " "]]
        self.assertEqual(self.board.score(grid, 3), 0)

    def test_is_game_over_is_over(self):
        self.board.grid = [["O", "X", "O"], ["X", "O", "O"], ["X", "X", "O"]]
        self.assertTrue(self.board.is_game_over())

    def test_is_game_over_not_over(self):
        self.assertFalse(self.board.is_game_over())

    def test_minimax(self):
        self.assertListEqual(self.board.minimax(self.board.grid, 0), [0, 2])
Exemplo n.º 9
0
 def setUp(self):
     self.board = Board()
Exemplo n.º 10
0
import pygame
import random

from image_process import image
from main import Board

black = (0, 0, 0)
white = (255, 255, 255)
width = 4  #20, 8
height = 4  #20, 8
margin = 1  #5, 2

grid = Board([[random.randint(0, 1) for i in range(240)] for j in range(150)])
img = image('Resources/delhi_contrasting.jpg')
img.compress(240, 150)
img.convert_to_black()
#grid = Board(img.get_binary_arr())
#grid = Board([[0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,1,0,0,0,0,0,0],
#              [0,0,0,0,0,1,0,0,0,0,0],
#              [0,0,0,1,1,1,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0]])

pygame.init()
# width, height (25*40), (25*24) (each cell of width/height 25)
window_size = [1200, 750]  # ratio 1.6
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("GRID")
Exemplo n.º 11
0
        bestMove = bestTotalVal = bestVal = bestNextVal = 0
        for i in range(len(possibleMoves)):
            Rval = self.R.get((str(state), possibleMoves[i]), default=0)
            newState = np.negative(self.nextState(state, possibleMoves[i]))
            newMoves = possibleMoves[:i] + possibleMoves[i + 1:]
            nextVal = self.discountRate * self.bestQVal(
                newState, newMoves)  # Opponent's best move
            val = Rval - nextVal  # nextVal is opponent's Q, so we subtract it
            if val > bestval:
                bestMove, bestVal = i, val
        bestMove = possibleMoves[bestMove]
        currentVal = self.Q.get((str(state), bestMove), default=0)
        self.Q[str(state), bestMove] = currentVal + self.learningRate * (
            bestVal - currentVal)  # Update Q
        return bestMove


boardParams = main.boardParams
# boardParams = {"numPlayers" : 2, "size" : 3, "dimension" : 2, "limit" : 10}

agents = main.compileAgents(boardParams, numRand=1) + [Q(boardParams)]
train = Board(boardParams)  #, debugMode=True)
train.setAgents(agents)
trainWins = train.runGames(numGames=1000)
print trainWins.count(2)

test = Board(boardParams)  #, debugMode=True)
test.setAgents(agents)
testWins = test.runGames(numGames=100)
print testWins.count(2)
Exemplo n.º 12
0
def creating_board_tests():
    board = Board(5)
    board.add(WHITE_STONE, 1, 0)
    print(board.is_empty(1, 0))
    print(board.is_empty(0, 0))
Exemplo n.º 13
0
import random

from image_process import image
from main import Board

black = (0, 0, 0)
white = (255, 255, 255)
width = 2  #20, 8
height = 2  #20, 8
margin = 1  #5, 2

#grid = Board([[random.randint(0, 1) for i in range(240)] for j in range(1500)])
img = image('Resources/delhi_contrasting.jpg')
img.compress(420, 300)
img.convert_to_black()
grid = Board(img.get_binary_arr())
#grid = Board([[0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,1,0,0,0,0,0,0],
#              [0,0,0,0,0,1,0,0,0,0,0],
#              [0,0,0,1,1,1,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0],
#              [0,0,0,0,0,0,0,0,0,0,0]])

pygame.init()
# width, height (25*40), (25*24) (each cell of width/height 25)
#window_size = [1200, 750] # ratio 1.6
window_size = [1600, 1000]
screen = pygame.display.set_mode(window_size)
pygame.display.set_caption("GRID")
Exemplo n.º 14
0
 def setUp(self):
     self.board = Board()
Exemplo n.º 15
0
        if self.env is not None:
            self.board.assert_state(self.env)
        self.update_board()


if __name__ == "__main__":
    size = int(input())

    list_bomb = []
    list_flag = []
    for i in range(int(input())):
        coor = tuple(map(int, input().split(', ')))
        list_bomb.append(coor)
        list_flag.append(coor)

    board = Board(size, list_bomb)

    env = Environment()
    board.env = env
    env.load('minesweeper.clp')

    env.define_function(board.click_tile_env, 'click_tile')
    rule = """
    (defrule open-tile-program
        (aman ?x ?y)
        (not (siku ?x ?y))
        (not (open ?x ?y))
        (size ?n)
        (test (>= ?x 0))
        (test (< ?x ?n))
        (test (>= ?y 0))
Exemplo n.º 16
0
class BoardTest(unittest.TestCase):

    def setUp(self):
        self.board = Board()

    def test_get_empty_spots(self):
        grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", " "]]
        expected_empty = [[0, 0], [2, 0], [2, 1], [2, 2]]
        self.assertEqual(self.board.get_empty_spots(grid), expected_empty)

    def test_get_new_state_player_turn(self):
        grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", " "]]
        move = [2, 2]
        new_grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", "O"]]
        self.assertListEqual(self.board.get_new_state(grid, move), new_grid)

    def test_get_new_state_ai_turn(self):
        grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", " "]]
        move = [2, 2]
        new_grid = [[" ", "X", "O"], ["X", "O", "O"], [" ", " ", "X"]]
        self.board.player_turn, self.board.ai_turn = self.board.ai_turn, self.board.player_turn
        self.assertListEqual(self.board.get_new_state(grid, move), new_grid)

    def test_game_win_at_row(self):
        grid = [[" ", " ", " "], ["O", "O", "O"], [" ", " ", " "]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_game_win_at_col(self):
        grid = [[" ", "O", " "], [" ", "O", " "], [" ", "O", " "]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_game_win_at_main_diagonal(self):
        grid = [["O", " ", " "], [" ", "O", " "], [" ", " ", "O"]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_game_win_at_other_diagonal(self):
        grid = [[" ", " ", "O"], [" ", "O", " "], ["O", " ", " "]]
        self.assertTrue(self.board.game_win(grid, Board.PLAYER))

    def test_have_winner_winner_no_winner(self):
        grid = [[" ", " ", " "], ["X", "O", "O"], [" ", " ", " "]]
        self.assertFalse(self.board.game_win(grid, Board.PLAYER))

    def test_score_player_wins(self):
        grid = [[" ", " ", " "], ["O", "O", "O"], [" ", " ", " "]]
        self.assertEqual(self.board.score(grid, 3), 7)

    def test_score_ai_wins(self):
        grid = [[" ", " ", " "], ["X", "X", "X"], [" ", " ", " "]]
        self.assertEqual(self.board.score(grid, 3), -7)

    def test_score_nobody_wins(self):
        grid = [[" ", " ", " "], ["X", "O", "O"], [" ", " ", " "]]
        self.assertEqual(self.board.score(grid, 3), 0)

    def test_is_game_over_is_over(self):
        self.board.grid = [["O", "X", "O"], ["X", "O", "O"], ["X", "X", "O"]]
        self.assertTrue(self.board.is_game_over())

    def test_is_game_over_not_over(self):
        self.assertFalse(self.board.is_game_over())

    def test_minimax(self):
        self.assertListEqual(self.board.minimax(self.board.grid, 0), [0, 2])
Exemplo n.º 17
0
def main():
    '''Main function of the game'''

    # Instantiates the game
    user_board = Board()
    ai = AI()
    draw_header('Place your ships. Use space to rotate a ship.')
    draw_board(ai.board, user_board)

    run = True
    while run:  # Overall pygame loop
        # Loop for the user to place ships
        while len(ships) > 0:
            x, y = pygame.mouse.get_pos()

            if x > SQUARESIZE * 12 and y > 5 * SQUARESIZE:
                x -= SQUARESIZE * 12
                y -= SQUARESIZE * 5

                x = math.ceil(x / SQUARESIZE)
                y = math.ceil(y / SQUARESIZE)

                draw_ship(ships[0], (x, y), user_board)

            for event in pygame.event.get():
                draw_board(ai.board, user_board)
                if event.type == pygame.QUIT:
                    sys.exit()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos

                    if x > SQUARESIZE * 12 and y > 5 * SQUARESIZE:
                        x -= SQUARESIZE * 12
                        y -= 5 * SQUARESIZE

                        x = math.ceil(x / SQUARESIZE)
                        y = math.ceil(y / SQUARESIZE)

                        is_placed = user_board.place_ship(
                            ships[0]['name'], ships[0]['length'], (x, y),
                            ships[0]['vertical'])
                        if is_placed:
                            ships.pop(0)

                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_SPACE:
                        ships[0]['vertical'] = not ships[0]['vertical']

        winner = False
        while not winner:  # Gameplay loop
            draw_board(ai.board, user_board)
            draw_header('Your turn, select a set of the enemy\'s coordinates.')

            for event in pygame.event.get():

                if event.type == pygame.QUIT:
                    sys.exit()

                if event.type == pygame.MOUSEBUTTONDOWN:
                    x, y = event.pos

                    if x < SQUARESIZE * 12 and x > SQUARESIZE and y > SQUARESIZE * 5:
                        x -= SQUARESIZE
                        y -= SQUARESIZE * 5

                        x = math.ceil(x / SQUARESIZE)
                        y = math.ceil(y / SQUARESIZE)

                        result = ai.board.attempt_coordinates((x, y), 'User')
                        draw_board(ai.board, user_board)
                        draw_header(result)

                        if ai.board.is_loser():
                            pygame.time.wait(1250)
                            draw_header(
                                'Congratulations, you have decimated the enemy\'s fleet!'
                            )
                            pygame.time.wait(2000)
                            winner = True
                            run = False
                        else:
                            print("\nEnemy's board:")
                            pprint.pprint(ai.board.display)

                            pygame.time.wait(1250)
                            result = ai.attempt_target(user_board)
                            draw_board(ai.board, user_board)
                            draw_header(result)

                            if user_board.is_loser():
                                pygame.time.wait(1250)
                                draw_header(
                                    'The enemy has decimated your fleet.')
                                pygame.time.wait(2000)
                                winner = True
                                run = False

                            print("\nOwn board:")
                            pprint.pprint(user_board.display)
                            print("\n")

                            pygame.time.wait(1250)
Exemplo n.º 18
0
    def test_blank_board_setup_white(self):
            """
            This tests that the white pieces on the board are setup correctly.
            """

            # Create a standard board.
            board = Board()

            # Check all the black pieces.
            self.assertIsInstance(board.get(0, 7), Rook)
            self.assertEqual(board.get(0, 7).player, "white")

            self.assertIsInstance(board.get(1, 7), Knight)
            self.assertEqual(board.get(1, 7).player, "white")

            self.assertIsInstance(board.get(2, 7), Bishop)
            self.assertEqual(board.get(2, 7).player, "white")

            self.assertIsInstance(board.get(3, 7), Queen)
            self.assertEqual(board.get(3, 7).player, "white")

            self.assertIsInstance(board.get(4, 7), King)
            self.assertEqual(board.get(4, 7).player, "white")

            self.assertIsInstance(board.get(5, 7), Bishop)
            self.assertEqual(board.get(5, 7).player, "white")

            self.assertIsInstance(board.get(6, 7), Knight)
            self.assertEqual(board.get(6, 7).player, "white")

            self.assertIsInstance(board.get(7, 7), Rook)
            self.assertEqual(board.get(7, 7).player, "white")

            for x in range(8):
                self.assertIsInstance(board.get(x, 6), Pawn)
                self.assertEqual(board.get(x, 6).player, "white")
Exemplo n.º 19
0

def loadboards():
    boards = {}
    with open('boards.bds', 'r') as infile:
        for line in infile.readlines():
            readline = line.split('|')
            boards[readline[0]] = readline[1].replace('\n', '')
    return boards


end = False
board = [0, 0, 0,
         0, 0, 0,
         0, 0, 0]
b = Board(barray=board)
boards = loadboards()

pos = boards[b.printversion]
b.board[int(pos)] = 1
b.refresh()
print(b)
print('----------------------')

while not end:
    if b.full and b.winner is 0:
        print('Draw!')
        end = True
    else:
        n = int(input('Enter field: '))
        if n > 8: