Пример #1
0
def play(pool_size=10, variant='rostov'):
    """
  """
    # Initialize new game
    pool_closed = False
    pls = [players.Player(ai=True), players.Player(ai=True), players.Player()]
    d = cards.Deck()
    first = W
    turn = W

    # Play
    while not pool_closed:  # TODO: change to keep track of score
        hands, blind = d.deal()
        for i in range(3):
            # Deal in proper order: from first hand onwards
            pls[(i + turn) % 3].set_hand(hands[i])

        # Bidding
        bidding = True
        bids = [None, None, None]
        while bidding:
            if not pls[turn].ai:
                draw_table(
                    first=first,
                    bidding=True,
                    bids=bids,  # blind=blind,
                    hands=[pls[W].ncards(), pls[E].ncards(), pls[S].hand])
            pls[turn].make_bid(turn, bids)
            turn = (turn + 1) % 3
Пример #2
0
    def __init__(self, white_name, black_name):

        self.b = board.Board()

        self.white = players.Player(name=white_name,
                                    color='white',
                                    board=self.b)
        self.black = players.Player(name=black_name,
                                    color='black',
                                    board=self.b)

        self.b[0][0].set(pieces.Rook('white'))
        self.b[1][0].set(pieces.Knight('white'))
        self.b[2][0].set(pieces.Bishop('white'))
        self.b[3][0].set(pieces.Queen('white'))
        self.b[4][0].set(pieces.King('white'))
        self.b[5][0].set(pieces.Bishop('white'))
        self.b[6][0].set(pieces.Knight('white'))
        self.b[7][0].set(pieces.Rook('white'))

        self.b[0][1].set(pieces.Pawn('white'))
        self.b[1][1].set(pieces.Pawn('white'))
        self.b[2][1].set(pieces.Pawn('white'))
        self.b[3][1].set(pieces.Pawn('white'))
        self.b[4][1].set(pieces.Pawn('white'))
        self.b[5][1].set(pieces.Pawn('white'))
        self.b[6][1].set(pieces.Pawn('white'))
        self.b[7][1].set(pieces.Pawn('white'))

        self.b[0][6].set(pieces.Pawn('black'))
        self.b[1][6].set(pieces.Pawn('black'))
        self.b[2][6].set(pieces.Pawn('black'))
        self.b[3][6].set(pieces.Pawn('black'))
        self.b[4][6].set(pieces.Pawn('black'))
        self.b[5][6].set(pieces.Pawn('black'))
        self.b[6][6].set(pieces.Pawn('black'))
        self.b[7][6].set(pieces.Pawn('black'))

        self.b[0][7].set(pieces.Rook('black'))
        self.b[1][7].set(pieces.Knight('black'))
        self.b[2][7].set(pieces.Bishop('black'))
        self.b[3][7].set(pieces.Queen('black'))
        self.b[4][7].set(pieces.King('black'))
        self.b[5][7].set(pieces.Bishop('black'))
        self.b[6][7].set(pieces.Knight('black'))
        self.b[7][7].set(pieces.Rook('black'))

        # white to move first
        self.current_player = self.white
Пример #3
0
def getPlayers(code):
    teamPage = requests.get(URL + code + '/2016.html')
    teamTree = html.fromstring(teamPage.content)

    playersWeb = teamTree.xpath('//table[@id="roster"]//a/text()')
    playerStats = teamTree.xpath('//table[@id="roster"]/tbody/tr/td/text()')

    if '\xa0' in playerStats:
        playerStats.remove('\xa0')

    teamPlayers = []

    row = 0
    for player in playersWeb:
        team = code
        name = player
        position = playerStats[row + 1]
        age = playerStats[row + 2]
        height = playerStats[row + 3]
        weight = playerStats[row + 4]
        experience = playerStats[row + 6]
        summary = playerStats[row + 8]
        salary = playerStats[row + 9]

        addition = players.Player(team, name, position, age, height, weight,
                                  experience, summary, salary)
        teamPlayers.append(addition)

        row += 10

    return teamPlayers
Пример #4
0
def main():

    player = players.Player(login_flow())

    command_list = [key for key in command_args]

    while True:
        print('\nCommand list')

        for i in range(0, len(command_list)):
            print(i, ' - ', command_list[i])

        print('\n(', player.id, ')Seclect command: ', end='')
        user_input = input()
        cmd_id = int(user_input)
        cmd = command_list[cmd_id]
        args = get_command_arguments(cmd)

        if cmd == 'login':
            client.print_responce(login_flow())
        elif cmd == 'merge_wizard':
            client.merge_wizard(player.id, args['destination'])
        elif cmd == 'allocation':
            args = {'player_id': player.id}
            responce = client.send_request('player_data', args, player.id)
            player_data = responce['result']
            client.deserialize_player_data(player, player_data)
            #print(player.data())
            client.print_responce(allocation(player))
        else:
            client.print_responce(client.send_request(cmd, args, player.id))
Пример #5
0
def read_players():
    players = []
    read = input(
        "Do you wish to load the contents of 'players.json'? (Y/N) ").upper()
    if read != "N" or read != "NO":
        if os.path.isfile("players.json"):
            with open("players.json", "r") as playersfile:
                players = json.loads(playersfile.read())  # load the data...
        else:
            print("'players.json' was not found...")
    for i in range(len(players)):
        if "points" in players[i].keys():  # implies BasketballPlayer
            players[i] = p.BasketballPlayer(
                players[i]["first_name"], players[i]["last_name"],
                players[i]["height_cm"], players[i]["weight_kg"],
                players[i]["points"], players[i]["rebounds"],
                players[i]["assists"])
        elif "goals" in players[i].keys():  # implies FootballPlayer
            players[i] = p.FootballPlayer(players[i]["first_name"],
                                          players[i]["last_name"],
                                          players[i]["height_cm"],
                                          players[i]["weight_kg"],
                                          players[i]["goals"],
                                          players[i]["yc"], players[i]["rc"])
        else:  # implies base class
            players[i] = p.Player(players[i]["first_name"],
                                  players[i]["last_name"],
                                  players[i]["height_cm"],
                                  players[i]["weight_kg"])
    return players
Пример #6
0
def findplayer(user):
    for player in active_players:
        if player.user.id == user.id:
            return player
    player = players.Player(user)
    active_players.append(player)
    return player
Пример #7
0
    def _update_player(self, address, name):

        # Attempt to get the player by name and then address
        player = None
        if name != 'defaultPlayer' and name in self.name_to_player:
            player = self.name_to_player[name]
        elif address and address in self.addr_to_player:
            player = self.addr_to_player[address]
        else:
            player = players.Player(address, name)

        # Make sure the player model is up to date
        player.address = address
        player.name = name

        # Update the set of player aliases
        player.aliases.add(name)

        # Update the address mapping for human players
        if address:
            self.addr_to_player[address] = player

        # Update the id and name mappings for the player
        self.id_to_player[player.id] = player
        self.name_to_player[name] = player

        # Update the master player index
        self.players.add(player)
        return player
Пример #8
0
 def read_players(self):
     players = []
     read = input(
         "Do you wish to load the contents of 'players.json'? (Y/N) "
     ).upper()
     if read != "N" or read != "NO":
         if os.path.isfile("players.json"):
             with open("players.json", "r") as playersfile:
                 players = json.loads(
                     playersfile.read())  # load the data...
         else:
             print("'players.json' was not found...")
     # since we've got a list of dictionaries,
     # we still have to create actual objects...
     for i in range(len(players)):
         if "points" in players[i].keys():  # implies BasketballPlayer
             self.players.append(
                 p.BasketballPlayer(
                     players[i]["first_name"], players[i]["last_name"],
                     players[i]["height_cm"], players[i]["weight_kg"],
                     players[i]["points"], players[i]["rebounds"],
                     players[i]["assists"]))
         elif "goals" in players[i].keys():  # implies FootballPlayer
             self.players.append(
                 p.FootballPlayer(players[i]["first_name"],
                                  players[i]["last_name"],
                                  players[i]["height_cm"],
                                  players[i]["weight_kg"],
                                  players[i]["goals"], players[i]["yc"],
                                  players[i]["rc"]))
         else:  # implies base class
             self.players.append(
                 p.Player(players[i]["first_name"], players[i]["last_name"],
                          players[i]["height_cm"], players[i]["weight_kg"]))
Пример #9
0
 def add_player(self):
     print("0: Player (base class)")
     print("1: BasketballPlayer")
     print("2: FootballPlayer")
     choice = input(
         "What kind of player do you wish to add? (enter corresponding number) "
     )
     first_name = input("Enter a first name: ")
     last_name = input("Enter a last name: ")
     height_cm = read_positive_float("Enter a height in cm: ")
     weight_kg = read_positive_float("Enter a weight in kg: ")
     if choice == "0":
         self.players.append(
             p.Player(first_name, last_name, height_cm, weight_kg))
     elif choice == "1":
         points = read_positive_integer("Enter a number of points: ")
         rebounds = read_positive_integer("Enter a number of rebounds: ")
         assists = read_positive_integer("Enter a number of assists: ")
         self.players.append(
             p.BasketballPlayer(first_name, last_name, height_cm, weight_kg,
                                points, rebounds, assists))
     elif choice == "2":
         goals = read_positive_integer("Enter a number of goals: ")
         yc = read_positive_integer("Enter a number of yellow cards: ")
         rc = read_positive_integer("Enter a number of red cards: ")
         self.players.append(
             p.FootballPlayer(first_name, last_name, height_cm, weight_kg,
                              goals, yc, rc))
Пример #10
0
async def dgive(ctx, *args):
    if len(args) == 0:
        return

    amount = 1
    plant = ""
    try:
        int(args[0])
    except ValueError:
        plant = " ".join(args).strip()
    else:
        amount = int(args[0])
        plant = " ".join(args[1:]).strip()

    if not items.is_item(plant):
        await client.say(f"`{plant}` isn't a real item...")
        return

    if ctx.message.author not in play.players:
        play.players[ctx.message.author] = play.Player(ctx.message.author)
    current_player = play.players[ctx.message.author]

    item = items.Item(plant, amount=amount)
    current_player.items += item
    await client.say(
        f"Gave {item.emoji} **{item.name}** (x{item.amount}) to {current_player.player.name}"
    )
Пример #11
0
def main():

    player = players.Player(login_flow())

    print('AI ' + str(player.id) + '(' + sys.argv[1] + '/' + sys.argv[2] +
          ') is created. merging it to wizard ' + sys.argv[3])
    update_wizard(player.id)

    while True:
        time.sleep(10)
        responce = client.send_request('status', [], player.id)
        print(responce)
        status = responce['result']
        if status['type'] == "wizard":
            continue
        if status['phase'] == 'allocation' and status[
                'player_turn'] == player.id:
            args = {'player_id': player.id}
            responce = client.send_request('player_data', args, player.id)
            player_data = responce['result']
            client.deserialize_player_data(player, player_data)
            free_man = get_free_man(player)
            if free_man:
                args = {'location': 'hunting_grounds', 'men': [free_man.name]}
                if client.send_request('allocation', args,
                                       player.id)['result']:
                    print('AI ' + str(player.id) + '(' + sys.argv[1] + '/' +
                          sys.argv[2] + '): sending ' + free_man.name +
                          ' to hunting grounds')
Пример #12
0
   def post(self, clubid, name):
      r_name   = self.request.get('name')
      r_fname  = self.request.get('fname')
      r_lname  = self.request.get('lname')
      r_rank   = self.request.get('rank')
      r_op     = self.request.get('op')

      user = users.get_current_user()
      club = clubs.Club.get_by_id(clubid)

      if user not in club.owners:
         self.response.clear()
         self.response.set_status(405)
         self.response.out.write("Not authorized")
         return
      player = players.Player.query(ndb.AND(players.Player.name == name, players.Player.club == club.key)).fetch(1)
      if player:
         player = player[0]
      else:
         player = players.Player()
         player.club = club.key

      if r_op == 'update':
         player.name = r_name
         if r_fname:
            player.firstName = r_fname
         if r_lname:
            player.lastName = r_lname
         player.handicap = r_rank
         player.put()
      elif r_op == 'delete':
         player.key.delete()
Пример #13
0
def test_gamePlayState(cards,n):
	pl=[players.FastRandomPlayer() for j in xrange(3)]
	superplayer=players.Player()
	pl[n]=superplayer
	allpass_rules.play(pl,cards,True)
	for v in superplayer.vectors:
		print aux.vectorToText(v)
Пример #14
0
def test_player():
    p = players.Player()
    print("\n---------  TEST player constructor  -------------\n")
    print(f'--Player name: {p.name}')
    print(f'--Player score: {str(p.score)}')
    print(f'--Player cards: {p.cards}')
    print(f'--Player is_dealer: {p.is_dealer}')
Пример #15
0
async def inv(ctx, *args):
    if ctx.message.author not in play.players:
        play.players[ctx.message.author] = play.Player(ctx.message.author)
    current_player = play.players[ctx.message.author]

    embed = discord.Embed(title=f"*{current_player.player.name}'s Inventory:*",
                          colour=0x0080d6)
    embed.add_field(name="**__Money__:**",
                    value=f":moneybag: ${current_player.money}")

    items_text = ""
    seeds_text = ""
    if len(current_player.items) > 0:
        for item in current_player.items:
            if item.name.endswith(("seeds", "pellets")):
                seeds_text += f"{item.emoji} **{item.name}** (x{item.amount})\n"
            else:
                items_text += f"{item.emoji} **{item.name}** (x{item.amount})\n"

        if items_text is not "":
            embed.add_field(name="**__Items__:**", value=items_text)
        if seeds_text is not "":
            embed.add_field(name="**__Seeds__:**", value=seeds_text)

    await client.send_message(ctx.message.channel,
                              f"{current_player.player.mention} ->",
                              embed=embed)
Пример #16
0
def run(turns, rounds, decks, goldfish=True):
    print("Running %s games for %s turns...") % (rounds, turns)
    if goldfish:
        print("In goldfish (single player) mode")
        nplayers = 1
    else:
        nplayers = 2
        print("Can only goldfish, sorry")
        sys.exit(1)

    ourplayers = []
    for n in range(0, nplayers):
        player = players.Player(name="Player%s" % n, deck=decks[n])
        ourplayers.append(player)

    for round in range(0, rounds):
        print("Round %s... FIGHT" % (round + 1))
        for player in ourplayers:
            player.reset()
            print("%s has a %s card deck" %
                  (player.name, len(player.deck.main)))
            player.mulligan(rules={})
            print("After mulligans player %s has %s cards." %
                  (player.name, len(player.hand)))
            print("%s" % ([str(c) for c in player.hand]))
Пример #17
0
def startBlackJack(playerName):
    deck_of_cards = deck.Deck()
    dealer = players.Player('Computer AI', 100, isDealer=True)
    player1 = players.Player(playerName, 100)
    blackJack = Blackjack(deck_of_cards, dealer, player1)
    return blackJack


# ---------------------TEST-------------------
# print("is_Game_over: {}".format(blackJack.isEndOfRound()))

# for cardFace in blackJack.deck.cardFace:
#     print("\'{}\' card face has value of: {}".format(
#         cardFace, blackJack.checkCardValue(cardFace)))

# for player in blackJack.players:
#     print(player, player.getBalance())
Пример #18
0
def main():
    print("The Program has started")
    #card = Card("Clubs", 6, False)
    this_game = game.Game()

    #Add players to game
    this_game.add_player(players.Player("Will Holcomb"))
    this_game.add_player(players.Player("John Fuex"))
    this_game.add_player(players.Player("Joe Holcomb"))
    this_game.add_player(players.Player("Elvis Presley"))

    this_game.start_game()

    for this_player_index, this_player in enumerate(this_game.game_players):
        print("Player #{} {}'s hand:\n {}".format(this_player_index + 1,
                                                  this_player,
                                                  this_player.showHand("\n")))
Пример #19
0
 def _name_ok(self, buttin, choice):
     if self.name:
         player = players.Player(self.statics.PLAYER_ID, self.name,
                                 self.statics.CHARACTER_ID, 1)
         player.db_name = store.put_player(self.statics.BOARD_DB_NAME,
                                           player.to_json_dict())
         self.statics.PLAYERS.append(player)
         self._change_to_screen(
             LobbyScreen(self.statics, self.screen_wt, self.screens))
Пример #20
0
 def add_players(self):
     """initalizes Player objects with name input step and adds to player list"""
     name = input('Enter player name here (ENTER when finished): ')
     while name != '':
         self.num_players += 1
         player = p.Player(name)
         self.players[self.num_players] = player
         name = input('Enter player name here (ENTER when finished): ')
     print(f'{len(self.players)} players added!\n')
Пример #21
0
def _extract_player_name_and_url(card):
    player = players.Player()
    tds = card.find_all('td')
    player_name = tds[3].find('span')
    player.get_first_last_name(player_name.text)
    link = player_name.find('a')
    if link:
        href = link.get('href')
        player.url = urljoin(constants.WIKI_BASE_URL, href)
    return player
Пример #22
0
 def __init__(self, sound, player):
     QWidget.__init__(self)
     self.setWindowTitle("Street Fighter")
     self.sound = sound
     self.state = 0
     self.player = player
     self.ennemi = players.Player("assets/ken_normal_left.png", "assets/ken_fight_left.png")
     self.playSound("assets/sounds/title.wav")
     self.resize(1200, 1000)
     self.label = QLabel(self)
Пример #23
0
def read_playersCSV(bstats_settings, playerdict, teams):
    teamsFile = open('PlayerLists/playerlist.csv')
    teamsReader = csv.reader(teamsFile)
    teamsData = list(teamsReader)
    for index, info in enumerate(teamsData):
        if int(info[1]) < 0:
            teams.append(Team(bstats_settings, info[0], info[1], info[2]))
        else:
            playerdict['player{0}'.format(index)] = \
                players.Player(bstats_settings, info[0], info[1], info[2])
Пример #24
0
    def room(self, ID):
        print("I'm in room", ID, "now!")
        mybuttons = button.ButtonRoom()
        mybuttons_color = button.ButtonColor()

        room_players = {
            self.clientNO: self.player,
        }
        while True:
            sendSomething(self.clientSocket,
                          ["myplayer_info", self.player_info])
            data = receive(self.clientSocket)
            if type(data) != bool and data[0] == "players_info":
                pos = 1
                room_players = {
                    self.clientNO: self.player,
                }
                for i in data[1].keys():
                    i = int(i)
                    if i != self.clientNO:
                        room_players[i] = players.Player(
                            i, data[1][str(i)]['hero'],
                            data[1][str(i)]['color'], pos)
                        pos += 1

            self.screen.fill((100, 50, 50))
            for j in range(0, 2):
                for i in range(0, 4):
                    pygame.draw.rect(self.screen, (0, 127, 127),
                                     (i * 150 + 75, j * 150 + 50, 150, 150), 3)

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    sys.exit()
                if event.type == pygame.MOUSEBUTTONUP:
                    if mybuttons.buttons[0].isOver():  # 开始游戏
                        print("room - 0 start game")
                        self.start(ID)
                        sendSomething(self.clientSocket, ["return room"])
                        break
                    elif mybuttons.buttons[1].isOver():  # 返回上级
                        print("room - 1 return hall")
                        self.exitRoom(ID)
                        return
                    else:
                        for i in range(len(mybuttons_color.buttons)):
                            if mybuttons_color.buttons[i].isOver():
                                self.player_info['color'] = i - 1
                                self.player.changeColor(i - 1)

            mybuttons.render(self.screen)
            mybuttons_color.render(self.screen)
            for i in room_players.values():
                i.blit(self.screen)
            pygame.display.update()
Пример #25
0
def register():
    if current_user.is_authenticated and current_user.get_id() == 'msamogh':
        if request.method == 'GET':
            return render_template('register.html',
                                   users=players.get_all_players(db))
        player = players.Player(db, request.form['name'])

        return render_template('register.html',
                               username=player.username,
                               users=players.get_all_players(db))
    return 'Not authorized'
Пример #26
0
    def __init__(self, clientNO):
        self.clientNO = clientNO

        self.name = heroes.randHero()
        self.color = heroes.randColor()
        self.player = players.Player(self.clientNO, self.name, self.color, 0)

        nextnode = 0
        serverName = server_name[nextnode]
        serverPort = server_port[nextnode]
        self.clientSocket = socket(AF_INET, SOCK_STREAM)
        self.clientSocket.connect((serverName, serverPort))
Пример #27
0
 def test_init(self):
     player = players.Player('eric', 1, 2, self.game, 'green', (100, 100))
     assert player._name == 'eric'
     assert player._vision == 1
     assert player._speed == 2
     assert player._game == self.game
     assert player._colour == 'green'
     assert player._location == (100, 100)
     assert player._points == 0
     assert player._targets == []
     assert player._enemies == []
     assert player._direction in 'NSEW'
Пример #28
0
    def add_player(self, id):
        '''
        (int) -> Wizard

        Creates player in core list with passed id. Creates Wizard for
        this player and returns this wizard instance.
        '''
        new_player = players.Player(id)
        self.players.append(new_player)
        new_wiz = wizard.Wizard(new_player)
        self.wizards.append(new_wiz)
        return new_wiz
Пример #29
0
def mapinit(skin1, skin2, nombre_perso, viemax, fondchoix, mapchoix):

    #copie image map
    mapcopie = Image.open(mapchoix)
    mapcopie.save("image/mapcopie.png", 'PNG')

    #Chargement du fond
    fond = pygame.image.load(fondchoix).convert()

    #Chargement de la montagne + mask + rect
    decor = pygame.sprite.Sprite()
    decor.image = pygame.image.load("image/mapcopie.png").convert_alpha()
    decor.rect = decor.image.get_rect()
    decor.rect.topleft = 0, 0
    decor.mask = pygame.mask.from_surface(decor.image)

    #Chargement du rectangle projectile + mask + rect
    projectile = pygame.sprite.Sprite()
    projectile.image = pygame.image.load(
        "image/armes/prj1.png").convert_alpha()
    projectile.rect = projectile.image.get_rect()
    projectile.mask = pygame.mask.from_surface(projectile.image)

    #generation des personnages :
    vies1 = [viemax] * nombre_perso  #on donne de la vie a chaque perso
    vies2 = [viemax] * nombre_perso

    rouge = [0] * nombre_perso
    bleu = [0] * nombre_perso
    #creer les objets personnages
    for rang in range(nombre_perso):
        #        rouge[rang] = players.Player(rang, decor, projectile, skin1, randint(100, 700), 50, viemax, "red", tombe1)
        rouge[rang] = players.Player(rang, decor, projectile, skin1,
                                     randint(20, 780), 0, viemax, "red",
                                     tombe1)
        bleu[rang] = players.Player(rang, decor, projectile, skin2,
                                    randint(20, 780), 0, viemax, "blue",
                                    tombe2)

    return fond, decor, rouge, bleu, vies1, vies2
Пример #30
0
def root(controllerID=None):
    request_ip = str(request.remote_addr)
    # Garbage Collection
    current_players.garbage_collector()
    if 'user' in session:
        if controllerID in current_players._players:
            if (session['user'] ==
                    current_players._players[controllerID]._cookie):
                # User is successfull validated
                pass
            else:
                # Someone is already controlling
                return redirect(url_for('play_menu'))
        else:
            current_players.add_player(controllerID,
                                       players.Player(request_ip))
            session['user'] = current_players._players[controllerID]._cookie
            return redirect('play/' + str(controllerID))
    else:
        current_players.add_player(controllerID, players.Player(request_ip))
        session['user'] = current_players._players[controllerID]._cookie
        return redirect('play/' + str(controllerID))

    controller_name = {
        0: "Base",
        1: "Shoulder",
        2: "Elbow",
        3: "Elbow Rotation",
        4: "Wrist",
        5: "Wrist Rotation",
        6: "Pincer"
    }
    if (controllerID in controller_name):
        controller_name = str(controller_name[controllerID])
    else:
        controller_name = None
    return (render_template('control.html',
                            ip=HOST_IP,
                            controllerID=controllerID,
                            controller_name=controller_name))