Python Tutorial

Introduction Python Features Python Applications System requirements for Python Python Installation Python Basics Python Variables Python Data Types Python IDE Python Keywords Python Operators Python Comments Python Pass Statement

Python Conditional Statements

Python if Statement Python elif Statement Python If-else statement Python Switch Case

Python Loops

Python for loop Python while loop Python Break Statement Python Continue Statement Python Goto Statement

Python Arrays

Python Array Python Matrix

Python Strings

Python Strings Python Regex

Python Built-in Data Structure

Python Lists Python Tuples Python Lists vs Tuples Python Dictionary Python Sets

Python Functions

Python Function Python min() function Python max() function Python User-define Functions Python Built-in Functions Anonymous/Lambda Function in Python

Python File Handling

Python File Handling Python Read CSV Python Write CSV Python Read Excel Python Write Excel Python Read Text File Python Write Text File Read JSON File in Python

Python Exception Handling

Python Exception Handling Python Errors and exceptions Python Assert

Python OOPs Concept

OOPs Concepts in Python Classes & Objects in Python Inheritance in Python Polymorphism in Python Python Encapsulation Python Constructor Static Variables in Python Abstraction in Python

Python Iterators

Iterators in Python Yield Statement In Python

Python Generators

Python Generator

Python Decorators

Python Decorator

Python Functions and Methods

Python Built-in Functions Python String Methods Python List Methods Python Dictionary Methods Python Tuple Methods Python Set Methods

Python Modules

Python Modules Python Datetime Module Python Calendar Module  

Python MySQL

Python MySQL Python MySQL Update Operation Python MySQL Delete Operation

Python MongoDB

Python MongoDB

Python Data Structure Implementation

Python Stack Python Queue Python Hash Table Python Graph

Python Advance Topics

Speech Recognition in Python Face Recognition in Python Python Rest API Python Command Line Arguments Python JSON Python Virtual Environment Type Casting in Python Collections in python Python Enumerate Python Debugger Python DefaultDict

Misc

Python PPTX Python Pickle Python Seaborn Python Coroutine Python EOL Python Infinity Python math.cos and math.acos function Python Project Ideas Based On Django Reverse a String in Python Reverse a Number in Python Python Word Tokenizer Python Trigonometric Functions Python try catch exception GUI Calculator in Python Implementing geometric shapes into the game in python Installing Packages in Python Python Try Except Python Sending Email Socket Programming in Python Python CGI Programming Python Data Structures Python abstract class Python Compiler Python K-Means Clustering List Comprehension in Python3 NSE Tools In Python Operator Module In Python Palindrome In Python Permutations in Python Pillow Python introduction and setup Python Functionalities of Pillow Module Python Argmin Python whois Python JSON Schema Python lock Return Statement In Python Reverse a sentence In Python tell() function in Python Why learn Python? Write Dictionary to CSV in Python Write a String in Python Binary Search Visualization using Pygame in Python Latest Project Ideas using Python 2022 Closest Pair of Points in Python ComboBox in Python Python vs R Python Ternary Operators Self in Python Python vs Java Python Modulo Python Packages Python Syntax Python Uses Python Logical Operators Python Multiprocessing Python History Difference between Input() and raw_input() functions in Python Conditional Statements in python Confusion Matrix Visualization Python Python Algorithms Python Modules List Difference between Python 2 and Python 3 Is Python Case Sensitive Method Overloading in Python Python Arithmetic Operators Design patterns in python Assignment Operators in Python Is Python Object Oriented Programming language Division in Python Python exit commands Continue And Pass Statements In Python Colors In Python Convert String Into Int In Python Convert String To Binary In Python Convert Uppercase To Lowercase In Python Convert XML To JSON In Python Converting Set To List In Python Covariance In Python CSV Module In Python Decision Tree In Python Difference Between Yield And Return In Python Dynamic Typing In Python Abstract design pattern in python Builder design pattern in python Prototype design pattern in Python Creational design patterns in Python

How to

How to convert integer to float in Python How to reverse a string in Python How to take input in Python How to install Python in Windows How to install Python in Ubuntu How to install PIP in Python How to call a function in Python How to download Python How to comment multiple lines in Python How to create a file in Python How to create a list in Python How to declare array in Python How to clear screen in Python How to convert string to list in Python How to take multiple inputs in Python How to write a program in Python How to compare two strings in Python How to create a dictionary in Python How to create an array in Python How to update Python How to compare two lists in Python How to concatenate two strings in Python How to print pattern in Python How to check data type in python How to slice a list in python How to implement classifiers in Python How To Print Colored Text in Python How to develop a game in python How to print in same line in python How to create a class in python How to find square root in python How to import numy in python How to import pandas in python How to uninstall python How to upgrade PIP in python How to append a string in python How to open a file in python

Sorting

Python Sort List Sort Dictionary in Python Python sort() function Python Bubble Sort

Programs

Factorial Program in Python Prime Number Program in Python Fibonacci Series Program in Python Leap Year Program in Python Palindrome Program in Python Check Palindrome In Python Calculator Program in Python Armstrong Number Program in Python Python Program to add two numbers Anagram Program in Python Even Odd Program in Python GCD Program in Python Python Exit Program Python Program to check Leap Year Operator Overloading in Python Pointers in Python Python Not Equal Operator Raise Exception in Python Salary of Python Developers in India What is a Script in Python Singleton design pattern in python

How to develop a game in python

Fun always makes a task interesting and easy to execute. Learning in the same theoretical way at some point reaches the boring spot. In this article, using some Python knowledge, let us build a game – remember the game we played as children on our little Nokia cell phones?

Let us now build the “Hungry snake game”.

Python is a very user-friendly language. Its library provides many inbuilt functions and modules to make every complex task easy and approachable for beginners. Then, does it help in creating games? Of course, yes!

There is an inbuilt library in Python called the pygame library. It is a set of modules. Just as the name suggests, it is used to develop games. It provides great help to the designers with suitable graphics, animations, and even sounds.

Pete Shinners developed this cross-platform set of modules.

It is no big deal to learn about the module. It would be best if you had a basic understanding of Python language and its concepts. Let’s start by installing the module:

Installation

To use the module, we need to install it first, and for that, all you need to do is to type a command in the cmd terminal; follow the below steps:

1. Open cmd from the start menu

2. Type the command:

pip install pygame

3. Open the anaconda terminal prompt and type the same command if you are using anaconda.

Creating a simple pygame window:

We cannot play the game in the output terminal like executing a program. We need to create a separate window using pygame to play the game.

Program:

import pygame    
pygame. init ()    
scr = pygame. display. set_mode ((500, 600))    
flag = False    
    
while flag != True:    
    for event in pygame. event. get ():    
        if event. type == pygame. QUIT:    
            flag = True    
            pygame. display. flip ()

Output: A 500 * 600 (Width * Height) pygame empty window will be created.

How to Develop a Game in Python
How to Develop a Game in Python

Understanding:

  1. pygame. init (): init () stands for initializing. It is the same as in the concept of classes and objects in Python. Here, it is used to initialize the modules in pygame.
  2. pygame. display. set_mode ((width, height)): It gives dimensions to the pygame window to be created.
  3. pygame. event. get (): It is used to get or obtain the event/ action performed and do the tasks accordingly, like when the user hits the close button.
  4. pygame. QUIT: When the user clicks the close button of the pygame window, this function closes the window by quitting the program execution.
  5. flip (): This function applies any update to the whole program/ game.

These are the functions we used from pygame to create a window. All we did in the program is:

We imported the pygame; we gave the dimensions to the window. We took a flag variable and initialized it to False. Now, we ran a loop with the user's events/ actions, which we get by the get () function. When the user clicks close, the flag is set to True, and the loop is broken; the window will be closed.

Graphics/ designs:

In the module, many pre-defined functions help us create designs and draw shapes on the screen.

First, let us go through the functions and their syntaxes:

The module used to draw geometrical shapes is the draw module:

We can use different constructors to draw these shapes with different arguments. In the below program, we are going to use:

1. To draw a rectangle:

pygame. draw. rect (surface, color, dimensions, fill)
  • For color, we use the color codes.
  • If we give fill == 0: fill the rectangle with a color

                   fill > 0: for line thickness

                   fill < 0: nothing will be drawn

2. To draw a line:

pygame. draw. line(surface, color, initial_pos, final_pos, width)
  • width represents the thickness of the line
  • If width >= 1  : line thickness is grown
  • Default width = 1
  • If width < 1, nothing will be drawn

3. To draw multiple lines continuously:

pygame. draw. lines (surface, color, closed? width)
  • This function is used to draw multiple lines with the given coordinates
  • Closed?:  if it is given True, an additional line segment will be drawn to close the drawn lines into a closed figure.

4. To draw an ellipse:

pygame. draw. ellipse (surface, color, dimensions, fill)
  • Dimensions of the rectangle should be given by which the ellipse will be bounded.
  • If we give fill == 0: fills the ellipse with a color

                   fill > 0: for line thickness

                   fill < 0: nothing will be drawn

5. To draw a polygon:

pygame. draw. polygon (surface, color, points, fill)

6. To draw an arc:

pygame. draw. arc (surface, color, intial_angle, stop_angle,  width)

7. To draw a circle:

pygame. draw. circle (surface, color, center_point, radius)

Example:

Here is a sample program using the above functions:

import pygame    
from math import pi    
pygame. init ()    
  
size = [500, 600]    
window = pygame.display.set_mode(size)    




flag = False    
seconds = pygame. time. Clock()    
while not flag:    
    
    seconds. tick(10)    
    for event in pygame. event. get():  
        if event. type == pygame. QUIT:  
            flag = True 
    window. fill ((255, 255, 255))    
    pygame. draw. line (window, (255, 255, 0), [0, 0], [50,40], 5)    
    pygame. draw. lines (window, (0, 255, 0), False, [[0, 70], [40, 70], [150, 80],  [220, 30]], 5)    
    pygame. draw. rect (window, (0, 255, 0), [65, 17, 54, 22], 3)    
    pygame. draw. rect (window, (0, 255, 0), [190, 15, 58, 30])    
    pygame. draw. ellipse (window, (255, 0, 0), [245, 15, 30, 40], 2)    
    pygame. draw. ellipse (window, (255, 0, 0), [350, 10, 30, 20])    
    pygame. draw. polygon (window, (0, 0, 0), [[300, 100], [0, 200], [200, 200]], 5)    
    pygame. draw. circle (window, (0, 255, 255), [70, 250], 40)    
    pygame. draw. arc (window, (0, 255, 0), [220, 85, 150, 125], 0, pi / 2, 2)
    pygame. display. flip ()    
  
pygame. quit ()   

Understanding:

We imported pygame and pi from the math module. We used pi to specify the angle while drawing a circle. We created a window. We used:

  • pygame. time. Clock. tick (): time is a module used to keep track of time, and clock is an object. The tick function helps to compute the number of milliseconds passed after the previous call. We passed an argument – 10. The function will delay or slow the program than 10 frames per second, thus controlling the speed.

After that, we used the fill function to give the color code of white to fill the window with white color. We used the functions from the draw module to draw different shapes, from lines to circles.

Output:

How to Develop a Game in Python

Program to develop Snake Game

Now, it is time to jump into the concept, program for the snake game:

import random  
import pygame  
import Tkinter as tk  
from Tkinter import messagebox  
  
  
class cube (object):  
    rows = 20  
    w = 500  
  
    def __init__ (self, start, x_dir = 1, y_dir = 0, color = (255, 0, 0)):  
        self. pos = start  
        self. x_dir = 1  
        self. y_dir = 0  
        self. color = color  
  
    def movement (self, x_dir, y_dir):  
        self. x_dir = x_dir  
        self. y_dir = y_dir  
        self. pos = (self. pos[0] + self. x_dir, self. pos[1] + self. y_dir)  
  
    def draw (self, surface, flag = False):  
        dis = self. w // self. rows  
        i = self. pos [0]  
        j = self. pos [1]  
  
        pygame. draw. rect (surface, self. color, (i * dis + 1, j * dis + 1, dis - 2, dis - 2))  
        if flag:  
            centre = dis // 2  
            radius = 3  
            cirmid = (i * dis + centre - radius, j * dis + 8)  
            cirmid2 = (i * dis + dis - radius * 2, j * dis + 8)  
            pygame. draw. circle (surface, (0, 0, 0), cirmid, radius)  
            pygame. draw. circle (surface, (0, 0, 0), cirmid2, radius)  
  
  
class snake (object):  
    body = []  
    turns = {}  
  
    def __init__ (self, color, pos):  
        self.  color = color  
        self.  head = cube (pos)  
        self.  body.  append (self.  head)  
        self.  x_dir = 0  
        self.  y_dir = 1  
  
    def movement (self):  
        for event in pygame.  event.  get ():  
            if event.  type == pygame.  QUIT:  
                pygame.  quit ()  
  
            clicks = pygame.  key.  get_pressed ()
            for click in clicks:  
                if clicks [pygame.  K_LEFT]:  
                    self.  x_dir = -1  
                    self.  y_dir = 0  
                    self.  turns [self.  head.  pos [:]] = [self.  x_dir, self.  y_dir]  
  
                elif clicks [pygame.  K_RIGHT]:  
                    self.  x_dir = 1  
                    self.  y_dir = 0  
                    self.  turns [self.  head.  pos [:]] = [self.  x_dir, self.  y_dir]  
  
                elif clicks [pygame.  K_UP]:  
                    self.  x_dir = 0  
                    self.  y_dir = -1  
                    self.  turns [self.  head.  pos [:]] = [self.  x_dir, self.  y_dir]  
  
                elif clicks [pygame. K_DOWN]:  
                    self. x_dir = 0  
                    self. y_dir = 1  
                    self. turns [self. head. pos [:]] = [self. x_dir, self. y_dir]  
        # When snake hits the boundary wall  
        for i, j in enumerate (self. body):  
            position = j. pos [:]  
            if position in self. turns:  
                turn = self. turns [position]  
                j. movement (turn [0], turn [1])  
                if i == len (self. body) - 1:  
                    self. turns. pop (position)  
            else:  
                if j. x_dir == -1 and j. pos [0] <= 0:  
                    j. pos = (j. rows - 1, j. pos [1])  
                elif j. x_dir == 1 and j. pos [0] >= j. rows - 1:  
                    j. pos = (0, j. pos [1])  
                elif j. y_dir == 1 and j. pos [1] >= j. rows - 1:  
                    j. pos = (j. pos [0], 0)  
                elif j. y_dir == -1 and j. pos [1] <= 0:  
                    j. pos = (j. pos [0], j. rows - 1)  
                else:  
                    j. movement(j. x_dir, j. y_dir)  
  
    def reset (self, pos):  
        self. head = cube (pos)  
        self. body = []  
        self. body. append (self. head)  
        self. turns = {}  
        self. x_dir = 0  
        self. y_dir = 1  
#To add a cube after eating
    def pluscube (self):  
        snaketail = self. body [-1]  
        x, y= snaketail. x_dir, snaketail. y_dir  
  
        if x == 1 and y== 0:  
            self. body. append (cube ((snaketail. pos [0] - 1, snaketail. pos [1])))  
        elif x == -1 and y == 0:  
            self. body. append (cube ((snaketail. pos [0] + 1, snaketail. pos [1])))  
        elif x == 0 and y== 1:  
            self. body. append (cube ((snaketail. pos [0], snaketail. pos [1] - 1)))  
        elif x == 0 and y== -1:  
            self. body. append (cube ((snaketail. pos [0], snaketail. pos [1] + 1)))  
  
        self. body [-1]. x_dir = x  
        self. body [-1]. y_dir = y 
  
    def draw (self, surface):  
        for i, j in enumerate (self. body):  
            if i == 0:  
                j. draw (surface, True)  
            else:  
                j. draw (surface)  
 
  
def Grid (w, rows, surface):  
    sizebetween = w // rows  
  
    x = 0  
    y = 0  
    for i in range (rows):  
        x = x + sizebetween  
        y = y + sizebetween  
        # draw grid line  
        pygame. draw. line (surface, (255, 255, 255), (x, 0), (x, w))  
        pygame. draw. line (surface, (255, 255, 255), (0, y), (w, y))  
  
def Redraw (surface):  
    global rows, width, s, snack  
    surface. fill ((0, 0, 0))  
    s. draw (surface)  
    snack. draw (surface)  
    Grid (width, rows, surface)  
    pygame. display. update ()  
  
def randsnack (rows, item):  
    positions = item. body 
  
    while True:  
        x = random. randrange (rows)  
        y = random. randrange (rows)  
        if len (list (filter (lambda z: z. pos == (x, y), positions))) > 0:  
            continue  
        else:  
            break  
  
    return (x, y)  
  
def screen_message (subject, content):  
    root = tk. Tk ()  
    root. Attributes ("-topmost", True)  
    root. withdraw ()  
    messagebox. showinfo (subject, content)  
    try:  
        root. destroy ()  
    except:  
        pass  
  
def main ():  
    global width, rows, s, snack  
    width = 500  
    rows = 20  
    win = pygame. display. set_mode ((width, width))  
    s = snake ((255, 0, 0), (10, 10))  
    snack = cube (randsnack (rows, s), color = (0, 255, 0))  
    flag = True  
  
    clock = pygame. time. Clock ()  
  
    while flag:  
        pygame. time. delay (50)  
        clock. tick (10)  
        s. movement ()  
        if s. body[0]. pos == snack. pos:  
            s. pluscube () 
            snack = cube (randsnack (rows, s), color = (0, 255, 0))  
  
        for x in range (len (s. body)):  
            if s. body [x]. pos in list (map (lambda z: z. pos, s.  body [x + 1 :])):  
                print ('Your score: \n', len (s. body))  
                screen_message ('Game over! \n', 'Play again. . . \n')  
                s. reset ((10, 10))  
                break  
  
        Redraw (win) 
main ()  

Output:

How to Develop a Game in Python

If the snake runs into its body, the game will be over, and the above message box will be displayed. We used Tkinter to make the dialog box, and all the other functions are from pygame.

You can refer to the official website to know more about pygame and its functions.



ADVERTISEMENT
ADVERTISEMENT