Beispiel #1
0
 def __init__(self, agent_name="basic"):
     """
 Initilize the list of available commands, binding appropriate names to the
 funcitons defined in this file.
 """
     commands = {}
     commands["name"] = self.gtp_name
     commands["version"] = self.gtp_version
     commands["protocol_version"] = self.gtp_protocol
     commands["known_command"] = self.gtp_known
     commands["list_commands"] = self.gtp_list
     commands["quit"] = self.gtp_quit
     commands["boardsize"] = self.gtp_boardsize
     commands["size"] = self.gtp_boardsize
     commands["clear_board"] = self.gtp_clear
     commands["play"] = self.gtp_play
     commands["genmove"] = self.gtp_genmove
     commands["showboard"] = self.gtp_show
     commands["print"] = self.gtp_show
     commands["set_time"] = self.gtp_time
     commands["winner"] = self.gtp_winner
     commands["hexgui-analyze_commands"] = self.gtp_analyze
     commands["agent"] = self.gtp_agent
     self.commands = commands
     self.game = Gamestate(8)
     self.agent_name = agent_name
     try:
         self.agent = self.AGENTS[agent_name]()
     except KeyError:
         print("Unknown agent defaulting to basic")
         self.agent_name = "basic"
         self.agent = self.AGENTS[agent_name]()
     self.agent.set_gamestate(self.game)
     self.move_time = 10
     self.last_move = None
Beispiel #2
0
 def gtp_clear(self, args):
     """
 Clear the game board.
 """
     self.game = Gamestate(self.game.size)
     self.agent.set_gamestate(self.game)
     self.last_move = None
     return (True, "")
Beispiel #3
0
    def test_IfBoardIsFlippedTwoTimes_ThenItShouldBeTheSame(self):
        gamestate = Gamestate.from_document(self.get_test_gamestate_document())
        gamestate_copy = Gamestate.from_document(self.get_test_gamestate_document())
        gamestate_copy.created_at = gamestate.created_at
        gamestate_copy.flip_all_units()
        gamestate_copy.flip_all_units()

        self.assert_equal_documents(gamestate.to_document(), gamestate_copy.to_document())
        self.assertEqual(gamestate, gamestate_copy)
Beispiel #4
0
def stop_event_loop(state, events):
    """
    Turns off the camera (if on), stops sending events.
    """
    log.debug('Stopping event loop!')
    _stop_webcam(events)
    return Gamestate(current_game=state.current_game, should_go_on=True)
Beispiel #5
0
 def __init__(self, agent_name="basic"):
   """
   Initilize the list of available commands, binding appropriate names to the
   funcitons defined in this file.
   """
   commands={}
   commands["name"] = self.gtp_name
   commands["version"] = self.gtp_version
   commands["protocol_version"] = self.gtp_protocol
   commands["known_command"] = self.gtp_known
   commands["list_commands"] = self.gtp_list
   commands["quit"] = self.gtp_quit
   commands["boardsize"] = self.gtp_boardsize
   commands["size"] = self.gtp_boardsize
   commands["clear_board"] = self.gtp_clear
   commands["play"] = self.gtp_play
   commands["genmove"] = self.gtp_genmove
   commands["showboard"] = self.gtp_show
   commands["print"] = self.gtp_show
   commands["set_time"] = self.gtp_time
   commands["winner"] = self.gtp_winner
   commands["hexgui-analyze_commands"] = self.gtp_analyze
   commands["agent"] = self.gtp_agent
   self.commands = commands
   self.game = Gamestate(8)
   self.agent_name = agent_name
   try:
     self.agent = self.AGENTS[agent_name]()
   except KeyError:
     print("Unknown agent defaulting to basic")
     self.agent_name = "basic"
     self.agent = self.AGENTS[agent_name]()
   self.agent.set_gamestate(self.game)
   self.move_time = 10
   self.last_move = None
Beispiel #6
0
 def reset(self):
     #drawn power, not power
     self.gamestate = Gamestate(self.initial_deck, self.initial_power,
                                self.initial_non_power, self.initial_market)
     np.random.shuffle(self.gamestate.deck)
     np.random.shuffle(self.gamestate.power)
     np.random.shuffle(self.gamestate.non_power)
Beispiel #7
0
    def gtp_boardsize(self, args):
        """
    Set the size of the game board (will also clear the board).
    """
        if (len(args) < 1):
            return (False, "Not enough arguments")
        try:
            size = int(args[0])
        except ValueError:
            return (False, "Argument is not a valid size")
        if size < 1:
            return (False, "Argument is not a valid size")

        self.game = Gamestate(size)
        self.agent.set_gamestate(self.game)
        self.last_move = None
        return (True, "")
Beispiel #8
0
 def gtp_clear(self, args):
   """
   Clear the game board.
   """
   self.game = Gamestate(self.game.size)
   self.agent.set_gamestate(self.game)
   self.last_move = None
   return (True, "")
Beispiel #9
0
 def __init__(self, db):
     ts = uuid.uuid4().int
     self.db = db[str(ts)]
     self.gamestate = Gamestate(db[str(ts)])
     self.gamestate.init_locations(db[str(ts)])
     self.gamestate.init_persons(db[str(ts)])
     self.gamestate.init_items(db[str(ts)])
     self.is_running = True
     self.start()
Beispiel #10
0
    def __init__(self, game_name):
        self.game_name = game_name

        # Set the parameters for each game type
        if self.game_name == "Oh Hell":
            self.min_players = 3
            self.max_players = 7
            self.num_decks = 1
            self.valid_cards = regular_deck

        elif self.game_name == "Rummy":
            self.min_players = 2
            self.max_players = 7
            self.num_decks = 1
            self.valid_cards = regular_deck

        else:
            # Set default of game parameters
            self.min_players = 4
            self.max_players = 4
            self.num_decks = 1
            self.valid_cards = regular_deck

        # Get Number of Players
        print("Starting game: {}".format(self.game_name))
        num_players = int(input("How many players are playing? "))
        while (num_players < self.min_players
               or num_players > self.max_players):
            num_players = int(
                input(
                    "{} isn't a valid number of players, please enter a new amount: "
                    .format(num_players)))
        self.num_players = num_players

        # Enter the player names in order
        players = []
        for i in range(0, self.num_players):
            name = input("Enter the name of player {}: ".format(i + 1))
            date = math.floor(time.time())
            id_ = name + "-" + str(date)
            players.append(Player(name, id_))

        # Build the deck of cards
        deck = Deck(self.num_decks * len(self.valid_cards),
                    enforce_order=False)
        for i in range(0, self.num_decks):
            for j in self.valid_cards:
                deck.append(Card.fromID(j))

        # Create the gamestate object, likely will switch to using a factory
        # since some games will need special gamestate attributes like current suit in Oh Hell
        self.gamestate = Gamestate(deck, players)
        print(self.gamestate)

        # Start the first action
        print("Actions not implemented yet. Ending game.")
Beispiel #11
0
def start_event_loop(state, events):
    """
    Turns on the camera (if off), start watching for events and subsequently
    sending them to the Mother Brain.
    """
    log.debug('Starting event loop!')
    events.start_camera()
    t = threading.Thread(target=_show_webcam, args=(events, ))
    t.start()
    return Gamestate(current_game=state.current_game, should_go_on=True)
Beispiel #12
0
def draw_action(view, path):

    rolls = outcome.Outcome()
    rolls.set_suboutcome(Position(3, 7), outcome.rolls(2, 1))

    gamestate = Gamestate.from_file(path + "Gamestate.json")
    units = gamestate.all_units()
    action = Action.from_document(
        units, json.loads(open(path + "Action.json").read()))
    view.draw_action_tutorial(action, rolls)
Beispiel #13
0
    def test_ActionDocument_WhenSavingAndLoading_ThenItShouldBeTheSame(self):
        gamestate = Gamestate.from_document(self.get_test_gamestate_document())
        actions = action_getter.get_actions(gamestate)
        for action in actions:
            action_document = action.to_document()
            same_action = Action.from_document(gamestate.all_units(), action_document)
            same_action.created_at = action.created_at
            same_action_document = same_action.to_document()

            self.assertEquals(action, same_action)
            self.assertEquals(action_document, same_action_document)
Beispiel #14
0
def parse_log(log):
    log = log.split('\n')
    state = Gamestate()
    nicks = {0: {}, 1: {}}
    players = {}
    start = 2
    while len(log) > 0:
        experiences = handle_turn(log, state, nicks, players)
        for experience in experiences:
            if start > 0:
                start -= 1
            else:
                yield experience
Beispiel #15
0
def draw_scenario(view, path, number, total):
    if os.path.exists(path + "Gamestate.json"):
        gamestate = Gamestate.from_file(path + "Gamestate.json")
    else:
        gamestate = Gamestate({}, {}, 2)

    players = [Player("Green", "Human"), Player("Red", "Human")]
    game = Game(players, gamestate)
    view.draw_game_tutorial(game)
    view.draw_tutorial_page_number(number, total)

    if os.path.exists(path + "Blue.marked"):
        marked_blue = [
            Position.from_string(position)
            for position in json.loads(open(path +
                                            "Blue.marked").read())["tiles"]
        ]
        view.shade_positions(marked_blue, shading_blue)

    if os.path.exists(path + "Red.marked"):
        marked_red = [
            Position.from_string(position)
            for position in json.loads(open(path +
                                            "Red.marked").read())["tiles"]
        ]
        view.shade_positions(marked_red, shading_red)

    if os.path.exists(path + "Unit.txt"):
        unit_name = open(path + "Unit.txt").readline()
        unit = getattr(units_module, unit_name.replace(" ", "_"))()
        view.show_unit_zoomed_tutorial(unit, None)
        draw_unit = True
    else:
        draw_unit = False

    if os.path.exists(path + "Description.txt"):
        description = open(path + "Description.txt").readlines()
        view.draw_tutorial_message(description, draw_unit)
Beispiel #16
0
 def gtp_boardsize(self, args):
   """
   Set the size of the game board (will also clear the board).
   """
   if(len(args)<1):
     return (False, "Not enough arguments")
   try:
     size = int(args[0])
   except ValueError:
     return (False, "Argument is not a valid size")
   if size<1:
     return (False, "Argument is not a valid size")
   
   self.game = Gamestate(size)
   self.agent.set_gamestate(self.game)
   self.last_move = None
   return (True, "")
Beispiel #17
0
class Game(object):
    """
    Represents the application as a game.
    """

    def __init__(self, db):
        ts = uuid.uuid4().int
        self.db = db[str(ts)]
        self.gamestate = Gamestate(db[str(ts)])
        self.gamestate.init_locations(db[str(ts)])
        self.gamestate.init_persons(db[str(ts)])
        self.gamestate.init_items(db[str(ts)])
        self.is_running = True
        self.start()
    def start(self):
        while(self.is_running):
            self.update()

    def update(self):
        self.gamestate.update()
Beispiel #18
0
def show_upgrades(view, folder):
    unit = menu_choice(view, sorted([unit for unit in Unit.name.values()]))
    gamestate = Gamestate.from_file(folder + "/Gamestate.json")
    gamestate.player_units["C2"] = unit
    unit = getattr(units_module, unit.replace(" ", "_"))()
    view.show_unit_zoomed_tutorial(unit, None)
    show_upgrade_list(view, unit)

    while 1:
        event = pygame.event.wait()
        if event.type == pygame.MOUSEBUTTONDOWN:
            if within(event.pos, view.interface.help_area):
                break
        if event.type == pygame.MOUSEBUTTONDOWN:
            if within(event.pos, view.interface.to_help_menu_area):
                run_tutorial(view)
                break
        if quit_game_requested(event):
            sys.exit()
Beispiel #19
0

normfont = pygame.font.Font( pygame.font.get_default_font(), 50 )


pygame.display.set_caption("Apreta_R.txt: Bloc de notas")



bggrid = bg.BackgroundAnim()

target_delay = int(1000 / 60)
tickerEvent = pygame.event.custom_type()
pygame.time.set_timer(tickerEvent, target_delay)

state = Gamestate()

def tick():
    pass

while 1:
    castTick = False
    for event in pygame.event.get():
        if event.type == pygame.QUIT: sys.exit()
        if event.type == tickerEvent: castTick = True

    if castTick:
        keys = pygame.key.get_pressed()

        # predraw time (bg stuf)
        msurf.fill(blackbg)
Beispiel #20
0
 def __init__(self, state=Gamestate(8)):
   self.set_gamestate(state)
   self.short_symetrical = True
Beispiel #21
0
import profile
import gamestate
import json
from gamestate import Gamestate
from player import Player
from game import Game
from common import Intelligence
from glob import glob

games = []
for path in glob("./keep_replays/*.json"):
    document = json.loads(open(path).read())
    gamestate = Gamestate.from_document(document["gamestate"])
    gamestate.actions_remaining = 2
    gamestate.set_available_actions()
    players = [
        Player("Green", Intelligence.AI),
        Player("Red", Intelligence.AI)
    ]
    games.append(Game(players, gamestate))


def a():
    for game in games:
        game.current_player().ai.select_action(game)


profile.run('a()')
Beispiel #22
0
class GTPInterface2:
  """
  Interface for using go-text-protocol to control the program
  Each implemented GTP command returns a string response for the user, along
  with a boolean indicating success or failure in executing the command.
  The interface contains an agent which decides which moves to make on request
  along with a gamestate which holds the current state of the game.
  """
  
  AGENTS = {"decisive_move": DecisiveMoveMctsagent, "lgr": LGRMctsagent,
            "dca": DCAMctsagent, "basic": RaveMctsagent,
            "poolrave": PoolraveMctsagent} 
  
  def __init__(self, agent_name="basic"):
    """
    Initilize the list of available commands, binding appropriate names to the
    funcitons defined in this file.
    """
    commands={}
    commands["name"] = self.gtp_name
    commands["version"] = self.gtp_version
    commands["protocol_version"] = self.gtp_protocol
    commands["known_command"] = self.gtp_known
    commands["list_commands"] = self.gtp_list
    commands["quit"] = self.gtp_quit
    commands["boardsize"] = self.gtp_boardsize
    commands["size"] = self.gtp_boardsize
    commands["clear_board"] = self.gtp_clear
    commands["play"] = self.gtp_play
    commands["genmove"] = self.gtp_genmove
    commands["showboard"] = self.gtp_show
    commands["print"] = self.gtp_show
    commands["set_time"] = self.gtp_time
    commands["winner"] = self.gtp_winner
    commands["hexgui-analyze_commands"] = self.gtp_analyze
    commands["agent"] = self.gtp_agent
    self.commands = commands
    self.game = Gamestate(8)
    self.agent_name = agent_name
    try:
      self.agent = self.AGENTS[agent_name]()
    except KeyError:
      print("Unknown agent defaulting to basic")
      self.agent_name = "basic"
      self.agent = self.AGENTS[agent_name]()
    self.agent.set_gamestate(self.game)
    self.move_time = 10
    self.last_move = None

  def send_command(self, command):
    """
    Parse the given command into a function name and arguments, execute it
    then return the response.
    """
    parsed_command = command.split()
    #first word specifies function to call, the rest are args
    name = parsed_command[0]
    args = parsed_command[1:]
    if(name in self.commands):
      return self.commands[name](args)
    else:
      return (False, "Unrecognized command")

  def register_command(self, name, command):
    """
    Add a new command to the commands list under name which
    calls the function command, will also overwrite old commands.
    """
    self.commands[name] = command

  def gtp_name(self, args):
    """
    Return the name of the program.
    """
    return (True, "RHex")

  def gtp_version(self, args):
    """
    Return the version of the program.
    """
    return (True, str(version))

  def gtp_protocol(self, args):
    """
    Return the version of GTP used.
    """
    return(True, str(protocol_version))

  def gtp_known(self, args):
    """
    Return a boolean indicating whether the passed command name is
    a known command.
    """
    if(len(args)<1):
      return (False, "Not enough arguments")
    if(args[0] in self.commands):
      return (True, "true")
    else:
      return (True, "false")

  def gtp_list(self, args):
    """
    Return a list of all known command names.
    """
    ret=''
    for command in self.commands:
      ret+='\n'+command
    return (True, ret)

  def gtp_quit(self, args):
    """
    Exit the program.
    """
    sys.exit()

  def gtp_boardsize(self, args):
    """
    Set the size of the game board (will also clear the board).
    """
    if(len(args)<1):
      return (False, "Not enough arguments")
    try:
      size = int(args[0])
    except ValueError:
      return (False, "Argument is not a valid size")
    if size<1:
      return (False, "Argument is not a valid size")
    
    self.game = Gamestate(size)
    self.agent.set_gamestate(self.game)
    self.last_move = None
    return (True, "")

  def gtp_clear(self, args):
    """
    Clear the game board.
    """
    self.game = Gamestate(self.game.size)
    self.agent.set_gamestate(self.game)
    self.last_move = None
    return (True, "")

  def gtp_play(self, args):
    """
    Play a stone of a given colour in a given cell.
    1st arg = colour (white/w or black/b)
    2nd arg = cell (i.e. g5)

    Note: play order is not enforced but out of order turns will cause the
    search tree to be reset
    """
    if(len(args)<2):
      return (False, "Not enough arguments")
    try:
      x = ord(args[1][0].lower())-ord('a')
      y = int(args[1][1:])-1

      if(x<0 or y<0 or x>=self.game.size or y>=self.game.size):
        return (False, "Cell out of bounds")

      if args[0][0].lower() == 'w':
        self.last_move = (x, y)
        if self.game.turn() == Gamestate.PLAYERS["white"]:
          self.game.play((x,y))
          self.agent.move((x,y))
          return (True, "")
        else:
          self.game.place_white((x,y))
          self.agent.set_gamestate(self.game)
          self.last_move = None
          return (True, "")


      elif args[0][0].lower() == 'b':
        self.last_move = (x, y)
        if self.game.turn() == Gamestate.PLAYERS["black"]:
          self.game.play((x,y))
          self.agent.move((x,y))
          return (True, "")
        else:
          self.game.place_black((x,y))
          self.agent.set_gamestate(self.game)
          self.last_move = None
          return (True, "")
        
      else:
        return(False, "Player not recognized")

    except ValueError:
      return (False, "Malformed arguments")

  def gtp_genmove(self, args):
    """
    Allow the agent to play a stone of the given colour (white/w or black/b)
    
    Note: play order is not enforced but out of order turns will cause the
    agents search tree to be reset
    """
    #if user specifies a player generate the appropriate move
    #otherwise just go with the current turn
    if(len(args)>0):
      if args[0][0].lower() == 'w':
        if self.game.turn() != Gamestate.PLAYERS["white"]:
          self.game.set_turn(Gamestate.PLAYERS["white"])
          self.agent.set_gamestate(self.game)
          self.last_move = None

      elif args[0][0].lower() == 'b':
        if self.game.turn() != Gamestate.PLAYERS["black"]:
          self.game.set_turn(Gamestate.PLAYERS["black"])
          self.agent.set_gamestate(self.game)
          self.last_move = None
      else:
        return (False, "Player not recognized")

    move = self.agent.special_case(self.last_move)
    self.agent.search(self.move_time)

    if not move:
      move = self.agent.best_move()

    if(move == Gamestate.GAMEOVER):
      return (False, "The game is already over")
    self.game.play(move)
    self.agent.move(move)
    self.last_move = move
    return (True, chr(ord('a')+move[0])+str(move[1]+1))

  def gtp_time(self, args):
    """
    Change the time per move allocated to the search agent (in units of seconds)
    """
    if(len(args)<1):
      return (False, "Not enough arguments")
    try:
      time = int(args[0])
    except ValueError:
      return (False, "Argument is not a valid time limit")
    if time<1:
      return (False, "Argument is not a valid time limit")
    self.move_time = time
    return (True, "")

  def gtp_show(self, args):
    """
    Return an ascii representation of the current state of the game board.
    """
    if(len(args)<1):
      return (True, str(self.game))
    elif args[0][0].lower() == 'w':
      return (True, self.game.show_board(Gamestate.PLAYERS["white"]))
    elif args[0][0].lower() == 'b':
      return (True, self.game.show_board(Gamestate.PLAYERS["black"]))
    else:
      return (False, "Player not recognized")    

  def gtp_winner(self, args):
    """
    Return the winner of the current game (black or white), none if undecided.
    """
    if(self.game.winner()==Gamestate.PLAYERS["white"]):
      return (True, "white")
    elif(self.game.winner()==Gamestate.PLAYERS["black"]):
      return (True, "black")
    else:
      return (True, "none")

  def gtp_analyze(self, args):
    """Added to avoid crashing with gui but not yet implemented."""
    return (True, "")

  def gtp_agent(self, args):
    """Change which agent is used by the player between available options."""

    if len(args)<1:
      ret="Available agents:"
      for agent in self.AGENTS.keys():
        if self.agent_name == agent:
          ret+="\n\033[92m"+agent+"\033[0m"
        else:
          ret+="\n"+agent
      return (True, ret)
    else:
      try:
        self.agent = self.AGENTS[args[0]](self.game)
      except KeyError:
        return (False, "Unknown agent")
      self.agent_name = args[0]
      return (True, "")
Beispiel #23
0
class Game:
    def __init__(self):
        self.gs = Gamestate()
        self.pb = PB()

    def play(self):
        while True:
            print('\nPlayer {} is the dealer.'.format(self.gs.dealer + 1))

            # Deal and sort players' hands
            for player in range(self.gs.num_players):
                for card in range(self.gs.hand_size):
                    self.gs.hands[player].add_card(self.gs.deck.draw())
                self.gs.hands[player].sort(self.gs.trump, self.gs.lead_suit)

            # Print player's hand

            print('\nYour hand:\n{}'.format(self.gs.hands[0].to_string()))

            # Do bidding round, return highest bidder
            self.bidding_round()
            self.gs.active_player = self.gs.bidder

            # Print highest bidder and their bid
            print('\nPlayer {} won the bidding round with a bid of {}.'.format(
                self.gs.bidder + 1, self.gs.bid))

            # Set round from -1 (bidding round) to 0
            self.gs.round = 0

            # Play out a hand
            for player in range(self.gs.hand_size):
                self.gs.active_player = self.do_round()
                self.gs.round += 1

            # Print each player's tricks after the hand
            for player in range(self.gs.num_players):
                print('\nPlayer {} took {}'.format(
                    player + 1, self.gs.tricks[player].to_string()))

            # Score each player's hand and increment their score accordingly
            self.score_hands()

            # Print score
            print('\nSCORE')
            for player in range(self.gs.num_players):
                print('Player {} has {} points.'.format(
                    player + 1, self.gs.scores[player]))

            # Check if anyone has reached the score limit
            winners = []
            for player in range(self.gs.num_players):
                if self.gs.scores[player] >= self.gs.score_limit:
                    # Add everyone at/above the score limit to the winner list
                    winners.append(player)

            # Bidder gets winning precedence
            if self.gs.bidder in winners:
                print('\nPlayer {} wins with {} points!'.format(
                    self.gs.bidder + 1, self.gs.scores[self.gs.bidder]))
                break
            else:
                if len(winners) == 1:
                    print('\nPlayer {} wins with {} points!'.format(
                        winners[0] + 1, self.gs.scores[winners[0]]))
                    break

            self.prepare_new_hand()

    # Set up/reset variables for a new round
    def prepare_new_hand(self):
        # Advance to next dealer, set them as active player
        self.gs.active_player = self.gs.next_dealer()
        # Set player after dealer as active
        self.gs.next_player()

        self.gs.min_bid = 2
        self.gs.bid = 0
        self.gs.bidder = -1

        self.gs.round = -1

        self.gs.trump = Suit.SPADES
        self.gs.lead_suit = Suit.HEARTS

        self.gs.deck = Deck(filled=True)

        for player in range(self.gs.num_players):
            self.gs.tricks[player] = Deck()

    # Returns player that wins the bidding round
    def bidding_round(self):
        print('\nPlayer {} bids first.'.format(self.gs.active_player + 1))

        bid = 0

        # Bid until back to the dealer
        while self.gs.active_player != self.gs.dealer:
            # Human
            if self.gs.active_player == 0:
                print('\nCurrent bid is {}.'.format(bid))
                # Loop until valid bid
                while True:
                    # Get bid from the player
                    bid = int(input('Your bid (0 to pass): '))
                    # If bid too small/large, get new bid
                    if (bid < self.gs.min_bid or bid > 4) and bid != 0:
                        print('Bid must be between {} and 4.'.format(
                            self.gs.min_bid))
                    # Valid bid
                    else:
                        # Player does not pass
                        if bid != 0:
                            self.gs.bid = bid
                            self.gs.min_bid = bid + 1
                            self.gs.bidder = self.gs.active_player
                        break
            # Bot
            else:
                # Get bid from bot
                bid = self.pb.bid(self.gs)
                # Bot passes
                if bid == 0:
                    print('\nPlayer {} passes the bid.'.format(
                        self.gs.active_player + 1))
                else:
                    self.gs.bid = bid
                    self.gs.min_bid = bid + 1
                    self.gs.bidder = self.gs.active_player
                    print('\nPlayer {} bid {}.'.format(
                        self.gs.active_player + 1, bid))

            self.gs.next_player()

        # No bids, dealer's bid is forced
        if self.gs.bid < 2:
            print('\nPlayer {} is forced to bid {}.'.format(
                self.gs.active_player + 1, self.gs.min_bid))
            self.gs.bid = self.gs.min_bid
            self.gs.bidder = self.gs.active_player

            return self.gs.bidder

        # Give dealer chance to match or pass
        # Human
        if self.gs.active_player == 0:
            print(
                '\nAs the dealer, you may match Player {}\'s bid of {} or pass.'
                .format(self.gs.active_player + 1, self.gs.bid))
            # Loop until valid input (match/pass)
            while True:
                bid = input('Match bid or pass (0): ')
                # Invalid bid
                if bid != 0 and bid != self.gs.bid:
                    print('Bid must be {} or pass (0).'.format(self.gs.bid))
                else:
                    break
        # Bot
        else:
            bid = self.pb.bid(self.gs)

        # Dealer passes
        if bid == 0:
            print('\nPlayer {} passes.'.format(self.gs.active_player + 1))
        # Dealer matches
        else:
            print('\nPlayer {} matches Player {}\'s bet of {}.'.format(
                self.gs.active_player + 1, self.gs.bidder + 1, self.gs.bid))
            self.gs.bidder = self.gs.active_player

    # Play a round and return the winning player
    def do_round(self):
        print('\nPlayer {} is leading out.'.format(self.gs.active_player + 1))

        # Give each player a turn to play their card
        for turn in range(self.gs.num_players):
            self.gs.turn = turn

            # Sort player's hand before player's action
            self.gs.hands[self.gs.active_player].sort(self.gs.trump,
                                                      self.gs.lead_suit)

            # Force player to play their last card
            if self.gs.round == self.gs.hand_size - 1:
                choice = 1
            else:
                # Human
                if self.gs.active_player == 0:
                    # Get number of playable cards in player's hand
                    if turn == 0:
                        # If leading the round, all cards are playable
                        playable_cards = self.gs.hand_size - self.gs.round
                    else:
                        playable_cards = self.gs.hands[
                            self.gs.active_player].playable_cards(
                                self.gs.trump, self.gs.lead_suit)

                    # Print player's hand
                    print('\nYour hand:\n{}'.format(
                        self.gs.hands[self.gs.active_player].to_string()))
                    # Print selection numbers under hand
                    for i in range(playable_cards):
                        # Only print selection numbers for playable cards
                        print('{}. '.format(i + 1), end='')

                    # Let player choose a card
                    # Loop until valid choice
                    while True:
                        choice = int(
                            input('\n\nChoose a card to play (1-{}): '.format(
                                playable_cards)))
                        # Choice out of bounds
                        if choice < 1 or choice > playable_cards:
                            print('Invalid choice.')
                        else:
                            break
                # Bot
                else:
                    choice = self.pb.play_card(self.gs)

            # Get played card from hand
            played_card = self.gs.hands[self.gs.active_player].deck[choice - 1]

            # Print played card
            print('\nPlayer {} plays {}.'.format(self.gs.active_player + 1,
                                                 played_card.to_string()))

            # If leading the round
            if self.gs.turn == 0:
                self.gs.lead_suit = played_card.suit
                self.gs.taker = self.gs.active_player
                self.gs.top_card = played_card

                # Set trump if first round
                if self.gs.round == 0:
                    self.gs.trump = played_card.suit
                    print('Trump is now {}.'.format(self.gs.trump.name))
            # Check if new card beats previous top
            else:
                # Current top card is trump
                if self.gs.top_card.suit == self.gs.trump:
                    # Played card is also trump
                    if played_card.suit == self.gs.trump:
                        # Played card beats value of top card
                        if played_card.value > self.gs.top_card.value:
                            self.gs.top_card = played_card
                            self.gs.taker = self.gs.active_player
                # Current top card is not trump (must be lead suit)
                else:
                    # Played card is trump
                    if played_card.suit == self.gs.trump:
                        self.gs.top_card = played_card
                        self.gs.taker = self.gs.active_player
                    # Played card is lead suit
                    elif played_card.suit == self.gs.lead_suit:
                        # Played card beats value of top card
                        if played_card.value > self.gs.top_card.value:
                            self.gs.top_card = played_card
                            self.gs.taker = self.gs.active_player

            # Move card from hand to the middle pile
            self.gs.middle.add_card(played_card)
            self.gs.hands[self.gs.active_player].remove_card(choice - 1)

            # Move on to next player
            self.gs.next_player()

        print('\nPlayer {} takes the trick.'.format(self.gs.taker + 1))

        # Take trick
        for card in range(self.gs.num_players):
            self.gs.tricks[self.gs.taker].add_card(self.gs.middle.deck[card])

        # Clear middle
        self.gs.middle = Deck()

        # Return winner of the round
        return self.gs.taker

    # Score each player's hand and increment points according
    def score_hands(self):
        high_trump = 0
        low_trump = 14
        jack_taker = -1
        game_taker = -1
        round_scores = []
        pips = []

        # Pip values for each card
        pip_values = {10: 10, 11: 1, 12: 2, 13: 3, 14: 4}
        pip_values = defaultdict(lambda: 0, pip_values)

        print()

        # For each stack of tricks
        for player in range(self.gs.num_players):
            # Append 0 to round_score and pips for each player
            round_scores.append(0)
            pips.append(0)

            # For each card in the stack
            for card in range(self.gs.tricks[player].size()):
                current_card = self.gs.tricks[player].deck[card]
                # If card is trump
                if current_card.suit == self.gs.trump:
                    # Card is higher than current high trump
                    if current_card.value > high_trump:
                        high_trump = current_card.value
                        high_taker = player

                    # Card is lower than current low trump
                    if current_card.value < low_trump:
                        low_trump = current_card.value
                        low_taker = player

                    # Card is jack
                    if current_card.value == 11:
                        jack_taker = player

                # Add pips
                pips[player] += pip_values[current_card.value]

            print('Player {} game = {}'.format(player + 1, pips[player]))

        # Find game point taker
        max_pips = 0
        for player in range(self.gs.num_players):
            if pips[player] > max_pips:
                game_taker = player
                max_pips = pips[player]
            # Tie: if player's pips matches max_pips, set taker to -1
            elif pips[player] == max_pips:
                game_taker = -1

        # Add up round scores
        round_scores[high_taker] += 1
        round_scores[low_taker] += 1
        if jack_taker > -1:
            round_scores[jack_taker] += 1
        if game_taker > -1:
            round_scores[game_taker] += 1

        # Bidder does not make their bid
        if round_scores[self.gs.bidder] < self.gs.bid:
            # Lose points equal to bid and set round score to 0
            # (bidder gets nothing when points are added)
            self.gs.scores[self.gs.bidder] -= self.gs.bid
            round_scores[self.gs.bidder] = 0

        # Increment game scores
        for player in range(self.gs.num_players):
            self.gs.scores[player] += round_scores[player]

        # Print who got what points
        print('\nPlayer {} took high.'.format(high_taker + 1))
        print('Player {} took low.'.format(low_taker + 1))
        if jack_taker > -1:
            print('Player {} took jack.'.format(jack_taker + 1))
        if game_taker > -1:
            print('Player {} took game.'.format(game_taker + 1))
        else:
            print('Players tied for game.')
Beispiel #24
0
 def __init__(self, state=Gamestate(8)):
     self.rootstate = deepcopy(state)
     self.root = Node()
Beispiel #25
0
 def __init__(self):
     self.gs = Gamestate()
     self.pb = PB()
Beispiel #26
0
            del (player.friends[f])
            pre_lvl = c.level + start_combat(player, c)
        else:
            pre_lvl = r_list[c].level + start_combat(player, r_list[c])
            r_list.remove(r_list[c])
        cave(player)
    elif c == 'shady roach':
        print('You decide to head over to the Shady Roach.')
        ShadyRoach.main(player)
        cave(player)
    else:
        leave(player)


if __name__ == '__main__':
    g = Gamestate()
    print('Welcome, to RODENT RUMBLE!')
    skip = select('Load Game?', 'yes', 'no')
    skip = True if skip == 'yes' else False

    if skip:
        player = g.load()
        print('You are ' + str(player) + '.')
        print(repr(player))
        wait()
        clear()
    else:
        player = pick_rodent()
        print('You are ' + str(player) + '.')
        print(repr(player))
        clear()
Beispiel #27
0
    def test_GamestateDocument_WhenSavingAndLoading_ThenItShouldBeTheSame(self):
        document = self.get_test_gamestate_document()
        gamestate = Gamestate.from_document(document)
        same_document = gamestate.to_document()

        self.assert_equal_documents(document, same_document)
Beispiel #28
0
from gamestate import Gamestate
from myboard import Myboard

# Used to run all the code
if __name__ == '__main__':
    # Creates a board with given parameters
    board = Myboard(20, 20, 75)
    # Adds mines into the board
    board.add_mines()
    # Creates a game from the given board
    game = Gamestate(board.make_tiles(), board.safespots())
    # Draws and begins the game
    game.draw()
Beispiel #29
0

from gamestate import Gamestate
from host import Host
from action import action
import output
import states

state = Gamestate()

prompt = state.triggeronprompt
parse = state.triggeronparse
oninput = state.triggeroninput

before = state.triggerbefore
instead = state.triggerinstead
after = state.triggerafter

def check(actiontype):
    def register(func):
        actiontype.check = func
        return func
    return register
        
def carryout(actiontype):
    def register(func):
        actiontype.carryout = func
        return func
    return register

def report(actiontype):
    def register(func):
Beispiel #30
0
class GTPInterface2:
    """
  Interface for using go-text-protocol to control the program
  Each implemented GTP command returns a string response for the user, along
  with a boolean indicating success or failure in executing the command.
  The interface contains an agent which decides which moves to make on request
  along with a gamestate which holds the current state of the game.
  """

    AGENTS = {
        "decisive_move": DecisiveMoveMctsagent,
        "lgr": LGRMctsagent,
        "dca": DCAMctsagent,
        "basic": RaveMctsagent,
        "poolrave": PoolraveMctsagent
    }

    def __init__(self, agent_name="basic"):
        """
    Initilize the list of available commands, binding appropriate names to the
    funcitons defined in this file.
    """
        commands = {}
        commands["name"] = self.gtp_name
        commands["version"] = self.gtp_version
        commands["protocol_version"] = self.gtp_protocol
        commands["known_command"] = self.gtp_known
        commands["list_commands"] = self.gtp_list
        commands["quit"] = self.gtp_quit
        commands["boardsize"] = self.gtp_boardsize
        commands["size"] = self.gtp_boardsize
        commands["clear_board"] = self.gtp_clear
        commands["play"] = self.gtp_play
        commands["genmove"] = self.gtp_genmove
        commands["showboard"] = self.gtp_show
        commands["print"] = self.gtp_show
        commands["set_time"] = self.gtp_time
        commands["winner"] = self.gtp_winner
        commands["hexgui-analyze_commands"] = self.gtp_analyze
        commands["agent"] = self.gtp_agent
        self.commands = commands
        self.game = Gamestate(8)
        self.agent_name = agent_name
        try:
            self.agent = self.AGENTS[agent_name]()
        except KeyError:
            print("Unknown agent defaulting to basic")
            self.agent_name = "basic"
            self.agent = self.AGENTS[agent_name]()
        self.agent.set_gamestate(self.game)
        self.move_time = 10
        self.last_move = None

    def send_command(self, command):
        """
    Parse the given command into a function name and arguments, execute it
    then return the response.
    """
        parsed_command = command.split()
        #first word specifies function to call, the rest are args
        name = parsed_command[0]
        args = parsed_command[1:]
        if (name in self.commands):
            return self.commands[name](args)
        else:
            return (False, "Unrecognized command")

    def register_command(self, name, command):
        """
    Add a new command to the commands list under name which
    calls the function command, will also overwrite old commands.
    """
        self.commands[name] = command

    def gtp_name(self, args):
        """
    Return the name of the program.
    """
        return (True, "RHex")

    def gtp_version(self, args):
        """
    Return the version of the program.
    """
        return (True, str(version))

    def gtp_protocol(self, args):
        """
    Return the version of GTP used.
    """
        return (True, str(protocol_version))

    def gtp_known(self, args):
        """
    Return a boolean indicating whether the passed command name is
    a known command.
    """
        if (len(args) < 1):
            return (False, "Not enough arguments")
        if (args[0] in self.commands):
            return (True, "true")
        else:
            return (True, "false")

    def gtp_list(self, args):
        """
    Return a list of all known command names.
    """
        ret = ''
        for command in self.commands:
            ret += '\n' + command
        return (True, ret)

    def gtp_quit(self, args):
        """
    Exit the program.
    """
        sys.exit()

    def gtp_boardsize(self, args):
        """
    Set the size of the game board (will also clear the board).
    """
        if (len(args) < 1):
            return (False, "Not enough arguments")
        try:
            size = int(args[0])
        except ValueError:
            return (False, "Argument is not a valid size")
        if size < 1:
            return (False, "Argument is not a valid size")

        self.game = Gamestate(size)
        self.agent.set_gamestate(self.game)
        self.last_move = None
        return (True, "")

    def gtp_clear(self, args):
        """
    Clear the game board.
    """
        self.game = Gamestate(self.game.size)
        self.agent.set_gamestate(self.game)
        self.last_move = None
        return (True, "")

    def gtp_play(self, args):
        """
    Play a stone of a given colour in a given cell.
    1st arg = colour (white/w or black/b)
    2nd arg = cell (i.e. g5)

    Note: play order is not enforced but out of order turns will cause the
    search tree to be reset
    """
        if (len(args) < 2):
            return (False, "Not enough arguments")
        try:
            x = ord(args[1][0].lower()) - ord('a')
            y = int(args[1][1:]) - 1

            if (x < 0 or y < 0 or x >= self.game.size or y >= self.game.size):
                return (False, "Cell out of bounds")

            if args[0][0].lower() == 'w':
                self.last_move = (x, y)
                if self.game.turn() == Gamestate.PLAYERS["white"]:
                    self.game.play((x, y))
                    self.agent.move((x, y))
                    return (True, "")
                else:
                    self.game.place_white((x, y))
                    self.agent.set_gamestate(self.game)
                    self.last_move = None
                    return (True, "")

            elif args[0][0].lower() == 'b':
                self.last_move = (x, y)
                if self.game.turn() == Gamestate.PLAYERS["black"]:
                    self.game.play((x, y))
                    self.agent.move((x, y))
                    return (True, "")
                else:
                    self.game.place_black((x, y))
                    self.agent.set_gamestate(self.game)
                    self.last_move = None
                    return (True, "")

            else:
                return (False, "Player not recognized")

        except ValueError:
            return (False, "Malformed arguments")

    def gtp_genmove(self, args):
        """
    Allow the agent to play a stone of the given colour (white/w or black/b)
    
    Note: play order is not enforced but out of order turns will cause the
    agents search tree to be reset
    """
        #if user specifies a player generate the appropriate move
        #otherwise just go with the current turn
        if (len(args) > 0):
            if args[0][0].lower() == 'w':
                if self.game.turn() != Gamestate.PLAYERS["white"]:
                    self.game.set_turn(Gamestate.PLAYERS["white"])
                    self.agent.set_gamestate(self.game)
                    self.last_move = None

            elif args[0][0].lower() == 'b':
                if self.game.turn() != Gamestate.PLAYERS["black"]:
                    self.game.set_turn(Gamestate.PLAYERS["black"])
                    self.agent.set_gamestate(self.game)
                    self.last_move = None
            else:
                return (False, "Player not recognized")

        move = self.agent.special_case(self.last_move)
        self.agent.search(self.move_time)

        if not move:
            move = self.agent.best_move()

        if (move == Gamestate.GAMEOVER):
            return (False, "The game is already over")
        self.game.play(move)
        self.agent.move(move)
        self.last_move = move
        return (True, chr(ord('a') + move[0]) + str(move[1] + 1))

    def gtp_time(self, args):
        """
    Change the time per move allocated to the search agent (in units of seconds)
    """
        if (len(args) < 1):
            return (False, "Not enough arguments")
        try:
            time = int(args[0])
        except ValueError:
            return (False, "Argument is not a valid time limit")
        if time < 1:
            return (False, "Argument is not a valid time limit")
        self.move_time = time
        return (True, "")

    def gtp_show(self, args):
        """
    Return an ascii representation of the current state of the game board.
    """
        if (len(args) < 1):
            return (True, str(self.game))
        elif args[0][0].lower() == 'w':
            return (True, self.game.show_board(Gamestate.PLAYERS["white"]))
        elif args[0][0].lower() == 'b':
            return (True, self.game.show_board(Gamestate.PLAYERS["black"]))
        else:
            return (False, "Player not recognized")

    def gtp_winner(self, args):
        """
    Return the winner of the current game (black or white), none if undecided.
    """
        if (self.game.winner() == Gamestate.PLAYERS["white"]):
            return (True, "white")
        elif (self.game.winner() == Gamestate.PLAYERS["black"]):
            return (True, "black")
        else:
            return (True, "none")

    def gtp_analyze(self, args):
        """Added to avoid crashing with gui but not yet implemented."""
        return (True, "")

    def gtp_agent(self, args):
        """Change which agent is used by the player between available options."""

        if len(args) < 1:
            ret = "Available agents:"
            for agent in self.AGENTS.keys():
                if self.agent_name == agent:
                    ret += "\n\033[92m" + agent + "\033[0m"
                else:
                    ret += "\n" + agent
            return (True, ret)
        else:
            try:
                self.agent = self.AGENTS[args[0]](self.game)
            except KeyError:
                return (False, "Unknown agent")
            self.agent_name = args[0]
            return (True, "")