def __init__(self): root = tk.Tk() root.title("Schaken") self.game = Game(root) self.game.setStartBoard() # self.game.setEnPassantBoard() # self.game.setRokadeBoard() # self.game.setCheckBoard() # self.game.setCheckmateBoard() # self.game.setPawnBoard() # self.game.setRookBoard() # self.game.setKnightBoard() # self.game.setBishopBoard() # self.game.setQueenBoard() # self.game.setKingBoard() # self.game.setPromoteBoard() board = GameBoard(root, self.game) board.pack(side="top", fill="both", expand="true", padx=4, pady=4) root.mainloop() # for piece in self.game.whitePiecesInGame + self.game.blackPiecesInGame: # for piece in self.game.blackPiecesInGame: # for piece in self.game.whitePiecesInGame: # if isinstance(piece, Rook): # print("--------") # r,c = self.game.getCurrentPosOfPiece(piece) # print("(r,c)=",(r,c)) # print("possibleMoves=", piece.possibleMoves(r,c)) # print("legalMovesAndNotBlockedInPath=", piece.legalMovesAndNotBlockedInPath((r,c), None, self.game.board)) # print("takeableMoves=", piece.takeableMoves((r,c), None, self.game.board))
def main(): gb = GameBoard(3, 3) player_2 = AI() player_2.move(gb) player_2.move(gb) print gb.position
def mainMenu(self): self.header("Minesweeper") inputTool = InputTool({"2": "Play", "3": "Help", "4": "Settings", "5": "High Scores", "6": "Exit"}) self.screen = inputTool.getInput() # set up and reset the game if (self.screen == "2"): self.firstTurn = True if (self.difficulty == "1"): self.num_rows = 9 self.num_cols = 9 self.num_mines = 10 self.mines_remaining = 10 elif (self.difficulty == "2"): self.num_rows = 12 self.num_cols = 12 self.num_mines = 24 self.mines_remaining = 24 elif (self.difficulty == "3"): self.num_rows = 16 self.num_cols = 16 self.num_mines = 40 self.mines_remaining = 40 self.game_board = GameBoard(self.num_rows, self.num_cols, self.num_mines) self.game_board.createBoard() self.game_board.placeMines() self.game_board.fillBoard() self.start_time = time.time()
def test_horizontal(): """ Validate the rows members match what are in the data matrix. """ g = GameBoard(width=5, height=5) for row in g.rows: # Convert the search string back into a list of characters row_list = list(row) assert row_list in g.data
def __init__(self, players, display=True, bot_time_limit_ms=5000, disable_time_limit=False, pieces=None, cols=7, rows=17): self.display = display self._running = True self._display_surf = None self.size = self.weight, self.height = 640, 400 self.bot_time_limit = bot_time_limit_ms self.disable_time_limit = disable_time_limit self.hex_radius = 20 self.hex_size = hex_coords.Point(self.hex_radius, self.hex_radius) self.piece_radius = 9 self.layout = Layout(hex_coords.layout_flat, self.hex_size, hex_coords.Point(50, 50)) self.controllers = [] for i in range(len(players)): p = players[i] if p == PlayerType.HUMAN: self.controllers.append(None) elif p == PlayerType.RANDOM: from bots.randombot import RandomBot self.controllers.append(RandomBot()) elif p == PlayerType.TRIVIAL_MCTS: from bots.trivial_mcts import MctsPlayer self.controllers.append(MctsPlayer(i, bot_time_limit_ms)) elif p == PlayerType.EBL_MCTS: import bots.ebl_mcts as ebl_mcts self.controllers.append(ebl_mcts.Player(i)) elif p == PlayerType.K2BD_MCTS: from bots.k2bd_mcts import KevBot self.controllers.append(KevBot(i, bot_time_limit_ms)) elif p == PlayerType.MJ: from bots.mj import PengWin self.controllers.append(PengWin(i, bot_time_limit_ms)) elif p == PlayerType.WARIO: from bots.wariobot import WarioBot self.controllers.append(WarioBot(i)) self.board = GameBoard(len(players), pieces=pieces, cols=cols, rows=rows) self.pending_action = None self.score_pos = (300, 30) self.score_spacing = 30 self.selected_piece = None
def experimentGenerator(): """returns random board with 2 pieces already on it""" board = GameBoard() x, y = choice(board.possibleMoves()) board.addMove(GameBoard.O, x, y) x, y = choice(board.possibleMoves()) board.addMove(GameBoard.X, x, y) return board
def __init__(self, ship_owner, bomb_owner, board_size): #receive all data from the match self.board = GameBoard(board_size).set_up_board() self.ship_owner = ship_owner self.bomb_owner = bomb_owner self.ship_positions = ship_owner.board_positions self.bombs_positions = bomb_owner.bomb_position self.plot_ship()
def main(): armada = Armada() armada.printShips() print(len(armada)) newBoard = GameBoard(6) print(newBoard.showBoard()) newBoard.placePiece(1, 1, armada[0]) print(newBoard.showBoard())
def initGameObjects(self): self.prevGameState = self.gameState self.inp = Input() self.gameBoard = GameBoard(self) self.shipMan = ShipManager(self.screen, GameBoard.BOTTOM) self.hitMan = HitManager(self.screen) self.opponent = Opponent(self.screen, OpponentType.AI) self.helpergui = Helpergui(self) self.sound = Sound(self.screen)
def test_hashing(self): board = GameBoard('./puzzles/only_18_steps.txt') board2 = GameBoard('./puzzles/only_18_steps.txt') self.assertEqual(board.hash_state(), board2.hash_state()) board.blocks['A'].move_block(np.array([1, 0])) board.blocks['D'].move_block(np.array([-1, 0])) self.assertEqual(board.hash_state(), board2.hash_state()) board.blocks['z'] = Block((1, 1), (5, 5)) board2.blocks['z'] = Block((1, 1), (5, 5)) self.assertEqual(board.hash_state(), board2.hash_state()) board.blocks['z'].move_block(np.array([1, 1])) self.assertNotEqual(board.hash_state(), board2.hash_state()) board.blocks['z'].move_block(np.array([-1, -1])) self.assertEqual(board.hash_state(), board2.hash_state())
def test_file_loading(self): board = GameBoard('./puzzles/only_18_steps.txt') self.assertEqual(board.shape, tuple([9, 6])) block_names = [ 'A', '*', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O' ] for bn in block_names: self.assertTrue(bn in board.blocks)
def main(): # create a game board - with randomized colors (rgby) gb = GameBoard(NUM_OF_ROWS_COLUMNS, GAME_COLORS, COLORS_COLOR) steps_played = 0 print("Welcome to the Coloring Game!") print( f"Please enter one of the possible colors to play this game: {GAME_COLORS}" ) gb.print_board() # start listening on inputs from the user (the actual game) print(f"Available game colors: {GAME_COLORS}") print(f"Please select a color:") for line in sys.stdin: # game over if played too many steps if steps_played == ALLOWED_STEPS: print( f'Game over! Unfortunately you ran out of steps. (Allowed steps: {ALLOWED_STEPS})' ) break steps_played += 1 # remove the newline char from the input line line = line[:-1] # when quit/q - exit game if line in ["quit", "q"]: print("Exiting game!") return # when input is a color - paint the board accordingly if line in GAME_COLORS: # color with the selected color gb.color(line) if gb.is_game_finished(): print("Congratulations! you finished the game") break # TODO: add an option to retry print("Current game board:") gb.print_board() print( f"Please select the next color: (Remaining steps: {ALLOWED_STEPS - steps_played})" ) print("Goodbye! Hope to see you back soon!")
def __init__(self, boardSize, cellSize, setSize, numFeatures, handSize, numPlayers): self.boardSize = boardSize self.cellSize = cellSize self.setSize = setSize self.numFeatures = numFeatures self.gameboard = GameBoard(boardSize, cellSize) self.cardSet = Card.createCardSet(setSize,numFeatures) self.deck = set(self.cardSet) self.players = [Player(i, self.drawCardsFromDeck(handSize)) for i in range(numPlayers)] self.numPlayers = numPlayers
def performanceSystem(first_strategy, board=None, second_strategy=DEFAULT_STRATEGY): if not board: board = GameBoard() i = len(board.trace) while not board.gameEnded(): player, strategy = GameBoard.X, second_strategy if i % 2: player, strategy = GameBoard.O, first_strategy x, y = board.chooseMove(strategy, player) board.addMove(player, x, y) i += 1
def __init__(self): self.mw = tkinter.Tk( ) #assigning the GUI method Tk to variable self.mw # default image = black hole/empty space self.default_image = tkinter.PhotoImage( file="empty2.gif" ) #all buttons will start with this deafult image when game starts and need to make instance so tkinter does keeps image # red and yellow represent the disc colours self.default_image_r = tkinter.PhotoImage( file="Red2.gif" ) #IMPORTANT TO MAKE INSTANCE OF ALL IMAGES IN __INIT__ METHOD TO PREVENT IMAGES FROM DISAPPAERING self.default_image_y = tkinter.PhotoImage(file="Yellow2.gif") self.size = 7 self.buttons_2d_list = [] for i in range(self.size): self.row = [' '] * self.size self.buttons_2d_list.append( self.row ) #creating a button list in order to configure mechanics of the game nad game GUI self.gboard = GameBoard(6) #gameboard reference print("\tYELLOW or RED") colour = input("Please Select Your Colour(y/r): " ) #giving user option to select colour colour = colour.lower() if colour == "y": p1 = HumanPlayer("Y") #assigning colours to variables p1 and p2 p2 = ComputerPlayer("R", self.buttons_2d_list) opnt = input("\t Do you want to play against a computer(y/n)? ") if opnt == "y": p2 = ComputerPlayer("R", self.buttons_2d_list) else: p2 = HumanPlayer("R") else: p1 = HumanPlayer("R") p2 = ComputerPlayer("Y", self.buttons_2d_list) opnt = input("\t Do you want to play against a computer(y/n)? ") if opnt == "y": p2 = ComputerPlayer("Y", self.buttons_2d_list) else: p2 = HumanPlayer("Y") self.players_lst = (p1, p2) # creating a list of the players self.currnt_player_index = 0 #initilise the current player to zero self.winner = False #initilise winner to false
def testWidth(self): self.input_file = os.path.join('./Test_Files/', 'Wrong Size.txt') gb = GameBoard() raised = False try: game = gb.readMapData(self.input_file) except CorruptedMapFileError: raised = True self.assertTrue(raised, 'Exception raised')
def start_new_game(self): """ Initialisation of the game. Prints introduction. Asks about being first player. """ # Game introduction print('Tic-Tac-Toe!') self._player_first = input("Do you want to be the first player? (Y/N): " ).strip().upper() == 'Y' self._player_char = self.CHARS[not self._player_first] print('Your char is: {}'.format(self._player_char)) self._computer_char = self.CHARS[self._player_first] self._board = GameBoard()
def initVars(self): self.winner = False self.tie = False self.first_player = self.LETTERS[randint(0, 1)] self.last_player = None self.turn_nr = 0 self.board = GameBoard() kwargs = { 'difficulty': self.difficulty, 'board': self.board, 'letter': self.pc_letter, 'user_letter': self.user_letter } self.pc_player = PCPlayer(**kwargs)
def main(): width, height = -1, -1 bad = lambda x: x != 3 and x != 4 while bad(width) or bad(height): height, width = [ int(x) for x in raw_input( "Enter height and width of game board: ").split() ] gb = GameBoard(height, width) p1 = Player() p2 = AI() ttoe = TicTacToe(gb, p1, p2) ttoe.play()
def start(width=10, height=20): global is_bottom_colliding global is_side_colliding global tempCounter global engine global direction global fallingSpeed global actualFallingSpeed global tFallingSpeed gameBoard = GameBoard(width, height) engine = gameEngine.GameEngine(gameBoard) ConsoleRenderer.start() engine.create_random_object() engine.assign_next_object_to_current() listener = keyboard.Listener(on_press=on_press, on_release=on_release) listener.start() while (not quitRequested): is_side_colliding = False is_bottom_colliding = False if not engine.gameOver and not pause: if (direction == -1): engine.move_object(-1, 0) direction = 0 if (direction == 1): engine.move_object(1, 0) direction = 0 if (direction == 2): engine.rotate_object() direction = 0 tFallingSpeed = actualFallingSpeed - math.floor( engine.scoreManager.linesRemoved / 4) if tempCounter >= actualFallingSpeed: engine.move_object(0, 1) tempCounter = 0 engine.remove_full_lines(gameBoard) renderFrame(x=engine.activeObjectPosition[0], y=engine.activeObjectPosition[1], gameBoard=gameBoard, gameObject=engine.activeObject)
def __init__(self): self.mw = tkinter.Tk() self.size = 3 self.buttons_2d_list = [] for i in range(self.size): self.row = [' '] * self.size self.buttons_2d_list.append(self.row) # place players 1 and 2 in tuple for turn based game. self.gboard = GameBoard(3) p1 = HumanPlayer("X") p2 = ComputerPlayer("O", self.buttons_2d_list) self.players_lst = (p1, p2) self.currnt_player_index = 0 self.winner = False
def game(self, stdscr): ''' Actual game''' self.level = GameBoard(self.screen_size) #making gameboard #game loop while self.pressed_key != ord('q'): #main while loop #PLAYER CONTROL SECTION self.pressed_key = self.level.board.getch( ) #getting key from player #CPUs SECTIONS for cpu in self.population.cpus: self.level.unprint(cpu) #erasing all snakes cpu.move(self.morsel) #generating moves if cpu.collides(): #collision checking self.population.cpus.remove(cpu) self.level.unprint(cpu) if cpu.eats(self.morsel): #snake eats an apple pass #temporarly disabled if cpu.starved(): #if snake dies of self.population.cpus.remove(cpu) #starvation self.level.unprint(cpu) #it need to be killed #IS FUN OVER? if self.population.empty(): #checking if board has its winner self.level.unprint(self.population.cpus[0]) self.population.new_generation() #winner is having a child #SCREEN SECTION #printing everything out for cpu in self.population.cpus: #printing every snake self.level.inprint(cpu) self.level.board.border() self.level.print_aux( self.morsel, #print nesseceties self.population.generation) self.level.board.refresh() #refreshing the screen
def critic(trace, strategy): """produces training examples by successor rule""" training_examples = [] for index in range(2, len(trace)): if index == len(trace) - 1: if GameBoard(trace[index]).isDraw(): training_examples.append((GameBoard(trace[index]).getFeatures(), 0)) elif GameBoard(trace[index]).hasWon(GameBoard.O): #print "We have won!" training_examples.append((GameBoard(trace[index]).getFeatures(), 10)) else: # means we have lost #print "We have lost!" training_examples.append((GameBoard(trace[index - 1]).getFeatures(), -10)) elif index % 2 == 0: training_examples.append((GameBoard(trace[index - 2]).getFeatures(), GameBoard(trace[index]).evaluateBoard(strategy, GameBoard.O))) return training_examples
def main(): #init load_config() #config contains all the constants for the game pygame.init() pygame.display.set_caption(config_get_screencaption()) pygame.mouse.set_visible(1) #1 == visible, 0==invisible clock = pygame.time.Clock() gameBoard = GameBoard( ) #gameBoard is supposed to be a self-controlled singleton, it is just perturbed by main() frames_elapsed = 0 #game testing gameBoard.add_tower() #Main Loop while 1: print("tick") if (frames_elapsed % 21 == 5): #spawn creeps gameBoard.add_creep() if (frames_elapsed % 41 == 40): #spawn towers gameBoard.add_tower() clock.tick(config_get_fps()) #number of frames per second pygame.display.set_caption(config_get_screencaption() + " --- FPS: " + str(clock.get_fps())) gameBoard.update() if gameBoard.is_game_over(): print("game over!") return pygame.display.flip( ) #reveal the scene - this is the last thing to do in the loop #Handle Input Events for event in pygame.event.get(): if event.type == QUIT: return elif event.type == KEYDOWN and event.key == K_ESCAPE: return if event.type is MOUSEBUTTONUP: if event.dict[ 'button'] == 1: #'button' == 1:left click, 2 == middle, 3 == right ; 'pos' == (x,y) == position of click gameBoard.do_left_click(event.dict['pos']) elif event.dict['button'] == 3: #right click gameBoard.do_right_click(event.dict['pos']) frames_elapsed += 1
def __init__(self,Display): """ here we need a Display to show popup windows on screen play : it says about game is paused or playing GameBoard : to play game and display it save : it save text to display in popup yes : '' no : '' x : cross mark in popup """ self.Display=Display self.play=True self.GameBoard=GameBoard(self.Display) font=pygame.font.SysFont('comicsansms', 32) self.save=font.render('Save' , True, [200,200,200]) font=pygame.font.SysFont('comicsansms', 25) self.yes=font.render('YES',True,[200,200,200]) self.no=font.render('NO',True,[200,200,200]) font=pygame.font.SysFont('comicsansms', 17) self.x=font.render('X',True,[0,0,0])
def main(): """ Main entry point for the script. :return: None """ logging.basicConfig(stream=sys.stdout) logger = logging.getLogger() options = process_cli(logger) if options is None: exit(1) # Load in the dictionary dictionary = [] with open(options.dictionary_file) as file: for word in file: dictionary.append(word.rstrip()) logger.info('Generating game board...') game_board = GameBoard(height=options.board_height, width=options.board_width) logger.debug('====================') logger.debug('Generated Game Board') logger.debug('====================') logger.debug(game_board) # Search the board results = game_board.search(word_list=dictionary) # Print results print('====================') print(' RESULTS ') print('====================') print(f'Total words found: {len(results)}') grid_width = 6 for i in range(0, len(results), grid_width): sublist = results[i:i + grid_width] print(''.join(f'{x:<10}' for x in sublist)) print(f'Board creation time: {game_board.gen_time:.5f} seconds') print(f'Board search time: {game_board.search_time:.5f} seconds')
def initialize(): world_size = 0 mine_count = 0 while (True): try: world_size = int(input('size: ')) break except: print('wrong input type') while (True): try: mine_count = int(input('mines: ')) if mine_count <= world_size * world_size: break print( f'mines should be less than number of cells ({world_size*world_size})' ) except: print('wrong input type') return GameBoard(world_size, mine_count)
def main() -> None: """Creates board and runs the game""" parser = argparse.ArgumentParser( description='Conways Game of life that runs for as many generations as you like') parser.add_argument('x', type=int, help='Size of x-axis') parser.add_argument('y', type=int, help='Size of y-axis') args = parser.parse_args() # Create board board = GameBoard(args.x, args.y) # Program loop finished = "a" while finished != 'q': board.draw_board() finished = input( "Press enter continue and 'q' to quit\n> ") if finished.lower() == "q": print("Program terminated")
def __init__(self, parent): super().__init__(parent) self._gameBoard = GameBoard() self._parent = parent self._gameover = False self._isTowerSelected = False self._isTowerHovered = False self._towerBeingHovered = None self._selectedTower = None self._waveFinishTime = 0 self._gameSpeed = self._parent.speed self._timePassed = 0 self.timer = QBasicTimer() self._gameBoard.readMapData(os.path.join('./Maps/', self._parent.map)) self.timer.start(self._gameSpeed, self) self.initUI()
def testFlawlessMapFile(self): self.input_file = os.path.join('./Maps/', 'Test Map.txt') gb = GameBoard() game = None try: game = gb.readMapData(self.input_file) except CorruptedMapFileError: self.fail("Loading a correctly structured file caused an exception") self.assertEqual(gb.name, "Test Map", "Map name not correct") self.assertEqual(gb.width, 50, "Width not correc") self.assertEqual(gb.height, 20, "Height not correct") self.assertEqual(gb.startingLives, 10, "Lives not correct") self.assertEqual(gb.money, 100, "Money not correct") self.assertEqual(gb.getTowers(), ["t1", "t2"], "Towers not correct") self.assertEqual(gb.waves, [[50, ["e1","e2", "e1", "e1", "e1"]], [10, ["e1", "e1", "e2", "e1", "e1"]]], "Waves not correct")