Example #1
0
def create_game():
    game_id = "".join(choice(string.lowercase) for _ in range(5))
    p1 = request.form["p1"]
    p2 = request.form["p2"]
    m = request.form.get("map", "Random")
    planets = None
    fleets = None
    state = State()

    if m == "Random":
        m = random.choice(PlanetWars.maps.keys())
    if m == "Generate":
        m = None
        state.random_setup(2, 2, 10)
    c = request.form["collisions"]
    if c == "True":
        c = True
    else:
        c = False

    tps = float(request.form.get("tps", 8))
    seed = random.randint(1, 2000000000)
    print "############ SEED=", seed

    games[game_id] = PlanetWars([p1, p2],
                                m,
                                state.planets,
                                state.fleets,
                                turns_per_second=tps,
                                collisions=c)
    view = WebsocketView(game_id)
    games[game_id].add_view(view)
    Thread(target=games[game_id].play).start()
    return redirect("/game/" + game_id)
Example #2
0
def create_game():
    game_id = "".join(choice(string.lowercase) for _ in range(5))
    p1 = request.form["p1"]
    p2 = request.form["p2"]
    m = request.form.get("map", "Random")
    planets = None
    fleets = None
    state = State()

    if m == "Random":
        m = random.choice(PlanetWars.maps.keys())
    if m == "Generate":
        m = None
        state.random_setup(2, 2, 10)
    c = request.form["collisions"]
    if c == "True":
        c = True
    else:
        c = False
                        
    tps = float(request.form.get("tps", 8))
    seed = random.randint(1,2000000000)
    print "############ SEED=", seed
    
    games[game_id] = PlanetWars([p1, p2], m, state.planets, state.fleets, turns_per_second=tps, collisions=c)
    view = WebsocketView(game_id)
    games[game_id].add_view(view)
    Thread(target=games[game_id].play).start()
    return redirect("/game/" + game_id)
Example #3
0
 def get_successors(self, state: State[IntTuple]) -> Iterable[Successor[IntTuple, str, float]]:
     row, col = state.value
     successors: List[Successor[IntTuple, str, float]] = []
     if row - 1 >= 0:
         successors.append(Successor(State((row - 1, col)), 'UP', 1.0))
     if row + 1 < self.__num_rows:
         successors.append(Successor(State((row + 1, col)), 'DOWN', 1.0))
     if col - 1 >= 0:
         successors.append(Successor(State((row, col - 1)), 'LEFT', 1.0))
     if col + 1 < self.__num_col:
         successors.append(Successor(State((row, col + 1)), 'RIGHT', 1.0))
     return successors
Example #4
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--collisions', action='store_true', required=False, default=False,
                        help="Should the ships collide among each other?")
    parser.add_argument('--rate', type=int, required=False, default=100,
                        help="Number of turns per second run by the game.")
    parser.add_argument('--map', type=str, required=False, default="map1",
                        help="The filename without extension for planets.")
    parser.add_argument('--quiet', action='store_true', required=False, default=False,
                        help="Suppress all output to the console.")

    parser.add_argument('--seed', type=int, required=False, default=0,
                        help="Initial rng seed, 0 = time-based")
    parser.add_argument('--p1num', type=int, required=False, default=1,
                        help="Planet number for player 1.")
    parser.add_argument('--p2num', type=int, required=False, default=1,
                        help="Planet number for player 2.")
    parser.add_argument('--nnum', type=int, required=False, default=10,
                        help="Number of neutral planets.")
    parser.add_argument('--genmaps', action='store_true', required=False, default=False,
                        help="Generate random maps.")

    arguments, remaining = parser.parse_known_args(argv)

    seed = 0
    if arguments.seed == 0:
      # use system seed and print the resulting random integer
      seed = random.randint(1, 2000000000)
    else:
      # use passed on seed
      seed = arguments.seed

    random.seed(seed)
    print "seed=", seed  #, "rnd1=", random.randint(1, 2000000000)

    if arguments.genmaps:
      print "p1num=", arguments.p1num
      print "p2num=", arguments.p2num
      print "nnum=",  arguments.nnum

    if arguments.genmaps:
      state = State()
      state.random_setup(arguments.p1num, arguments.p2num, arguments.nnum)
      game = PlanetWars(remaining[:2], planets=state.planets, fleets=state.fleets, turns_per_second=arguments.rate, collisions=arguments.collisions)
    else:
      game = PlanetWars(remaining[:2], map_name=arguments.map, turns_per_second=arguments.rate, collisions=arguments.collisions)
      
    game.add_view(TextView(arguments.quiet))
    game.play()
Example #5
0
def home():
    """Home screen with the chess board and all functionality"""

    # Create a new state and save it in session
    session["fen"] = State().board.fen()

    # Render the page
    return render_template("home.html")
Example #6
0
def move():
    fen = session["fen"]
    state = State()
    state.board.set_fen(fen)
    source = request.form["source"]
    target = request.form["target"]

    move = chess.Move(chess.SQUARE_NAMES.index(source),
                      chess.SQUARE_NAMES.index(target))
    if move is not None and move != "":
        assert move in state.board.legal_moves
        try:
            state.board.push(move)

            # now let the computer take it's turn
            if not state.board.is_game_over():
                ai_move(state)

            session["fen"] = state.board.fen()
            return app.response_class(response=state.board.fen(), status=200)
        except Exception:
            traceback.print_exc()
            return app.response_class(response="Error processing gameplay",
                                      status=500)
 def test_valid_state(self) -> None:
     state_value: Tuple[str, float, int] = ("left", 1.0, 0)
     state = State(state_value)
     self.assertEqual(state.value, state_value)
 def test_cannot_add_dynamic_property(self) -> None:
     with self.assertRaises(AttributeError):
         state: State[str] = State('A')
         state.x = state.value
Example #9
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--collisions',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Should the ships collide among each other?")
    parser.add_argument('--rate',
                        type=int,
                        required=False,
                        default=100,
                        help="Number of turns per second run by the game.")
    parser.add_argument('--map',
                        type=str,
                        required=False,
                        default="map1",
                        help="The filename without extension for planets.")
    parser.add_argument('--quiet',
                        action='store_true',
                        required=False,
                        default=True,
                        help="Suppress all output to the console.")

    parser.add_argument('--seed',
                        type=int,
                        required=False,
                        default=0,
                        help="Initial rng seed, 0 = time-based")
    parser.add_argument('--p1num',
                        type=int,
                        required=False,
                        default=1,
                        help="Planet number for player 1.")
    parser.add_argument('--p2num',
                        type=int,
                        required=False,
                        default=1,
                        help="Planet number for player 2.")
    parser.add_argument('--nnum',
                        type=int,
                        required=False,
                        default=10,
                        help="Number of neutral planets.")
    parser.add_argument('--genmaps',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Generate random maps.")
    parser.add_argument(
        '--gennum',
        type=bool,
        required=False,
        default=False,
        help="Generate player and neutral numbers at runtime with random seed."
    )
    parser.add_argument('--train',
                        type=bool,
                        required=False,
                        default=False,
                        help="Do you want to train a bot")
    parser.add_argument('--games',
                        type=int,
                        required=False,
                        default=1,
                        help="The number of games to play")

    arguments, remaining = parser.parse_known_args(argv)

    seed = 0
    if arguments.seed == 0:
        # use system seed and print the resulting random integer
        seed = random.randint(1, 2000000000)
    else:
        # use passed on seed
        seed = arguments.seed

    random.seed(seed)
    print("seed=", seed)  #, "rnd1=", random.randint(1, 2000000000)

    all_games_timing = time.time()
    winners = {3: 0, 0: 0, 1: 0, 2: 0}
    logging.info('------------------------------- vs ' + str(remaining[:2][1]))
    for games in xrange(arguments.games):
        if arguments.genmaps:
            if arguments.gennum:
                player_starting_p = random.randint(1, 2)
                arguments.p1num = player_starting_p
                arguments.p2num = player_starting_p
                arguments.nnum = random.randint(2, 5)
            print("p1num=", arguments.p1num)
            print("p2num=", arguments.p2num)
            print("nnum=", arguments.nnum)

        games_timing = time.time()
        if arguments.genmaps:
            state = State()
            state.random_setup(arguments.p1num, arguments.p2num,
                               arguments.nnum)
            game = PlanetWars(remaining[:2],
                              planets=state.planets,
                              fleets=state.fleets,
                              turns_per_second=arguments.rate,
                              collisions=arguments.collisions,
                              train=arguments.train)
        else:
            game = PlanetWars(remaining[:2],
                              map_name=arguments.map,
                              turns_per_second=arguments.rate,
                              collisions=arguments.collisions,
                              train=arguments.train)

        game.add_view(TextView(arguments.quiet))
        winner, _, _, _, _ = game.play()
        if winner == 1 or winner == 2 or winner == 3:
            winners[winner] += 1
        else:
            winners[0] += 1  # this is a tie
        logging.info(
            str(winners) + '     Time: ' + str(time.time() - games_timing))
        print('---------------------------------------------------------')
        print('Game time: ', time.time() - games_timing, ' seconds')
        print('---------------------------------------------------------')
        # before every game
        if arguments.train == True and (remaining[:2][0] == 'HeuristicNN'
                                        or remaining[:2][1] == 'HeuristicNN'):
            from planetwars.neuralnetwork import NNetwork
            NNetwork.save()

    print('---------------------------------------------------------')
    print('All games: ', time.time() - all_games_timing, ' seconds')
    print('---------------------------------------------------------')
    print('Ties        ' + str(remaining[:2][0]) + '        ' +
          remaining[:2][1])
    print(
        str(winners[0]) + '           ' + str(winners[1]) +
        '                  ' + str(winners[2]))
    print('---------------------------------------------------------')
Example #10
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--collisions', action='store_true', required=False, default=False,
                        help="Should the ships collide with each other?")
    parser.add_argument('--games', type=int, required=False, default=100,
                        help="Number of games to be played.")
    parser.add_argument('--seed', type=int, required=False, default=0,
                        help="Initial rng seed, 0 = system-based")
    parser.add_argument('--p1num', type=int, required=False, default=1,
                        help="Planet number for player 1.")
    parser.add_argument('--p2num', type=int, required=False, default=1,
                        help="Planet number for player 2.")
    parser.add_argument('--nnum', type=int, required=False, default=21,
                        help="Number of neutral planets.")
    parser.add_argument('--genmaps', action='store_true', required=False, default=False,
                        help="Generate random maps.")
    parser.add_argument('--quiet', action='store_true', required=False, default=False,
                        help="Suppress all output to the console.")

    arguments, remaining = parser.parse_known_args(argv)

    seed = 0
    if arguments.seed == 0:
      # use system seed and print the resulting random integer
      seed = random.randint(1, 2000000000)
    else:
      # use passed on seed
      seed = arguments.seed

    random.seed(seed)
    print "seed=", seed  #, "rnd1=", random.randint(1, 2000000000)

    if arguments.genmaps:
      print "p1num=", arguments.p1num
      print "p2num=", arguments.p2num
      print "nnum=",  arguments.nnum

    players = remaining
    res = numpy.zeros((len(players), len(players)))
    time_max = numpy.zeros((len(players)))
    time_totals = numpy.zeros((len(players)))    

    maps = []
    
    for gn in range(arguments.games):
      n = gn+1
      state = State()
      map_name = None
      if arguments.genmaps:
        state.random_setup(arguments.p1num, arguments.p2num, arguments.nnum)
      else:
        if len(maps) == 0:
          maps = ["map%i" % i for i in range(1, 100)]
          random.shuffle(maps, random.random)
        map_name = maps.pop()

      print "---------"
      if map_name == None:
        print "game", gn, "Map: generated"
      else:
        print "game", gn, "Map:", map_name
      print
      
      for i1,p1 in enumerate(players):
        for i2,p2 in enumerate(players):
          if i2 >= i1:
            continue
          pair = [players[i1], players[i2]]
          if map_name == None:
            game = PlanetWars(pair, planets=copy.deepcopy(state.planets), \
                              fleets=copy.deepcopy(state.fleets), collisions=arguments.collisions)
            #print_planets(state.planets)
          else:
            game = PlanetWars(pair, map_name, collisions=arguments.collisions)
          
          winner, ship_counts, turns, tt, tm = game.play()
          
          print "%-16s vs. %-16s winner= %d turns= %d" % (p1, p2, winner, turns)
          if winner == 0:
            res[i1][i2] += 0.5
            res[i2][i1] += 0.5
          elif winner == 1:
            res[i1][i2] += 1
            res[i2][i1] += 0
          else:
            res[i1][i2] += 0
            res[i2][i1] += 1

          time_totals[i1] += tt[1]/turns
          time_totals[i2] += tt[2]/turns
          time_max[i1] = max(time_max[i1], tm[1])
          time_max[i2] = max(time_max[i2], tm[2])          
          
      totals = []
      list = []
      for i1,p1 in enumerate(players):
        total = 0
        for i2,p2 in enumerate(players):
          total += res[i1][i2]
        totals.append(total)
        list.append((i1, total))

      slist = sorted(list, key=itemgetter(1), reverse=True)

      print
      print "                            ",
      for i1,p1 in enumerate(players):
        print "    %2d" % i1,
      print
      
      for i1,p1 in enumerate(players):
        mi1 = slist[i1][0]
        mt1 = slist[i1][1]
        print "%2d %-17s : %5.1f : " % (i1, players[mi1], 100*mt1/n/(len(players)-1)),
        for i2,p2 in enumerate(players):
          mi2 = slist[i2][0]
          print "%5.1f " % (100*res[mi1][mi2]/n),
        print " avgt: %7.2f maxt: %7.2f" % (1000*time_totals[mi1]/n/(len(players)-1), 1000*time_max[mi1])
      
      #sys.stdout.write('.')
      #sys.stdout.flush()

    print res
Example #11
0
def main(argv):

    stats = []
    win_ctr = turns_ctr = r_ctr = counter = n_g = qv = qv_ctr = 0

    parser = argparse.ArgumentParser()
    parser.add_argument('--collisions',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Should the ships collide with each other?")
    parser.add_argument('--games',
                        type=int,
                        required=False,
                        default=100,
                        help="Number of games to be played.")
    parser.add_argument('--seed',
                        type=int,
                        required=False,
                        default=0,
                        help="Initial rng seed, 0 = system-based")
    parser.add_argument('--p1num',
                        type=int,
                        required=False,
                        default=1,
                        help="Planet number for player 1.")
    parser.add_argument('--p2num',
                        type=int,
                        required=False,
                        default=1,
                        help="Planet number for player 2.")
    parser.add_argument('--nnum',
                        type=int,
                        required=False,
                        default=21,
                        help="Number of neutral planets.")
    parser.add_argument('--genmaps',
                        action='store_true',
                        required=False,
                        default=False,
                        help='Use generated maps.')
    parser.add_argument('--toy',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Use toy maps.")
    parser.add_argument('--quiet',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Suppress all output to the console.")

    arguments, remaining = parser.parse_known_args(argv)

    seed = 0
    if arguments.seed == 0:
        # use system seed and print the resulting random integer
        seed = random.randint(1, 2000000000)
    else:
        # use passed on seed
        seed = arguments.seed

    random.seed(seed)
    print "seed=", seed  #, "rnd1=", random.randint(1, 2000000000)

    if arguments.genmaps:
        print "p1num=", arguments.p1num
        print "p2num=", arguments.p2num
        print "nnum=", arguments.nnum

    players = remaining
    res = numpy.zeros((len(players), len(players)))
    time_max = numpy.zeros((len(players)))
    time_totals = numpy.zeros((len(players)))

    maps = []
    temp = 0
    for gn in range(arguments.games):
        n = gn + 1
        state = State()
        map_name = None
        if arguments.genmaps:
            state.random_setup(arguments.p1num, arguments.p2num,
                               arguments.nnum)
        else:
            if len(maps) == 0:
                if arguments.toy:
                    maps = ["map_toy%i" % i for i in range(1, 10)]
                else:
                    maps = ["map%i" % i for i in range(1, 100)]
                random.shuffle(maps, random.random)
            map_name = maps.pop()

        print "---------"
        if map_name == None:
            print "game", gn, "Map: generated"
        else:
            print "game", gn, "Map:", map_name
        print

        for i1, p1 in enumerate(players):
            for i2, p2 in enumerate(players):
                if i2 >= i1:
                    continue

                pair = [players[i1], players[i2]]

                if map_name == None:
                    game = PlanetWars(pair, planets=copy.deepcopy(state.planets), \
                                      fleets=copy.deepcopy(state.fleets), collisions=arguments.collisions)
                else:
                    game = PlanetWars(pair,
                                      map_name,
                                      collisions=arguments.collisions)

                winner, ship_counts, turns, tt, tm, reward, reward_e, counter, qv, qv_ctr = game.play(
                )

                turns_ctr += turns
                r_ctr += reward

                print("DQN bot reward for game is {}".format(reward))
                print("Another bot reward for game is {}".format(reward_e))

                print "%-16s vs. %-16s winner= %d turns= %d" % (p1, p2, winner,
                                                                turns)
                if winner == 0:
                    res[i1][i2] += 0.5
                    res[i2][i1] += 0.5
                elif winner == 1:
                    win_ctr += 1
                    res[i1][i2] += 1
                    res[i2][i1] += 0
                else:
                    res[i1][i2] += 0
                    res[i2][i1] += 1

                time_totals[i1] += tt[1] / turns
                time_totals[i2] += tt[2] / turns
                time_max[i1] = max(time_max[i1], tm[1])
                time_max[i2] = max(time_max[i2], tm[2])

        totals = []
        list = []
        for i1, p1 in enumerate(players):
            total = 0
            for i2, p2 in enumerate(players):
                total += res[i1][i2]
            totals.append(total)
            list.append((i1, total))

        slist = sorted(list, key=itemgetter(1), reverse=True)

        print
        print "                            ",
        for i1, p1 in enumerate(players):
            print "    %2d" % i1,
        print

        for i1, p1 in enumerate(players):
            mi1 = slist[i1][0]
            mt1 = slist[i1][1]
            print "%2d %-17s : %5.1f : " % (i1, players[mi1], 100 * mt1 / n /
                                            (len(players) - 1)),
            for i2, p2 in enumerate(players):
                mi2 = slist[i2][0]
                print "%5.1f " % (100 * res[mi1][mi2] / n),
            print " avgt: %7.2f maxt: %7.2f" % (1000 * time_totals[mi1] / n /
                                                (len(players) - 1),
                                                1000 * time_max[mi1])

        stats.append('{};{};{}'.format(win_ctr, turns_ctr, r_ctr))
        win_ctr = turns_ctr = r_ctr = 0

        if counter >= 10000:
            n_g = (gn - n_g + 1.0 if temp == 0 else float(gn - temp))
            temp = gn

    write_to_file(game, stats)

    print res
Example #12
0
    start = time.time()
    val, moves = minimax(state,
                         ai,
                         playing_as_white=state.board.turn == chess.WHITE)
    best_moves = sorted(moves, key=lambda x: x[0], reverse=True)
    if len(best_moves) == 0:
        return None

    eta = time.time() - start
    print("AI move in %.3f second(s)" % (eta))

    print("top 3 options:")
    for i, m in enumerate(best_moves[0:3]):
        print("  ", m)

    return best_moves[0][1]


def ai_move(state):
    move = eval_options(state)
    state.board.push(move)


if __name__ == '__main__':
    ai = ChessAI()
    state = State()
    state.board.set_fen("4k3/2R5/2R5/8/8/8/8/3K4 w - - 0 1")

    move = eval_options(state)
Example #13
0
 def get_start_state(self) -> State[IntTuple]:
     for row in range(self.__num_rows):
         for col in range(self.__num_col):
             if self.__maze[row][col] == 'S':
                 return State((row, col))
     return State((-1, -1))
Example #14
0
def main(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument('--collisions',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Should the ships collide among each other?")
    parser.add_argument('--rate',
                        type=int,
                        required=False,
                        default=100,
                        help="Number of turns per second run by the game.")
    parser.add_argument('--map',
                        type=str,
                        required=False,
                        default="map1",
                        help="The filename without extension for planets.")
    parser.add_argument('--quiet',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Suppress all output to the console.")

    parser.add_argument('--seed',
                        type=int,
                        required=False,
                        default=0,
                        help="Initial rng seed, 0 = time-based")
    parser.add_argument('--p1num',
                        type=int,
                        required=False,
                        default=1,
                        help="Planet number for player 1.")
    parser.add_argument('--p2num',
                        type=int,
                        required=False,
                        default=1,
                        help="Planet number for player 2.")
    parser.add_argument('--nnum',
                        type=int,
                        required=False,
                        default=10,
                        help="Number of neutral planets.")
    parser.add_argument('--genmaps',
                        action='store_true',
                        required=False,
                        default=False,
                        help="Generate random maps.")

    arguments, remaining = parser.parse_known_args(argv)

    seed = 0
    if arguments.seed == 0:
        # use system seed and print the resulting random integer
        seed = random.randint(1, 2000000000)
    else:
        # use passed on seed
        seed = arguments.seed

    random.seed(seed)
    print "seed=", seed  #, "rnd1=", random.randint(1, 2000000000)

    if arguments.genmaps:
        print "p1num=", arguments.p1num
        print "p2num=", arguments.p2num
        print "nnum=", arguments.nnum

    if arguments.genmaps:
        state = State()
        state.random_setup(arguments.p1num, arguments.p2num, arguments.nnum)
        game = PlanetWars(remaining[:2],
                          planets=state.planets,
                          fleets=state.fleets,
                          turns_per_second=arguments.rate,
                          collisions=arguments.collisions)
    else:
        game = PlanetWars(remaining[:2],
                          map_name=arguments.map,
                          turns_per_second=arguments.rate,
                          collisions=arguments.collisions)

    game.add_view(TextView(arguments.quiet))
    game.play()