예제 #1
0
 def __init__(self, color):
     self.drone = Drone('/' + color)
     self.color = color
     drone = self.drone
     self.modes = {
         "idle": Mode(drone),
         "follow": FollowGesture(drone),
         "land": TakeoffLand(drone),
         "takeoff": TakeoffLand(drone, takeoff=True),
         "north": Move(drone, 0),
         "east": Move(drone, 3 * math.pi / 2),
         "south": Move(drone, math.pi),
         "west": Move(drone, math.pi / 2),
         "stop": Move(drone, 0),
         "forward": Move(drone, 0, relative=True),
         "duck": Move(drone, 0, -1),
         "jump": Move(drone, 0, 1),
         "analyze": Photo(drone)
     }
     self.look_modes = {
         "look": Turn(drone),
         "right": Turn(drone, -1),
         "left": Turn(drone, 1)
     }
     self.look_direction = 0
     self.current_mode_pub = rospy.Publisher("/" + color + "_current_mode",
                                             String,
                                             queue_size=10)
     self.look_mode_pub = rospy.Publisher("/" + color + "_look_mode",
                                          String,
                                          queue_size=10)
     self.current_mode = self.modes["idle"]
     self.look_mode = self.modes["idle"]
     print('Drone ' + color + ' initialized')
예제 #2
0
 def _turn1(self):
     """ get the Turn object for the first turn
     Returns
     -------
     Turn
     """
     return Turn(self.params, self.turn1_ang)
예제 #3
0
    def __init__(
            self,
            nplayers=2,
            onmove=0,
            systems=None,
            stash=None,
            alive=None,  # list of player statuses, None for not yet created
    ):
        self.nplayers = nplayers
        self.onmove = onmove

        if systems is None:
            systems = []
            alive = [None] * nplayers
        self.systems = systems

        if stash is None:
            stash = Stash(nplayers + 1)
            for sys in systems:
                for m in sys.markers:
                    stash.request(m)
                for s in sys.ships:
                    stash.request(s.piece)
        self.stash = stash

        if alive is None:
            # This assumes that players with no home have been eliminated
            alive = [False] * nplayers
            for sys in systems:
                if not sys.home is None:
                    alive[sys.home] = True

        self.alive = alive
        # This turn will be built one event as a time
        self.curTurn = Turn(self)
예제 #4
0
 def __is_stalemate(self):
     stale = []
     for i in range(0,8):
         for j in range(0,8):
             if isinstance(self.board[i][j], Piece) and self.board[i][j].colour == self.current_player:
                 for sq in self.board[i][j].available_moves(self.board, i, j):
                     stale.append(Turn(self.game.ruleset, self.board, self.game.log, self.game.player_1, self.game.player_2).ruleset.check_if_move_into_check(self.board, i, j, sq[0], sq[1]) == 'invalid move')
     return all(stale)
예제 #5
0
    def run(self):
        # Preflop
        self.globalPot += Turn(self.players, self.board, self.smallBlind,
                               self.bigBlind).run()
        self.emptyPlayersPots()
        self.dealBoardCard(3)
        # Flop
        self.globalPot += Turn(self.players, self.board, self.smallBlind,
                               self.bigBlind).run()
        self.emptyPlayersPots()
        self.dealBoardCard(1)

        #Turn
        self.globalPot += Turn(self.players, self.board, self.smallBlind,
                               self.bigBlind).run()
        self.emptyPlayersPots()
        self.dealBoardCard(1)

        #River
        self.globalPot += Turn(self.players, self.board, self.smallBlind,
                               self.bigBlind).run()
        self.emptyPlayersPots()
예제 #6
0
파일: game.py 프로젝트: matteomartelli/tabu
    def newTurn(self, timeout):
        '''
        Create turn and select not last playing team.
        return back the turn object pointer.
        '''
        for t in self.teams:
            if t.wasLastPlaying() == False:
                break

        if t.wasLastPlaying():
            raise Exception('Error in teams switching')
        #TODO: start team play

        turn = Turn(self, t, timeout)
        self.currentTurn = turn
        return self.currentTurn
예제 #7
0
파일: game.py 프로젝트: nehoraigold/hangman
 def play(self):
     explain_rules()
     answer_guessed = False
     while not self.did_win() and not self.strikes.limit_reached():
         utils.clear_screen()
         utils.print_header("Turn {}".format(str(self.turn_number)))
         turn = Turn(self.answer, self.guessed_letters, self.strikes)
         if self.answer.equals(turn.guess):
             answer_guessed = True
             break
         self.guessed_letters.append(turn.guess)
         if turn.guess not in self.answer.lower():
             self.strikes.add(turn.guess)
         self.turn_number += 1
     self.end_game(answer_guessed)
     return self.play_again()
예제 #8
0
    def next_turn(self):
        print("Turn: {}. Active Player: {}".format(
            self.turn_count, str(self._active_player.color)))
        current_turn = Turn(self._active_player, self.board)
        # DOMOVE:
        self.board.move_piece(current_turn)
        self.turn_list.append(current_turn)

        # Switch player
        if not current_turn.extra_turn:
            if self._active_player is self.player1:
                self._active_player = self.player2
            else:
                self._active_player = self.player1
        # And increment the turn_count
        self.turn_count += 1
예제 #9
0
    def __init__(self,
                 name,
                 height,
                 width,
                 max_number_players,
                 end_type=False,
                 length_to_win=3):
        self.name = name
        self.width = width
        self.height = height
        self.grid = [[0 for i in range(self.width)]
                     for j in range(self.height)]
        self.max_number_players = max_number_players
        self.length_to_win = length_to_win

        # Instantiate a dummy turn object
        self.turn = Turn()
예제 #10
0
    def play(self):
        last_action = None
        self.end_seat = self.filtered_seats[-1]
        self.align_seat_deques()

        while True:
            seat = self.filtered_seats[0]

            turn = Turn(
                self.seats,
                self.filtered_seats,
                self.cards,
                self.current_bet,
                last_action,
            )

            action = turn.play()

            if action:
                last_action = action
                self.resolve_action(seat, action)

            if len(self.filtered_seats) == 1:
                self.LOGGER.debug("Player {} wins".format(
                    self.filtered_seats[0].index))
                self.move_all_bets_to_pots()
                return list(self.filtered_seats)

            if seat is self.end_seat:
                # bets have been called
                self.move_all_bets_to_pots()
                return [
                    seat for seat in self.remaining_seats
                    if seat in self.filtered_seats
                ]

            self.filtered_seats.rotate(-1)
            self.align_seat_deques()
예제 #11
0
def main():
    players = {}
    numberOfPlayers = 0
    while numberOfPlayers < 1 or numberOfPlayers > 5:
        try:
            numberOfPlayers = int(input("How many players (1-5)? "))
        except ValueError:
            print("Pick a number between 1-5.")

    i = 1
    while i <= numberOfPlayers:
        players[i] = Player(i)
        i += 1

    # Run a turn
    n = 1
    while True:
        newPlayers = playerRefresh(players, n)
        if newPlayers:
            Turn(newPlayers)
            n += 1
        else:
            break
예제 #12
0
def move(direction, seconds):
    """generic move method"""
    if direction in ['forward', 'backward']:
        exec_move = Move()
        if direction == 'forward':
            exec_move.forward(seconds)
        else:
            exec_move.backward(seconds)
        result = 'done move'
    elif direction in ['left', 'right']:
        exec_move = Turn()
        if direction == 'left':
            exec_move.left(seconds)
        else:
            exec_move.right(seconds)
        result = 'done turn'
    else:
        result = '{0} is no valid direction, choose between forward, backward, left, right.'.format(
            direction)
    return jsonify({
        'result': result,
        'direction': direction,
        'seconds': seconds
    })
예제 #13
0
class GameService(Service):
    __model__ = Game
    __schema__ = GameSchema()
    __schema_many__ = GameSchema(many=True)
    turn = Turn()

    def get_open_games(self):
        result = self.__model__.query.filter(Game.status == 'starting').all()
        response = self.__schema_many__.dump(result)
        return response.data

    def create_game(self, request, player):
        data = {'status': 'starting'}
        game = Game(**data)
        game.hosting = player
        db.session.add(game)
        self.__create_deck(game)
        self.__create_board(game)
        db.session.commit()
        result = self.__schema__.dump(game)
        return jsonify(result.data)

    def join_game(self, game, player):
        if not game:
            return "Game does not exist"
        if game.joining:
            return "Already Full"
        if game.hosting == player:
            return "Cannot Join your own game"
        game.joining = player
        game.status = "In Progress"
        game.turn = game.hosting
        self.__add_join_to_board(game)
        self.__initial_deal(game)
        self.__add_end_spaces(game)
        db.session.commit()
        return 'Join %d' % game.id

    def __create_deck(self, game):
        card_types = ['UL', 'U', 'UR', 'DR', 'D', 'DL']
        deck = []
        for x in xrange(0, 72):
            value = x % 6
            card = dict(position=x, value=card_types[value], game=game)
            result = Card(**card)
            db.session.add(result)

        color = ['']
        for x in xrange(0, 12):
            direction = x % 6
            card = dict(position=72 + x,
                        value='P',
                        direction=card_types[direction],
                        game=game,
                        color=direction,
                        points=0)
            result = Card(**card)
            db.session.add(result)

        db.session.commit()

        # Kind of hacky, can be made better by calling all the cards in a game at once,
        # update in objects, then commit to the database
        for x in range(0, 84):
            switch = random.randint(0, 83)
            card1 = Card.query.filter_by(position=x).filter_by(
                game=game).first()
            card2 = Card.query.filter_by(position=switch).filter_by(
                game=game).first()
            card1.position = switch
            card2.position = x
            db.session.commit()

    def __create_board(self, game):
        for x in xrange(-5, 6):
            for y in xrange(-4, 5):
                if abs(y - x) < 5:
                    space = BoardSpace(x_loc=x, y_loc=y, game=game)
                    db.session.add(space)

    def __add_join_to_board(self, game):
        space1 = BoardSpace.get(-3, 1, game)
        space2 = BoardSpace.get(-4, -2, game)
        space3 = BoardSpace.get(-3, -4, game)
        Meeple.add_meeple(game, game.joining, space1)
        Meeple.add_meeple(game, game.joining, space2)
        Meeple.add_meeple(game, game.joining, space3)
        space4 = BoardSpace.get(3, -1, game)
        space5 = BoardSpace.get(4, 2, game)
        space6 = BoardSpace.get(3, 4, game)
        Meeple.add_meeple(game, game.hosting, space4)
        Meeple.add_meeple(game, game.hosting, space5)
        Meeple.add_meeple(game, game.hosting, space6)

    def __add_end_spaces(self, game):
        space1 = BoardSpace.get(5, 1, game)
        space2 = BoardSpace.get(5, 2, game)
        space3 = BoardSpace.get(5, 3, game)
        space4 = BoardSpace.get(5, 4, game)
        space1.player = game.joining
        space2.player = game.joining
        space3.player = game.joining
        space4.player = game.joining
        space5 = BoardSpace.get(-5, -1, game)
        space6 = BoardSpace.get(-5, -2, game)
        space7 = BoardSpace.get(-5, -3, game)
        space8 = BoardSpace.get(-5, -4, game)
        space5.player = game.hosting
        space6.player = game.hosting
        space7.player = game.hosting
        space8.player = game.hosting

    def __initial_deal(self, game):
        deck = game.deck.order_by(Card.position)
        for x in range(0, 14):
            if x % 2 == 0:
                deck[x].player = game.hosting
            else:
                deck[x].player = game.joining
예제 #14
0
 def _turn2(self):
     """
     The second turn will be used from the rear end!
     """
     return Turn(self.params, self.turn2_ang)
예제 #15
0
 def startNewTurn(self):
     if self.isEnd():
         raise Exception('State is at endpoint.')
     self.advanceOnmove()
     self.curTurn = Turn(self)
예제 #16
0
 def setUp(self):
     self.a_turn = Turn(1, Player("maruko"), Card(Suit.CLUB, Rank.ACE))
예제 #17
0
파일: game.py 프로젝트: nogur9/reversi
 def play_turn(self, player):
     new_turn = Turn(player, self.board, self.rules, self.ui)
     result = new_turn.play_turn()
     self.moves_left[player.color] = result
예제 #18
0
 def __fight(self):
     print(f'Um {self.npc.name} apareceu! Prepare-se!')
     printWSleep()
     while self.player.alive and self.npc.alive:
         self.turns += 1
         Turn(self.player, self.npc)
예제 #19
0
 def pickTurn(self):
     """ Yields the turn for the proper player """
     while True:
         for player in self.players:
             yield Turn(player, self)
예제 #20
0
 def add_turn(self, player, card):
     turn = Turn(self.turn_number_generator + 1, player, card)
     # TODO: log the alternative?
     if not any(existing_turn == turn for existing_turn in self.turns):
         self.turn_number_generator += 1
         self.turns.append(turn)
예제 #21
0
def game():

    scorecard = Scorecard()

    while "empty" in scorecard.values.values():

        turn = Turn()
        turn.take_turn()
        scorecard.show_scorecard()

        while True:
            choice = raw_input("What would you like to take?")

            if choice == "quit":
                return

            if choice == "1s" and scorecard.values["1's"] != 'empty':
                print "You have already taken 1's"
                continue

            if choice == "1s":
                scorecard.take_1s(turn.dice_values)
                break

            if choice == "2s" and scorecard.values["2's"] != 'empty':
                print "You have already taken 2's"
                continue

            elif choice == "2s":
                scorecard.take_2s(turn.dice_values)
                break

            if choice == "3s" and scorecard.values["3's"] != 'empty':
                print "You have already taken 3's"
                continue

            elif choice == "3s":
                scorecard.take_3s(turn.dice_values)
                break

            if choice == "4s" and scorecard.values["4's"] != 'empty':
                print "You have already taken 4's"
                continue

            elif choice == "4s":
                scorecard.take_4s(turn.dice_values)
                break

            if choice == "5s" and scorecard.values["5's"] != 'empty':
                print "You have already taken 5's"
                continue

            elif choice == "5s":
                scorecard.take_5s(turn.dice_values)
                break

            if choice == "6s" and scorecard.values["6's"] != 'empty':
                print "You have already taken 6's"
                continue

            elif choice == "6s":
                scorecard.take_6s(turn.dice_values)
                break

            if choice == "3 of a kind" and scorecard.values[
                    "3 of a kind"] != 'empty':
                print "You have already taken 3 of a kind"
                continue

            elif choice == "3 of a kind":
                number = raw_input("Which number?")
                number = int(number)

                if turn.dice_values.count(number) < 3:
                    print "You don't have 3 of that number"
                    decision = raw_input(
                        "Do you still want to take 3 of a kind, [y/n]?")
                    if decision == "n":
                        continue
                    else:
                        scorecard.no_three_of_a_kind()
                    break
                else:
                    scorecard.three_of_kind(turn.dice_values, number)
                    break

            if choice == "4 of a kind" and scorecard.values[
                    "4 of a kind"] != 'empty':
                print "You have already taken 4 of a kind"
                continue

            elif choice == "4 of a kind":
                number = raw_input("Which number?")
                number = int(number)

                if turn.dice_values.count(number) < 4:
                    print "You don't have 4 of that number"
                    decision = raw_input(
                        "Do you still want to take 4 of a kind, [y/n]?")
                    if decision == "n":
                        continue
                    else:
                        scorecard.no_four_of_a_kind()
                        break

                else:
                    scorecard.four_of_kind(turn.dice_values, number)
                    break

            if choice == "low run" and scorecard.values["low run"] != 'empty':
                print "You have already taken low run"
                continue

            elif choice == "low run":
                scorecard.low_run(turn.dice_values)
                break

            if choice == "low run" and collections.Counter(
                    turn.dice_values) == collections.Counter([1, 2, 4, 5, 3]):
                scorecard.low_run(turn.dice_values)
                break

            elif choice == "low run" and collections.Counter(
                    turn.dice_values) != collections.Counter([2, 3, 4, 5, 1]):
                scorecard.no_low_run(turn.dice_values)
                break

            if choice == "high run" and scorecard.values["high run"] != 'empty':
                print "You have already taken high run"
                continue

            if choice == "high run" and collections.Counter(
                    turn.dice_values) == collections.Counter([2, 3, 4, 5, 6]):
                scorecard.high_run(turn.dice_values)
                break

            elif choice == "high run" and collections.Counter(
                    turn.dice_values) != collections.Counter([2, 3, 4, 5, 6]):
                scorecard.no_high_run(turn.dice_values)
                break

            if choice == "full house" and scorecard.values[
                    "full house"] != 'empty':
                print "You have already taken full house"
                continue

            if choice == "full house":
                countvalues = collections.Counter(turn.dice_values)
                if countvalues.values() == [2, 3] or countvalues.values() == [
                        3, 2
                ] or countvalues.values() == [5]:
                    scorecard.full_house(turn.dice_values)
                    break
                else:
                    scorecard.no_full_house()
                break

            if choice == "sum" and scorecard.values["sum"] != 'empty':
                print "You have already taken sum"
                continue

            elif choice == "sum":
                scorecard.sum_of(turn.dice_values)
                break

            if choice == "yahtzee" and scorecard.values["yahtzee"] != 'empty':
                print "You have already taken yahtzee"
                continue

            elif choice == "yahtzee" and collections.Counter(
                    turn.dice_values) == collections.Counter([6, 6, 6, 6, 6]):
                scorecard.yahtzee(turn.dice_values)
                break

            elif choice == "yahtzee" and collections.Counter(
                    turn.dice_values) != collections.Counter([6, 6, 6, 6, 6]):
                scorecard.noyahtzee(turn.dice_values)
                break

        scorecard.show_scorecard()

    print "End of Game. Your final score is %s" % scorecard.total_score()
예제 #22
0
def create_game_menu(board_list):

    board = None
    actions = None
    repeat = True
    while repeat:
        print("Choose a name for the game:")
        name = input()

        print("Height of the grid:")
        height = int_input_greater_than_one()

        print("Width of the grid:")
        width = int_input_greater_than_one()

        print("Number of players:")
        max_number_players = positive_int_input()

        piece_markers = []
        print("How many types of pieces?")
        number_types_pieces = positive_int_input()

        for i in range(number_types_pieces):
            print("Marker of piece number {}: (it can't be 0)".format(i + 1))
            need_to_ask = True
            while need_to_ask:
                marker = input()
                if marker != "0":
                    need_to_ask = False
                    piece_markers.append(marker)
                else:
                    print("Marker can't be 0! Try again")
                    need_to_ask = True
        #print("Verify win every turn? (y or n)")
        #end_type=input()
        #print("Length to win:")
        #length_to_win = positive_int_input()

        print("-------------------------------------")
        print("Recap: ")
        print("Name: {}".format(name))
        print("Grid height: {}".format(height))
        print("Grid width: {}".format(width))
        #print("End type: {}".format(end_type))
        #print("Length to win: {}".format(length_to_win))
        print("Pieces:")

        for i in range(number_types_pieces):
            print("  Piece number {}: {}".format(i + 1, piece_markers[i]))

        print("Everything OK so far? ")
        print("1: Yes, proceed")
        print("2: No, start over again")
        print("3: Go back to menu")
        option = input()

        if option == "1":

            print("Continuing...")

            # Create a new Boardgame Object
            board = Boardgame(name, height, width, max_number_players)

            # But we still need to define the following parameters in this object before we can use the board:
            # - type (defined inside add_turn_actions())
            # - piece_marker_dict
            # - turn (An object of Turn)
            # - players (List of players, will be well defined during game execution rather than creation)
            # At the moment (game creation), we'll define the first three

            # Define piece_marker_dict:
            # Create a dictionary to relate each type of piece with its marker
            marker_dict = {0: " "}

            # To well define the turn object, we need to define a set of actions
            actions = add_turn_actions(board, marker_dict, piece_markers)
            # Verify if list of actions creation was successful
            if actions is not None:
                # Instantiate a turn
                turn = Turn()
                # Define its actions
                turn.actions = actions

                # Then, put it into board as the selected game (Load into menu)
                board.turn = turn

                # Show the created actions
                for action in actions:
                    print("Action: {} with description: {}".format(
                        action.keyboard_input, action.description))

                # Add board into list
                board_list.append(board)

                # Save the created game in a file

                # Try to see if the file already exists
                try:
                    with open("saved_games.bin", "rb") as file_object:
                        # Load board list from file
                        board_list = pickle.load(file_object)

                        # Add newly created game into the loaded list
                        board_list.append(board)
                except FileNotFoundError:
                    print("saved_games.bin not found! Creating...")

                # Save board list:
                try:
                    with open("saved_games.bin", "wb") as file_object:
                        pickle.dump(board_list, file_object)
                except:
                    print("Error trying to create saved_games.bin!")

            repeat = False
        elif option == "2":
            repeat = True
        elif option == "3":
            repeat = False

    return board, actions
예제 #23
0
#Start Battle!
battle = Battle(pokemon1, pokemon2)


def ask_command(pokemon):
    command = None
    while not command:
        # DO ATTACK -> attack 0
        tmp_command = input("what should " + pokemon.name + " do?").split(" ")
        if len(tmp_command) == 2:
            try:
                if tmp_command[0] == DO_ATTACK and 0 <= int(tmp_command[1]):
                    command = Command({DO_ATTACK: int(tmp_command[1])})
            except Exception:
                pass
    return command


while not battle.is_finished():
    #First ask for command
    command1 = ask_command(pokemon1)
    command2 = ask_command(pokemon2)

    turn = Turn()
    turn.command1 = command1
    turn.command2 = command2

    if turn.can_start():
        #Execute turn
        battle.execute_turn(turn)
        battle.print_current_status()
예제 #24
0
def right(seconds):
    """right method"""
    turn_rgt = Turn()
    turn_rgt.right(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
예제 #25
0
def left(seconds):
    """left method"""
    turn_lft = Turn()
    turn_lft.left(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
예제 #26
0
파일: game.py 프로젝트: Pwarde/MasterMind
 def do_turn(self, game, turns):
     turn = Turn(game, turns)
     return turn.do_turn()
예제 #27
0
파일: mover.py 프로젝트: tuvokki/pistuff
                    help='How long must the car drive',
                    type=int,
                    default=1)
PARSER.add_argument('--speed',
                    help='How fast must the car drive',
                    type=int,
                    default=1)
ARGS = PARSER.parse_args()
# LOGLEVEL = ARGS.loglevel
DIRECTION = ARGS.direction
DIRECTION = -1  # backward
DRIVE_TIME = ARGS.seconds
WAIT_TIME = ARGS.speed / float(1000)

# set log level
if ARGS.verbose:
    logging.getLogger().setLevel(logging.DEBUG)

AMOVE = Move()
AMOVE.drive_time = 2
AMOVE.run()

ATURN = Turn()
ATURN.drive_time = 2
ATURN.direction = -1
ATURN.run()

AMOVE = Move()
AMOVE.wait_time = 5
AMOVE.run()