简体   繁体   中英

Append every 2nd element of list (Python)

I am working on a card game challenge. I made 3 classes: a "Card:" class, a "Deck:" class, and a "Player:" class.

In the deck class is a function to create a deck(list) full of cards in the player class is an empty list (eg "self.hand = []")

To save on space, I won't show all the classes' full codes, but here are the key pieces:

In the Deck class:

# Deal one card
def deal_one(self):
    return self.deck.pop(0)

In the Player class:

# Take a card:
def take(self, new_cards):
    if type(new_cards) == type([]):
        self.hand.extend(new_cards)
    else:
        self.hand.append(new_cards)

It's easy enough to create 2 players and split the deck down the middle between them as follows:

for card in range(26):
    pl_1.take(mydeck.deal_one())
    pl_2.take(mydeck.deal_one())

but as a challenge, I wanted to deal every second card to each player. I tried this:

for card in mydeck.deck[::2]:
    pl_1.take(mydeck.deal_one())

But this returned the same result as the first code (first half of deck given to player 1). Can anyone help with a fix? Thanks!

In your deck class, add a function that accepts a List of players and use a modulo to alternate between players.

Bonus: accept an int to break the for loop after maximum cards per player is reached.

def takeAlternate(players : list, maxCardsPerPlayer : int = 0):
      numPlayers = len(players)
      currentCard = 0
      currentPlayer = 0
      for card in self.deck:
        currentPlayer = currentCard % numPlayers
        # move card from deck to player
        players[currentPlayer].takeCard(card)
        self.deck.remove(card)
        currentCard += 1
        if maxCardsPerPlayer != 0 and currentCard >= maxCardsPerPlayer * numPlayers:
            break

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM