Draw Polygon with Pygame

Today we will continue with our draw’s class in Pygame and in this article we will draw a Polygon object with the pygame.draw.polygon method. This polygon method will take in a few arguments. 1) The screen surface 2) The color of the Polygon 3) An array of tuples contain the x, y coordinate 4) An optional width value if stated then the pygame.draw.polygon method will draw a hollow Polygon object or else the Polygon will be filled with solid color.

In the following script, after you have clicked on any 5 locations on the screen then the pygame.draw.polygon method will start to draw Polygon on the surface of that screen!

import pygame
from pygame.locals import *
from sys import exit

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
cooordinate = []

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
        if event.type == MOUSEBUTTONDOWN: #if mouse click then coordinate array will append x,y tuple 
            cooordinate.append(event.pos)
    screen.fill((255,255,255))
    screen.lock()
    if len(cooordinate) >= 5:
        pygame.draw.polygon(screen, (255,255,100), cooordinate, 3)
    
    screen.unlock()
    pygame.display.update()

Click on more positions on the screen and the shape will now change accordingly.

Pygame draw polygon
Pygame draw polygon

How to draw circle with Pygame

Drawing circle with Pygame is just like drawing a rectangle which I have shown you in the previous post. Let draw a circle on the screen this time with the pygame.draw.circle method. This method takes in the screen surface argument, a tuple consists of the RGB color value for the circle, the tuple consists of the position of the circle on the screen, the radius of the circle as well as an optional line width property which we have previously used in the previous rectangle example! Below is the entire script to draw a solid circle (no outline) on the screen.

import pygame
from pygame.locals import *
from sys import exit
from random import *
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.fill((255,255,255))
    screen.lock()

    circle_pos = (290, 220)
    circle_radius = 100
    circle_color = (255, 100, 230)
    pygame.draw.circle(screen, circle_color, circle_pos, circle_radius)
    
    screen.unlock()
    pygame.display.update()

The rest of the script above is almost the same as the previous script which uses to create two rectangle objects.

Python circle
Python circle

How to draw a rectangle with Pygame

There are two methods you can use to put a game character on the screen with Pygame. The first method which I have shown you before is to insert either a png or a jpeg image on the screen with the screen.blit method. The second method which I am about to show you now is to draw on the screen. Actually you can create a game without using any image by just drawing square or circle on the screen and I am going to show you how to draw a few different shapes on the screen with Pygame in this pygame tutorial series. In this post we will draw two rectangles, one will be filled with color and another one is a hollow rectangle.

In order to draw a rectangle on the screen we will use the

pygame.draw.rect

method which will take a few arguments as shown in the below example.

pygame.draw.rect(screen, (100, 100, 150), Rect((150, 150), (100, 100)), 3)

The first argument is the surface of the screen, the second one is the tuple which contains the RGB value of the color which will be used to fill the entire rectangle or to be used as the color of the line if that rectangle is a hollow one. The third argument is the rectangle object itself which takes two arguments (the tuple which contains the top left corner’s (x and y coordinate point) of that rectangle (on the screen) as well as the tuple which contains the width and height of that rectangle). The fourth argument is an optional line width argument which if you use it will draw line around the hollow rectangle according to the width you have specified. If you leave out that fourth argument then the rectangle will be filled up with the color which we have specified.

Before we start to draw on a surface we will also need to lock that surface first with the following method.

screen.lock()

Then we also need to unlock that same surface again once we have finished drawing on it with this method.

screen.unlock()

Below is the entire script which I use to draw two rectangles on the screen, one is the hollow rectangle and another one is the rectangle filled with color.

import pygame
from pygame.locals import *
from sys import exit
from random import *
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.lock()
    rectangle_pos = (150, 150)
    rectangle_pos2 = (250, 350)
    rectangle_size = (100, 100)
    screen.fill((255,255,255))
    pygame.draw.rect(screen, (100, 100, 150), Rect(rectangle_pos, rectangle_size), 3)
    pygame.draw.rect(screen, (100, 100, 150), Rect(rectangle_pos2, rectangle_size))
    screen.unlock()
    pygame.display.update()

If you run the above script you will get the following outcome.

Draw rectangle with Pygame script
Draw rectangle with Pygame script

There are more tutorials on Pygame coming everyday so make sure to bookmark this Pygame channel for the daily Pygame tutorial : http://gamingdirectional.com/blog/category/pygame/

Pygame tutorial 2 – Moving the object with keyboard

Before we start, make sure you have read the first tutorial of creating game in python with pygame, if you not then just go ahead and read the first part of this pygame tutorial series.

In this tutorial I am going to show you how to move the game object within the pygame’s display screen with your keyboard.

In order to move our object within pygame we will need to find out whether the user has pressed a certain key or not from the value of the event’s key property and also we will only move our character if the user is continue pressing that key.

Below is the entire python script to move a boat in the right or the left direction on the display screen. The display portion of the script is almost the same as the previous one but with an additional loop to retrieve the value of the event’s key property (in this example the left or the right arrow key on your keyboard) as well as to detect whether you are continue pressing that key or have already released it, if you have released the key then the direction will again set to zero which means no movement will be made by that object at the moment or else the object will move to either left or the right by 0.05 unit (if you pressed the left arrow key then the boat will move left or else it will move right if right arrow key is pressed).

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit

background_image = 'terain7.png'
boat = 'boat.png'

pygame.init()
SCREEN_SIZE = (500, 500)
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
pygame.display.set_caption("Pygame Demo")
background = pygame.image.load(background_image).convert()
player = pygame.image.load(boat).convert_alpha()

x, y = 150, 353
MOVE_RIGHT = 1
MOVE_LEFT = 2
direction = 0

while True:
   
    for event in pygame.event.get():
        
        if event.type == QUIT:
            exit()
            
        if event.type == KEYDOWN:
            if event.key == K_LEFT:
                direction = MOVE_LEFT
            elif event.key == K_RIGHT:
                direction = MOVE_RIGHT
                
        elif event.type == KEYUP:
            if event.key == K_LEFT:
                direction = 0
            elif event.key == K_RIGHT:
                direction = 0
                
        
    if(direction == MOVE_LEFT):
        x-=0.05
    elif(direction == MOVE_RIGHT):
        x+=0.05
    
    screen.blit(background, (0, 0))
    screen.blit(player, (x, y))
    pygame.display.update()

Run the above script in NetBeans 8.1 and you will see the below outcome.

If you are interested in pygame then don’t miss my daily pygame tutorial because starting from today I will write one to three posts per day on pygame so do visit this blog everyday and master the entire pygame tutorial within a week!

Journey into PyGame — The beginning

For those python fans, Pygame is indeed a great python’s game engine which you all should really consider if you want to write game using the python language. Although some of you might disagree with my thought but if we remove PyGame from the list of Python’s gaming engine then the only one left for us to consider will be pyglet which is not that well documented as compared to PyGame and thus makes our game development process even harder as compared to using the PyGame engine.

In this article I am going to show you how to install and run your first pygame program with a few lines of python script, ok, without wasting any time let get started.

I have installed python 3.5.2 in my computer and thus I will need to install the PyGame version which matches my python version. In order to install PyGame which matches Python 3.x you will need to visit this PyGame download page. Although my computer’s os belongs to windows 64bit but it seems like the 64bit PyGame version is not working due to some unknown reason (either one of the module is missing or the platform is not supported), due to that I have selected the 32bit version instead because it really doesn’t matter either we are installing the 32bit or the 64bit in our 64bit os as long as the os is 64bit then we can either select the 32bit or the 64bit version, however the reverse is not true because if we install the 64bit PyGame in our 32bit pc then we will not be able to use it at all.

I have downloaded this file pygame-1.9.2b1-cp35-cp35m-win32.whl from the above website. The cp35 in the filename means python 3.5 and win32 means it is for 32bit of windows os. After I have downloaded this file I will need to install it either with pip or pip3 or pip3.5. Browse to the folder where you have downloaded the whl file in the windows command prompt then type in this command : pip3 install pygame-1.9.2b1-cp35-cp35m-win32.whl to extract and then install the PyGame module into Python’s site package folder.

Next create a new project in NetBeans 8.1 IDE and then create a new python module with any name you like and enter below script into it. If you want to know how to use PyGame in your python program then you can visit the PyGame official homepage for further detail.

#!/usr/bin/env python

import pygame
from pygame.locals import *
from sys import exit

background_image = 'terain7.png'

pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Pygame Demo")
background = pygame.image.load(background_image).convert()

while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            exit()
    screen.blit(background, (0,0))
    pygame.display.update()

You will also need to provide a background image (terain7.png) in the same folder as your gaming module in order for the display to show that image. Now run the script and you should see the below pop up with any background image which you have included together with your gaming module.

Pygame
Pygame

Pygame engine starts slowly which is a common problem for all the python programs but once it is ready then it will operate smoothly!