def test_check_4(): # Checked by pawn board = Board.Board() wk = Piece.King([4, 3], "w") bp = Piece.Pawn([5, 4], "b") board.add_piece(wk) board.add_piece(bp) assert wk.is_checked(board)
def deletePiece(self, piece: Piece): if piece is None: return import math (mouseX, mouseY) = pygame.mouse.get_pos() diffX = (mouseX - self.posX - piece.getpatternY() * Settings.GRID_RES / 2) / Settings.GRID_RES diffY = (mouseY - self.posY - piece.getpatternX() * Settings.GRID_RES / 2) / Settings.GRID_RES x = math.ceil(diffX) if math.ceil(diffX) - diffX < 0.5 else math.floor( diffX) y = math.ceil(diffY) if math.ceil(diffY) - diffY < 0.5 else math.floor( diffY) if x < -piece.getpatternY( ) + 1 or x >= self.columns or y < -piece.getpatternX( ) + 1 or y >= self.rows: return for tile in piece.getTiles(): toffX, toffY = tile.getXOffset(), tile.getYOffset() if x + toffY < 0 or x + toffY > self.columns - 1 or y + toffX < 0 or y + toffX > self.rows - 1: continue self.grid[y + toffX][x + toffY] = 0
def main(argv): nb = -1 if len(sys.argv) == 3: if argv[0] == "-n": tmp = int(argv[1]) if tmp > 0: nb = tmp if nb == -1: print('argument non valide') exit(1) print("----- DEBUT SIMULATION ENTREPOT -----") # Pièces Piece.processusPieces(nb) # Machine mA Machine.processusMachine("mA",["pA", "pB"],["mB"],nb) # Machine mB Machine.processusMachine("mB",["pB", "pC"],["mA"],nb) # Entrepôt Entrepot.processusEntrepot() print("------ FIN SIMULATION ENTREPOT ------")
def shrink_board(self, my_pieces, pieces, my_char, enemy_char, enemy_pieces): """ Shrink the board, eliminating all pieces along the outermost layer, and replacing the corners. This method can be called up to two times only. Taken from the referee.py module with minor modifications. """ s = self.n_shrinks # number of shrinks so far, or 's' for short # Remove edges for i in range(s, 8 - s): for square in [(i, s), (s, i), (i, 7 - s), (7 - s, i)]: y, x = square piece = self.board[y][x] if piece.get_type() in pieces: pieces[piece.get_type()] -= 1 if piece.get_type() == my_char: my_pieces.pop(piece.coord) self.board[y][x] = Piece.Piece(" ", (y, x)) # we have now shrunk the board once more! self.add_shrink() s = self.n_shrinks # replace the corners (and perform corner elimination) for corner in [(s, s), (s, 7 - s), (7 - s, 7 - s), (7 - s, s)]: y, x = corner piece = self.board[y][x] if piece.get_type() in pieces: pieces[piece.get_type()] -= 1 if piece.get_type() == my_char: my_pieces.pop(piece.coord) self.board[y][x] = Piece.Piece('X', (y, x)) self.eliminate_about(corner, my_pieces, pieces, my_char, enemy_char, enemy_pieces)
def test_check_1(): # Checked by rook board = Board.Board() wk = Piece.King([4, 3], "w") br = Piece.Rook([2, 3], "b") board.add_piece(wk) board.add_piece(br) assert wk.is_checked(board)
def readFile(self, filename: str) -> [[]]: """Returns the setup from a txt file in the form of a double list. """ # initialize a field and an empty list setup_field = [['X' for i in range(6)] for i in range(4)] setup_list = [] # open file and read the lines with open(filename) as f: line = f.readline() setup_list.append(line.rstrip('\n')) while line: line = f.readline() if line != '': setup_list.append(line.rstrip('\n')) # get team, position and pieces from the lines and create pieces on the right square for i in range(4): line = setup_list[i] help_list = line.split() for j in help_list: if j != 'X': # check wheter rank is a str, otherwise make it an int (for comparing purposes) if j[1:] == 'F' or j[1:] == 'B': setup_field[i][help_list.index(j)] = Piece( j[0], [i, help_list.index(j)], j[1:]) else: setup_field[i][help_list.index(j)] = Piece( j[0], [i, help_list.index(j)], int(j[1:])) return setup_field
def __init__(self, isRendered=False, clone=None): if clone is not None: self.isRendered = clone.isRendered self.grid = copy.deepcopy(clone.grid) self.currentPiece = copy.deepcopy(clone.currentPiece) self.nextPiece = copy.deepcopy(clone.nextPiece) self.numLinesCleared = clone.numLinesCleared return self.isRendered = isRendered self.grid = [ [False for i in range(gridWidth)] for j in range(gridHeight) ] # [0][0] is bottom-left corner, index row, then col ([x][y] on caresian plane) self.currentPiece = Piece.Piece(Piece.intToBitMaps[random.randint( 0, 6)]) # there are 7 pieces to choose from self.nextPiece = Piece.Piece(Piece.intToBitMaps[random.randint(0, 6)]) self.numLinesCleared = 0 # fitness function if self.isRendered: # set up a pygame window for this game pygame.init() self.screen = pygame.display.set_mode( (2 + gridWidth * (squareLength + 1), 2 + gridHeight * (squareLength + 1))) self.screen.fill(white) pygame.display.update()
def test_check_2(): # Not checked board = Board.Board() wk = Piece.King([4, 3], "w") br = Piece.Rook([3, 4], "b") board.add_piece(wk) board.add_piece(br) assert not wk.is_checked(board)
def __hasPiecesFrozen(self, board, row, col, piece): value = 0 piecesFrozen = 0 # Generate all the occupied adjacent positions. adj_occ_pos = Board.getAdjacentPositions(board, row, col, True) for pos in adj_occ_pos: adj_row = pos[0] adj_col = pos[1] adj_piece = board[adj_row][adj_col] # Make sure you're not looking at piece that # you're friends with. if not Piece.areFriends(piece, adj_piece): # If you're stronger than the adjacent piece, # then you've frozen it. if Piece.isStronger(piece, adj_piece): piecesFrozen = piecesFrozen + 1 # Return a value now based on the number of pieces frozen. # If it has too many pieces frozen, then it has potential # to being trapped. So it needs to be careful. if piecesFrozen == 1: value = 100 elif piecesFrozen == 2: value = 1000 elif piecesFrozen == 3: value = -100 if piecesFrozen == 4: value = -1000 return value
def capture(self, x_start, y_start, x_target, y_target): if self.figures[x_start][y_start].name == 'man': self.figures[x_target][y_target] = Piece.Man(self.player, x_target, y_target) elif self.figures[x_start][y_start].name == 'dame': self.figures[x_target][y_target] = Piece.Dame(self.player, x_target, y_target) self.images[x_target][y_target] = ImageTk.PhotoImage(image=self.figures[x_target][y_target].icon) self.buttons[x_target][y_target].configure(image=self.images[x_target][y_target]) for i in range(abs(x_target - x_start)): x_captured = int(x_start + i * (x_target - x_start) / abs(x_target - x_start)) y_captured = int(y_start + i * (y_target - y_start) / abs(y_target - y_start)) self.figures[x_captured][y_captured] = Piece.NotPiece(0, x_captured, y_captured) self.images[x_captured][y_captured] = ImageTk.PhotoImage(image=self.figures[x_captured][y_captured].icon) self.buttons[x_captured][y_captured].configure(image=self.images[x_captured][y_captured]) if len(self.figures[x_target][y_target].capturing_possibilities(self.figures)) > 0: for i in range(8): for j in range(8): self.buttons[i][j].configure(state=tk.DISABLED) self.buttons[x_target][y_target].configure( state=tk.NORMAL, command=partial(self.choice, x_target, y_target) ) for possibility in self.figures[x_target][y_target].capturing_possibilities(self.figures): self.buttons[possibility[0]][possibility[1]].configure( state=tk.NORMAL, command=partial(self.capture, x_target, y_target, possibility[0], possibility[1]) ) else: if (self.player == 1 and x_target == 0) or (self.player == -1 and x_target == 7): self.convert_to_dame(x_target, y_target) if self.end_of_the_game() != 1: self.dark_turn() self.enable_player(self.player)
def test_check_3(): # Checked by bishop board = Board.Board() wk = Piece.King([4, 3], "w") bb = Piece.Bishop([5, 4], "b") board.add_piece(wk) board.add_piece(bb) assert wk.is_checked(board)
def get_max_move_pieces(self): piece_list = [] current_max = 0 for i in range(self.rows): for j in range(self.columns): if self.current_player != self.matrix[i][j]: pass # Determines the number of moves available for the piece on square (i,j) piece_move_numb = 0 if i < self.rows - 1 and self.matrix[i + 1][j] == 0: piece_move_numb = piece_move_numb + 1 if i > 0 and self.matrix[i - 1][j] == 0: piece_move_numb = piece_move_numb + 1 if j > 0 and self.matrix[i][j - 1] == 0: piece_move_numb = piece_move_numb + 1 if j < self.columns - 1 and self.matrix[i][j + 1] == 0: piece_move_numb = piece_move_numb + 1 # Adds piece to current move list if it has the same number of moves available as current max if piece_move_numb == current_max: piece_list.append(Piece(i, j)) # If a piece with more moves than the current max is found, the current_max is updated and a new move list created if piece_move_numb > current_max: current_max = piece_move_numb piece_list = [] piece_list.append(Piece(i, j)) return piece_list
def promotions(self, color, pos, to_pos): promos = [] promos.append(self.create_move(pos, to_pos, Piece.Knight(color))) promos.append(self.create_move(pos, to_pos, Piece.Rook(color))) promos.append(self.create_move(pos, to_pos, Piece.Queen(color))) promos.append(self.create_move(pos, to_pos, Piece.Bishop(color))) return promos
def dark_capture(self, x_start, y_start, x_target, y_target): if self.figures[x_start][y_start].name == 'man': self.figures[x_target][y_target] = Piece.Man(-1, x_target, y_target) elif self.figures[x_start][y_start].name == 'dame': self.figures[x_target][y_target] = Piece.Dame(-1, x_target, y_target) self.images[x_target][y_target] = ImageTk.PhotoImage(image=self.figures[x_target][y_target].icon) self.buttons[x_target][y_target].configure(image=self.images[x_target][y_target]) for i in range(abs(x_target - x_start)): x_captured = int(x_start + i * (x_target - x_start) / abs(x_target - x_start)) y_captured = int(y_start + i * (y_target - y_start) / abs(y_target - y_start)) self.figures[x_captured][y_captured] = Piece.NotPiece(0, x_captured, y_captured) self.images[x_captured][y_captured] = ImageTk.PhotoImage(image=self.figures[x_captured][y_captured].icon) self.buttons[x_captured][y_captured].configure(image=self.images[x_captured][y_captured]) value = inf figures = self.figures.copy() if len(figures[x_target][y_target].capturing_possibilities(figures)) > 0: for possibility in figures[x_target][y_target].capturing_possibilities(figures): ev = logic.simulate_capture(x_target, y_target, possibility[0], possibility[1], figures, -1)[1] if ev < value: value = ev start_position = (x_target, y_target) target_position = (possibility[0], possibility[1]) figures = logic.simulate_capture(x_target, y_target, possibility[0], possibility[1], figures, -1)[0] self.dark_capture(start_position[0], start_position[1], target_position[0], target_position[1]) else: if x_target == 7: self.convert_to_dame(x_target, y_target) if self.end_of_the_game() != 1: self.enable_player(self.player)
def __init__(self): self.grid = Grid.Grid(GRID_HEIGHT, GRID_WIDTH) self.current_piece = Piece.next_piece() self.ai = AI.AI([0.510066, 0.760666, 0.35663, 0.184483]) self.working_pieces = [Piece.next_piece(), Piece.next_piece()] self.working_piece = self.working_pieces[0] self.font_score = pygame.font.SysFont('comicsans', 60, True, False) self.is_ai_active = True self.score = 0
def generate_piece(self, mode): self.piece = Piece() self.next_piece = Piece() if (mode == 'basic' or 'two' or 'ai'): self.piece_x, self.piece_y = Var.block_start_basic_x, Var.block_start_y if (mode == 'mini'): self.piece_x, self.piece_y = Var.block_start_mini_x, Var.block_start_y
def __init__(self, name="olivia", color="purple", order=1): self.name = name self.color = color self.pieces = (Piece.Piece(name, 1, color), Piece.Piece(name, 2, color), Piece.Piece(name, 3, color), Piece.Piece(name, 4, color) ) #piece should contain player name self.order = order self.win = 0
def test_castling_queenside(): board = Board.Board() # Kings are needed for check testing when calling valid_moves wk = Piece.King([4, 0], "w") bk = Piece.King([7, 7], "b") board.add_piece(wk) board.add_piece(bk) wr = Piece.Rook([0, 0], "w") board.add_piece(wr) assert [2, 0] in wk.valid_moves(board)
def start(self): # Initializing center values p1 = Piece.Piece(1, False, True, True, False) p2 = Piece.Piece(0, False, True, False, True) p3 = Piece.Piece(1, True, False, False, True) p4 = Piece.Piece(0, True, False, True, False) self.array[3][3] = p1 self.array[3][4] = p4 self.array[4][3] = p2 self.array[4][4] = p3
def __init__(self, color): # Set player colors self.p1Color = color if color == 'w': self.p2Color = 'b' else: self.p2Color = 'w' # Put pieces on the board in starting arrangement for i in range(1, 25): self.board[i] = Point.Point(i) if i == 1: for j in range(2): self.board[i].addPiece(Piece.Piece(self.p2Color)) if i == 6: for j in range(5): self.board[i].addPiece(Piece.Piece(self.p1Color)) if i == 8: for j in range(3): self.board[i].addPiece(Piece.Piece(self.p1Color)) if i == 12: for j in range(5): self.board[i].addPiece(Piece.Piece(self.p2Color)) if i == 13: for j in range(5): self.board[i].addPiece(Piece.Piece(self.p1Color)) if i == 17: for j in range(3): self.board[i].addPiece(Piece.Piece(self.p2Color)) if i == 19: for j in range(5): self.board[i].addPiece(Piece.Piece(self.p2Color)) if i == 24: for j in range(2): self.board[i].addPiece(Piece.Piece(self.p1Color))
def test_castling_checked_dest(): board = Board.Board() # Kings are needed for check testing when calling valid_moves wk = Piece.King([4, 0], "w") bk = Piece.King([7, 7], "b") board.add_piece(wk) board.add_piece(bk) wr = Piece.Rook([7, 0], "w") br = Piece.Rook([6, 7], "b") board.add_piece(br) board.add_piece(wr) assert not [6, 0] in wk.valid_moves(board)
def simulate_capture(x_start, y_start, x_target, y_target, figures, player): figures_copy = [[] for i in range(8)] for x in range(8): for y in range(8): figures_copy[x].append(copy.copy(figures[x][y])) if figures_copy[x_start][y_start].name == 'man': figures_copy[x_target][y_target] = Piece.Man(player, x_target, y_target) elif figures_copy[x_start][y_start].name == 'dame': figures_copy[x_target][y_target] = Piece.Dame(player, x_target, y_target) for i in range(abs(x_target - x_start)): x_captured = int(x_start + i * (x_target - x_start) / abs(x_target - x_start)) y_captured = int(y_start + i * (y_target - y_start) / abs(y_target - y_start)) figures_copy[x_captured][y_captured] = Piece.NotPiece( 0, x_captured, y_captured) value = evaluation(figures_copy) temp_value = -inf * player temp_figures = figures_copy if len(figures_copy[x_target][y_target].capturing_possibilities( figures_copy)) > 0: for possibility in figures_copy[x_target][ y_target].capturing_possibilities(figures_copy): ev = simulate_capture(x_target, y_target, possibility[0], possibility[1], figures_copy, player)[1] if ev < temp_value and player == -1: temp_value = ev temp_figures = simulate_capture(x_target, y_target, possibility[0], possibility[1], figures_copy, player)[0] if ev > temp_value and player == 1: temp_value = ev temp_figures = simulate_capture(x_target, y_target, possibility[0], possibility[1], figures_copy, player)[0] figures_copy = temp_figures else: if (player == 1 and x_target == 0) or (player == -1 and x_target == 7): figures_copy[x_target][y_target] = Piece.Dame( player, x_target, y_target) if temp_value != inf and temp_value != -inf: value = temp_value return figures_copy, value
def customState(self, state): ''' Update board state to the given custom value. Input: lists of lists of integers ''' transform = { 0: 0, 1: Piece(True), 2: Piece(True, True), -1: Piece(False), -2: Piece(False, True) } self.state = [[transform[v] for v in row] for row in state] return (0)
def test_en_passant_1(): board = Board.Board() # Kings are needed for check testing when calling valid_moves wk = Piece.King([7, 7], "w") bk = Piece.King([0, 7], "b") board.add_piece(wk) board.add_piece(bk) wp = Piece.Pawn([2, 1], "w") bp = Piece.Pawn([3, 3], "b") board.add_piece(wp) board.add_piece(bp) wp.move([2, 3], board) assert [2, 2] in bp.valid_moves(board)
def test_setcolorstoomanycolorswithedgepiece(self): self.piece = Piece.Piece(Piece.Piece.EDGE, (1, 1, 1)) self.piece.set_color(cp.RED, Piece.FRONT) self.piece.set_color(cp.GREEN, Piece.BACK) self.piece.set_color(cp.BLUE, Piece.UP) self.piece.set_color(cp.YELLOW, Piece.DOWN) self.assertEqual(3, len(self.piece.colors.items()))
def update(self, action): """ Update our internal board with our opponent's move :param action: """ if self.my_char == "@": if self.moving_phase: self.enemy_moving_phase = True # placing phase if not self.enemy_moving_phase: new_piece = Piece.Piece(self.enemy_char, action) self.enemy_pieces[action] = new_piece self.board.add_piece(new_piece) self.pieces[self.enemy_char] += 1 self.board.eliminate_about(action, self.my_pieces, self.pieces, self.my_char, self.enemy_char, self.enemy_pieces) # moving phase else: initial_coordinate, new_coordinate = action piece = self.enemy_pieces[initial_coordinate] self.enemy_pieces.pop(initial_coordinate) self.enemy_pieces[new_coordinate] = piece self.make_move(self.board.get_piece_at(initial_coordinate), new_coordinate) if self.my_char == "O": if self.moving_phase: self.enemy_moving_phase = True
def test_en_passant_2(): board = Board.Board() # Kings are needed for check testing when calling valid_moves wk = Piece.King([7, 7], "w") bk = Piece.King([0, 7], "b") board.add_piece(wk) board.add_piece(bk) wp = Piece.Pawn([2, 1], "w") bp = Piece.Pawn([3, 3], "b") board.add_piece(wp) board.add_piece(bp) wp.move([2, 3], board) wp.clear_passant() # Clear en passant flag so it can't be taken that way assert not [2, 2] in bp.valid_moves(board)
def addPieces(self, data, edition): for pieceType in Constants.PIECE_TYPES: for (name, properties) in data.get(pieceType, {}).items(): if not pieceType in self.pieces: self.pieces[pieceType] = [] self.pieces[pieceType].append( Piece(name, self.name, edition, pieceType, properties))
def evaluateBoard(self, board, color, combined, start_row = 0, start_col = 0, end_row = 7, end_col = 7): value = 0 for row in range(start_row, end_row + 1): for col in range (start_col, end_col + 1): piece = board[row][col] # If it's my piece, then add to my total. if color == Piece.pieceColor(piece): value = value + self.__getMaterialValue(board, color, piece) value = value + self.__getPositionValue(color, piece, row, col) if Board.isFrozen(board, piece, row, col): value = value + self.__getFrozenValue(color, piece, row, col) # Else, it's the opponent's piece, the value goes down. elif combined == True: value = value - self.__getMaterialValue(board, color, piece) value = value - self.__getPositionValue(color, piece, row, col) if Board.isFrozen(board, piece, row, col): value = value - self.__getFrozenValue(color, piece, row, col) return value
def __init__(self): self.tasks = list() self.currTask = Task("", "", "") self.currTaskIndex = 0 self.currPiece = Piece("", "", "") self.currDuty = Duty() self.isTimerRunning = False self.timeTimerStart = "" self.timeTimerEnd = "" self.pathWeekData = "" self.filenameDutyData = "" self.pathTasksData = "" self.pathData = "" self.currDate = ""
def nextPiece(self): self.index += 1 if self.index >= len(self.bag): self.shuffleBag() self.index = 0 return Piece().select_piece(self.bag[self.index])
def dark_move(self, x_start, y_start, x_target, y_target): if self.figures[x_start][y_start].name == 'man': self.figures[x_target][y_target] = Piece.Man(-1, x_target, y_target) elif self.figures[x_start][y_start].name == 'dame': self.figures[x_target][y_target] = Piece.Dame(-1, x_target, y_target) self.images[x_target][y_target] = ImageTk.PhotoImage(image=self.figures[x_target][y_target].icon) self.buttons[x_target][y_target].configure(image=self.images[x_target][y_target]) self.figures[x_start][y_start] = Piece.NotPiece(0, x_start, y_start) self.images[x_start][y_start] = ImageTk.PhotoImage(image=self.figures[x_start][y_start].icon) self.buttons[x_start][y_start].configure(image=self.images[x_start][y_start]) # convert to dame? if x_target == 7: self.convert_to_dame(x_target, y_target) self.enable_player(1)
def addPiece(self,owner,type,x,y): piece = Piece() piece.setup(owner,type) if self.array[int(x)][int(y)] == None: if piece.getOwner()== "AI" and (piece.getType() == 1 or piece.getType() == 0): self.array[int(x)][int(y)] = piece self.aiPieces+=1 return True elif piece.getOwner()== "Player" and (piece.getType() == 1 or piece.getType() == 0): self.array[int(x)][int(y)] = piece self.playerPieces+=1 return True else: return False
def __nextMoveType(self, steps): if len(steps) <= 0: return Step.Step.REGULAR # Get rid of traps, not necessary for this for step in steps: if step.dir == "x" or step.dir == "X": steps.remove(step) last_step = steps[-1] # We may be in the process of doing a push # or just completing a pull. if last_step.color != self.color: # We just completed a pull if len(steps) >= 2: prev_step = steps[-2] if prev_step.start_row == last_step.end_row and \ prev_step.start_col == last_step.end_col: return Step.Step.REGULAR else: return Step.Step.MUST_PUSH # Or we're in the middle of a push else: return Step.Step.MUST_PUSH else: # Get all the occupied adjacent positions to see if we can attempt a pull. adj_pos = Board.getAdjacentPositions(self.board, last_step.start_row, last_step.start_col, True) for pos in adj_pos: row = pos[0] col = pos[1] other_piece = self.board[row][col] # Ensure that the piece we are trying to pull is not our own. if Piece.pieceColor(other_piece) != self.color: # Now are we actually stronger than that piece if Piece.isStronger(last_step.piece, other_piece): return Step.Step.CAN_PULL return Step.Step.REGULAR
def place_piece(self, x, y, piece_type, piece_colour): """Place a piece of the passed type at the passed location. Args: - x, y: ints specifying the position on the board to place piece - type: a member of the PieceType enum - piece_colour: a member of the PieceColour enum Will raise IndexError if the indices are not valid. """ self.piece_array[x][y] = Piece.make_piece(piece_type, piece_colour)
def isSafe(board, row, col): piece = board[row][col] if piece == "x" or piece == "X": return True adj_occ_pos = getAdjacentPositions(board, row, col, True) for pos in adj_occ_pos: adj_row = pos[0] adj_col = pos[1] adj_piece = board[adj_row][adj_col] if Piece.isFriends(adj_piece, piece): return True return False
def __init__(self,displaysurf,fontobj): self.displaysurf = displaysurf self.fontobj = fontobj self.board = self.getBlankBoard() self.boardWithPieces = self.getBlankBoard() self.piece = Piece(random.choice(list(SHAPES))) self.completedLines = 0 self.totalCompletedLines = 0 self.score = 0 self.level = LEVELONE self.gameState = ACTIVE self.softDropDistance = 0 self.hardDropDistance = 0 #draw the board self.draw()
def isFrozen(board, piece, row, col): occ_adj_pos = getAdjacentPositions(board, row, col, True) for pos in occ_adj_pos: adj_row = pos[0] adj_col = pos[1] adj_piece = board[adj_row][adj_col] if adj_piece == " ": continue elif adj_piece.isupper() and piece.isupper(): continue elif adj_piece.islower() and piece.islower(): continue elif Piece.isStronger(adj_piece, piece): return True return False
def __init__(self, step): self.arimaa_step = step if (step == ""): return self.piece = step[0:1] # C self.start_col = step[1:2] # c self.start_row = step[2:3] # 1 self.dir = step[3:4] # n # Get the correct color. self.color = Piece.pieceColor(self.piece) # Make the translation table for columns transTable = string.maketrans("abcdefgh", "12345678") self.start_col = string.translate(self.start_col, transTable) # Translate the column # Our notation is flipped from the Arimaa board. # Also we start at 0 not 1. self.start_row = 8 - int(self.start_row) self.start_col = int(self.start_col) - 1 self.end_row = self.start_row self.end_col = self.start_col if self.dir == "n": self.end_row = self.end_row - 1 elif self.dir == "s": self.end_row = self.end_row + 1 elif self.dir == "w": self.end_col = self.end_col - 1 elif self.dir == "e": self.end_col = self.end_col + 1 elif self.dir == "x": # Removal of piece self.end_row = -1 self.end_col = -1 elif self.dir == "": # Initial placement of piece self.start_row = -1 self.start_col = -1 self.type = Step.REGULAR
class PieceTest(unittest.TestCase): def setUp(self): self.piece = Piece() # test piece setup def pieceTest(self): self.piece.setup("Player", 0) self.assertEqual("Player", self.piece.getOwner()) self.assertEqual(0, self.piece.getType()) self.piece.setup("AI", 0) self.assertEqual("AI", self.piece.getOwner()) self.assertEqual(0, self.piece.getType()) self.piece.setup("Player",1) self.assertEqual("Player", self.piece.getOwner()) self.assertEqual(1, self.piece.getType()) self.piece.setup("AI",1) self.assertEqual("AI", self.piece.getOwner()) self.assertEqual(1, self.piece.getType()) self.piece.setup(293,"hello") self.assertEqual(293, self.piece.getOwner()) self.assertEqual("hello", self.piece.getType()) self.piece.setup(1,3) self.assertEqual(1, self.piece.getOwner()) self.assertEqual(3, self.piece.getType()) def tearDown(self): self.piece = None def main(self): self.setUp() self.pieceTest() self.tearDown()
moving_right = False moving_down = False rotate = False last_falling_block_time = 0 is_fast_drop = False game_over = False cleared_lines = 0 game_paused = False board = Board(BOARD_WIDTH, BOARD_HEIGHT) dir_path = os.path.dirname(os.path.realpath(__file__)) music_filepath = dir_path + '/tetris_music.mid' pygame.mixer.music.load(music_filepath) pygame.mixer.music.play(-1, 0.0) current_block = Piece(BOARD_WIDTH, 1) viewerSurface = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT)) pygame.display.set_caption(TITLE) game_window_width = viewerSurface.get_width() game_window_height = viewerSurface.get_height() def box_to_window_rect(x, y): x = BOX_LENGTH * x + BORDER_WIDTH y = BOX_LENGTH * y + BORDER_HEIGHT return x, y, BOX_LENGTH, BOX_LENGTH def draw_board(board): for i in xrange(BOARD_HEIGHT): for j in xrange(BOARD_WIDTH):
class Queue: def __init__(self,displaysurf): self.panel = self.getBlankPanel() self.displaysurf = displaysurf self.piece = Piece(random.choice(list(SHAPES))) self.piece.x = 1 self.piece.y = 1 def draw(self): queueX = XMARGIN + BOXSIZE + (BOARDWIDTH * BOXSIZE) queueY = YMARGIN queueWidth = PANELWIDTH * BOXSIZE queueHeight = PANELHEIGHT * BOXSIZE #draw the panel border pygame.draw.rect(self.displaysurf, BORDERCOLOR, (queueX - BORDERWIDTH, queueY - BORDERWIDTH, queueWidth + BORDERWIDTH*2,queueHeight + BORDERWIDTH*2)) #draw the panel pygame.draw.rect(self.displaysurf, BOARDGAMECOLOR, (queueX, queueY, queueWidth, queueHeight)) #draw the piece self.drawPiece() #draw the panel to the screen for x in range(PANELWIDTH): for y in range(PANELHEIGHT): self.drawBox(x, y, self.panel[x][y]) #draw each box in the board based on the given x,y, coordinate and box type def drawBox(self,x,y,boxType): if boxType == I: boxColor = RED elif boxType == J: boxColor = YELLOW elif boxType == L: boxColor = PURPLE elif boxType == O: boxColor = BLUE elif boxType == S: boxColor = LIGHTBLUE elif boxType == T: boxColor = GREEN elif boxType == Z: boxColor = ORANGE else: boxColor = BLACK #draw box border pygame.draw.rect(self.displaysurf, BLACK, (x*BOXSIZE + PANELPIXELX, y*BOXSIZE + PANELPIXELY, BOXSIZE, BOXSIZE)) #draw box fill pygame.draw.rect(self.displaysurf, boxColor, (x*BOXSIZE + PANELPIXELX + BBWIDTH, y*BOXSIZE + PANELPIXELY + BBWIDTH, BOXSIZE - BBWIDTH, BOXSIZE - BBWIDTH)) def drawPiece(self): #clear the old piece self.clearOldPiece() #place the piece on the board. for x in range(4): for y in range(4): self.panel[self.piece.x+x][self.piece.y+y] = self.piece.piece[x][y] def clearOldPiece(self): for x in range(4): for y in range(4): self.panel[x][y] = BLANK def getNextPiece(self): nextPieceType = self.piece.pieceType #get a new random shape self.piece.pieceType = random.choice(list(SHAPES)) #replace the queued piece self.piece.piece[:] = self.piece.setPiece(self.piece.pieceType) #return the next piece return nextPieceType def getBlankPanel(self): panel = [] # create and return a new blank board data structure for i in range(PANELWIDTH): panel.append([BLANK] * PANELHEIGHT) return panel def reset(self): self.clearOldPiece()
def __init__(self,displaysurf): self.panel = self.getBlankPanel() self.displaysurf = displaysurf self.piece = Piece(random.choice(list(SHAPES))) self.piece.x = 1 self.piece.y = 1
def setUp(self): self.piece = Piece()
def __genSteps(self, steps, start_row, start_col, end_row, end_col): moves = [] steps_left = MoveGenerator.MAX_STEPS last_step = Step.Step("") push = "" # Go through all the previous steps. # Decrement number of steps left and determine what the last step was. # We need to know the last step for pushes and pulls. for step in steps: if step.dir != "x" or step.dir != "X": steps_left = steps_left - 1 last_step = step if steps_left <= 0: return moves # Next move type gives information about what the next step can/must be next_move_type = self.__nextMoveType(steps) # If we're in the process of making a push, we have to complete the push. # Multiple pieces could move into that position, just as long as their # stronger and aren't on the same team. if next_move_type == Step.Step.MUST_PUSH: occ_adj_pos = Board.getAdjacentPositions(self.board, last_step.start_row, last_step.start_col, True) for pos in occ_adj_pos: row = pos[0] col = pos[1] piece = self.board[row][col] color = Piece.pieceColor(piece) if piece == " " or piece == "x" or piece == "X": continue # A piece can't move into it's friendly space. elif color != last_step.color: # See if this piece is stronger than the one that was just moved if Piece.isStronger(piece, last_step.piece): # Can this piece even move? Or is it frozen. if not Board.isFrozen(self.board, piece, row, col): step = self.__makeStep(piece, row, col, [[last_step.start_row, last_step.start_col]]) moves.append(step) # Were not completing a push, we are free to do what we want else: for row in range(start_row, end_row + 1): for col in range(start_col, end_col + 1): piece = self.board[row][col] # Don't care for blank spaces or trap squares if piece == " " or re.match("x", piece, re.IGNORECASE): continue piece_color = Piece.pieceColor(piece) # Get all the unoccupied and occupied adjacent positions to this piece unocc_adj_pos = Board.getAdjacentPositions(self.board, row, col, False) occ_adj_pos = Board.getAdjacentPositions(self.board, row, col, True) # Only generate moves for the current player if piece_color == self.color: # Is the piece NOT frozen if not Board.isFrozen(self.board, piece, row, col): unocc_adj_pos = self.__adjustRabbitPositions(piece, row, col, unocc_adj_pos) step = self.__makeStep(piece, row, col, unocc_adj_pos) moves.append(step) # If we're here, then we found the opponent piece. # Lets see if we can push or pull it. else: # Try doing a pull if the last move we did can initialize a pull. if (next_move_type == Step.Step.CAN_PULL): # Get all the occupied positions to the last step. prev_adj_occ_pos = Board.getAdjacentPositions(self.board, last_step.start_row, last_step.start_col, True) for prev_adj_pos in prev_adj_occ_pos: if piece_color != self.color and \ Piece.isStronger(last_step.piece, piece): prev_adj_row = prev_adj_pos[0] prev_adj_col = prev_adj_pos[1] if row == prev_adj_row and col == prev_adj_col: step = self.__makeStep(piece, row, col, [[last_step.start_row, last_step.start_col]]) moves.append(step) # Try performing a push on this piece. if (steps_left >= 2): for pos in occ_adj_pos: adj_row = pos[0] adj_col = pos[1] adj_piece = self.board[adj_row][adj_col] adj_color = Piece.pieceColor(adj_piece) if adj_color == self.color and \ Piece.isStronger(adj_piece, piece): if not Board.isFrozen(self.board, adj_piece, row, col): step = self.__makeStep(piece, row, col, unocc_adj_pos) moves.append(step) return moves
def newPiece(self,shapeType): self.piece = Piece(shapeType)
class Board: def __init__(self,displaysurf,fontobj): self.displaysurf = displaysurf self.fontobj = fontobj self.board = self.getBlankBoard() self.boardWithPieces = self.getBlankBoard() self.piece = Piece(random.choice(list(SHAPES))) self.completedLines = 0 self.totalCompletedLines = 0 self.score = 0 self.level = LEVELONE self.gameState = ACTIVE self.softDropDistance = 0 self.hardDropDistance = 0 #draw the board self.draw() def draw(self): # draw the border around the board pygame.draw.rect(self.displaysurf, BORDERCOLOR, (XMARGIN - BORDERWIDTH, YMARGIN - BORDERWIDTH, (BOARDWIDTH * BOXSIZE) + BORDERWIDTH*2, (BOARDHEIGHT * BOXSIZE) + BORDERWIDTH*2), 0) # fill the background of the board pygame.draw.rect(self.displaysurf, BOARDGAMECOLOR, (XMARGIN, YMARGIN, BOXSIZE * BOARDWIDTH, BOXSIZE * BOARDHEIGHT)) if self.gameState == ACTIVE: self.drawPiece() # draw the individual boxes on the board for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): self.drawBox(x, y, self.board[x][y]) if self.gameState == PAUSE: pausedSurf = self.fontobj.render('PAUSED', True, WHITE) pausedRect = pausedSurf.get_rect() pausedRect.topleft = (XMARGIN + (BOARDWIDTH * BOXSIZE)/2 - pausedRect.width/2, YMARGIN + (BOXSIZE * BOARDHEIGHT / 2)) pygame.draw.rect(self.displaysurf, BOARDGAMECOLOR, pausedRect) self.displaysurf.blit(pausedSurf, pausedRect) elif self.gameState == OVER: overSurf = self.fontobj.render('GAMEOVER!', True, WHITE) overRect = overSurf.get_rect() overRect.topleft = (XMARGIN + (BOARDWIDTH * BOXSIZE)/2 - overRect.width/2, YMARGIN + (BOXSIZE * BOARDHEIGHT / 2)) pygame.draw.rect(self.displaysurf, BOARDGAMECOLOR, overRect) self.displaysurf.blit(overSurf, overRect) elif self.gameState == WIN: winSurf = self.fontobj.render('YAY! YOU WON!', True, WHITE) winRect = winSurf.get_rect() winRect.topleft = (XMARGIN + (BOARDWIDTH * BOXSIZE)/2 - winRect.width/2, YMARGIN + (BOXSIZE * BOARDHEIGHT / 2)) pygame.draw.rect(self.displaysurf, BOARDGAMECOLOR, winRect) self.displaysurf.blit(winSurf, winRect) win2surf = self.fontobj.render("'P' to Play again!", True, WHITE) win2Rect = win2surf.get_rect() win2Rect.topleft = (XMARGIN + (BOARDWIDTH * BOXSIZE)/2 - winRect.width/2, YMARGIN + BOXSIZE * (1 + BOARDHEIGHT / 2)) pygame.draw.rect(self.displaysurf, BOARDGAMECOLOR, win2Rect) self.displaysurf.blit(win2surf, win2Rect) def clearOldPiece(self): for x in range(4): for y in range(4): if self.piece.piece[x][y] != BLANK and self.board[self.piece.x+x][self.piece.y+y] != BLANK: self.board[self.piece.x+x][self.piece.y+y] = BLANK def drawPiece(self,dX=0,dY=0): #clear the old piece self.clearOldPiece() #change the coordinates self.piece.x += dX self.piece.y += dY #check if valid if not self.isValidMove(None): self.gameState = OVER #place the piece on the board for x in range(4): for y in range(4): if self.isOnBoard(bX=self.piece.x+x,bY=self.piece.y+y): if self.piece.piece[x][y] != BLANK: #only draw the nonblank tiles self.board[self.piece.x+x][self.piece.y+y] = self.piece.piece[x][y] def setPiece(self): #place the piece on the boardWithPieces. for x in range(4): for y in range(4): if self.isOnBoard(bX=self.piece.x+x,bY=self.piece.y+y): if self.piece.piece[x][y] != BLANK: #only draw the nonblank tiles self.boardWithPieces[self.piece.x+x][self.piece.y+y] = self.piece.piece[x][y] self.board[self.piece.x+x][self.piece.y+y] = self.piece.piece[x][y] def newPiece(self,shapeType): self.piece = Piece(shapeType) #draw each box in the board based on the given x,y, coordinate and box type def drawBox(self,x,y,boxType): if boxType == I: boxColor = RED elif boxType == J: boxColor = YELLOW elif boxType == L: boxColor = PURPLE elif boxType == O: boxColor = BLUE elif boxType == S: boxColor = LIGHTBLUE elif boxType == T: boxColor = GREEN elif boxType == Z: boxColor = ORANGE else: boxColor = BLACK #draw box border pygame.draw.rect(self.displaysurf, BLACK, (x*BOXSIZE + XMARGIN, y*BOXSIZE + YMARGIN, BOXSIZE, BOXSIZE)) #draw box fill pygame.draw.rect(self.displaysurf, boxColor, (x*BOXSIZE + XMARGIN + BBWIDTH, y*BOXSIZE + YMARGIN + BBWIDTH, BOXSIZE - BBWIDTH, BOXSIZE - BBWIDTH)) def getBlankBoard(self): board = [] # create and return a new blank board data structure for i in range(BOARDWIDTH): board.append([BLANK] * BOARDHEIGHT) return board def clearBoard(self): for x in range(BOARDWIDTH): for y in range(BOARDHEIGHT): self.board[x][y] = BLANK self.boardWithPieces[x][y] = BLANK #def getNextPiece(self): def movePiece(self, action): isSet = False if action == DROP: while self.isValidMove(action): self.clearOldPiece() self.piece.y += 1 self.hardDropDistance += 1 self.setPiece() isSet = True elif action == DOWN: if self.isValidMove(action): self.drawPiece(dY=1) else: self.setPiece() isSet = True elif action == LEFT: if self.isValidMove(action): self.drawPiece(dX=-1) elif action == RIGHT: if self.isValidMove(action): self.drawPiece(dX=1) elif action == ROTATE: if self.isValidMove(action): self.rotate() return isSet def rotate(self): #clear the old piece for x in range(4): for y in range(4): if self.piece.piece[x][y] != BLANK: self.board[self.piece.x+x][self.piece.y+y] = BLANK self.piece.rotate() #checks if provided coordinates are still on the board. def isOnBoard(self,bX=0,bY=0): if (0 <= bX < BOARDWIDTH) and (0 <= bY < BOARDHEIGHT): return True else: return False ''' isValidMove() input action - directional or rotational action output boolean - True if valid action, otherwise False ''' def isValidMove(self,action): valid = True #generate a list of valid moves base of piece's current position #TODO The following block of code can still be condensed if action == DOWN or action == DROP: for y in reversed(range(self.piece.gridSize)): for x in range(self.piece.gridSize): if self.piece.piece[x][y] != BLANK: #if current box is not blank, check below it on the boardWithPieces if self.isOnBoard(bX=(self.piece.x + x), bY=(self.piece.y + y + 1)): #check if the next spot is on the board if self.boardWithPieces[self.piece.x + x][self.piece.y + y + 1] != BLANK: #check if the next spot is blank valid = False else: valid = False elif action == LEFT: for x in range(self.piece.gridSize): for y in range(self.piece.gridSize): if self.piece.piece[x][y] != BLANK: #if current box is not blank, check to the left of it if self.isOnBoard(bX=(self.piece.x + x - 1), bY =(self.piece.y + y)): #check if the next spot is on the board if self.boardWithPieces[self.piece.x + x - 1][self.piece.y + y] != BLANK: #check if the next spot is blank valid = False else: valid = False elif action == RIGHT: for x in reversed(range(self.piece.gridSize)): for y in range(self.piece.gridSize): if self.piece.piece[x][y] != BLANK: #if current box is not blank, check to the left of it if self.isOnBoard(bX=(self.piece.x + x + 1), bY =(self.piece.y + y)): #check if the next spot is on the board if self.boardWithPieces[self.piece.x + x + 1][self.piece.y + y] != BLANK: #check if the next spot is blank valid = False else: valid = False elif action == ROTATE: #Initialize temporary variables tempRotatedPiece = self.piece.setPiece(BLANK) #Rotate the piece for col in range(self.piece.gridSize): for index, cell in zip(reversed(range(self.piece.gridSize)),self.piece.piece[col]): tempRotatedPiece[index][col] = cell for x in range(self.piece.gridSize): for y in range(self.piece.gridSize): if tempRotatedPiece[x][y] != BLANK: if self.isOnBoard(bX=(self.piece.x + x), bY= (self.piece.y + y)): if self.boardWithPieces[self.piece.x + x][self.piece.y + y] != BLANK: valid = False else: valid = False else: #check current position for x in range(self.piece.gridSize): for y in range(self.piece.gridSize): if self.piece.piece[x][y] != BLANK: #if current box is not blank, check under it if self.isOnBoard(bX=(self.piece.x + x), bY =(self.piece.y + y)): #check if the next spot is on the board if self.boardWithPieces[self.piece.x + x][self.piece.y + y] != BLANK: valid = False else: valid = False return valid #scan for completed rows, update completedLines, clear them. def clearCompletedRows(self): y = BOARDHEIGHT - 1; while y >= 0: if self.isCompletedRow(y): self.completedLines += 1 #clear row by shifting board down for y1 in reversed(range(y)): for x in range(BOARDWIDTH): self.boardWithPieces[x][y1+1] = self.boardWithPieces[x][y1] self.board[x][y1+1] = self.board[x][y1] else: y -= 1 self.totalCompletedLines += self.completedLines self.level = 1 + int(self.totalCompletedLines/10) self.updateScore() def updateScore(self): #scores for completed lines if self.completedLines == 1: self.score += (ONELINEPTS * self.level) elif self.completedLines == 2: self.score += (TWOLINEPTS * self.level) elif self.completedLines == 3: self.score += (THREELINEPTS * self.level) elif self.completedLines == 4: #TETRIS!! self.score += (FOURLINEPTS * self.level) #score for soft and hard dropping self.score += self.softDropDistance * 1 self.score += self.hardDropDistance * 4 #clear old tallies self.completedLines = 0 self.softDropDistance = 0 self.hardDropDistance = 0 #returns a boolean if a row is completed def isCompletedRow(self, y): completed = True for x in range(BOARDWIDTH): if self.boardWithPieces[x][y] == BLANK: completed = False return completed def checkGameState(self): if self.level == 11: self.gameState = WIN def reset(self): self.clearBoard() self.completedLines = 0 self.totalCompletedLines = 0 self.score = 0 self.level = LEVELONE self.gameState = ACTIVE self.softDropDistance = 0 self.hardDropDistance = 0