[Author Prev][Author Next][Thread Prev][Thread Next][Author Index][Thread Index]
Re: [pygame] A bunch of newbie questions
Miguel Sicart wrote:
What I want is that, when the player presses space, a new object
companion is created, up to for. So, how do I do that? Sprites are in
groups in the main loop, but how do I append/add an instance to a group
from the class.
In other words: how do I access the main loop from an object's method?
(if that is possible).
Welcome, hopefully you can get all the answers you need here.
When I'm making games, the game objects themselves are not responsible
for directly handling input, this is usually a good idea. You would some
part of the main loop check for the spacebar, and create and track the
created helpers.
If the design is that the player object should really "own" the helper
objects, then make a list or a set on the player class. The player
object can create the helpers and keep track of them for itself.
For a game object to talk to the main loop, you need to set up some way
to access the loop. Typically a game only has one main loop. Keep a
reference to this main loop in a common module your game shared. Then
anyone can reference the current main loop through the module.
1. The chain reaction - I am using rect.inflate, but it seems to be
quite unprecise. Is it just better to load a new image, a "explosion",
with a different rect, instead of inflating the original's rect?
It kind of depends on the number of effects that will be going on. The
easiest will be for each explosion in the chain reaction to create a new
game object with its own image and rect.
If you are going to have many overlapping objects in a rectangle. You
may want to keep track of only the bounding rectangle of all of them.
Then you can use this single rectangle for calls to
pygame.display.update().
2. Dying: as someone said, dying is easy, comedy is hard. OK, so when
the hero dies, I need to kill the sprite, make a timer, and then
instantiate it again. And I have no clue how to do any of these things
(well, except self.(kill)). I am not fishing for code here, but for how
to think about how to solve this problem.
Your game main loop will work with something usually called a "state
machine". This mainly means some kind of class or global variables that
tell the game what mode it is in. The job of the state machine is to
track what is going on, and figure out when to switch to some other
mode. A simplistic method would use a set of strings with the main loop.
if game_mode == "player_alive":
handle_input()
move_player()
if player.is_killed():
if number_of_lives == 0:
game_mode == "game_over"
else:
game_mode == "player_dead"
killed_time = current_time()
elif game_mode == "player_dead":
if current_time() - killed_time > 3seconds():
player.restart()
game_mode == "player_alive"