4.4 - App Class

4.4 App Class

Now that we’ve defined our objects, we can start programming the application.
Since large games have lots of code, it can be hard to know where to start. So, what we can do is think about our structure or the flow of the code. To do this, we create an abstract class App from which our actual game will inherit. App is “abstract”, meaning that we don’t need to define functional methods since it should just provide the structure that we want our game to have.
Since we will need to create objects before interacting with them, the App’s init method should call a create_objects method. (It should also do what we’ve been doing so far before our main loop; ie: pygame.init(), etc.)
So, our init method should look like this:
def __init__( self, flags=RESIZABLE, width=960, height=540, title="My Game" ): pygame.init() self.size = [width, height] self.screen = pygame.display.set_mode(self.size, flags) pygame.display.set_caption(title, title) self.running = True self.create_objects()
Our app class will have a main loop similar to the loops we’ve used before. However, this time we want to divide up the game into methods that can be called by the main loop. For this, we need to think about what the game will be doing. Since the tank game needs to check events (such as KEYDOWN and MOUSEBUTTONDOWN), move objects (such as the bullets and the tank), check collisions (between the bullets and targets), and update the screen, these can be our other methods.
So, this is what our main loop would look like:
def mainloop(self): while self.running: for event in pygame.event.get(): if event.type == QUIT: self.running = False break else: self.check_events( event ) # this will handle checking for user input # such as KEYUP and MOUSEBUTTONDOWN events needed to run the game self.check_collisions() # checks collisions between bullet/tank and targets self.move_objects() # moves each object on the screen self.update_display() # redraws updated objects onto the screen pygame.display.update() # pygame’s method to show the updated screen time.sleep(0.01) # not necessary; it's a frame cap pygame.quit()
Then, now that we’ve outlined our main loop's structure, we can define the following methods: create_objects, check_events, check_collisions, move_objects, and update_display. Once we define all of them, we’ve finished our game.
An App class isn't necessary. If you can think of your main loop without the help of an App class, then feel free to do so. However, it often does help to define a basic structure in the App (or whatever you would like to call it) class
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.