Search code examples
pythonooppoker

I'm trying to invoke an object within a method in a different object


Im working on a simple poker game just to improve my OOP experience, i ran into an error that might be beyond my knowledge.

The program goes like this, i have a class called Deck() which is of course the deck, a class called player and a class called table. In the player class i have couple of methods but i'm only gonna name what is necessary for the sake of keeping this as short as possible. I have the following methods (in the player class) bet(), call() fold(), all_in() and player_choice(). The first four method i named are all invoked by the player_choice method(). However the problem is in the bet(), all_in() and call method. the following methods looks like this

        def all_in(self):
    table.table_money += self.money
    self.money = 0
    print('{} went all in!').format(self.name)

def cal(self, last_bet):
    if last_bet > self.money:
        while True:
            res = input('You dont have enough money to call.\tyou have=> {}\nDo you want to go all in?\ty/n\n>>> ').format(str(self.money))
            if res.lower() == 'y':
                self.all_in()
                break
            elif res.lower() == 'n':
                self.fold()
                break
            else:
                print('Invalid input. Try again...')
    else:
        table.table_money += self.money - last_bet
        self.money -= last_bet
        print('{} called.').format(self.name)


def bet(self, last_bet):
    res = int(input('Enter bet below.\t must be over {}\n>>> '.format(str(last_bet))))
    table.latest_bet += res
    table.table_money += res
    self.money -= res
    print('{} has bet {}$').format(self.name, str(res))

The problem is that when i call one of these methods and the method is in the process of subtracting the players money and adding it to the table.table_money() (as shown in the code above) thats when i get a NameError saying 'table' is not defined.

here is the Table() class:

    class Table():
def __init__(self):
    self.table_money = 0
    self.latest_bet = 0

    if players == '':
        print('Table is empty!')
    else:
        print(str(len(players)) + ' players on the table.')

def list_table(self):
    for i in players:
        print(i.__str__())

I know what you might be thinking that i typed table instead of Table. but he is he thing, when i run the code in the main() function i initialize a Table object into a variable called table which is supposed to be the same variable as the one being called by the Player() class methods.

Here is a short view of the main() function:

    def main():
while welcome():
    rond = 1
    while rond <= 5:
        table = Table()
        deck = Deck()
        deck.deal()
        user = players[0]
        user.list_hand()
        user.player_choice(table.latest_bet)
        break
    break

the structure of the problem is like this:

  1. first i define the player class.
  2. 2nd i define the table.
  3. 3rd i define main().

This is the output of the error:

    Traceback (most recent call last):
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 161, in <module>
    main()
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 157, in main
    user.player_choice(table.latest_bet)
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 38, in player_choice
    self.cal(last_bet)
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 71, in cal
    table.table_money += self.money - last_bet
    NameError: name 'table' is not defined

If i didn't include enough details about the program let me know i will share more if needed. I apologize if i didn't explain all this in the best way and if the post is too long. I am more then grateful for any comment. Thanks for reading.

Full code:

    import random as r

    suits = ['H','C','S','D']
    values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
    players = []

    class Card():
        def __init__(self, suit, value):
            self.suit = suit
            self.value = value

        def valu(self):
            return self.value + self.suit

    class Player():
        def __init__(self, name, money):
            global players
            self.name = name
            self.money = money
            print(self.name+ ' joined the table!')
            players.append(self)
            self.hand = []

        def __str__(self):
            return '{}: {}'.format(self.name, str(self.money))

        def add_to_hand(self, cards):
            self.hand.append(cards)

        def list_hand(self):
            for i in self.hand:
                print(i)

        def player_choice(self, last_bet):
            while True:
                resu = input('c - Call | b - bet | a - all in | f - fold\n>>> 
    ').lower()
            if resu == 'c':
                self.cal(last_bet)
                break
            elif resu == 'b':
                self.bet(last_bet)
                break
            elif resu == 'a':
                self.all_in()
                break
            elif resu == 'f':
                self.fold()
                break
            else:
                print('Invalid input. Try again...')


        def all_in(self):
            table.table_money += self.money
            self.money = 0
            print('{} went all in!').format(self.name)

        def cal(self, last_bet):
            if last_bet > self.money:
                while True:
                    res = input('You dont have enough money to call.\tyou have=> {}\nDo you want to go all in?\ty/n\n>>> ').format(str(self.money))
                    if res.lower() == 'y':
                    self.all_in()
                    break
                    elif res.lower() == 'n':
                    self.fold()
                    break
            else:
                print('Invalid input. Try again...')
        else:
            table.table_money += self.money - last_bet
            self.money -= last_bet
            print('{} called.').format(self.name)


    def bet(self, last_bet):
        res = int(input('Enter bet below.\t must be over {}\n>>> '.format(str(last_bet))))
        table.latest_bet += res
        table.table_money += res
        self.money -= res
        print('{} has bet {}$').format(self.name, str(res))

    def fold(self):
        players.remove(self)
        print('{} has folded.').format(self.name)


    class Table():
        def __init__(self):
            self.table_money = 0
            self.latest_bet = 0

            if players == '':
                print('Table is empty!')
            else:
                print(str(len(players)) + ' players on the table.')

        def list_table(self):
            for i in players:
            print(i.__str__())




    class Deck():
        def __init__(self):
            self.cards = []

            for suit in suits:
                for value in values:
                   self.cards.append(Card(suit, value).valu())

            r.shuffle(self.cards)

        def show_deck(self):
            return self.cards

        def shuffle_d(self):
            r.shuffle(self.cards)

        def deal(self):
            for p in players:
                for c in range(0, 1):
                    p.add_to_hand((self.cards.pop(), self.cards.pop()))

    #The welcome function is not a method for any of the classes above 

    def welcome():
        global players
print('''
        Welcome to the poker table. 
        q - Quit
        s - Take a seat
''')
res = ''
while res != 'q' or 's':
    res = input('>>> ')
    if res == 'q':
        return False
    elif res == 's':
        name = input('Enter your name: ')
        money = int(input('Enter how much money you wish to have(max 500$): '))
        Player(name, money)
        return True
    else:
        print('Invalid input. q - Quit\ts - Take a seat')



    def main():
        while welcome():
        rond = 1
            while rond <= 5:
                table = Table()
                deck = Deck()
                deck.deal()
                user = players[0]
                user.list_hand()
                user.player_choice(table.latest_bet)
                break
            break

    main()

Try to ignore the miss


Solution

  • tables is a local variable in the main() function. You should add it as an attribute of the player class.

    def go_to_table(self, table):
        self.table = table
    

    Then all the methods should use self.table instead of just table. In main, you do:

    def main():
        while welcome():
            rond = 1
            while rond <= 5:
                table = Table()
                deck = Deck()
                deck.deal()
                user = players[0]
                user.go_to_table(table)
                user.list_hand()
                user.player_choice(table.latest_bet)
                break
            break