You are on page 1of 56

Shree Mouni Vidhyapeeth’s

Institute of Civil and Rural Engineering,


Gargoti
INDUSTRIAL TRAINING
At

Bhudargad Gramin Vikas Sanstha Khanapur


On
Game Development
Using Python
Submitted by:

Kamble Asmita Dhanaji


In Partial Fulfilment of

Diploma in Computer Engineering.


Under the guidance of
Mr. Kalke V.S.

Department of Computer Engineering (Un-AidedWing)


INSTITUTE OF CIVIL & RURAL ENGINEERING, GARGOTI
(2020-2021)
Acknowledgments

I would like to express my deepands in ceregratitude to my Guide


Mr.Kalke V.S. Department of Computer Engineering, for guiding me to
accomplish this Industrial Training.

I express my deep gratitude to Prof.PoreM.E., Head of Computer


Engineering Department,for his valuable guidance and constant
encouragement. I am very much thankful to Mr.Bhosale
A.R.,Principal,Institute of Civil & Rural Engineering, Gargoti.I would also like
to acknowledge the Bhudargad Gramin vikas sanstha khanapur, for allowing
me to under go the Industrial Training at their company.Mr. Kalke V.S. is
acknowledged for providing the information and help duringTraining period.

Last but not least, it would not have possible for me to complete the
training without support of my family members. Constant encouragement
and support of my Father and Mother made me possible to complete the
work.

Place:ICRE,Gargoti. Kamble Asmita Dhanaji

Date:
INSTITUTE OF CIVIL AND RURAL ENGINEERING, GARGOTI
DEPARTMENT OF COMPUTER ENGINEERING

CERTIFICATE

This is to certify tha, Kamble Asmita Dhanaji as satisfactorily completed the


Industrial Training at “Bhudargad Gramin Vikas Sanstha Khanapur”. This report
is being submitted in partial fulfilment for the award of Diploma in Computer
Engineering Affiliated to Maharashtra State Board of Technical Education,
Mumbai, under my guidance.

Prof. Kalke V.S. Mr.PoreM.E.


Guide Professor & HOD

Mr.BhosaleA.R.
Principal
InstituteofCivil&RuralEngineering,Gargoti.
Sr.no. title Page no.
1 Company Profile
2 Module 1
3 Chapter 1 – Installation Python
4 Chapter 2 – Python Basic Syntax
5 Chapter 3 – Python Basic Operators
6 Chapter 4 – Python Decision Making
7 Chapter 5 – Python Loops
8 Chapter 6 – Python Numbers
9 Chapter 7 – Python Date & Time
10 Chapter 8 – Python Function
11 Chapter 9 – Python Module
12 Chapter 10 – Python File Handling
13 Chapter 11 – Python Exception
14 Chapter 12 – Python Classes & Object
15 Module 2
16 Module 3
Company Profile

Bhudargad Gramin Vikas Sanstha Khanapur was established in 2008.The


organization has been set up with the objective of imparting skills training to the
youth and women in rural areas, imparting vocational education and assisting
them in gaining and creating employment opportunities. Mr. Praveen Singh
Sawant, the head of the organization, is involved in both business and social
sciences by this they directly comes in touch to serve society via Bhudargad
Gramin Vikas Sanstha Khanapur.

Bhudargad Gramin Vikas Sanstha Khanapur provides training in


Electrician, Fitter, Diesel Mechanic, Tailoring, Carpentering, Computer
Hardware and Programming and Hotel Management. Carrying out tree planting
campaigns for environmental protection, Taking women for women’s
empowerment, Organizing lectures and competitions to guide students, To
provide training for women self help group formation and to provide guidance
for the loan process, The organization conducts drip irrigation guidance fairs for
farmers and co-operates for it mainly with social commitment.

Training Modules

1] Python Basics and advance Programing

2] Python GUI Programming

3] Game Development using python


Module 1
Overview of Python
Python is a high-level, interpreted, interactive and object-oriented scripting
language. Python is designed to be highly readable. It uses English keywords
frequently where as other languages use punctuation, and it has fewer syntactical
constructions than other languages.

Python is Interpreted : Python is processed at runtime by the interpreter.


You do not need to compile your program before executing it. This is similar
to PERL and PHP.

Python is Interactive: You can actually sit at a Python prompt and interact
with the interpreter directly to write your programs.

Python is Object-Oriented: Python supports Object-Oriented style or


technique of programming that encapsulates code within objects.

Python is a Beginner's Language: Python is a great language for the


beginner-level programmers and supports the development of a wide range of
applications from simple text processing to WWW browsers to games.

History of Python

Python was developed by Guido van Rossum in the late eighties and early nineties
atthe National Research Institute for Mathematics and Computer Science in the
Netherlands.
Python is derived from many other languages, including ABC, Modula-3, C, C++,
Algol-68, SmallTalk, Unix shell, and other scripting languages.
Python is copyrighted. Like Perl, Python source code is now available under the GNU
General Public License (GPL).
Python is now maintained by a core development team at the institute, although
Guido van Rossum still holds a vital role in directing its progress.─
Python Features
Easy-to-learn: Python has few keywords, simple structure, and a clearly
defined syntax. This allows the student to pick up the language quickly.

Easy-to-read: Python code is more clearly defined and visible to the eyes.

Easy-to-maintain: Python's source code is fairly easy-to- maintain.

A broad standard library: Python's bulk of the library is very portable and
cross-platform compatible on UNIX, Windows, and Macintosh.

Interactive Mode: Python has support for an interactive mode which allows
interactive testing and debugging of snippets of code.

Portable: Python can run on a wide variety of hardware platforms and has the
same interface on all platforms.

Extendable: You can add low-level modules to the Python interpreter. These
modules enable programmers to add to or customize their tools to be more
efficient.

Databases: Python provides interfaces to all major commercial databases.

GUI Programming: Python supports GUI applications that can be created and
ported to many system calls, libraries, and windows systems, such as Windows
MFC, Macintosh, and the X Window system of Unix.

Scalable: Python provides a better structure and support for large programs
than shell scripting.
Chapter 1 - Installing Python─

Windows Installation
Open a Web browser and go to http://www.python.org/download/

Follow the link for the Windows installer python-XYZ.msi file where XYZ is the
version you need to install.

To use this installer python-XYZ.msi, the Windows system must support


Microsoft Installer 2.0. Save the installer file to your local machine and then
run it to find out if your machine supports MSI.

Run the downloaded file. This brings up the Python install wizard, which is
really easy to use. Just accept the default settings, wait until the install is
finished, and you are done.

Unix and Linux Installation


Open a Web browser and go to http://www.python.org/download/.

Follow the link to download zipped source code available for Unix/Linux.

Download and extract files.

Editing the Modules/Setup file if you want to customize some options.

run ./configure script

make install
This installs Python at standard location /usr/local/bin and its libraries at
/usr/local/lib/pythonXX where XX is the version of Python.
Chapter 2 – Python Basic Syntax

First Python Program

print("Hello, Python!");
print('Hello, Students!');

Multi-Line Statements
print("Hello, \
Python!");
print('Hello, \
Students!');

Comments in Python
A hash sign (#) that is not inside a string literal begins a comment.

#print("Hello, Python!"); This is single line comment


print('Hello, Students!');

“”print("Hello, Python!");
This is single multiline comment”””
print('Hello, Students!');

Waiting for the User

a=int(input("Enter value for a "))


b=int(input("\nEnter value for b "))
c=a+b
print("Result is ",c)

Multiple Statements on a Single Line


print("Hello Students!!!!");print("Welcome to Python
Workshop!!!!");
Python Keywords
Python Variable Type

Assigning Values to Variables

a = 100 # An integer assignment


b = 3.14 # A floating point
c = "John" # A string
print(a);
print(b);
print (c);
Multiple Assignment
a=b=c=1
#a, b, c = 1, 2, "john";
print(a);
print(b);
print (c);

Standard Data Types


Numbers
String
List
Tuple
Dictionary
Python Numbers
Number data types store numeric values. Number objects are created
when you
assign a value to them
a = 20
b = 10
print(a)
print(b)
You can also delete the reference to a number object by using the del
statement
a = 20
b = 10
del b
print(a)
print(b)
Python Strings
str ='Hello World!'
print(str)
print(str[0])
print(str[2:5])
print(str[2:])
print (str * 2)
print(str + "TESTING")

Python Lists
list1 = [ 121,'Present', 82.23,'Gargoti']
list2 = [123,'Absent']
print(list1 )
print(list1[0])
print(list1[1:4])
print(list1[2:])
print(list2 * 2)
print(list1 + list2)

Python Tuples
a = ( 121,'Present', 82.23,'Gargoti')
b = (123,'Absent')
print(a)
print(a[0])
print(a[1:4])
print(a[2:])
print(b * 2)
print(a + b)
Difference Between Python Lists & Tuple
a = [ 121,'Present', 82.23,'Gargoti']
b = (123,'Absent')
a[0]=525
b[0]=786
print(a)
print(b)

Python Dictionary
Python's dictionaries are kind of hash table type. They work like
associative arrays or hashes found in Perl and consist of key-value
pairs.

dict = {}
dict['one'] = "This is one named dictionary"
dict[2] = "This is two named dictionary"

print(dict['one'])
print(dict[2])

print('\n#################################\n')

c = {'Name': 'Sachin','PRN Code':67340, 'Dept': 'computer'}


print(c)
print(c.keys())
print(c.values())
Data Type Conversion

a=25
b=float(a)
c=oct(a)
d=hex(a)

print("Int a =",a)
print("float b =",b)
print("Octal c =",c)
print("Hex d =",d)
Chapter 3 – Python Basic Operators

Python Arithmetic Operators


a = 21
b = 10
c=a%b
print ("After operation c is ", c)

a=2
b=3
c = a**b
print ("After ** operation c is ", c)
a = 10
b=5
c = a//b
print("After// operation c is ", c)

Python Comparison Operators


a = 21
b = 10
c = a != b
print ("After operation c is ", c)

a = 21
b = 10
c = a != b
print ("After operation c is ", c)

Python Comparison Operators


a = 21
c=1
c %= a
print ("After operation c is ", c)
Python Bitwise Operators

a = 21
c=1
c %= a
print ("After operation c is ", c)

#&,|,^,~,<<,>>
a=0
b=1
c = b<<2
print ("After operation c is ", c)
Python Membership Operators
#in , not in
a = 10
list = [1, 2, 3, 4, 5 ];

if ( a not in list ):
print("true")
else:
print("false")

Python Identity Operators


#is , is not
a = 10
b = 20
if ( a is not b ):
print("true")
else:
print("false")
Chapter 4 – Python Decision Making

If Statement
a = 100
if a:
print("Got a true expression value")
print(a)

b=0
if b:
print("Got a true expression value")
print(b)
print("Good bye!")

If else Statement
a = 100
b=50

if (a<b):
print("true expression")
print(a)
else:
print("false expression")
print(b)

The elif Statement


a = int(input("Enter a percentage "))
if (a<=59) & (a>=40):
print("Class Second")
elif (a<=74) & (a>=60) :
print("Class First")
elif (a<=100) & (a>=75):
print("Class Distinction")
else:
print("Take a rest")

Chapter 5 – Python Loops

while loop
#print all even numbers from 1 to 10
a=1
while (a <= 10):
print(a)
a=a+2
print("work is done")

for loop

for letter in 'Python': # First Example


print('Current Letter :', letter)
digits = [12, 19, 47]

for i in digits:
print(i)
else:
print("No items left.")

Iterating by Sequence Index


digits = [12, 19, 47]
for index in range(len(digits)):
print(digits [index], ' index is ',index)

#for loop to print odd even number


for num in range(10,20): #to iterate between 10 to 20
if num%2 == 0: #to determine the first factor
print(num, 'is even num')
else:
print(num,'is a odd number')

Loop Control Statements


#break,continue,pass statements
for letter in 'Python':
if letter == 'h':
continue
print('ur in pass block')
print('Current Letter :', letter)
print("Good bye!")
Chapter 6 – Python Numbers

Number Type Conversion a] while loop

Type int(x) to convert x to a plain integer.

Type long(x) to convert x to a long integer.

Type float(x) to convert x to a floating-point number

Type complex(x) to convert x to a complex number with real part


x and imaginary part zero.

Type complex(x, y) to convert x and y to a complex number with


real part x and imaginary part y. x and y are numeric expressions
Mathematical Functions

a=(23,5,38,45,2)
print(min(a))
print(max(a))
print(round(10.6))

Random Number Functions


Random numbers are used for games, simulations,
testing, security, and privacy applications.
import random
#print(random.randrange(10,20))

x = ['a', 'b', 'c', 'd', 'e']


# Get random choice
#print(random.choice(x))

# Shuffle x
random.shuffle(x)
# Print the shuffled x
print(x)

# Print random element


print(random.random())

Trigonometric Functions
import math
# Output: 3.141592653589793
print(math.pi)

# Output: 22026.465794806718
print(math.exp(10))

# Output: 720
print(math.factorial(5))

Chapter 7 – Python Date & Time

time.time() function
The function time.time() returns the current system time in
ticks since 12:00am, January1, 1970(epoch).

import time; # This is required to include time module.


ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970:",
ticks)
Getting current time

import time;
localtime = time.localtime(time.time())
print("Local current time :", localtime)

Getting Formatted Time


import time;
localtime = time.asctime( time.localtime(time.time()) )
print("Local current time :", localtime)

Getting Formatted Time


import calendar
cal = calendar.month(2017, 9)
print("Here is the calendar:")
print(cal)

ime.sleep(secs)
import time
print("Start : %s" % time.ctime())
time.sleep( 5 )
print("End : %s" % time.ctime())

Chapter 8 – Python Function

user defined function

def myfun(name):
print("Hello, " + name + ". Good morning!")
#calling function
myfun('vinayak')

function returns values

def numreturner(num):
if num >= 0:
return num
else:
return -num

print(numreturner(2))
print(numreturner(-4))

Passing by Reference Versus Passing by


Value

def changeme( mylist ):


mylist.append([1,2,3,4]);
print("Values inside the function: ", mylist)
return
# Now you can call changeme function
mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)

def changeme( mylist ):


mylist = [1,2,3,4]; # This would assig new reference in
mylist
print("Values inside the function: ", mylist)
return

mylist = [10,20,30];
changeme( mylist );
print("Values outside the function: ", mylist)

Default Arguments

def printinfo( name, age = 28 ):


print("Name: ", name)
print("Age ", age)
return;
# Now you can call printinfo function
printinfo(age=50, name="jiyan")
printinfo(name="kenechi")

Variable Length Arguments

def printinfo( arg1, *vartuple ):


print("Output is:")
print(arg1)
for var in vartuple:
print(var)
return;
# Now you can call printinfo function
printinfo( 20 );
printinfo( 25, 54, 89 );

The return Statement

def sum( arg1, arg2 ):


# Add both the parameters and return them."
total = arg1 + arg2
print("Inside the function : ", total)
return total;
# Now you can call sum function
total = sum( 10, 20 );
print("Outside the function : ", total)

Global vs. Local variables

total=0
def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print("Inside the function local total : ", total)
return
# Now you can call sum function
sum( 10, 20 );
print("Outside the function global total : ", total)

Chapter 9 – Python Module


A module allows you to logically organize your Python code. Grouping
related code
into a module makes the code easier to understand and use. A module is a
Python
object with arbitrarily named attributes that you can bind and reference.
Simply, a module is a file consisting of Python code. A module can define
functions,
classes and variables. A module can also include runnable code.

Creating & Importing Module

def mymodule():
print('Hi, this is mymodule speaking')

way1:-
import Wshop
Wshop.mymodule()

Way2:-
from DShop2 import mymodule
mymodule()

The dir( ) Function


The dir() built-in function returns a sorted list of strings containing the
names defined by a module

import math
data = dir(math)
print(data)

import derivedfile
data=dir(derivedfile)
print(data)

Chapter 10 – Python File Handling


Different modes of opening a file:
attributes related to file object

Opening and Closing Files


# Open a file
fo = open("foo.txt", "wb")
print "Name of the file: ", fo.name
# Close opend file
fo.close()

Writing and Reading Files

obj = open("vsk.txt", "a")


obj.write( "Python is a great language.\nYeah its great!!\n");
obj.close()
_______________________________________________
__
obj = open("vsk.txt", "r+")
#str=obj.readline()
#print(str) #reading single line

#str=obj.readlines()
#print(str)

str = obj.read();
print("Read String is : ", str)

obj.close()
_______________________________________________
__

Renaming and Removing Files

import os
#os.remove('vsk.txt')
os.rename('foo.txt','d.txt')
________________________________________________
Directories in Python

import os
#os.mkdir("test")
#os.rmdir('test')
#os.chdir('test')
#print(os.getcwd())
Chapter 11 – Python Exception

What is Exception?

An exception is an event, which occurs during the execution of a


program that disrupts the normal flow of the program's instructions. In
general, when a Python script encounters a situation that it cannot
cope with, it raises an exception. An exception is a Python object that
represents an error.
When a Python script raises an exception, it must either handle
the exception
immediately otherwise it terminates and quits.
Handling an Exception

try:
obj = open("dx.txt", "r")
obj.write("\nThis is my test file for exception handling!!")
except IOError:
print("Error: can\'t find file or read data")
else:
obj.close()

try:
a=5
b=0
c=a/b
print(c)
except ArithmeticError: #Exception IOError ArithmeticError
print("Error: can\'t divide by zero")
else:
obj.close()

Argument of an Exception

def num_display(arg):
try:
return int(arg)
except ValueError:
print('The argument does not contain numbers',arg)
# Call above function here.

print(num_display('xyz'))
Chapter 12 – Python classes & Object

Creating Classes
class student:
scount = 0
def __init__(self, ern, name ):
self.ern = ern
self.name = name
student.scount += 1
def showstudent(self):
print(" EnrollNu :", self.ern," Name :", self.name)

s1 = student(3712,"Motu")
s2 = student(9839,"Patlu")
s1.showstudent()
s2.showstudent()
print("Total Student",student.scount)
Destroying Objects (Garbage Collection)
class Point:
def __init( self, x=0, y=0):
self.x = x;
self.y = y;
def __del__(self):
class_name = self.__class__.__name__;
print(class_name, "destroyed");

pt1 = Point();
pt2 = pt1;
pt3 = pt1;
print(id(pt1), id(pt2), id(pt3)); # prints the ids of the obejcts
del pt1;
del pt2;
del pt3;
Class Inheritance

class parent: # define parent class


pAge = 50
def __init__(self):
print("Calling parent constructor")
def pMethod(self):
print("Calling parent method")

def setData(self, arg):


parent.pAge = arg

def getData(self):
print("Parent attribute :", parent.pAge)

class child(parent): # define child class


def __init__(self):
print("Calling child constructor")

def cMethod(self):
print("Calling child method")

c = child() # instance of child


c.cMethod() # child calls its method
c.pMethod() # calls parent's method
c.setData(60) # again call parent's method
c.getData() # again call parent's method
Module 2

Python GUI Programming

Python provides various options for developing graphical user


interfaces (GUIs). Mostimportant are ,

Tkinter:

wxPython:

JPython:

Tkinter

Tkinter is the standard GUI library for Python. Python when


combined with Tkinter provides a fast and easy way to create GUI
applications. Tkinter provides a powerful object-oriented interface to
the Tk GUI toolkit.
First Window Program
import tkinter
pwnd = tkinter.Tk()
pwnd.mainloop()

Button
import tkinter
pwnd = tkinter.Tk()
B = tkinter.Button(pwnd, text ="Hello")
B.pack()
pwnd.mainloop()

Canvas
import tkinter
pwnd = tkinter.Tk()
C = tkinter.Canvas(pwnd, bg="blue", height=250, width=300)
coord = 10, 50, 240, 150
arc = C.create_arc(coord, start=0, extent=180, fill="red")
C.pack()
pwnd.mainloop()

Entry

import tkinter
pwnd = tkinter.Tk()
L1 = tkinter.Label(pwnd, text="User Name")
L1.pack()
E1 = tkinter.Entry(pwnd, bd =5)
E1.pack()
pwnd.mainloop()

Listbox

import tkinter
pwnd = tkinter.Tk()
Lb1 = tkinter.Listbox(pwnd)
Lb1.insert(1, "IND")
Lb1.insert(2, "CHN")
Lb1.insert(3, "PAK")
Lb1.insert(4, "USA")
Lb1.insert(5, "AUS")
Lb1.pack()
pwnd.mainloop()

Module 3
Create the Screen:

import pygame

pygame.init()
dis = pygame.display.set_mode((400, 300))
pygame.display.update()
pygame.display.set_caption('Snake game by Data Corner Tech)
game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True

pygame.quit()
quit()

Create the Snake:


import pygame

pygame.init()
dis = pygame.display.set_mode((400, 300))

pygame.display.set_caption('Snake game by Data Corner Tech)

blue = (0, 0, 255)


red = (255, 0, 0)

game_over = False
while not game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.draw.rect(dis, blue, [200, 150, 10, 10])
pygame.display.update()
pygame.quit()
quit()

Moving the Snake:

import pygame

pygame.init()

white = (255, 255, 255)


black = (0, 0, 0)
red = (255, 0, 0)

dis = pygame.display.set_mode((800, 600))


pygame.display.set_caption('Snake Game by Data Corner Tech')
game_over = False

x1 = 300
y1 = 300

x1_change = 0
y1_change = 0

clock = pygame.time.Clock()

while not game_over:


for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -10
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = 10
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -10
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = 10
x1_change = 0

x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis, black, [x1, y1, 10, 10])

pygame.display.update()

clock.tick(30)

pygame.quit()
quit()

Game Over when Snake hits the boundaries:

import pygame
import time

pygame.init()

white = (255, 255, 255)


black = (0, 0, 0)
red = (255, 0, 0)

dis_width = 600
dis_height = 600
dis = pygame.display.set_mode((dis_width, dis_width))
pygame.display.set_caption('Snake Game by Data Corner Tech')

game_over = False
x1 = dis_width / 2
y1 = dis_height / 2

snake_block = 10

x1_change = 0
y1_change = 0

clock = pygame.time.Clock()
snake_speed = 10

font_style = pygame.font.SysFont(None, 50)

def message(msg, color):


mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 2, dis_height / 2])

while not game_over:


for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:


game_over = True

x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])

pygame.display.update()

clock.tick(snake_speed)

message("You lost", red)


pygame.display.update()
time.sleep(2)

pygame.quit()
quit()
Adding the Food:

import pygame
import time
import random

pygame.init()

white = (255, 255, 255)


black = (0, 0, 0)
red = (255, 0, 0)
blue = (0, 0, 255)

dis_width = 600
dis_height = 600

dis = pygame.display.set_mode((dis_width, dis_height))


pygame.display.set_caption('Snake Game by Data Corner Tech')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 30

font_style = pygame.font.SysFont(None, 30)

def message(msg, color):


mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 3, dis_height / 3])

def gameLoop(): # creating a function


game_over = False
game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) *


10.0
foody = round(random.randrange(0, dis_width - snake_block) / 10.0) *
10.0
print(foodx)
print(foody)

while not game_over:

while game_close == True:


dis.fill(white)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()

for event in pygame.event.get():


if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:


game_close = True

x1 += x1_change
y1 += y1_change
dis.fill(white)
pygame.draw.rect(dis, blue, [foodx, foody, snake_block,
snake_block])
pygame.draw.rect(dis, black, [x1, y1, snake_block, snake_block])
pygame.display.update()

if x1 == foodx and y1 == foody:


print("Yummy!!")
clock.tick(snake_speed)

pygame.quit()
quit()

gameLoop()

Increasing the Length of the Snake:

import pygame
import time
import random

pygame.init()

white = (255, 255, 255)


yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))


pygame.display.set_caption('Snake Game by Data Corner Tech')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)


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

def our_snake(snake_block, snake_list):


for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block,
snake_block])

def message(msg, color):


mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])

def gameLoop():
game_over = False
game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_List = []
Length_of_snake = 1

foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) *


10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) *
10.0

while not game_over:

while game_close == True:


dis.fill(blue)
message("You Lost! Press C-Play Again or Q-Quit", red)

pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()

for event in pygame.event.get():


if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:


game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(blue)
pygame.draw.rect(dis, green, [foodx, foody, snake_block,
snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]

for x in snake_List[:-1]:
if x == snake_Head:
game_close = True

our_snake(snake_block, snake_List)

pygame.display.update()

if x1 == foodx and y1 == foody:


foodx = round(random.randrange(0, dis_width - snake_block) /
10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) /
10.0) * 10.0
Length_of_snake += 1

clock.tick(snake_speed)

pygame.quit()
quit()

gameLoop()

Displaying the Score:


import pygame
import time
import random

pygame.init()

white = (255, 255, 255)


yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)

dis_width = 600
dis_height = 400

dis = pygame.display.set_mode((dis_width, dis_height))


pygame.display.set_caption('Snake Game by Edureka')

clock = pygame.time.Clock()

snake_block = 10
snake_speed = 15

font_style = pygame.font.SysFont("bahnschrift", 25)


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

def Your_score(score):
value = score_font.render("Your Score: " + str(score), True, yellow)
dis.blit(value, [0, 0])

def our_snake(snake_block, snake_list):


for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block,
snake_block])

def message(msg, color):


mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])

def gameLoop():
game_over = False
game_close = False

x1 = dis_width / 2
y1 = dis_height / 2

x1_change = 0
y1_change = 0

snake_List = []
Length_of_snake = 1

foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) *


10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) *
10.0

while not game_over:

while game_close == True:


dis.fill(blue)
message("You Lost! Press C-Play Again or Q-Quit", red)
Your_score(Length_of_snake - 1)
pygame.display.update()

for event in pygame.event.get():


if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()

for event in pygame.event.get():


if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0

if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:


game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(blue)
pygame.draw.rect(dis, green, [foodx, foody, snake_block,
snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]

for x in snake_List[:-1]:
if x == snake_Head:
game_close = True

our_snake(snake_block, snake_List)
Your_score(Length_of_snake - 1)

pygame.display.update()

if x1 == foodx and y1 == foody:


foodx = round(random.randrange(0, dis_width - snake_block) /
10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) /
10.0) * 10.0
Length_of_snake += 1

clock.tick(snake_speed)

pygame.quit()
quit()

gameLoop()

You might also like