Movatterモバイル変換


[0]ホーム

URL:


Discord
Login
microStudio
Community
DARK THEME

How to use the init() function for Python?

1
2
1650
Constantine_RetroGamerQuestions

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.speedplayer1 = Player()def init():  passdef update():    player1.move()    passdef draw():    screen.clear("rgb(142,255,255)")    player1.draw()    pass#Monitors whether the keyboard object field is defined before checking the value of this fielddef checkInput(obj, val):  if hasattr(obj, val):    return obj[val] != 0  return 0
4
gilles

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 callinginit() correctly resets the player to the center of the screen. I hope this helps!

1
Constantine_RetroGamer

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

[8]ページ先頭

©2009-2025 Movatter.jp