def _init(self): self.selected = None self.board = Board() self.player = 1 self.valid_moves = [] self.lastMove = None self.boards = {} self.hintSquarePiece = None self.hintSquareToMove = None self.nodes = 0
def __init__(self): # instanciate board self.board = Board() self.players = [] self.player_count = 0 self.playing = 0 self.launch_game()
def main_loop(level): settings = Settings() settings.set_screen_sizes(screen.get_size()) delta_time = clock.tick() / 1000 board_list = generate_map_board_list(load_level(level), settings) map_board = Board(board_list, settings) settings.enemy_waves = generate_enemy_waves(load_level(level)) add_buttons(screen, settings, [towers.NormalTower, towers.FastTower, towers.SplitTower]) background_surface = create_background_surface(screen.get_size()) while True: events = pg.event.get() for event in events.copy(): if event.type == pg.QUIT: terminate() elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: action = menu(screen) if action == 'restart': return 'restart' elif event.type == pg.MOUSEBUTTONDOWN: if event.button == 3: settings.action = None if settings.lives <= 0: return game_over(screen) if not settings.enemy_waves and not settings.enemy_sprites.sprites(): return 'next_level' screen.fill(pg.Color('black')) screen.blit(background_surface, (0, 0)) add_text_info(screen, settings) map_board.update(events.copy(), screen, action=settings.action) settings.all_sprites.draw(screen) settings.all_sprites.update(delta_time=delta_time, screen=screen, mouse_pos=pg.mouse.get_pos()) pg.display.flip() delta_time = clock.tick(60) / 1000
def initiallize_game(n_joys): """initiallizes the game n_joys: number of game pads detected""" # initiallizing screen width = int(args.width_factor * args.screen_width / args.game_size) space = int(args.space_factor * args.screen_width / args.game_size) screen = pygame.display.set_mode((args.screen_width, args.screen_height)) state = State(size=args.game_size, win=args.game_win, next_turn=random.randint(1, 2)) screenpos = ScreenPos(c=args.camera_pos, t=args.camera_angle, e=args.screen_pos, height=args.screen_height, width=args.screen_width, horizon=args.horizon) board = Board(state=state, width=width, space=space, height=args.board_height, colors=args.board_colors, edge_colors=args.board_edge_colors) cursor = Cursor(state=state, width=width, space=space, colors=(args.cursor_color_1, args.cursor_color_2), edge_colors=(args.cursor_edge_color_1, args.cursor_edge_color_2)) game = Game(state=state, width=width, space=space, colors=(args.player_color_1, args.player_color_2), edge_colors=(args.player_edge_color_1, args.player_edge_color_2)) get2dcoords = Get2dcoords(light_pos=args.light_pos, offset=args.offset, screenpos=screenpos) drawer = Draw(max_shading=args.max_shading) cover = Cover(cover_image=os.path.join('.', 'images', args.cover_image), cover_music=os.path.join('.', 'sounds', args.cover_music), screen_shape=(args.screen_width, args.screen_height)) controller = Controller(size=args.game_size, num_joys=n_joys, time_limit=args.time_limit, max_alpha=args.max_alpha, max_beta=args.max_beta) player = [args.player1_name, args.player2_name] announcements = [] return screen, state, screenpos, board, cursor, game, get2dcoords, drawer, cover, \ controller, player, announcements
def __init__(self, users: List[str]): self.users: List[str] = users self.n_of_players: int = len(users) self.players: List[Player] = self.init_players(users) self.deck = Deck() self.board: Board = Board(self.n_of_players) self.minister: Player = choice(self.players) self.director: Player = None self.last_minister: Player = None self.last_director: Player = None self.phase: GamePhase = GamePhase.PROPOSE_DIRECTOR self.cards: List[Card] = self.deck.take_3_cards() self.votes: Dict[str, Vote] = dict() self.last_update = datetime.now() self.casted_imperius_by: Player = None self.chaos_counter: int = 0 self.investigated_players: List[Player] = list() self.casted_expelliarmus: bool = False
class Game: def __init__(self): self._current_player = 0 self._players = [Player(0), Player(1)] self._board = Board() self._gameUI = GameUI(self._players[0]) def game_loop(self): valid_keys = [1, 2, 3, 4, 5, 6, 7] update_ui = False done = False player_won = False row = -1 column = -1 while not done: update_ui = False # check for player input events for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYUP: if player_won: # N key if event.key == 110: done = True # Y key elif event.key in [121, 122]: player_won = False done = False self.restart() else: # Try to insert to a column column = (event.key - 49) if column + 1 in valid_keys: row = self.add_chip(column) # Adding a chip wa possible if row > -1: player_won = self.check_player_wins( self.get_current_player()) update_ui = True # UI has to be updated if update_ui: self._gameUI.draw_board(self.get_current_player(), row, column) if player_won: self._gameUI.draw_player_won(self.get_current_player()) else: self.switch_player() self._gameUI.draw_player(self.get_current_player()) def switch_player(self): self._current_player += 1 self._current_player = self._current_player % 2 def restart(self): self._board.clear() self._gameUI.init_ui(self.get_current_player()) def add_chip(self, column): player = self.get_current_player() return self._board.add_chip(player, column) def check_player_wins(self, player): return self._board.check_player_wins(player) def get_board(self): return self._board def get_player(self, id): return self._players[id] def get_current_player(self): return self._players[self._current_player]
from classes.board import Board from classes.NN import Network from classes.mutator import Mutator import csv import os WIDTH = 600 HEIGHT = 600 ROWS = 24 COLS = 24 BLACK = (0, 0, 0) SURFACE = pygame.display.set_mode((WIDTH, HEIGHT)) CLOCK = pygame.time.Clock() B = Board(SURFACE, WIDTH, HEIGHT, ROWS, COLS, BLACK, False) GENS = 250 POP_SIZE = 250 MUTATE_CHANCE = 0.3 MUTATE_WEIGHT_CHANCE = 0.02 RETAIN_TOP_RATIO = 0.3 RETAIN_REST_RATIO = 0.1 LAYERS = [24, 14, 3] def get_file_name(): files = os.listdir("data") files.sort()
def run(file): init_cells = load_data_from_file(file) # Parsed coordinates of active cells during the "step zero" offset = 5 # The minimal distance between the outermosts active cells and the edge of the board board = Board(init_cells, offset) board.play()
- Number of squares must obviously be greater than number of bombs - Number of squares -> Min : 4 // Max : 100 Enjoy ! """) print("By hugomez\n") squares, bombs = 0, 0 valid_board_infos = False while not valid_board_infos: try: squares = int(input(">> Number of squares : \n")) if squares < 4: raise ValueError bombs = int(input(">> Number of bombs : \n")) if bombs > (squares**2) - 1 or bombs == 0: raise ValueError valid_board_infos = True except ValueError: print( "/!\ Please enter valid numbers (checkout the rules enumerated above)" ) board = Board(squares, bombs) board.init_board() while not board.finished: print( "------------------------------------------------------------------\n") board.print_board() print("\n") move = board.make_move() board.check_status(move)
from classes.board import Board from classes.player import Player print("Welcome to Tic Tac Toe!") while True: theBoard = Board() player1 = Player() player2 = Player() player1.marker, player2.marker = Player.player_input() print('Player 1 choose ' + player1.marker + ', Player 2 choose ' + player2.marker) print(('Player 1' if theBoard.turn == 1 else 'Player 2') + ' will play first!') theBoard.game_state = input( 'Are you ready to play? Enter Yes or No: ').lower().startswith('y') while theBoard.game_state: if theBoard.turn == 1: theBoard.do_turn(player1) else: theBoard.do_turn(player2) if not input('Do you want to play again? Enter Yes or No: ').upper( ).startswith('Y'): break
import os from classes.board import Board from classes.piece import Piece """ Main program """ # Instantiate the board class board = Board().create() while True: # Clears the screen between loop iterations (linux only) os.system("clear") # Prints the board print("\n\n".join( ["\t".join([str(cell) for cell in row]) for row in board])) # Asks for coordinates and prints the contents of the selected box col_s, row_s = input("Input coordinates (x y): ").split() col = int(col_s) row = int(row_s) print("Selected piece: {}".format(board[row][col])) if board[row][col] == " ": print("Empty box, please try again") # Checks movement of pawns elif board[row][col] == "Pv" or board[row][col] == "P^": pawn = Piece()
from tkinter import * from classes.board import Board, generateFourPlayerSet if __name__ == '__main__': fenetre = Tk() board = Board((9, 9)) generateFourPlayerSet() board.initBoard(fenetre) fenetre.mainloop()
class Game: def __init__(self): self._players = [Player(0), Player(1)] self._current_player = 0 self._board = Board() self._gameUI = GameUI(self._players[0]) def end_game(self, player): if messagebox.askquestion(player.get_name() + 'WON!', 'Restart game?') == 'yes': self.switch_player() self._gameUI.draw_player(self.get_current_player()) def switch_player(self): self._current_player += 1 self._current_player = self._current_player % 2 def restart(self): self._board.clear_board() self._gameUI.init_ui(self.get_current_player()) def add_chip(self, column): player = self.get_current_player() return self._board.try_add_chip(player, column) def check_player_wins(self, player): return self._board.check_player_wins(player) def get_board(self): return self._board def get_player(self, id): return self._players[id] def get_current_player(self): return self._players[self._current_player] def game_loop(self): row = -1 column = -1 valid_keys = [1, 2, 3, 4, 5, 6, 7] update_ui = False end_game = False player_won = False while not end_game: update_ui = False # check for player input events for event in pygame.event.get(): if event.type == pygame.QUIT: end_game = True elif event.type == pygame.KEYUP: column = (event.key - 49) if column + 1 in valid_keys: row = self.add_chip(column) if row > -1: player_won = self.check_player_wins( self.get_current_player()) update_ui = True if update_ui: self._gameUI.draw_board(self.get_current_player(), row, column) if player_won: if messagebox.askquestion( self.get_current_player().get_name() + ' WON!', 'Restart game?') == 'yes': player_won = False end_game = False self.restart() else: end_game = True else: self.switch_player() self._gameUI.draw_player(self.get_current_player())
class Game: #Game class constructor def __init__(self,window, gamemode): self._init() self.window = window self.lastMove = None self.winner = None self.gamemode = gamemode self.button = None self.time = None #method to update the game state def update(self, time_elapsed): if time_elapsed != None: self.time = time_elapsed self.drawBoard() self.drawSideBoard() self.draw_valid_moves(self.valid_moves) pygame.display.update() #private method to initialize class attributes def _init(self): self.selected = None self.board = Board() self.player = 1 self.valid_moves = [] self.lastMove = None self.boards = {} self.hintSquarePiece = None self.hintSquareToMove = None self.nodes = 0 #method to draw the game board on screen def drawBoard(self): self.window.fill((76,188,228)) for row in range(ROWS): for col in range(COLS): if (col, row) == self.hintSquarePiece: pygame.draw.rect(self.window, GREEN, (row*SQUARE_SIZE,col*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE), 0) else: pygame.draw.rect(self.window, BLUE, (row*SQUARE_SIZE,col*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE), 0) pygame.draw.rect(self.window, BLACK, (row*SQUARE_SIZE,col*SQUARE_SIZE,SQUARE_SIZE,SQUARE_SIZE), 1) for row in range(ROWS): for col in range(COLS): piece = self.board.board[row][col] if piece != 0: self.window.blit(color_dic[piece], (SQUARE_SIZE * col - 10, SQUARE_SIZE * row - 10)) #method to draw the right side of the screen def drawSideBoard(self): if self.player == 1: myfont = pygame.font.SysFont('', 60) sideboard_title = myfont.render('BLACK TURN', True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 50)) self.window.blit(sideboard_title, text_rect) elif self.player == 2: myfont = pygame.font.SysFont('', 60) sideboard_title = myfont.render('WHITE TURN', True, WHITE) text_rect = sideboard_title.get_rect(center=(1000, 50)) self.window.blit(sideboard_title, text_rect) if self.gamemode == 1 or (self.gamemode == 2 and self.player == 1): self.button = Button(BLUE, 850, 150, 300, 100, 'Press for a hint') self.button.draw(self.window, True) elif self.gamemode == 3 or (self.gamemode == 2 and self.player == 2): self.button = Button(BLUE, 825, 150, 350, 100, 'Press for computer play') self.button.draw(self.window, True) if (self.gamemode == 3 and self.time != None): myfont = pygame.font.SysFont('', 40) sideboard_title = myfont.render("AI move took: " + str(round(self.time,5)) + " s", True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 300)) self.window.blit(sideboard_title, text_rect) sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 350)) self.window.blit(sideboard_title, text_rect) elif (self.gamemode == 1 and self.time != None): myfont = pygame.font.SysFont('', 40) sideboard_title = myfont.render("Hint calc. took: " + str(round(self.time,5)) + " s", True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 300)) self.window.blit(sideboard_title, text_rect) sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 350)) self.window.blit(sideboard_title, text_rect) elif (self.gamemode == 2 and self.time != None): myfont = pygame.font.SysFont('', 40) sideboard_title = myfont.render("Calculation took: " + str(round(self.time,5)) + " s", True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 300)) self.window.blit(sideboard_title, text_rect) sideboard_title = myfont.render("Visited nodes: " + str(self.nodes) + " nodes", True, BLACK) text_rect = sideboard_title.get_rect(center=(1000, 350)) self.window.blit(sideboard_title, text_rect) if self.winner != None and self.winner != -1: myfont = pygame.font.SysFont('', 60) if self.winner == 1: sideboard_title = myfont.render('BLACK WINS!', True, (0,0,0)) text_rect = sideboard_title.get_rect(center=(1000, 700)) self.window.blit(sideboard_title, text_rect) elif self.winner == 2: sideboard_title = myfont.render('WHITE WINS!', True, (255,255,255)) text_rect = sideboard_title.get_rect(center=(1000, 700)) self.window.blit(sideboard_title, text_rect) elif self.winner == 0: sideboard_title = myfont.render('TIE!', True, (72,68,68)) text_rect = sideboard_title.get_rect(center=(1000, 650)) self.window.blit(sideboard_title, text_rect) myfont = pygame.font.SysFont('', 40) sideboard_title = myfont.render('Press ENTER to continue', True, (72,68,68)) text_rect = sideboard_title.get_rect(center=(1000, 750)) self.window.blit(sideboard_title, text_rect) #method to reset the game state def reset(self): self._init() #method to get the current player (turn) def getPlayer(self): return self.player #method to get the last move made def getLastMove(self): return self.lastMove #method to get the current board def getBoard(self): return self.board #method to update the last move made def updateLastMove(self,row,col): self.lastMove = row,col #method that shows to the player what are the possible moves for the selected piece def select(self,row,col): if self.selected: result = self.move(row,col) if not result: self.selected = None self.select(row,col) piece = self.board.get_piece(row,col) if piece == self.player: self.selected = (row,col) self.valid_moves = self.board.get_valid_moves(row, col) return True return False #method that moves a piece and changes turn def move(self,row,col): piece = self.board.get_piece(row,col) if self.selected and piece == 0 and (row,col) in self.valid_moves: oldRow, oldCol = self.selected self.board.move_piece(oldRow,oldCol, row, col) self.updateLastMove(row,col) self.change_turn() else: return False return True #method that executes the ai move def ai_move(self, row, col): oldRow, oldCol = self.selected self.board.move_piece(oldRow,oldCol, row, col) self.updateLastMove(row,col) self.change_turn() #method that changes the turn def change_turn(self): self.valid_moves = [] self.player = 3 - self.player self.hintSquarePiece = None self.hintSquareToMove = None if self.board.board_as_string() in self.boards.keys(): self.boards[self.board.board_as_string()] += 1 else: self.boards.update({self.board.board_as_string() : 1}) #method that draws the valid moves on the screen def draw_valid_moves(self,moves): for move in moves: row, col = move if (row, col) == self.hintSquareToMove: self.window.blit(GREEN_DOT,(SQUARE_SIZE*col+66,SQUARE_SIZE*row+66)) else: self.window.blit(GRAY_DOT,(SQUARE_SIZE*col+66,SQUARE_SIZE*row+66)) #method that verifies if the game is over or not def checkWin(self): if self.lastMove == None : return -1 if self.boards[self.board.board_as_string()] == 3: self.winner = 0 return 0 row, col = self.lastMove self.winner = self.board.threeInRow(row,col, 3-self.player) return self.board.threeInRow(row,col, 3-self.player) #method that evaluates the score of the board on easy level def easyLevelHeuristics(self, row, col, player): if self.board.threeInRow(row, col, player) == player: return 1000 else: return 0 #method that evaluates the score of the board on medium level def mediumLevelHeuristics(self, row, col, player): if self.board.threeInRow(row, col, player) == player: return 1000 elif self.board.twoInRow(row, col, player) == player: return 200 else: return 0 #method that evaluates the score of the board on hard level (best heuristic) def hardLevelHeuristics(self, row, col, player): if self.board.threeInRow(row, col, player) == player: return 1000 elif self.board.twoInRow(row, col, player) == player: return 200 elif self.board.twoPiecesClose(row, col, player) == player: return 100 else: return 0 #method that chooses the heuristic according to the level selected in the menu def chooseHeuristics(self, level, row, col, player): if level == 1: return self.easyLevelHeuristics(row, col, player) elif level == 3: return self.mediumLevelHeuristics(row, col, player) elif level == 6: return self.hardLevelHeuristics(row, col, player) #method that implements the maximum part of the minimax with alpha-beta cuts algorithm def max_with_alpha_beta_cuts(self, lastRow, lastCol, maxDepth, alpha, beta, player, ordering, level): maxv = -2000 depth = maxDepth - 1 finalRow = None finalCol = None finalOldRow = None finalOldCol = None opponent = 3 - player result = self.chooseHeuristics(level, lastRow, lastCol, opponent) x = random.randint(0,9)/10 if result == 1000: return (-result - depth - x, 0, 0, 0, 0) elif result != 1000 and depth == -1: return (-result - depth - x, 0, 0, 0, 0) if player == 1: pieces = deepcopy(self.board.get_black_pieces()) else: pieces = deepcopy(self.board.get_white_pieces()) for piece in pieces: oldRow, oldCol = piece possibleMoves = self.board.get_valid_moves(oldRow, oldCol) orderedMoves = [] if ordering != None: for i in range(0, len(possibleMoves)): moveRow, moveCol = possibleMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) evaluation = self.chooseHeuristics(level, lastRow, lastCol, player) orderedMoves.append((moveRow, moveCol, evaluation)) self.board.move_piece(moveRow,moveCol, oldRow, oldCol) orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering) else: orderedMoves = possibleMoves for i in range(0,len(orderedMoves)): self.nodes += 1 if ordering != None: moveRow, moveCol, score = orderedMoves[i] else: moveRow, moveCol = orderedMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) (m, min_old_row, min_old_col, min_row, min_col) = self.min_with_alpha_beta_cuts(moveRow, moveCol, depth, alpha, beta, opponent, ordering, level) if m > maxv: maxv = m finalRow = moveRow finalCol = moveCol finalOldRow = oldRow finalOldCol = oldCol self.board.move_piece(moveRow,moveCol, oldRow, oldCol) if maxv >= beta: return (maxv, finalOldRow, finalOldCol, finalRow, finalCol) if maxv > alpha: alpha = maxv return (maxv, finalOldRow, finalOldCol, finalRow, finalCol) #method that implements the minimum part of the minimax with alpha-beta cuts algorithm def min_with_alpha_beta_cuts(self, lastRow, lastCol, maxDepth, alpha, beta, player, ordering, level): minv = 2000 finalRow = None finalCol = None finalOldRow = None finalOldCol = None depth = maxDepth - 1 opponent = 3 - player result = self.chooseHeuristics(level, lastRow, lastCol, opponent) x = random.randint(0,9)/10 if result == 1000: return (result + depth + x, 0, 0, 0, 0) elif result != 1000 and depth == -1: return (result + depth + x, 0, 0, 0, 0) if player == 1: pieces = deepcopy(self.board.get_black_pieces()) else: pieces = deepcopy(self.board.get_white_pieces()) for piece in pieces: oldRow, oldCol = piece possibleMoves = self.board.get_valid_moves(oldRow, oldCol) orderedMoves = [] if ordering != None: for i in range(0, len(possibleMoves)): moveRow, moveCol = possibleMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) evaluation = self.chooseHeuristics(level, lastRow, lastCol, player) orderedMoves.append((moveRow, moveCol, evaluation)) self.board.move_piece(moveRow,moveCol, oldRow, oldCol) orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering) else: orderedMoves = possibleMoves for i in range(0,len(orderedMoves)): self.nodes += 1 if ordering != None: moveRow, moveCol, score = orderedMoves[i] else: moveRow, moveCol = orderedMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) (m, max_old_row, max_old_col, max_row, max_col) = self.max_with_alpha_beta_cuts(moveRow, moveCol, depth, alpha, beta, opponent, ordering, level) if m < minv: minv = m finalRow = moveRow finalCol = moveCol finalOldRow = oldRow finalOldCol = oldCol self.board.move_piece(moveRow,moveCol, oldRow, oldCol) if minv <= alpha : return (minv, finalOldRow , finalOldCol ,finalRow, finalCol) if minv < beta: beta = minv return (minv, finalOldRow , finalOldCol ,finalRow, finalCol) #method that implements the maximum part of the minimax algorithm def max(self, lastRow, lastCol, maxDepth, player, ordering, level): maxv = -2000 depth = maxDepth - 1 finalRow = None finalCol = None finalOldRow = None finalOldCol = None opponent = 3 - player result = self.chooseHeuristics(level, lastRow, lastCol, opponent) x = random.randint(0,9)/10 if result == 1000: return (-result - depth - x, 0, 0, 0, 0) elif result != 1000 and depth == -1: return (-result - depth - x, 0, 0, 0, 0) if player == 1: pieces = deepcopy(self.board.get_black_pieces()) else: pieces = deepcopy(self.board.get_white_pieces()) for piece in pieces: oldRow, oldCol = piece possibleMoves = self.board.get_valid_moves(oldRow, oldCol) orderedMoves = [] if ordering != None: for i in range(0, len(possibleMoves)): moveRow, moveCol = possibleMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) evaluation = self.chooseHeuristics(level, lastRow, lastCol, player) orderedMoves.append((moveRow, moveCol, evaluation)) self.board.move_piece(moveRow,moveCol, oldRow, oldCol) orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering) else: orderedMoves = possibleMoves for i in range(0,len(orderedMoves)): self.nodes += 1 if ordering != None: moveRow, moveCol, score = orderedMoves[i] else: moveRow, moveCol = orderedMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) (m, min_old_row, min_old_col, min_row, min_col) = self.min(moveRow, moveCol, depth, opponent, ordering, level) if m > maxv: maxv = m finalRow = moveRow finalCol = moveCol finalOldRow = oldRow finalOldCol = oldCol self.board.move_piece(moveRow,moveCol, oldRow, oldCol) return (maxv, finalOldRow, finalOldCol, finalRow, finalCol) #method that implements the minimum part of the minimax algorithm def min(self, lastRow, lastCol, maxDepth, player, ordering, level): minv = 2000 finalRow = None finalCol = None finalOldRow = None finalOldCol = None depth = maxDepth - 1 opponent = 3 - player result = self.chooseHeuristics(level, lastRow, lastCol, opponent) x = random.randint(0,9)/10 if result == 1000: return (result + depth + x, 0, 0, 0, 0) elif result != 1000 and depth == -1: return (result + depth + x, 0, 0, 0, 0) if player == 1: pieces = deepcopy(self.board.get_black_pieces()) else: pieces = deepcopy(self.board.get_white_pieces()) for piece in pieces: oldRow, oldCol = piece possibleMoves = self.board.get_valid_moves(oldRow, oldCol) orderedMoves = [] if ordering != None: for i in range(0, len(possibleMoves)): moveRow, moveCol = possibleMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) evaluation = self.chooseHeuristics(level, lastRow, lastCol, player) orderedMoves.append((moveRow, moveCol, evaluation)) self.board.move_piece(moveRow,moveCol, oldRow, oldCol) orderedMoves = sorted(orderedMoves, key = lambda x: x[2], reverse=ordering) else: orderedMoves = possibleMoves for i in range(0,len(orderedMoves)): self.nodes += 1 if ordering != None: moveRow, moveCol, score = orderedMoves[i] else: moveRow, moveCol = orderedMoves[i] self.board.move_piece(oldRow, oldCol, moveRow,moveCol) (m, max_old_row, max_old_col, max_row, max_col) = self.max(moveRow, moveCol, depth, opponent, ordering, level) if m < minv: minv = m finalRow = moveRow finalCol = moveCol finalOldRow = oldRow finalOldCol = oldCol self.board.move_piece(moveRow,moveCol, oldRow, oldCol) return (minv, finalOldRow , finalOldCol ,finalRow, finalCol)
def __init__(self): self._current_player = 0 self._players = [Player(0), Player(1)] self._board = Board() self._gameUI = GameUI(self._players[0])
def Test__init__(self): b = Board() unittest.assertTrue(len(b.Squares) == 40)
from classes.board import Board from classes.robot import Robot f = open('list_moves.txt') list_moves_from_file = [line.rstrip('\n').split(",") for line in f] board_size = 5 step = 1 for moves in list_moves_from_file: print(moves) board = Board() board.generate(board_size) robot = Robot('ROBOT', 0, 0) robot.print_position() for move in moves: board.set_robot('O', robot.x, robot.y) robot.walk(move, step, board_size) robot.print_position() board.set_robot(robot.symbol, robot.x, robot.y) board.display()
game_board.reset_board() def ask_input(): """""" # Asking the user for the input while True: try: size = int(input("Introduce the number of rows and columns: ")) if size < 3: print("Input must be bigger than 2") continue break except: print("That's not a valid option!") return size length = ask_input() # Creating the board game_board = Board(length) # Variables where we are going to store the play of the user and computer column = 0 row = 0 inputQuit = "" # Playing the game game()