示例#1
0
    def test_lost_but_still_there(self):
        game = Game(self.app,
                    "12345678",
                    "crazyhouse",
                    "",
                    self.wplayer,
                    self.bplayer,
                    rated=True,
                    chess960=True,
                    create=True)
        self.assertEqual(game.status, CREATED)

        for row in game.highscore["crazyhouse960"].items():
            print(row)
        highscore0 = game.highscore["crazyhouse960"].peekitem(7)

        game.update_status(status=RESIGN, result="0-1")
        self.loop.run_until_complete(game.update_ratings())

        print("-------")
        print(game.p0, game.p1)
        print(self.bplayer.perfs["crazyhouse960"])
        print(self.wplayer.perfs["crazyhouse960"])

        for row in game.highscore["crazyhouse960"].items():
            print(row)
        highscore1 = game.highscore["crazyhouse960"].peekitem(7)

        self.assertNotEqual(highscore0, highscore1)
        self.assertTrue(
            self.wplayer.username in game.highscore["crazyhouse960"])
示例#2
0
def main():
    SUNDAY=6
    # use one of the next two lines
    tillWeekday = datetime.datetime.today().weekday()  # by default only today()
    tillWeekday = SUNDAY
    
    nextDay=datetime.datetime.today()
    
    # build a List of dates we want Games for 
    untilDates = []
    while(True):
        if tillWeekday == nextDay.weekday():
            untilDates.append(nextDay.strftime('%Y%m%d'))
            break;
        else:
            untilDates.append(nextDay.strftime('%Y%m%d'))
            nextDay += datetime.timedelta(1)
    buf=''
    for targetDate in untilDates:
        for league in ['NFL', 'MLB', 'NBA', 'NHL', 'CBK', 'CFB']:
            gd = DailyGames(league, targetDate)
            todays_games = gd.GetAndProcessData()
            for gameInfo in todays_games:
                game = Game(info=gameInfo)
                buf += game.toString() + os.linesep
                utils.session.add(game)
                utils.session.commit()
            #time.sleep(2)
    print buf
    MySendMail.MySendMail('Schuled Games until Sunday', buf)
示例#3
0
async def create_game(games, ctx) -> Game:
    voice: VoiceState = ctx.author.voice
    game = Game(voice.channel)

    # add players in voice chat to game
    for member in voice.channel.members:
        await member.edit(mute=False, deafen=False)
        game.add_player(member)

    games.append(game)
    return game
示例#4
0
def play(board, save_normalized_matrix=True):
    """
    Parameters
    ----------
    board : numpy.array
    save_normalized_matrix : bool
        Whether to save normalized (log2 transformed) or original matrix.

    Returns
    -------
    collections.namedtuple
        Game with recorded steps.
    """

    steps = []
    render_board(board)

    while True:
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()
            if event.type == pygame.KEYDOWN:
                if event.key in POSSIBLE_ACTIONS:
                    matrix = board.normalized_matrix if save_normalized_matrix else board.matrix
                    action = POSSIBLE_ACTIONS[event.key]
                    moved = board.move(action) #boolean

                    if moved:
                        print()
                        print(board.matrix)
                        print("SCORE:", board.score, "\tSTEP:", board.n_steps_valid, "\tHIGHEST VALUE:", board.highest_value)
                        steps.append(Step(matrix=matrix, action=action, action_encoded=encode_action(action)))
                        render_board(board)

                        if board.is_gameover():
                            print("GAME OVER!")
                            return Game(steps=steps, score=board.score, random_seed=board.random_seed, is_gameover=True)
                    else:
                        print("\nCannot move to this direction!")
                elif event.key == pygame.K_q:
                    screen.fill(BLACK)
                    return Game(steps=steps, random_seed=board.random_seed, is_gameover=False)
                elif event.key == pygame.K_p:
                    screen.fill(BLACK)
                    return "quit"

        clock.tick(60)
        pygame.display.flip()
示例#5
0
def do_game_gc(game: Game,
               reparse: bool,
               actions_gc: dict,
               converter: str = None):
    try:
        # check if the gamecontroller file needs to be converted
        if game.has_gc_file():
            # convert gamecontroller file first
            if not game.gc.has_converted() and converter:
                if not args.dry_run: game.gc.convert(converter)
            # check if gamecontroller file needs to be re-created
            if reparse or set(actions_gc.keys()) - set(
                    game.gc.parsed_actions()):
                logging.info(
                    '%s / %s - missing actions in gamecontroller file! re-creating ...',
                    str(game.event), str(game))
                if not args.dry_run: game.gc.create_info_file(actions_gc)
    except KeyboardInterrupt:
        # ignore canceled jobs
        pass
    except Exception:
        logging.error(
            "An error occurred during conversion of gamecontroller of %s",
            game)
        traceback.print_exc()
    return game
示例#6
0
def play_random(board, save_normalized_matrix=True):

    steps = []
    render_board(board)

    while True:

        #Exit if needed by pressing red cross
        for event in pygame.event.get():
            if event.type == QUIT:
                pygame.quit()
                sys.exit()

        #Playing randomly
        r = np.random.RandomState()
        action = r.choice(list(range(GameEnv.NB_ACTIONS)))  #Select a random action
        moved = board.move(action)
        matrix = board.normalized_matrix if save_normalized_matrix else board.matrix

        if moved:
            print()
            print(board.matrix)
            print("SCORE:", board.score, "\tSTEP:", board.n_steps_valid, "\tHIGHEST VALUE:", board.highest_value)
            steps.append(Step(matrix=matrix, action=action, action_encoded=encode_action(action)))
            render_board(board)

            if board.is_gameover():
                print("GAME OVER!")
                return Game(steps=steps, score=board.score, random_seed=board.random_seed, is_gameover=True)            

        clock.tick(5)
        pygame.display.flip()
示例#7
0
def do_sync(game: Game):
    """
    Tries to synchronize the log files of the game.

    :param game:
    :return: return a synchronized game
    """
    try:
        if not all([l.has_syncing_info() for l in game.logs.values()]):
            if not args.dry_run: game.sync()
    except KeyboardInterrupt:
        # ignore canceled jobs
        pass
    except Exception:
        logging.error("An error occurred during synchronization of %s", game)
        traceback.print_exc()

    return game
示例#8
0
def init(dat=None):
    global PLAYER, CURRENT_MAP, EVENTS, GAME, MAPS, BOTS, KO_BOTS, SOUNDS, useAudio
    if NEW_GAME is True:
        name = getInput("Your Name: ")
        m = getInput("Play the tutorial? [Y/N]: ")
        if m == "y": tutorial.start()
        MAPS[1] = mapper.Map(1, reqs.testlevel, reqs.testlevel_hit, PLAYER, reqs.testlevel_events, reqs.testlevel_objects, GlobalVar("BOTS1", {}), {'BOTS':BOTS.value()})
        MAPS[2] = mapper.Map(2, reqs.testlevel2, reqs.testlevel2_hit, PLAYER, reqs.testlevel2_events, reqs.testlevel2_objects, GlobalVar("BOTS2", {}), {'BOTS':BOTS.value()})
        MAPS[3] = mapper.Map(3, reqs.testlevel3, reqs.testlevel3_hit, PLAYER, reqs.testlevel3_events, reqs.testlevel3_objects, GlobalVar("BOTS3", {}), {'BOTS':BOTS.value()})
        CURRENT_MAP.set(MAPS[1])
        initMap(CURRENT_MAP.e.events)
        PLAYER = Player(name, [2,2], CURRENT_MAP, 1, {'retMap':retMap, 'setMap':setMap})
        BOTS[1] = ai.Enemy(1, "Evil Bunny", PLAYER, [6,4], 1, [5,5], True, True, data={'attack':1,'char':".", "maps":MAPS.value(), "level":1, 'current':CURRENT_MAP})
        BOTS[2] = ai.Enemy(2, "Ye Old Ogre", PLAYER, [10,4], 2, [10,10], True, True, data={'attack':3.5,'char':"O", "maps":MAPS.value(), "level":2, 'current':CURRENT_MAP})
        BOTS[3] = ai.Enemy(3, "Evil Bunny", PLAYER, [2,2], 3, [8,8], True, True, data={'attack':1,'char':".", "maps":MAPS.value(), "level":3, 'current':CURRENT_MAP})
        BOTS[4] = ai.Enemy(4, "Evil Bunny", PLAYER, [8,4], 3, [8,8], True, True, data={'attack':1,'char':".", "maps":MAPS.value(), "level":3, 'current':CURRENT_MAP})
        BOTS[5] = ai.Enemy(5, "Evil Bunny", PLAYER, [7,7], 3, [15,15], True, True, data={'attack':1,'char':".", "maps":MAPS.value(), "level":3, 'current':CURRENT_MAP})
        BOTS[2].doMove = False
        MAPS[1].bots[1] = BOTS[1]
        MAPS[2].bots[2] = BOTS[2]
        MAPS[3].bots[3] = BOTS[3]
        MAPS[3].bots[4] = BOTS[4]
        MAPS[3].bots[5] = BOTS[5]
        regMapz()
        GAME = Game("Gametasim", PLAYER, MAPS.value(), 1, BOTS, KO_BOTS, {'setMap':setMap, 'events':EVENTS})
        SOUNDS["pok1"] = sound.Sound("pok1", './data/sounds/pok1.wav', useAudio)
        initEvents()
    elif NEW_GAME is False:
        r = open('maps.dat', 'rw')
        mapz = pickle.load(r)
        r.close()
        BOTS = mapz['bots']
        MAPS.e[1] = mapz[1]
        MAPS.e[2] = mapz[2]
        MAPS.e[3] = mapz[3]
        CURRENT_MAP.set(MAPS[1])
        PLAYER = Player(dat[1], [2,2], CURRENT_MAP, 1, {'retMap':retMap, 'setMap':setMap})
        MAPS[1].player = PLAYER
        MAPS[2].player = PLAYER
        GAME = Game("Gametasim", PLAYER, MAPS, 1, BOTS, KO_BOTS, {'setMap':setMap, 'events':EVENTS})
        SOUNDS["pok1"] = sound.Sound("pok1", './data/sounds/pok1.wav', useAudio)
        initEvents()
        GAME.regSave(dat[0])
示例#9
0
def do_game_video(game: Game):
    try:
        # check, if video info file should be created or updated
        if not game.has_video_file():
            logging.info(
                "%s / %s - missing video info file! creating default ...",
                str(game.event), str(game))
            if not args.dry_run: game.create_video_file()
        elif game.has_video_file() and game.has_video_file_changed():
            logging.info("%s / %s - updating video info file ...",
                         str(game.event), str(game))
            if not args.dry_run: game.create_video_file()
    except KeyboardInterrupt:
        # ignore canceled jobs
        pass
    except Exception:
        logging.error("An error occurred updating video file of %s", game)
        traceback.print_exc()
    return game
示例#10
0
def main(opt):
    win = pygame.display.set_mode(config.BOARD_SIZE)
    pygame.display.set_caption('Wumpus World, Q learning')
    FPS = 60

    clock = pygame.time.Clock()
    game = Game(win, None, None, None, None)

    items = {
        "robot": None,
        "wumpus": None,
        "hole1": None,
        "hole2": None,
        "gold": None
    }
    for i, item in enumerate(items.keys()):
        run = True
        logging.info(f"***SELECT {item}***")
        while run:
            clock.tick(FPS)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return

                if event.type == pygame.MOUSEBUTTONDOWN:
                    pos = pygame.mouse.get_pos()
                    row, col = get_row_col_from_mouse(pos)

                    items[item] = (col, row)
                    run = False
                    break

            game.reset(items['robot'], [items['hole1'], items['hole2']],
                       items['wumpus'], items['gold'])
            game.update()
    '''HyperParameters'''
    epsilon = opt.epsilon
    alpha = opt.lr
    gamma = opt.gamma

    q_learner = QLearning(gamma, alpha)
    penalties = 0

    logging.info(f"\n\n{40 * '*'} start learning {40 * '*'}\n\n")
    for epoch in range(1, opt.num_epochs + 1):
        game.reset(items['robot'], [items['hole1'], items['hole2']],
                   items['wumpus'], items['gold'])
        run = True
        while run:
            clock.tick(FPS)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    return

            state = game.board.robot

            if random.uniform(0, 1) < epsilon:
                action = random.randint(0, 3)
            else:
                action = q_learner.select_action(state)

            next_state, reward, end = game.move(action)

            q_learner.optimize(state,
                               action=action,
                               next_state=next_state,
                               reward=reward)

            if reward == -100:
                penalties += 1

            game.update()
            pygame.time.delay(1)

            if game.end():
                break

        if epoch % 100 == 0:
            logging.info(f"Epoch: {epoch}, Penalties: {penalties}")
            if opt.decay:
                epsilon *= 0.9
                q_learner.alpha *= 0.9

                logging.info(
                    f"Learning Rate : {q_learner.alpha} | Epsilon : {epsilon}")
示例#11
0
def main():
    game = Game()
    while True:
        print('Cards: %d' % game.card_sum_player)
        if game.draw(
        ) == 'stay':  # when stay is called from the game.draw() function
            if game.card_sum_player > game.card_sum_dealer:  # the condition for winning after staying
                game.score()
                if game.game_end(2) == 'end':
                    break
            elif game.card_sum_player < game.card_sum_dealer:  # the condition for losing after staying
                if game.game_end(1) == 'end':
                    break
            elif game.card_sum_player == game.card_sum_dealer:  # the condition for a draw after staying
                break
        if game.card_sum_player > 21:  # if exceeds 21 then lost
            game.score()
            if game.game_end(1) == 'end':
                break
        elif game.card_sum_player == 21:  # if is 21 then win
            if game.card_sum_dealer == 21:  # unless dealer also gets 21
                if game.game_end(0) == 'end':
                    break
            game.score()
            if game.game_end(2) == 'end':
                break
示例#12
0
from utils import Game
from fict_play import fictPlay
from mult_weights import no_regrets

print 'RESULTS:'
print '===================='

print
print ('Outputs are lists where the index is the agent and the value is a'
       ' mixed strategy represented by a mapping from actions to'
       ' probabilities.')
print

print "Prisoner's Dilemma:"
print '--------------------'
pd = Game('PrisonersDilemma.game')
print 'Fictitious Play:\t', fictPlay(pd, 2000)
print 'Multpilicative Weights:\t', no_regrets(pd, 100, .1)
print

print "Matching Pennies:"
print '--------------------'
mp = Game('MatchingPennies.game')
print 'Fictitious Play:\t', fictPlay(mp, 2000)
print 'Multpilicative Weights:\t', no_regrets(mp, 100, .1)
print

print "Rock, Paper, Scissors:"
print '--------------------'
rps = Game('RockPaperScissors.game')
print 'Fictitious Play:\t', fictPlay(rps, 2000)