Beispiel #1
0
def menu():
    fast = False
    if fast:
        board = generate_board(3)
        return Game([Player("p1"), Player("p2")], board)

    players = []
    print(
        '''Entre respectivamente o tamanho da quadra que voce quer usar, um valor de 3 a 10, 
    e o qantidade de jogadores que vao jogar. Minimo 2, maximo 5, para sair digite sair a qualquer momento'''
    )

    while True:
        board_size = int(input('Tamanho do tabuleiro: '))
        if 2 < board_size <= 10:
            break
    while True:
        pos = len(players)
        player_name = input('Nome do jogador ' + (pos + 1).__str__() + ": ")
        players.append(Player(player_name))

        # verifica se o tamanho do tabuleiro é 3 e se tem 2 jogadores e continua o jogo, fica impossivel
        # jogar com mais de dois jogadores no mesmo tabuleiro
        if board_size.__eq__(3) and len(players).__eq__(2):
            break

        if board_size > 3 and len(players) >= 2:
            more = input('Continuar(S/N)? ')
            if more.upper().__eq__("N"):
                break

    board = generate_board(board_size)
    return Game(players, board)
Beispiel #2
0
 def startNewGame(self):
     "starts a new game of X01. sets up rounds and initial score for players"
     Game.startNewGame(self)
     self.addRoundRow("", (self.styleWhiteFrame, self.styleWhiteLabel))
     for player in self.playerList:
         self.addScoreRow(player, (self.styleWhiteFrame, self.styleWhiteLabel))
     self.addRoundRow(self.currentRound)
Beispiel #3
0
 def __init__(self, gameFrame, playerList, startScore=301):
     '''
     Sets up the interface and variables for a game of 301
     '''
     Game.__init__(self, gameFrame, playerList)
     self.startScore = startScore
     self.startNewGame()
Beispiel #4
0
 def __init__(self, gameFrame, playerList, startScore=0):
     '''
     Constructor
     '''
     Game.__init__(self, gameFrame, playerList)
     self.startScore = startScore
     self.startNewGame()
Beispiel #5
0
    def reset_game(self):
        try:
            self.model = Game(int(self.size.get()), int(self.num_mines.get()))
        except ValueError:
            self.model = Game()

        self.view.reset_view(self.model, self.reveal_field)
Beispiel #6
0
def test_create_and_delete_game(wait_for_api, create_clean_db, client):
    # create our game
    game = Game('test')
    start = Waypoint(game.graph, 'start')
    w1 = Waypoint(game.graph, 'w1')
    w2 = Waypoint(game.graph, 'w2', items=['some item'])
    end = Waypoint(game.graph, 'end')
    start.add_destination(w1)
    task = Task(w2, 'test description', 'test text', 'answer')
    w1.add_task(task)
    w2.add_destination(end)
    game.set_start(start)
    # create user
    lg = client.post(
        f"{ROOT_URL}/register", json=default_account
    )
    assert lg.status_code == 201
    token = json.loads(lg.data)
    # convert it to an API object
    game_data = generate_api_game(game)
    lg = client.post(
        f"{ROOT_URL}/games", json=game_data, headers={'X-TOKEN': token}
    )
    assert lg.status_code == 201
    lg = client.get(
        f"{ROOT_URL}/games"
    )
    assert lg.status_code == 200
    assert game.title in [g['title'] for g in lg.data]
Beispiel #7
0
class Controller:
    def __init__(self):
        self.game = Game()
        self.dialog = Dialog()
        self.last_destination = None

    def start_game(self):
        self.dialog.show_intro()
        self._play()

    def _play(self):
        with self.game:
            while self.game.continues():
                possible_moves = self.game.get_possible_moves()
                selected_move = self._get_next_move(possible_moves)
                self.game.move(selected_move)
                self.last_destination = selected_move.dest

        self._print_board()
        self.dialog.show_ending(self.game.winner)

    def _get_next_move(self, possible_moves):
        # fixme: duplicated ids when king and piece available
        id_field_translator = IdFieldTranslator(possible_moves)
        piece = self._get_next_piece(id_field_translator)
        move = self._get_destination(piece, id_field_translator)

        if move is None:
            move = self._get_next_move(possible_moves)

        return move

    def _get_next_piece(self, translator):
        movable_pieces = translator.pieces_dict()

        if self._is_continuation(movable_pieces):
            return translator.id_to_piece('a')
        else:
            self._print_board(movable_pieces)
            piece_id = self.dialog.get_piece(movable_pieces.values())
            return translator.id_to_piece(piece_id)

    def _is_continuation(self, pieces):
        is_single = len(pieces) == 1
        same_piece = list(pieces.keys())[0] == self.last_destination
        return is_single and same_piece

    def _get_destination(self, piece, translator):
        reachable_fields = translator.moves_dict(piece)
        # todo: add selected piece to reachable_fields to highlight it properly
        self._print_board(reachable_fields)
        move_id = self.dialog.get_dest(reachable_fields.values())
        return translator.id_to_move(move_id, piece)

    def _print_board(self, fields_with_id=None):
        if fields_with_id is None:
            fields_with_id = {}

        print_board(self.game.get_board(), fields_with_id)
Beispiel #8
0
def test_simple_graph_generation():
    game = Game('test')
    start = Waypoint(game.graph, 'start')
    end = Waypoint(game.graph, 'end')
    start.add_destination(end)
    assert len(game.graph.nodes) == 2
    assert len(game.graph.edges) == 1
    assert not game.start_is_set()
Beispiel #9
0
    def train(self, rounds: int) -> None:
        for i in range(rounds):
            initial_state = self._choose_initial_state()
            # safe, because of acyclic Markov Process
            self._pi[initial_state] = np.random.choice(list(Action))

            game = Game(player_policy=self.policy)
            game_info = game.play_starting_in(initial_state)
            self._update_with(game_info)
Beispiel #10
0
    def __init__(self):
        self.root = tk.Tk()

        self.size = tk.StringVar()
        self.num_mines = tk.StringVar()
        self.size.set(6)
        self.num_mines.set(3)

        self.model = Game(int(self.size.get()), int(self.num_mines.get()))
        self.view = MainWindow(self.root, self.model, self.reveal_field, self.reset_game, self.size, self.num_mines)
Beispiel #11
0
def test_adding_task_adds_path():
    game = Game('test')
    start = Waypoint(game.graph, 'start')
    end = Waypoint(game.graph, 'end')
    task = Task(end, 'test description', 'test text', 'answer')
    start.add_task(task)
    game.set_start(start)
    assert len(game.graph.nodes) == 2
    assert len(game.graph.edges) == 1
    assert game.start_is_set()
Beispiel #12
0
    def __init__(self, view):
        self.__game = Game()
        self.__view = view

        self.__view.set_info("Next player: {}".format(self.__game.next_player))

        self.__view.connect('cell-clicked', self.on_cell_clicked)
        self.__view.connect('new-game', self.on_new_game)
        self.__view.connect('destroy', Gtk.main_quit)

        self.__view.show_all()
Beispiel #13
0
def run():

    from view.util import Settings
    from model.game import Game
    from config import defaults, __NAME__

    settings = Settings(__NAME__.lower(), defaults)
    game = Game(settings)
    game.new()
    for i in range(10):
        game.turn_done()
Beispiel #14
0
    def test_game_next_player(self):
        rules = Rules(mode='standard', opponent='human')

        p1 = Player('p1')
        p2 = Player('p2')

        g = Game(1, p1, p2, rules)

        expected = p2
        actual = g.next_player()
        self.assertEqual(expected, actual)
def build_game_with_2maps_winning_picks_team1_and_team3():
    game = Game(None, team1.id_team, team3.id_team, None, 2, 1, team1.id_team,
                3, "Mapa 1", "Mapa 2", "", "", "Mapa 3", team1.actual_rank,
                team3.actual_rank)
    game.team1 = team1
    game.team2 = team3
    map1 = Map(game.id_game, "Mapa 1", 9, 6, 7, 6, 0, 0, 16, 12)
    map2 = Map(game.id_game, "Mapa 2", 8, 7, 8, 4, 0, 0, 16, 11)

    game.maps = [map1, map2]

    return game
Beispiel #16
0
def new_game():
    print(request.form)
    host_name = 'Host'
    presentation_file = request.files['presentation_file']
    host = Player(host_name)
    game = Game(host)
    game.load_presentation(presentation_file)

    redis_client.set(f'stopwatch.{game.id}', pickle.dumps(epoch()))
    save_game(game)

    return jsonify(game_id=game.id, player_id=host.id)
    def test_pickling(self):
        game = Game(PlayerId.ONE, seed=2)
        self.assertEqual(Suit.DIAMONDS, game.game_state.trump)

        actions = [
            # Player TWO wins the first trick. Score: 0-6.
            PlayCardAction(PlayerId.TWO, Card(Suit.HEARTS, CardValue.JACK)),
            PlayCardAction(PlayerId.ONE, Card(Suit.CLUBS, CardValue.KING)),

            # Player TWO closes the talon.
            CloseTheTalonAction(PlayerId.TWO),

            # Player TWO wins the second trick. Score: 0-18.
            PlayCardAction(PlayerId.TWO, Card(Suit.DIAMONDS, CardValue.TEN)),
            PlayCardAction(PlayerId.ONE, Card(Suit.DIAMONDS, CardValue.JACK)),

            # Player TWO wins the third trick. Score: 0-31.
            PlayCardAction(PlayerId.TWO, Card(Suit.HEARTS, CardValue.TEN)),
            PlayCardAction(PlayerId.ONE, Card(Suit.SPADES, CardValue.QUEEN)),

            # Player ONE wins the forth trick. Score: 13-31.
            PlayCardAction(PlayerId.TWO, Card(Suit.CLUBS, CardValue.JACK)),
            PlayCardAction(PlayerId.ONE, Card(Suit.CLUBS, CardValue.ACE)),

            # Player TWO wins the fifth trick. Score: 13-52.
            PlayCardAction(PlayerId.ONE, Card(Suit.SPADES, CardValue.TEN)),
            PlayCardAction(PlayerId.TWO, Card(Suit.SPADES, CardValue.ACE)),

            # Player TWO wins the sixth trick. Score: 13-67.
            PlayCardAction(PlayerId.TWO, Card(Suit.HEARTS, CardValue.ACE)),
            PlayCardAction(PlayerId.ONE, Card(Suit.SPADES, CardValue.KING))
        ]
        for action in actions[:8]:
            game.play_action(action)
        self.assertFalse(game.game_state.is_game_over)
        self.assertEqual(PlayerPair(0, 31), game.game_state.trick_points)
        self.assertFalse(game.game_state.is_to_lead(PlayerId.ONE))
        self.assertFalse(game.game_state.is_to_lead(PlayerId.TWO))

        unpickled_game: Game = loads(dumps(game))
        self.assertEqual(unpickled_game.game_state, game.game_state)
        self.assertFalse(unpickled_game.game_state.is_game_over)
        self.assertFalse(unpickled_game.game_state.is_to_lead(PlayerId.ONE))

        for action in actions[8:]:
            unpickled_game.play_action(action)

        self.assertTrue(unpickled_game.game_state.is_game_over)
        self.assertEqual(PlayerPair(13, 67),
                         unpickled_game.game_state.trick_points)
        self.assertEqual(PlayerPair(0, 3),
                         unpickled_game.game_state.game_points)
def build_game_with_3maps_winning_picks():
    game = Game(None, team1.id_team, team2.id_team, None, 2, 1, team1.id_team,
                3, "Mapa 1", "Mapa 2", "", "", "Mapa 3", team1.actual_rank,
                team2.actual_rank)
    game.team1 = team1
    game.team2 = team2
    map1 = Map(game.id_game, "Mapa 1", 9, 6, 6, 2, 0, 0, 16, 8)
    map2 = Map(game.id_game, "Mapa 2", 7, 8, 6, 8, 0, 0, 13, 16)
    map3 = Map(game.id_game, "Mapa 3", 7, 8, 6, 8, 0, 0, 13, 16)

    game.maps = [map1, map2, map3]

    return game
def check_stats_of_policy(
    player_policy: Policy,
    dealer_policy: Policy = DealerPolicy()) -> GameStats:
    wins, losses = 0, 0
    game = Game(player_policy, dealer_policy)

    for run in range(GAME_RUNS):
        winner = game.play().winner
        if winner == Winner.PLAYER: wins += 1
        elif winner == Winner.DEALER: losses += 1

    return GameStats(wins=wins / GAME_RUNS,
                     losses=losses / GAME_RUNS,
                     draws=(GAME_RUNS - wins - losses) / GAME_RUNS)
    def create(self):
        gMap            = Map.convertToWorldMap(self.request.POST['game_map'])
        game            = Game(gid = uuid.uuid4().hex)
        game.name       = self.getPOSTorRandom('game_name', Game)
        game.gmap       = gMap.toString()
        game.maxPlayers = gMap.countHabitable()
        game.private    = False if self.request.POST['game_type'] == 'public' else True
        game.owner      = self.join_game(game, self.getPOSTorRandom('game_user', User))
        game.put()

        self.json    = game.toDict()
    def get_game(self, gid):
        query = Game.query(Game.gid == gid)

        # Look for the game
        if query.count() != 1:
            self.stderr('Unknown Game')
        else:
            game = query.fetch(1)[0]

            self.json['status'] = 'running' if game.running else 'waiting'
            self.json['full']   = (len(game.members) >= game.maxPlayers)
            self.json['users']  = game.members

            if game.running and self.checkLogin(False):
                self.json['game']           = { }
                self.json['game']['data']   = {
                    'status' : 'running' if game.running else 'waiting',
                    'token'  : game.gid,
                    'secret' : self.user.secret
                }
                self.json['player']         = self.user.toDict()
                self.json['game']['maps']   = {
                    "world" : Map(game.gmap).toDict(),
                    "city"  : Map(self.user.homeMap).toDict()
                }
                self.json['game']['maps']['world']['players'] = { }

                for user in User.query(User.gid == game.gid).fetch():
                    self.json['game']['maps']['world']['players'][user.uid] = {
                        "id"    : user.uid,
                        "name"  : user.name,
                        "level" : user.level
                    }
    def join(self, gid):
        query = Game.query(Game.gid == gid)
        name  = self.getPOSTorRandom('username', User)

        # Look for the game
        if query.count() != 1:
            self.stderr('Unknown Game')
        else:
            game = query.fetch(1)[0]

            if game.running:
                self.stderr('Game has started')
            elif len(game.members) >= game.maxPlayers:
                self.stderr('The maximum number of players has been reached')
            elif User.query(User.name==name, User.gid==gid).count() != 0:
                self.stderr('Username already exists')
            else:
                sid = self.join_game(game, name)
                game.put()

                self.json['status']  = 'joined'

                # Not sure why either of these are needed
                self.json['token']   = game.gid
                self.json['session'] = sid
Beispiel #23
0
def find_game(title_in):  #search for game by title
    try:
        searched_game = Game.get_or_none(Game.title == title_in)
        return searched_game, None
    except DatabaseError as e:
        logging.error(e)
        return None, e
Beispiel #24
0
def generate_games_summary_table(target_file):
    match_quantity = model.match.get_match_quantity()
    with open(target_file, 'w', encoding='ANSI') as f:
        add_cell(f, "Circuit")
        add_cell(f, "Numéro")
        add_cell(f, "Nom")
        add_cell(f, "Responsable")
        for i in range(1, match_quantity + 1):
            add_cell(f, i)
        f.write("\n")
        add_cell(f)
        add_cell(f)
        add_cell(f)
        add_cell(f)
        schedules = service.get_all_schedules()
        for schedule in schedules:
            add_cell(f, schedule)
        f.write("\n")
        for game in Game.objects().order_by('number'):
            add_cell(f, game.circuit)
            add_cell(f, game.number)
            add_cell(f, game.name)
            add_cell(f, game.leader)
            for match in game.matches:
                add_cell(f, "{} - {}".format(*match.players_code))
            f.write("\n")
Beispiel #25
0
def test_player_at_game_change(mocker):
    ps = Playerset()
    gs = Gameset(ps)

    p = Player(**{"id_": 1, "login": "******"})
    ps[p.id] = p
    p = Player(**{"id_": 2, "login": "******"})
    ps[p.id] = p
    p = Player(**{"id_": 3, "login": "******"})
    ps[p.id] = p

    data = copy.deepcopy(GAME_DICT)
    g1 = Game(playerset=ps, **data)

    gUpd = mocker.Mock()
    ps[1].newCurrentGame.connect(gUpd)

    gs[1] = g1
    gUpd.assert_called_with(ps[1], g1, None)
    gUpd.reset_mock()

    data["state"] = GameState.PLAYING
    gs[1].update(**data)

    assert not gUpd.called

    data["state"] = GameState.CLOSED
    gs[1].update(**data)
    gUpd.assert_called_with(ps[1], None, g1)
Beispiel #26
0
def get_all_schedules():
    schedules = list()
    highest_time_game_number = Match.objects(
        time=model.match.get_match_quantity()).first().game_number
    for match in Game.objects(number=highest_time_game_number).get().matches:
        schedules.append(match.schedule)
    return schedules
Beispiel #27
0
def test_player_at_another_game(mocker):
    ps, gs = setup()

    data = copy.deepcopy(GAME_DICT)

    # Game starts
    data["state"] = GameState.PLAYING
    gs[1].update(**data)

    data["state"] = GameState.OPEN
    data["uid"] = 2
    data["teams"] = {1: ["Guy"]}
    g2 = Game(playerset=ps, **data)

    gUpd = mocker.Mock()
    ps[1].newCurrentGame.connect(gUpd)

    gs[2] = g2
    gUpd.assert_called_with(ps[1], g2, gs[1])
    gUpd.reset_mock()

    # Test if closing the first game changes player state
    data = copy.deepcopy(GAME_DICT)
    data["state"] = GameState.CLOSED
    gs[1].update(**data)
    assert not gUpd.called
Beispiel #28
0
def generate_game_roadmaps(target_file):
    files_to_merge = list()
    with tempfile.TemporaryDirectory() as tmpdir:
        for game in Game.objects():
            tpl = DocxTemplate(GAME_ROADMAP_TEMPLATE)

            qr = pyqrcode.create(game.hash, error=QR_ERROR, version=QR_VERSION)
            qr_file = os.path.join(tmpdir, "game.png")
            qr.png(qr_file,
                   scale=QR_SCALE,
                   module_color=QR_COLOR,
                   quiet_zone=QUIET_ZONE)

            context = dict(gameName=game.name,
                           gId=str(game.number),
                           circuit=game.circuit,
                           leader=game.leader,
                           qrCode=InlineImage(tpl, qr_file, width=Mm(QR_SIZE)))

            for i, match in enumerate(game.matches, 1):
                context["players{}".format(i)] = "{} - {}".format(
                    match.players_code[0], match.players_code[1])

            tpl.render(context)
            game_file = os.path.join(tmpdir, "game{}.docx".format(game.number))
            tpl.save(game_file)
            files_to_merge.append(game_file)

        _combine_docx(target_file, files_to_merge)
Beispiel #29
0
    def _build_hosted_game(self, main_mod, mapname=None):
        if mapname is None:
            mapname = util.settings.value("fa.games/gamemap", "scmp_007")

        if self._me.player is not None:
            host = self._me.player.login
        else:
            host = "Unknown"

        title = util.settings.value("fa.games/gamename", host + "'s game")
        friends_only = util.settings.value("friends_only", False, type=bool)

        return Game(
            playerset=self._playerset,
            uid=0,  # Mock
            state=GameState.OPEN,  # Mock
            launched_at=None,
            num_players=1,
            max_players=12,
            title=title,
            host=host,
            mapname=mapname,
            map_file_path="",  # Mock
            teams={1: [host]},
            featured_mod=main_mod,
            featured_mod_versions={},
            sim_mods={},
            password_protected=False,  # Filled in later
            visibility=(GameVisibility.FRIENDS
                        if friends_only else GameVisibility.PUBLIC))
Beispiel #30
0
    def init_game(self, mode):
        game = Game()
        controller = Controller(game)

        ai = AI(game)
        first_player = Player(PieceColor.WHITE, controller,
                              ai if mode == GameMode.AI_VS_HUMAN else None)
        second_player = Player(PieceColor.BLACK, controller,
                               ai if mode == GameMode.HUMAN_VS_AI else None)

        players = [first_player, second_player]

        game_board = GameBoardWidget(game)
        for player in players:
            if player.type == PlayerType.HUMAN:
                game_board.move_receive_from_ui.append(
                    player.move_receive_from_ui_handler)

        if first_player.type == PlayerType.AI:
            first_player.move_complete_event(PieceColor.BLACK)

        Clock.schedule_interval(lambda delta_time: game_board.update(), 0.03)

        self.clear_widgets()

        game_widget = GameWidget(game)
        size = (game_board.width, game_board.height + 50)
        game_widget.size = size
        Window.size = size
        game_widget.set_game_board(game_board)
        self.add_widget(game_widget)
Beispiel #31
0
def generate_team_roadmaps(target_file):
    files_to_merge = list()
    with tempfile.TemporaryDirectory() as tmpdir:
        for team in Team.objects():
            tpl = DocxTemplate(TEAM_ROADMAP_TEMPLATE)

            qr = pyqrcode.create(team.hash, error=QR_ERROR, version=QR_VERSION)
            qr_file = os.path.join(tmpdir, "team.png")
            qr.png(qr_file,
                   scale=QR_SCALE,
                   module_color=QR_COLOR,
                   quiet_zone=QUIET_ZONE)

            context = dict(section=team.section,
                           teamCode=team.code,
                           qrCode=InlineImage(tpl, qr_file, width=Mm(QR_SIZE)))
            for i, match in enumerate(team.matches, 1):
                game_number = match.game_number
                context["game{}".format(i)] = Game.objects(
                    number=game_number).get().name
                context["gId{}".format(i)] = str(game_number)

            tpl.render(context)
            team_file = os.path.join(tmpdir, "team{}.docx".format(team.code))
            tpl.save(team_file)
            files_to_merge.append(team_file)

        _combine_docx(target_file, files_to_merge)
Beispiel #32
0
 def __init__(self,
              black_hole_input=None,
              omikron_color_input=None,
              include_ui=False):
     black_hole_coordinates = black_hole_input or input()
     color_input = omikron_color_input or input()
     omikron_bot_color = Player(self.COLOR_NAMING_MAP[color_input])
     korotenko_bot_color = Player(self.OPPOSITE_PLAYER[omikron_bot_color])
     self.game = Game(
         self.INPUT_MAPPER.get_coordinates(black_hole_coordinates))
     self.players = {
         omikron_bot_color: self.OMIKRON_BOT(omikron_bot_color),
         korotenko_bot_color: self.KOROTENKO_BOT(korotenko_bot_color),
     }
     self.winner = None
     self.include_ui = include_ui
Beispiel #33
0
def find_game_by_igdb_id(igdb_id):
    try:
        searched_game = Game.get_or_none(Game.igdb_id == igdb_id)
        return searched_game, None
    except DatabaseError as e:
        logging.error(e)
        return None, e
Beispiel #34
0
def test_game_at_missing_player(mocker):
    ps = Playerset()
    gs = Gameset(ps)

    p = Player(**{"id_": 1, "login": "******"})
    ps[p.id] = p
    p = Player(**{"id_": 2, "login": "******"})
    ps[p.id] = p

    data = copy.deepcopy(GAME_DICT)
    g1 = Game(playerset=ps, **data)
    pAdd = mocker.Mock()
    g1.connectedPlayerAdded.connect(pAdd)

    gs[1] = g1
    assert len(g1.players) == 3
    gps = [g1.to_player(n) for n in g1.players if g1.is_connected(n)]
    assert len(gps) == 2
    assert ps[1] in gps
    assert ps[2] in gps

    assert not pAdd.called
    p = Player(**{"id_": 3, "login": "******"})
    ps[p.id] = p
    pAdd.assert_called_with(g1, ps[3])

    gps = [g1.to_player(n) for n in g1.players if g1.is_connected(n)]
    assert len(gps) == 3
    assert ps[3] in gps
    assert g1.is_ingame(ps[3].login)
    assert ps[3].currentGame is g1
Beispiel #35
0
def test_npc_interaction():
    """
      start
        |
        w1 <- dialog becomes available
        |
        end
    """
    game = Game('test')
    start = Waypoint(game.graph, 'start')
    w1 = Waypoint(game.graph, 'w1')
    end = Waypoint(game.graph, 'end')
    start.add_destination(w1)
    w1.add_destination(end)
    game.set_start(start)
    npc_dialog = Dialog()
    ds = Mail(npc_dialog.graph, 'test subject', 'test body')
    with pytest.raises(PlayerStateException):
        NonPlayableCharacter('test', 'npc', npc_dialog)
    npc_dialog.set_start(ds)
    npc_dialog.start.waypoints.append(w1)
    game.add_non_playable_character(NonPlayableCharacter('test', 'npc', npc_dialog))
    instance = game.create_new_game()
    instance.add_player(Player('test', 'player'), 'testy', 'mctestpants')
    assert len(instance.npc_states) == 1
    assert ds not in [k for k, _ in instance.player_states[0].inventory.values()]
    interactions = instance.player_states[0].move_to(w1)
    assert len(interactions.keys()) == 1 and len(interactions.values()) == 1
Beispiel #36
0
def test_identify_player_path():
    """
    start
      |
      w1
      |  <- task answer required before transition becomes available
      w2
      |
      end
    """
    game = Game('test')
    start = Waypoint(game.graph, 'start')
    w1 = Waypoint(game.graph, 'w1')
    w2 = Waypoint(game.graph, 'w2', items=['some item'])
    end = Waypoint(game.graph, 'end')
    start.add_destination(w1)
    task = Task(w2, 'test description', 'test text', 'answer')
    w1.add_task(task)
    w2.add_destination(end)
    game.set_start(start)
    instance = game.create_new_game()
    player = Player('test', 'player')
    instance.add_player(player, 'testy', 'mctestpants')
    assert len(instance.player_states[0].path) == 1
    assert instance.player_states[0].path[0][1] == start
    assert w1 in instance.player_states[0].available_moves()
    assert w2 in instance.player_states[0].available_path()
    # not allowed to skip to end
    with pytest.raises(PlayerIllegalMoveException):
        instance.player_states[0].move_to(end)
    instance.player_states[0].move_to(w1)
    # no backsies
    with pytest.raises(PlayerIllegalMoveException):
        instance.player_states[0].move_to(start)
    # w2 is blocked from w1
    with pytest.raises(PlayerIllegalMoveException):
        instance.player_states[0].move_to(w2)
    answer = 'answer'
    assert len(instance.player_states[0].inventory) == 0
    instance.player_states[0].move_to(w2, answer)
    assert not instance.player_states[0].is_finished()
    assert len(instance.player_states[0].inventory) == 1
    instance.player_states[0].move_to(end)
    assert instance.player_states[0].current_position() == end
    assert instance.player_states[0].is_finished()
Beispiel #37
0
    def __init__(self):
        tkinter.Tk.__init__(self)
        self.geometry(f'{WIDTH}x{HEIGHT}')
        self.title("Arkanoid")
        self.resizable(width=False, height=False)
        self.canvas = tkinter.Canvas(self, width=WIDTH, height=HEIGHT)
        self.canvas.pack()

        self.canvas.bind('<Motion>', self.__on_mouse_event)
        self.canvas.bind('<Button-1>', self.__on_mouse_click)

        self.images = [
            get_image(r'.\images\background.png'),
            get_image(r'.\images\paddle_blue.png'),
            get_image(r'.\images\brick_yellow.png'),
            get_image(r'.\images\brick_blue.png'),
            get_image(r'.\images\brick_purple.png'),
            get_image(r'.\images\brick_grey.png'),
            get_image(r'.\images\brick_red.png'),
            get_image(r'.\images\ball.png')
        ]

        self.image_bg = ImageTk.PhotoImage(self.images[0])  # background image
        self.canvas.create_image(0, 0, image=self.image_bg, anchor='nw')

        self.image_paddle = ImageTk.PhotoImage(self.images[1])
        self.image_bricks = [
            ImageTk.PhotoImage(self.images[2]),
            ImageTk.PhotoImage(self.images[3]),
            ImageTk.PhotoImage(self.images[4]),
            ImageTk.PhotoImage(self.images[5]),
            ImageTk.PhotoImage(self.images[6])
        ]
        self.image_ball = ImageTk.PhotoImage(self.images[7])

        # self.music = [get_wave_object(r'.\audio\music\Arkanoid_SoundTrack_1.wav'),  # background music
        #               get_wave_object(r'.\audio\music\Arkanoid_SoundTrack_2.wav'),
        #               get_wave_object(r'.\audio\music\Arkanoid_SoundTrack_3.wav')]

        # self.i = 0
        # self.playing_music = self.music[self.i].play()

        self.game = Game()
        self.game.start_game()
        self.__game_field()
Beispiel #38
0
 def do_controller_specific_work(self):
     if len(self.invited_user_ids) < 4:
         raise API_Exception("400 Bad Request", "The minimum number of players is 5. Please invite more people.")
     db_session = DB_Session_Factory.get_db_session()
     game = Game(self.user.user_id)
     db_session.add(game)
     for invited_user_id in self.invited_user_ids:
         user = db_session.query(User).get(invited_user_id)
         if user is None:
             user = User(invited_user_id, None, None, None)
             db_session.add(user)
             db_session.flush()
         player = Player(invited_user_id, game.game_id, 'INVITED')
         db_session.add(player)
     inviting_player = Player(self.user.user_id, game.game_id, 'ALIVE')
     db_session.add(inviting_player)
     db_session.commit()
     return HTTP_Response('200 OK', {'game' : game.for_api(inviting_player)})
    def get(self):
        self.json['games'] = [ ]
        query              = Game.query(
            Game.private == False,
            Game.running == False
        )

        for game in query.fetch():
            # Only show games which aren't full
            if len(game.members) < game.maxPlayers:
                self.json['games'].append(game.toDict())
Beispiel #40
0
    def remote_createGame(self, playerOneSymbol, playerOneType,
                          playerTwoSymbol, playerTwoType,
                          searchDepth=0,
                          cbk=None):
        """Creates a new Game object.

        Args:
            playerOneSymbol (int)
            playerOneType (int)
            playerTwoSymbol (int)
            playerTwoType (int)
            searchDepth (Optional[int])

        Returns:
            UUID: The UUID of the newly created game.

        Raises:
            ValueError

        """
        # creates the game
        playerOne = Player.playerBuilder().symbol(playerOneSymbol). \
            type(playerOneType).build()

        playerTwo = Player.playerBuilder().symbol(playerTwoSymbol). \
            type(playerTwoType).build()

        if playerOne.isAi:
            playerOne.depth = searchDepth
        elif playerTwo.isAi:
            playerTwo.depth = searchDepth
        else:
            raise ValueError('No AI player')

        game = Game.create(playerOne, playerTwo)

        # stores the game in our map
        self._games[game.uuid] = game

        # returns the GUID back to the caller
        self.log.info('A new game ({uuid}) was created', uuid=game.uuid)

        # starts the game
        try:
            game.start()
        except Exception, e:
            self.log.failure('Failed to start the game {0}. Reason: {1}'.
                             format(game.uuid, str(e)))
    def start(self, gid):

        # You must be the owner of a game to start it, so we should
        # check if they are loged on
        if not self.checkLogin(): return

        query = Game.query(Game.gid == gid)

        if query.count() != 1:
            self.stderr('Unknown Game')
        else:
            game = query.fetch(1)[0]

            if game.owner != self.user.uid:
                self.stderr('You are not authorised to start this game')
            else:
                game.running = True
                savedCMap    = None

                # Pick places for each of the players and set their
                # lastUpdated value to the start of the game so they can
                # load resources
                mapObj = Map(game.gmap)
                for user in User.query(User.gid == game.gid).fetch():
                    cMap               = Map.generateCityMap()
                    user.positionOnMap = mapObj.pickRandomTile(user)
                    user.lastUpdated   = datetime.datetime.now()
                    user.homeMap       = cMap.toString()
                    user.put()
                    if user.uid == self.user.uid:
                        savedCMap = cMap

                game.gmap = mapObj.toString()
                game.put()

                self.json['game'] = { }
                self.json['game']['data'] = {
                    "status" : 'started',
                    "token"  : game.gid
                }
                self.json['player'] = self.user.toDict()
                self.json['game']['maps']   = {
                    "world" : mapObj.toDict(),
                    "city"  : cMap.toDict()
                }
Beispiel #42
0
 def __init__(self, config):
     # Build a Game object based on config
     self.game = Game(config)
Beispiel #43
0
 def load_game(self, name):
     self.__game = Game()
     self.set_speed(configuration.settings["SPEED"])
     self.__game.load(name)
     self.toggle_game()
Beispiel #44
0
class GameControl:

    __gui = None

    def __init__(self, window):
        window.geometry(str(configuration.settings["WIDTH"])+"x"+str(configuration.settings["HEIGHT"]))
        self.__game = None
        self.__menu = MenuGui(self, window)
        self.__menu.show()
        self.__sleeptime = configuration.Speed.normal
        self.__window = window
        self.disable_menu()
        self.show_main_menu()

    def show_main_menu(self):
        if self.__gui is not None:
            self.__gui.remove()
        if self.__game is not None:
            self.__game.stop()
        self.__gui = MainGui(self, self.__window)
        self.__gui.show()

    def show_save_menu(self):
        if self.__gui is not None:
            self.__gui.remove()
        self.__gui = SaveGui(self, self.__window)
        self.__gui.show()

    def show_game(self):
        self.__init_all_except_Game()
        self.__gui.show()

    def create_new(self, fieldsize_x, fieldsize_y):
        self.__game = Game(fieldsize_x=fieldsize_x, fieldsize_y=fieldsize_y)
        self.__init_all_except_Game()

    def load_previous(self, memory):
        self.__game = Game(memory)
        self.__init_all_except_Game()

    def load_named(self, name):
        self.load_game(name)
        self.__init_all_except_Game()

    def set_speed(self, speed):
        if self.__game is not None:
            if type(speed) is configuration.Speed:
                self.__game.set_sleeptime(speed.value)
            elif type(speed) is float:
                self.__game.set_sleeptime(speed)
            else:
                self.__game.set_sleeptime(float(speed))


    def toggle_tile(self, x, y):
        self.__game.toggle_tile(x, y)

    def toggle_game(self):
        self.__game.toggle()

    def stop_game(self):
        if self.__game is not None:
            self.__game.stop()

    def start_game(self):
        if self.__game is not None:
            self.set_speed(configuration.settings["SPEED"])
            self.__game.start()
        if self.__gui is not None:
            self.__gui.show()

    def end_game(self):
        if self.__game is not None:
            self.__game.stop()
            self.__game.save()
        self.__gui.remove()
        self.__game = None
        self.__gui = None

    def save_game(self, name):
        if self.__game is not None:
            self.__game.save(name)

    def load_game(self, name):
        self.__game = Game()
        self.set_speed(configuration.settings["SPEED"])
        self.__game.load(name)
        self.toggle_game()

    def enable_menu(self):
        self.__menu.enable()

    def disable_menu(self):
        self.__menu.disable()

    def quit(self):
        # stop running threads, flush everything remaining
        if self.__game is not None:
            self.end_game()
        sys.stdout.flush()
        # exit the program
        if self.__window is not None:
            self.__window.quit()
        else:
            exit()

    def restart(self):
        # stop running threads, flush everything remaining
        if self.__game is not None:
            self.end_game()
        # restart
        os.execl(sys.executable, sys.executable, * sys.argv)

    def notify(self, field):
        if self.__gui is not None and field is not None:
            try:
                self.__gui.draw_field(field)
            except AttributeError:
                print("back to main menu")

    def __init_all_except_Game(self):
        self.__gui = GameGui(self, self.__window)
        self.__game.remove_observer(self)
        self.__game.add_observer(self)
Beispiel #45
0
 def load_previous(self, memory):
     self.__game = Game(memory)
     self.__init_all_except_Game()
Beispiel #46
0
 def create_new(self, fieldsize_x, fieldsize_y):
     self.__game = Game(fieldsize_x=fieldsize_x, fieldsize_y=fieldsize_y)
     self.__init_all_except_Game()
Beispiel #47
0
        event_parser = EventsParser(game.id)
        event_collection = event_parser.parse(get_event_data(game))
        collection.join(event_collection)
    except ParseError:
        print "Unable to parse events for %s" % (game.to_json())


if __name__ == '__main__':
    global game_set
    game_set = set(session.query(Game).all())
    now = datetime.datetime.now()
    day = datetime.timedelta(days=1)
    collection = DbCollection()
    db_batch = 0
    while start_date < now:
        game = Game(start_date.year, start_date.month, start_date.day, 1)
        game.year = start_date.year
        game.month = start_date.month
        game.day = start_date.day
        while has_game(game):
            if game in game_set:
                game = Game(start_date.year, start_date.month, start_date.day, game.game_num + 1)
                continue
            session.add(game)
            session.commit()
            db_batch += 1
            parse_boxscore(game, collection)
            parse_events(game, collection)
            game = Game(start_date.year, start_date.month, start_date.day, game.game_num + 1)
            if db_batch % 1000 == 0:
                collection.commit()
Beispiel #48
0
 def victory(self, player):
     "handles post-game, player won the game"
     Game.victory(self, player)
     self.startNewGame()
Beispiel #49
0
class Cli(object):
    def __init__(self, config):
        # Build a Game object based on config
        self.game = Game(config)

    def Run(self):
        self.select_gamemap()
        while not self.game.game_over():
            print("It's Player {}'s turn.".format(self.game.get_current_player()))
            raw = raw_input("$ ")
            cmd = string.split(raw, " ")

            if cmd[0] == "exit":
                self.game.end_game()
            elif cmd[0] == "help":
                print("exit - End program")
                print("help - Print this help message")
                print("list_units - List all game units and their location")
                print("list_buildings - List all game buildings on the map")
                print("attack_unit <u1> <u2> - Attack unit u1 with unit u2")
                print("move_unit <u1> <x>.<y> - Move unit u1 to position (x, y)")
                print("done - End player's turn")
            elif cmd[0] == "list_buildings":
                for b in self.game.ListBuildings():
                    print(b)
            elif cmd[0] == "list_units":
                self.game.ListUnits()
            elif cmd[0] == "move_unit":
                args = self.move_unit(cmd)
                self.game.MoveUnit(args[0], args[1])
            elif cmd[0] == "attack_unit":
                args = self.attack_unit(cmd)
                if not self.game.my_unit(args[1]):
                    print("{} is not your unit to attack with.".format(args[1]))
                elif self.game.my_unit(args[0]):
                    print("{} is your own unit. You cannot attack it.".format(args[0]))
                else:
                    results = self.game.AttackUnit(args[0], args[1])
                    if results[0] <= 0:
                        print("Unit {} was destroyed.".format(args[0]))
                    else:
                        print("Unit {}: {}HP, Unit {}: {}HP".format(args[0],results[0],args[1],results[1]))
            elif cmd[0] == "done":
                print("Player{}'s turn is over.".format(self.game.get_current_player()))
                self.game.next_player()
            else:
                print("Bad command")
        # Game loop has been broken by exit command
        print("Game Over")

    def attack_unit(self, cmd):
        d_unit = int(cmd[1])
        a_unit = int(cmd[2])
        return (d_unit, a_unit)

    def move_unit(self, cmd):
        uid = int(cmd[1])
        pos = string.split(cmd[2], ".")
        pos[0] = int(pos[0])
        pos[1] = int(pos[1])
        return (uid, pos)

    def select_gamemap(self):
        gamemaps = self.game.get_gamemaps()
        
        print("Select a Map...")
        for _map in gamemaps:
            print(_map)

        while True:
            raw = raw_input("$ ")
            cmd = string.split(raw, " ")
            if self.game.load_gamemap(cmd[0]):
                break
Beispiel #50
0
from model.attr_reader import AttrReaderError
from model.game import Game
from controller.controller import Controller
from config import defaults, map_defaults, __NAME__

def parse_cmdline():
    
    d = {
        'quit after startup': False,
    }
    
    options, args = getopt(sys.argv[1:], 'q')
    for option, value in options:
        if option == '-q':
            d['quit after startup'] = True
    return d

options = parse_cmdline()
settings = Settings(__NAME__.lower(), defaults)
map_settings = Settings(__NAME__.lower() + '_map', map_defaults)
game = Game(Controller(), settings)
view = game.view()

app = QtGui.QApplication(sys.argv)
main = MainWindow(__NAME__, view, settings, map_settings, options)
main.setGeometry(300, 0, 1000, 600)
main.show()
app.exec_()