예제 #1
0
        def on_click(event):
            import Rectangle
            print("Clicked at: " + str(event.x) + ", " + str(event.y))

            if Rectangle.Rectangle().contains(
                [event.x, event.y],
                [1256, 664, 2000, 664, 2000, 2000, 1256, 2000]):
                frame.destroy()
            else:
                CountryInfo = allCountries.CountryInfo()
                text = ""
                clickedOnCountry = CountryInfo.GetCountryNameByClick(
                    [event.x, event.y])
                file = open("CurrentClickedCountry.txt", "w")
                file.write(clickedOnCountry)
                file.close()
                text += str(clickedOnCountry + ", bordered by: \n")
                for i in CountryInfo.GetBorderingCountries(clickedOnCountry):
                    text += str("\t\t" + i + "\n")
                text += str("\tOccupied by: " +
                            CountryInfo.GetCurrentOccupent(clickedOnCountry) +
                            "\n")
                text += str(
                    "\t\tWith: " +
                    str(CountryInfo.GetCurrentSoliderCount(clickedOnCountry)) +
                    " armies\n")
                GameFunctions.printOnScreen(canvas, str(text))
 def find_moves(self, chessboard, my_king, d_tool):
     count = 0
     for i in range(-1, 2):
         for j in range(-1, 2):
             x = self.col + i
             y = self.row + j
             while self.can_move(chessboard, x, y, my_king) == 1:
                 count += 1
                 pygame.draw.ellipse(d_tool.screen, rgb_blue,
                                     (GameFunctions.calc_x(
                                         x, d_tool.sqr_l, d_tool.w_buffer),
                                      GameFunctions.calc_y(
                                          y, d_tool.sqr_l, d_tool.h_buffer),
                                      d_tool.sqr_l, d_tool.sqr_l), 4)
                 x += i
                 y += j
             if self.can_move(chessboard, x, y, my_king) == 2:
                 count += 1
                 pygame.draw.ellipse(d_tool.screen, rgb_red,
                                     (GameFunctions.calc_x(
                                         x, d_tool.sqr_l, d_tool.w_buffer),
                                      GameFunctions.calc_y(
                                          y, d_tool.sqr_l, d_tool.h_buffer),
                                      d_tool.sqr_l, d_tool.sqr_l), 4)
     return count
예제 #3
0
    def checkKeys(self):
        # Check movement input

        # Apply drag and direction
        for i in [0, 1]:
            if not self.direction[i] and self.speed[i]:
                # direction is zero but we still have speed
                if self.speed[i] < 0:
                    self.speed[i] += self.ACCEL
                    if self.speed[i] > 0:
                        self.speed[i] = 0
                else:
                    self.speed[i] -= self.ACCEL
                    if self.speed[i] < 0:
                        self.speed[i] = 0
            elif self.direction[i] and (
                    abs(self.speed[i]) < self.MWS
                    or not gf.csign(self.direction[i], self.speed[i])):
                #we have input and not max walk speed reached
                if gf.csign(self.direction[i], self.speed[i]):
                    self.speed[i] += self.ACCEL * self.direction[i]
                    if abs(self.speed[i]) > self.MWS:
                        self.speed[i] = self.MWS * self.direction[i]
                else:
                    self.speed[i] += 2 * self.ACCEL * self.direction[i]
예제 #4
0
def game_loop():
    gameState = Classes.GameState()
    decision = 1

    player1, player2 = AI.initiateModel()

    while decision != 0:
        print('0. Exit')
        print('1. Make AI play hands')
        print('2. Show AI blinds')
        print('3. Train AI')
        print('4. Save AI')
        decision = int(input())
        if decision == 0:
            pass

        if decision == 1:
            print('How many hands?')
            decision2 = int(input())
            for i in range(decision2):
                gameState = GameFunctions.initiateGame(gameState)
                gameState = GameFunctions.startGame(gameState)

        if decision == 2:
            print(gameState.player1.blinds)

        if decision == 3:
            AI.trainAI(player1)

        if decision == 4:
            oppData = ['nada']
            AI.saveModel(player1, 'Alfa0', oppData)
 def find_moves(self, chessboard, my_king, d_tool):
     count = 0
     for i in range(-2, 3):
         check = self.can_move(chessboard, self.col + i,
                               self.row - (3 - abs(i)), my_king)
         if check > 0:
             count += 1
             pygame.draw.ellipse(
                 d_tool.screen, colour[check + 1],
                 (GameFunctions.calc_x(self.col + i, d_tool.sqr_l,
                                       d_tool.w_buffer),
                  GameFunctions.calc_y(
                      self.row - (3 - abs(i)), d_tool.sqr_l,
                      d_tool.h_buffer), d_tool.sqr_l, d_tool.sqr_l), 4)
         check = self.can_move(chessboard, self.col + i,
                               self.row + (3 - abs(i)), my_king)
         if check > 0:
             count += 1
             pygame.draw.ellipse(
                 d_tool.screen, colour[check + 1],
                 (GameFunctions.calc_x(self.col + i, d_tool.sqr_l,
                                       d_tool.w_buffer),
                  GameFunctions.calc_y(
                      self.row + (3 - abs(i)), d_tool.sqr_l,
                      d_tool.h_buffer), d_tool.sqr_l, d_tool.sqr_l), 4)
     return count
예제 #6
0
def game():
    pg.init()
    GS = GameSettings()
    screen = pg.display.set_mode((GS.screen_width, GS.screen_height))
    pg.display.set_caption("Shootnshit")

    Player1 = Player(screen,
                     pg.image.load("Spielfigur.png").convert(), (500, 500),
                     (0, 0))
    mobcount = 3
    mobarray = [0] * mobcount
    for i in range(0, mobcount):
        print(i)
        x = np.random.randint(20, 1004)
        y = np.random.randint(20, 748)
        mobarray[i] = testmob(i, screen,
                              pg.image.load("goomba enemy.png").convert(),
                              [x, y], [2, 0])

    while True:
        gf.check_events(Player1)
        Player1.checkKeys()
        Player1.update()
        for i in range(0, mobcount):
            mobarray[i].update()
        gf.update_screen(GS, screen, Player1, mobarray)
        Clock.tick(120)
예제 #7
0
def launchGame():

    # Show the available maps.
    availableMaps = os.listdir("levels")
    print("All available levels: ")
    for map in availableMaps:
        print("\t" + map)

    # Ask the user to enter the map they want to play.
    selectedMap = "none"
    while selectedMap not in availableMaps:
        selectedMap = input("Please enter the level you want to play: ")

    # Initialize pygame.
    pygame.init()

    # Initialize game settings.
    settings = Settings()

    # Create a window with the specified size.
    screen = pygame.display.set_mode(
        (settings.screenWidth, settings.screenHeight))

    # Set the title of the window.
    pygame.display.set_caption("Space Battle")

    # Create an empty list of walls.
    walls = Group()

    # Create an empty list of bullets.
    bullets = Group()

    # Create astronauts.
    astronautBlue = Astronaut(settings, screen, walls, bullets,
                              "sprites/astronaut_blue_standing.png",
                              "sprites/astronaut_blue_dead.png")
    astronautOrange = Astronaut(settings, screen, walls, bullets,
                                "sprites/astronaut_orange_standing.png",
                                "sprites/astronaut_orange_dead.png")

    # Read the game level from a file.
    GameFunctions.loadGameLevel("levels/" + selectedMap, screen, settings,
                                walls, astronautBlue, astronautOrange)

    # Start the game loop.
    while True:
        # Limit the frame rate to 80 FPS.
        clockobject = pygame.time.Clock()
        clockobject.tick(80)

        GameFunctions.checkEvents(settings, screen, astronautBlue,
                                  astronautOrange, bullets)
        GameFunctions.updateAstronauts(astronautBlue, astronautOrange)
        GameFunctions.updateBullets(settings, astronautBlue, astronautOrange,
                                    bullets, walls)
        GameFunctions.updateScreen(settings, screen, astronautBlue,
                                   astronautOrange, bullets, walls)
예제 #8
0
def checkIfWin(board, letter, possibleMoves):
    """Look at all the empty spaces in the board and check if that space will allow the computer to win"""
    for move in possibleMoves:  # Look at each square of the board
        boardCopy = board.copy()
        if GameFunctions.checkMove(boardCopy, move):  # if the space is empty
            GameFunctions.markSquare(boardCopy, letter, move)  # Mark the space
            if GameFunctions.checkForWinner(boardCopy,
                                            letter):  # Check if winner
                return True, move  # If winner return that key and computer will go there

    return False, -1
예제 #9
0
def compTurn(board, computerLetter, userLetter, possibleMoves):
    """If the computer can win mark that square, if the user can win block that square, if none check empty"""
    canCompWin, square = checkIfWin(board, computerLetter, possibleMoves)

    if canCompWin is False:  # If the Computer can't win check if the user can win and block that spot
        canUserWin, square = checkIfWin(board, userLetter, possibleMoves)

        if canUserWin is False:  # If the User can't win either pick random spot
            square = checkCornersCenterSides(board)

    GameFunctions.markSquare(board, computerLetter, square)
예제 #10
0
def runGame():
    #initialize pygame, screen and screen object
    pygame.init()
    aiSettings = Settings(
    )  #store the settings variables in the aiSettings to access them through this variable
    screen = pygame.display.set_mode(
        (aiSettings.screenWidth, aiSettings.screenHeight))
    pygame.display.set_caption(aiSettings.caption)

    #make a ship
    ship = Ship(aiSettings, screen)
    #make an alien
    alien = Alien(aiSettings, screen)

    #make a group to store bullets in & a group of aliens
    bullets = Group()
    aliens = Group()

    #create the fleat of aliens
    gf.createFleet(aiSettings, screen, ship, aliens)

    #start the main loop for the game
    while True:
        #Watch for keyboard/mouse events
        gf.checkEvents(aiSettings, screen, ship, bullets)
        ship.update()
        gf.updateBullets(bullets)
        gf.updateScreen(aiSettings, screen, ship, aliens, bullets)
예제 #11
0
    def update(self):
        # Check user input
        change = [0, 0]
        shooting = 0
        if Input.key_pressed(pg.K_UP): change[1] -= 1
        if Input.key_pressed(pg.K_LEFT): change[0] -= 1
        if Input.key_pressed(pg.K_DOWN): change[1] += 1
        if Input.key_pressed(pg.K_RIGHT): change[0] += 1
        if Input.key_pressed(pg.K_SPACE): shooting = 1

        # Apply drag and change
        for i in [0, 1]:
            if not change[i] and self.speed[i]:
                # change is zero but we still have speed
                if self.speed[i] < 0:
                    self.speed[i] += self.ACCEL
                    if self.speed[i] > 0:
                        self.speed[i] = 0
                else:
                    self.speed[i] -= self.ACCEL
                    if self.speed[i] < 0:
                        self.speed[i] = 0

            if change[i]:
                if abs(self.speed[i]) < self.MWS or not gf.csign(
                        change[i], self.speed[i]):
                    # We have input and not max walk speed reached
                    if gf.csign(change[i], self.speed[i]):
                        self.speed[i] += self.ACCEL * change[i]
                        if abs(self.speed[i]) > self.MWS:
                            self.speed[i] = self.MWS * change[i]
                    else:
                        self.speed[i] += 2 * self.ACCEL * change[i]

                self.facing[i] = change[i]
            else:
                self.facing[i] = 0

        # Shoot if space pressed
        if shooting and self.shoot_tick_count <= 0:
            self.shoot(self.pos)
            self.shoot_tick_count = self.shoot_speed

        self.shoot_tick_count -= 1

        # This should be refactored somewhere else, so bullets get updated even if player dies
        # Needed if player has lives and can respawn back amongst the battle
        self.bullets.update()

        super().update()
예제 #12
0
def runGame():
	#Initialize pygame, settings, and screen object.
	pygame.init
	settings = Settings()
	screen = pygame.display.set_mode((settings.screenWidth, settings.screenHeight))
	pygame.display.set_caption("Name of the Game")
	
	#Make a person
	person = Person(settings, screen)
	
	#Start the main loop for tha game
	while True:
		gf.checkEvents(settings, screen, person)
		person.update()
		gf.updateScreen(settings, screen, person)
예제 #13
0
def game():
    pg.init()
    GO = GameObject()
    screen= pg.display.set_mode((GO.screen_width,GO.screen_height))
    pg.display.set_caption("Shootnshit")
    running = True
    Player1 = Player(screen, pg.image.load("Spielfigur.png").convert(), (500,500),(0,0))
  

    while running:
        gf.check_events(Player1)
        Player1.checkKeys()
        Player1.update()
        gf.update_screen(GO, screen, Player1) 

        Clock.tick(120)
예제 #14
0
def findEmptySpaces(board):
    possibleMoves = []
    for key in board:
        if GameFunctions.checkMove(board, key):
            possibleMoves.append(key)
        else:
            continue
    return possibleMoves
예제 #15
0
def game():
    pg.init()
    GS = GameSettings()
    screen= pg.display.set_mode((GS.screen_width,GS.screen_height))
    pg.display.set_caption("Shootnshit")


    Player1 = Player(screen, pg.image.load("Spielfigur.png").convert(), (500,500),(0,0))

    while True:
        gf.check_events(Player1)
        Player1.checkKeys()
        Player1.update()
        bullets.update()
        gf.update_screen(GS, screen, Player1,bullets) 

        Clock.tick(120)
예제 #16
0
    def interact(self, object, keyPressed):
        if GameFunctions.isCollisionCollisionBox(self, object):
            if keyPressed[pygame.K_x]:
                object.pickUpItem()

        else:
            if keyPressed[pygame.K_z] and object.inInventory:
                object.dropItem(self.getCollisionBox().x, self.collision_box.y)
예제 #17
0
    def __init__(self, *args, **kwargs):
        singleConnect = kwargs["singleConnect"]
        del kwargs["singleConnect"]
        super(GameServer, self).__init__(*args, **kwargs)
        self.game = GameFunctions.GameFunctions(singleConnect)
        self.game.runGame()

        self.route('/show/:user', callback=self.showCharacter, method="GET")
        self.route('/show', callback=self.showAll, method="GET")
        self.route('/fight/:user1/:user2', callback=self.fight, method="GET")
예제 #18
0
def randomChoiceFromList(board, moveList):
    """Check if the desired moves from moveList are valid"""
    validMoves = []
    for move in moveList:
        if GameFunctions.checkMove(board, move):
            validMoves.append(move)

    if len(validMoves) != 0:
        return random.choice(validMoves)
    else:
        return None
예제 #19
0
def run_game():
    # Initialize game loop
    pygame.init()
    ai_settings = Settings.Settings()
    # Create instance to store game statistics and create scoreboard
    stats = GameStats.GameStats(ai_settings)
    screen = pygame.display.set_mode(
        (ai_settings.screen_width, ai_settings.screen_height))
    sb = Scoreboard.Scoreboard(ai_settings, screen, stats)
    pygame.display.set_caption("Alien Invasion!")

    # Create play button
    play_button = Button.Button(screen, "Play Space Invaders!", "High Score")

    # Make a ship, group of bullets, and group of aliens
    ship = Ship.Ship(ai_settings, screen)
    # Creating bullet group
    bullets = Group()
    aliens = Group()

    # Create fleet of aliens
    gf.create_fleet(ai_settings, screen, ship, aliens)

    pygame.mixer.init()
    pygame.mixer.music.load("Sounds/invaders.wav")
    pygame.mixer.music.play(-1)

    gameRunning = True

    while gameRunning:
        # Responding to key presses and mouse clicks
        gf.check_events(ai_settings, screen, stats, sb, play_button, ship,
                        aliens, bullets)
        if stats.game_active:
            Ship.Ship.update(ship)
            gf.update_bullets(ai_settings, screen, ship, stats, sb, aliens,
                              bullets)
            gf.update_aliens(ai_settings, stats, screen, sb, ship, aliens,
                             bullets)
        gf.update_screen(ai_settings, screen, stats, sb, ship, aliens, bullets,
                         play_button)
예제 #20
0
def checkCornersCenterSides(board):
    """Check if corners, center, side are empty (if that order)"""
    move = randomChoiceFromList(board, [1, 3, 7, 9])
    if move is not None:
        return move

    if GameFunctions.checkMove(board, 5):
        return 5

    move = randomChoiceFromList(board, [2, 4, 6, 8])
    if move is not None:
        return move
예제 #21
0
    def checkKeys(self):
        # Check movement input

        # Apply drag and direction
        for i in [0, 1]:
            if not self.direction[i] and self.speed[i]:
                # direction is zero but we still have speed
                if self.speed[i] < 0:
                    self.speed[i] += self.ACCEL
                    if self.speed[i] > 0:
                        self.speed[i] = 0
                else:
                    self.speed[i] -= self.ACCEL
                    if self.speed[i] < 0:
                        self.speed[i] = 0
            elif self.direction[i] and (
                    abs(self.speed[i]) < self.MWS
                    or not gf.csign(self.direction[i], self.speed[i])):
                #we have input and not max walk speed reached
                if gf.csign(self.direction[i], self.speed[i]):
                    self.speed[i] += self.ACCEL * self.direction[i]
                    if abs(self.speed[i]) > self.MWS:
                        self.speed[i] = self.MWS * self.direction[i]
                else:
                    self.speed[i] += 2 * self.ACCEL * self.direction[i]
        #shoot if space pressed
        if self.shooting:
            if self.shoottickcount == 0:
                self.shoot(self.facing, self.pos)
                self.shoottickcount = self.shootspeed
            else:
                self.shoottickcount -= 1
        if self.direction[0]: self.facing[0] = self.direction[0]
        elif self.direction[1]: self.facing[0] = 0
        if self.direction[1]: self.facing[1] = self.direction[1]
        elif self.direction[0]: self.facing[1] = 0
예제 #22
0
    def __init__(self, bIsRootNode, nTerminalStateType, bIsAINode, nDepth,
                 nProbability, parentNode, topCard, currentHand,
                 compatibilityList):
        # Initialize member variables.
        self.bIsRootNode = bIsRootNode  # Boolean for if this state is a root node, meaning it has no parent node.
        self.nTerminalStateType = nTerminalStateType  # Integer which denotes what type of terminal state this is, if it is one (0 - NULL, 1 - WINNER, 2 - DRAW_CARD).
        self.bIsAINode = bIsAINode  # Boolean for if this is an AI node. If it isn't, then it is a player node (adversary ply).
        self.nDepth = nDepth  # Integer for the node's depth in the tree.
        self.nProbability = nProbability  # Probability that the previous action was taken to reach this state.
        self.parentNode = parentNode  # The parent node for this node.
        self.topCard = topCard  # The top card of the pile.
        self.currentHand = currentHand  # The current hand of cards.
        self.compatibilityList = compatibilityList  # List of binary values to denote which cards in the hand are compatible.
        self.nNumCompatibleCards = len(
            GameFunctions.getCompatibleCardsList(topCard, currentHand)
        )  # The number of cards in the current hand that are compatible with the top card.

        self.childNodeList = []
 def find_moves(self, chessboard, my_king, d_tool):
     count = 0
     if self.can_move(chessboard, self.col, self.row + self.owner,
                      my_king) == 1:
         count += 1
         pygame.draw.ellipse(
             d_tool.screen, rgb_blue,
             (GameFunctions.calc_x(self.col, d_tool.sqr_l, d_tool.w_buffer),
              GameFunctions.calc_y(
                  self.row + self.owner, d_tool.sqr_l,
                  d_tool.h_buffer), d_tool.sqr_l, d_tool.sqr_l), 4)
         if self.can_move(chessboard, self.col, self.row + (2 * self.owner),
                          my_king) == 1:
             count += 1
             pygame.draw.ellipse(
                 d_tool.screen, rgb_blue,
                 (GameFunctions.calc_x(self.col, d_tool.sqr_l,
                                       d_tool.w_buffer),
                  GameFunctions.calc_y(
                      self.row + (2 * self.owner), d_tool.sqr_l,
                      d_tool.h_buffer), d_tool.sqr_l, d_tool.sqr_l), 4)
     if self.can_move(chessboard, self.col - 1, self.row + self.owner,
                      my_king) == 2:
         count += 1
         pygame.draw.ellipse(
             d_tool.screen, rgb_red,
             (GameFunctions.calc_x(self.col - 1, d_tool.sqr_l,
                                   d_tool.w_buffer),
              GameFunctions.calc_y(
                  self.row + self.owner, d_tool.sqr_l,
                  d_tool.h_buffer), d_tool.sqr_l, d_tool.sqr_l), 4)
     if self.can_move(chessboard, self.col + 1, self.row + self.owner,
                      my_king) == 2:
         count += 1
         pygame.draw.ellipse(
             d_tool.screen, rgb_red,
             (GameFunctions.calc_x(self.col + 1, d_tool.sqr_l,
                                   d_tool.w_buffer),
              GameFunctions.calc_y(
                  self.row + self.owner, d_tool.sqr_l,
                  d_tool.h_buffer), d_tool.sqr_l, d_tool.sqr_l), 4)
     return count
예제 #24
0
def main():
    number_of_mobs = 3
    pg.display.init()
    screen = pg.display.set_mode((1024, 768))

    player = pg.image.load("Spielfigur.png").convert()
    background = pg.image.load("background.png").convert()
    projectile = pg.image.load("red_square.png").convert()

    running = True

    Player1 = Player(screen,
                     pg.image.load("Spielfigur.png").convert(), (500, 500))

    #create the Enemies using the Enemies.create() function in andi_classes
    mobs_list = modu.mobs_create(number_of_mobs)[1]
    mobs = modu.mobs_create(number_of_mobs)[0]

    while running:

        screen.fill((50, 50, 50))
        mobs = modu.mobs_collide(number_of_mobs, mobs, mobs_list, screen)
        check_events_return = gf.check_events(Player1)
        projectiles, event_number, running = check_events_return[
            0], check_events_return[1], check_events_return[2]
        projectiles = Player1.shoot(projectile, projectiles)
        if not pg.Rect(Player1.rect).collidelist(mobs_list) == -1:
            running = True
        #blit the players position and the movement
        print(mobs_list[1].left)
        #print(mobs_list[1].right)
        #print(mobs_list[1].top)
        #print(mobs_list[1].bottom)
        Player1.checkKeys()
        Player1.update()
        screen.blit(player, Player1.pos)
        pg.display.update()
        Clock.tick(120)
예제 #25
0
def main():
    
    pg.display.init()
    screen = pg.display.set_mode((1920,1080),flags = pg.HWSURFACE|pg.FULLSCREEN)


    player = pg.image.load("Spielfigur.png").convert()
    background = pg.image.load("background.png").convert()
    projectile = pg.image.load("red_square.png").convert()
    
  
    running = True
    

    Player1 = Player(screen, pg.image.load("Spielfigur.png").convert(), (500,500))

    #create the Enemies using the Enemies.create() function in andi_classes
    mobs_list = mobf.mobs_function(2)[0]
    
    while running:

        screen.blit(background, (0,0))
        mobs_list = mobf.mobs_collision(2,mobs_list,screen)
        
        check_events_return = gf.check_events(Player1)
        projectiles, event_number, running = check_events_return[0], check_events_return[1], check_events_return[2]
        projectiles = Player1.shoot(projectile,projectiles)  
        if not pg.Rect(Player1.rect).collidelist(mobs_list) == -1:
            running = True
        #blit the players position and the movement
        
        Player1.checkKeys()
        Player1.update_2()
        screen.blit(player, Player1.pos)
        pg.display.update()
        Clock.tick(120)
예제 #26
0
def createPlayerStateChildNode(stateNodeListParam, bPlayCardPossible,
                               nDepthParam, aiObservedCardsModelParam,
                               chosenCardParam, parentNodeParam, aiHandParam):
    # If the AI played their last card to reach this state...
    if (bPlayCardPossible == True) and (len(aiHandParam.cards) == 0):
        # Create a "WINNER" Terminal State Node.
        stateNodeListParam.append(
            StateNode(False, 1, False, nDepthParam, 1, parentNodeParam,
                      chosenCardParam, aiHandParam, None))
    # Else if the AI was able to play a card to reach this state...
    elif bPlayCardPossible == True:

        # Declaration of variable for a list of cards unobserved by the AI's model.
        unobservedCards = CardClasses.Deck()
        # Go through all the AI's observed cards.
        for card in aiObservedCardsModelParam:
            # If the card is in the unobserved cards model.
            if card in unobservedCards.deck:
                # Remove the observed card from the unobserved deck.
                unobservedCards.removeCard(card)

        # Create a Player State Child Node and add it to the list.
        newChildNode = StateNode(False, 0, False, nDepthParam, 1,
                                 parentNodeParam, chosenCardParam, aiHandParam,
                                 None)
        stateNodeListParam.append(newChildNode)

        # Declaration of variable for the number of potential actions that can be taken from this state.
        # Set this equal to 2 to the power of the number of cards in the AI's hand. This will include all permutations of cards being compatible or not.
        nNumPotentialActions = 2**len(aiHandParam.cards)
        nNumActualActions = 0

        # Go through every potential action. Each potential action is a different combination of compatible cards.
        # For example, if the AI has two cards left, one action the player can take is to play a card that is compatible with the left card,
        # another is to play a card that is compatible with the right card, and another is to play a card that is compatible with both cards.
        # We won't consider the case where the player plays a card that is not compatible with ANY of the AI's cards here. We'll do that later.
        for i in range(1, nNumPotentialActions):
            potentialCompatibilityList = getBinaryList(i,
                                                       len(aiHandParam.cards))
            ###cardSubset = GameFunctions.createCardSubsetFromCompatibilityList(potentialCompatibilityList, aiHandParam)

            # Calculate the probability that a card that is compatible with the card subset will be played on top of the chosen card.
            nProbability = GameFunctions.calculateProbabilityThatCardAccordingToCompatibilityListWillBePlayed(
                unobservedCards.deck, aiHandParam, potentialCompatibilityList,
                chosenCardParam)

            # If the probability that this action can be taken is greater than 0...
            if nProbability > 0:
                nNumActualActions += 1
                # Pick a random card to play.
                listOfCardsThatCouldBePlayed = GameFunctions.getListOfCompatibleCardsAccordingToCompatibilityList(
                    unobservedCards.deck, aiHandParam,
                    potentialCompatibilityList, chosenCardParam)
                newChosenCard = random.choice(listOfCardsThatCouldBePlayed)
                # Add that card to the aiObservedCardsModel.
                newAIObservedCardsModel = aiObservedCardsModelParam.copy()
                newAIObservedCardsModel.append(newChosenCard)

                # Call the function to create an AI State Child Node and add it to the list.
                createAIStateChildNode(stateNodeListParam, nDepthParam + 1,
                                       nProbability, newAIObservedCardsModel,
                                       newChosenCard, newChildNode,
                                       aiHandParam, potentialCompatibilityList)

        # If there were no cards that the player could play that would be compatible with the ones in the AI's hand...
        if nNumActualActions == 0:
            # Call the function to create an AI State Child where all cards are incompatible.
            # Note that we only do this if there are no other child nodes created.
            createAIStateChildNode(stateNodeListParam, nDepthParam + 1, 1,
                                   aiObservedCardsModelParam, chosenCardParam,
                                   newChildNode, aiHandParam,
                                   getBinaryList(0, len(aiHandParam.cards)))

    # Else, the AI had no compatible cards to play...
    else:
        # Create a "DRAW_CARD" Terminal State Node and add it to the list.
        stateNodeListParam.append(
            StateNode(False, 2, False, nDepthParam, 1, parentNodeParam,
                      chosenCardParam, aiHandParam, None))

    return stateNodeListParam
예제 #27
0
def doAITurn(aiNameParam, topCardParam, aiHandParam, gameDeckParam,
             aiObservedCardsModelParam, bDebugModeOnParam):
    while True:
        # If the AI can't play any of the cards in their hand...
        if GameFunctions.doesHandHaveCompatibleCard(topCardParam,
                                                    aiHandParam) == False:
            # If there are no cards left in the deck...
            if gameDeckParam.isDeckEmpty() == True:
                print(aiNameParam + " cannot make a move. Skipping " +
                      aiNameParam + "'s turn.")
                # The AI's turn is over. Return the top card, the AI's hand, and the game deck, which have all been affected.
                return (topCardParam, aiHandParam, gameDeckParam,
                        aiObservedCardsModelParam)
            # Else, the deck isn't empty...
            else:
                # Draw one card from the deck and add it to the AI's hand.
                drewCard = gameDeckParam.drawCard()
                aiHandParam.pickUpCard(drewCard)
                # Add the drawn card to the AI's observed card model.
                aiObservedCardsModelParam.append(drewCard)
                # Display on screen that a card was drawn.
                print(aiNameParam + " drew a card.")
        # Else, there is a compatible card in the hand...
        else:
            # Declaration of variable for the compatible cards in the hand.
            compatibleCardsList = GameFunctions.getCompatibleCardsList(
                topCardParam, aiHandParam)
            # If there is only one compatible card in the hand...
            if len(compatibleCardsList) == 1 or len(aiHandParam.cards) >= 7:
                # Set the new top card.
                topCardParam = compatibleCardsList[0]
                # Remove the played card from the AI's hand.
                aiHandParam.removeCard(compatibleCardsList[0])
                # Display the new top card.
                print("The top card is now " + str(topCardParam) + ".\n")

                # If DEBUG mode is on, then we'll print some information about what the AI is doing.
                if bDebugModeOnParam == True and len(aiHandParam.cards) < 6:
                    print(
                        "DEBUG: The AI only had one compatible card. No adversary search here!\n"
                    )
                elif bDebugModeOnParam == True and len(aiHandParam.cards) >= 6:
                    print(
                        "DEBUG: The AI has too many cards to perform adversary search."
                    )

                # The AI's turn is over. Return the top card, the AI's hand, and the game deck, which have all been affected.
                return (topCardParam, aiHandParam, gameDeckParam,
                        aiObservedCardsModelParam)
            elif len(compatibleCardsList) > 1:
                # Call function to begin the adversary search! This also sets the new top card.
                topCardParam = beginAdversarySearch(aiObservedCardsModelParam,
                                                    topCardParam, aiHandParam,
                                                    bDebugModeOnParam)

                # Remove the played card from the AI's hand.
                aiHandParam.removeCard(topCardParam)
                # Display the new top card.
                print("The top card is now " + str(topCardParam) + ".\n")
                # The AI's turn is over. Return the top card, the AI's hand, and the game deck, which have all been affected.
                return (topCardParam, aiHandParam, gameDeckParam,
                        aiObservedCardsModelParam)
예제 #28
0
def beginAdversarySearch(aiObservedCardsModelParam, topCardParam, aiHandParam,
                         bDebugModeOnParam):
    # Declaration of variable for the compatibility list.
    compatibilityList = []
    # Go through all the cards in the AI's hand.
    for card in aiHandParam.cards:
        # If the current card is compatible with the top card...
        if GameFunctions.isCardCompatible(topCardParam, card):
            compatibilityList.append(1)
        # Else, it is NOT compatible with the top card...
        else:
            compatibilityList.append(0)

    # Declaration of variable for the list of state nodes.
    stateNodeList = []
    # Create the root node and add it to the list.
    rootAIStateNode = StateNode(True, 0, True, 0, 1, None, topCardParam,
                                aiHandParam, compatibilityList)
    stateNodeList.append(rootAIStateNode)

    # Go through the compatibility list. This is how we'll create the child nodes for our root node.
    for i in range(0, len(compatibilityList)):
        # If the current element is a 1, then we will create a new Player State Child Node.
        if compatibilityList[i] == 1:
            # Declaration of variables for a new hand, which will have the chosen card removed.
            tempCards = aiHandParam.cards.copy()
            newAIHand = CardClasses.Hand(tempCards)
            # Remove the chosen card.
            newAIHand.removeCard(aiHandParam.cards[i])

            # Call the function to create a Player State Child Node and add it to the list.
            createPlayerStateChildNode(stateNodeList, True, 1,
                                       aiObservedCardsModelParam,
                                       aiHandParam.cards[i], rootAIStateNode,
                                       newAIHand)

    # Once we are done, we'll go through all of our nodes and find the best value.

    # First, we'll have to get all of the winner states.
    winnerStateList = []
    # Go through each state node.
    for node in stateNodeList:
        # If the current node is a WINNER Terminal State...
        if node.nTerminalStateType == 1:
            # Add it to the winner state list.
            winnerStateList.append(node)

    # If there is at least one WINNER Terminal State...
    if len(winnerStateList) > 0:
        # Inside each AI node is a probability value of how likely it is to reach that state directly from the parent node.
        # We want to calculate the actual probability it takes to reach the terminal state from the top.
        # We will do this by multiplying all the probabilities on the path to the winner state.
        # Declare a list variable for it.
        winnerActualProbabilities = []

        # Go through all the winner state nodes.
        for node in winnerStateList:
            nActualProbability = 1
            currentNode = node
            # While loop to traverse through the node's parent nodes.
            while True:
                # If the current node's parent node is NOT the root node...
                if currentNode.parentNode.bIsRootNode == False:
                    # Multiply the probability by the parent's probability.
                    nActualProbability = nActualProbability * currentNode.parentNode.nProbability
                    # Update the current node.
                    currentNode = currentNode.parentNode
                # Else, the current node's parent node IS the root node...
                else:
                    # The probability has been calculated, so append it to the list.
                    winnerActualProbabilities.append(nActualProbability)
                    # Break out of the loop.
                    break
        # Now that all the probabilities have been calculated, let's pick the biggest one!
        nTempLargest = 0
        nLargestProbabilityIndex = 0
        # Go through all the winner actual probabilities.
        for i in range(0, len(winnerActualProbabilities)):
            # If the current probability is larger than the temporary one...
            if winnerActualProbabilities[i] > nTempLargest:
                # Set the largest probability and its index.
                nTempLargest = winnerActualProbabilities[i]
                nLargestProbabilityIndex = i

        # Save the best winning state in a variable.
        bestWinningState = winnerStateList[nLargestProbabilityIndex]

        # We have the best state. Now, let's find out which card needs to be played first to reach this state!
        bestPlayingCard = getBestCardToPlayForTerminalState(bestWinningState)

        # If DEBUG mode is on, then we'll print some information on what the AI is doing.
        if bDebugModeOnParam == True:
            # Display DEBUG information about the AI's decision.
            displayDebugInformation(nTempLargest, aiHandParam, topCardParam,
                                    True, winnerStateList, bestPlayingCard,
                                    bestWinningState)

        return bestPlayingCard
    # Else, there is no probability of a winner state.
    else:
        # The next best thing is the deepest "DRAW_CARD" state.
        # First, we'll get the depth of the tree.
        nDeepestDepth = 0
        for node in stateNodeList:
            # If the current node's depth is greater than our depth variable...
            if node.nDepth > nDeepestDepth:
                nDeepestDepth = node.nDepth

        # Next, we'll have to get all of the DRAW_CARD states at that depth.
        deepestDrawCardStateList = []
        # Go through each state node.
        for node in stateNodeList:
            # If the current node is a DRAW_CARD Terminal State at the deepest depth...
            if node.nTerminalStateType == 2 and node.nDepth == nDeepestDepth:
                # Add it to the DRAW_CARD state list.
                deepestDrawCardStateList.append(node)

        # Inside each AI node is a probability value of how likely it is to reach that state directly from the parent node.
        # We want to calculate the actual probability it takes to reach the terminal state from the top.
        # We will do this by multiplying all the probabilities on the path to the DRAW_CARD state.
        # Declare a list variable for it.
        drawCardActualProbabilities = []

        # Go through all the DRAW_CARD nodes at the deepest depth.
        for node in deepestDrawCardStateList:
            nActualProbability = 1
            currentNode = node
            # While loop to traverse through the node's parent nodes.
            while True:
                # If the current node's parent node is NOT the root node...
                if currentNode.parentNode.bIsRootNode == False:
                    # Multiply the probability by the parent's probability.
                    nActualProbability = nActualProbability * currentNode.parentNode.nProbability
                    # Update the current node.
                    currentNode = currentNode.parentNode
                # Else, the current node's parent node IS the root node...
                else:
                    # The probability has been calculated, so append it to the list.
                    drawCardActualProbabilities.append(nActualProbability)
                    # Break out of the loop.
                    break
        # Now that all the probabilities have been calculated, let's pick the biggest one!
        # We want the biggest one because that means it is the highest chance that the AI will get rid of as many of its cards as possible.
        nTempLargest = 0
        nLargestProbabilityIndex = 0
        # Go through all the DRAW_CARD actual probabilities.
        for i in range(0, len(drawCardActualProbabilities)):
            # If the current probability is larger than the temporary one...
            if drawCardActualProbabilities[i] > nTempLargest:
                # Set the largest probability and its index.
                nTempLargest = drawCardActualProbabilities[i]
                nLargestProbabilityIndex = i

        # Save the best DRAW_CARD state in a variable.
        bestDrawCardState = deepestDrawCardStateList[nLargestProbabilityIndex]

        # We have the best state. Now let's find out which card needs to be played first to reach this state!
        bestPlayingCard = getBestCardToPlayForTerminalState(bestDrawCardState)

        # If DEBUG mode is on, then we'll print some information on what the AI is doing.
        if bDebugModeOnParam == True:
            # Display DEBUG information about the AI's decision.
            displayDebugInformation(nTempLargest, aiHandParam, topCardParam,
                                    False, deepestDrawCardStateList,
                                    bestPlayingCard, bestDrawCardState)

        return bestPlayingCard
예제 #29
0
def run_game():
    # screen initializations and menu screen
    pygame.init()
    settings = Settings()
    screen = pygame.display.set_mode(
        (settings.screen_width, settings.screen_height))
    play_button = Button(screen, "Play")
    title = Title(screen, "Pong", 0)

    # game screen display settings
    while True:
        screen.fill(settings.bg_color)
        title.draw()
        play_button.draw()
        pygame.display.flip()
        midpaddle1 = MidPaddle1(settings, screen)
        toppaddle1 = TopPaddle1(settings, screen)
        bottompaddle1 = BottomPaddle1(settings, screen)
        midpaddle2 = MidPaddle2(settings, screen)
        toppaddle2 = TopPaddle2(settings, screen)
        bottompaddle2 = BottomPaddle2(settings, screen)
        ball = Ball(settings, screen)
        score1 = Score1(screen)
        score2 = Score2(screen)
        winner = Winner(screen)
        while settings.game_start is False:
            gameFunc.check_events(settings, play_button, midpaddle1,
                                  toppaddle1, bottompaddle1)
        gameFunc.update_screen(screen, settings, ball, midpaddle1, toppaddle1,
                               bottompaddle1, midpaddle2, toppaddle2,
                               bottompaddle2, score1, score2)
        while score1.points < 3 and score2.points < 3:
            gameFunc.check_events(settings, play_button, midpaddle1,
                                  toppaddle1, bottompaddle1)
            gameFunc.ai_directives(
                ball,
                midpaddle2,
                toppaddle2,
                bottompaddle2,
            )
            gameFunc.check_score(settings, screen, ball, midpaddle1,
                                 toppaddle1, bottompaddle1, midpaddle2,
                                 toppaddle2, bottompaddle2, score1, score2)
            gameFunc.update_game(settings, ball, midpaddle1, toppaddle1,
                                 bottompaddle1, midpaddle2, toppaddle2,
                                 bottompaddle2)
            gameFunc.update_screen(screen, settings, ball, midpaddle1,
                                   toppaddle1, bottompaddle1, midpaddle2,
                                   toppaddle2, bottompaddle2, score1, score2)
        # show win screen after player scores 3 points and play win audio
        if score1.points == 3:
            winner.prep_msg("You won")
            winner.draw()
            sound = pygame.mixer.Sound('Victory.wav')
            pygame.mixer.music.load('Victory.wav')
            pygame.mixer.music.play(1, 0.0)
        # show lose screen when player loses and play lose audio
        else:
            winner.prep_msg("You lost")
            winner.draw()
            sound = pygame.mixer.Sound('lost.wav')
            pygame.mixer.music.load('lost.wav')
            pygame.mixer.music.play(1, 0.0)
        # 3 second delay before game start after clicking play from menu screen
        pygame.display.flip()
        sleep(3)
        settings.game_start = False
        pygame.mouse.set_visible(True)
예제 #30
0
def computePreflopHands(gameState):
    computed_hands = []
    r = random.SystemRandom()
    counter = 998
    counter2 = 0

    # Compute off-suit hand pairs
    # I will be using only hearts and spades
    considered_cards = [
        '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A'
    ]
    considered_suits = ['h', 's']
    result = []
    for suit in considered_suits:
        for card in considered_cards:
            result.append(card + suit)

    remaining_suits = ['d', 'c']

    deck = result.copy()

    # Adding the rest of the cards to the deck
    for suit in remaining_suits:
        for card in considered_cards:
            deck.append(card + suit)

    file = open("Hands//InitialHandStrength.txt", 'a')

    for first_card in result[:-1]:
        for second_card in result[result.index(first_card) + 1:]:
            current_hand = [first_card, second_card]
            current_deck = deck.copy()
            current_deck.remove(current_hand[0])
            current_deck.remove(current_hand[1])
            opponent_hand = []
            opponent_hand.append(current_deck[r.randint(
                0,
                len(current_deck) - 1)])
            current_deck.remove(opponent_hand[0])
            opponent_hand.append(current_deck[r.randint(
                0,
                len(current_deck) - 1)])
            current_deck.remove(opponent_hand[1])

            win = tie = loss = 0

            for i in range(1000):
                if counter < i:
                    print("Computed " + str(counter2 + 1) + " card(s)")
                    counter2 += 1
                felt = []
                testing_deck = current_deck.copy()
                win = tie = loss = 0
                for j in range(5):
                    felt.append(testing_deck[r.randint(0,
                                                       len(testing_deck) - 1)])
                    testing_deck.remove(felt[j])

                decision = GameFunctions.decideWinningHand(
                    current_hand, opponent_hand, felt)

                if decision == 0:
                    tie += 1
                elif decision == 1:
                    win += 1
                elif decision == 2:
                    loss += 1

            if current_hand[0][1] == current_hand[1][1]:
                offsuit = "1"
            else:
                offsuit = "0"

            file.write(','.join([
                current_hand[0][0], current_hand[1][0], offsuit,
                str(win - loss)
            ]))
            file.write('\n')

    file.close()


#gameState = Classes.GameState()
#gameState = GameFunctions.initiateGame(gameState)
#computePreflopHands(gameState)