Exemplo n.º 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')
Exemplo n.º 2
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)
Exemplo n.º 3
0
 def _turn1(self):
     """ get the Turn object for the first turn
     Returns
     -------
     Turn
     """
     return Turn(self.params, self.turn1_ang)
Exemplo n.º 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)
Exemplo n.º 5
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()
Exemplo n.º 6
0
 def firstTurn(self):
     for player in self.players:
         self.playerDict[player.name] = player
         self.playerStates[player.name] = PlayerState(player, self)
     self.round = 1
     self.currentPlayer = self.players.pop(0)
     self.firstPlayer   = self.currentPlayer
     self.log.append("Round 1")
     self.currentTurn = Turn(self.currentPlayer, self.players, self.round, self.log, self)
Exemplo n.º 7
0
    def nextTurn(self):
        self.currentTurn.cleanupPhase()
        if self.supply.gameOver():
            self.log.append("The Game is Over!!")
            self.determineWinner()

        self.players.append(self.currentPlayer)
        self.currentPlayer = self.players.pop(0)
        if self.currentPlayer == self.firstPlayer:
            self.round += 1
            self.log.append("Round %d" % (self.round))
        self.currentTurn = Turn(self.currentPlayer, self.players, self.round, self.log, self)
Exemplo n.º 8
0
def drive_to(bot, target: Vec3) -> Turn:
    """
    Find the most naive turn to get to the target position
    """

    car = bot.info.my_car
    turns = Turn.all(car)

    # Find best turn
    delta_n = normalize(target - car.pos)
    turn, _ = argmax(turns, lambda turn: dot(turn.dir, delta_n))

    return turn
Exemplo n.º 9
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()
Exemplo n.º 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()
Exemplo n.º 11
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
Exemplo n.º 12
0
 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()
Exemplo n.º 13
0
    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
Exemplo n.º 14
0
def smart_drive_to(bot, target: Vec3) -> Turn:
    """
    Find a turn that will get us to the target position and avoid creating short line segments
    """
    car = bot.info.my_car
    speed = min(2295, norm(car.vel) * 1.4)
    next_turn_pos = car.pos if bot.can_turn(
    ) else car.pos + car.forward * speed * bot.time_till_turn()
    line_seg_min_len = speed * TURN_COOLDOWN
    # local.x: how far in front of my car
    # local.y: how far to the left of my car
    # local.z: how far above my car
    delta_local = dot(target - next_turn_pos, car.rot)
    SOME_SMALL_VALUE = 20
    if delta_local.x < 0:
        delta_local.x = -delta_local.x
    if SOME_SMALL_VALUE < delta_local.x < line_seg_min_len:
        # Turning now results in a miss later
        return Turn.no_turn(car)
    else:
        return drive_to(bot, target)
Exemplo n.º 15
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
Exemplo n.º 16
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
    })
Exemplo n.º 17
0
 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
Exemplo n.º 18
0
class State:
    def __init__(self, data):
        self.nouns = data.nouns
        self.rooms = data.rooms
        self.vars = data.vars
        self.messages = data.messages
        self.lexicon = data.lexicon

        self.current_room = next(room for room in self.rooms.itervalues() if room.is_start)
        self.current_room.visit()

        # junction lists
        self.locations = set()
        self.tags = set()
        for noun in self.nouns.itervalues():
            self.locations |= set((noun, self.locations_by_id(lid)) for lid in noun.initial_locs)
            self.tags |= set((noun, tag) for tag in noun.initial_tags)
        for room in self.rooms.itervalues():
            self.tags |= set((room, tag) for tag in room.initial_tags)

        self.current_turn = None


    def start_turn(self, command):
        """Create a new turn object with the given command."""
        self.current_turn = Turn(command)


    def command_matches(self, control_str):
        """Check if the number of terms in the given control string is equal to or less
        than the number of words in current turn's command, and each term is a wildcard,
        a synonymous word, or a piped list of words where at least one is synonymous."""
        control_terms = [cterm for cterm in control_str.lower().split()
                         if cterm not in ('a', 'an', 'the')]
        return (len(control_terms) <= len(self.current_turn.words) and
                all(cterm == '*' or
                    any(self.lexicon.words_match(cword, self.current_turn.words[i])
                        for cword in cterm.split('|'))
                    for i, cterm in enumerate(control_terms)))


    def sub_words(self, phrase):
        return self.current_turn.sub_words(phrase) if self.current_turn is not None else phrase


    def locations_by_id(self, lid):
        """Return the noun or room with the given ID."""
        return (lid if lid in ('INVENTORY', 'WORN')
                else self.nouns.get(lid) or self.rooms.get(lid))


    def entities_by_tag(self, *tags):
        """Return a list of rooms or nouns with at least one of the given tags."""
        return set(entity for entity, tag in self.tags if tag in tags)


    def nouns_by_tag(self, *tags):
        """Return a list of nouns with at least one of the given tags."""
        return self.entities_by_tag(*tags) & set(self.nouns.itervalues())


    def rooms_by_tag(self, *tags):
        """Return a list of rooms with at least one of the given tags."""
        return self.entities_by_tag(*tags) & set(self.rooms.itervalues())


    def nouns_by_word(self, *words):
        """Return a list of nouns that match any of the given words."""
        return set(noun for noun in self.nouns.itervalues() if set(words) & noun.words)


    def nouns_by_input_word(self, wordnum):
        """Return a list of nouns matching the input word at the given index."""
        try:
            return self.nouns_by_word(self.current_turn.words[wordnum - 1])
        except IndexError:
            return set()


    def nouns_at_loc(self, *locs):
        """Return all nouns at any of the given locations."""
        return set(noun for noun, loc in self.locations if loc in locs)


    def noun_locs(self, *nouns):
        """Return all nouns or rooms containing any of the given nouns."""
        return set(loc for noun, loc in self.locations if noun in nouns)


    def add_noun(self, noun, *locs):
        """Add the given noun to all the given locations."""
        self.locations |= set((noun, loc) for loc in locs)


    def remove_noun(self, noun, *locs):
        """Remove the given noun from all the given locations."""
        self.locations -= set((noun, loc) for loc in locs)


    def move_noun(self, noun, *locs):
        """Replace the given noun's current locations with the given ones."""
        self.clear_noun_locs(noun)
        self.add_noun(noun, *locs)


    def clear_noun_locs(self, *nouns):
        """Remove the given nouns from all locations."""
        self.locations -= set((noun, loc) for noun, loc in self.locations if noun in nouns)


    def add_tag(self, tag, *entities):
        """Add the tag to all given entities."""
        self.tags |= set((entity, tag) for entity in entities)


    def remove_tag(self, tag, *entities):
        """Remove the tag from all given entities."""
        self.tags -= set((entity, tag) for entity in entities)
Exemplo n.º 19
0
def find_turns(topic, turn_section):
    #This is the regular expression to find the turn of a topic 
    #This is the regular expression to find out the user and date of a turn
    author_reg = '\[\[User(\s*talk)*:(?P<name>.*?)\|(?P<alias>.*?)\]\]'
    author_reg_c = re.compile(author_reg)
    user_date_reg = '\[\[User(\s*talk)*:(?P<name>.*?)'\
                '\|(?P<alias>.*?)\]\]'\
                '[\s\|]*(\(*\[\[.*\]\]\)*)*\s*'\
                '(?P<date>[a-zA-Z0-9i/,:\-\s]+)?'

    user_date_reg_c= re.compile(user_date_reg)

    #try to different turn indent from list indent
    list_reg = '[:\*#;\d]+'
    list_reg_c = re.compile(list_reg)
    #this indicate turn indent as a discussion thread 
    thread_reg = ':+'
    thread_reg_c = re.compile(thread_reg)
    #Find the potential turn list based on line break
    #The turn list returned mightnot be the actual one, because
    #some authors add linebreak in their messages
    #we may need to combine a few contiguous turns to form a 
    #complete turn
    #We know a turn is complete if we see user information at the 
    #end, or if the next candidate starts with ":", a wiki markup
    #indicating indent and follow up thread
    #
    turn_text_pre = ''
    turn_finish = True
    turn_list = turn_section.split('\n')
    for turn_text in turn_list:
        #pdb.set_trace()
        turn_text = turn_text.strip()
        if len(turn_text) == 0: 
            continue
    	user = user_date_reg_c.search(turn_text)
    	if user is not None:
            if turn_text.startswith(':'):
                if list_reg_c.match(turn_text) is  None:
                    if not turn_finish:
                        turn = Turn(turn_text_pre.strip())
                        topic.add_turn(turn)
                        turn_text_pre = ''
                        turn_finish = True
	    if not turn_finish:
	        turn_text = turn_text_pre + '\n' + turn_text
            #if there are multiple matching, we take th    e last one
            #pdb.set_trace()
            users = user_date_reg_c.finditer(turn_text)
            for match in users:
                date_str = match.group('date')
                author = match.group('name')
            date = None
            if date_str is not None:
                date = str_to_datetime(date_str)
            if date is not None:
                turn = Turn(turn_text.strip(), author,date)
            else:
                turn = Turn(turn_text.strip(), author)
            topic.add_turn(turn)
            turn_text_pre = ''
            turn_finish = True
        else:
            # a normal paragraph add it to previous one
            if not turn_text.startswith(':'):
                turn_text_pre = turn_text_pre+ '\n' + turn_text
                turn_finish = False
            else:
                # check if it is just a list
                if list_reg_c.match(turn_text) is not None:
                    turn_text_pre = turn_text_pre + '\n' + turn_text
                    turn_finish = False
                    # this is a new turn
                else:
                #check if there is a previous unfinished turn    
                    if not turn_finish:  
                        turn = Turn(turn_text_pre.strip())
                        topic.add_turn(turn)
                        #start the new turn
                        turn_text_pre = turn_text 
                    else: #this is another section of a previous turn
                        turn_text_pre = turn_text
                        turn_finish = False
                        
    if not turn_finish  and len(turn_text_pre)> 0:
        topic.add_turn(Turn(turn_text_pre.strip()))
    # build parent-child relationship
    # turns in a topic is added in time order 
    # after previous processing
    # some user use list mark up to indicate followup
    turns = topic.turns
    parent_stack = []
    for turn in turns:
        turn_text = turn.text
        indent = list_reg_c.match(turn_text)
        #pdb.set_trace()
        if indent is None:
            # start of a new thread
            if len(parent_stack) > 0:
                del parent_stack[:]
            parent_stack.append(turn)
        else:
            indent_str = indent.group()
            level = len(indent_str) # intended level
            #pdb.set_trace()
            current = len(parent_stack)-1 # current level
            if current < 0: # this is the first turn
                parent_stack.append(turn)
                continue
            if level > current:
                parent = parent_stack[current]
                parent.add_sub(turn)
                turn.add_parent(parent)
                parent_stack.append(turn)
            #    continue
            #if level == current: #same level,maybe a reply of previous one
                # pop the old one
             #    parent_stack.pop()
              #   parent = parent_stack[current]
              #   parent.add_sub(turn)
              #   turn.add_parent(parent)
              #   parent_stack.append(turn)
            else: # this is a reply of previous turn
                diff = current - level + 1
                for counter in range(diff):
                    parent_stack.pop()
                parent = parent_stack[len(parent_stack)-1]
                parent.add_sub(turn)
                turn.add_parent(parent)
                parent_stack.append(turn)
Exemplo n.º 20
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)
Exemplo n.º 21
0
def right(seconds):
    """right method"""
    turn_rgt = Turn()
    turn_rgt.right(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
Exemplo n.º 22
0
 def pickTurn(self):
     """ Yields the turn for the proper player """
     while True:
         for player in self.players:
             yield Turn(player, self)
Exemplo n.º 23
0
                    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()
Exemplo n.º 24
0
class Boardgame:
    piece_marker_dict = {0: " "}
    max_number_players = 0
    players = []
    type = ""  # Options: "2048-like" or "tic-tac-toe-like"
    length_to_win = 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()

    def update_available_markers(self):
        # First, get all markers
        available_markers = list(self.piece_marker_dict.values())
        # Remove the empty space as an available marker
        available_markers.remove(' ')
        # Then, search for markers being used by a player
        for player in self.players:
            # Remove not available markers in list
            if player.marker in available_markers:
                available_markers.remove(player.marker)
        return available_markers

    def g2048_init(self):
        g2048_add_new_tile(self.grid)
        g2048_add_new_tile(self.grid)

    def tic_tac_toe_init(self):
        selected_marker = ""
        for player in self.players:
            print("Associate player {} with which marker?".format(player.name))
            available_markers = self.update_available_markers()
            ask_marker = True
            while ask_marker:
                print("Available markers: {}".format(available_markers))
                selected_marker = input()
                if selected_marker not in available_markers:
                    print("Invalid marker! Try again")
                else:
                    ask_marker = False
                    player.marker = selected_marker

    def g2048_after_execution(self, grid_altered):

        # Procedures object made just to access the methods that test the game over condition
        procedures_obj = Procedures()

        # If the grid was altered, add a new random tile
        if grid_altered:
            g2048_add_new_tile(self.grid)

        # Verify if it's game over
        game_over = procedures_obj.g2048_is_game_over(self.grid)
        max_value = get_grid_tile_max(self.grid)

        if max_value == 2048:
            print("Congratulations! You have a winning configuration!")
        return game_over

    def tic_tac_toe_after_execution(self, grid_altered):
        game_over = False
        if grid_altered:
            game_over, winner_marker, number = tic_tac_toe_victory(
                self.grid, self.length_to_win)
            if game_over:
                winner = self.players[0]
                for player in self.players:
                    if player.marker == self.piece_marker_dict[winner_marker]:
                        winner = player

                print("{} has won the game!".format(winner.name))

        return game_over

    def init_game(self):
        if self.type == "2048-like":
            self.g2048_init()
        elif self.type == "tic-tac-toe-like":
            self.tic_tac_toe_init()

    def run_game(self):
        # Add players in the game
        for i in range(self.max_number_players):
            print("Player {} name: ".format(i + 1))
            new_player = Player(input())
            self.players.append(new_player)
            if i + 1 < self.max_number_players:
                print("Do you want to add more players? (You can add {} more)".
                      format(self.max_number_players - (i + 1)))
                print("1: Yes")
                print("2: No")
                option = input()
                if option == "2":
                    break

        # Start procedure:
        # Put the first player in the list as their turn
        self.turn.player = self.players[0]

        # Run init_game() to load starting situation
        self.init_game()

        # Create game loop
        turn_index = 0  # Variable to keep track of each player's turn
        grid_altered = True  # Variable that tells if the grid was altered after an action
        game_over = False
        while not game_over:  # Game loop

            # Print the grid
            print(
                grid_to_string_with_size_and_theme(self.grid,
                                                   self.piece_marker_dict,
                                                   len(self.grid)))

            # Announce the player's turn, and their available actions
            self.turn.list_actions()
            # Ask the player which action he/she will perform
            self.turn.ask_action()

            # Execute action
            action_result = self.turn.execute_action()

            # Check if result is valid
            if action_result is not None:
                # If it is, check whether the updated grid is different from the old one
                if not equal_grids(self.grid, action_result):
                    # Update grid
                    self.grid = action_result
                    grid_altered = True
                else:
                    grid_altered = False
            else:
                # Else, the user has put an invalid input (an input that is not equal to any action)
                print("Wrong input! Try again")
                continue

            # Do things after execution (like verify movement)
            if self.type == "2048-like":
                game_over = self.g2048_after_execution(grid_altered)
            elif self.type == "tic-tac-toe-like":
                game_over = self.tic_tac_toe_after_execution(grid_altered)

            if not game_over:
                # Change turn:
                turn_index += 1
                if turn_index == len(self.players):
                    turn_index = 0
                self.turn.player = self.players[turn_index]

        # Print the grid one more time to show the game over grid
        print(
            grid_to_string_with_size_and_theme(self.grid,
                                               self.piece_marker_dict,
                                               len(self.grid)))
        print("Game Over !")
Exemplo n.º 25
0
class HWState:
    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)

    def deepCopy(self):
        systems = [s.deepCopy() for s in self.systems]
        stash = self.stash.deepCopy()
        alive = list(self.alive)
        return HWState(self.nplayers, self.onmove, systems, stash, alive)

    def creationOver(self):
        return self.alive.count(None) == 0

    def addSystem(self, system):
        self.systems.append(system)

    def removeSystem(self, system):
        self.systems.pop(self.systems.index(system))

    def findHome(self, player):
        for sys in self.systems:
            if sys.home == player:
                return sys
        # Player's home is missing
        return None

    def cancelTurn(self):
        self.curTurn.undoAll()

    def addEvent(self, e):
        # Event should be a Creation, Action, Catastrophe, or Pass
        # Fade and Elimination events are checked for and triggered here

        self.curTurn.addEvent(e)
        try:
            e.enact(self)
        except Exception as ex:
            # Signal the turn that the event is cancelled
            # This affects the turn's understanding of whether a sacrifice is occurring
            try:
                self.curTurn.undoLast()
            except:
                print(
                    'A problem occurred while resetting the turn. This could be a serious problem.'
                )
                print(str(ex))
            raise ex

        # Check for Fades (but not for home systems)
        sys = e.getThreatenedSystem()
        if (not sys is None) and (sys.home is None) and sys.isVoid():
            fade = sys.getFade()
            self.curTurn.addEvent(fade)
            fade.enact(self)

    def finishTurn(self):
        # Checks for home system fades and eliminations
        if not self.curTurn.isCompleted():
            self.cancelTurn()
            raise TurnNotOverException(
                'Turn is not complete. Did you forget to pass an unwanted sacrifice action?'
            )

        # Check for elimination
        # TODO this is better for huge numbers of players, but slower otherwise
#        for player in self.curTurn.getThreatenedPlayers()
        for player in range(self.nplayers):
            # Check if player has been eliminated
            if self.alive[player] != True:
                # Player is either already known to be dead or hasn't created a home
                continue
            # Player is believed to be alive but may have just been eliminated
            home = self.findHome(player)
            abandoned = not home.hasPresence(player)
            voided = home.isVoid()

            if abandoned or voided:
                # Player has been eliminated
                elim = event.Elimination(player, self.onmove)
                self.curTurn.addEvent(elim)
                elim.enact(self)
            if voided:
                fade = home.getFade()
                self.curTurn.addEvent(fade)
                fade.enact(self)

    def startNewTurn(self):
        if self.isEnd():
            raise Exception('State is at endpoint.')
        self.advanceOnmove()
        self.curTurn = Turn(self)

    def advanceOnmove(self, d=1):
        # set d=-1 to get previous player
        self.onmove = self.getNextPlayer(d)

    def getNextPlayer(self, d=1):
        # set d=-1 to get previous player
        i = (self.onmove + d) % self.nplayers
        # TODO if current player is somehow dead, this is an endless loop
        while self.alive[i] == False:
            i = (i + d) % self.nplayers
        return i

    def getScores(self):
        if not self.isEnd():
            raise Exception('Game is not over.')
        if self.alive.count(True) == 0:
            return [1 / self.nplayers] * self.nplayers
        scores = [0] * self.nplayers
        scores[self.alive.index(True)] = 1
        return scores

    def saveTuple(self):
        # Returns a tuple appropriate for saving the game
        # Systems are not sorted, so not appropriate for comparing states
        # Includes system names
        stuples = [s.saveTuple() for s in self.systems]
        return (self.onmove, tuple(self.alive), tuple(stuples))

    def tuplify(self):
        # Does not include system names, but systems are sorted
        # Appropriate for comparing states
        if not self.tupled is None:
            return self.tupled
        stuples = [s.tuplify() for s in self.systems]
        stuples.sort()
        self.tupled = (self.onmove, tuple(self.alive), tuple(stuples))
        return self.tupled

    def __hash__(self):
        return self.calcHash()

    def calcHash(self):
        return hash(self.tuplify())

    def isEnd(self):
        # TODO implement other win conditions
        if not self.creationOver():
            return False
        return self.alive.count(True) <= 1

    def __eq__(self, other):
        return self.tuplify() == other.tuplify()

    def __str__(self):
        divider = '/' * 30
        movestr = 'Player %s to move' % self.onmove
        stashStr = str(self.stash)
        sysStr = ('\n%s\n' % divideSysStr).join([str(s) for s in self.systems])
        return '%s\n%s\n%s\n%s\n%s' % (divider, movestr, stashStr, sysStr,
                                       divider)

    def buildStr(self):
        return '<{}>;\n{}'.format(
            self.onmove,
            ';\n'.join([sys.buildStr(self.nplayers) for sys in self.systems]))

    def getConnections(self, sys):
        # Return a list of systems connected to sys INCLUDING DISCOVERIES
        # TODO remember connections so this doesn't have to keep getting called
        connects = []
        # Existing systems
        for s in self.systems:
            if s.connectsTo(sys):
                connects.append(s)

        # Discoveries
        for size in piece.sizes:
            for m in sys.markers:
                if m.size == size:
                    break
            else:
                # Inner loop exited normally, discoveries may have this size
                for c in colors:
                    if self.stash.isAvailable(c, size):
                        p = piece.Piece(size, c)
                        connects.append(System([p]))
        return connects
Exemplo n.º 26
0
def left(seconds):
    """left method"""
    turn_lft = Turn()
    turn_lft.left(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
Exemplo n.º 27
0
 def setUp(self):
     self.a_turn = Turn(1, Player("maruko"), Card(Suit.CLUB, Rank.ACE))
Exemplo n.º 28
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
Exemplo n.º 29
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()
Exemplo n.º 30
0
class Game(object):
    def __init__(self, playerList, sets):
        self.log = []
        allCards = []
        for Set in sets:
            allCards.extend(Set)
        gameCards = sample(allCards,10) ## gets 10 random cards from inluded sets
        numOfPlayers = len(playerList)
        self.supply  = BaseSupply(gameCards,numOfPlayers)
        #print self.supply
        self.players = [Player(name,self.supply) for name in playerList]
        shuffle(self.players)

        self.playerDict = dict()
        self.playerStates = dict()
        for player in self.players:
            self.playerDict[player.name]  = player
            self.playerStates[player.name]= PlayerState(player,self)
        self.firstTurn()

    def firstTurn(self):
        for player in self.players:
            self.playerDict[player.name] = player
            self.playerStates[player.name] = PlayerState(player, self)
        self.round = 1
        self.currentPlayer = self.players.pop(0)
        self.firstPlayer   = self.currentPlayer
        self.log.append("Round 1")
        self.currentTurn = Turn(self.currentPlayer, self.players, self.round, self.log, self)

    def nextTurn(self):
        self.currentTurn.cleanupPhase()
        if self.supply.gameOver():
            self.log.append("The Game is Over!!")
            self.determineWinner()

        self.players.append(self.currentPlayer)
        self.currentPlayer = self.players.pop(0)
        if self.currentPlayer == self.firstPlayer:
            self.round += 1
            self.log.append("Round %d" % (self.round))
        self.currentTurn = Turn(self.currentPlayer, self.players, self.round, self.log, self)


    def determineWinner(self):
        winner = (None, 0)
        for player in self.players:
            vp = player.numOfVictoryPoints()
            if vp > winner[1]:
                winner = ([player], vp)
            elif vp == winner[1]:
                if winner[0]:
                    winner = (winner[1].append(player),winner[1])
                else:
                    winner = ([player], vp)
        winners = ''

        for player in winner[0]:
            if player == winner[0][-1]:
                winners += player
            else:
                winners += player + " and "
        self.log.append("%s Just won with %d Victory Points" % (winners, winner[1]))
        for player in self.players:
            if player not in winner[0]:
                self.log.append("%s scored %d Victory Points" % (player.name, player.numOfVictoryPoints()))
Exemplo n.º 31
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)
Exemplo n.º 32
0
 def startNewTurn(self):
     if self.isEnd():
         raise Exception('State is at endpoint.')
     self.advanceOnmove()
     self.curTurn = Turn(self)
Exemplo n.º 33
0
def left(seconds):
    """left method"""
    turn_lft = Turn()
    turn_lft.left(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
Exemplo n.º 34
0
 def _turn2(self):
     """
     The second turn will be used from the rear end!
     """
     return Turn(self.params, self.turn2_ang)
Exemplo n.º 35
0
def right(seconds):
    """right method"""
    turn_rgt = Turn()
    turn_rgt.right(seconds)
    return jsonify({'result': "done", 'direction': '', 'drive_time': seconds})
Exemplo n.º 36
0
                    action="store_true")
PARSER.add_argument(
    '--direction', help='Set to 1 for clockwise and -1 for anti-clockwise', type=int, default=1)
PARSER.add_argument(
    '--seconds', 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()
Exemplo n.º 37
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()
Exemplo n.º 38
0
 def do_turn(self, game, turns):
     turn = Turn(game, turns)
     return turn.do_turn()
Exemplo n.º 39
0
 def start_turn(self, command):
     """Create a new turn object with the given command."""
     self.current_turn = Turn(command)