Beispiel #1
0
def getFirstPlayer(gamemode):
    if gamemode == 1:
        p1, p2 = player.Player(True), player.Player(False)
    elif gamemode == 2:
        userInput, difficulty = getGamemode2Input()
        if userInput == 0:
            return False
        elif userInput == 1:
            p1, p2 = player.Player(True), ai.Ai(False, difficulty)
        else:
            p1, p2 = ai.Ai(True, difficulty), player.Player(False)
    else:
        difficulty1, difficulty2 = getGamemode3Input()
        p1, p2 = ai.Ai(True, difficulty1), ai.Ai(False, difficulty2)
    return p1, p2
Beispiel #2
0
    def testt_PlayALand(self):
        test_Ai = ai.Ai("test_ai", "red")

        forest = card.Land("forest", "Land", "G", 0, "", "mana")
        test_card_1 = card.Creature("test", "Creature", "B", "B", "", 4, 2)

        test_Ai.land_flag = False
        test_Ai.hand = [forest] * 3
        test_Ai.play_land()

        self.assertTrue(test_Ai.hand == [forest, forest]
                        and test_Ai.land_zone == [forest])

        test_Ai.land_flag = False
        test_Ai.hand = [forest] * 3 + [test_card_1]
        test_Ai.land_zone = []

        test_Ai.play_land()
        self.assertTrue(test_Ai.hand == [forest, forest, test_card_1]
                        and test_Ai.land_zone == [forest])

        test_Ai.land_flag = False
        test_Ai.hand = [test_card_1]
        test_Ai.land_zone = []

        test_Ai.play_land()
        self.assertTrue(test_Ai.hand == [test_card_1]
                        and test_Ai.land_zone == [])
Beispiel #3
0
    def initboard(self, screen):

        # Create empty pygame surface.
        background = pygame.Surface(screen.get_size())
        # Fill the background white color.
        background.fill((255, 255, 255))
        # Convert Surface object to make blitting faster.
        self.background = background.convert()
        # Copy background to screen (position (0, 0) is upper left corner).
        screen.blit(self.background, (0, 0))

        self.chesspic = pygame.image.load("xqz.png")

        handimg = {
            "white": ("handcenter2.png", "handcenter.png"),
            "black": ("hand2center.png", "hand2center2.png")
        }
        handcon1 = {
            "up": pygame.K_w,
            "down": pygame.K_s,
            "left": pygame.K_a,
            "right": pygame.K_d,
            "pick": pygame.K_SPACE,
            "counter_c": pygame.K_g,
            "clock": pygame.K_h,
            "added_degree": -2.2
        }
        handcon2 = {
            "up": pygame.K_UP,
            "down": pygame.K_DOWN,
            "left": pygame.K_LEFT,
            "right": pygame.K_RIGHT,
            "pick": pygame.K_RETURN,
            "counter_c": pygame.K_COMMA,
            "clock": pygame.K_PERIOD,
            "added_degree": 0
        }

        self.hands = hand.Hand(self, (40, 120), handimg["white"], 5, handcon1,
                               self.posOK1, 0)
        self.handt = ai.Ai(self, (1240, 120), handimg["black"], 5, handcon2,
                           self.posOK2, 1)
        self.allhand = [self.hands, self.handt]
        self.chesses = []
        #everthing is important
        self.game_phase = "picking1"
        self.a = -0.25
        self.font = pygame.font.Font(None, 30)
        for s in range(0, 2):
            for i in range(0, 12):
                self.chesses.append(
                    chessps.Chess(self, (s * 1450 + 20, 100 + i * 50), 5,
                                  self.chesspic, 5, s, i))

        self.testpos = [(1220, 200, 840, 172, 1175, 100),
                        (200, 100, 300, 250, -80, -80),
                        (200, 200, 300, 300, 250, 260)]
        self.outchess = []
        self.gameover = False
        self.buttons = []
Beispiel #4
0
    def test_AvailableLands(self):
        test_Ai = ai.Ai("test_ai", "red")
        forest = card.Land("forest", "Land", "G", 0, "", "mana")
        forest.tapped = False

        test_Ai.land_zone = [forest] * 6
        self.assertTrue(test_Ai.check_available_lands() == 6)

        forest.tapped = True

        test_Ai.land_zone = [forest] * 6
        self.assertTrue(test_Ai.check_available_lands() == 0)

        test_Ai.land_zone = [forest] * 0
        self.assertTrue(test_Ai.check_available_lands() == 0)
Beispiel #5
0
    def __init__(self):
        self.ai = ai.Ai(self)
        self.current_level = 'test'
        self.bases = levels.create_lvl(self, self.current_level)

        self.powerbar = powerbar.Powerbar(100, 100, self.bases)
        self.upgrade_wheel = upgrade_wheel.Upgrade_wheel()

        self.selected_base = None

        self.selection_box = selection_box.Selection_box()
        self.clickables = self.bases + [self.upgrade_wheel, self.selection_box]
        self.selection_box.load_selectables(self.clickables)

        self.drawables = [self.powerbar] + self.clickables
        self.pause = False
Beispiel #6
0
    def test_CardPlayable(self):
        test_Ai = ai.Ai("test_ai", "red")
        forest = card.Land("forest", "Land", "G", 0, "", "mana")

        test_card_1 = card.Creature("test", "Creature", "G", "G", "", 4, 2)
        test_Ai.land_zone = [forest] * 6
        self.assertTrue(test_Ai.check_card_playable(test_card_1))

        test_card_1 = card.Creature("test", "Creature", "G", "G", "", 4, 2)
        test_Ai.land_zone = [forest] * 0
        self.assertFalse(test_Ai.check_card_playable(test_card_1))

        test_card_1 = card.Creature("test", "Creature", "G", "2G", "", 4, 2)
        test_Ai.land_zone = [forest] * 3
        self.assertTrue(test_Ai.check_card_playable(test_card_1))

        test_card_1 = card.Creature("test", "Creature", "G", "0", "", 4, 2)
        test_Ai.land_zone = [forest] * 0
        self.assertTrue(test_Ai.check_card_playable(test_card_1))
Beispiel #7
0
def new_game():
    game.game["boards"]["boardP"] = game.create_board()
    game.game["boards"]["boardC"] = game.create_board()
    game.game["boards"]["boardC_show"] = game.create_board()
    game.game["player_last"] = "Game on"
    game.game["com_last"] = ""
    game.game["player_ships"]["a"] = 2
    game.game["player_ships"]["b"] = 3
    game.game["player_ships"]["c"] = 3
    game.game["player_ships"]["d"] = 4
    game.game["player_ships"]["e"] = 5
    game.game["computer_ships"]["a"] = 2
    game.game["computer_ships"]["b"] = 3
    game.game["computer_ships"]["c"] = 3
    game.game["computer_ships"]["d"] = 4
    game.game["computer_ships"]["e"] = 5
    game.ai_place_ships()
    state["ai"] = ai.Ai()
    state["ship"] = 1
    state["state"] = 0
Beispiel #8
0
def play():
    game["turn"] = random.randint(0,1)  # Randomly choose which start
    comp_ai = ai.Ai()                   # Init ai

    if game["turn"] == 0:
        print("Computer starts")
    else:
        print("You start")

    while game_on():
        if game["turn"] == 0:
            # Computer's turn
            comp_ai = computer_guess(game["boards"]["boardP"], comp_ai)
            game["turn"] = 1
        else:
            # Player's turn
            print(" ")
            print_board()
            print_radar()
            player_guess(game["boards"]["boardC"])
            game["turn"] = 0
            print("You: ", game["player_last"]) # Prints 'Missed', 'Hit', or 'Hit and sunk'
Beispiel #9
0
def generate_entity(id: int, team: 'Team' = None) -> Entity:
    """
    Generate entity
    :param team:
    :param id:
    :return: new entity
    """
    default_ai = ai.Ai()
    name = names.get_full_name()

    fast_attack = Action(f'fast hit', 'enemy', 1, 2, get_melee_cooldown(1))
    normal_attack = Action(f'normal attack', 'enemy', 1, 5,
                           get_melee_cooldown(2))
    heavy_attack = Action(f'heavy strike', 'enemy', 1, 7,
                          get_melee_cooldown(3))
    pistol_shot = Action('pistol shot', 'enemy', 1, 20,
                         get_perk_cooldown(10))  # pistol
    simple_heal = Action('hp potion', 'ally', 0, -10,
                         get_perk_cooldown(5))  # drink potion

    entity = Entity(
        id,
        (0, 0),
        f'{name}',
        Health(25),
        default_ai,
        dict(),
        {
            fast_attack,
            normal_attack,
            heavy_attack,
            pistol_shot,
            simple_heal,
        },
        team=team,
    )
    return entity
Beispiel #10
0
def draw_button(name):
    #list of possible resolutions
    res_list = ["1920x1080", "800x600", "1440x900", "1024x768", "1600x900"]

    #Take in the co-ordinates of the mouse
    mouse = pygame.mouse.get_pos()

    #Check what buttons have been pressed by the mouse
    click = pygame.mouse.get_pressed()

    #Check if mouse position is within the boundry of the button
    if (name.x + name.w) > mouse[0] > name.x and (name.y +
                                                  name.h) > mouse[1] > name.y:

        #Highlight the button with a lighter shad of blue
        pygame.draw.rect(screen_res.gameDisplay, name.a_colour,
                         (name.x, name.y, name.w, name.h))

        if click[0] == 1 and name.action != None:
            global player_1_d_path
            global player_2_d_path
            if name.action == "play_vs_ai":
                player_1 = player.Player("Sean")

                ai_mode = "red"
                if player_2_d_path == "./personal_decks/deck_1":
                    ai_mode = "red"
                elif player_2_d_path == "./personal_decks/deck_2":
                    ai_mode = "black"
                elif player_2_d_path == "./personal_decks/deck_3":
                    ai_mode == "green"
                elif player_2_d_path == "./personal_decks/deck_4":
                    ai_mode == "white"
                elif player_2_d_path == "./personal_decks/deck_5":
                    ai_mode == "blue"

                player_2 = ai.Ai("AI_Dusty", ai_mode)
                game_1 = game.Game(player_1, player_2, player_1_d_path,
                                   player_2_d_path)
                game_1.run_game(player_1_d_path, player_2_d_path)
                game_intro()

            elif name.action == "quit":
                my_quit()

            elif name.action == "options":
                option()

            elif name.action == "back":
                game_intro()

            elif name.action == "plus":
                increase_volume()

            elif name.action == "minus":
                decrease_volume()

            elif name.action == "change_res":
                for res in res_list:
                    if name.msg == res:
                        new_res = res.split("x")
                        screen_res.display_size = (int(new_res[0]),
                                                   int(new_res[1]))
                        pygame.display.set_mode(screen_res.display_size)
                        option()

            elif name.action == "deck tools":
                deck_tools()

            elif name.action == "green_deck_1":
                player_1_d_path = "./personal_decks/deck_3"

            elif name.action == "green_deck_2":
                player_2_d_path = "./personal_decks/deck_3"

            elif name.action == "red_deck_1":
                player_1_d_path = "./personal_decks/deck_1"

            elif name.action == "red_deck_2":
                player_2_d_path = "./personal_decks/deck_1"

            elif name.action == "blue_deck_1":
                player_1_d_path = "./personal_decks/deck_5"

            elif name.action == "blue_deck_2":
                player_2_d_path = "./personal_decks/deck_5"

            elif name.action == "white_deck_1":
                player_1_d_path = "./personal_decks/deck_4"

            elif name.action == "white_deck_2":
                player_2_d_path = "./personal_decks/deck_4"

            elif name.action == "black_deck_1":
                player_1_d_path = "./personal_decks/deck_2"

            elif name.action == "black_deck_2":
                player_2_d_path = "./personal_decks/deck_2"

    #Else we are not over the button so it stays as it is
    else:
        pygame.draw.rect(screen_res.gameDisplay, name.i_colour,
                         (name.x, name.y, name.w, name.h))

    if name.msg in res_list:
        smallFont = pygame.font.Font("freesansbold.ttf", int(name.h / 7))
        smallText = smallFont.render(name.msg, True, black)
        smallRect = smallText.get_rect()
        smallRect.center = (name.x + (name.w / 2), name.y + (name.h / 2))
        screen_res.gameDisplay.blit(smallText, smallRect)

    else:
        if name.w > name.h:
            font_size = name.h / 4
        else:
            font_size = name.w / 4
        smallFont = pygame.font.Font("freesansbold.ttf", int(font_size))
        smallText = smallFont.render(name.msg, True, black)
        smallRect = smallText.get_rect()
        smallRect.center = (name.x + (name.w / 2), name.y + (name.h / 2))
        screen_res.gameDisplay.blit(smallText, smallRect)
Beispiel #11
0
 def __init__(self, color="white"):
     self.color = color
     self.ai = ai.Ai()
Beispiel #12
0
def creaturesTest(rootNode1_acc,
                  rootNode2_acc,
                  showing=False,
                  time_length=None,
                  playing=False,
                  online=False):
    number_of_balls = 1
    number_of_players = 2
    number_of_skulls = 0

    balls = list()
    players = list()
    skulls = list()

    if online: socket, isClient = tcp_connect(ip_address)

    if not playing:
        rootNode1_accx = rootNode1_acc[0]
        rootNode1_accy = rootNode1_acc[1]
        rootNode2_accx = rootNode2_acc[0]
        rootNode2_accy = rootNode2_acc[1]

    if showing: pygame.init()
    if showing: os.environ['SDL_VIDEO_CENTERED'] = '1'

    if showing:
        vis = general.getVisibleSize()
        window = pygame.display.set_mode(
            (int(vis[0]), int(vis[1])),
            pygame.DOUBLEBUF)  # , pygame.FULLSCREEN)
    else:
        window = pygame.display.set_mode((100, 100))

    fitness1 = 0
    fitness2 = 0

    if showing:
        pygame.display.set_caption('Genetic Soccer')
        general.surface = pygame.display.get_surface()
        field = Field()
        goal1 = field.getGoal1()
        goal2 = field.getGoal2()

    for i in xrange(0, number_of_balls):
        balls.append(Ball(surface=general.surface, radius=6, showing=showing))

    for i in xrange(0, number_of_players):
        players.append(
            Player(general.surface, (20, 20), number_of_players - i, showing))

    for i in xrange(0, number_of_skulls):
        skulls.append(CreatureBodyComputer(surface=general.surface))

    ai_state = ai.State(players[0], players[1], balls[0])
    my_ai = ai.Ai(players[1], goal1, goal2)

    if showing: clock = pygame.time.Clock()

    counter = 0

    while counter < time_length or time_length is None:
        """ Main loop of the simulation (e.g., game). """
        moveCamera(balls[0])
        stoppingx_event = False
        stoppingy_event = False
        new_key = False
        mouse_pos = pygame.mouse.get_pos()
        goal_size = goal1.image.get_size()

        if online:
            ball = balls[0]
            player1 = players[0]
            player2 = players[1]
            terminals0 = Terminals(counter, ball.pos, ball.vel, player1.pos,
                                   player1.vel, 1, [0, 0], [0, 0], 1)
            terminals1 = Terminals(
                counter, ball.pos, ball.vel,
                [width - player2.pos[0], height - player2.pos[1]],
                [-player2.vel[0], -player2.vel[1]], 1, [0, 0], [0, 0], 1
            )  # width-players[1].pos[0],height-players[1].pos[1],    players[1].vel[0], players[1].vel[1],  1)

        if not playing:
            players[0].acc[0] = running_tree(terminals0).run_tree(
                rootNode1_accx)
            players[0].acc[1] = running_tree(terminals0).run_tree(
                rootNode1_accy)

            players[1].acc[0] = running_tree(terminals1).run_tree(
                rootNode2_accx)
            players[1].acc[1] = -running_tree(terminals1).run_tree(
                rootNode2_accy)

        if showing: clock.tick(120)

        counter += 1

        if showing:
            """ Background """
            if showing: field.blitBackground(general.surface)
            """ Keyboard events """
            input = pygame.event.get()
            for event in input:
                whatkey = Keyboard(event)
                if whatkey.isKEYDOWN():
                    if whatkey.isEscape():
                        sys.exit(0)
                    elif whatkey.isEquals():
                        general.global_zoom *= 1.1
                    elif whatkey.isMinus():
                        general.global_zoom /= 1.1
                    elif whatkey.isLeft():
                        players[0].fireLeft()
                    elif whatkey.isRight():
                        players[0].fireRight()
                    elif whatkey.isUp():
                        players[0].fireUp()
                    elif whatkey.isDown():
                        players[0].fireDown()
                    elif whatkey.isPeriod():
                        balls[0].getShooted(players[0])
                    elif whatkey.isSlash():
                        balls[0].getShooted(players[0], 0.46)
                    elif whatkey.isA():
                        players[1].fireLeft()
                    elif whatkey.isD():
                        players[1].fireRight()
                    elif whatkey.isW():
                        players[1].fireUp()
                    elif whatkey.isS():
                        players[1].fireDown()
                    elif whatkey.isBackquote():
                        balls[0].getShooted(players[1])
                    elif whatkey.isOne():
                        balls[0].getShooted(players[1], 0.46)
                elif whatkey.isKEYUP():
                    if whatkey.isLeft() or whatkey.isRight():
                        players[0].stopLeftAndRight()
                    elif whatkey.isUp() or whatkey.isDown():
                        players[0].stopUpAndDown()
                    elif whatkey.isA() or whatkey.isD():
                        players[1].stopLeftAndRight()
                    elif whatkey.isW() or whatkey.isS():
                        players[1].stopUpAndDown()
                if event.type == pygame.MOUSEBUTTONDOWN:
                    left, top = (x - 50 for x in event.pos)

                if whatkey.isKEYUP() or whatkey.isKEYDOWN():
                    new_key = True
            if online: net.updatePlayers(new_key, isClient, socket, players)

        ai_state.update()
        my_ai.do(ai_state)
        for player in players:
            player.collidingGoal(goal1)
            player.collidingGoal(goal2)
            player.move(general.surface,
                        field,
                        counter,
                        cameraPos=cameraPos,
                        goal_size=goal_size)

        for ball in balls:
            """ All balls """
            ball_centre = ball.getCentre()

            # fitness1 += 1000/distance(ball_centre, players[0].get_pos())
            # fitness2 += 1000/distance(ball_centre, players[1].get_pos())

            ball.is_under_player = False
            # players colliding with the ball
            for player in players:
                ball.getKicked(player)
            # computer player colliding with the ball and the goal
            for cc in skulls:
                cc.collidingGoal(goal1)
                cc.collidingGoal(goal2)
                ball.getKicked(cc)
                if debug:
                    print(mouse_pos)
                cc.acc = [(random.random() - 0.5) / 5.0,
                          (random.random() - 0.5) / 5.0]
                cc.move(general.surface,
                        field,
                        counter,
                        cameraPos=cameraPos,
                        goal_size=goal_size)

            # to the pipe (tirake darvaze):
            is_colliding_goal_pipe_top_right = (
                ball.vel[1] < 0
                and (diff(ball_centre[1], goal_size[1]) < ball.radius)
                and (diff(ball_centre[0], (width / 2 + goal_size[0] / 2)) < 3))
            is_colliding_goal_pipe_top_left = (
                ball.vel[1] < 0
                and (diff(ball_centre[1], goal_size[1]) < ball.radius)
                and (diff(ball_centre[0], (width / 2 - goal_size[0] / 2)) < 3))
            is_colliding_goal_pipe_bottom_right = (
                ball.vel[1] > 0
                and (diff(ball_centre[1],
                          (height - goal_size[1])) < ball.radius)
                and (diff(ball_centre[0], (width / 2 + goal_size[0] / 2)) < 3))
            is_colliding_goal_pipe_bottom_left = (
                ball.vel[1] > 0
                and (diff(ball_centre[1],
                          (height - goal_size[1])) < ball.radius)
                and (diff(ball_centre[0], (width / 2 - goal_size[0] / 2)) < 3))

            if is_colliding_goal_pipe_top_right or is_colliding_goal_pipe_top_left or is_colliding_goal_pipe_bottom_right or is_colliding_goal_pipe_bottom_left:
                ball.vel[1] = -ball.vel[1]
            else:
                ball.collidingGoal(goal1)
                ball.collidingGoal(goal2)

            if goal1.rect.contains(ball.rect):
                fitness2 += 100
                field.score2 += 1
                ball.reset()
                players[0].reset()
                players[1].reset()
                players[0].fire_acc += 0.01
                players[1].fire_acc += 0.01
                if showing: field.setMessage2()
            elif goal2.rect.contains(ball.rect):
                fitness1 += 100
                field.score1 += 1
                ball.reset()
                players[0].reset()
                players[1].reset()
                players[0].fire_acc += 0.01
                players[1].fire_acc += 0.01
                if showing: field.setMessage1()

            ball.move(counter, cameraPos=cameraPos)
            if showing:
                field.blitField(width=width,
                                height=height,
                                surface=general.surface,
                                cameraPos=cameraPos)

        vis = general.getVisibleSize()
        if debug:
            pygame.draw.rect(general.surface, pygame.Color(0, 0, 0),
                             (0, 0, vis[0], vis[1]), 1)
        if showing: pygame.display.flip()
    return (1.0 * fitness1 / counter, 1.0 * fitness2 / counter)
Beispiel #13
0
 def createAi(self, type):
     if (type == "default"):
         return ai.Ai()
     else:
         return ai.Ai()