Program
cr= int(input("Enter Current month reading:"))
pr= int(input("Enter previous month reading:"))
consumed =cr-pr
if (consumed>=1 and consumed<=100):
amount =consumed*2
print("your bill is RS :",amount)
elif (consumed>100 and consumed<=200):
amount =consumed*3
print ("your bill is RS :",amount)
elif (consumed>200 and consumed<=500):
amount =consumed*5
print ("your bill is RS :",amount)
elif (consumed>500):
amount =consumed*5
print ("your bill is RS :",amount)
else :
print ("Invalid reading")
output
Enter Current month reading:700
Enter previous month reading:300
your bill is RS: 2000
Program
import math
x=int (input ("Enter the value of x in degrees :"))
n=int (input ("Enter the number of terms :"))
sine = 0
for i in range(n):
sign = (-1)**i
pi =22/7
y=x*(pi/180)
sine = sine + ((y**(2.0*i+1))/math.factorial(2*i+1))*sign
print (sine)
output
Enter the value of x in degrees: 4
Enter the number of terms: 5
1.0895473542016753e-16
Program
mass = float(input("Enter the Mass of the Motor Bike: "))
Weight =mass*9.8
print(" The weight of a Motor Bike for a given mass is:",Weight)
output
Enter the Mass of the Motor Bike: 100
The weight of a Motor Bike for a given mass is: 980.0000000000001
Program
diameter = float(input("Enter the Diameter of the Rounded Steel Bar:"))
length = float(input("Enter the Length of the Rounded Steel Bar:"))
Weight =((diameter*diameter)/162.28)*length
print("Weight of a Steel Bar:", Weight)
output
Enter the Diameter of the Rounded Steel Bar:2
Enter the Length of the Rounded Steel Bar:15
Weight of a Steel Bar: 0.3697313285679073
Program
import math
R = 20
X_L = 15
V_L = 400
f = 50
V_Ph=V_L/1.732
Z_Ph=math.sqrt((R**2)+(X_L**2))
I_Ph=V_Ph/Z_Ph
I_L=I_Ph
print ("The Electrical Current in Three Phase AC Circuit",
round(I_L,6))
output
The Electrical Current in Three Phase AC Circuit 9.237875
Program
p1=input("Name of the product1:")
q1=int(input("Quantity:"))
p2=input("Name of the product2:")
q2=int(input("Quantity:"))
p3=input("Name of the product3:")
q3=int(input("Quantity:"))
tot1=q1*55
tot2=q2*30
tot3=q3*25
amount=tot1+tot2+tot3
print("product1:",p1,"Quantity:",q1,"Total:",tot1)
print("product2:",p2,"Quantity:",q2,"Total:",tot2)
print("product1:",p3,"Quantity:",q3,"Total:",tot3)
print("Total Amount:", amount)
output
Name of the product1:Rice
Quantuty:10
Name of the product2:onion
Quantuty:5
Name of the product3:Tomoto
Quantuty:2
product1: Rice Quantity: 10 Total: 550
product2: onion Quantity: 5 Total: 150
product1: Tomato Quantity: 2 Total: 50
Total Amount: 750
Program
#using temporary variable
x=input("Enter value of x:")
y=input("Enter value of y:")
temp=x
x=y
y=temp
print("The value of after swapping :",x)
print('The value of y after swapping :',y)
#few other method to swap variables without using temporary variable
x=5
y=10
x,y=y,x
print("x=",x)
print("y=",y)
#using Addition and subtraction
x=15
y=10
x=x+y
y=x-y
x=x-y
print("The value of x after swapping :",x)
print("The value of y after swapping :",y)
# Multiplitation and Division Program
x=25
y=10
x=x*y
y=x/y
x=x/y
print("The value of x after swapping :",x)
print("The value of y after swapping :",y)
#Swapping using XOR
x=35
y=10
x=x^y
y=x^y
print(x)
print(y)
output
#using temporary variable
Enter value of x:20
Enter value of y:30
The value of after swapping: 30
The value of y after swapping: 20
#few other method to swap variables without using temporary variable
x= 10
y= 5
#using Addition and subtraction
The value of x after Swapping: 10
The value of y after Swapping: 15
#Multipilation and Division Program
The value of x after Swapping: 10.0
The value of y after Swapping: 25.0
#Swapping using XOR
41
35
Program
A=list(input("Enter the list Values: "))
print(A)
for i in range (1, len(A), 1):
print(A[i: ]+A[ :i])
output
Enter the List Value:5
[‘5’]
Program
import math
print("Enter coordinates for point 1: ")
x1 = int(input("x1="))
y1 = int(input("y1="))
print("Enter coordinates for point 2: ")
x2= int(input("x2="))
y2= int(input("y2="))
dist = math.sqrt((x2-x1)*2)+((y2-y1)*2)
print("Distance between given point is", round (dist,2))
output
Enter coordinates for point 1:
x1=10
y1=20
Enter coordinates for point 2:
x2=30
y2=40
Distance between given point is 46.32
Program
n=int(input("Enter the value of r: "))
a=0
b=1
Sum=0
count=1
print("Fibonacci series=",end=" ")
while(count<=n):
print(sum,end=" ")
count+=1
a=b
b=Sum
Sum=a+b
output
Enter the valve of r: 5
Fibonacci series=01123
Program
list1=[10,21,4,45,66,93]
for num in list1:
if (num%2!=0):
print(num, end="")
output
21 45 93
Program
rows=int(input("Enter the number of rows:"))
for i in range(rows+i):
for j in range(i):
print(j+i,end='')
print('')
output
Enter the number of rous:7
1
12
123
1234
12345
123456
1234567
Program
n=int(input("Enter number of rows:"))
for i in range(0,n):
for j in range(0,i+1):
print("*", end=" ")
print()
output
Enter number of rows:6
*
**
***
****
*****
******
Program
#Creating a List
Library=['OS','OOAP','MPMC']
print("Books in Library are:")
print(Library)
# Accessing elements from the List
Library=['OS', 'OOAD', 'MPMC']
print("Accessing a element from the list")
print(Library[0])
print(Library[2])
#Creating a Multi-Dimensional List
Library = [['os', 'OOAD', 'MPMC'], ['TOC', 'PYTHON', 'NET WORK']]
print("Accessing a element Creating a Multi-Dimensional list")
print(Library [0][1])
print(Library [1][0])
#Negative Indexing
Library = ['OS', 'OOAD', 'MPMC']
print("Negative accessing a element from the List")
print(Library [-1])
print(Library [-2])
#Slicing
Library = ['OS', 'OOAD', 'MPMC', 'TOC', 'NAI']
print(Library [1][ :-3])
print(Library [1][ :4])
print(Library [2][2:4])
print(Library [3][0:4])
print(Library [9][:])
#Append()
Library=['OS', 'OOAD', 'MPMC']
Library.append("ps")
Library.append("Oops")
Library.append("Nus")
print(Library)
#extend()
Library=['OS','OOAD', 'MPMC']
Library.extend(["TOC", "DWOM"])
print(Library)
#insert()
Library=['OS','OOAD', 'MPMC']
Library.insert(0,"DS")
print(Library)
# del method
Library=['OS','OOAD', 'MPMC']
del Library[ :2]
print(Library)
#remove()
Library=['OS', 'OOAD', 'MPMC','OOAD']
Library.remove('OOAD')
print(Library)
#reverse()
Library=['OS', 'OOAD', 'MEMC']
Library.reverse()
print(Library)
#sont()
Library=['os', 'OOAD', 'MPMC']
Library.sort()
print(Library)
# concatenation operator
Library = ['Dos', 'OOAD', 'MPMC']
Books=['DS', 'Toc', 'OMDW']
print(Library+Books)
# replication operator
Library=['OS','OOAD','MPMC','TOC','NEW']
print('OS' in Library)
print(' DWDM 'in Library)
print('OS' not in Library)
#Count()
Library=['OS','OOAD','MPMC','TOC','NEW']
x=Library.count("TOC")
print(x)
output
Books in Library are:
['OS', 'OOAP', 'MPMC']
Accessing a element from the list
OS
MPMC
Accessing a clement creating a Multi-Dimensional list
OOAD
TOC
Negative accessing a element from the List
MPMC
OOAD
O
OOAD
MC
TOC
['OS', 'OOAD', 'MPMC', 'PS', 'Oops', 'Nus']
['OS', 'OOAD', 'MPMC', 'TOC', 'DWOM']
['DS', 'OS', 'OOAD', 'MPMC']
['MPMC']
['OS', 'MPMC', 'OOAD']
['MEMC', 'OOAD', 'OS']
['MPMC', 'OOAD', 'OS']
['Dos', 'OOAD', 'MPMC', 'DS', 'Toc', 'OMDW']
True
False
False
1
Program
bk_list=["OS","MPMC","DS"]
print ("Welcome to library")
while(1):
ch=int(input("\n 1. add the book to list \n2. issue a book \n 3. Return the book \n 4. View the
book list \n 5. Exit \n"))
if (ch==1):
bk=input("enter the book name")
bk_list.append(bk)
print(bk_list)
elif (ch==2):
ibk=input("Enter the book to issue")
bk_list.remove(ibk)
print(bk_list)
elif (ch==3):
rbk = input("Enter the book to return")
bk_list.append(rbk)
print(bk_list)
elif (ch==4):
print(bk_list)
else:
break
output
Welcome to library
1. add the book to list
2. issue a book
3. return the book
4. View the book list
5. Exit
1
enter the book name END
['OS', 'MPMC', 'DS', 'END']
1. add the book to list
2. issue a book
3. return the book
4. View the book list
5. Exit
2
Enter the book to issue OS
['MPMC', 'DS', 'END']
3
Enter the book to return MPMC
['os', 'MPMC', 'DS', 'MPMC']
1. add the book to list
2. issue a book
3. return the book
4. View the book list
5. Exit
4
['OS', 'MPMC', 'DS', 'MPMC']
1. add the book to list
2. issue a book
3. return the book
4. View the book list
5. Exit
5
Program
cc=[' Engine ','Front xle ','Battery',' transmission ']
com=input("Enter the car components:")
cc.append(com)
print("Components of car :",cc)
print("Length of list:",len(cc))
print("maximum of the list :",max(cc))
print("minimum of list :",min(cc))
print("indexing(Valve at the index 3):",cc[3])
print("Return True if Battery in present in the list")
print("Battery" in cc)
print("multiplication of list element :",cc*2)
output
Enter the car components :Engine
Components of car: ['Engine', 'Front xle', 'Battery', ' transmission ', 'Engine']
Length of list: 5
maximum of the list: transmission
minimum of list: Battery
indexing(Valve at the index 3): transmission
Return True if Battery in present in the list
True
multiplication of list element: ['Engine', 'Front xle ', 'Battery', ' transmission ', 'Engine',
'Engine', 'Front xle ', 'Battery', ' transmission ', 'Engine']
Program
cc=['Bricks', 'Cement', 'Paint',' wood ']
cc.sort()
print("Sorted List")
print(cc)
print("Reverse List")
cc.reverse()
print(cc)
print("insert valve 'glass' to the list")
cc.insert(0,'Glass')
print (cc)
print("Delete List")
del cc[:2]
print(cc)
print("Find the index of cement")
print(cc.index('Cement'))
print("New List")
new=[]
for i in cc:
if "n" in i:
new.append(i)
print(new)
output
Sorted List
['Bricks', 'Cement', 'Paint', 'wood']
Reverse List
['wood', 'Paint', 'Cement', 'Bricks']
insert valve 'glass' to the list
['Glass', 'wood', 'Paint', 'Cement', 'Bricks']
Delete List
['Paint', 'Cement', 'Bricks']
Find the index of cement
1
New List
['Paint']
['Paint', 'Cement']
Program
book=("OS","MPMC","DS")
book=book+("NW",)
print(book)
print(book[1:2])
print(max(book))
print(min(book))
book1=("OOAD","C++","C")
print(book1)
New=list(book)
print(New)
del (book1)
print(book1)
output
('OS', 'MPMC', 'DS', 'NW')
('MPMC',)
OS
DS
('OOAD', 'C++', 'C')
['OS', 'MPMC', 'DS', 'NW']
Trace back (most recent call last):
File "D:/python/4.5.py", line 12, in <module>
print(book1)
Name Error: name 'book1' is not defined. Did you mean: 'book'?
Program
cc=('Engine ','Front axle',' Battery ', 'transmission')
Y=list(cc) # adding a value to a tuple means we have to convert to a list
Y=[]='Gear'
cc=tuple(Y)
print(cc)
Y=list(cc) #removing a value from tuple
Y.remove("Gear")
cc=tuple(y)
print(cc)
New=("Handle")
print(type(New))
output
('Engine', 'Front axle', 'Battery', 'transmission')
('Engine', 'Battery', 'transmission')
<class’ tuple ’>
Program
cm=('sand ','cement ','bricks ','water')
a,b,c,d=cm
#tuple unpacking
print("\n Values after unpacking:")
print(a)
print(b)
print(c)
print(d)
print(cm.count('stand'))
print(cm.index('Sand'))
new=tuple("Sand")
print(new)
print(sorted(cm))
print(type(sorted(cm)))
output
Values after unpacking:
Sand
cement
bricks
water
0
0
('S', 'a', 'n', 'd')
['Sand', 'bricks', 'cement', 'water']
<class 'list'>
Program
Language = {}
print("Empty Dictionary :",Language)
Language=dict({1:"english",2:"tamil",3:"Malayalam"})
print("using dict()the language are:", Language)
New_Language ={4: "hindi",5:"hindi"}
Language.update(New_Language)
print("The updated languages are :",Language)
print("The length of the languages:",len(Language))
Language.pop(5)
print("key 5 has been Popped with Value:", Language)
print("the keys are:",Language.keys())
print("the values are:",Language.values())
print("The items in languages are:",Language.items())
Language.clear()
print("The items are cleated in dictionary ",Language)
del Language
print(Language)
output
Empty Dictionary: {}
using dict()the language are: {1: ' english ' , 2: 'tamil', 3: 'Malayalam'}
The updated languages are: {1: 'english', 2: 'tamil', 3: 'Malayalam', 4: 'hindi', 5: 'hindi'}
The length of the languages: 5
key 5 has been Popped with Value: {1: 'english', 2: 'tamil', 3: 'Malayalam', 4: 'hindi'}
the keys are: dict_keys([1, 2, 3, 4])
the values are: dict_values(['english', 'tamil', 'Malayalam', 'hindi'])
The items in languages are: dict_items([(1, 'english'), (2, 'tamil'), (3, 'Malayalam'), (4,
'hindi')])
The items are cleated indictionary {}Traceback (most recent call last):
File "D:/python/5.1.py", line 17, in <module>
print(Language)
NameError: name 'Language' is not defined
Program
auto_mobile=[]
print("Empty dictionary",auto_mobile)
auto_mobile=dict({1:"Engine",2:"Clutch",3:"Gearbox"})
print("Automobile Parts:",auto_mobile)
print("The value for 2 is",auto_mobile.get(2))
auto_mobile[4]="chassis"
print("updated auto_mobile",auto_mobile)
print(auto_mobile. popitem())
print("The current auto_mobile parts is:", auto_mobile)
print("Is a available in auto mobile parts")
print(2 in auto_mobile)
output
Empty dictionary []
Automobile Parts: {1: 'Engine', 2: 'Clutch', 3: 'Gearbox'}
The value for 2 is Clutch
updated auto_mobile {1: 'Engine', 2: 'Clutch', 3: 'Gearbox', 4: 'chassis'}
(4, 'chassis')
The current auto_mobile parts is: {1: 'Engine', 2: 'Clutch', 3: 'Gearbox'}
Is a available in auto mobile parts
True
Program
civil_ele={}
print(civil_ele)
civil_ele=dict([(1,"Beam"),(2, "plate")])
print("the elements of civil structure are",civil_ele)
print("the value for key 1 is:",civil_ele[1])
civil_ele['three']='concrete'
print(civil_ele)
new=civil_ele.copy()
print("The copy of civil_ele",new)
print("The length is",len(civil_ele))
for i in civil_ele:
print(civil_ele[i])
output
{}
the elements of civil structure are {1: 'Beam', 2: 'plate'}
the value for key 1 is: Beam
{1: 'Beam', 2: 'plate', 'three': 'concrete'}
The copy of civil_ele {1: 'Beam', 2: 'plate', 'three': 'concrete'}
The length is 3
Beam
plate
concrete
Program
def gcd (a,b):
if (b==0):
return a
else:
return gcd(b,a%b)
a=int(input("Enter the value of a:"))
b=int(input("Enter the value of b:"))
result=gcd(a,b)
print("The greatest common divisor is ",result)
output
Enter the value of a:24
Enter the value of b:54
The greatest common divisor is 6
Program
def newton_sqrt():
approx = 0.5*n
better=0.5*(approx+n/approx)
while (better!=approx):
approx = better
n=int(input("Enter the number"))
result=newton_sqrt(n)
print("The Square root for the given number is",result)
output
Enter the number25
The Square root for the given number is5.0
Program
def Factorial(n):
if n==0:
return 1
else:
return n*Factorial(n-1)
n=int(input("Input a number to compute the Factiorial:"))
print(Factorial(n))
output
Input a number to compute the Factiorial:5
120
Program
def largest(n):
list=[]
print("Enter list elements one by one")
for i in range(0,n):
x=int(input())
list.append(x)
print("The list elements are")
print(list)
large=list[o]
for i in range(1,n):
if (list[i]>large):
large=list[i]
print("The largest element in the list is",large)
n=int(input("Enter the limit"))
largest(n)
output
Enter the limit 5
Enter list elements one by one
10
20
30
40
50
The list elements are
[10,20,30,40,50]
The largest element in the list is 50
Program
def rect(x,y):
return x*y
def circle(r):
PI= 3.142
return PI*(r*r)
def triangle(a,b,c):
Perimeter = a+b+c
s=(a+b+c)/2
Area=math.sqrt((s*(s-a)*(s-b)*(s-c)))
print(" The Perimeter of Triangle = %.2f"%Perimeter)
print(" The Semi Perimeter of Triangle =%.2f"%s)
print(" The Area of a Triangle is %0.2f"%Area)
def parallelogram(a,b):
return a* b;
#Python program to compute area of rectangle
l = int(input(" Enter the length of rectangle: "))
b = int(input(" Enter the breadth of rectangle: "))
a = rect(l,b)
print("Area =",a)
#Python program to find Area of a circle
num=float(input("Enter r value of circle:"))
print("Area is %.6f"%circle(num))
#python program to compute area of triangle
import math
triangle(6,7,8)
#Python Program to find area of Parallelogram
Base=float(input("Enter the Base:"))
Height=float(input("Enter the Height:"))
Area=parallelogram(Base,Height)
print("The Area of a Parallelogram=%.3f"%Area)
output
Enter the length of rectangle: 2
Enter the breadth of rectangle: 3
Area = 6
Enter r value of circle:2
Area is 12.568000
The Perimeter of Triangle = 21.00
The Semi Perimeter of Triangle =10.50
The Area of a Triangle is 20.33
Enter the Base:2
Enter the Height:5
The Area of a Parallelogram=10.000
Program
def revetsed_sthing(text):
if len(text)==1:
return text
return revetsed_sthing(text [1:])+text[:1]
a=revetsed_sthing("Hello, world!")
print(a)
output
!dlrow ,olleH
Program
string=input("Enter a string:")
if (string== string[ : :-1]):
print("The string is a Palindrome")
else:
print("not a Palindrome")
output
Enter a string: madam
The string is a Palindrome
Enter a string: nice
not a Palindrome
Program
String="once in a blue moon"
ch='0'
#Replace h with Specific character ch
String=String.replace(ch,'h')
print("string after replacing with given character:")
print(String)
output
string after replacing with given character:
once in a blue moon
Program
a=input("Enter the String:")
count=0;
#counts each character expect space
for i in dange (0,len(a)):
if (a[i]!=''):
count=Count+1;
#Displays the total number of charactets Present in the given string
print ("Total number of characters in a String:" + Str(count));
output
Enter the String :hai
Total number of characters in a String:1
Total number of characters in a String:2
Total number of characters in a String:3
Program
#To use pandas first we have to import pandas
import pandas as pd
#Here pd just a objest of pandas
#Defining a list
A=['b', 'c', 'd',’e’]
#converting into a series
df = pd. Series (A)
Print (df)
output
0a
1b
2c
3d
4e
dtype:object
Program
import numpy as np
x=np.array([1,2,3,4,])
print("Original array:")
print(x)
print("Test if none of the elements of the said array in zero:")
print(np.all(x))
x=np.array([0,1,2,3])
print("Original array:")
print(x)
print("Test if none of the element of the said array is zero:")
print(np.all(x))
output
Original array:
[1 2 3 4]
Test if none of the elements of the said array in zero
True
Original array:
[0 1 2 3]
Test if none of the elements of the said array in zero
False
Program
from matplotlib import pyplot as plt
plt.plot([1,2,3],[4,5,1])
plt.show()
output
Program
from scipy import special
a= special.exp1(3)
Print (a)
b = special.exp2(3)
Print (6)
C = special.sindg(90)
Print (c)
d = special.cosdg (45)
Print (d)
output
1000.0
8.0
1.0
0.707106781187
Program
with open("file.txt") as f:
with open("sample.txt", "w") as f1:
for line in f:
f1.write(line)
output
The content of file named file.txt is copied into sample.txt
Program
def longest_word(filename):
with open(filename, 'r') as infile:
words = infile.read().split()
max_len = len(max(words, key = len))
return[ word for word in words if len(word) ==max_len]
print(longest_word('Z:\sample.txt))
output
[‘Engineering’]
Program
File=open("Z: \sample.txt")
Data=file.read()
words=Data.split()
print("Number of words in text file:",len(words))
output
Number of words in text file:5
Program
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number:"))
result = num1/num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
output
Enter First Number:12.5
Invalid Input Please Input Integer...
Enter First Number:12
Enter Second Number:0
Division by zero
Enter First Number:12
Enter Second Number:2
6.0
Program
def main():
#single try statement can have multiple except statements.
try:
age=int(input("Enter your age"))
if age>18:
print("You are eligible to vote")
else:
print("You are not eligible to vote")
except ValueError:
print("age must be a valid number")
except IOError:
print("Enter correct value")
#generic except clause, which handles any exception.
except:
print("An Error occured")
main()
output
Enter your age35
You are eligible to vote
Enter your age20.2
age must be a valid number
Enter your age12
You are not eligible to vote
Program
def main():
try:
mark=int(input(" Enter your mark:"))
if(mark>=50 and mark<101):
print(" You have passed")
else:
print(" You have failed")
except ValueError:
print(" It must be a valid number")
except IOError:
print("Enter correct valid number")
except:
print("An error occured")
main()
output
Enter your mark:50
You have passed
Enter your mark:r
It must be a valide number
Enter your mark:0
You have failed
Ex.no.11
Date: Exploring Pygame Tool
Aim:
To study the basics of pygame.
About pygame :
Python is the most popular programming language or it is the next-generation programming
language. In every emerging field in computer science, Python makes its presence actively.
Python has vast libraries for various fields such as Machine Learning (Numpy, Pandas,
Matplotlib), Artificial intelligence (Pytorch, TensorFlow), and Game development
(Pygame,Pyglet).
Pygame is a cross-platform set of Python modules which is used to create video games.It
consists of computer graphics and sound libraries designed to be used with the Python
programming language. Pygame is suitable to create client-side applications that can be
potentially wrapped in a standalone executable.
Syntax Used:
import pygame - This provides access to the pygame framework and imports all functions of
pygame.
pygame.init() - This is used to initialize all the required module of the pygame.
pygame.display.set_mode((width, height)) - This is used to display a window of the desired
size. The return value is a Surface object which is the object where we will perform graphical
operations.
pygame.event.get()- This is used to empty the event queue. If we do not call this, the window
messages will start to pile up and, the game will become unresponsive in the opinion of the
operating system.
Pygame Surface
The pygame Surface is used to display any image. The Surface has a pre-defined resolution
and pixel format. The Surface color is by default black. Its size is defined by passing the size
argument.
Surfaces can have the number of extra attributes like alpha planes, color keys, source rectangle
clipping, etc. The blit routines will attempt to use hardware acceleration when possible;
otherwise, they will use highly enhanced software blitting methods.
Pygame Clock
Times are represented in millisecond (1/1000 seconds) in pygame. Pygame clock is used to
track the time. The time is essential to create motion, play a sound, or, react to any event. In
general, we don't count time in seconds. We count it in milliseconds. The clock also provides
various functions to help in controlling the game's frame rate. The few functions are the
following:
tick()
This function is used to update the clock. The syntax is the following:
tick(framerate=0)
This method should be called once per frame. It will calculate how many milliseconds have
passed since the previous call. The framerate argument is optional to pass in the function, and
if it is passed as an argument then the function will delay to keep the game running slower than
the given ticks per second.
tick_busy_loop()
The tick_busy_loop() is same as the tick(). By calling the Clock.tick_busy_loop(20) once per
frame, the program will never run at more than 20 frames per second. The syntax is the
following: tick_busy_loop()
get_time()
The get_time() is used to get the previous tick. The number of a millisecond that isdra passed
between the last two calls in Clock.tick().
Pygame Blit
The pygame blit is the process to render the game object onto the surface, and this process is
called blitting. When we create the game object, we need to render it. If we don't render the
game objects and run the program, then it will give the black window as an output. Blitting is
one of the slowest operations in any game so, we need to be careful to not to blit much onto
the screen in every frame. The primary function used in blitting is blit(), which is: blit()
blit(source,dest,area=None,special_flags=0)
This function is used to draw one image into another. The draw can be placed with the dest
argument. The dest argument can either be a pair of coordinates representing the upper left
corner of the source.
Pygame Adding Image
image = pygame.image.load(r'image_path')
Pygame Draw
Pygame provides geometry functions to draw simple shapes to the surface. These functions
will work for rendering to any format to surfaces. Most of the functions accept a width
argument to signify the size of the thickness around the edge of the shape. If the width is passed
0, then the shape will be solid(filled).
All the drawing function takes the color argument that can be one of the following formats:
A pygame.Color objects
An (RGB) triplet(tuple/list)
An (RGBA) quadruplet(tuple/list)
An integer value that has been mapped to the surface's pixel format
Draw a rectangle
The following functions are used to draw a rectangle on the given surface.
pygame.draw.rect(surface, color, rect)
pygame.draw.rect(surface, color, rect, width=0)
Draw an ellipse
The following functions are used to draw an ellipse on the given surface.
pygame.draw.ellipse(surface, color, rect)
pygame.draw.ellipse(surface, color, rect, width=0)
Parameters:
surface - Screen to draw on.
color- This argument is used to color the given shape. The alpha value is optional if we are
using a tuple.
Draw a straight line
This method is used to draw a straight line on the given surface. There are no endcaps.
pygame.draw.line(surface,color,start_pos,end_pos,width)
pygame.draw.line(surface,color,start_pos,end_pos,width=1)
Parameters:
surface - Screen to draw on.
color- This argument is used to color the given shape. The alpha value is optional if we are
using a tuple.
start_pos- start position of the line(x,y)
end_pos- End position of the line
Draw a Circle
Below are the functions, which are used to draw a circle on the given surface.
circle(surface, color, center, radius)
circle(surface, color, center, radius, width=0)
Parameters:
surface - Screen to draw on.
color- This argument is used to color the given shape. The alpha value is optional if we are
using a tuple.
center - The center point of the circle as a sequence of two int/float, e.g. (x,y)
radius(int or float)- radius of the circle, measured from the center parameter, if the radius is
zero, then it will only draw the center pixel.
pygame Text and Font
Pygame also provides facilities to render the font and text. We can load fonts from the system
by using the pygame.font.SysFont() function. Pygame comes with the built-in default font
which can be accessed by passing the font name or None. There are many functions to help to
work with the font. The font objects are created with pygame.font.Font().
display.flip() will update the contents of the entire display
Result:
Thus basics of pygame are studied.
Program:
import sys, pygame
pygame.init()
size = width, height = 800, 400
speed = [1, 1]
background = 255, 255, 255
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Bouncing Ball")
ball = pygame.image.load("ball.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left< 0 or ballrect.right> width:
speed[0] = -speed[0]
if ballrect.top< 0 or ballrect.bottom> height:
speed[1] = -speed[1]
screen.fill(background)
screen.blit(ball, ballrect)
pygame.display.flip()
Output: