Tuesday, October 26, 2021

Two squares and circle game

 SIMPLE GAME IN PYGAME: TWO SQUARES AND A RECTANGLE



In this blog, we shall create a simple python game that involves two enemy squares and a player circle. The code is not the cleanest but as long as the game plays we are good to go!

A.    Importing the modules

For this game to run, we require two modules; pygame and math. It is here that we also initialise the pygame module. After initialising the module we need to set the window size and the caption.

import pygame

import math

 

pygame.init()

 

modex, modey = 700, 600

window = pygame.display.set_caption("GAME!!")

window = pygame.display.set_mode((modex, modey))

 

B.     Variables

We require a couple of variables for this game to run. Read the comments to understand the purpose of each variable.

#setting the font we will use in the game

font = pygame.font.SysFont("comicsansms", 35)

#setting the x, y coordinates, radius and velocity of the circle

x, y, radius, vel = modex/2, modey, 30, 15

#setting the colors we will use

green, blue = (0, 255, 0), (0, 0, 128)

#setting the length and width of the rectangle - it becomes a square since length = width

rectx, recty , rectx1, recty1 = 50, 50, 50, 50

#setting the x-y coordinates and velocity of each square

rect, rect1 = [700, 600, 1], [0, 500, 1.3]

#Boolean values required for the game-play

run, jump, move_right, move_left, move_right1, move_left1 = True, False, False, True, True, False

#initalizing the clock method in pygame

clock = pygame.time.Clock()

 

 

C.     Function to check collision

To check if the circle has collided with either of the two squares, we use the formula
for checking the distance between two coordinates. i.e The distance, d, between two points whose coordinates are (x1,y1)(x1,y1) and (x2,y2(x2,y2) is: d = √[(x2x2 − x1x1)2 + (y2y2 − y1y1)2]. If the distance is less than the radius of the circle then a collision has happened.


def HasCollided(rx, ry, cx, cy):

    if cx > rx:

        cx -= rectx                          

    distance = math.sqrt((math.pow(rx-cx,2)) + (math.pow(ry-cy,2)))

    if distance < (radius+2):

        return True

    else:

        return False

 

D.    Gameplay

In the gameplay loop, several things happen;

1.     Time delay – We delay the time using the clock method we initialised. The reason for this is to make sure that the game runs smoothly across all devices regardless of their speed.

while run:

    pygame.time.delay(40)

2.     Quitting the game – We use a for loop to check if an event that could lead to the closing of the game has occurred. (in this case the pressing x button at the right-top of the game window)

while run:

pygame.time.delay(40)

for the event in pygame.event.get():

        if event.type == pygame.QUIT:

            run = False

3.     Moving the circle – To move the circle we use left and right arrow keys on our keyboard. We, therefore, need to check whether a certain key has been pressed and if so move the circle accordingly. To move the circle we subtract the velocity of the circle from its initial location.

keys = pygame.key.get_pressed()

if keys[pygame.K_RIGHT] and x < modex - radius:

x += 10

    if keys[pygame.K_LEFT] and x > radius:

        x -= 10

3.1  Jump – To make the circle ‘jump’ the player will have to press the up arrow key. When they do so the y coordinate of the circle reduces making the circle move up and sets the condition jump to false to prevent jumping while ‘jumping’. It reaches a certain point where the circle starts moving downward. This is achieved by multiplying the velocity of the circle by 2 and then subtracting the result from its coordinate. At some point the velocity becomes negative hence subtracting it from the y coordinate of the circle would result in an increase in the value of the coordinate

#Jump

if jump is False and keys[pygame.K_UP]:

jump = True

if jump is True:

y -= vel * 2

vel -= 2

if vel < -15:

   jump = False

   vel = 15

4.     Moving the squares

The ‘computer’ will be moving the rectangles. We work with move_left and move_right Boolean values. The idea is to prevent the squares from going beyond the game window. The square should be within points 0 and 700. If their x-value goes beyond that scope we prompt them to move in the opposite direction while increasing their speed.

#Moving the square 1

    if move_left is True:

        rect[0] -= rect[2]

        if rect[0] < 0:

            move_left = False

            move_right = True

    if move_right is True:

        rect[0] += rect[2]

        if rect[0] > modex-rectx:

            move_left = True

            move_right = False

    rect[2] += .005

    #Moving the square 2

    if move_left1 is True:

        rect1[0] -= rect1[2]

        if rect1[0] < 0:

            move_left1 = False

            move_right1 = True

    if move_right1 is True:

        rect1[0] += rect1[2]

        if rect1[0] > modex-rectx1:

            move_left1 = True

            move_right1 = False

    rect1[2] += .005

5.     Drawing the shapes – Pygame makes it possible for us to draw shapes using its inbuilt methods. We also fill the background of the game window with an RGB color

pygame.draw.circle(window, (0, 0, 0), (int(x), int(y - radius)), radius)

pygame.draw.rect(window, (255, 0, 0), (rect[0], rect[1]-recty, rectx,recty))

pygame.draw.rect(window, (20, 100, 0), (rect1[0], rect1[1]-recty, rectx, recty))

window.fill ((25, 30, 100))

pygame.display.update()

6.     Checking for collisions – We first need to run the collision function and if it returns true then a collision has happened. So if a collision has occurred the game needs to be stopped and display the game over text or something. To display the text, we use pygames’ blit method.

 

Collision = HasCollided(rect[0], rect[1], x, y)  

    if Collision == True:

        text = font.render('Game Over Bitch!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

    Collision1 = HasCollided(rect1[0], rect1[1], x, y)  

    if Collision1 == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

 

Our game loop now looks like this;

while run:

    pygame.time.delay(40)

    for event in pygame.event.get():

        if event.type == pygame.QUIT:

            run = False

    keys = pygame.key.get_pressed()

    if keys[pygame.K_RIGHT] and x < modex - radius:

        x += 10

    if keys[pygame.K_LEFT] and x > radius:

        x -= 10

        #Jump

    if jump is False and keys[pygame.K_UP]:

        jump = True

    if jump is True:

        y -= vel * 2

        vel -= 2

        if vel < -15:

            jump = False

            vel = 15  

    #Moving the square 1

    if move_left is True:

        rect[0] -= rect[2]

        if rect[0] < 0:

            move_left = False

            move_right = True

    if move_right is True:

        rect[0] += rect[2]

        if rect[0] > modex-rectx:

            move_left = True

            move_right = False

    rect[2] += .005

    #Moving the square 2

    if move_left1 is True:

        rect1[0] -= rect1[2]

        if rect1[0] < 0:

            move_left1 = False

            move_right1 = True

    if move_right1 is True:

        rect1[0] += rect1[2]

        if rect1[0] > modex-rectx1:

            move_left1 = True

            move_right1 = False

    rect1[2] += .005

 

    window.fill ((2530100))

    pygame.draw.circle(window, (0, 0, 0), (int(x), int(y - radius)), radius)

    pygame.draw.rect(window, (255, 0, 0), (rect[0], rect[1]-recty, rectx, recty))

    pygame.draw.rect(window, (20, 100, 0), (rect1[0], rect1[1]-recty, rectx, recty))

    pygame.display.update()

   

    Collision = HasCollided(rect[0], rect[1], x, y)  

    if Collision == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

    Collision1 = HasCollided(rect1[0], rect1[1], x, y)  

    if Collision1 == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

 

We finally end the game using pygames’ quit method

    Collision1 = HasCollided(rect1[0], rect1[1], x, y)  

    if Collision1 == True:

        text = font.render('Game Over!', True, green)

        window.blit(text, [300, modey/2])

        pygame.display.update()

        pygame.time.delay(1000)

        run = False

 

pygame.quit()


Click here to view the full code

                                                                                                            

0 Comments:

Post a Comment

Subscribe to Post Comments [Atom]

<< Home