Example #1
0
 def setUp(self):
     self.player = Player("player")
     self.player.history.append(
         Action.put(1, 1, Position(Piece("a"), Player("a"))))
     self.player.history.append(
         Action.put(1, 2, Position(Piece("a"), Player("a"))))
     self.player.history.append(Action.see(1, 1))
 def __areFiveConsecutiveWithOneEmpty(self, x, y, direction, value):
     """
     Checks whether there is a line of values value starting from (x, y) in direction of length 5 having a empty space.
     """
     moves = 5
     piecesWithValue = 0
     neutralPieces = 0
     while moves > 0:
         if x < 0 or x > 14 or y < 0 or y > 14:
             return False
         if value == 0:
             if Piece(x, y) in self.userPiecesRepository.getList():
                 piecesWithValue += 1
             elif Piece(x, y) not in self.aiPiecesRepository.getList():
                 neutralPieces += 1
         else:
             if Piece(x, y) in self.aiPiecesRepository.getList():
                 piecesWithValue += 1
             elif Piece(x, y) not in self.userPiecesRepository.getList():
                 neutralPieces += 1
         x += self.directionX[direction]
         y += self.directionY[direction]
         moves -= 1
     if piecesWithValue == 4 and neutralPieces == 1:
         return True
     else:
         return False
 def test_add(self):
     repositoryMock = Repository()
     repositoryMock.add(5)
     repositoryMock.add(Piece(5, 7))
     self.assertEqual(repositoryMock.getList(), [5, Piece(5, 7)])
     with self.assertRaises(RepositoryException):
         repositoryMock.add(5)
 def test_isGameOver(self):
     userPiecesRepository = Repository()
     userPiecesRepository.add(Piece(0, 0))
     userPiecesRepository.add(Piece(1, 1))
     userPiecesRepository.add(Piece(2, 2))
     userPiecesRepository.add(Piece(3, 3))
     userPiecesRepository.add(Piece(4, 4))
     aiPiecesRepository = Repository()
     validator = Validator(userPiecesRepository, aiPiecesRepository)
     userPiecesService = UserService(userPiecesRepository, validator)
     aiPiecesService = AIService(aiPiecesRepository, userPiecesRepository,
                                 validator)
     gameService = GameService(userPiecesService, aiPiecesService)
     self.assertEqual(gameService.isGameOver(), True)
     userPiecesRepository = Repository()
     userPiecesRepository.add(Piece(0, 0))
     userPiecesRepository.add(Piece(1, 1))
     userPiecesRepository.add(Piece(3, 3))
     userPiecesRepository.add(Piece(4, 4))
     aiPiecesRepository = Repository()
     validator = Validator(userPiecesRepository, aiPiecesRepository)
     userPiecesService = UserService(userPiecesRepository, validator)
     aiPiecesService = AIService(aiPiecesRepository, userPiecesRepository,
                                 validator)
     gameService = GameService(userPiecesService, aiPiecesService)
     self.assertEqual(gameService.isGameOver(), False)
 def __emptyPlaceInLine(self, startX, startY, direction):
     """
     Find the empty place in line of 5 from (startX, startY) in direction.
     """
     while True:
         if Piece(startX, startY) not in self.userPiecesRepository.getList(
         ) and Piece(startX,
                     startY) not in self.aiPiecesRepository.getList():
             return startX, startY
         startX += self.directionX[direction]
         startY += self.directionY[direction]
 def test_addPieceToBlock(self):
     userPiecesRepository = Repository()
     userPiecesRepository.add(Piece(0, 0))
     userPiecesRepository.add(Piece(1, 1))
     userPiecesRepository.add(Piece(2, 2))
     userPiecesRepository.add(Piece(3, 3))
     aiPiecesRepository = Repository()
     validator = Validator(userPiecesRepository, aiPiecesRepository)
     aiPiecesService = AIService(aiPiecesRepository, userPiecesRepository,
                                 validator)
     aiPiecesService.addPiece()
     self.assertEqual(aiPiecesService.getList(), [Piece(4, 4)])
 def test_addBestPlayPiece(self):
     userPiecesRepository = Repository()
     aiPiecesRepository = Repository()
     aiPiecesRepository.add(Piece(0, 0))
     aiPiecesRepository.add(Piece(1, 1))
     validator = Validator(userPiecesRepository, aiPiecesRepository)
     aiPiecesService = AIService(aiPiecesRepository, userPiecesRepository,
                                 validator)
     aiPiecesService.addPiece()
     self.assertEqual(
         aiPiecesService.getList(),
         [Piece(0, 0), Piece(1, 1), Piece(2, 2)])
    def __moveBestPiece(self):
        """
        Move piece following the longest line already done.
        """
        if self.aiPiecesRepository.getList():
            piecesSorted = self.aiPiecesRepository.getList()
            self.__sortListByObjectAttribute(
                piecesSorted, lambda a, b: True
                if a < b else False, lambda pieceTemporary: self.
                __maximumLengthFromPiece(pieceTemporary)[0])
            for piece in piecesSorted:
                maximumDirection = self.__maximumLengthFromPiece(piece)[1]
                newX = piece.getX() + self.directionX[maximumDirection]
                newY = piece.getY() + self.directionY[maximumDirection]
                if self.validator.isValid(Piece(newX, newY)):
                    self.aiPiecesRepository.add(Piece(newX, newY))
                    return
                newX = piece.getX() - self.directionX[maximumDirection]
                newY = piece.getY() - self.directionY[maximumDirection]
                if self.validator.isValid(Piece(newX, newY)):
                    self.aiPiecesRepository.add(Piece(newX, newY))
                    return

            for piece in piecesSorted:
                for direction in range(0, 8):
                    newX = piece.getX() + self.directionX[direction]
                    newY = piece.getY() + self.directionY[direction]
                    if self.validator.isValid(Piece(newX, newY)):
                        self.aiPiecesRepository.add(Piece(newX, newY))
                        return
        xPool, yPool = self.__generatePools()
        x = random.choice(xPool)
        y = random.choice(yPool)
        self.aiPiecesRepository.add(Piece(x, y))
Example #9
0
 def addPiece(self, x, y):
     """
     Add Piece(x, y) if not already on board.
     """
     newPiece = Piece(x, y)
     if self.validator.isValid(newPiece):
         self.userPiecesRepository.add(newPiece)
     else:
         raise ValidException
 def winner(self):
     """
     Return the winner.
     """
     for i in range(0, 15):
         for j in range(0, 15):
             value = None
             pool = None
             if Piece(i, j) in self.userPiecesService.getList():
                 value = 0
                 pool = self.userPiecesService.getList()
             if Piece(i, j) in self.aiPiecesService.getList():
                 value = 1
                 pool = self.aiPiecesService.getList()
             if value is not None:
                 if self.__isLineFromPoint(i, j, pool):
                     return value
     return None
 def __generatePools(self):
     """
     Generate the pools of available empty positions.1
     """
     xPool = []
     yPool = []
     for i in range(0, 15):
         for j in range(0, 15):
             if self.validator.isValid(Piece(i, j)):
                 xPool.append(i)
                 yPool.append(j)
     return xPool, yPool
 def __moveToWin(self):
     """
     Put piece to complete 5 length row.
     """
     for i in range(0, 15):
         for j in range(0, 15):
             for k in range(0, 8):
                 if self.__areFiveConsecutiveWithOneEmpty(i, j, k, 1):
                     self.aiPiecesRepository.add(
                         Piece(
                             self.__emptyPlaceInLine(i, j, k)[0],
                             self.__emptyPlaceInLine(i, j, k)[1]))
                     return
 def __blockUserWin(self):
     """
     Block user win by placing piece to block row.
     """
     for i in range(0, 15):
         for j in range(0, 15):
             for k in range(0, 8):
                 if self.__areFiveConsecutiveWithOneEmpty(i, j, k, 0):
                     self.aiPiecesRepository.add(
                         Piece(
                             self.__emptyPlaceInLine(i, j, k)[0],
                             self.__emptyPlaceInLine(i, j, k)[1]))
                     return
 def __maximumLengthFromPiece(self, piece):
     """
     Find the maximum line that can be done starting from piece.
     """
     maximumLength = 0
     directionOfMaximum = None
     startX = piece.getX()
     startY = piece.getY()
     count = 0
     for k in range(0, 8):
         while Piece(startX, startY) in self.aiPiecesRepository.getList():
             count += 1
             startX += self.directionX[k]
             startY += self.directionY[k]
         if count > maximumLength:
             maximumLength = count
             directionOfMaximum = k
     return maximumLength, directionOfMaximum
 def test_addPiece(self):
     repository1 = Repository()
     repository1.add(Piece(0, 0))
     repository1.add(Piece(1, 1))
     repository2 = Repository()
     repository2.add(Piece(13, 13))
     repository2.add(Piece(14, 14))
     validator = Validator(repository1, repository2)
     userService = UserService(repository1, validator)
     userService.addPiece(5, 5)
     self.assertEqual(
         userService.getList(),
         [Piece(0, 0), Piece(1, 1), Piece(5, 5)])
     with self.assertRaises(ValidException):
         userService.addPiece(0, 0)
     with self.assertRaises(ValidException):
         userService.addPiece(13, 13)
     with self.assertRaises(ValidException):
         userService.addPiece(-1, 0)
     with self.assertRaises(ValidException):
         userService.addPiece(0, 199)
 def __isLineFromPoint(self, i, j, pool):
     """
     Checks whether line starting from Piece(i, j) is a winner.
     """
     directionX = [-1, -1, -1, 0, 1, 1, 1, 0]
     directionY = [-1, 0, 1, 1, 1, 0, -1, -1]
     for k in range(0, 8):
         temporaryI = i
         temporaryJ = j
         consecutivePoints = 1
         consecutive = True
         inside = True
         while inside and consecutive and consecutivePoints != 5:
             temporaryI += directionX[k]
             temporaryJ += directionY[k]
             if 0 > temporaryI or 0 > temporaryJ or 14 < temporaryI or 14 < temporaryJ:
                 inside = False
             elif not Piece(temporaryI, temporaryJ) in pool:
                 consecutive = False
             else:
                 consecutivePoints += 1
         if consecutivePoints == 5:
             return True
     return False
Example #17
0
from flask import Flask
from src.BoardSystem import BoardSystem
from src.Piece import Piece
import csv

app = Flask(__name__)
app.secret_key = 'very-secret-123'

# Board setup
board = BoardSystem()

# input Piece details
with open('pieces/pieces.csv') as f:
    reader = csv.reader(f)
    for row in reader:
        name = row[0]
        species = [row[1], None if row[2] == 'None' else row[2]]
        clas = row[3]
        cost = int(row[4])
        tier = int(row[5])
        board.add_piece(Piece(name, species, clas, cost, tier))
Example #18
0
 def isValidMove(self, x, y):
     return self.validator.isValid(Piece(x, y))
Example #19
0
def main():
    global win
    locked_positions = {}  # (x,y):(255,0,0)

    # init grid
    grid = PlayField.create_grid()  #matrix that contains (r,g,b)
    win = PlayField.draw_window(win, grid, 0)
    current_piece = Piece(Utils.INIT_COL, Utils.INIT_ROW,
                          random.choice(Utils.SHAPES))
    next_piece = Piece(Utils.INIT_COL, Utils.INIT_ROW,
                       random.choice(Utils.SHAPES))
    change_piece = False
    fall_time = 0
    score = 0

    while Utils.run:
        grid = PlayField.create_grid(locked_positions)
        fall_time += clock.get_rawtime()
        clock.tick()
        # Piece goes down anyway
        if fall_time / 1000 >= Utils.FALL_SPEED:
            fall_time = 0
            current_piece.row += 1
            #Check if the piece is blocked (if yes, the row can't be incremented) and we chage piece
            if not (current_piece.is_in_valid_space(grid)
                    ) and current_piece.row > 0:
                current_piece.row -= 1  #avoid piece to across other pieces
                change_piece = True

        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                Utils.run = False
                pygame.display.quit()
                quit()

            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT:
                    current_piece.shift_left(grid)

                if event.key == pygame.K_RIGHT:
                    current_piece.shift_right(grid)

                if event.key == pygame.K_UP:
                    current_piece.rotate(grid)

                if event.key == pygame.K_DOWN:
                    current_piece.go_down(grid)

        # add color of piece to the grid for drawing
        grid = current_piece.update_grid(grid)
        shape_pos = current_piece.convert_shape_format()

        # if piece hit other pieces and is blocked
        if change_piece:
            for pos in shape_pos:  #shape pos are tuple (x,y) for every block
                p = (pos[1], pos[0])
                locked_positions[
                    p] = current_piece.color  #update locked positions
            #swap piece
            current_piece = next_piece
            next_piece = Piece(Utils.INIT_COL, Utils.INIT_ROW,
                               random.choice(Utils.SHAPES))
            change_piece = False
            locked_positions, inc_score = PlayField.clear_rows(
                grid, locked_positions)
            score += inc_score

        #Update display
        win = PlayField.draw_window(win, grid, score)
        PlayField.draw_next_shape(next_piece, win)  #piece on the right side
        pygame.display.update()

        if PlayField.check_lost(locked_positions):
            print("check_lost TRUE")
            Utils.run = False
            pygame.display.update()
            #pygame.time.delay(1500)
            Utils.run = False
Example #20
0
 def setUp(self):
     self.board = Board("go")
     self.board.put(1, 1, Piece("white"))
Example #21
0
 def test_put(self):
     self.assertEqual(Action.put(1, 1, Position(Piece("a"), Player("a"))),
                      "put: (%d, %d, %s)" % (1, 1, "a"))
 def test_isValid(self):
     repository1 = Repository()
     repository1.add(Piece(0, 0))
     repository1.add(Piece(1, 1))
     repository2 = Repository()
     repository2.add(Piece(13, 13))
     repository2.add(Piece(14, 14))
     validator = Validator(repository1, repository2)
     self.assertTrue(validator.isValid(Piece(3, 3)))
     self.assertTrue(validator.isValid(Piece(3, 8)))
     self.assertFalse(validator.isValid(Piece(-1, 5)))
     self.assertFalse(validator.isValid(Piece(-1, -9)))
     self.assertFalse(validator.isValid(Piece(21, 5)))
     self.assertFalse(validator.isValid(Piece(1, 55)))
     self.assertFalse(validator.isValid(Piece(0, 0)))
     self.assertFalse(validator.isValid(Piece(14, 14)))
Example #23
0
 def setUp(self):
     self.game = Game(Player("a"), Player("b"), Board("go"))
     self.game.player1.record(
         Action.put(1, 1, Position(Piece("a"), Player("a"))))
     self.game.player1.record(Action.see(1, 1))