def passageOuest(plateau, ligne, colonne): """ teste si on peut passer de la case à la case adjacente vers l'ouest paramètres: plateau le plateau considéré ligne le numéro de la ligne (en commençant par 0) colonne le numéro de la colonne (en commençant par 0) résultat: un booléen indiquant si le passage est possible ou non """ if colonne > 0: num_pieceA = getCategorieP(plateau, ligne, colonne) pieceA = piece.Piece(0) if num_pieceA != None: if num_pieceA > 0: liste_pieces = getPieces(plateau) pieceA = liste_pieces[num_pieceA] if num_pieceA == case.COULOIR or num_pieceA < 0 or ( entree.OUEST, ligne, colonne) in piece.getEntreesDirection( pieceA, entree.OUEST): num_pieceO = getCategorieP(plateau, ligne, colonne - 1) pieceO = piece.Piece(0) if num_pieceO != None: if num_pieceO > 0: liste_pieces = getPieces(plateau) pieceO = liste_pieces[num_pieceO] if num_pieceO == case.COULOIR or num_pieceO < 0 or ( entree.EST, ligne, colonne - 1) in piece.getEntreesDirection( pieceO, entree.EST): return True
def passageSud(plateau, ligne, colonne): """ teste si on peut passer de la case à la case adjacente vers le sud paramètres: plateau le plateau considéré ligne le numéro de la ligne (en commençant par 0) colonne le numéro de la colonne (en commençant par 0) résultat: un booléen indiquant si le passage est possible ou non """ if ligne < getNbLignesP(plateau) - 1: num_pieceA = getCategorieP(plateau, ligne, colonne) pieceA = piece.Piece(0) if num_pieceA != None: if num_pieceA > 0: liste_pieces = getPieces(plateau) pieceA = liste_pieces[num_pieceA] if num_pieceA == case.COULOIR or num_pieceA < 0 or ( entree.SUD, ligne, colonne) in piece.getEntreesDirection( pieceA, entree.SUD): num_pieceS = getCategorieP(plateau, ligne + 1, colonne) pieceS = piece.Piece(0) if num_pieceS != None: if num_pieceS > 0: liste_pieces = getPieces(plateau) pieceS = liste_pieces[num_pieceS] if num_pieceS == case.COULOIR or num_pieceS < 0 or ( entree.NORD, ligne + 1, colonne) in piece.getEntreesDirection( pieceS, entree.NORD): return True
def Loop(display_Screen, logo, MainGameGrid, preview_grid, game_piece, preview_piece, font, m): global Khalaas global Shuru while not Khalaas: display_Screen.fill(ORANGE) display_Screen.blit(logo, LOGO_POS) MainGameGrid.display_text(MainGameGrid.small_text, "Score: {}".format(MainGameGrid.get_score()), (20, 150), display_Screen) MainGameGrid.display_text(MainGameGrid.small_text, "Level: {}".format(MainGameGrid.get_level()), (1400, 150), display_Screen) for event in pygame.event.get(): if event.type == pygame.QUIT: Quit() if event.type == pygame.KEYDOWN: # if event.key == pygame.K_a: # game_piece.leftMove() # if event.key == pygame.K_d: # game_piece.rightMove() if event.key == pygame.K_q: Khalaas = TRUE if event.key == pygame.K_SPACE: game_piece.falldown_fast() if event.key == pygame.K_s: game_piece.Clockwise_turn() if event.key == pygame.K_p: MainGameGrid.pause(display_Screen, font, logo, m) keys = pygame.key.get_pressed() if (keys[pygame.K_a]): game_piece.leftMove() if (keys[pygame.K_d]): game_piece.rightMove() if (keys[pygame.K_SPACE]): game_piece.falldown_fast() drop_loop = game_piece.dropdown() if (drop_loop == finished1): if (MainGameGrid.is_game_over(display_Screen, font, m)): Khalaas = TRUE game_piece = piece.Piece(MainGameGrid, preview_piece.get_type()) preview_piece.RESET_cells() preview_piece = piece.Piece(preview_grid, upper_left=[1, 0]) preview_grid.draw_cells(display_Screen) MainGameGrid.draw_cells(display_Screen) clock.tick(8 + MainGameGrid.get_score() / 100) pygame.display.update()
def hold_piece(self): """ Switch the active piece and the held piece, returning both to default coordinates and rotation """ self.held_piece, self.active_piece = self.active_piece, self.held_piece if self.active_piece: self.active_piece = piece.Piece(self.active_piece.name) self.held_piece = piece.Piece(self.held_piece.name) self.held_piece.x = -6 self.held_piece.y = 18
def get_valid_available_coordinates(self, piece): """ idk yet :param piece: :return: """ row1 = piece.row col1 = piece.col color = piece.color piece = self.grid[row1][col1].piece available_coordinates = piece.get_available_coordinates(self) # If there is no king, all available coordinates are valid one if not self._has_king: return available_coordinates # Build a valid available coordinates list valid_available_coordinates = [] # For every available move in coordinate... for coordinate in available_coordinates: # Copy grid and evaluate new position previous_grid = self._copy_grid() row2 = coordinate[0] col2 = coordinate[1] # Grab Squares start_square = self.grid[row1][col1] end_square = self.grid[coordinate[0]][col2] # Use Square's set_piece rather than self's because self's variables should not be updated end_square.set_piece(start_square.piece) if len(coordinate) != 2 and coordinate[-1] == 'is_en_passant': self.grid[row1][col2].set_piece(PIECE.Piece()) start_square.set_piece(PIECE.Piece()) # Are we in Check? if end_square.piece.name == 'King': check = self.is_coordinate_in_check(color, row2, col2) else: if color == "white": check = self.is_coordinate_in_check(color, self.white_king_position[0], self.white_king_position[1]) else: check = self.is_coordinate_in_check(color, self.black_king_position[0], self.black_king_position[1]) if not check: valid_available_coordinates.append(coordinate) self.grid = previous_grid return valid_available_coordinates
def __init__(self, char): self.__num_wins = Player.START self.__spots_open = [1, 2, 3, 4, 5, 6, 7, 8, 9] self.__spots_used = [] self.__piece1 = piece.Piece(char) self.__piece2 = piece.Piece(char) self.__piece3 = piece.Piece(char) self.__piece4 = piece.Piece(char) self.__piece5 = piece.Piece(char) self.__pieces_left = [self.__piece1, self.__piece2, self.__piece3, \ self.__piece4, self.__piece5] self.__pieces_used = [] self.__status = True
def test_get_edge_eq(self): """ Unit test to check that edges are properly specified """ piece_spec = [["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["G", "T"]] piece1 = pc.Piece(piece_spec) piece2 = pc.Piece(piece_spec) self.assertTrue(piece1 == piece2)
def LoadPieceObjects(self): self.pieces = [] i = 0 lineCounter = 0 for line in self.letterPieces: self.pieces.append([]) for letter in line: envIndex = 0 if letter == "T": # Tour envIndex = 0 if letter == "C": # cavalier envIndex = 1 if letter == "F": # fou envIndex = 2 if letter == "Q": # Queen envIndex = 3 if letter == "K": # King envIndex = 4 if letter == "P": # pion envIndex = 5 if letter == "t": # opponent's Tour envIndex = 6 if letter == "c": # opponent's cavalier envIndex = 7 if letter == "f": # opponent's fou envIndex = 8 if letter == "q": # opponent's Queen envIndex = 9 if letter == "k": # opponent's King envIndex = 10 if letter == "p": # opponent's pion envIndex = 11 envVal = self.envPiece[envIndex] if i < 16 and letter != ".": newPiece = piece.Piece(letter, 0, envVal) self.pieces[lineCounter].append(newPiece) if i >= 16 and letter != ".": newPiece = piece.Piece(letter, 1, envVal) self.pieces[lineCounter].append(newPiece) if letter == ".": newPiece = piece.Piece(".", -1, 0) self.pieces[lineCounter].append(newPiece) i = i + 1 lineCounter = lineCounter + 1 print(self.Board())
def testTree(self): print() x = deque([ piece.Piece(1, (0, 0)), piece.Piece(3, (2, 2)), piece.Piece(5, (1, 1)), piece.Piece(7, (4, 4)) ], maxlen=4) y = deque([ piece.Piece(2, (0, 6)), piece.Piece(4, (0, 4)), piece.Piece(6, (2, 4)), piece.Piece(8, (3, 4)) ], maxlen=4) players = {"one": x, "two": y} root = board.Board(players) root.find_children(1, 3) boards = network.filter_children(root, 1) for child in boards: print(child.score_one, child.score_two) end = time.time()
def initializePawn(self, color): for i in range(9): print(self.boardd[1][i].getColor()) for i in range(9): self.boardd[1][i] = piece.Piece(piece.Type.PAWN, 'white') for i in range(9): print(self.boardd[2][i].getColor())
def traiterCase(laCase, lig, col, plateau, pieces): if laCase == '': setCase(plateau, lig, col, None) else: contenu = laCase.split(";") sorte = int(contenu[0]) setCase(plateau, lig, col, sorte) if sorte > 0 and sorte not in pieces: pieces[sorte] = piece.Piece(sorte) if len(contenu) > 1: if contenu[1] == 'P': piece.setPassage(pieces[sorte], int(contenu[2]), lig, col) elif contenu[1] == 'N': piece.addEntree(pieces[sorte], entree.Entree(entree.NORD, lig, col)) elif contenu[1] == 'E': piece.addEntree(pieces[sorte], entree.Entree(entree.EST, lig, col)) elif contenu[1] == 'S': piece.addEntree(pieces[sorte], entree.Entree(entree.SUD, lig, col)) elif contenu[1] == 'O': piece.addEntree(pieces[sorte], entree.Entree(entree.OUEST, lig, col)) elif contenu[1] == 'J': if sorte > 1: piece.addJoueur(pieces[sorte], int(contenu[2])) else: mettrePion(plateau, lig, col, int(contenu[2]))
def MovePiece(self, givenPiece, from_square, to_square): self.letterPieces[from_square[1]][from_square[0]] = "." self.letterPieces[to_square[1]][ to_square[0]] = givenPiece.DisplayLetter() self.pieces[from_square[1]][from_square[0]] = piece.Piece(".", -1, 0) self.pieces[to_square[1]][to_square[0]] = givenPiece print(self.Board())
def __init__(self, cSpeed=0, cHeight=0, cMusic='a', ): self.speed = self.startSpeed = cSpeed # 0-9 self.startHeight = cHeight # 0-5 self.score = 0 self.bag = bag.bag(7) self.lines = 0 self.timer = stopwatch.Stopwatch() self.pause = False # generate height garbage self.field = field.Field() # populate blocks self.currPiece = piece.Piece(self.bag.grab()) self.nextPiece = piece.Piece(self.bag.grab())
def __place_pieces(self, fitness): """ Places pieces according to what gives the total highest fitness. This is a greedy algorithm that places the piece with the highest fitness on the cell with the highest fitness for that piece first. :param fitness: For each rank a grid of cells indicating the fitness for a piece with that rank in that cell. :return: A board configuration filled with pieces for the AI. """ placement = [[None for y in range(0, len(self.board[x]))] for x in range(0, len(self.board))] pieces_left = self.playboard.num_pieces.copy() total_pieces_left = sum(pieces_left.values()) #Place each piece individually. while total_pieces_left > 0: best_rank = None best_place = (-1, -1) best_value = -9999999999999999 for x in range(0, len(self.board)): for y in range(0, len(self.board)): for current_rank in rank.all_ranks: if pieces_left[current_rank] > 0: if fitness[current_rank][x][y] > best_value: best_value = fitness[current_rank][x][y] best_rank = current_rank best_place = (x, y) print(best_rank, "goes to", best_place[0], best_place[1], "with value", best_value) placement[best_place[0]][best_place[1]] = piece.Piece(best_rank, is_ai=True) pieces_left[best_rank] -= 1 total_pieces_left -= 1 for current_rank in rank.all_ranks: #Don't place another piece there. fitness[current_rank][best_place[0]][best_place[1]] = -99999999999999999 return placement
def undoMove(self): """ Undo last move. Note that only one move is stored so succesive calls to this function will not redo moves. """ newEmptyPiece = pc.Piece() newEmptyPiece.x = self.pieceMoved.x newEmptyPiece.y = self.pieceMoved.y self.pieceMoved.x = self.movedFrom[0] self.pieceMoved.y = self.movedFrom[1] pc.Piece.board.setPiece(self.pieceMoved) pc.Piece.board.setPiece(newEmptyPiece) if (self.playerToMove == self.p1): playerLosingPiece = self.p2 else: playerLosingPiece = self.p1 if (not self.newKing is None): self.playerToMove.pieces.remove(self.newKing) self.newKing = None self.playerToMove.pieces.append(self.pieceMoved) for piece in self.piecesRemoved: playerLosingPiece.pieces.append(piece) pc.Piece.board.setPiece(piece) pc.Piece.board.checkConsistency(self.p1) pc.Piece.board.checkConsistency(self.p2)
def setupGame(self): """ Initialize the game, has to be called before the game is started and should only be called once """ # Fill board with empty for i in range(0, 8): for j in range(0, 8): newpiece = pc.Piece() newpiece.x = i newpiece.y = j pc.Piece.board.setPiece(newpiece) # Create the pieces of player 1 and player 2 # Each has 4*3 = 12 pieces for i in range(0, 12): indx = 2 * i y = int(indx / 8) x = indx % 8 + y % 2 self.p1.pieces.append(pc.Man()) self.p1.pieces[-1].x = x self.p1.pieces[-1].y = y self.p1.pieces[-1].color = "white" y = 7 - int(indx / 8) x = (indx + 1) % 8 - int(indx / 8) % 2 self.p2.pieces.append(pc.Man()) self.p2.pieces[-1].x = x self.p2.pieces[-1].y = y self.p2.pieces[-1].color = "black" # Put pieces on the board pc.Piece.board.setPiece(self.p1.pieces[-1]) pc.Piece.board.setPiece(self.p2.pieces[-1])
def game_settings(self): "constructs a 2d list and appends piece objects inside each list" for i in range(self._row): self._list.append([]) for j in range(self._column): pieces = piece.Piece(i, j) self._list[i].append(pieces)
def player_turn(turn, brd): print("Turn: ", turn, "\n") print(brd) inpt = input("Your move x,y: ") inpt = tuple(int(x) for x in inpt.split(",")) next_piece = piece.Piece(turn, inpt) brd.place_piece(next_piece) return brd
def getPiece(cs): # cs is the color and size of the ship, like 'y3' if len(cs) != 2: raise Exception('Not a valid piece identifier: "%s"' % cs) try: return piece.Piece(int(cs[1]), char2color[cs[0].lower()]) except: raise Exception('Not a valid piece identifier: "%s"' % cs)
def set_pieces(self): id = 0 for row in enumerate(self.squares): if row[0] not in (3, 4): for sqr in row[1]: if sqr.color == 1: color = -1 + 2 * (row[0] // 4) sqr.piece = piece.Piece(color, color * (id % 12 + 1)) id += 1
def __init__(self, row, col): """ Define Square Class Variables :param row: row of chess square :param col: col of chess square """ self.row = row self.col = col self.piece = PIECE.Piece()
def generate_pieces(self): pieces = [] for i in range(self.number_of_pieces): start = i * 20 end = start + 20 if i == (self.number_of_pieces - 1): piece_length = self.torrent.total_length - ( self.number_of_pieces - 1) * self.torrent.piece_length pieces.append( piece.Piece(i, piece_length, self.torrent.pieces[start:end])) else: pieces.append( piece.Piece(i, self.torrent.piece_length, self.torrent.pieces[start:end])) return pieces
def move(self, action): """ Les actions sont au format (case de la piece, case ou la bouger, action a réaliser) par exemple : ((0, 1), (2, 0, 'MVT')) """ (y_beg, x_beg) = action[0] (y_end, x_end, act) = action[1] self.cases[y_end][x_end] = self.cases[y_beg][x_beg] self.cases[y_beg][x_beg] = pc.Piece(pc.vide, pc.vide)
def testBasicPieceDraw(self, mock_draw_circle): basic_piece = piece.Piece() basic_piece.draw(self.d_surf, (0, 0)) mock_draw_circle.assert_called_once_with(self.d_surf, piece.DEFAULT_PIECE_COLOUR, (0, 0), piece.DEFAULT_PIECE_SIZE)
def newPiece(self): """ Rotates next piece to current piece, makes new next piece. """ self.currPiece, self.nextPiece = self.nextPiece, piece.Piece(self.bag.grab()) if self.currPiece.type == 5: self.currPiece.pos[0] -= 1 if pieceOcc.pieceOcc(self.currPiece, self.field): return True else: return False
def execute_valid_move(self, start_coordinate, end_coordinate): """ should not be called unless move is 100% verified to be valid :param start_coordinate: :param end_coordinate: :return: """ row1 = start_coordinate[0] col1 = start_coordinate[1] row2 = end_coordinate[0] col2 = end_coordinate[1] color = self.grid[row1][col1].piece.color previous_grid = self._copy_grid() # Grab Squares start_square = self.grid[row1][col1] end_square = self.grid[row2][col2] if end_coordinate[-1] == 'is_queening': self.set_piece(QUEEN.Queen(color), row2, col2, debug=True) else: self.set_piece(start_square.piece, row2, col2, debug=True) end_square.piece.update_turn_last_moved(self.turn_count) if end_coordinate[-1] == 'is_en_passant': self.set_piece(PIECE.Piece(), row1, col2, debug=True) start_square.set_piece(PIECE.Piece()) if end_coordinate[-1] == 'is_castling': if col2 - col1 > 0: # King Side Castle self.set_piece(self.grid[row2][col2 + 1].piece, row2, col2 - 1, debug=True) self.grid[row2][col2 - 1].piece.update_turn_last_moved(self.turn_count) self.set_piece(PIECE.Piece(), row2, col2 + 1, debug=True) else: # Queen Side Castle self.set_piece(self.grid[row2][col2 - 2].piece, row2, col2 + 1, debug=True) self.grid[row2][col2 + 1].piece.update_turn_last_moved(self.turn_count) self.set_piece(PIECE.Piece(), row2, col2 - 2, debug=True) # Add the previous position to history self.history.append(previous_grid) # Update Turn Variables self.turn_count += 1 self.turn_last_capture += 1
def execute(self, game_state): "Interacts with the start end and capture Space objects to carry out this move command" empty_slot = self._space p = piece.Piece(game_state._current_side, game_state._board, empty_slot) empty_slot.piece = p game_state.last_placed = p # advance turn and update draw counter game_state.next_turn()
def test_not_enough_edges_specd(self): """ Unit test to check that correct number of edges are specified """ piece_spec = [["P", "T"], \ ["R", "B"], \ ["O", "B"]]#, \ #["G", "T"]] with self.assertRaises(ValueError): pc.Piece(piece_spec)
def test_add_second_board_piece_no_match(self): """ Unit test to ensure an incorrect piece cannot be added to the second spot """ piece1 = pc.Piece([["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["G", "T"]]) piece2 = pc.Piece([["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["G", "T"]]) board = bd.Board() board.add_piece(0,piece1) self.assertFalse(board.add_piece(1,piece2))
def test_add_second_board_piece_match(self): """ Unit test to ensure a correct second piece can be added to the board """ piece1 = pc.Piece([["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["G", "T"]]) piece2 = pc.Piece([["P", "T"], \ ["R", "B"], \ ["O", "B"], \ ["R", "T"]]) board = bd.Board() board.add_piece(0,piece1) self.assertTrue(board.add_piece(1,piece2))