Where did it go wrong in my code? - python

class Player:
def __init__(self):
self.speed
self.hp
def Berserker(self):
self.speed == 12
self.hp == 6
print("Berserkers stats are: " + Berserker())
So, What have I done wrong? As you can see, I'm very new to Python.
The error I'm getting is: TypeError: Berserker() missing 1 required positional argument: 'self'

You're missing quite a few things, but I'll help you out!
Your __init__ function doesn't do anything. Let's give it some base stats. I'll say that a Player's default speed and health will be 10 and 100, respectively. Then we'll make Berserker a subclass of Player (I think that's what you were going for?). And lastly, I'll give Player a method that will allow you to get a string-formatted output for its values.
First, the new Player:
class Player:
def __init__(self, speed=10, health=100):
self.speed = speed
self.health = health
def __str__(self):
return "A player with speed {} and health {}.".format(self.speed, self.health)
And now for the Berserker. I'll give it a base speed of 15 and health of 85. (Obviously the specifics are up to you!)
class Berserker(Player):
def __init__(self):
super().__init__(speed=15, health=85)
Lastly, we can create these and print the value. I'll make a couple different versions so you can see how it works. (And I'll use the regular Python interpreter for this).
>>> p1 = Player()
>>> p2 = Player(7, 120)
>>> b = Berserker()
>>> print(p1)
A player with speed 10 and health 100.
>>> print(p2)
A player with speed 7 and health 120.
>>> print(b)
A player with speed 15 and health 85.
Hopefully this gives you a good place to start!

You did a bunch of mistakes there :
Indent your Berserker method to be part of the class
Assignement in python is with one "=" not with "==" ( like most programming languages actually )
Give speed and hp initial values or don't put them in the constructor at all , in python variables are created when they're assigned a value.
Make your Berserker method return a string to be able to print it
Create an instance of your class
a working version of you code should be like this :
class Player:
def __init__(self):
self.speed = 0
self.hp = 0
def Berserker(self):
self.speed = 12
self.hp = 6
return "speed {} hp {}".format(self.speed,self.hp)
m = Player()
print("Berserkers stats are: " + m.Berserker())
Now that's a working version but it's still poorly designed IMO ,this is better :
class Player:
def __init__(self):
self.speed = 0
self.hp = 0
def Berserker(self):
self.speed = 12
self.hp = 6
def __str__(self):
return "speed {} hp {}".format(self.speed,self.hp)
m = Player()
m.Berserker()
print(m)

Related

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())

Printing my Class attributes

these are 2 parts of my misbehaving text based adventure code that I'm trying to learn how to do with a youtube tutorial. I believe that most of my problems arise because the tutorial I'm pretty sure is using python2.something and I'm using 3.
My problem is I'm trying to list the "Player" class attributes on the start screen, which I have successfully done with Playername, but I'm having trouble getting the numbers listed as self.attack and self.health etc to print.
I downloaded python for the first time about 5 days ago, so bear with a noob if you can, please.
Let me know what I can change, and thank you in advance!
class Player:
def _init_(self, name):
self.name = name
self.maxhealth = 100
self.health = self.health
self.attack = 10
self.gold = 0
self.bandages = 0
def start1():
os.system("cls")
print("Name: %s" % (PlayerIG))
print("Attack: {}".format (PlayerIG.attack))
print('Health: {}/{}'.format(PlayerIG.health, PlayerIG.maxhealth))
print("Gold: %i") % PlayerIG.gold
print("Bandages: %i") % PlayerIG.bandages
A few things immediately:
def _init_ needs to be def __init__ (note the double underscores).
self.health = self.health doesn't make sense - whatever is on the right side of an = needs to exist before you can assign some other variable to it, and self.health doesn't exist until that line.
The variable PlayerIG was never assigned to anything, so none of the code in start1 will work (unless it was done somewhere else, that you haven't included in the question).
A working version of what you have in your question would be something like
class Player:
def __init__(self, name, maxhealth, health, attack, gold, bandages):
self.name = name
self.maxhealth = maxhealth
self.health = health
self.attack = attack
self.gold = gold
self.bandages = bandages
def start1():
PlayerIG = Player('foo', 100, 50, 10, 0, 0)
print('Name: {}'.format(PlayerIG.name))
print('Health: {}/{}'.format(PlayerIG.health, PlayerIG.maxhealth))
print('Attack: {}'.format(PlayerIG.attack))
print('Gold: {}'.format(PlayerIG.gold))
print('Bandages: {}'.format(PlayerIG.bandages))
start1()
There are many improvements you could make from there, like defining a __str__ function for Player or using keyword arguments in your __init__ method.

pygame - How to group sprites

Having a real struggle getting this sorted. Had look at some other answers, and I get an error saying that I have too many arguments.
Class containing the objects I want to add.
class Digimon(pygame.sprite.Sprite):
def __init__(self,age,weight,strength,defence,speed,intelligence, image):
self.age = age
self.weight = weight
self.strength = strength
self.defence = defence
self.speed = speed
self.intelligence = intelligence
self.image = image
Have tried to do:
class Digimon(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self,age,weight,strength,defence,speed,intelligence, image)
self.age = age
self.weight = weight
self.strength = strength
self.defence = defence
self.speed = speed
self.intelligence = intelligence
self.image = image
but I error regarding the amount of arguments. (1 given, 7 needed).
Player = Digimon(0,2,0,0,0,0, [pygame.image.load("images/koro_1.png"), pygame.image.load("images/koro_2.png"), pygame.image.load("images/koro_3.png") ] )
This is in example of an object which I want to group together. From this, I'll be able to add keyboard events which affect all the objects grouped.
Any help would be fantastic :D
edit: full code: http://pastebin.com/uPWEM8bD
pygame.sprite.Sprite.__init__(self,age,weight,strength,defence,speed,intelligence, image)
The base Sprite class has no need for your age/weight/etc variables. Just pass in self:
pygame.sprite.Sprite.__init__(self)
You have 8 arguments (7 number variables and an image) in the definition but when you call it you pass 7 (6 ints and a list of images).

passing self to another classes function in self's function

I have two classes, the first one has a function move(creature, board). Then in the creature class there is a function that calls move, so how do I pass the current creature to the move function while in the creature class? Should it just be move(self, self.board), because when I try that I get a "Undefined variable from import:
move" error?
Here's the relevant code:
Creature:
class creature:
def __init__(self, social, intelligence, sensory, speed, bravery, strenght, size):
self.traits = [social, intelligence, sensory, speed, bravery, strenght]
self.x = 0
self.y = 0
self.hunger = 10
self.energy = 30
self.shelter = 0
self.dominance = 0
self.boardSize = size - 1
self.SOCIAL = 0
self.INTELLIGENCE = 1
self.SENSORY = 2
self.SPEED = 3
self.BRAVERY = 4
self.STRENGTH = 5
...
def performAction(self, action, location):
...
if action == "storeFood":
food = location.vegetation
location.vegetation = -1
simulation.move(self, self.shelter)
self.shelter.foodStorage += food
...
Simulation:
class simulation():
def __init__(self, x):
self.creatures = {creature.creature():"", creature.creature():"", }
self.map = land.landMass
self.lifeCycles = x
self.runStay = ["rfl", "rbf", "rbl", "rbf", ]
self.befriend = ["bbl", "bbf"]
self.fight = ["fbl", "fbf", "bfl", "bff", "ffl", "fff"]
...
def move(self, creature, target):
map[creature.x][creature.y].creatures.remove(creature)
creature.energy -= abs(map[creature.x][creature.y].elevation - target.elevation) / creature.getSpeed()
target.creatures.append(creature)
creature.x, creature.y = target.location
...
EDIT:
OK so I have somewhat solved the problem. Python requires that I have simulation.simulation.map(self, self.shelter) I'm assuming this means that it requires not just the class file but also an instance of that class. So the new question is do I have to make that instance somewhere else then pass it in? Or will this work with an instance of Simulation somewhere else?
Inherit the simulation class into the creature class:
class Creature(Simulation): # I have inherited the functions from Simulation into Creature
...
Now instead of simulation.move(self, self.shelter), you want:
self.move(yourparameters)
If you noticed, I capitalised your class names. It's good to do so.
For more on inheritance in classes, take a look [at the docs].(http://docs.python.org/2/tutorial/classes.html#inheritance)

python: setting attributes from module to module

Im teaching myself python and I've come upon a snag in a simple game project I'm working on.
I would like to keep the players stats in a different module from the rooms that are being run by the game engine. Problem is when I try to set a Playerattribute from a different module, it doesn't save the new attribute and instantiates the original attribute.
here is the Playerclass in the entities module
class Player(object):
def __init__(self):
self.name = ' '
self.hp = 0
self.current_hp = 0
self.strength = 0
self.dexterity = 0
self.constitution = 0
And here is how im trying to manipulate and test the attributes in the rooms module
class CharacterCreation(Scene):
def enter(self):
character = entities.Player()
character.hp = 10
print character.hp
return 'barracks'
class Barracks(Scene):
def enter(self):
character = entities.Player()
print character.hp
return 'shop'
When I test this with the rest of my code, here is what I get.
-------------------------------------------------------------------------------
10
-------------------------------------------------------------------------------
0
-------------------------------------------------------------------------------
So what am I missing here? I thought I could set that attribute using =but it seems I'm mistaken? the first time I did it, it worked, but then how do i get python to set the new value of hp to 10?
You're creating a new Player object in each scene, changing its attributes, and then throwing it away.
You should be explicitly passing one single player into each scene:
def enter(self, player):
... do something with player ...
It looks like you're creating a new Player instance on every enter method...
If you're going to have only one player in the game, you could have it as a global variable (usually not very good idea) or even better, as a singleton class:
http://blog.amir.rachum.com/post/21850841339/implementing-the-singleton-pattern-in-python
I made some tweakings to the code. It adds the PlayerPool class (which is more like a cache, actually). It may give you some ideas :)
#!/usr/bin/env python
#http://stackoverflow.com/questions/14629710/python-setting-attributes-from-module-to-module/14629838#14629838
class Player(object):
def __init__(self):
self.name = ' '
self.hp = 0
self.current_hp = 0
self.strength = 0
self.dexterity = 0
self.constitution = 0
class PlayerPool(object):
_players = dict()
#classmethod
def getPlayerByName(cls, name):
if not name in cls._players:
newPlayer = Player()
newPlayer.name = name
cls._players[newPlayer.name] = newPlayer
return cls._players[name]
class Scene(object):
pass
class CharacterCreation(Scene):
def enter(self):
character = PlayerPool.getPlayerByName("foobar-hero")
character.hp = 10
print "%s has %s points of hp" % (character.name, character.hp)
return 'barracks'
class Barracks(Scene):
def enter(self):
character = PlayerPool.getPlayerByName("foobar-hero")
print "%s has %s points of hp" % (character.name, character.hp)
return 'shop'
if __name__ == "__main__":
step1 = CharacterCreation()
if step1.enter() == "barracks":
step2 = Barracks()
step2.enter()
That outputs:
borrajax#borrajax-comp:~/Tests/Python/Stack Overflow$ python ./players.py
foobar-hero has 10 points of hp
foobar-hero has 10 points of hp
Welcome to python. I'm sure you'll find it has really cool features... such as the ability to return functions, or pass functions as parameters, inspect the classes defined in any module... Looks like things you could find useful.

Categories