Beispiel #1
0
def test_whole():
    sys.stdin = open("test_input_files/2p_input.txt")
    player, board_size, reverse_status = game_setup()
    assert play_game(board_size, player) == 1

    sys.stdin = open("test_input_files/2p_input.txt")
    run_game()
Beispiel #2
0
    def run_game2():
        global ch, dobollet, bulets
        forrand = 1000
        pygame.init()
        ai_settings = Settings()
        screen = pygame.display.set_mode(
            (ai_settings.screen_width, ai_settings.screen_height))
        pygame.display.set_caption('Alien Invasion')
        planets = Group()
        t = [0, 1, 1, 1]

        mars = Planet(ai_settings, screen, 0, 0, t)
        planets.add(mars)
        while True:

            for event in pygame.event.get():

                #for event in pygame.event.get():

                if event.type == pygame.MOUSEBUTTONDOWN:
                    mouse_x, mouse_y = pygame.mouse.get_pos()
                    for planet in planets.sprites():
                        if planet.rect.collidepoint(mouse_x, mouse_y):
                            print(planet.libe)
                            game.run_game(planet.libe)

            screen.fill(ai_settings.bg_color)
            planets.draw(screen)
            pygame.display.flip()
Beispiel #3
0
 def test_exit_game(self, patch_pause, patch_keys):
     """Проверяем, работает ли пауза."""
     patch_keys.return_value = {pygame.K_ESCAPE : True, pygame.K_RETURN : False}
     patch_pause.return_value = 'paused'
     try:
         game.run_game()
     except KeyError as e:
         pass
     self.assertTrue(patch_pause.called)
Beispiel #4
0
def play_map(map):
    if data.playerData.isLocked(map):
        return
    global gui
    if not gui == None:
        gui.stop()
    console.clear()

    from game import run_game
    run_game(map)
Beispiel #5
0
def main():
    
    interface = InteractiveInterface()#Keyboard(), ExternalWindow())
    p1 = Player(Color.WHITE, interface)
    p2 = Player(Color.BLACK, interface)

    game = HiveGame([p1, p2])
    run_game(game)

    return
Beispiel #6
0
def recur_calc(parameters_list,
               pos,
               parameters,
               current_val,
               nrun,
               logfile,
               player,
               top_score=[]):
    top_plays = top_score
    min_value = parameters[parameters_list[pos]][0]
    max_value = parameters[parameters_list[pos]][1]
    for i in range(min_value, max_value):
        current_val[parameters_list[pos]] = i
        if len(parameters_list) - 1 != pos:
            top_plays = recur_calc(parameters_list, pos + 1, parameters,
                                   current_val, nrun, logfile, player,
                                   top_plays)
        else:
            n = nrun
            wins = 0
            loses = 0
            while n != 0:
                world = World([Company(Director(player, current_val))],
                              hideoutput=True)

                run_game(world)

                if world.winner_is_here:
                    wins += 1
                else:
                    loses += 1
                n -= 1
            strings.send_text(strings.AI_WIN_RESULT %
                              (wins, nrun, str(current_val), ''))
            logfile.write(strings.AI_WIN_RESULT %
                          (wins, nrun, str(current_val), '\n'))
            if top_plays:
                if wins < top_plays[0]:
                    pass
                else:
                    if len(top_plays) < 10:
                        top_plays.append(wins)
                    else:
                        top_plays[0] = wins
            else:
                top_plays.append(wins)
            top_plays.sort()
    return top_plays
Beispiel #7
0
def old_user():
    countnum = 0
    while countnum <= 2:
        user = input("\033[1;37m%s\033[0m" % "username:"******"\033[1;37m%s\033[0m" % "password:"******"\033[0;31m%s\033[0m" %
                  "\nLogin incorrent,there are %s/3 chances left.\n" %
                  (3 - countnum))
        else:
            print("\033[0;31m%s\033[0m" % "\n%s Login successful!\n" % user)
            os.system("say 'welcome to login,%s'" % user)
            run_game()
            break
Beispiel #8
0
def train_net_vs_simple(net_player):
    net_player.color = PlayerColor.BLUE
    players = {
        PlayerColor.BLUE: net_player,
        PlayerColor.RED: SimplePlayer(PlayerColor.RED)
    }
    global_map, players, fights, winning_player = game.init_game(
        map_filename, players)
    winner, global_map = game.run_game(False, global_map, players, fights,
                                       winning_player)

    owned_nodes = 0
    owned_buildings = 0
    owned_units = 0
    for row in global_map:
        for loc in row:
            if loc and loc.unit_in_loc and loc.unit_in_loc.owner is net_player.color:
                owned_units += 1
            if isinstance(loc, Node):
                if loc.owner is net_player.color:
                    owned_nodes += 1
                    if not loc.building.is_empty():
                        owned_buildings += 1
    net_player.g.fitness = owned_units + 10 * owned_nodes + 20 * owned_buildings
    if winner is net_player.color:
        net_player.g.fitness += 10000
    print("Genome: ", net_player.g.key, " Fitness: ", net_player.g.fitness)
Beispiel #9
0
def train_net_vs_other(net_player, other_net_player):
    net_player.color = PlayerColor.BLUE
    other_net_player.color = PlayerColor.RED
    players = {PlayerColor.BLUE: net_player, PlayerColor.RED: other_net_player}
    global_map, players, fights, winning_player = game.init_game(
        map_filename, players)
    winner, global_map = game.run_game(False, global_map, players, fights,
                                       winning_player, max_game_time)

    for row in global_map:
        for loc in row:
            if loc and loc.unit_in_loc:
                if loc.unit_in_loc.owner is net_player.color:
                    net_player.g.fitness += 1
                elif loc.unit_in_loc.owner is other_net_player.color:
                    other_net_player.g.fitness += 1
            if isinstance(loc, Node):
                if not loc.building.is_empty():
                    if loc.owner is net_player.color:
                        net_player.g.fitness += 100
                    elif loc.owner is other_net_player.color:
                        other_net_player.g.fitness += 100
    if players.__contains__(winner):
        players[winner].g.fitness += 1000
    print("Genome: ", net_player.g.key, " Fitness: ", net_player.g.fitness,
          "\tOther Genome: ", other_net_player.g.key, " Fitness: ",
          other_net_player.g.fitness)
    return winner
Beispiel #10
0
def eventLoop(message,left,all_sprites_list,block_list,monsta_list,pacman_collide,wall_list,gate):
  while True:
      # ALL EVENT PROCESSING SHOULD GO BELOW THIS COMMENT
      for event in pygame.event.get():
        if event.type == pygame.QUIT:
          pygame.quit()
        if event.type == pygame.KEYDOWN:
          if event.key == pygame.K_ESCAPE:
            pygame.quit()
          if event.key == pygame.K_RETURN:
            del all_sprites_list
            del block_list
            del monsta_list
            del pacman_collide
            del wall_list
            del gate
            run_game()
def run_script(heuristic,
               type,
               amount,
               domain_file_name,
               problem_file_name,
               gen_flag=2):
    player_init = player.Player(type, (11, 9), (1, 0), amount)
    return game.run_game(heuristic, player_init, domain_file_name,
                         problem_file_name, gen_flag)
Beispiel #12
0
def run_menu(state=None, msg=None):
    this_active = True
    while this_active:
        os.system('clear')
        if msg is None:
            print('\n Sokoban! Probably the best game in the world.')
        else:
            print(msg)
        selection = get_menu_selection(state)
        if selection is 'q':
            os.system('clear')
            sys.exit()
        else:
            try:
                state = sokoban_load(int(selection))
                this_active = False
            except (FileNotFoundError, ValueError):
                pass
    game.run_game(state)
Beispiel #13
0
def main():
    winning_players = []
    players = {PlayerColor.BLUE: blue_player, PlayerColor.RED: red_player}
    for map_iter in map_files:
        global_map, players, fights, winning_player = game.init_game(
            map_iter, players)
        for _ in range(run_count):
            winner, global_map = game.run_game(show_window, global_map,
                                               players, fights, winning_player)
            winning_players.append(winner)
            wins[winner] += 1
    print(wins)
    print(winning_players)
Beispiel #14
0
def main(arguments):
    parsed_arguments = parse_arguments(arguments)

    model = Model()
    model.create(7, 7)
    model.save(parsed_arguments.model_dir)
    for i in range(parsed_arguments.num_iterations):
        exploration_factor = 0.75 - 0.5 * i / parsed_arguments.num_iterations
        run_game(parsed_arguments.playgame_path, parsed_arguments.map_path,
                 parsed_arguments.log_dir, parsed_arguments.exe_path,
                 parsed_arguments.model_dir, parsed_arguments.turns,
                 parsed_arguments.games, exploration_factor)
        games = load_games(parsed_arguments.log_dir, 1, parsed_arguments.games)
        print(f'Iteration: {i + 1} of {parsed_arguments.num_iterations}')
        print_score(games)
        print(f'Exploration factor: {exploration_factor}')
        for _ in range(3):
            games = load_games(parsed_arguments.log_dir, 1,
                               parsed_arguments.games)
            input, output = convert_experiences(experiences(games), model)
            model.train(input, output)
        model.save(parsed_arguments.model_dir)
Beispiel #15
0
def main():
    if len(sys.argv) == 3 and sys.argv[1] == "--debug":
        username, server_code = sys.argv[2].split(":")
        player = Player(username,
                        server_code)  #, url="http://localhost", port=51337)
    else:
        player = run_menu(surface, font, clock)

    while True:
        minigame_name = run_game(player, surface, font, clock)

        # run a minigame
        module = import_module('minigames.{}'.format(minigame_name))
        minigame = getattr(module, 'main')
        minigame(player, surface, font, clock)
Beispiel #16
0
class GameTests(unittest.TestCase):
   
    @patch('game.stop_game')
    def test_game_start(self, test_patch):
        """Проверяем работает ли остановка игры при health = 0"""
        test_patch.return_value = 'win_test' 
        game.health2 = 0
       self.assertEqual(game.run_game(), 'win_test')
      
    @patch('pygame.key.get_pressed')
    @patch('game.pause_game')
    def test_exit_game(self, patch_pause, patch_keys):
        """Проверяем, работает ли пауза."""
        patch_keys.return_value = {pygame.K_ESCAPE : True, pygame.K_RETURN : False}
        patch_pause.return_value = 'paused'
        try:
            game.run_game()
        except KeyError as e:
            pass
        self.assertTrue(patch_pause.called)
Beispiel #17
0
            a.backProp(target_values2)
        print rep
        print input_values
        print a.get_results()
    a.to_string()

elif testing == "animal":
    anim1 = animal.animal()
    anim2 = anim1.reproduce()
    anim1.brain_output()
#    anim1.mutate()
#   anim1.to_string()
#  anim2.to_string()

elif testing == "game":
    game.run_game()

elif testing == "simulator":
    p1 = [0, 0]
    p2 = [0, 90]
    simulator.angle_between(p1, p2)
    print simulator.polar_coordinates(90, 1)

elif testing == "simulation1":
    turns = 0
    attempts = 10000
    best_animals = []
    for sim in range(attempts):
        animals = [animal.animal() for i in range(1)]
        animals[0].health.value = 2.0
        simulation_data = game.simulate_game(3000, animals)
    company_list = []
    for i in range(0, int(player_count)):
        strings.send_text(strings.PLAYER_SELECT % (i + 1))
        for j in range(0, len(players.players_list)):
            strings.send_text('%d) %s' % (j + 1, players.players_list[j]))
        selected_player = int(input(strings.INPUT_NUMBER)) - 1
        visible_info = input(strings.SHOW_HIS_TURNS)
        if visible_info == '1':
            visible_info = True
        else:
            visible_info = False
        company_list.append(
            Company(Director(players.func_list[selected_player]),
                    visible_info))

    world = World(company_list)
    run_game(world)
elif answer == '2':
    from calculation import calc
    from players.semiai import semiai_command
    calc(semiai_command, 100, {
        'credit_sum': (70, 90),
        'money_for_product_reserve': (0, 10)
    })
else:
    strings.send_text(strings.BYE)
    try:
        exit(0)
    except SystemExit:
        strings.send_text(strings.SYSTEMEXIT_EXCEPTION)
Beispiel #19
0
if sys.argv[1].startswith('create'):
    nrows = int(get_param('rows'))
    ncols = int(get_param('columns'))
    filepath = get_param('file-path')

    maze = Maze.create_maze(nrows, ncols)
    draw_maze(maze, file_path=filepath)


elif sys.argv[1].startswith('solve'):
    start = make_tuple(get_param('start'))
    end = make_tuple(get_param('end'))

    maze = Maze.load_from_file(get_param('file-path'))
    path = astar_solver.solve_maze(maze, start, end)
    print(path)
    #draw_maze(maze, path)
elif sys.argv[1].startswith('play'):
    game.run_game(get_param('file-path'))
elif sys.argv[1] == 'help':
    print('Key controls')
    print('z    Highlight current location')
    print('x    Highlight destination')
    print('t    Show solution from current location')
    print('c    Decrease frame rate')
    print('v    Increase frame rate')
    print('f    Show frame rate')
    print('Arrows or WASD for movement')

Beispiel #20
0
 def begin(self):
     tag = run_game()
     qwin = queryWindow(tag)
     self.windowList.append(qwin)
     self.close()
     qwin.show()
Beispiel #21
0
 def begin(self):
     tag = run_game()
     the_window = queryWindow(tag)
     self.windowList.append(the_window)
     self.close()
     the_window.show()
Beispiel #22
0
        except:
            return False

    def split(self, hand):
        if hand.cards[0].rank == 8 or hand.cards[0].rank == 'A':
            return True

class Super_Cheater(GameStrategy):
    def hit(self, hand):
        try:
            theoretical_hand = Hand( *hand.cards, self.player.table.deck[-1] )
            for x in range(25):
                if theoretical_hand.is_bust():
                    self.player.table.get_card()
                    theoretical_hand = Hand( *hand.cards, self.player.table.deck[-1] )
            if not theoretical_hand.is_bust():
                return True
            else:
                return False
        except:
            return False

    def split(self, hand):
        if hand.cards[0].rank == 8 or hand.cards[0].rank == 'A':
            return True


if __name__ == '__main__':
    game.run_game( Cheater )
    #game.run_game( Super_Cheater )
#! /u/qaeng/anaconda3/bin/python3
import game
from cards import *


class inclass_strat(GameStrategy):
    def double_down(self, hand):
        return False

    def split(self, hand):
        return False

    def hit(self, hand):
        ## Dealver Visible Card
        dc = self.player.table.get_dealer_visible_card()
        if dc.hard >= 2 and dc.hard <= 7:
            if hand.score() >= 17:
                return False
            else:
                return True
        else:
            return True


game.run_game(inclass_strat)
Beispiel #24
0
def main(): 
    run_game()
Beispiel #25
0
                from PIL import Image
            except ImportError:
                logger.warning("You chose a different size but Pillow is "
                               "not installed. Default size is going to "
                               "be used instead")
                factor = 1
                folderPath = join("cache", str(factor))
            else:  # Generate images
                mkdir(folderPath)
                from generate_images import generate_images
                generate_images(factor)
                logger.info("Cached images for a factor of %d" % factor)
        # Copying from default
        if factor == 1 and not exists(folderPath):
            mkdir(folderPath)
            from generate_images import NAMES as names
            from shutil import copyfile
            sourcePath = join("media", "default", "")
            destPath = join(folderPath, "")
            for name in names:
                copyfile(sourcePath + name + ".gif", destPath + name + ".gif")
            menuPath = join("media", "menu.gif")
            copyfile(menuPath, destPath + "menu.gif")
            logger.info("Cached images from default")
    return factor, difficulty


if __name__ == "__main__":
    from game import run_game
    run_game(*prepare())
Beispiel #26
0
#!/usr/bin/python
import game

game = game.LightGame()
game.run_game()
Beispiel #27
0
from game import run_game

run_game()
Beispiel #28
0
            a.backProp(target_values2)
        print rep
        print input_values
        print a.get_results()
    a.to_string()

elif testing == "animal":
    anim1 = animal.animal()
    anim2 = anim1.reproduce()
    anim1.brain_output()
#    anim1.mutate()
 #   anim1.to_string()
  #  anim2.to_string()

elif testing == "game":
    game.run_game()

elif testing == "simulator":
    p1 = [0,0]
    p2 = [0,90]
    simulator.angle_between(p1,p2)
    print simulator.polar_coordinates(90,1)

elif testing == "simulation1":
    turns = 0
    attempts = 10000
    best_animals = []
    for sim in range(attempts):
        animals = [animal.animal() for i in range(1)]
        animals[0].health.value = 2.0
        simulation_data = game.simulate_game(3000,animals)