Example #1
0
 def test_move(self):
     game = Game('Kf3,Pe2,ke8,qf7')
     self.assertEqual(game.current_player, WHITE)
     with self.assertRaises(errors.WrongTurnError):
         game.move(BLACK, (5, 4), (5, 5))
     with self.assertRaises(errors.NotFoundError):
         game.move(WHITE, (5, 4), (5, 5))
     with self.assertRaises(errors.WrongFigureError):
         game.move(WHITE, (5, 8), (5, 7))
     with self.assertRaises(errors.WrongMoveError):
         game.move(WHITE, (5, 2), (5, 5))
     fig, move = game.move(WHITE, (5, 2), (5, 4))
     self.assertIsInstance(fig, Pawn)
     self.assertEqual(move, 'e2-e4')
     self.assertEqual(game.current_player, BLACK)
     with self.assertRaises(errors.BlackWon) as cm:
         game.move(BLACK, (6, 7), (6, 3))
     self.assertIsInstance(cm.exception.figure, Queen)
     self.assertEqual(cm.exception.move, 'f7-f3')
     self.assertEqual(str(game.board.lastCut), 'Kf3')
     game = Game('Ke1,Rh1,ke8')
     fig, move = game.move(WHITE, (5, 1), (7, 1))
     self.assertIsInstance(fig, King)
     self.assertEqual(move, '0-0')
     self.assertEqual(game.current_player, BLACK)
Example #2
0
 def on_create(self, game_mode, word_length):
     word = self.dictionary.filter_by_length(word_length).choice()
     query = self.dictionary.filter_from_string(word).filter_by_length(
         3, word_length)
     if game_mode == GameMode.TIMED_RETRIES or game_mode == GameMode.RETRIES:
         self.current_game = Game(word, query, mistakes=3, mode=game_mode)
     else:
         self.current_game = Game(word, query, mode=game_mode)
Example #3
0
def execute():
    ai = Player()

    ai.bank = 3000
    ai.limit = 3000

    op = Opponent()

    op.bank = 3000

    participants = [ai, op]

    game = Game()

    game.handout(1)

    pre_chance, _ = game.make_round(participants)

    floop_chance, _ = game.make_round(participants)

    turn_chance, _ = game.make_round(participants)

    game.make_round(participants)

    river_chance, gess = game.make_round(participants)

    return gess, river_chance, turn_chance, floop_chance, pre_chance
Example #4
0
def game_gen_worker(*args):
    global WORKER_NN
    if not WORKER_NN:
        if WORKER_MODEL_ID > 0:
            WORKER_NN = load_net(WORKER_DNAME + fname_from_id(WORKER_MODEL_ID))
        else:
            WORKER_NN = Net()
        WORKER_NN.eval()
    nn = WORKER_NN

    p1 = NNSimplePlayer('p1', nn=nn, train=True)
    p2 = NNSimplePlayer('p2', nn=nn, train=True)
    g = Game(players=[p1, p2], verbose=False)
    winner = g.run()
    extra = ''
    for _ in range(5):
        try:
            fname = '{:05}_{}_{}__{}.json'.format(WORKER_MODEL_ID, int(time.time()), extra, len(p1._states) + len(p2._states))
            with open(f'{WORKER_DNAME}{fname}', 'x') as f:
                json.dump({'p1_s': p1._states, 'p2_s': p2._states, 'w': 0 if p1 == winner else 1}, f)
                log.info('wrote %s', fname)
            break
        except FileExistsError:
            log.info('file exists')
            extra = str(random.randint(1,1000))
Example #5
0
    def test_self_discard(self):
        p1 = TestPlayer('p1', hand=[EXPLORER])
        p2 = TestPlayer('p2')
        g = Game([p1, p2])

        with patch.object(TestPlayer, 'choose_action') as choose_action:
            choose_action.return_value = UserActionPlayCard(EXPLORER)

            g.do_one_user_action(p1, p2)
            choose_action.assert_called_once()
            self.assertEqual(2, p1.trade)
            self.assertEqual(1, len(p1.remaining_actions))
            self.assertSequenceEqual([(EXPLORER, EXPLORER.actions[1])],
                                     p1.remaining_actions)

        action = UserActionCardAction(EXPLORER, EXPLORER.actions[1])
        actions = g.available_actions(p1, p2)
        self.assertIn(action, actions)

        with patch.object(TestPlayer, 'choose_action') as choose_action:
            choose_action.return_value = action

            g.do_one_user_action(p1, p2)
            choose_action.assert_called_once()
            self.assertEqual(2, p1.trade)
            self.assertEqual(2, p1.damage)
            self.assertEqual(0, len(p1.remaining_actions))
Example #6
0
def execute(participants, game_num, small_blind, num_of_members):
    print('\n â„–{}\n'.format(game_num))

    if game_num == 1:
        fill_banks_of_members(participants, num_of_members, bank=limit)

    participants[0].limit = participants[0].bank
    participants[0].blef_rises = 0

    for p in participants:
        p.in_game = True

    kol = Game(game_num, small_blind)

    kol.handout(num_of_members - 1)
    kol.make_round(participants)
    kol.make_round(participants)
    kol.make_round(participants)
    kol.make_round(participants)
    kol.make_round(participants)

    for p in participants:
        add_money(p, limit)

    check_banks(participants)

    if len(participants) == 1:
        print('Игра окончена: победитель {}, выигрыш ${}'.format(
            participants[0].nick, participants[0].bank))
        exit()

    return kol.game_num
Example #7
0
 def test_move_2(self):
     game = Game('pc2,Ke1,ke8', BLACK)
     self.assertEqual(str(game.board.getFigure(BLACK, PAWN)), 'pc2')
     with self.assertRaises(errors.NotFoundError):
         game.board.getFigure(BLACK, QUEEN)
     game.move(BLACK, (3, 2), (3, 1))
     self.assertEqual(str(game.board), 'Ke1,ke8,qc1')
     self.assertEqual(str(game.board.getFigure(BLACK, QUEEN)), 'qc1')
     with self.assertRaises(errors.NotFoundError):
         game.board.getFigure(BLACK, PAWN)
Example #8
0
 def test_move_1(self):
     game = Game('Pc7,Ke1,ke8')
     self.assertEqual(str(game.board.getFigure(WHITE, PAWN)), 'Pc7')
     with self.assertRaises(errors.NotFoundError):
         game.board.getFigure(WHITE, QUEEN)
     game.move(WHITE, (3, 7), (3, 8))
     self.assertEqual(str(game.board), 'Ke1,ke8,Qc8')
     self.assertEqual(str(game.board.getFigure(WHITE, QUEEN)), 'Qc8')
     with self.assertRaises(errors.NotFoundError):
         game.board.getFigure(WHITE, PAWN)
Example #9
0
def worker(p1_p2):
    p1, p2 = p1_p2
    p1 = PLAYERS_MAP[p1]
    p2 = PLAYERS_MAP[p2]

    players = [p1(), p2()]
    game = Game(players, verbose=False)
    winner = game.run()
    loser = players[0] if winner == players[1] else players[1]
    return winner.name, loser.name
Example #10
0
def game():
    # By seed(0), random sequence for dice becomes [8, 8, 2, 6, 10, 9, 8, 6, 9, 7, 11, 5, 10, 4, 6, 4, 3, 11, 6, 10]
    global event_queue
    seed(0)
    event_queue = deque()
    ee = EventEmitterSingleton.instance()
    ee.remove_all_listeners()
    for e in [
            'transaction', 'newplayer', 'newround', 'offer', 'invoice',
            'match', 'leaving'
    ]:
        ee.on(e, queue_event(e))
    return Game()
Example #11
0
def simple_match():

    win = {'p1': 0, 'p2': 0}
    for i in range(500):
        p1 = RandomPlayer('p1')
        p2 = RandomPlayer('p2', w=WEIGHT_MAP29)
        players = [p1, p2]
        if i % 2:
            players = players[::-1]
        g = Game(players, seed=None)
        winner = g.run()
        win[winner.name] += 1
        print(win)
    print(win)
Example #12
0
def run_match(x: np.ndarray):
    w = {k: v for k, v in zip(ACTIONS, x)}
    win = {'p1': 0, 'p2': 0}
    for i in range(100):
        p1 = RandomPlayer('p1', w=WEIGHT_MAP)
        p2 = RandomPlayer('p2', w=w)
        players = [p1, p2]
        if i % 2:
            players = players[::-1]
        g = Game(players, seed=None, verbose=False)
        try:
            winner = g.run()
            win[winner.name] += 1
        except:
            log.exception('error running game')
    pct = win['p1'] / (win['p1'] + win['p2'])
    #log.info('match win ratio: %s', pct)
    return pct
Example #13
0
async def wshandle(request):
    ws = web.WebSocketResponse()
    await ws.prepare(request)

    game = None

    log = logging.getLogger(request.remote)

    async for msg in ws:
        log.info('got: %s', msg)
        if msg.type == web.WSMsgType.text:
            event, data = msg.json()
            if event == 'start_game':
                if game:
                    p1._q.put(STOP_GAME)
                    # should really not do this...
                    t.join()

                from players.monte_carlo import MCSimplePlayer

                p1 = WebPlayer(ws, 'p1')
                # p2 = InteractivePlayer('p2')
                #p2 = MCSimplePlayer('p2')
                p2 = SimplePlayer('p2')
                p2 = NNSimplePlayer('p2', '8 7')

                game = Game([p1, p2], seed=666)
                p1.game = game
                p1.proxy_player(p2)
                t = Thread(target=game.run)
                await ws.send_json(['status', 'game started'])
                t.start()
            elif event in ('choose_action', 'choose_piles'):
                # TODO: check game is started...
                p1._q.put([event, data])
            else:
                log.warning('unknown event: %s; data=%s', event, data)
        #elif msg.type == web.WSMsgType.binary:
        #    await ws.send_bytes(msg.data)
        elif msg.type == web.WSMsgType.close:
            break
        else:
            log.warning('unknown message type:', msg)
    return ws
Example #14
0
 def test_full_game(self):
     moves = [
         'e2-e4', 'e7-e5', 'g1-f3', 'b8-c6', 'f1-c4', 'c6-d4', 'f3-e5',
         'd8-g5', 'e5-f7', 'g5-g2', 'h1-f1', 'g2-e4', 'c4-e2', 'd4-f3',
         'e2-f3', 'e4-e1'
     ]
     game = Game()
     with self.assertRaises(errors.BlackWon):
         for move in moves:
             positions = map(coors2pos, move.split('-'))
             game.move(game.current_player, *positions)
     expect = [
         'Pa2', 'Pb2', 'Pc2', 'Pd2', 'Pf2', 'Ph2', 'Ra1', 'Rf1', 'Nb1',
         'Nf7', 'Bc1', 'Bf3', 'Qd1', 'pa7', 'pb7', 'pc7', 'pd7', 'pg7',
         'ph7', 'ra8', 'rh8', 'ng8', 'bc8', 'bf8', 'qe1', 'ke8'
     ]
     self.assertEqual(str(game.board), ','.join(expect))
     expect = [(PAWN, BLACK), (PAWN, BLACK), (PAWN, WHITE), (PAWN, WHITE),
               (KNIGHT, BLACK), (KING, WHITE)]
     self.assertEqual(game.board.cuts, expect)
Example #15
0
    def test_card_optional_ally_action(self):
        p1 = TestPlayer('p1')
        p2 = TestPlayer('p2')
        g = Game([p1, p2])
        p1.trade = 100
        p1.bases.append(BlobWheel)
        p1.hand.append(BlobCarrier)

        action = UserActionCardAction(BlobCarrier, ActionFreeShipCard())

        actions = g.available_actions(p1, p2)
        self.assertNotIn(action, actions)

        with patch.object(TestPlayer, 'choose_action') as choose_action:
            choose_action.return_value = UserActionPlayCard(BlobCarrier)
            g.do_one_user_action(p1, p2)

            choose_action.assert_called_once()
            self.assertEqual(1, len(p1.in_play))

        actions = g.available_actions(p1, p2)
        self.assertIn(action, actions)
Example #16
0
    def test_attack_outpost(self):
        p1 = TestPlayer('p1')
        p2 = TestPlayer('p2')
        g = Game([p1, p2])

        p1.damage = 10
        p1.trade = 100
        p2.outposts.append(Junkyard)

        action = UserActionAttackOutpost(Junkyard)
        actions = g.available_actions(p1, p2)
        self.assertIn(action, actions)

        with patch.object(TestPlayer, 'choose_action') as choose_action:
            choose_action.return_value = action

            g.do_one_user_action(p1, p2)
            choose_action.assert_called_once()
            self.assertEqual(0, len(p2.outposts))
            self.assertEqual(10 - Junkyard.defence, p1.damage)

        actions = g.available_actions(p1, p2)
        self.assertNotIn(action, actions)
Example #17
0
import sys
import os
sys.path.append(os.path.dirname(__file__) + os.sep + '../')

import pygame.locals
from Environment import *
from engine.Game import *
from game.scenes.SceneType import *

Environment.init()
game = Game(SceneType.Welcome)
while True:
    event = Environment.getEvent()
    if event.type == pygame.locals.QUIT:
        sys.exit()
    game.handleEvent(event)
Example #18
0
def main():
    game = Game()
    game.run()
Example #19
0
def main(): 
    game = Game(_details)
    game.run()
Example #20
0
            return a

        return random.choice(actions)

    def choose_buy_actions(self, game, p1, p2, buys):
        card_to_action = {a.card: a for a in buys}
        c = self.choose_buy_card(game, p1, p2, card_to_action.keys())
        if c:
            return card_to_action[c]

    def choose_buy_card(self, game, p1, p2, cards):
        # buy most expensive
        b = max(cards, key=attrgetter('cost'))
        return b


class SimplePlayer(Player, SimplePolicy):
    def choose_action(self, b, p_other, actions):
        return self.simple_action_policy(self, b, p_other, actions)

    choose_card_action = choose_action

    def do_choose_from_piles(self, action, piles, min_n, max_n):
        return self.simple_pile_policy(self, action, piles, min_n, max_n)


if __name__ == '__main__':
    p1 = InteractivePlayer('p1')
    p2 = SimplePlayer('p2')
    g = Game(players=[p1, p2])
    winner = g.run()
Example #21
0
def main(stdscr):
    currentGame = Game(20,40)
    f_stop = threading.Event()
    step(f_stop, currentGame, stdscr)
    listen_for_keypress(currentGame, stdscr)
Example #22
0
                break
        f.close()


def getAllWardrobes():
    return [
        Wardrobe('audiencia/boy/'),
        Wardrobe('audiencia/girl/'),
        Wardrobe('audiencia/fashion_boy/'),
        Wardrobe('audiencia/fashion_girl/'),
        Wardrobe('audiencia/goth/'),
    ]


all_wardrobes = getAllWardrobes()


def buildIndividual(level, wardrobes):
    if wardrobes is None:
        wardrobes = all_wardrobes
    wd = random.choice(wardrobes)
    i = Individual(wd)
    i.random(level=level + 1, clothinBehavior=wd.behaviour)
    return i


if __name__ == "__main__":
    wardrobes = getAllWardrobes()  # x,y
    g = Game(*SCREEN_SIZE, **{'framerate': 200})
    g.run(SampleScene(g, "Scene1", wardrobes, level=6))
Example #23
0
 def restart_game(self):
     game = Game()
     self.restart_with_game_engine = game
Example #24
0
def handle_restart():
    global game
    app.logger.info('got restart')
    game = Game()
    emit('restart_ack', broadcast=True)