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_adding_piece_to_full_column_shoul_throw(self): g = GameBoard() while not g.column_full(3): g.add_piece(0, 3) self.assertRaises(IndexError, lambda: g.add_piece(0, 3))
def __init__(self): self.mw = tkinter.Tk() self._board = [] self.default_image = tkinter.PhotoImage(file="empty2.gif") self.default_image_r = tkinter.PhotoImage(file="Red2.gif") 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) self.gboard = GameBoard(6) p1 = ComputerPlayer( "Y", self.buttons_2d_list ) #no input required from user, p1 and p2 are computer players, with given colours p2 = ComputerPlayer("R", self.buttons_2d_list) print("\tCLCIK ON ANY BUTTON ON THE GRID TO START" ) #the user must click on any button to start the sim self.players_lst = (p1, p2) self.currnt_player_index = 0 self.winner = False
def __init__(self, method): super().__init__() self.cart_items = QLabel() self.ga_info = QLabel() self.table = GameBoard(20, 20, self, method) self.setLayout(self.init_ui()) self.showMaximized()
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 make_move_ai(self, board): best_move = -1, -1 if self.val == "O": best_val = -1000 for cols in range(3): for rows in range(3): if board.isValidMove(cols, rows): temp_board = GameBoard() temp_board.board = copy.deepcopy(board.board) temp_board.playpiece(cols, rows, self.val) move_val = self.minimax(temp_board, 0, False) if move_val > best_val: best_val = move_val best_move = cols, rows else: best_val = 1000 for cols in range(3): for rows in range(3): if board.isValidMove(cols, rows): temp_board = GameBoard() temp_board.board = copy.deepcopy(board.board) temp_board.playpiece(cols, rows, self.val) move_val = self.minimax(temp_board, 0, True) if move_val < best_val: best_val = move_val best_move = cols, rows print("Player " + self.val + ": Minimax Score = " + str(best_val) + " - Optimal move = " + str(best_move)) board.playpiece(best_move[0], best_move[1], self.val)
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 test_getting_the_piece_at_a_given_location(self): g = GameBoard() g.add_piece(0, 3) g.add_piece(1, 4) self.assertEquals(g.get_piece_at(3,0), 0) self.assertEquals(g.get_piece_at(4,0), 1) self.assertEquals(g.get_piece_at(5,0), None)
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 two_players_menu(): player1 = input("Enter player 1's name: ") player2 = input("Enter player 2's name: ") gameboard1 = GameBoard(player1) gameboard2 = GameBoard(player2) setUpMenu(gameboard1, gameboard2) gameboard1_attack = GameBoard(player1) gameboard2_attack = GameBoard(player2) attackPhaseMenu(False, gameboard1, gameboard2, gameboard1_attack, gameboard2_attack) os.system('clear') print("Winner: " + winner)
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 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 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 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 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 main(): args = greeting() initialBoard = getFromFile(args.infile) print "You entered:\n\r" printBoard(initialBoard) g = GameBoard(initialBoard, args.toroidal) g.simulate(args.num_generations) print "\n\rAfter " + str(args.num_generations)\ + " generations, the board will look like:\n\r" printBoard(g.board)
def __init__(self, colour, buttns_list): Player.__init__(self, colour) self.buttons_2d_list = buttns_list self.name = "Computer Player" self.__space = ' ' self.gboard = GameBoard(6)
def main(): gb = GameBoard(3, 3) player_2 = AI() player_2.move(gb) player_2.move(gb) print gb.position
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 start(self): self.screen = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT), MODE) self.gameboard = GameBoard((GAME_SIZE, GAME_SIZE), self) self.scoreboard = ScoreBoard((WINDOW_WIDTH - GAME_SIZE, WINDOW_HEIGHT), self.score_manager) self.topmenu = TopMenu((GAME_SIZE, WINDOW_HEIGHT - GAME_SIZE)) self.mainmenu = MainMenu((WINDOW_WIDTH, WINDOW_HEIGHT), self) self.gameovermenu = GameOverMenu((WINDOW_WIDTH, WINDOW_HEIGHT), self) while not self.done: key = pygame.key.get_pressed() left, right = self._get_movement(key) #if key[pygame.K_ESCAPE]: # self.done = True for event in pygame.event.get(): if event.type == pygame.QUIT: self.done = True if self.state == GameState.Running: self._tick(left, right) elif self.state == GameState.MainMenu: self._main_menu_tick(left, right) elif self.state == GameState.GameOver: self._game_over_tick() pygame.display.flip() self.time_passed = self.clock.tick(FPS) pygame.quit()
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 traverse_by_cols(): gb = GameBoard.get_board() max_rows = gb.get_row_count() max_cols = gb.get_column_count() for c in range(max_cols): for r in range(max_rows): cell = gb.get_cell(r,c) __blink_cell(cell)
def __change_labels(label): gb = GameBoard.get_board() max_rows = gb.get_row_count() max_cols = gb.get_column_count() for r in range(max_rows): for c in range(max_cols): cell = gb.get_cell(r, c) cell.set_label(label)
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 __init__(self, mode, difficulty, screen, menu): self.mode = mode self.screen = screen self.current_player = None #x always goes first self.player = None self.pc = None self.menu = menu self.gameBoard = GameBoard() self.AI = MoveGenerator(difficulty)
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
class BoardWindow(QWidget): def __init__(self, method): super().__init__() self.cart_items = QLabel() self.ga_info = QLabel() self.table = GameBoard(20, 20, self, method) self.setLayout(self.init_ui()) self.showMaximized() def init_ui(self): main_layout = QHBoxLayout() font = QFont("Sans", 12) self.cart_items.setText(f"\nAgent: Wózek widłowy\nPrzedmioty:") self.cart_items.setFont(font) self.cart_items.setAlignment(Qt.AlignTop) main_layout.addWidget(self.cart_items) for i in range(self.table.columnCount()): self.table.setColumnWidth(i, 55) for i in range(self.table.rowCount()): self.table.setRowHeight(i, 45) self.table.setIconSize(QSize(45, 45)) main_layout.addWidget(self.table) ga_pic = QLabel() pic = QPixmap("images/dna.png") pic.setDevicePixelRatio(8) ga_pic.setPixmap(pic) self.ga_info.setFont(font) ga_title = QLabel("Algorytm genetyczny:") ga_title.setFont(font) ga_info = QFormLayout() ga_info.addRow(ga_pic, ga_title) ga_info.addRow(QLabel(""), self.ga_info) main_layout.addLayout(ga_info) return main_layout @pyqtSlot(str, name="Update cart items info") def update_items_info(self, info): self.cart_items.setText( f"\nAgent: Wózek widłowy\nPrzedmioty:\n\n{info}") @pyqtSlot(str, name="Update genetic algorithm info") def update_ga_info(self, info): self.ga_info.setText(info)
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 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(): """ 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 test_bad_args(): """ Verify we handle dumb coding! """ with pytest.raises(ValueError): GameBoard(width=-1, height=15) with pytest.raises(ValueError): GameBoard(width=1, height=0) g = GameBoard(width=1, height=1) with pytest.raises(ValueError): g.search(word_list=None) with pytest.raises(ValueError): g.search(word_list=[])
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 reset(): # all functions whose names do not begin with underscore will appear as menu options under MyFuncs gb = GameBoard.get_board() max_rows = gb.get_row_count() max_cols = gb.get_column_count() for r in range(max_rows): for c in range(max_cols): cell = gb.get_cell(r, c) cell.set_color("GRAY") __change_labels('O')
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 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")
def search(): gb = GameBoard.get_board() word = input("Enter word for which to search: ") h = gb.get_row_count() w = gb.get_column_count() done = False for row in range(h): for col in range(w): done = search_east(gb, row, col, word, 0) if done: return
def word_search(): gb = GameBoard.get_board() word = input("Enter word for which to search: ") h = gb.get_row_count() w = gb.get_column_count() for row in range(h): k = 0 for col in range(w): letter = gb.get_label(row, col) if letter == word[k]: k += 1 if k == len(word): #found word __highlight_row(row, col, len(word)) break
def init_game(): file = open("Resources/Places.txt", "r") lines = [] for line in file: line = line.strip() lines.append(line.split()) h = len(lines) w = len(lines[0]) gb = GameBoard.get_board() gb.set_size(h, w) for row in range(h): for col in range(w): letter = lines[row][col] gb.set_label(row, col, letter)
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 demo(): import random import time #get a reference to the GameBoard #you will use this reference to communicate with the gameboard gb = GameBoard.get_board() #resize it to the specified dimensions gb.set_size(6,8) row = 3 col = 4 #change the color of specified cell gb.set_color(row, col, "RED") #change the label of the specified cell gb.set_label(row, col, "X") #Retrieve the name of the color of the specified cell c = gb.get_color(row, col) print("Cell ", row, col, " is colored ", c) #Retrieve the label of the specified cell letter = gb.get_label(row, col) print("Cell ", row, col, " has label ", letter) #Retrieve the number of rows in the board max_rows = gb.get_row_count() #Retrieve the number of columns in the board max_cols = gb.get_column_count() #Iterate over the board and assign random letters to the cells for row in range(max_rows): for col in range(max_cols): letter = chr(random.randint(ord('A'), ord('Z'))) gb.set_label(row, col, letter) time.sleep(0.1)
def __init__(self, **kwargs): super(FilGame, self).__init__(**kwargs) # define tile types self.tiles = [] # holds all tile widgets self.types = { #'arrow': {'id': 1, 'rot': True, 'mov': True}, #'start': {'id': 2, 'rot': False, 'mov': False}, 'movchair': {'id': 1, 'rot': False, 'mov': True}, 'rotchair': {'id': 2, 'rot': True, 'mov': True}, 'couch3m': {'id': 4, 'rot': False, 'mov': False}, } self.images = self.setup_images() # set background image self.bg = Image(source=os.path.join('assets', 'bg.png'), pos=(0,0), width=glo.const.WIDTH, height=glo.const.HEIGHT) self.bg.allow_stretch = True self.bg.keep_ratio = False self.add_widget(self.bg) # set up game board self.board = GameBoard() self.board.load() # place tiles for starting level self.setup()
__author__ = 'Alexis' import getpass import sys from gameboard import GameBoard if __name__ == '__main__': while True: words = getpass.getpass(prompt='Please enter words: ') words = words.lower() gameboard = GameBoard(words) gameboard.setupBoard() gameboard.board.append(["Letters guessed:"]) letters_guessed = [] gameboard.board.append(letters_guessed) while gameboard.guess_wrong < 6: guess = raw_input("What is your guess?") guess = guess.lower() letters_guessed.append(guess) gameboard.getGuess(guess) gameboard.guessWrong(guess) gameboard.printBoard() if gameboard.guess_right == len(set(words)) - (1 if ' ' in words else 0): print "You win!" play_again = raw_input("Would you like to play again? (Y/N)") if play_again == "Y": break else: print "Thanks for playing!" sys.exit(0) if gameboard.guess_wrong >= 6:
def test1b(self): g = GameBoard(test1) g.simulate(2) #test in email self.assertEqual(test1bans, g.board)
def test8(self): g = GameBoard(test8) g.simulate(1) #single row self.assertEqual(test8ans, g.board)
def test7(self): g = GameBoard(test7) g.simulate(1) #diagnols self.assertEqual(test7ans, g.board)
def test6(self): g = GameBoard(test6) g.simulate(1) #all 1s self.assertEqual(test6ans, g.board)
def test5(self): g = GameBoard(test5) g.simulate(1) # different perimeters self.assertEqual(test5ans, g.board)
def test4(self): g = GameBoard(test4) g.simulate(1) #weird bounds self.assertEqual(test4ans, g.board)
def test3(self): g = GameBoard(test3) g.simulate(1) #single digit self.assertEqual(test3ans, g.board)
def test2(self): g = GameBoard(test2) g.simulate(1) #all zeroes self.assertEqual(test2, g.board)
def test_testing_for_a_full_column(self): g = GameBoard() for i in range(g.NUM_ROWS): g.add_piece(0, 3) self.assertTrue(g.column_full(3))
class UserInterface(QMainWindow): 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 initUI(self): centralWidget = QWidget() self.setCentralWidget(centralWidget) self.setWindowTitle(self._gameBoard.name) self.setWindowIcon(QIcon(os.path.join('./Pictures/', 'berserker_icon.png'))) #Apparently this doens't work the same way on a mac. self.statusBar().showMessage('Ready!') vbox = QVBoxLayout() centralWidget.setLayout(vbox) self.gameStats = GameStats(self) self.mapView = MapView(self) self.bottomButtons = BottomButtons(self) vbox.addWidget(self.gameStats) vbox.addWidget(self.mapView) vbox.addWidget(self.bottomButtons) screen = QDesktopWidget().screenGeometry() self.setGeometry((screen.width() - (self.gameboard.width - 1) * 20) / 2, (screen.height() - self.gameboard.height * 20 - 200) / 2, 500, 400) self.show() def getGameboard(self): return self._gameBoard def getIsTowerSelected(self): return self._isTowerSelected def setIsTowerSelected(self, boolean): self._isTowerSelected = boolean def getSelectedTower(self): return self._selectedTower def setSelectedTower(self, towerType): self._selectedTower = towerType def getIsTowerBeingHovered(self): return self._isTowerHovered def setIsTowerBeingHovered(self, boolean, tower): self._isTowerHovered = boolean self._towerBeingHovered = tower def getTowerBeingHovered(self): return self._towerBeingHovered def getGameStats(self): return self.gameStats def getTimePassed(self): return self._timePassed def setWaveFinishTime(self, value): self._waveFinishTime = value def getGameOver(self): return self._gameover def timerEvent(self, event): # The time passed attribute helps with setting the enemy appearance interval and tower firerate. self._timePassed += 1 self.mapView.summonEnemy() self.mapView.moveEnemies() self.mapView.checkShooting() self.mapView.moveProjectiles() self.mapView.update() def loseGame(self): self.bottomButtons.clockTimer.stop() self.timer.stop() self.statusBar().showMessage('Game has ended. You lost.') self._gameover = True self.popUp = QFrame() self.popUp.setGeometry(500, 500, 100, 100) vbox = QVBoxLayout() youLost = QLabel() youLost.setPixmap(QPixmap(os.path.join('./Pictures/', "game_over.png"))) vbox.addWidget(youLost) done = QPushButton("Done") vbox.addWidget(done) self.popUp.setLayout(vbox) self.popUp.move(self.mapToGlobal(QPoint(0,0)).x() + self.gameboard.width*blockSize / 2 - 130, self.mapToGlobal(QPoint(0,0)).y() + self.gameboard.height*blockSize / 2) self.popUp.show() done.clicked.connect(self.backToMainMenu) def winGame(self): self.bottomButtons.clockTimer.stop() self.timer.stop() self.statusBar().showMessage('Game has ended. You won.') self._gameover = True self.popUp = QFrame() self.popUp.setGeometry(500, 500, 100, 100) vbox = QVBoxLayout() youLost = QLabel() youLost.setPixmap(QPixmap(os.path.join('./Pictures/', "victory.png"))) vbox.addWidget(youLost) done = QPushButton("Done") vbox.addWidget(done) self.popUp.setLayout(vbox) self.popUp.move(self.mapToGlobal(QPoint(0,0)).x() + self.gameboard.width*blockSize / 2 - 130, self.mapToGlobal(QPoint(0,0)).y() + self.gameboard.height*blockSize / 2) self.popUp.show() done.clicked.connect(self.backToMainMenu) def backToMainMenu(self): self._parent.show() self.popUp.deleteLater() self.deleteLater() def getGameSpeed(self): return self._gameSpeed def setGameSpeed(self, value): self._gameSpeed = value def getWaveFinishTime(self): return self._waveFinishTime def getTimer(self): return self.timer isTowerSelected = property(getIsTowerSelected, setIsTowerSelected) selectedTower = property(getSelectedTower, setSelectedTower) isTowerHovered = property(getIsTowerBeingHovered) towerBeingHovered = property(getTowerBeingHovered) gamestats = property(getGameStats) gameboard = property(getGameboard) timePassed = property(getTimePassed) gameover = property(getGameOver) gameSpeed = property(getGameSpeed, setGameSpeed) waveFinishTime = property(getWaveFinishTime, setWaveFinishTime)
class LocalGame: #Constructor params: #@mode: 1 or 2, repping either 1 or 2 players #@difficulty = "Easy", "Normal" or "Hard"; only used if in 1P mode #@board_coordinates = starting (x,y) coordinate of the board #@screen = screen to blit to def __init__(self, mode, difficulty, screen, menu): self.mode = mode self.screen = screen self.current_player = None #x always goes first self.player = None self.pc = None self.menu = menu self.gameBoard = GameBoard() self.AI = MoveGenerator(difficulty) def run_game(self): clock = pygame.time.Clock() #Determine whether AI or player goes first self.determine_turns() '''Game Loop''' while (not (self.check_game_over() or self.check_tie()) and (self.menu.current_state != 0)): #Event Processing mouse_click = (0,0) mouse_position = pygame.mouse.get_pos() for event in pygame.event.get(): if event.type == pygame.QUIT: self.menu.current_state = -1 return if event.type == pygame.MOUSEBUTTONUP: mouse_click = mouse_position #Logic if (self.mode == 1): if (self.current_player == self.player): self.player_click(mouse_click[0], mouse_click[1]) else: self.pc_move() elif (self.mode == 2): try: mouse_x = mouse_click[0] mouse_y = mouse_click[1] self.player_click(mouse_x, mouse_y) except: pass #Drawing self.draw_background() self.draw_buttons() self.draw_buttons_hover(mouse_position[0], mouse_position[1]) self.draw_marker_hover(mouse_position[0], mouse_position[1]) self.gameBoard.draw_markers(self.screen, constants.BOARD_COORDINATES) if (self.check_game_over()): self.switch_turns() #Turn is switched after move, so switch back to draw winner correctly if (self.current_player == "x"): l = self.gameBoard.x_list else: l = self.gameBoard.o_list self.draw_win(l) pygame.display.flip() #If the game is over, pause for a moment to let player see that game is over if (self.check_game_over() or self.check_tie()): time.sleep(1) clock.tick(60) #For 1p, determine whether pc or player goes first. "x" always goes first def determine_turns(self): num = randint(1,10) if (num%2 == 0): self.player = "x" self.pc = "o" self.current_player = self.player else: self.player = "o" self.pc = "x" self.current_player = self.pc def check_game_over(self): if ((self.gameBoard.check_win(self.gameBoard.x_list, constants.WIN_POSITION_LIST)) or (self.gameBoard.check_win(self.gameBoard.o_list, constants.WIN_POSITION_LIST))): return True else: return False def check_tie(self): if (len(self.gameBoard.taken_positions_list) == 9) and (not (self.check_game_over())): return True else: return False def player_click(self, mouse_x, mouse_y): b_x = constants.BOARD_COORDINATES[0] b_y = constants.BOARD_COORDINATES[1] if b_x < mouse_x < (b_x + constants.TILE_DIMENSION): if (b_y < mouse_y < (b_y + constants.TILE_DIMENSION*3)) and ((((mouse_y - b_y) // 100)*3) not in self.gameBoard.taken_positions_list): position = ((mouse_y - b_y) // 100)*3 self.gameBoard.update_player_list(self.current_player, position) self.switch_turns() elif b_x + constants.TILE_DIMENSION < mouse_x < (b_x + 2*constants.TILE_DIMENSION): if (b_y < mouse_y < (b_y + constants.TILE_DIMENSION*3)) and (((((mouse_y - b_y) // 100)*3+1) not in self.gameBoard.taken_positions_list)): position = ((mouse_y - b_y) // 100)*3+1 self.gameBoard.update_player_list(self.current_player, position) self.switch_turns() elif b_x + 2*constants.TILE_DIMENSION < mouse_x < (b_x + 3*constants.TILE_DIMENSION): if (b_y < mouse_y < (b_y + constants.TILE_DIMENSION*3)) and (((((mouse_y - b_y) // 100)*3+2) not in self.gameBoard.taken_positions_list)): position = ((mouse_y - b_y) // 100)*3+2 self.gameBoard.update_player_list(self.current_player, position) self.switch_turns() elif (constants.GAME_BACK_ARROW_COOR[0] < mouse_x < constants.GAME_BACK_ARROW_COOR[0] + constants.BACK_ARROW.get_size()[0]): if (constants.GAME_BACK_ARROW_COOR[1] < mouse_y < constants.GAME_BACK_ARROW_COOR[1] + constants.BACK_ARROW.get_size()[1]): self.menu.current_state = 0 if (constants.GAME_RESET_COOR[0] < mouse_x < constants.GAME_RESET_COOR[0] + constants.RESET.get_size()[0]): if (constants.GAME_RESET_COOR[1] < mouse_y < constants.GAME_RESET_COOR[1] + constants.RESET.get_size()[1]): self.reset_game() def pc_move(self): if self.current_player == "x": AI_list = self.gameBoard.x_list player_list = self.gameBoard.o_list else: AI_list = self.gameBoard.o_list player_list = self.gameBoard.x_list time.sleep(0.2) pc_move = self.AI.generate_move(AI_list, player_list, self.gameBoard.taken_positions_list) self.gameBoard.update_player_list(self.current_player, pc_move) self.switch_turns() def draw_background(self): self.screen.blit(constants.BACKGROUND, (0,0)) self.screen.blit(constants.HEADING, constants.HEADING_COORDINATES) self.screen.blit(constants.TITLE, constants.TITLE_COORDINATES) self.screen.blit(constants.BOARD_SURFACE, constants.BOARD_COORDINATES) def draw_marker_hover(self, mouse_x, mouse_y): if (self.mode == 1): if (self.current_player == self.player): self.draw_marker_hover_helper(mouse_x, mouse_y) else: self.draw_marker_hover_helper(mouse_x, mouse_y) def draw_marker_hover_helper(self, mouse_x, mouse_y): if (self.current_player == "x"): hover_marker = constants.HOVER_EX else: hover_marker = constants.HOVER_OH self.gameBoard.draw_hover(mouse_x, mouse_y, hover_marker, self.screen, constants.BOARD_COORDINATES) def draw_markers(self): self.gameBoard.draw_markers(self.screen, constants.BOARD_COORDINATES) def draw_buttons(self): self.screen.blit(constants.BACK_ARROW, constants.GAME_BACK_ARROW_COOR) self.screen.blit(constants.RESET, constants.GAME_RESET_COOR) def draw_buttons_hover(self, mouse_x, mouse_y): if (constants.GAME_BACK_ARROW_COOR[0] < mouse_x < constants.GAME_BACK_ARROW_COOR[0] + constants.BACK_ARROW.get_size()[0]): if (constants.GAME_BACK_ARROW_COOR[1] < mouse_y < constants.GAME_BACK_ARROW_COOR[1] + constants.BACK_ARROW.get_size()[1]): self.screen.blit(constants.BACK_ARROW_HOVER, constants.GAME_BACK_ARROW_COOR) if (constants.GAME_RESET_COOR[0] < mouse_x < constants.GAME_RESET_COOR[0] + constants.RESET.get_size()[0]): if (constants.GAME_RESET_COOR[1] < mouse_y < constants.GAME_RESET_COOR[1] + constants.RESET.get_size()[1]): self.screen.blit(constants.RESET_HOVER, constants.GAME_RESET_COOR) def draw_win (self, given_list): gset = set(given_list) for item in constants.WIN_POSITION_LIST: wset = set(item) intersection = wset.intersection(gset) if (len(intersection) == 3): if (self.current_player == "x"): surface = constants.WINNING_EX else: surface = constants.WINNING_OH for i in intersection: self.gameBoard.draw_marker(self.current_player, i, self.screen, constants.BOARD_COORDINATES, surface) def reset_game(self): self.gameBoard.x_list = [] self.gameBoard.o_list = [] self.gameBoard.taken_positions_list = [] def switch_turns(self): if (self.current_player == self.player): self.current_player = self.pc else: self.current_player = self.player def change_difficulty(self, diff): self.AI.change_difficulty(diff)
def test_adding_piece_should_return_pieces_final_position(self): g = GameBoard() result = g.add_piece(0, 3) self.assertEqual(result, (3,0))
def test_adding_pieces_should_places_pieces_in_lowest_unoccupied_cell_in_column(self): g = GameBoard() g.add_piece(0, 3) result = g.add_piece(0, 3) self.assertEqual(result, (3, 1))
def __init__(self): self.__gameboard = GameBoard()