Python Referencing Object Inside Object Incorrectly - python

I have 2 python classes: Player, and Board. The board contains a dict with "A1" reference style for spaces.
player.py's Player class:
from board import Board
class Player:
def __init__(self):
self.name = input("Name: ")
self.board = Board(3, ["A", "B", "C"])
board.py's Board class:
class Board:
EMPTY = "0"
spaces = {}
def __init__(self, size, letters):
for let in letters:
for num in range(1, size + 1):
self.spaces["{}{}".format(let, num)] = self.EMPTY
def place_piece(self, spot):
self.spaces[spot] = "X"
def display_board(self):
for let in letters:
for num in range(1, size + 1):
print("\n" + self.spaces["{}{}".format(let, num)]
When Player is instantiated, it creates a Board object inside.
2 players are created, and each is added to the list players[]. Each player's turn is selected with a simple 1/0 variable called current_player.
from player import *
from board import *
current_player = 1
players = []
player_1 = Player()
player_2 = Player()
players.append(player_1)
players.append(player_2)
while True:
# Switches players
current_player = abs(current_player - 1)
# Prints the current player's name
print(players[current_player].name)
# Calls some method which should alter the current player's board
players[current_player].board.place_piece(input("> "))
# Calls some method which should show the current player's board
players[current_player].board.show_board()
Obviously, very simplified. The name prints out correctly every single time. The board, however, only uses the first player's board for both players. I know it's working because the players' name prints correctly.
The issue persists even if the boards are created separately and placed in their own list.
What am I doing wrong?

As it is written now the code posted shouldn't be working. The two methods in Board, place_piece and display_board, need to accept 'self' as a first argument.
Assuming this is a typo here's what's happening. The class Board is created with a class member spaces. Each time you're referencing self.spaces in an object, it is not found in the object is instead looked up in the class. Meaning you're using the same dict for all object of the class Board. Instead, to create a regular member place the declaration in the init method as you do in the Player class:
class Board:
EMPTY = "0"
# Remove spaces = {}
def __init__(self, size, letters):
self.spaces = {}
...
Finally, since you're using Python 2x please let me encourage you to always use new style classes (i.e. write class Board(object)). See What is the difference between old style and new style classes in Python?

Related

Error when calling a method from separate Python file

I am trying to make a Tic Tac Toe game in Python, where I use two separate files. Each has different code and separate classes, which I am trying to call. However, each time I try to do so, I receive this error:
def __init__(self, letter): super().__init__(letter)
TypeError: object.__init__() takes exactly one argument (the instance to initialize)
Why does this happen? I have imported the right files (as below) and used the code (under that) to call it.
from player import NormalPlayer, ComputerPlayer
--
if __name__ == "__main__":
x_player = NormalPlayer("X")
o_player = ComputerPlayer("O")
ttt = TicTacToe()
play(ttt,
x_player,
o_player,
print_game = True)
I haven't included it, but if you need me to provide all my code from both files, please let me know. If you know what my error is from this code, however, please let me know. Thank you!
# Recognise the player as an object, with a specific letter (X or O)
class Player:
# Set the player's letter (noughts or crosses)
def __init__(self, letter): self.letter = letter
# Turn-based system
def get_move(self, game): pass
# Use the inheritance of classes to create a computer player that uses the 'Player' class
class ComputerPlayer:
# Set the computer's letter with teh super class
def __init__(self, letter): super().__init__(letter)
# Turn-based system, get a random move from all open possibilities
def get_move(self, game):
choice = random.choice(game.open_moves())
return choice
# Use the inheritance of classes for the user object that uses the 'Player' class
class NormalPlayer:
# Set the user's letter with the super class
def __init__(self, letter): super().__init__(letter)
# Turn-based system, get the player's movement choice
def get_move(self, game):
# Player's choice must first be verified
verified = False
# The spot value of the move the player wants to make
value = None
# Ask for the player's move
while not verified:
choice = input(self.letter + "\s turn. Which spot do you want to play? ")
# Check if the player's choice is valid...
try:
# Turn the input into an integer
value = int(choice)
# If the spot value is not available, catch the error and tell the player
if value not in game.open_moves():
raise ValueError
# ...if it is, then announce it
except ValueError:
# If the choice was invalid, have the player decide their move again
print("The spot value is not valid. Please choose another spot.")
return value
You're not specifying which class you are inheriting from. To use inheritance, you do class ClassName(ClassToInheritFrom).
So your file would look like:
# Recognise the player as an object, with a specific letter (X or O)
class Player:
# Set the player's letter (noughts or crosses)
def __init__(self, letter): self.letter = letter
# Turn-based system
def get_move(self, game): pass
# Use the inheritance of classes to create a computer player that uses the 'Player' class
class ComputerPlayer(Player):
# Set the computer's letter with teh super class
def __init__(self, letter): super().__init__(letter)
# Turn-based system, get a random move from all open possibilities
def get_move(self, game):
choice = random.choice(game.open_moves())
return choice
# Use the inheritance of classes for the user object that uses the 'Player' class
class NormalPlayer(Player):
# Set the user's letter with the super class
def __init__(self, letter): super().__init__(letter)
# Turn-based system, get the player's movement choice
def get_move(self, game):
# Player's choice must first be verified
verified = False
# The spot value of the move the player wants to make
value = None
# Ask for the player's move
while not verified:
choice = input(self.letter + "\s turn. Which spot do you want to play? ")
# Check if the player's choice is valid...
try:
# Turn the input into an integer
value = int(choice)
# If the spot value is not available, catch the error and tell the player
if value not in game.open_moves():
raise ValueError
# ...if it is, then announce it
except ValueError:
# If the choice was invalid, have the player decide their move again
print("The spot value is not valid. Please choose another spot.")
return value

How do I make my (derived?) python instance attributes "self-update" based on alterations to other same-instance attributes?

I know that I have a misunderstanding of how Python attributes work because I'm here writing this problem, but I don't know exactly what I'm misunderstanding. I'm trying to get
self.card = self.hand[self.card_number].split()
self.card_val = deck.ranks.get(self.card[0])
to attain their values based on self.hand, which I pass to __init__ upon instantiation. Throughout the game I am altering .hand, and I want .card & .card_val to change every time I change .hand, instead of having to tell it to do that elsewhere (outside of the attribute definitions). I know there is a way to do this, or at least I think there is, and by that I mean simply by defining their values as inherited based on whatever .hand is at any given time, without calling an internal or external function.
In the posted code, I have altered it to work as the game instructions require, using...
def get_card_vals(p1, p2):
for player in [p1, p2]:
player.card = player.hand[player.card_number].split()
player.card_val = deck.ranks.get(player.card[0])
print("{a} vs. {b}".format(a = p1.card, b = p2.card))
print("---------------------------")
...but that's what I want to change. I want what that function is doing to be executed more concisely inside of the attribute definitions upon handling of the instance. Basically my question is why can't these two attributes get their values directly from the first attribute that I define via "hand" passed to the init?
Any help would be appreciated, and more importantly, I think more than just solutions, it would help me even more to understand what I am misunderstanding about how attributes, instances, and instantiation and all that works so that I know where my thinking is wrong. Thanks!
import random
from random import shuffle
from collections import deque
class Deck():
def __init__(self):
self.ranks = {"Ace":14, "King":13, "Queen":12, "Jack":11, "10":10, "9":9, "8":8, "7":7, "6":6, "5":5, "4":4, "3":3, "2":2}
self.suites = ["Heart", "Diamond", "Spade", "Club"]
self.cards = []
def create_cards(self):
for suite in self.suites:
for key in self.ranks.keys():
self.cards.append(key + " " + suite)
def shuffle(self):
random.shuffle(deck.cards)
deck = Deck()
deck.create_cards()
deck.shuffle()
class Player():
def __init__(self, hand):
self.name = "name"
self.hand = hand
self.card_number = 1
self.card = self.hand[self.card_number].split()
self.card_val = deck.ranks.get(self.card[0])
def war(bool, p1, p2):
if bool == True:
for player in [p1, p2]:
player.card_number = 4
else:
for player in [p1, p2]:
player.card_number = 0
p2 = Player(deque(deck.cards[::2]))
p1 = Player(deque(deck.cards[1::2]))
p2.name = "The Computer"
def get_card_vals(p1, p2):
for player in [p1, p2]:
player.card = player.hand[player.card_number].split()
player.card_val = deck.ranks.get(player.card[0])
print("{a} vs. {b}".format(a = p1.card, b = p2.card))
print("---------------------------")
def cant_war_lose(winner, loser):
print("{a} doesn't have enough cards to go to war, so {b} wins the Battle!".format(a = loser, b = winner))
def battle_win(winner, loser):
print("{a} has run out of cards, therefore {b} has won via Battle!".format(a = loser, b = winner))
def play_cards(p1, p2):
war(False, p1, p2)
get_card_vals(p1, p2)
if p1.card_val > p2.card_val:
p1.hand.append(p2.hand.popleft())
p1.hand.rotate(-1)
elif p1.card_val == p2.card_val:
if len(p1.hand) < 5 or len(p2.hand) < 5:
if len(p1.hand) > len(p2.hand):
cant_war_lose(p1.name, p2.name)
else:
cant_war_lose(p2.name, p1.name)
return 0
else:
input("War is inititated! Press Enter to continue!")
print("---------------------------")
war(True, p1, p2)
get_card_vals(p1, p2)
if p1.card_val > p2.card_val:
for i in range(0,5):
p1.hand.append(p2.hand.popleft())
p1.hand.rotate(-5)
elif p1.card_val < p2.card_val:
for i in range(0,5):
p2.hand.append(p1.hand.popleft())
p2.hand.rotate(-5)
else:
p1.hand.rotate(-1)
p2.hand.rotate(-1)
elif p1.card_val < p2.card_val:
p2.hand.append(p1.hand.popleft())
p2.hand.rotate(-1)
if len(p1.hand) != 0 and len(p2.hand) != 0:
input("After the last round of Battle, {a} now has {b} cards, and {c} now has {d} cards! Press Enter to continue!".format(a = p1.name, b = len(p1.hand), c = p2.name, d = len(p2.hand)))
print("---------------------------")
else:
if len(p1.hand) > len(p2.hand):
battle_win(p1.name, p2.name)
else:
battle_win(p2.name, p1.name)
return 0
def game_run():
run = 1
p1.name = input("Player 1's name? ")
print("---------------------------")
while run == 1:
if play_cards(p1, p2) == 0:
run = 0
game_run()
You can use the property decorator to create a calculated property
class Player():
def __init__(self, hand):
self.name = "name"
self.hand = hand
self.card_number = 1
#property
def hand(self):
return self._hand
#hand.setter
def hand(self, value):
self._hand = value
self.card = self._hand[self.card_number].split()
self.card_val = deck.ranks.get(self.card[0])
What you misunderstand is variables, not instances. For instance, the attribute card is a scalar variable attached to the instance. Assigning to it with
self.card = <blah>
does not bind it to blah for constant recomputation. This is a value assignment, not a memory mapping. If you want that long-term binding, you must either write the maintenance routine yourself -- which you've already done, in a way, with the consistent recomputation -- or you must assign a mutable reference to self.card, so that card refers to teh same object as the expression you created.
Given that you are consistently rotating and altering the hand, this is not feasible in your design. Instead, simply write an access routine, perhaps get_next_card(hand), which will rotate the hand, extract the card, and return the desired rank and suit.
If you plan to program more card games, you will also find it handy to define a class card and class hand, with appropriate support routines. Maintain the card as a pair of integers; convert to strings only for printing.
Does that get you moving?
For anyone who wanted to compare a before and after of the problem & final solution, below is the working code for my specific issue. All I had to do was convert self.card and self.card_val to a calculated property. By passing in hand, and subsequently handling only hand, self.card & self.card_val are calculated, since every time I handle the instance of the class (by handling hand), these "method attributes" are being called and altered. Thanks for the input, guys!
class Player():
def __init__(self, hand):
self.name = "name"
self.card_number = 1
self.hand = hand
#property
def card(self):
return self.hand[self.card_number].split()
#property
def card_val(self):
return deck.ranks.get(self.card[0])

Inheriting class attributes without declaring attributes or better OOP

I am attempting to construct classes to play out a game of MTG (A card game). I have three relevant classes: MTGGame(...), MTGCard(...), and AbilityList(). An object of MTGGame has several attributes about the player (turn, mana,..., deck).
A player must have a deck of cards to play, so I create a list of MTGCard objects for each player that is a deck, and create an MTGGame object for each from the respective decks. The cards have abilities, and when creating the cards I store abilities as functions/params into each MTGCard. However, I need the abilities to inherit and access methods/attributes from MTGGame and update them, but if I use super().__init__, then I will need to call my deck as a parameter for AbilityList when making MTGCards, which I wouldn't have yet.
Can this be achieved? If not, any suggestions improving my OOP logic to achieve this task?
I am aware that I can do something like this:
class MTGGame():
def __init__(self, deck, turn = 0, mana = 0, lifeTotal = 20, cavalcadeCount = 0, hand = [], board = []):
self.turn = turn
self.mana = mana
self.lifeTotal = lifeTotal
...
def gainLife(self, lifeGained):
self.lifeTotal = self.lifeTotal +lifeGained
def combatPhase(self):
for card in self.board:
card.attackingAbility()
class MTGCard():
def __init__(self, name, CMC, cardType, power, toughness, castedAbility, attackingAbility, activatedAbility, canAttack = False):
....
self.attackingAbility = attackingAbility
Class abilityList():
def healersHawkAbility(self, lifeAmt):
MTGGame.gainLife(lifeAmt)
But this would affect all instances of MTGGame, not the specific MTGGame object this would've been called from. I'd like it to simply update the specific object in question. I'd like to do something like this but I don't know how abilityList methods could access MTGGame attributes/methods ('AbilityList' object has no attribute 'gainLife'):
Class abilityList():
def healersHawkAbility(self, lifeAmt):
#How do I access methods/attributes in MTGGame from here? self?
self.gainLife(lifeAmt)
aL = abilityList()
#One example card:
card1 = MTGCard("Healers Hawk",1,'Creature',1,1, aL.nullAbility(), aL.healersHawkAbility, aL.nullAbility())
whiteDeck = [list of constructed MTGCard() objects, card1, card2,...,cardLast]
player1 = MTGGame(whiteDeck)
...
#Call the ability in a method contained in MTGGame:
player1.combatPhase()
#Would call something like this inside
card.attackingAbility()
#Which may refer to card.healersHawkAbility() since we stored healersHawkAbility() as an attribute for that MTGCard,
#and would declare gainLife(), which refers to self.lifeTotal or player1.lifeTotal in this case.
This is an excellent start and clearly you have already thought a lot of this through. However, you haven't thought through the relationship between the classes.
First thing to note:
MTGGame.gainLife(lifeAmt) is a method call accessed via the class rather than an instance. This means that the self paramter is not actually filled in i.e. you will get an error becuase your method expects 2 arguments but only receive one.
What you perhaps meant to do is the following:
class MTGGame:
lifeTotal = 20 # Notice this is declared as a class variable
def __init__(self, ...):
...
#classmethod
def healersHawkAbility(cls, lifeGained):
cls.lifeTotal = cls.lifeTotal + lifeGained
However, this requires class variables which here defeats the point of having an instance.
Your naming throughout the program should suggest that your classes are a little off.
For instance player1 = MTGGame(). Is player a game? No, of course not. So actually you might want to rename your class MTGGame to Player to make it clear it refers to the player, not the game. A seperate class called MTGGame will probably need to be created to manage the interactions between the players e.g. whose turn it is, the stack holding the cards whilst resolving.
The main focus of your question: how to deal with the cards accessing the game/player object.
Cards should be able to access instances of the player and game classes, and if the player has a is_playing attribute, the card should not have this. The rule of thumb for inheritance is 'is a'. Since card 'is not a' player, it should not inherit from it or MTGGame. Instead, card should be like this for example:
game = RevisedMTGGame()
player1 = Player()
player2 = Player()
class Card:
def __init__(self, name, text, cost):
self.name = name
self.text = text
self.cost = cost
self.owner = None
self.game = None
class Creature(Card):
def __init__(self, name, text, cost, power, toughness):
super().__init__(self, name, text, cost)
self.power = power
self.toughness = toughness
def lifelink(self):
self.owner.heal(self.power) # NOTE: this is NOT how I would implement lifelink, it is an example of how to access the owner
healersHawk = Creature("Healer's Hawk", "Flying, Lifelink", 1, 1, 1)
healersHawk.game = game
healersHawk.owner = player1
You can see from this incomplete example how you can set up your cards easily, even with complex mechanics, and as the base classes have been defined you can avoid repitition of code. You might want to look into the event model in order to implement the lifelink mechanic, as an example. I wish you luck in continuing your game!

Is there a way to fix Name Error due to scope?

I have a function that creates a player object but when referencing the object, I get a NameError. I think it is happening due to local scope but global should fix it...
I just started out OOP and this code is working in the python shell but it is not working in script mode.
endl = lambda a: print("\n"*a)
class Score:
_tie = 0
def __init__(self):
self._name = ""
self._wins = 0
self._loses = 0
def get_name(self):
print
self._name = input().upper()
def inc_score(self, wlt):
if wlt=="w": self._wins += 1
elif wlt=="l": self._loses += 1
elif wlt=="t": _tie += 1
else: raise ValueError("Bad Input")
def player_num(): #Gets number of players
while True:
clear()
endl(10)
print("1 player or 2 players?")
endl(5)
pnum = input('Enter 1 or 2: '.rjust(55))
try:
assert int(pnum) == 1 or int(pnum) == 2
clear()
return int(pnum)
except:
print("\n\nPlease enter 1 or 2.")
def create_player(): #Creates players
global p1
p1 = Score()
yield 0 #stops here if there is only 1 player
global p2
p2 = Score()
def pr_(): #testing object
input(p1._wins)
input(p2._wins)
for i in range(player_num()):
create_player()
input(p1)
input(p1._wins())
pr_()
wherever I reference p1 I should get the required object attributes but I'm getting this error
Traceback (most recent call last):
File "G:/Python/TicTacTwo.py", line 83, in <module>
input(p1)
NameError: name 'p1' is not defined
Your issue is not with global but with the yield in create_player(), which turns the function into a generator.
What you could do:
Actually run through the generator, by executing list(create_player()) (not nice, but works).
But I suggest you re-design your code instead, e.g. by calling the method with the number of players:
def create_player(num): #Creates players
if num >= 1:
global p1
p1 = Score()
if num >= 2:
global p2
p2 = Score()
If you fix this issue, the next issues will be
1) input(p1) will print the string representation of p1 and the input will be lost, you probably want p1.get_name() instead.
2) input(p1._wins()) will raise TypeError: 'int' object is not callable
I will redesign the app to introduce really powerful python constructs that may help you when getting into OOP.
Your objects are going to represent players, then don't call them Score, call them Player.
Using _tie like that makes it a class variable, so the value is shared for all the players. With only two participants this may be true but this will come to hurt you when you try to extend to more players. Keep it as a instance variable.
I am a fan of __slots__. It is a class special variable that tells the instance variables what attributes they can have. This will prevent to insert new attributes by mistake and also improve the memory needed for each instance, you can remove this line and it will work but I suggest you leave it. __slots__ is any kind of iterable. Using tuples as they are inmutable is my recomendation.
Properties are also a really nice feature. They will act as instance attribute but allow you to specify how they behave when you get the value (a = instance.property), assign them a value (instance.property = value), or delete the value (del instance.property). Name seems to be a really nice fit for a property. The getter will just return the value stored in _name, the setter will remove the leading and trailing spaces and will capitalize the first letter of each word, and the deletter will set the default name again.
Using a single function to compute a result is not very descriptive. Let's do it with 3 functions.
The code could look like this:
# DEFAULT_NAME is a contant so that we only have to modify it here if we want another
# default name instead of having to change it in several places
DEFAULT_NAME = "Unknown"
class Player:
# ( and ) are not needed but I'll keep them for clarity
__slots__ = ("_name", "_wins", "_loses", "_ties")
# We give a default name in case none is provided when the instance is built
def __init__(self, name=DEFAULT_NAME):
self._name = name
self._wins = 0
self._loses = 0
self._ties = 0
# This is part of the name property, more specifically the getter and the documentation
#property
def name(self):
""" The name of the player """
return self._name
# This is the setter of the name property, it removes spaces with .strip() and
# capitalizes first letters of each word with .title()
#name.setter
def name(self, name):
self._name = name.strip().title()
# This is the last part, the deleter, that assigns the default name again
#name.deleter
def name(self):
self._name = DEFAULT_NAME
def won(self):
self._wins += 1
def lost(self):
self._loses += 1
def tied(self):
self._ties += 1
Now that's all we need for the player itself. The game should have a different class where the players are created.
class Game:
_min_players = 1
_max_players = 2
def __init__(self, players):
# Check that the number of players is correct
if not(self._min_players <= players <= self._max_players):
raise ValueError("Number of players is invalid")
self._players = []
for i in range(1, players+1):
self._players.append(Player(input("Insert player {}'s name: ".format(i))))
#property
def players(self):
# We return a copy of the list to avoid mutating the inner list
return self._players.copy()
Now the game would be created as follows:
def new_game():
return Game(int(input("How many players? ")))
After that you would create new methods for the game like playing matches that will call the players won, lost or tied method, etc.
I hope that some of the concepts introduced here are useful for you, like properties, slots, delegating object creation to the owner object, etc.

Problems with switching players and keeping track of each of their score when making a Cricket game

I want to create a very simple text-based Cricket game. But I am quite stuck.
from random import randint
class Player():
def __init__(self):
pass
def run(self, player, score):
# some code that will take a player and a score and associate that
# score with the player and store it (in a dictionary)
def switch(self, player):
# some code that will take a player name and change the current
# batsmen to the next one, for e.g this should change "a" to "b" or
# vice versa but not "c"
team_players = ["a", "b", "c"]
player = Player()
position = 0
run = randint(0,6)
current_batsman = team_players[position]
if run%2 == 0: # which means run is even
player.run(current_batsman, run) # sending the current player and their run
else: # if the run is odd
player.run(current_batsman, run) # still doing the same stuff as before but...
player.switch(current_batsman) # the current batsman should now be switched
Maybe tweaking position in the Player class somehow might help.
I hope my code explains my problem thoroughly. And by the way, in Cricket scores are called run and if a player (batsman) makes an odd run (1, 3, 5) the next batsman comes to play, and there are only two batsmen in the field until one gets out but I want my game to be really simple, for now. Any help is greatly appreciated. Thanks.
I don't know Cricket's rules but in class Player I would keep player's name and his score. It could have also function run() which adds random value to his score (or create method with parameter - value which you want to add to score)
class Player():
def __init__(self, name):
self.name = name
self.score = 0
def run(self):
self.score += random.randint(0, 6)
def __str__(self):
return "{} (score: {})".format(self.name, self.score)
I also added __str__ to easily display player.
Next I would create class Team which keeps all players, keep information which player is current batsman, switch batsman, and use run() for current batsman
class Team():
def __init__(self, players):
self.players = players
self.current_batsman = 0
self.current_run = 0
def set_next_batsman(self):
self.current_batsman += 1
if self.current_batsman >= len(self.players):
self.current_batsman = 0
def get_current_batsman(self):
return self.players[self.current_batsman]
def run(self):
self.players[self.current_batsman].run()
if self.current_run % 2 != 0:
self.set_next_batsman()
self.current_run += 1
def __str__(self):
return "Player: " + ", ".join(str(p) for p in self.players)
def total_score(self):
return sum(p.score for p in self.players)
And then two teams can play:
team1 = Team( [Player("a"), Player("b"), Player("c")] )
team2 = Team( [Player("x"), Player("y"), Player("z")] )
print('Team1:', team1)
print('Team2:', team2)
for number in range(1, 5):
print('Round:', number)
print('Team1 current batsman:', team1.get_current_batsman())
team1.run()
print('Team2 current batsman:', team2.get_current_batsman())
team2.run()
print('Team1:', team1)
print('Team2:', team2)
print('Team1 total score:', team1.total_score())
print('Team2 total score:', team2.total_score())

Categories