TinniT
TinniT

Reputation: 67

Guessing card game and help implementation

I am new to Python and I spent my first few dozens of hours with my online classes, homework projects and some documentation reading of course.

I almost finished one of my course. My final project there is to create easy card game which I already finished (code below). I would like to briefly explain what is my game about. Its easy "gamble" guessing card game for undefined amount of players. Players simply guess if next card is going to be lower or higher than previous one and win or loose they bet according to if they were right or no.

As far as I tested my code is working (I found one bug that I was not able to resolve so far - when all players lost in one round they are not all kicked from the game as they should be).

Anyway my main problem is that I don't know how to implement this to my code: At any point during the game, someone should be able to type "--help" to be taken to a screen where they can read the rules of the game and instructions for how to play. After they're done reading, they should be able to type "--resume" to go back to the game and pick up where they left off. (I found very much the same question here: Python simple card game -)

I googled a little bit and only one useful thing I found was help() function. I tried to implement it but I am not sure if its right choice how to do this --help and --resume flag (Is that even called flag? I am not 100% sure in all Python terminology)

My code is:

from random import shuffle, randrange


def cardDeck():  # create deck of the cards

    cardDeck = []
    for value in range(4):  # four sets of cards
        for i in range(2, 11):  # for number values
            if value == 0:
                cardDeck.append(str(i) + '♠')
            if value == 1:
                cardDeck.append(str(i) + '♣')
            if value == 2:
                cardDeck.append(str(i) + '♦')
            if value == 3:
                cardDeck.append(str(i) + '♥')
    figures = ['J', 'Q', 'K', 'A']
    for figure in figures:  # for four set of figures
        cardDeck.append(str(figure) + '♠')
        cardDeck.append(str(figure) + '♣')
        cardDeck.append(str(figure) + '♦')
        cardDeck.append(str(figure) + '♥')
    shuffle(cardDeck)
    return cardDeck


class Player: # define player class
    def __init__(self, nickname='Player', bankroll=100, value=0):
        self.nick = nickname
        self.bankroll = int(bankroll)
        self.value = value
        self.BetKind = ''
        self.amount = 0

    def __str__(self):
        return self.nick + ' plays'

    def win(self):

        self.bankroll += 2 * int(self.amount)

    def MassBet(self):

        for i in range(1000):
            self.amount = int(input('how much do you want to bet? '))
            if self.amount <= self.bankroll:
                break
            else:
                print('You can bet only your current bank!')
        for i in range(1000):
            self.BetKind = input('higher/lower [h/l] ')
            if self.BetKind == 'h' or self.BetKind == 'l':
                break
            else:
                print("Please enter only 'h' or 'l' ")
        self.bankroll -= int(self.amount)

    def GetValue(self, card):
        self.value = Values[card[0:-1]]


Deck = cardDeck()
Values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
          '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14} # define value of each card

PlayerList = []
NPlayers = int(input('How many players are going to play? ')) # Here you can define players
for i in range(NPlayers):
    print('Inicialization, player ', i+1)
    nickname = input('What is your nickname? ')
    bankroll = input('What is your bank? ')
    player = Player(nickname, bankroll)
    PlayerList.append(player)


oldCardsValues = []
oldCardsValues.append(Deck[-1]) # first card that everybody see
Deck.pop()
round = 0
while True:
    print('You bet againts: ', oldCardsValues[-1])
    for player in PlayerList:       # define kind of the bet for each player
        print(player.nick+', ', end = '')
        player.MassBet()
    DrawCard = Deck.pop()
    if NPlayers == 1:
        print('You draw: ', DrawCard)
    else:
        print('All players bet! Draw is: ', DrawCard)
    for player in PlayerList: # define if player won or lost
        player.GetValue(DrawCard)
        if player.BetKind == 'l':
            if Values[oldCardsValues[-1][0:-1]] > player.value:
                player.win()
                print(player.nick,'won! New bankroll: ', player.bankroll)
            elif Values[oldCardsValues[-1][0:-1]] < player.value:
                print(player.nick, 'lost! New bankroll: ', player.bankroll)
            else:
                print('Same card', player.nick, 'lost')
        elif player.BetKind == 'h':
            if Values[oldCardsValues[-1][0:-1]] < player.value:
                player.win()
                print(player.nick,'won! New bankroll: ', player.bankroll)
            elif Values[oldCardsValues[-1][0:-1]] > player.value:
                print(player.nick, 'lost! New bankroll: ', player.bankroll)
            else:
                print('Same card', player.nick, 'lost')
        print(player.bankroll)
        if player.bankroll <= 0: # if player run out of cash he is out
            print(player.nick, 'I am sorry, you run out of your cash. You are out.')
            PlayerList.remove(player)
    if len(PlayerList) == 0: # if there are no remaining players game is over
        print('No more players left. Game Over!')
        break

    round += 1
    MixCoeficcient = randrange(25, 35)
    if len(Deck) < MixCoeficcient: # create new deck in random interval of the remaining cards
        Deck = cardDeck()

    oldCardsValues.append(DrawCard)
    print('-'*40)

Please could you advice how to implement this --help and --resume to my game? Where to look or even tell me what I should look for?

Also if you would like to give me some feedback about code (what can be written in easier way or what I should avoid in my future coding carrier or anything else) I would be very grateful.

Upvotes: 4

Views: 460

Answers (1)

Captain Jack Sparrow
Captain Jack Sparrow

Reputation: 1111

In order to be able to get a "--help" or "--resume" prompt anywhere in the game, you need to use a special input function in every place you would normally use Python's regular input() function. Something like this:

def specialInput(prompt):
    action = input(prompt)
    if action == '--help':
        print("You need help")
        # Go to help screen
        showHelp()
        return specialInput(prompt)
    elif action == '--resume':
        print("You want to resume")
        # Resume the game
        # resume()
        return specialInput(prompt)
    else:
        return action

This function gets input using a given prompt and checks it to see if it equals either --help or --resume. If so, it will either show the help or continue the program's execution.
It isn't necessarily necessary(🤣) to have a resume() function, however. You could make showHelp() just print out some instructions, and then the program will automatically keep going(starting with the same input prompt where you left off) after the help has been printed.

The full program looks like this:

from random import shuffle, randrange


def showHelp():
    instructions = """\nPlayers simply guess if the next card is going to be lower or higher than previous one
and win or loose they bet according to if they were right or not.\n"""
    print(instructions)


def specialInput(prompt):
    action = input(prompt)
    if action == '--help':
        print("You need help")
        # Go to help screen
        showHelp()
        return specialInput(prompt)
    elif action == "--resume":
        print("You want to resume")
        # You can decide whether or not to do anything else here
        return specialInput(prompt)
    else:
        return action


def cardDeck():  # create deck of the cards
    cardDeck = []
    for value in range(4):  # four sets of cards
        for i in range(2, 11):  # for number values
            if value == 0:
                cardDeck.append(str(i) + '♠')
            if value == 1:
                cardDeck.append(str(i) + '♣')
            if value == 2:
                cardDeck.append(str(i) + '♦')
            if value == 3:
                cardDeck.append(str(i) + '♥')
    figures = ['J', 'Q', 'K', 'A']
    for figure in figures:  # for four set of figures
        cardDeck.append(str(figure) + '♠')
        cardDeck.append(str(figure) + '♣')
        cardDeck.append(str(figure) + '♦')
        cardDeck.append(str(figure) + '♥')
    shuffle(cardDeck)
    return cardDeck


class Player:  # define player class
    def __init__(self, nickname='Player', bankroll=100, value=0):
        self.nick = nickname
        self.bankroll = int(bankroll)
        self.value = value
        self.BetKind = ''
        self.amount = 0

    def __str__(self):
        return self.nick + ' plays'

    def win(self):

        self.bankroll += 2 * int(self.amount)

    def MassBet(self):

        for i in range(1000):
            self.amount = int(specialInput('how much do you want to bet? '))
            if self.amount <= self.bankroll:
                break
            else:
                print('You can bet only your current bank!')
        for i in range(1000):
            self.BetKind = specialInput('higher/lower [h/l] ')
            if self.BetKind == 'h' or self.BetKind == 'l':
                break
            else:
                print("Please enter only 'h' or 'l' ")
        self.bankroll -= int(self.amount)

    def GetValue(self, card):
        self.value = Values[card[0:-1]]


Deck = cardDeck()
Values = {'2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
          '8': 8, '9': 9, '10': 10, 'J': 11, 'Q': 12, 'K': 13, 'A': 14}  # define value of each card

PlayerList = []
NPlayers = int(specialInput('How many players are going to play? '))  # Here you can define players
for i in range(NPlayers):
    print('Inicialization, player ', i + 1)
    nickname = specialInput('What is your nickname? ')
    bankroll = specialInput('What is your bank? ')
    player = Player(nickname, bankroll)
    PlayerList.append(player)

oldCardsValues = [Deck[-1]]
Deck.pop()
print(Deck[45:])
round = 0
while True:
    print('You bet againts: ', oldCardsValues[-1])
    for player in PlayerList:  # define kind of the bet for each player
        print(player.nick + ', ', end='')
        player.MassBet()
    DrawCard = Deck.pop()
    if NPlayers == 1:
        print('You draw: ', DrawCard)
    else:
        print('All players bet! Draw is: ', DrawCard)
    for player in PlayerList:  # define if player won or lost
        player.GetValue(DrawCard)
        if player.BetKind == 'l':
            if Values[oldCardsValues[-1][0:-1]] > player.value:
                player.win()
                print(player.nick, 'won! New bankroll: ', player.bankroll)
            elif Values[oldCardsValues[-1][0:-1]] < player.value:
                print(player.nick, 'lost! New bankroll: ', player.bankroll)
            else:
                print('Same card', player.nick, 'lost')
        elif player.BetKind == 'h':
            if Values[oldCardsValues[-1][0:-1]] < player.value:
                player.win()
                print(player.nick, 'won! New bankroll: ', player.bankroll)
            elif Values[oldCardsValues[-1][0:-1]] > player.value:
                print(player.nick, 'lost! New bankroll: ', player.bankroll)
            else:
                print('Same card', player.nick, 'lost')
        print(player.bankroll)
        if player.bankroll <= 0:  # if player run out of cash he is out
            print(player.nick, 'I am sorry, you run out of your cash. You are out.')
            PlayerList.remove(player)
    if len(PlayerList) == 0:  # if there are no remaining players game is over
        print('No more players left. Game Over!')
        break

    round += 1
    print('current deck len: ', len(Deck), 'current round: ', round)
    MixCoeficcient = randrange(25, 35)
    if len(Deck) < MixCoeficcient:  # create new deck in random interval of the remaining cards
        Deck = cardDeck()

    oldCardsValues.append(DrawCard)
    print('-' * 40)

A little bit of feedback: You might wanna print the players bankroll each time they bet so that they know how much dough they have to deal with.

Upvotes: 3

Related Questions