Experimenting with Pygame #3: Mario Returns

Hi Guys, welcome again to another fascinating part in Experimenting with pygame. In this part I am not going to disappoint you guys. You are actually going to build user interactive game today. Interested??

Come lets build a very simple game. Don’t go with the title :). This is just a simple game. You guys would know well about the famous game SNAKE in nokia phones. Well this is kinda adapted on that. Here we are going to interact with Mario to keep him well within the bounds of the window. If he hits the boundary then its GAME OVER. Really simple game to make. So the take away in making this game are as follows;

  • How to capture user interactions in the game and manipulate accordingly
  •  Write some complex code enough to make it a game. 🙂

So as usual, first the code.

__author__ = 'krishnan'

import sys, time
import pygame

# Initialising pygame
pygame.init()
# Setting the frame rate variable
# X, y coordinates and direction control variable
fps = 40
x, y = (0, 0)
direction = ('x', 1)
# Setting the window size and screen according to it
window_size = length, width = (800, 600)
screen = pygame.display.set_mode(window_size)
clock = pygame.time.Clock()
# Creating the font for displaying the Game over
gameover = pygame.font.SysFont("Arial", 48)
text_to_render = gameover.render("Game Over", 1, (255, 255, 255), (0, 0, 255))
# Loading the Mario character to the pygame environment
mario = pygame.image.load("Mario.png")
mario = pygame.transform.scale(mario, (100, 50))
# Getting the size of mario
marioSize = mario.get_size()
screen.blit(mario, (x, y))

def gameFinish():
    """
    This is a simple function which exits the game because the user lost.
    The function is called when character hits the window walls.
    :return: No returns
    """
    # Display the Game over text on the screen
    screen.blit(text_to_render, (0, 0))
    pygame.display.flip()
    time.sleep(2)
    # Exit from the game
    sys.exit()

# Game Loop
while True:
    clock.tick(fps)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
        # Get all the four arrow events and
        # move the character according to arrow key pressed
        if event.type == pygame.KEYDOWN:
            if event.key == pygame.K_RIGHT:
                direction = ('x', 1)
            if event.key == pygame.K_LEFT:
                direction = ('x', -1)
            if event.key == pygame.K_DOWN:
                direction = ('y', 1)
            if event.key == pygame.K_UP:
                direction = ('y', -1)
    # Condition for the Game loss and exiting. If character hits the walls
    # of the window, user loses the game.
    if (x + marioSize[0] > length or y + marioSize[1] > width) or (x < 0 or y < 0):
        gameFinish()
    # Logic to move the character
    if direction[0] == 'x':
        x += 5 * direction[1]
    else:
        y += 5 * direction[1]

    # Render the display with the background and the current character position
    screen.fill((0,0,0))
    screen.blit(mario, (x, y))
    pygame.display.flip()

So we can see that our amount of code increases as our game logic gets more complex. So most of the parts you guys know. Or else please visit my previous posts to know.

So regarding this post we are going to see how an interactive game is built. So the basic game logic is

  • The character keeps moving in a particular direction.
  • We need to keep him of the boundary.
  • To change the direction we use the arrow keys.

So as usual we,

  •  Load the character to pygame
  • Create the game loop
  • Initiate the Clock instance with fps as it is an animation game
  • Create the basic exit scenario (clicking the close button)

In the previous post the superman moves on his own wish. That is upward.So there was no interaction. But now as a game we are going to need user to control the character using arrow keys. We already know that we have a for loop which gets all events in each iteration. Using this we can solve this. We know that every interaction is an event. So a keyboard key press will also be an event. So we capture that and do the logic accordingly.

if event.type == pygame.KEYDOWN:
    if event.key == pygame.K_RIGHT:
        direction = ('x', 1)
    if event.key == pygame.K_LEFT:
        direction = ('x', -1)
    if event.key == pygame.K_DOWN:
        direction = ('y', 1)
    if event.key == pygame.K_UP:
        direction = ('y', -1)

In the above code we check if the event type is a KEYDOWN. If it is a KEYDOWN we check if it is any of the four arrow keys by checking the key attribute in event. Then according to the key pressed we set the direction control variable. The direction variable is a tuple with two elements depicting the axis to move and the direction to take.

So that was the user interaction using keyboard. Now a game should have a win or lose part. The winning part is to keep Mario within bounds. Losing part comes when Mario hits the window boundary.

So for this we get the size of image first. Because the coordinates of the image is based on the top left corner of the image and not the complete one. So the image can go beyond boundaries. So we decide this by taking the imagesize and adding it with the actual x and y coordinate to check the boundaries.

mario = pygame.image.load("Mario.png")
mario = pygame.transform.scale(mario, (100, 50))
# Getting the size of mario
marioSize = mario.get_size()

 

if (x + marioSize[0] > length or y + marioSize[1] > width) or (x < 0 or y < 0):
    gameFinish()

Finally the based on the direction variable set using keyboard interaction we use the same superman logic to reposition the Mario in the window.

if direction[0] == 'x':
    x += 5 * direction[1]
else:
    y += 5 * direction[1]

# Render the display with the background and the current character position
screen.fill((0,0,0))
screen.blit(mario, (x, y))
pygame.display.flip()

mario_win

game_over

And thats it. We made our first User interactive game 🙂

2 thoughts on “Experimenting with Pygame #3: Mario Returns

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s