def place_pdu(self, context, client, x, y):
        if client == context.socket_player_white:
            if GameLogic.is_valid_position(context.boardmodel, x, y, Player.WHITE):
                affected_positions = GameLogic.get_affected_positions(context.boardmodel, x, y, Player.WHITE)
                GameLogic.apply_move(context.boardmodel, x, y, Player.WHITE)
                board_pdu = GameClientPDUCodec.update_board_pdu(Player.WHITE, affected_positions)
                context.request.send_req(context.socket_player_white, board_pdu)
                context.request.send_req(context.socket_player_black, board_pdu)
                next_turn_player = GameLogic.next_turn_player(context.boardmodel, Player.WHITE)

                white_count, black_count = context.boardmodel.count_disks()
                # if white_count > 4:
                #    context.end_game()

                if next_turn_player == Player.WHITE:
                    context.turn = context.socket_player_white
                    context.state = context.WHITE_TURN
                    context.state.turn_req(context)
                elif next_turn_player == Player.BLACK:
                    context.turn = context.socket_player_black
                    context.state = context.BLACK_TURN
                    context.state.turn_req(context)
                else:
                    # no valid movements->board full or no valid placements for any player
                    context.end_game()
            else:
                context.request.send_req(client, GameClientPDUCodec.place_error_pdu())
                context.request.send_req(client, GameClientPDUCodec.turn_pdu())
        else:
            # not your turn
            # read protocol, I don't remember if it's specified to report the error or not
            context.request.send_req(client, GameClientPDUCodec.place_error_pdu())
 def test_check_ace_eleven(self):
     gameLogic = GameLogic()
     player = Player(
         [Card('Hearts', 'A'), Card('Clubs', '2')], False, False, 500, 0)
     self.assertEqual(
         gameLogic.checkSum(player), 13,
         f"gameLogic.checkSum(player) = {gameLogic.checkSum(player)} // Player hand should sum to 13 because A is valued as 11"
     )
 def test_sum(self):
     gameLogic = GameLogic()
     player = Player(
         [Card('Hearts', 'A'), Card('Clubs', 'J')], False, True, 500, 0)
     self.assertEqual(
         gameLogic.checkSum(player), 21,
         f"gameLogic.checkSum(player) = {gameLogic.checkSum(player)} // Ace and Jack should sum to 21"
     )
 def test_check_double_ace(self):
     gameLogic = GameLogic()
     player = Player(
         [Card('Hearts', 'A'), Card('Clubs', 'A')], False, False, 500, 0)
     self.assertEqual(
         gameLogic.checkSum(player), 12,
         f"gameLogic.checkSum(player) = {gameLogic.checkSum(player)} // Player hand should be 12 because one A is valued as 11 and one as 1"
     )
 def __init__(self):
     self.controller = Controller()
     self.Handler = EventHandler(self.controller)
     self.object_list = []
     self.game_logic = GameLogic()
     self.fps_clock = pygame.time.Clock()
     self.fps = 60
     self.neuralnet = NeuralNetHolder()
     self.version = "v1.01"
 def test_check_ace_one(self):
     gameLogic = GameLogic()
     player = Player(
         [Card('Hearts', 'A'),
          Card('Clubs', 'J'),
          Card('Clubs', '9')], False, False, 500, 0)
     self.assertEqual(
         gameLogic.checkSum(player), 20,
         f"gameLogic.checkSum(player) = {gameLogic.checkSum(player)} // Player hand should sum to 20 because A is valued as 1"
     )
 def test_check_double_ace_and_normal_card(self):
     gameLogic = GameLogic()
     player = Player(
         [Card('Hearts', 'A'),
          Card('Clubs', 'A'),
          Card('Clubs', '10')], False, False, 500, 0)
     self.assertEqual(
         gameLogic.checkSum(player), 12,
         f"gameLogic.checkSum(player) = {gameLogic.checkSum(player)} // Player hand should be 12 because both aces are valued as 1"
     )
Пример #8
0
def run(col, row, k, ai_path_1, ai_path_2, fh, mode='t', full_path=None):
    if full_path is not None:
        ai_path_1 = full_path + ai_path_1
        ai_path_2 = full_path + ai_path_2
    main = GameLogic(col, row, k, 'l', debug=True)
    return main.Run(fh=fh,
                    mode=mode,
                    ai_path_1=ai_path_1,
                    ai_path_2=ai_path_2,
                    time=1200)
Пример #9
0
 def __init__(self):                                     # Initialize key objects
     
     self.game = GameLogic()
     self.grid = GameGrid()
     self.human = HumanView(self.game, self.grid)
     self.ai = AI_View(self.game, self.grid)
     self.showTitle()
Пример #10
0
    def draw(self, widget=None, events=None):
        self.drawingarea.window.draw_pixbuf(
            None, self.scaledbackground, 0, 0, int(round(self.shift_x)), int(round(self.shift_y))
        )
        for i in range(self.request.board_model.get_size()):
            for j in range(self.request.board_model.get_size()):
                player = self.request.board_model.get(i, j)
                if player == Player.WHITE:
                    self.draw_cell(i, j, self.scaledwhite)
                elif player == Player.BLACK:
                    self.draw_cell(i, j, self.scaledblack)
                elif (
                    self.yourturn
                    and self.toolbuttonShowHint.get_active()
                    and GameLogic.is_valid_position(self.request.board_model, i, j, self.player)
                ):
                    self.draw_cell(i, j, self.scaledhint)

        if (
            self.yourturn
            and self.selection_row is not None
            and self.selection_column is not None
            and self.selection_valid
        ):
            self.drawingarea.window.set_cursor(gtk.gdk.Cursor(gtk.gdk.HAND2))
            self.draw_cell(
                self.selection_row,
                self.selection_column,
                self.scaledwhite if self.player == Player.WHITE else self.scaledblack,
            )
        else:
            self.drawingarea.window.set_cursor(None)
Пример #11
0
    def initialize(self):
        self.player_frame = Frame(self.root)
        self.player_frame.pack(side=LEFT)

        self.enemy_frame = Frame(self.root)
        self.enemy_frame.pack(side=LEFT)

        self.menu_frame = Frame(self.root)
        self.menu_frame.pack(side=LEFT)

        # initialize GUI for player board
        divider = Label(self.player_frame,
                        text='  \n  \n \n  \n  \n  \n  \n  \n  \n  \n')
        divider.pack(side=TOP)

        self.enemy_buttons_2d_array = [[
            0 for x in range(self.player_board.get_board_size() + 1)
        ] for y in range(self.player_board.get_board_size() + 1)]

        # initialize GUI for enemy board
        for i in range(0, self.enemy_board.get_board_size()):
            for j in range(0, self.enemy_board.get_board_size()):
                b = Button(
                    self.enemy_frame,
                    text=' ',
                    command=lambda x=j, y=i: self.button_click_at_pos(x, y),
                    background="yellow")
                b.grid(row=i, column=j)
                self.enemy_buttons_2d_array[j][i] = b

        self.player_info_label = Label(self.menu_frame,
                                       text='You still have ships: ')
        self.player_info_label.pack(side=TOP)

        self.enemy_info_label = Label(self.menu_frame,
                                      text='Enemy still have ships: ')
        self.enemy_info_label.pack(side=TOP)

        greenbutton = Button(self.menu_frame,
                             text="Restart game",
                             command=lambda: self.restart_game(),
                             fg="brown")
        greenbutton.pack(side=LEFT)

        self.game_logic = GameLogic(self.player_board, self.enemy_board)
    def game_init(self):
        self.request.send_req(self.socket_player_white, GameClientPDUCodec.connect_ok_pdu(Player.WHITE))
        self.request.send_req(self.socket_player_black, GameClientPDUCodec.connect_ok_pdu(Player.BLACK))

        initial_board = GameLogic.initial_board_as_affected_positions(8)
        self.request.send_req(self.socket_player_white, GameClientPDUCodec.update_board_pdu(Player.WHITE, initial_board[0]))
        self.request.send_req(self.socket_player_white, GameClientPDUCodec.update_board_pdu(Player.BLACK, initial_board[1]))
        self.request.send_req(self.socket_player_black, GameClientPDUCodec.update_board_pdu(Player.WHITE, initial_board[0]))
        self.request.send_req(self.socket_player_black, GameClientPDUCodec.update_board_pdu(Player.BLACK, initial_board[1]))

        self.request.send_req(self.socket_player_black, GameClientPDUCodec.turn_pdu())
Пример #13
0
    def RunGameHuman(self):
        self.LoadObstacles()
        self.game = GameLogic(self, self.screen, self.level, self.text)
        self.GetSprites()
        self.player.DrawPlayer(self.screen)
        for o in self.obList:
            o.DrawObstacle(self.screen)
        self.menu.StartGame(self.screen)
        while self.playing and not self.collision.CheckCollision(
                self.obList, self.player):
            # Get the player movement
            self.HandlePlayerMovement()
            # Add other Obstacles
            self.AddObstacle()
            # Run the game logic
            self.game.TheGame(self.obList)
            # Refresh Rate
            self.clock.tick(120)

        pygame.time.delay(1000)
        self.menu.EndGameScreen(self.screen, self.player)
        pygame.time.delay(5000)
        self.menu.SetState('MainMenu')
Пример #14
0
class GuessingGame:
    def __init__(self, max_tries=5):
        self.logic = GameLogic(max_tries)

    def start(self):
        print(
            f"Welcome to NumGuesser!\n You have {self.logic.max_tries} tries to guess the right number between 1-1000.\n Do you want a starting clue?\nYes(Y), No(N)> "
        )
        choice = input()

        if (choice.lower() == "y"):
            print(self.logic.clue())
        elif (choice.lower() == "n"):
            print("No clue it is. Lets roll!")
        else:
            print("That's not a command, no clue for you. Lets roll!")

        running = True

        while running:
            print("Make your guess> ")
            guess = input()
            if (self.logic.make_guess(guess)):
                running = False
                print("Correct answer!")
            else:
                tries_left = self.logic.tries_left()
                if (tries_left == 0):
                    print(
                        f"You're out of tries, game over! Correct Answer was {self.logic.answer}"
                    )
                    running = False
                else:
                    print(
                        f"That's not quite it, You have {tries_left} tries left. here's a new clue!"
                    )
                    print(self.logic.clue())
Пример #15
0
def run_algorithm(algorithm, board, board_size):

    logic = GameLogic(State(board), board_size)
    if algorithm == 1:
        ids = IDS(State(board), logic)
        chosen = ids.run_search()
    elif algorithm == 2:
        bfs = BFS(State(board), logic)
        chosen = bfs.run_search()
    elif algorithm == 3:
        a_star = Astar(State(board), logic)
        chosen = a_star.run_search()
    else:
        raise Exception("No algorithm was chosen")
    if chosen is not None:
        to_print = ' '.join(map(str, chosen))
        with open('output.txt', 'w') as output_file:
            output_file.write(to_print)
Пример #16
0
def make_app():
    logic = GameLogic()
    _app = CokeApp(logic)
    return _app
Пример #17
0
 def __init__(self, max_tries=5):
     self.logic = GameLogic(max_tries)
Пример #18
0
            (r"/logout", LogoutHandler, dict(logic=logic)),
            (r"/chat/new", ChatMessageHandler, dict(logic=logic)),
            (r"/chat/update", ChatUpdateHandler, dict(logic=logic))
        ]

        #create random + safe cookie_secret key
        secret = base64.b64encode(uuid.uuid4().bytes + uuid.uuid4().bytes)
        settings = {
            "static_path": os.path.join(os.path.dirname(__file__), "static"),
            "template_path": os.path.join(os.path.dirname(__file__), "templates"),
            "cookie_secret": secret,
            "login_url": "/login",
            "xsrf_cookies":True,
            "debug":options.debug,
        }
        tornado.web.Application.__init__(self, handlers, **settings)

def make_app():
    logic = GameLogic()
    _app = CokeApp(logic)
    return _app

if __name__ == "__main__":

    logic = GameLogic()
    app = CokeApp(logic)
    app.listen(options.port)

    tornado.ioloop.IOLoop.current().spawn_callback(minute_loop, logic)

    tornado.ioloop.IOLoop.current().start()
Пример #19
0
 def updated_board_ind(self, context, player, affected_positions):
     GameLogic.apply_updated_positions(context.board_model, player, affected_positions)
     context.indication.updated_board_ind(player, affected_positions)
Пример #20
0
class GameLoop:
    
    def __init__(self):                                     # Initialize key objects
        
        self.game = GameLogic()
        self.grid = GameGrid()
        self.human = HumanView(self.game, self.grid)
        self.ai = AI_View(self.game, self.grid)
        self.showTitle()
          
    '''
    Evaluates player's guess against opponent fired upon:
    1. If the opponent's ship is hit, opponent's display grid is updated
    2. Prints results of the shot
    
    '''
    def shootAt(self, guess, opponent):
    
        result, label, shipKey = self.game.fire(
                               guess, opponent)             # Retrieve results of the guess
        if opponent == 'AI':                                # Opponent = AI
            print "Results:"
            if result:                                      # Hit 
                if label == "X":                            # Ship did not sink
                    self.grid.update(guess, 
                                     label, opponent)       # update display with a "X"
                    print("You hit one of the AI's ship!"),          
                else:      
                    for cell in self.game.aiShips[shipKey]: # Sunk ship
                        self.grid.update(cell,
                                 label, opponent)           # reveal ship type on game grid for human player
                    print("You sunk an AI ship!"),         
            else:                                           # Miss     
                print("You missed!"),                                                
        else:                                                   # Opponent = Human
            if result:                                          # Hit   
                if label == "X":                                # Ship did not sink
                    self.grid.update(guess, 
                                label, opponent)                # update display with a "X"
                    print("AI hit one of your ships!")        
                else:    
                    label = "O"                                 # Sunk ship             
                    for cell in self.game.humanShips[shipKey]:  # removes ship from the display grid
                        self.grid.update(cell, label, opponent)
    
                    print("AI sunk your ship!")          
            else:                                           # Miss
                print("AI missed!")
        print""

    def showTitle(self):                                    # Title & Credits
    
        print ("""
    
        Welcome to PYSHIP V1.0
    
        A battleship game written in Python
    
        By Ray "Cyberpup" Tong
    
        """)
    
    '''
    Auto plays
    
    '''
    
    def testMode(self):
        
        row = "ABCDEFGHIJ"
        col = "0123456789"
        pastGuesses = set()
        
        while True:                                     # Main loop
            self.grid.displayDual()                     # Display game grid  
            guess = row[randint(0,9)] + col[randint(0,9)]
            while guess in pastGuesses:
                guess = row[randint(0,9)] + col[randint(0,9)]    
            pastGuesses.add(guess) 
            print guess                          
            self.shootAt(guess, "AI")                                 
            if self.game.getNumOfShips('AI') == 0:      # If human wins, game's over
                print("Game over. You win!")            # otherwise, continue loop
                break
            guess = self.ai.guess()                     # AI's turn to fire
            self.shootAt(guess, "human")                              
            if self.game.getNumOfShips('human') == 0:   # If AI wins, game's over
                print("Game over. You lose!")           # otherwise, continue loop
                break
        print ""
        print "FINAL"
        self.grid.displayDual()                         # Display final grids
    
    '''
    Human vs AI play
    
    '''
    
    def gameMode(self):
        while True:                                     # Main loop
            self.grid.displayDual()                     # Display game grid 
            guess = self.human.guess()                  # Human's turn to fire
            self.shootAt(guess, "AI")                                 
            if self.game.getNumOfShips('AI') == 0:      # If human wins, game's over
                print("Game over. You win!")            # otherwise, continue loop
                break
            guess = self.ai.guess()                     # AI's turn to fire
            self.shootAt(guess, "human")                              
            if self.game.getNumOfShips('human') == 0:   # If AI wins, game's over
                print("Game over. You lose!")           # otherwise, continue loop
                break
        print ""
        print "FINAL"
        self.grid.displayDual()                         # Display final grids
Пример #21
0
class Player:

    gameLogic = GameLogic()

    def __init__(self, hand, isAI, playerChoice, balance, bet): 
        self.hand = hand                        # Hand list that will contain the cards the player has drawn
        self.isAI = isAI                        # Bool that shows if player is Artificial Intelligence or not
        self.playerChoice = playerChoice        # Bool that shows if it's players turn to hit or stand
        self.balance = balance                  # The initial balance of a player
        self.bet = bet                          # The bet each round

    def choseBetAmount(self):
        while True:                             # Loop
            choice = input("Please chose your desired bet(10, 20, 30, 40 or 50)")
            betList = [10, 20, 30, 40, 50]      # List containing possible bet amounts
            if int(choice) not in betList:      # If the entered bet is not in the bet list, repeat loop
                print("Your desired amount didn't match any of the allowed amounts - Try again!")
            elif self.balance - int(choice) >= 0:   # If their bet doesn't exceed their balance
                return int(choice)                  # Return the bet amount
            elif self.balance - int(choice) < 0:    # If their entered bet is higher than their current balance
                print("You don't have enough balance to place this bet - try again!")

    def checkBust(self):                        # Method that checks if the player exceeds 21, hits 21 or is below 21 in sum
        sum = self.gameLogic.checkSum(self)     # Call checkSum() method and recieve total sum of hand
        if sum > 21:                            # If the sum is greater than 21
            print(f"Player has lost the game with {sum} value!")    # Prints lost msg to user with total sum
            self.balance = self.balance - self.bet  # Update balance and print it
            self.printBalance()
            return False                        # Sets playerChoice to false so it breaks out of while-loop
        elif sum == 21:                         # If players total sum is exactly 21
            print(f"Player has hit {sum} - Dealers turn")   
            return False                        # Player is forced to stand - sets playerChoice to false to break out of while-loop
        else:                                   # If players total sum is below 21
            return True                         # Set playerChoice to True so while-loop repeats

    def printCardsAndSum(self):                 # Method that formats and prints players cards and total sum
        print("==============================================")
        print(" P L A Y E R  H A N D ")
        for i in self.hand:                     # For-loop traversing through cards in hand and printing them. Ex. 3 of Spades
            print('┌───────┐')
            print(f'| {i.value:<2}    |')
            print('|       |')
            print(f'|   {i.suit}   |')
            print('|       |')
            print(f'|    {i.value:>2} |')
            print('└───────┘') 
        print()
        print(f"Player hand sum: {self.gameLogic.checkSum(self)}")
        print("==============================================")

    def takeTurn(self, dealer, deck):             # Method that prompts user to tell if they want to stand or hit
        sum = self.gameLogic.checkSum(self)       # Get the total sum of hand
        choice = -1                               # Make sure we won't get error in if-statement
        if not self.isAI:                         # if player is not AI, give them option to hit or stand
            choice = input(f"The sum of your hand is {sum}, would you like to stand or hit?(type 1 for stand and 0 for hit)")
        if choice == '1' or self.isAI and sum > 16:     # If user's input is 1 - They want to stand - or if AI and sum above 16
            print('Player chose to stand - Dealers turn(Dealers 2nd card is revealed)')
            return False           # Set playersTurn to False to break out of while-loop

        elif choice == '0' or self.isAI and sum <= 16:  # Else-if the user input is 0 - They want to hit - or user is AI and below 17
            self.hand.append(self.gameLogic.dealCard(deck)) # Add new card to users hand
            self.printCardsAndSum()             # Print users cards and total sum
            return self.checkBust()                    # Check if user is bust after newly added card
                                                # TODO Make 404-else to prevent bad user input
        
    def isBlackjack(self):                      # Method that checks if players starting hand is blackjack(10 value card + Ace)
        ten = ['Q', 'K', 'J', '10']             # Initialize list with all card values that is equal to 10        
        if self.contains(self.hand, lambda x: x.value == 'A'):  # Call the contain method with our lambda expression
                                                                # that checks if object.value is equal to 'A' (Ace)
            for i in ten:                       # For-loop traversing through ten list                  
                if self.contains(self.hand, lambda x: x.value == i):    # Contain method if value is equal to either 10 value cards
                    print('Player has hit blackjack! Dealers turn..')   
                
                    return True   # If we have hit blackjack - end players turn and break out of while-loop
                                                # TODO Should player win instantly if blackjack is hit? 

    def contains(self, list, filter):           # Contain method that recieves a list and a lambda expression
        for x in list:                          # For-loop traverse through list
            if filter(x):                       # If given lambda expression is met
                return True                     
        return False                            # If lambda expression is NOT met

                                                # TODO Move this method to Menu / Client class when if created
    def chooseIfPlayerOrDealer(self, dealer):   # User is prompted if they want to play as player or dealer
        choice = input("Would you like to play as a player or a dealer? (type 1 for player and 0 for dealer)")

        if choice == '1':                       # If user types 1 and wants to be the player
            dealer.isAI = True                  # Dealer is Artificial Intelligence
            print("You are the player...")
            return False           # Break out of while-loop 

        elif choice == '0':                     # If user types 0 and wants to be dealer
            self.isAI = True                    # Player is Artificial Intelligence
            print("You are the dealer... You will now deal the cards.")
            dealer.isReveal = True              # Dealer can look at his own 2nd card
            return False           # Break out of while-loop

        else:                                   # If 404 bad input - print error msg and continue while-loop
            print(f"Your input: {choice} didn't match any of the cases - Please try again!")


    def printBalance(self):
        print(f"|| Bet placed: {self.bet}      ||      Total balance: {self.balance} ||")
Пример #22
0
class World():
    # Initialisation
    def __init__(self):
        #self.player = Player()
        self.ScreenSetup()
        self.menu = Menus(self.screen)
        self.text = Text(self.screen)
        self.state = ''
        self.playing = True
        self.clock = pygame.time.Clock()
        self.fps = 120
        self.obstacleSprites = []
        self.obList = []
        self.collision = CollisionChecker()

    def RunningStatus(self):
        if self.state == 'Quit':
            return False
        else:
            return True

    # Sets up the screen
    def ScreenSetup(self):
        width = 1000
        height = 800

        self.screen = pygame.display.set_mode(
            (width, height), pygame.HWSURFACE | pygame.DOUBLEBUF)
        pygame.display.set_caption('Dodge The Monsters 3')

    # Draws all the game objects
    def GameStatus(self):
        self.DetermineGameState()
        if self.state == 'MainMenu':
            self.menu.MainMenu(self.screen)
        elif self.state == 'TuteMenu':
            self.menu.TutorialMenu(self.screen)
        elif self.state == 'SelectAI':
            self.menu.SelectAI(self.screen)
        elif self.state == 'FSM':
            self.player = Player('AI')
            self.fsm = FiniteStateMachine(self)
            self.fsm.RunGameFSM()
            self.menu.SetState('MainMenu')
        elif self.state == 'PlayGameHuman':
            self.player = Player('HUMAN')
            self.level = Level(self.screen, self.player)
            self.RunGameHuman()

    def DetermineGameState(self):
        self.state = self.menu.GetState()

    def LoadObstacles(self):
        self.obList = [
            Obstacle(130, -100, 1),
            Obstacle(350, -100, 2),
            Obstacle(645, -100, 3),
            Obstacle(800, -100, 4)
        ]

    # Handles the left and right movement of the player
    def HandlePlayerMovement(self):
        if self.player.type == 'HUMAN':
            if pygame.key.get_pressed()[pygame.K_LEFT]:
                self.player.MoveLeft()
            if pygame.key.get_pressed()[pygame.K_RIGHT]:
                self.player.MoveRight()
            if not pygame.key.get_pressed(
            )[pygame.K_LEFT] and not pygame.key.get_pressed()[pygame.K_RIGHT]:
                self.player.ReturnStraight()

    def GetSprites(self):
        self.allObstacles = pygame.sprite.Group()
        for o in self.obList:
            self.allObstacles.add(o.oSprite)

    def AddObstacle(self):
        if self.level.level == 2 and len(self.obList) == 4:
            self.obList.append(
                Obstacle(random.randint(130, 850), (random.randint(50, 300)),
                         5))
        elif self.level.level == 3 and len(self.obList) == 5:
            self.obList.append(
                Obstacle(random.randint(130, 850), (random.randint(50, 300)),
                         6))
        elif self.level.level == 4 and len(self.obList) == 6:
            self.obList.append(
                Obstacle(random.randint(130, 850), (random.randint(50, 300)),
                         7))

    def RunGameHuman(self):
        self.LoadObstacles()
        self.game = GameLogic(self, self.screen, self.level, self.text)
        self.GetSprites()
        self.player.DrawPlayer(self.screen)
        for o in self.obList:
            o.DrawObstacle(self.screen)
        self.menu.StartGame(self.screen)
        while self.playing and not self.collision.CheckCollision(
                self.obList, self.player):
            # Get the player movement
            self.HandlePlayerMovement()
            # Add other Obstacles
            self.AddObstacle()
            # Run the game logic
            self.game.TheGame(self.obList)
            # Refresh Rate
            self.clock.tick(120)

        pygame.time.delay(1000)
        self.menu.EndGameScreen(self.screen, self.player)
        pygame.time.delay(5000)
        self.menu.SetState('MainMenu')
Пример #23
0
 def setConfig(self, policyConfig):
     self.gameLogic = GameLogic(policyConfig)
Пример #24
0
from GameLogic import GameLogic
import sys

if __name__ == "__main__":
    if len(sys.argv) < 6:
        print("Invalid Parameters")
        sys.exit(-1)

    col = int(sys.argv[1])
    row = int(sys.argv[2])
    k = int(sys.argv[3])
    g = int(sys.argv[4])
    mode = sys.argv[5]
    debug = False
    if len(sys.argv) == 7 and sys.argv[6] == "-d":
        debug = True

    main = GameLogic(col,row,k,g,mode,debug)
    main.Run()
Пример #25
0
 def __init__(self, policy):
     self.policy = policy
     self.width = None
     self.height = None
     self.values = np.zeros(0)
     self.gameLogic = GameLogic(getDefaultPolicyConfig())
Пример #26
0
from Player import Player
from Dealer import Dealer
from Deck import Deck
from GameLogic import GameLogic
import os

player = Player([], False, True, 200,
                0)  # Instantiate our player, dealer and deck
dealer = Dealer([], False, False, False, False)
gameLogic = GameLogic()

endGame = False

print("WELCOME TO THE BLACKJACK GAME")  # Welcome MSG TODO - Move to Menu class

while player.playerChoice:  # Loop while player needs to make a choice
    player.playerChoice = player.chooseIfPlayerOrDealer(
        dealer)  # Method that let's user make choice to be a player or dealer

while not endGame:
    deck = Deck([])
    for i in range(4):
        deck.createDeck()  # Create 4 decks in loop (208 cards)
    deck.shuffleDeck()  # Shuffle the deck randomly
    player = Player(
        [], player.isAI, True, player.balance,
        0)  # Instantiate our player and dealer with their correct fields
    dealer = Dealer(
        [], dealer.isAI, False, False, False
    )  # dealer ai, player ai and balance remains the same as previous round
    if not player.isAI:  # if player is not ai, he has to choose bet amount
class GameLoop:
    def __init__(self):
        self.controller = Controller()
        self.Handler = EventHandler(self.controller)
        self.object_list = []
        self.game_logic = GameLogic()
        self.fps_clock = pygame.time.Clock()
        self.fps = 60
        self.neuralnet = NeuralNetHolder()
        self.version = "v1.01"

    def init(self, config_data):
        # used to initialise the pygame library
        pygame.init()
        if config_data["FULLSCREEN"] == "TRUE":
            user32 = ctypes.windll.user32
            config_data['SCREEN_HEIGHT'] = int(user32.GetSystemMetrics(1))
            config_data['SCREEN_WIDTH'] = int(user32.GetSystemMetrics(0))
            self.screen = pygame.display.set_mode(
                (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT']),
                pygame.FULLSCREEN)
        else:
            config_data['SCREEN_HEIGHT'] = int(config_data['SCREEN_HEIGHT'])
            config_data['SCREEN_WIDTH'] = int(config_data['SCREEN_WIDTH'])
            self.screen = pygame.display.set_mode(
                (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT']))
        pygame.display.set_caption('CE889 Assignment Template')
        pygame.display.set_icon(
            pygame.image.load(config_data['LANDER_IMG_PATH']))

    def score_calculation(self):
        score = 1000.0 - (self.surface.centre_landing_pad[0] -
                          self.lander.position.x)
        angle = self.lander.current_angle
        if (self.lander.current_angle == 0):
            angle = 1
        if (self.lander.current_angle > 180):
            angle = abs(self.lander.current_angle - 360)
        score = score / angle
        velocity = 500 - (self.lander.velocity.x + self.lander.velocity.y)
        score = score + velocity

        print("lander difference " +
              str(self.surface.centre_landing_pad[0] - self.lander.position.x))
        print("SCORE " + str(score))

        return score

    def main_loop(self, config_data):
        pygame.font.init()  # you have to call this at the start,
        # if you want to use this module you need to call pygame.font.init()
        myfont = pygame.font.SysFont('Comic Sans MS', 30)

        # create the group for visuals to be updated
        sprites = pygame.sprite.Group()

        # booleans for what the game state is
        on_menus = [True, False, False]  # Main, Won, Lost
        game_start = False

        # Game modes: Play Game, Data Collection, Neural Net, Quit
        game_modes = [False, False, False, False]

        # The main loop of the window
        background_image = pygame.image.load(
            config_data['BACKGROUND_IMG_PATH']).convert_alpha()
        background_image = pygame.transform.scale(
            background_image,
            (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT']))

        data_collector = DataCollection(config_data["ALL_DATA"])
        main_menu = MainMenu(
            (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT']))
        result_menu = ResultMenu(
            (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT']))
        score = 0
        # Initialize
        while True:
            # menus
            # check if Quit button was clicked
            if (game_modes[len(game_modes) - 1]):
                pygame.quit()
                sys.exit()

            # if game is started, initialize all objects
            if game_start:
                self.controller = Controller()
                self.Handler = EventHandler(self.controller)
                sprites = pygame.sprite.Group()
                self.game_start(config_data, sprites)

            if on_menus[0] or on_menus[1] or on_menus[2]:
                if on_menus[1] or on_menus[2]:
                    result_menu.draw_result_objects(self.screen, on_menus[1],
                                                    score)
                else:
                    main_menu.draw_buttons(self.screen)
                    # draw the version number
                    textsurface = myfont.render(self.version, False, (0, 0, 0))
                    self.screen.blit(textsurface, (0, 0))

                # main_menu.draw_buttons(self.screen)
                for event in pygame.event.get():
                    if on_menus[0]:
                        main_menu.check_hover(event)
                        button_clicked = main_menu.check_button_click(event)
                        main_menu.draw_buttons(self.screen)
                        if button_clicked > -1:
                            game_modes[button_clicked] = True
                            on_menus[0] = False
                            game_start = True

                    elif on_menus[1] or on_menus[2]:
                        result_menu.check_hover(event)
                        on_menus[0] = result_menu.check_back_main_menu(event)
                        result_menu.draw_result_objects(
                            self.screen, on_menus[1], score)
                        if on_menus[0]:
                            on_menus[1] = False
                            on_menus[2] = False
            else:
                # game
                self.Handler.handle(pygame.event.get())
                # check if data collection mode is activated
                if (game_modes[2]):
                    input_row = data_collector.get_input_row(
                        self.lander, self.surface, self.controller)
                    nn_prediction = self.neuralnet.predict(input_row)
                    # print(nn_prediction)
                    # self.controller.set_mouse(False)
                    self.controller.set_up(False)
                    self.controller.set_left(False)
                    self.controller.set_right(False)
                    # self.controller.set_up(nn_prediction[0] == 1)
                    # self.lander.velocity.y = nn_prediction[0]
                    # self.lander.velocity.x = nn_prediction[1]
                    if (self.lander.velocity.y > nn_prediction[0]):
                        self.controller.set_up(True)
                    # self.lander.velocity.y = nn_prediction[0]
                    if (self.lander.velocity.x < nn_prediction[1]):
                        self.controller.set_right(True)
                    else:
                        self.controller.set_left(True)

                    if (self.lander.current_angle > 30
                            and self.lander.current_angle < 330):
                        ang_val = (self.lander.current_angle - 30) / (330 - 30)
                        ang_val = round(ang_val)
                        if (ang_val == 0):
                            self.lander.current_angle = 30
                        else:
                            self.lander.current_angle = 330
                    # print("lander vel: ", self.lander.velocity.y, " -- ", self.lander.velocity.x)
                    # if (nn_prediction[1] == 1):
                    #     self.controller.set_right(True)
                    # elif (nn_prediction[1] == -1):
                    #     self.controller.set_left(True)

                    # self.lander.velocity.y = nn_prediction[0]
                    # self.lander.velocity.x = nn_prediction[1]

                    # self.lander.current_angle = int(nn_prediction[1])

                    # if (nn_prediction[0] == 1):
                    #     self.controller.set_up(True)
                    # if (nn_prediction[1] == 1):
                    #     self.controller.set_left(True)
                    # elif (nn_prediction[2] == 1):
                    #     self.controller.set_right(True)

                # if (game_modes[1]):
                #     data_collector.save_current_status(self.lander, self.surface, self.controller)
                self.screen.blit(background_image, (0, 0))
                if (not self.Handler.first_key_press and game_start == True):
                    self.update_objects()
                    game_start = False

                if (self.Handler.first_key_press):
                    data_input_row = data_collector.get_input_row(
                        self.lander, self.surface, self.controller)
                    self.update_objects()
                    if (game_modes[1]):
                        data_collector.save_current_status(
                            data_input_row, self.lander, self.surface,
                            self.controller)
                    # then update the visuals on screen from the list
                sprites.draw(self.screen)
                # the win state and the score calculation
                if (self.lander.landing_pad_collision(self.surface)):
                    score = self.score_calculation()
                    on_menus[1] = True
                    if (game_modes[1]):
                        data_collector.write_to_file()
                        data_collector.reset()
                # check if lander collided with surface
                elif (self.lander.surface_collision(self.surface)
                      or self.lander.window_collision(
                          (config_data['SCREEN_WIDTH'],
                           config_data['SCREEN_HEIGHT']))):
                    on_menus[2] = True
                    data_collector.reset()

                if (on_menus[1] or on_menus[2]):
                    game_start = False
                    for i in range(len(game_modes)):
                        game_modes[i] = False

            # surface_sprites.draw(self.screen)
            pygame.display.flip()
            self.fps_clock.tick(self.fps)

    def update_objects(self):
        # update the speeds and positions of the objects in game
        self.game_logic.update(0.2)

    def setup_lander(self, config_data):
        lander = Lander(config_data['LANDER_IMG_PATH'], [
            config_data['SCREEN_WIDTH'] / 2, config_data['SCREEN_HEIGHT'] / 2
        ], Vector(0, 0), self.controller)
        self.game_logic.add_lander(lander)
        return lander

    def game_start(self, config_data, sprites):
        # Creates the lander object
        self.lander = self.setup_lander(config_data)
        self.surface = Surface(
            (config_data['SCREEN_WIDTH'], config_data['SCREEN_HEIGHT']))
        sprites.add(self.lander)
        sprites.add(self.surface)
Пример #28
0
class Dealer:

    gameLogic = GameLogic()

    def __init__(self, hand, isAI, isReveal, dealerTurn, roundOver):
        self.hand = hand  # List that stores cards in the dealers hand
        self.isAI = isAI  # Bool that decides if dealer is Artificial Intelligence
        self.isReveal = isReveal  # Bool that decides if dealer's 2nd card is revealed
        self.dealerTurn = dealerTurn  # Bool that decides if it's dealer's turn to hit or stand
        self.roundOver = roundOver  # Bool that decides if a round is over

    def takeTurn(self, player,
                 deck):  # Method for when dealer needs to take his  turn
        self.isReveal = True  # Dealers 2nd card is revealed
        self.printCardsAndSum()  # Print hand and sum
        self.checkWin(player)  # Check if the game is done
        self.dealerTurn = True  # Set dealerTurn to true so we enter while loop
        while self.dealerTurn and not self.roundOver:  # Loops while it's dealers turn to take an action
            sum = self.gameLogic.checkSum(self)
            if sum <= 16:  # If sum is 16 or lower, dealer needs to hit
                print(
                    'Dealers sum is equal to or lower than 16 - dealer hits!')
                self.hand.append(self.gameLogic.dealCard(
                    deck))  # Card is added to dealers hand
                self.printCardsAndSum()  # New hand and sum is printed
                self.checkWin(player)  # Check if anyone has won

    def printCardsAndSum(
            self):  # Method that prints out the dealers hand and total sum
        print("==============================================")
        if not self.isReveal:  # If user is dealer, show both cards - else, keep 2nd card hidden
            print(" D E A L E R  H A N D ")
            print('┌───────┐')
            print(f'| {self.hand[0].value:<2}    |')
            print('|       |')
            print(f'|   {self.hand[0].suit}   |')
            print('|       |')
            print(f'|    {self.hand[0].value:>2} |')
            print('└───────┘')
            print('┌───────┐')
            print('|///////|')
            print('|=======|')
            print('| ͡◉ ͜ʖ ͡◉)|')
            print('|=======|')
            print('|///////|')
            print('└───────┘')
        else:
            print(" D E A L E R  H A N D ")
            for i in self.hand:
                print('┌───────┐')
                print(f'| {i.value:<2}    |')
                print('|       |')
                print(f'|   {i.suit}   |')
                print('|       |')
                print(f'|    {i.value:>2} |')
                print('└───────┘')
            print(f"Dealer hand sum: {self.gameLogic.checkSum(self)}")
        print("==============================================")

    def checkWin(self, player):  # Method that checks if the game has ended
        playerSum = self.gameLogic.checkSum(player)
        sum = self.gameLogic.checkSum(self)
        if sum > 21:  # If dealers sum is larger than 21, dealer is bust
            print('Dealer exceeded 21 and has LOST the game!')
            player.balance += player.bet
            player.printBalance()
            self.dealerTurn = False  # Break out of while-loop
            self.roundOver = True
            # TODO Player instant win if hit blackjack?

        elif sum > playerSum and sum > 16:  # TODO Draw over 16 even tho player is below 16? check rules
            print(
                f'Dealer hit {sum} and WINS over the player with {playerSum}')
            player.balance = player.balance - player.bet
            player.printBalance()
            self.dealerTurn = False  # Break out of loop
            self.roundOver = True

        elif sum == playerSum and sum > 16:  # If both players are above 16 and they have equal values - game tied
            print(f"Game is tied! Both players hit {sum}")
            player.printBalance()
            self.roundOver = True

        elif sum < playerSum and sum > 16:  # If dealers sum is above 16 but less than players - player won
            print(
                f'Dealer hit {sum} and is still lower than players sum: {playerSum}'
            )
            print('Player has won')
            player.balance += player.bet
            player.printBalance()
            self.dealerTurn = False  # Break out of while-loop
            self.roundOver = True

        else:  # In any other case: It's still dealers turn to hit
            self.dealerTurn = True  # Set to true to keep looping TODO else needed?
Пример #29
0
from GameLogic import GameLogic
l = GameLogic()
l.newBots()
l.addPoison(100)
l.addFood(200)

l.run(10)
Пример #30
0

if __name__ == '__main__':

    width = 13
    height = 13

    map_ = Map(width, height)

    snake = Snake([(width // 2, height // 2)] * 3)

    fruit = Fruit(0, 0)

    fruit.randomPosition((0, width), (0, height), snake.getBody())

    gameLogic = GameLogic(snake, fruit, map_)

    renderer = cv2Renderer(width, height, 10)

    while not snake.isDead:

        setRenderer(snake, fruit, renderer)

        k = renderer.render()

        if k == ord('w'):
            k = 3

        elif k == ord('a'):
            k = 2
Пример #31
0
def run():
    """ The main method for running our game """

    # Keep track of when the game was started...
    # this is so that if you win, we can display how long it took you
    start_time = datetime.now()

    # Display highscores - maybe?
    get_highscores()

    # Class instantiation
    obj = GameLogic()

    # Initialize variables
    WinLoseCheck = 'continue to play'
    global west_bank
    global east_bank
    global canoe

    # Display the story so use knows what to do
    display_story()

    # Ask for player name so we know who to humiliate when they lose... just kidding.
    # This will be used to keep track of high scores
    player_name = input("Who is the brave soul playing this game?: ")
    player_name = str(player_name)

    #Begin game
    while WinLoseCheck == 'continue to play':
        # Display the locations
        obj.display_locations(east_bank, west_bank, canoe)

        # Ask for user prompt of who to send
        val_ask = obj.user_prompt(east_bank, west_bank, canoe)
        if val_ask[0] == "q" or val_ask[1] == "q":
            print("Thank you for playing!")
            sys.exit(1)
        else:
            # Update location dictionaries and reset values
            result = obj.update_locations(val_ask, east_bank, west_bank, canoe)
            east_bank = result[0]
            west_bank = result[1]
            canoe = result[2]

            # Check for a win/loss
            WinLoseCheck = obj.check_for_win(east_bank, west_bank)

    # If there is a win, get the ending time so we can compare start_time to see how long it took
    # We also display the winning screen, otherwise show the losing screen
    if WinLoseCheck == "Winner":
        end_time = datetime.now()
        date_diff = end_time - start_time
        print("You completed the game in: ", date_diff, '\n')

        # Update the highscore bank
        update_highscores(player_name, date_diff)

        display_win()

        get_highscores()

    elif WinLoseCheck == "Loser":
        display_lost()

    else:
        pass
Пример #32
0
from GameLogic import GameLogic
from CameraView import CameraView

# Intialize the pygame
pygame.init()
# create the screen
screen = pygame.display.set_mode((800, 600))

# Sound
mixer.music.load("music/background.wav")
mixer.music.play(-1)
# Caption and Icon
pygame.display.set_caption("Recycle Game")
pygame.display.set_icon(pygame.image.load('images/recycle_bin.png'))

logic = GameLogic()
view = CameraView()
clock = pygame.time.Clock()

#create pollution score

# Game Loop
while logic.state != "exit":
    pygame.display.set_caption('Pollution = ' + str(logic.pollution))
    #get elapsed time
    dt = clock.tick(60)
    #process user input
    view.processInput(screen, logic, dt)
    #tick natural game logic
    logic.update(dt)
    #draw window
Пример #33
0
from GameLogic import GameLogic

Condition = "y"

while Condition == "y":
    print("Lets play hangman...")
    GameLogic()
    Condition = input(
        "Press 'y' to continue and play again or press any key to stop.")
Пример #34
0
    # e.g. "python3 main.py 7 7 2 l {AI_path 1} {AI_path 2}"
    # e.g. "python3 main.py 7 7 2 n {AI_path}"

    # Because the initialization of network mode is different from the normal modes,
    # the initialization of network mode is separated from other modes.
    if len(sys.argv) == 3:
        mode = sys.argv[1]
        if mode == 'n' or mode == 'network':
            ai_path = sys.argv[2]
            response,host_flag, rule = network_init()

            rule = list(map(lambda x:int(x),rule))

            col, row, k, order = rule

            main = GameLogic(col, row, k, 'n', debug=True)
            try:
                main.Run(mode=host_flag, ai_path=ai_path, info=response, time=1200)
            except:
                import traceback
                traceback.print_exc()
                import threading
                for timer in threading.enumerate():
                    if type(timer) == threading.Timer:
                        timer.cancel()
            exit(0)
        else:
            print("Invalid Parameters")
            sys.exit(-1)

    if len(sys.argv) < 5:
Пример #35
0
class Policy:

    def __init__(self, policy):
        self.policy = policy
        self.width = None
        self.height = None
        self.values = np.zeros(0)
        self.gameLogic = GameLogic(getDefaultPolicyConfig())

    def getPolicy(self):
        return self.policy

    def setConfig(self, policyConfig):
        self.gameLogic = GameLogic(policyConfig)

    def __eq__(self, other):
        if not isinstance(other, Policy):
            return False
        if self.width != other.width:
            return False
        if self.height != other.height:
            return False
        #for (p1, p2) in zip(self.policy, other.policy):
            #if p1 != p2:
                #print (p1, p2)
        return self.policy == other.policy

    def getValues(self):
        return self.values

    def setPolicy(self, policy):
        self.policy = policy

    def setValues(self, values):
        self.values = values

    def resetValues(self):
        self.values = np.zeros(0)

    def setWidth(self, width):
        self.width = width

    def setHeight(self, height):
        self.height = height

    def policyActionForCell(self, cell):
        return self.policy[cell.getIndex()].getType()

    def pi(self, cell, action):
        # probability that policy performs action 'a' in state 's'
        if len(self.policy) == 0:
            # no policy: try all actions
            return 1

        if self.policyActionForCell(cell) == action:
            # policy allows this action
            return  1
        else:
            # policy forbids this action
            return 0

    def P(self, oldState, newState, actionType, gridWorld):
        # probability to transition from oldState to newState given action
        return self.gameLogic.getTransitionProbability(oldState, newState, actionType, gridWorld)

    def R(self, oldState, newState, action):
        return self.gameLogic.R(oldState, newState, action)

    def evaluatePolicy(self, gridWorld, gamma = 1):
        # determine the value function V using policy iteration
        # map: gridworld map
        # gamma: discount rate

        t = time.time()
        if len(self.policy) != len(gridWorld.getCells()):
            # sanity check whether policy matches dimension of gridWorld
            raise Exception("Policy dimension doesn't fit gridworld dimension.")
        maxIterations = 500
        V_old = None
        V_new = initValues(gridWorld)
        iter = 0
        convergedCellIndices = np.zeros(0) # cells where values don't change anymore
        while len(convergedCellIndices) != len(V_new):
            V_old = V_new
            iter += 1
            V_new = self.evaluatePolicySweep(gridWorld, V_old, gamma, convergedCellIndices)
            convergedCellIndices = self.findConvergedCells(V_old, V_new)
            if iter > maxIterations:
                print("Terminated policy evaluation after " + str(maxIterations) + " iterations")
                break
        t = time.time() - t
        print("Policy evaluation converged after iteration: " + str(iter) + ", time: " + str(t))
        #print(V_new)
        return V_new

    def findConvergedCells(self, V_old, V_new, theta = 0.01):
        # returns list of cells where values haven't changed
        # optimization for policy evaluation such that known values aren't recomputed again

        # silence warnings from '-inf' values
        with warnings.catch_warnings():
            warnings.filterwarnings('ignore', r'invalid value encountered')
            diff = abs(V_old-V_new)
            idx = np.where(diff < theta)[0]
            sameIdx = np.where(V_new == -np.inf)[0]
            return np.concatenate((idx, sameIdx))

    def evaluatePolicySweep(self, gridWorld, V_old, gamma, ignoreCellIndices):
        V = initValues(gridWorld)
        # evaluate policy for every state (i.e. for every viable actor position)
        for (i,cell) in enumerate(gridWorld.getCells()):
            if np.any(ignoreCellIndices == i):
                V[i] = V_old[i]
            else:
                if cell.canBeEntered():
                    gridWorld.setActor(cell)
                    V_s = self.evaluatePolicyForState(gridWorld, V_old, gamma)
                    gridWorld.unsetActor(cell)
                    V[i] = V_s
        self.setValues(V)
        return V

    def evaluatePolicyForState(self, gridWorld, V_old, gamma):
        V = 0
        cell = gridWorld.getActorCell()
        stateGen = StateGenerator()
        transitionRewards = [-np.inf] * len(Actions)
        # perform full backup operation for this state
        for (i, actionType) in enumerate(Actions):
            gridWorld.setActor(cell) # set state
            actionProb = self.pi(cell, actionType)
            if actionProb == 0 or actionType == Actions.NONE:
                continue
            newStates = stateGen.generateState(gridWorld, actionType, cell)
            transitionReward = 0
            for newActorCell in newStates:
                V_newState = V_old[newActorCell.getIndex()]
                # Bellman equation
                newStateReward = self.P(cell, newActorCell, actionType, gridWorld) *\
                                    (self.R(cell, newActorCell, actionType) +\
                                    gamma * V_newState)
                transitionReward += newStateReward
            transitionRewards[i] = transitionReward
            V_a = actionProb * transitionReward
            V += V_a
        if len(self.policy) == 0:
            V = max(transitionRewards)
        return V

    def getValue(self, i):
        return self.values[i]

    def resetPolicy(self):
        self.policy = []

    def valueIteration(self, gridWorld, gamma = 1, storeValueFunction = False):
        # determine the value function V by combining
        # evaluation and policy improvement steps

        # reset policy to ensure that value iteration algorithm is used
        # instead of improving existing policy
        self.resetPolicy()
        t = time.time()
        V_old = None
        V_new = np.repeat(0, gridWorld.size())
        iter = 0
        convergedCellIndices = np.zeros(0) # cells where values don't change anymore
        while len(convergedCellIndices) != len(V_new):
            V_old = V_new
            iter += 1
            V_new = self.evaluatePolicySweep(gridWorld, V_old, gamma, convergedCellIndices)
            self.setValues(V_new)
            if storeValueFunction:
                label = str(iter)
                if iter < 10:
                    label = "0" + str(iter)
                storeValueFunctionInIter(gridWorld, self, label, "value_iteration")
            convergedCellIndices = self.findConvergedCells(V_old, V_new)
        t = time.time() - t
        print("Value iteration terminated after: " + str(iter) + " iterations, time: " + str(t))
        # store policy found through value iteration
        greedyPolicy = findGreedyPolicy(V_new, gridWorld, self.gameLogic)
        self.setPolicy(greedyPolicy)
        self.setWidth(gridWorld.getWidth())
        self.setHeight(gridWorld.getHeight())
        return(V_new)

    def __str__(self):
        out = ""
        for (i,a) in enumerate(self.policy):
            if (i % self.width) == 0:
                out += "\n"
            if len(self.values) == 0:
                out += str(a)
            else:
                val = str(round(self.values[i], 1))
                while len(val) < 4:
                    val += " "
                out += val
        return(out)
Пример #36
0
class GUI:

    player_board = 0
    enemy_board = 0

    #always add +1 and get the direction rotation by modulo %4
    total_positions = 0

    def __init__(self, player_board, enemy_board):
        self.player_board = player_board
        self.enemy_board = enemy_board
        self.root = Tk()

    def initialize(self):
        self.player_frame = Frame(self.root)
        self.player_frame.pack(side=LEFT)

        self.enemy_frame = Frame(self.root)
        self.enemy_frame.pack(side=LEFT)

        self.menu_frame = Frame(self.root)
        self.menu_frame.pack(side=LEFT)

        # initialize GUI for player board
        divider = Label(self.player_frame,
                        text='  \n  \n \n  \n  \n  \n  \n  \n  \n  \n')
        divider.pack(side=TOP)

        self.enemy_buttons_2d_array = [[
            0 for x in range(self.player_board.get_board_size() + 1)
        ] for y in range(self.player_board.get_board_size() + 1)]

        # initialize GUI for enemy board
        for i in range(0, self.enemy_board.get_board_size()):
            for j in range(0, self.enemy_board.get_board_size()):
                b = Button(
                    self.enemy_frame,
                    text=' ',
                    command=lambda x=j, y=i: self.button_click_at_pos(x, y),
                    background="yellow")
                b.grid(row=i, column=j)
                self.enemy_buttons_2d_array[j][i] = b

        self.player_info_label = Label(self.menu_frame,
                                       text='You still have ships: ')
        self.player_info_label.pack(side=TOP)

        self.enemy_info_label = Label(self.menu_frame,
                                      text='Enemy still have ships: ')
        self.enemy_info_label.pack(side=TOP)

        greenbutton = Button(self.menu_frame,
                             text="Restart game",
                             command=lambda: self.restart_game(),
                             fg="brown")
        greenbutton.pack(side=LEFT)

        self.game_logic = GameLogic(self.player_board, self.enemy_board)

    def player_setup(self):

        self.setup_frame = Frame(self.root)
        self.setup_frame.pack(side=LEFT)

        self.setup_frame.grid_rowconfigure(1, weight=1)
        self.setup_frame.grid_columnconfigure(1, weight=1)

        self.setup_help_frame = Frame(self.root)
        self.setup_help_frame.pack(side=LEFT)

        title_label = Label(self.setup_help_frame,
                            text="Welcome to Battleship!")
        title_label.pack(side=TOP)

        help_label = Label(
            self.setup_help_frame,
            text=
            "Click to position ship!\nClick again to delete ship and rotate!")
        help_label.pack(side=TOP)

        start_button = Button(self.setup_help_frame,
                              text="Start!",
                              command=lambda: self.start_button())
        start_button.pack(side=BOTTOM)

        random_button = Button(self.setup_help_frame,
                               text="Place random!",
                               command=lambda: self.random_button())
        random_button.pack(side=BOTTOM)

        self.player_setup_buttons_2d_array = [[
            0 for x in range(self.player_board.get_board_size() + 1)
        ] for y in range(self.player_board.get_board_size() + 1)]

        # initialize GUI for player board
        for i in range(0, self.player_board.get_board_size()):
            for j in range(0, self.player_board.get_board_size()):
                b = Button(self.setup_frame,
                           text=' ',
                           command=lambda x=j, y=i: self.
                           player_setup_button_click_at_pos(x, y))
                b.grid(row=i, column=j)
                self.player_setup_buttons_2d_array[j][i] = b

        self.root.mainloop()

    def start_button(self):
        if len(self.player_board.get_remaining_ships()) > 0:
            msg = str("You still have to place ship with size: " +
                      str(self.player_board.get_remaining_ships()))
            self.popup_message(msg)
        else:
            self.player_board.clear_bounds()

            self.initialize()

            self.setup_help_frame.pack_forget()
            self.setup_help_frame.destroy()

            self.set_setup_buttons_disabled()

    def random_button(self):
        del self.player_board
        self.player_board = 0
        self.player_board = Board()
        self.player_board.set_blank_board()

        self.player_board.initialize()
        self.refresh_player_setup_frame()

    def set_setup_buttons_disabled(self):
        for i in range(0, self.player_board.get_board_size()):
            for j in range(0, self.player_board.get_board_size()):
                self.player_setup_buttons_2d_array[j][i]["state"] = DISABLED

    def popup_message(self, msg):
        popup = Tk()
        popup.wm_title("Place all the ships!")
        label = Label(
            popup,
            text=msg,
        )
        label.pack(side="top")
        b1 = Button(popup, text="Okay", command=popup.destroy)
        b1.pack()
        popup.mainloop()

    def player_setup_button_click_at_pos(self, x, y):
        if self.player_board.get_board_info_at_pos(
                x, y) != 0 and self.player_board.get_board_info_at_pos(x,
                                                                       y) != 7:
            self.player_board.delete_ship(x, y)
            self.refresh_player_setup_frame()
        else:
            self.player_board.place_ship_at_pos(x, y, self.total_positions % 2)
            self.total_positions += 1
            self.refresh_player_setup_frame()
            self.player_board.print_board()

    def refresh_player_setup_frame(self):
        # initialize GUI for player board
        self.player_board.print_board()
        for i in range(0, self.player_board.get_board_size()):
            for j in range(0, self.player_board.get_board_size()):
                self.player_setup_buttons_2d_array[j][i]["state"] = ACTIVE
                if self.player_board.get_board_info_at_pos(j, i) == 0:
                    self.player_setup_buttons_2d_array[j][i]["text"] = " "
                elif self.player_board.get_board_info_at_pos(j, i) == 7:
                    self.player_setup_buttons_2d_array[j][i][
                        "state"] = DISABLED
                else:
                    self.player_setup_buttons_2d_array[j][i]["text"] = "x"

    def button_click_at_pos(self, x, y):

        # player move
        self.game_logic.make_move(x, y)
        print("ENEMY BOARD =----")
        self.enemy_board.print_board()
        # AI Move
        self.game_logic.make_move(-1, -1)

        self.refresh_boards()
        self.refresh_info()

    def refresh_info(self):
        # refresh remaining ships info
        player_ships_sizes = []
        enemy_ships_sizes = []

        for i, obj in enumerate(self.player_board.get_remaining_alive_ships()):
            player_ships_sizes.append(obj.get_size())

        for i, obj in enumerate(self.enemy_board.get_remaining_alive_ships()):
            enemy_ships_sizes.append(obj.get_size())

        self.player_info_label["text"] = "You: " + str(player_ships_sizes)
        self.enemy_info_label["text"] = "Enemy: " + str(enemy_ships_sizes)

    def refresh_boards(self):
        # refresh player board
        for i in range(0, self.player_board.get_board_size()):
            for j in range(0, self.player_board.get_board_size()):
                if self.player_board.get_board_info_at_pos(j, i) == 9:
                    self.player_setup_buttons_2d_array[j][i]["text"] = 'hit'

                if self.player_board.get_board_info_at_pos(j, i) == 8:
                    self.player_setup_buttons_2d_array[j][i][
                        "state"] = DISABLED
                    self.player_setup_buttons_2d_array[j][i]["text"] = 'o'

        # refresh enemy board
        for i in range(0, self.enemy_board.get_board_size()):
            for j in range(0, self.enemy_board.get_board_size()):
                if self.enemy_board.get_board_info_at_pos(j, i) == 9:
                    self.enemy_buttons_2d_array[j][i]["state"] = DISABLED
                    self.enemy_buttons_2d_array[j][i]["text"] = 'x'

                if self.enemy_board.get_board_info_at_pos(j, i) == 8:
                    self.enemy_buttons_2d_array[j][i]["state"] = DISABLED
                    self.enemy_buttons_2d_array[j][i]["text"] = 'o'

    def restart_game(self):
        self.setup_frame.destroy()
        self.enemy_frame.destroy()
        self.menu_frame.destroy()

        del self.player_board
        self.player_board = 0
        self.player_board = Board()
        self.player_board.set_blank_board()

        del self.enemy_buttons_2d_array
        del self.player_setup_buttons_2d_array

        del self.enemy_board
        self.enemy_board = 0
        self.enemy_board = Board()

        self.enemy_board.initialize()
        self.player_setup()
Пример #37
0
    def play_game(self, data, conn):
        data = data.split('@')
        current_game_id = data[1]
        current_move = data[2:]
        print("current_move inside server ", current_move)
        connection1 = conn
        global current_games
        for con in current_games[current_game_id].get_connections():
            if con != connection1:
                connection2 = con
        current_game_name = current_games[current_game_id].get_game()
        current_game_board = current_games[current_game_id].get_board()
        current_game_logic = GameLogic()
        if current_game_name == "Othello":
            current_game_logic = OthelloLogic()
        elif current_game_name == "Connect4":
            current_game_logic = Connect4Logic()
        elif current_game_name == "Battleship":
            current_game_logic = BattleshipLogic()
        try:
            if current_game_name == "Battleship":
                current_game_logic.make_move(current_game_board, current_move)

                self.send_data_to_connection(connection1, "VALID_MOVE")

                tracking_move = ""
                for row in range(current_game_board.get_num_rows()):
                    for col in range(current_game_board.get_num_columns()):
                        tracking_move += "@" + current_game_board.get_tracking_state()[row][col]
                tracking_move += "@"

                current_game_logic.switch_Turn(current_game_board)

                move = ""
                for row in range(current_game_board.get_num_rows()):
                    for col in range(current_game_board.get_num_columns()):
                        move += "@" + current_game_board.get_game_state()[row][col]
                move += "@"
                print("Move from server ", move)

                self.send_data_to_connection(connection1, "BS_TRACKING" + tracking_move)
                self.send_data_to_connection(connection2, "BS_PRIMARY" + move)

                self.send_data_to_connection(connection1, "SWITCH_PLAYER")
                self.send_data_to_connection(connection2, "SWITCH_PLAYER")

            else:
                current_game_logic.make_move(current_game_board, current_move)

                self.send_data_to_connection(connection1, "VALID_MOVE")

                move = ""
                for row in range(current_game_board.get_num_rows()):
                    for col in range(current_game_board.get_num_columns()):
                        move += "@" + current_game_board.get_game_state()[row][col]
                move += "@"
                print("Move from server ", move)

                self.send_data_to_connection(connection1, "UPDATE" + move)
                self.send_data_to_connection(connection2, "UPDATE" + move)

                current_game_logic.switch_Turn(current_game_board)

                self.send_data_to_connection(connection1, "SWITCH_PLAYER")
                self.send_data_to_connection(connection2, "SWITCH_PLAYER")

            if current_game_logic.game_is_over(current_game_board):
                self.send_data_to_connection(connection1, "GAME_OVER")
                self.send_data_to_connection(connection2, "GAME_OVER")
            else:
                if len(current_game_logic.all_valid_moves(current_game_board)) != 0:
                    self.send_data_to_connection(connection1, "WAIT")
                    self.send_data_to_connection(connection2, "READY")
                else:
                    self.send_data_to_connection(connection2, "NO_MOVE_FOR_YOU")

                    current_game_logic.switch_Turn(current_game_board)
                    self.send_data_to_connection(connection1, "SWITCH_PLAYER")
                    self.send_data_to_connection(connection2, "SWITCH_PLAYER")

                    self.send_data_to_connection(connection1, "READY")
                    self.send_data_to_connection(connection2, "WAIT")

        except Exception as e:
            print("INVALID_MOVE Exception happened inside server.")
            print(str(e))
            self.send_data_to_connection(conn, "INVALID_MOVE")