How To Make a Game In Python With Source Code

In this tutorial on How to Make a Game in Python, we will make a program for a game called Simple Snake Game.

Snake Game In Python : Project Information

Project Name:Game In Python
Abstract:Python provides a built-in library called pygame, which used to develop the game.
Language/s Used:Python with Tkinter GUI Library
Python version (Recommended):2.x or 3.x
Database:None
Type:Python App
Developer:IT SOURCECODE
Updates:0
Game In Python – Project Information

Background and Setup

The SDL library is wrapped up in pygame, which is written in Python. SDL stands for Simple DirectMedia Layer. SDL gives you access to your system’s sound, video, mouse, keyboard, and joystick hardware, no matter what platform you’re using.

At first, pygame was made to replace the PySDL project, which had stopped moving forward. Both SDL and pygame work on multiple platforms, so you can write games and rich multimedia programs in Python for any platform that supports them.

Prerequisites

To learn how to use pygame, we need to know the Python programming language.

Installing Pygame

Before we start creating python game, we want to install first the pygame library.

To install pygame on your platform, use the proper pip command:

#command for installing pygame library

pip install pygame

Pygame Concepts

As pygame and the SDL library can be used on a variety of platforms and devices, they both need to define and work with abstractions for different hardware realities.

If you understand these ideas and abstractions, you will be able to make your own games.

Initialization and Modules

The pygame library is made up of several different Python constructs, which are called modules. These modules give you abstract access to specific hardware on your system and standard ways to work with it.

For example, display lets you access your video display in the same way every time, while joystick lets you control your joystick in a different way every time.

In the above example, after importing the pygame library, the first thing you did was set up PyGame with pygame.init (). This function calls the init() functions of all the pygame modules that are already installed.

Since these modules are just abstractions for specific hardware, this initialization step is needed so that you can use the same code on Linux, Windows, and Mac.

Displays and Surfaces

In addition to the modules, pygame has a number of Python classes that hold ideas that don’t depend on the hardware. One of these is the Surface, which, at its most basic, lets you draw on a rectangular area.

In pygame, surface objects are used in a lot of different ways. You’ll learn later how to put a picture on a Surface and show it on the screen.

Everything in pygame is shown on a single display that the user makes. This display can be a window or the whole screen. .set mode() is used to make the display.

It returns a Surface that shows what part of the window is visible. You give this Surface to drawing functions like pygame.draw.circle(), and when you call pygame.display.flip, the contents of this Surface are sent to the screen ().

How To Make a Game In Python?

Python is the most flexible language, and it is used in almost every field, including Web development, machine learning, artificial intelligence, GUI applications, and game development.

A built-in library in Python called pygame was used to make the game. Once we know how Python programming works on a basic level, we can use the pygame library to make games with good graphics, animation, and sound.

Pygame is a library that can be used to make video games on any platform. It comes with graphics and sound libraries so that the user can play a standard game.

Pete Shinners is making it to take the place of PySDL.

About Game in Python

In this tutorial I will teach you how to make game in python, this game in python is use for educational purposes only, and this article is a game development python to enhance your logic skills and develop more ideas about python programming.

This game engine python also includes a python game source code download.

Example Program for Simple Pygame

This is an example of how to make a simple pygame window.

Code:

import pygame

pygame.init()
screen = pygame.display.set_mode((400, 500))
done = False

while not done:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            done = True
    pygame.display.flip()    

Program Output:

Simple Pygame Program Output
Simple Pygame Program Output

Code Explanation

Here’s the code explanation about the code given above.

  • import pygame – It is the module which allows us to work with all function of pygame.
  • pygame.init() – It is used to initialize all the required modules of the pygame.
  • pygame.display.set_mode((width, height)) – It is used to resized the window size. It will return the surface object. The surface object is used to perform graphical operations.
  • pygame.event.get() – It makes the event queue empty. If we do not call it, the window messages will start to pile up and, the game will become unresponsive in the opinion of the operating system.
  • pygame.QUIT – It is used to dismiss the event when we click on the cross button at the corner of the window.
  • pygame.display.flip() – It is used to reflect any update to the game. If we make any change then we need to call the display.flip() function.

Steps on how to Create a Simple Snake Game in Python

Before we start creating a Simple Snake Game in Python, make sure that you have PyCharm IDE installed in your computer.

How To Make a Game In Python With Source Code

  • Step 1: Create a Project Name.

    Open Pycharm IDE and click “file” after that create a project name and then click “create” button.
    Create a Project for Snake Game

  • Step 2: Create a Python File.

    right click” your project name folder and choose new and then click “python file“.
    Create Python File in Snake Water Gun Game

  • Step 3: Name your File.

    name your python file and click “enter” to start creating on How To Make Game With Python.
    Rename Python File for Snake Game

  • Step 4: Now you can start create a game.

    You are free to copy the code given below and start creating on How To Make a Snake Game In Python.

Program for Snake Game in Python Code Explanation

Here’s the step by step program explanation on how to make a Game in Python.

1. Import Libraries

In this part line of code is for importing libraries of the game.

Code:

import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox

2. Class Cube

The line of code given below is about cube class that include the design of the snake given in the program.

Code:

class cube(object):
    rows = 20
    w = 500

    def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)):
        self.pos = start
        self.dirnx = 1
        self.dirny = 0
        self.color = color

    def move(self, dirnx, dirny):
        self.dirnx = dirnx
        self.dirny = dirny
        self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)

    def draw(self, surface, eyes=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 eyes:
            centre = dis // 2
            radius = 3
            circleMiddle = (i * dis + centre - radius, j * dis + 8)
            circleMiddle2 = (i * dis + dis - radius * 2, j * dis + 8)
            pygame.draw.circle(surface, (0, 0, 0), circleMiddle, radius)
            pygame.draw.circle(surface, (0, 0, 0), circleMiddle2, radius)

3. Snake Class

This class is defined for snake design and its movement.

Code:

class snake(object):
    body = []
    turns = {}

    def __init__(self, color, pos):
        self.color = color
        self.head = cube(pos)
        self.body.append(self.head)
        self.dirnx = 0
        self.dirny = 1

    def move(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            keys = pygame.key.get_pressed()

4. Snake Key Movement

It will manage the keys movement for the snake.

Code:

            for key in keys:
                if keys[pygame.K_LEFT]:
                    self.dirnx = -1
                    self.dirny = 0
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_RIGHT]:
                    self.dirnx = 1
                    self.dirny = 0
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_UP]:
                    self.dirnx = 0
                    self.dirny = -1
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_DOWN]:
                    self.dirnx = 0
                    self.dirny = 1
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

5. Boundary Wall

Snake when hit the boundary wall.

Code:

        for i, c in enumerate(self.body):
            p = c.pos[:]
            if p in self.turns:
                turn = self.turns[p]
                c.move(turn[0], turn[1])
                if i == len(self.body) - 1:
                    self.turns.pop(p)
            else:
                if c.dirnx == -1 and c.pos[0] <= 0:
                    c.pos = (c.rows - 1, c.pos[1])
                elif c.dirnx == 1 and c.pos[0] >= c.rows - 1:
                    c.pos = (0, c.pos[1])
                elif c.dirny == 1 and c.pos[1] >= c.rows - 1:
                    c.pos = (c.pos[0], 0)
                elif c.dirny == -1 and c.pos[1] <= 0:
                    c.pos = (c.pos[0], c.rows - 1)
                else:
                    c.move(c.dirnx, c.dirny)

6. Add New Cube

Code:

It will add the new cube in snake tail after every successful score.

    def addCube(self):
        tail = self.body[-1]
        dx, dy = tail.dirnx, tail.dirny

        if dx == 1 and dy == 0:
            self.body.append(cube((tail.pos[0] - 1, tail.pos[1])))
        elif dx == -1 and dy == 0:
            self.body.append(cube((tail.pos[0] + 1, tail.pos[1])))
        elif dx == 0 and dy == 1:
            self.body.append(cube((tail.pos[0], tail.pos[1] - 1)))
        elif dx == 0 and dy == -1:
            self.body.append(cube((tail.pos[0], tail.pos[1] + 1)))

        self.body[-1].dirnx = dx
        self.body[-1].dirny = dy

7. Draw Grid

In this line of code draw the grid line of the game.

Code:

def drawGrid(w, rows, surface):
    sizeBtwn = w // rows

    x = 0
    y = 0
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn
        # 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))

8. Draw Game Surface

This class define for draw game surface.

def redrawWindow(surface):
    global rows, width, s, snack
    # This is used to grid surface
    surface.fill((0, 0, 0))
    s.draw(surface)
    snack.draw(surface)
    drawGrid(width, rows, surface)
    pygame.display.update()

9. Display Message

Using Tkinter function to display message.

Code:

def message_box(subject, content):
    root = tk.Tk()
    root.attributes("-topmost", True)
    root.withdraw()
    messagebox.showinfo(subject, content)
    try:
        root.destroy()
    except:
        pass

10. Main Function

This line of code is the main function of the program.

Code:

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(randomSnack(rows, s), color=(0, 255, 0))
    flag = True

    clock = pygame.time.Clock()

    while flag:
        pygame.time.delay(50)
        clock.tick(10)
        s.move()
        if s.body[0].pos == snack.pos:
            s.addCube()
            snack = cube(randomSnack(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('Score: \n', len(s.body))
                message_box('You Lost!\n', 'Play again...\n')
                s.reset((10, 10))
                break

        redrawWindow(win)

    pass


main()

Complete Source Code on How To Make A Game in Python

Here’s the Complete Source Code in Creating a Simple Snake Game in Python.

# Snake Tutorial Using Pygame

import math
import random
import pygame
import tkinter as tk
from tkinter import messagebox


class cube(object):
    rows = 20
    w = 500

    def __init__(self, start, dirnx=1, dirny=0, color=(255, 0, 0)):
        self.pos = start
        self.dirnx = 1
        self.dirny = 0
        self.color = color

    def move(self, dirnx, dirny):
        self.dirnx = dirnx
        self.dirny = dirny
        self.pos = (self.pos[0] + self.dirnx, self.pos[1] + self.dirny)

    def draw(self, surface, eyes=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 eyes:
            centre = dis // 2
            radius = 3
            circleMiddle = (i * dis + centre - radius, j * dis + 8)
            circleMiddle2 = (i * dis + dis - radius * 2, j * dis + 8)
            pygame.draw.circle(surface, (0, 0, 0), circleMiddle, radius)
            pygame.draw.circle(surface, (0, 0, 0), circleMiddle2, radius)

        # This class is defined for snake design and its movement


class snake(object):
    body = []
    turns = {}

    def __init__(self, color, pos):
        self.color = color
        self.head = cube(pos)
        self.body.append(self.head)
        self.dirnx = 0
        self.dirny = 1

    def move(self):
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()

            keys = pygame.key.get_pressed()
            # It will manage the keys movement for the snake
            for key in keys:
                if keys[pygame.K_LEFT]:
                    self.dirnx = -1
                    self.dirny = 0
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_RIGHT]:
                    self.dirnx = 1
                    self.dirny = 0
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_UP]:
                    self.dirnx = 0
                    self.dirny = -1
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]

                elif keys[pygame.K_DOWN]:
                    self.dirnx = 0
                    self.dirny = 1
                    self.turns[self.head.pos[:]] = [self.dirnx, self.dirny]
                    # Snake when hit the boundary wall
        for i, c in enumerate(self.body):
            p = c.pos[:]
            if p in self.turns:
                turn = self.turns[p]
                c.move(turn[0], turn[1])
                if i == len(self.body) - 1:
                    self.turns.pop(p)
            else:
                if c.dirnx == -1 and c.pos[0] <= 0:
                    c.pos = (c.rows - 1, c.pos[1])
                elif c.dirnx == 1 and c.pos[0] >= c.rows - 1:
                    c.pos = (0, c.pos[1])
                elif c.dirny == 1 and c.pos[1] >= c.rows - 1:
                    c.pos = (c.pos[0], 0)
                elif c.dirny == -1 and c.pos[1] <= 0:
                    c.pos = (c.pos[0], c.rows - 1)
                else:
                    c.move(c.dirnx, c.dirny)

    def reset(self, pos):
        self.head = cube(pos)
        self.body = []
        self.body.append(self.head)
        self.turns = {}
        self.dirnx = 0
        self.dirny = 1

    # It will add the new cube in snake tail after every successful score
    def addCube(self):
        tail = self.body[-1]
        dx, dy = tail.dirnx, tail.dirny

        if dx == 1 and dy == 0:
            self.body.append(cube((tail.pos[0] - 1, tail.pos[1])))
        elif dx == -1 and dy == 0:
            self.body.append(cube((tail.pos[0] + 1, tail.pos[1])))
        elif dx == 0 and dy == 1:
            self.body.append(cube((tail.pos[0], tail.pos[1] - 1)))
        elif dx == 0 and dy == -1:
            self.body.append(cube((tail.pos[0], tail.pos[1] + 1)))

        self.body[-1].dirnx = dx
        self.body[-1].dirny = dy

    def draw(self, surface):
        for i, c in enumerate(self.body):
            if i == 0:
                c.draw(surface, True)
            else:
                c.draw(surface)


def drawGrid(w, rows, surface):
    sizeBtwn = w // rows

    x = 0
    y = 0
    for l in range(rows):
        x = x + sizeBtwn
        y = y + sizeBtwn
        # 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))

    # This class define for draw game surface


def redrawWindow(surface):
    global rows, width, s, snack
    # This is used to grid surface
    surface.fill((0, 0, 0))
    s.draw(surface)
    snack.draw(surface)
    drawGrid(width, rows, surface)
    pygame.display.update()


def randomSnack(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)


# Using Tkinter function to display message
def message_box(subject, content):
    root = tk.Tk()
    root.attributes("-topmost", True)
    root.withdraw()
    messagebox.showinfo(subject, content)
    try:
        root.destroy()
    except:
        pass

    # main() function


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(randomSnack(rows, s), color=(0, 255, 0))
    flag = True

    clock = pygame.time.Clock()

    while flag:
        pygame.time.delay(50)
        clock.tick(10)
        s.move()
        if s.body[0].pos == snack.pos:
            s.addCube()
            snack = cube(randomSnack(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('Score: \n', len(s.body))
                message_box('You Lost!\n', 'Play again...\n')
                s.reset((10, 10))
                break

        redrawWindow(win)

    pass


main()

Final Output:

Snake Game in Python Output
Snake Game in Python Output

Summary

We have successfully discussed about on how to create a Game in Python name Simple Snake Game, We have completely explain the step by step process of the program. I hope you learned a lot on how to create a Game using Python Programming.

Recommendation

  • If you want to explore your knowledge in developing a Game in Python, I have here the list of Code for Game in Python with Free Source Code.

Inquiries

If you have any questions or suggestions about How To Make a Game In Python , please feel free to comment below.

Leave a Comment