Python Inheritance Issue - python

I have a class that is inheriting from another class, and I get the issue:
Traceback (most recent call last):
File "main.py", line 45, in <module>
class Player(Entity):
File "main.py", line 53, in Player
self.image = pygame.image.load('sam_stand.png')
NameError: name 'self' is not defined
These are the classes:
class RigidBody(object):
def __init__(self, (x, y), size, mass=1):
self.x = x
self.y = y
self.size = size
self.mass = mass
self.thickness = 0
self.angle = 0
self.drag = 1
self.elasticity = 0.9
class Player(Entity):
"""Player class. Provides all player variables and methods"""
def __init__(self):
RigidBody.__init__(self)
self.grounded = True
self.direction = "Right"
self.axis = "Down"
self.jump_counter = 0
self.image = pygame.image.load('sam_stand.png')
How come self is recognized for all the other attributes for the Player, except for self.image? If I change it to image = pygame.image.load('sam_stand.png') the problem goes away.

You are mixing tabs and spaces. When looking at your first revision source I see this:
Your method body is indented with tabs, which Python expands to 8 spaces. The last line, however, is indented with spaces only. You have your editor set to 4 spaces per tab, so you cannot see this mistake.
As a result, the self.image line falls outside the __init__ method. It is part of the class definition instead.
You really want to configure your editor to indent with spaces only.
Run your code with python -tt scriptname.py and fix all the errors that reports. Then run the tabs-to-spaces feature in your text editor (converting to 4 spaces) and then configure it to use spaces for indentation (automatically inserting 4 spaces when you use the tab key).
Using spaces for indentation is recommended by the Python styleguide for a reason, after all.

Related

Python set class variable after calling

I'm making a game using the pygame module and I have a player class:
class Player(pygame.sprite.Sprite):
def __init__(self, name, position, axsis, movment, idle, walk = None, jump = None):
pygame.sprite.Sprite.__init__(self)
self.name = name
self.idle = idle
self.walk = walk
self.jump = jump
self.image = self.idle[0]
self.movment = movment
self.left, self.right = axsis
self.pos = vec(position[0],position[1])
I am adding my characters using json data type and trying to add animations after calling the class but i can't do it
Sample code
class Game():
def __init__(self,json_file):
self.player_attribute = json_file
def character(self):
self.npc = []
for i in self.player_attribute:
self.npc.append(Player(i['name'],
i['position'],
i['axsis'],
i['movment']))
self.animation()
return self.npc
def add_animation(self):
for i in self.npc:
i.idle = "images\ghost.png"
def main_loop()
self.character
when i try this i get an error
self.image = self.idle[0]
TypeError: init() missing 1 required positional argument: 'idle'
how can i add the variables of the class after calling the class
It is not clear what the 'idle' parameter is supposed to represent in your code. However, the reason for the exception is that you are not passing any argument for 'idle' when constructing the Player object. You need something like:
self.npc.append(Player(i['name'],
i['position'],
i['axsis'],
i['movment'],
i['idle']))
You can either do that or alternatively you can pass a default argument to the Player constructor so that, when initializing you do not need to explicitly pass idle:
class Player(pygame.sprite.Sprite):
def __init__(self, name, position, axsis, movment, idle=[1], walk = None, jump = None):
You can modify its content at a later time, however I suggest you are careful what you instantiate that object attribute as, because it might come bite you back later (type error or value error).
If it were me, I would move this out of init, or not build the object until all values and their types are known (see Builder Design Pattern).
Hope this helped :) Cheers!

TypeError: argument 1 must be pygame.Surface, not type

I'm making a submarine game in python, but when I try to run it, the interpreter gives me very strange error:
"TypeError: argument 1 must be pygame.Surface, not type."
I tried to search the web for my answer, but it seems like this isn't very usual error. I also tried to find error by myself, but everything seemed fine to me. Here 's part of the code that I think error is in:
mina = pygame.image.load('mina.png')
class mina():
def __init__(self, x , y):
self.x = x
self.y = y
self.eksplozija = False
def naris(self):
screen.blit(mina, (self.x, self.y))
igralec = podmornica(150, 300, 10)
eksploziv = mina(700, 350)
metki = []
clock = pygame.time.Clock()
def grafika():
clock.tick(60)
screen.blit(ozadje, (0,0))
igralec.naris()
#line, that doesn't work:
eksploziv.naris()
for metek in metki:
metek.naris(screen)
pygame.display.flip()
The variable mina and the class mina have the same name. The class mina shadows the variable mina. You need to rename one or the other. I recommend to rename the calss mina to Mina, since Python classes use the CapWords convention (PEP 8 -- Style Guide for Python Code):
class mina():
class Mina():
eksploziv = mina(700, 350)
eksploziv = Mina(700, 350)

Syntax Error; Python game spits out super method and imports

I made classes for what will basically become a BreakOut game, but I keep getting error messages. The nature of which always seem to surround two things; Class imports and the infamous "super" method. Usually in the form of a syntax error
I had some questions shot down in the past, so I will try to be as clear as I possibly can.
The main code for the game is as such...
import pygame
from Game import *
from Game.Scenes import *
from Game.Shared import *
class BreakOut:
def __init__(self):
self.__lives = 5
self.__score = 0
self.__level = Level(self)
self.__level.load(0)
self.__pad = Pad((0,0), 0)
self.__balls = [Ball((0,0), 0, self)]
pygame.init()
pygame.mixer.init()
pygame.display.set_caption("This is the Title of the Game")
self.__clock= pygame.time.Clock()
self.screen = pygame.display.set_mode(GameConstants.SCREEN_SIZE, pygame.DOUBLEBUF, 32)
pygame.mouse.set_visible(0)
self.__scenes = (
PlayingGameScene(self),
GameOver(self),
HighScoreScene(self),
MenuScene(self)
)
self.__currentScene = 0
self.__sounds = ()
def start(self):
while 1:
self.__clock.tick(100)
self.screen.fill((0,0,0))
currentScene = self.__scenes[self.__currentScene]
currentScene.handleEvents(pygame.event.get())
currentScene.render()
pygame.display.update()
def changeScene(self, scene):
pass
def getLevel(self):
pass
def getScore(self):
pass
def increaseScore(self, score):
pass
def getLives(self):
pass
def getBalls(self):
pass
def getPad(self):
pass
def playSound(self, soundClip):
pass
def reduceLives(self):
pass
def increaseLives(self):
pass
def reset (self):
pass
BreakOut().start()
At this stage, its only supposed to return a black screen, but instead it keeps giving me a error message with this traceback:
Traceback (most recent call last):
File "/Users/Ryan/PycharmProjects/Demo 1/Game/BreakOut.py", line 3, in <module>
from Game import *
File "/Users/Ryan/PycharmProjects/Demo 1/Game/__init__.py", line 9, in <module>
from Game.BreakOut import BreakOut
File "/Users/Ryan/PycharmProjects/Demo 1/Game/BreakOut.py", line 4, in <module>
from Game.Scenes import *
File "/Users/Ryan/PycharmProjects/Demo 1/Game/Scenes/__init__.py", line 3, in <module>
from Game.Scenes.HighScoreScene import HighScoreScene
File "/Users/Ryan/PycharmProjects/Demo 1/Game/Scenes/HighScoreScene.py", line 7
SyntaxError: invalid syntax
The bottom one connects to another class of code that looks like this:
from Game.Scenes.Scene import Scene
class HighScoreScene(Scene):
def __init__(self, game):
super(HighScoreScene, self.__init__(game)
PyCharm seems to highlight "super" and tells me "Old-style class contains call for super method" I don't know if that's important or not, but its something I've noticed consistently throughout the code.
I'm pretty sure its a simple mistake. Might be a typo, but I can't pinpoint it for the life of me. Please help!
super(HighScoreScene, self.__init__(game) # <- missing paren
It should be super(HighScoreScene, self).__init__(game)
And use object class BreakOut(object) if you want to use super.
New-style and classic classes
Your class Breakout line is not in line with the rest of your program (ahead by one space). If you backspace that line by one, everything should be fine (including #Padraic Cunningham 's answer).

python default argument syntax error

I just wrote a small text class in python for a game written using pygame and for some reason my default arguments aren't working. I tried looking at the python documentation to see if that might give me an idea what I did wrong, but I didn't fully get the language in the documentation. No one else seems to be having this issue.
Here's the code for the text class:
class Text:
def __init__(self,screen,x_location='center',y_location='center',writeable,color,size=12):
self.font = pygame.font.Font("Milleni Gem.ttf", size)
self.text = self.font.render(writeable,True,color)
self.textRect = self.text.get_rect()
if x_location == "center":
self.textRect.centerx = screen.get_rect().centerx
else:
self.textRect.x = x_location
if y_location == "center":
self.textRect.centery = screen.get_rect().centery
else:
self.textRect.y = y_location
self.update()
def update(self):
screen.blit(self.text,self.textRect)
and here's the code to call it:
from gui import *
Text(screen,75,75,currentweapon.clip)#currentweapon.clip is an integer
The error I get is this:
SyntaxError: non-default argument follows default argument
and points to the def __init__() line in the code. What does this error mean and what am I doing wrong here?
def __init__(self,screen,x_location='center',y_location='center',writeable,color,size=12):
You have defined non-default arguments after default arguments, this is not allowed. You should use:
def __init__(self,screen,writeable,color,x_location='center',y_location='center',size=12):

Python code returning syntax error on "if self.hp < 0" line

I've been following along with this series of youtube videos in order to get a more hands on approach to python. I don't have a deep understanding of what some of the code does, but I more or less get what each piece is supposed to achieve, even though I may not be sure how.
I'm getting a Syntax error on the last line here:
class Character(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
self.dead = False
def attack(self, other):
pass
def update(self):
if self.hp < 0 #Error's on this line
self.dead = True
self.hp = 0
Here is the traceback:
Traceback (most recent call last): File "game.py", line 4, in
<module>
from Characters.player import * File "/Users/Devlin/Desktop/Dev/Python/rpg/Characters/player.py", line 2,
in <module>
from character import * File "/Users/Devlin/Desktop/Dev/Python/rpg/Characters/character.py", line
12
if self.hp < 0
^ SyntaxError: invalid syntax
You forgot a colon (:) at the end of the line:
if hp < 0:
Your init also looks like a constructor. As such, it should likely be __init__ instead of init. Otherwise, you're going to run into problems with it not being executed at object instantiation.

Categories

Resources