Login
Community
DARK THEME

How to use the init() function for Python?

The question may seem silly, but I just started learning Python and don't know how to do it. When I write code, I don't use the init() function, since I can't get values from this function in the update() and draw() functions. So I can't understand why Python needs an initialization function. The code before the init() function is also executed once. The only thing I can't do without using the initialization function is to restart the game (by calling init()). The specific question is: how do I get the values from the init() function in other functions? Here is a sample code.

If you put all the code before the init() function in the init() function, then nothing will work.

class Player:
  
  def __init__(self):
    self.name = 'player'
    self.x = 0
    self.y = 0
    self.width = 8
    self.height = 8
    self.speed = 2
  
  def draw(self):
    screen.drawSprite('player', self.x, self.y, self.width, self.height)

  def move(self):
    if checkInput(keyboard, "UP"):
      self.y += self.speed
    if checkInput(keyboard, "DOWN"):
      self.y -= self.speed
    if checkInput(keyboard, "LEFT"):
      self.x -= self.speed
    if checkInput(keyboard, "RIGHT"):
      self.x += self.speed

player1 = Player()


def init():
  pass


def update():
  
  player1.move()
  
  pass


def draw():
  
  screen.clear("rgb(142,255,255)")
  
  player1.draw()
  
  pass


#Monitors whether the keyboard object field is defined before checking the value of this field
def checkInput(obj, val):
  if hasattr(obj, val):
    return obj[val] != 0
  return 0

You should maybe leave the class definition outside and just instantiate your player in the init() function:

class Player:
  
  def __init__(self):

  (...)


def init():
  global player1
  player1 = Player()

This seems to work for me and calling init() correctly resets the player to the center of the screen. I hope this helps!

Thank you Gilles! This is how everything really works. One line of "global player 1" clarified everything :-)

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community