πŸ” The Main Game Loop | myBetabox

πŸ” The Main Game Loop

Keyboard Guide

The Main Game Loop

The Code Explained

Make a list for the sprites (images etc..) in our main game screen called all_sprites. Think of lists like shopping lists!

🌟 Sprites are computer-generated, 2D images used in video games.

all_sprites = pygame.Sprite.Group()

Instancing will produce that sprite onto the screen at any given time. You can think of instancing like parallel universes where different versions of you are sitting, jumping, swimming, etc.. at the same time but you can only see one version at a time.

Let’s add the clicker object to the game by naming it c

c = Clicker()

…and then add it to the sprite group. Now our clicker image is in the list!

all_sprites.add(c)

Now , let’s make a different list for the sprites we’ll use for our store and store items.

store_sprites = pygame.sprite.Group()

Change the names of your powerups by editing this string but keep the quotation marks:

"INSERT NAME HERE"

This Boolean true/false statement will tell the computer if the game is running (on)…

running = True

…then it will run the following while loop to play the game code. Remember to capitalize the T in True!

while running:

Let’s set the frame rate of our game.

clock.tick(60)

We’ve set it to 60 frames per second (fps). This higher the frame rate, the better the gaming quality. Imagine flipping a flip book slowly vs. quickly – which would be better? If you’ve ever experienced lagging during gameplay, a low fps may be to blame.

If the game is not running we should end this while loop using the following code:

if event.type == pygameQUIT:
running = False

Notice how QUIT is in all upper case. This is because it’s an Enum (enumeration) value, which are always in caps, and they represent things that never change. A QUIT event always means quit, nothing else.

🌟Enums are Python classes that are associated with unique, constant values.

Now we need to create an event for when the player clicks the mouse!

if event.type == pygame.MOUSEBUTTONDOWN:

What happens when our clicking clicked the clicker?

clicks += click_amount

Incrementing with += makes coding easier and shorter. It stands for clicks = clicks + click_amount.

🌟Incrementing adds to a variable. In this example we’re adding to the total amount of clicks, which their clicking powers, from the game start.

If the player wants to buy something from the store, the game needs to check if the player has enough points to spend. If yes, then the shop items should increase in cost upon purchase. Let’s code for that.

if clicks >= s.cost:
Β clicks -= s.cost
Β click_amount += s.bonus
s.cost = int(s.cost * 1.75)

We should probably blit during the game so it can keep up with our gameplay.

screen.blit(background, bg_rect)
all_sprites.draw(screen)

Finally, let’s update the entire game screen….

pygame.display.flip()

… and code to quit the game if we leave the main game loop.

pygame.quit()