0% found this document useful (0 votes)
38 views57 pages

GP Practical

The document is a certificate from Sanpada College of Commerce & Technology certifying a student's completion of practical work in 'Game Programming' for the T.Y.B.Sc.CS program during the academic year 2024-2025. It includes an index of practical tasks such as setting up DirectX 11, game design techniques, and creating various games using pygame and Unity. The document outlines detailed steps and code examples for each practical task, demonstrating the application of programming concepts in game development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views57 pages

GP Practical

The document is a certificate from Sanpada College of Commerce & Technology certifying a student's completion of practical work in 'Game Programming' for the T.Y.B.Sc.CS program during the academic year 2024-2025. It includes an index of practical tasks such as setting up DirectX 11, game design techniques, and creating various games using pygame and Unity. The document outlines detailed steps and code examples for each practical task, demonstrating the application of programming concepts in game development.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Oriental Education Society’s

SANPADA COLLEGE OF COMMERCE & TECHNOLOGY


SECTOR-2, PLOT-3/4/5, ADJACENT SANPADA RAILWAY STATION, SANPADA (W), NAVI MUMBAI-400 705.

DEPARTMENT OF COMPUTER SCIENCE

CERTIFICATE

This is to certify that Mr/Ms. of Class T.Y.B.Sc.CS


bearing Roll No. of Semester V has successfully completed the
Practical work in the subject of “Game Programming ” during the
academic year 2024 - 2025 under the guidance of Prof. by
the partial requirement for the fulfillment of the curriculum of Degree of
Bachelor of Science in Computer Science, University of Mumbai.

Place :
Date :

Sign of Subject Sign of External Sign of H.O.D Sign of Principal


In-Charge Examiner
INDEX

SR. Practical Pg. Date Remark


Setup DirectX 11, Window Framework and
1 Initialize Direct3D Device, Loading models 1 16/7/24
into DirectX 11 and rendering

Learn Basic Game Designing Techniques


2 15 23/7/24
with pygame.

3 Develop Snake Game using pygame 31 30/7/24

4 Create 2D Target Shooting Game 36 6/8/24

5 Creating 2D Infinite Scrolling Background 39 13/8/24

6 Create Camera Shake Effect in Unity 41 20/8/24

Design and Animate Game Character in


7 48 17/9/24
Unity

8 Create Snowfall Particle effect in Unity 50 24/9/24


Game ProgrammingTYBSc. CS.

PRACTICAL 1

Aim: Setup DirectX 11, Window Framework and Initialize Direct3D


Device

In this practical we are just learning the window framework and initializing a Direct3D device.
Step 1:
I. Create new project, and select “Windows Forms Application”, select .NET
Framework as 2.0 in Visuals C#.
II. Right Click on properties Click on open click on build Select Platform Target
and Select x86.
Step 2:
Click on View Code of Form 1.
Step 3:
Go to Solution Explorer, right click on project name, and select Add Reference. Click
on Browse and select the given .dll files which are “Microsoft.DirectX”,
“Microsoft.DirectX.Direct3D”, and “Microsoft.DirectX.DirectX3DX”.
Step 4:
Go to Properties Section of Form, select Paint in the Event List and enter as
Form1_Paint.
Step 5:
Edit the Form’s C# code file. Namespace must be as same as your project name.

Program:

using System;
usingSystem.Collections.Generic;
usingSystem.ComponentModel;
usingSystem.Data;
usingSystem.Drawing;
usingSystem.Text;
usingSystem.Windows.Forms;

[USCSP5042]
1
Game ProgrammingTYBSc. CS.

usingMicrosoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace GP_P1
{
public partial class Form1 : Form
{
Microsoft.DirectX.Direct3D.Device device;
public Form1()
{
InitializeComponent();
InitDevice();
}

public void InitDevice()


{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing,
pp);
}

private void Render()


{
device.Clear(ClearFlags.Target, Color.Orange, 0, 1);
device.Present();
}

private void Form1_Paint(object sender, PaintEventArgs e)


{
Render();
}
}
}

Step 6: Click on Start. And here is the output. We have initialized 3D Device.
Output:

[USCSP5042]
2
Game ProgrammingTYBSc. CS.

B)Draw a triangle using Direct3D 11.


In this practical we are just learning To Draw a Triangle and initializing a Direct3D device.

Step 1:

.Create new project, and select “Windows Forms Application”, select .NET

Framework as 2.0 in Visuals C#.

i. Right Click on properties Click on open click on build Select Platform Target and

Select x86.

Step 2:

Click on View Code of Form 1.

Step 3:

Go to Solution Explorer, right click on project name, and select Add Reference. Click

on Browse and select the given .dll files which are “Microsoft.DirectX”,

“Microsoft.DirectX.Direct3D”, and “Microsoft.DirectX.DirectX3DX”.

Step 4:

Go to Properties Section of Form, select Paint in the Event List and enter as

Form1_Paint.

[USCSP5042]
3
Game ProgrammingTYBSc. CS.

Step 5:

Edit the Form’s C# code file. Namespace must be as same as your project name.

Program:

using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace p1_gp
{
public partial class Form3 : Form
{
CustomVertex.PositionColored[] vertexes = new
CustomVertex.PositionColored[6];
Microsoft.DirectX.Direct3D.Device device;
public Form3()
{
InitializeComponent();
InitDevice();
}
private void InitDevice()
{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp);
}

private void Form3_Load(object sender, EventArgs e)


{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp);
device.Transform.Projection = Matrix.PerspectiveFovLH(3.14f /
4, device.Viewport.Width / device.Viewport.Height, 1f, 1000f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0,
20), new Vector3(), new Vector3(0, 1, 0));
device.RenderState.Lighting = false;

vertexes[0] = new CustomVertex.PositionColored(new Vector3(-


5, 0, 0), Color.Blue.ToArgb());

[USCSP5042]
4
Game ProgrammingTYBSc. CS.

vertexes[1] = new CustomVertex.PositionColored(new Vector3(5,


0, 0), Color.Red.ToArgb());
vertexes[2] = new CustomVertex.PositionColored(new Vector3(0,
7, 0), Color.Violet.ToArgb());

}
private void Form3_Paint(object sender, PaintEventArgs e)
{
device.Clear(ClearFlags.Target, Color.WhiteSmoke, 1.0f, 0);
device.BeginScene();
device.VertexFormat = CustomVertex.PositionColored.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList,
vertexes.Length / 3, vertexes);
device.EndScene();
device.Present();

}
}

[USCSP5042]
5
Game ProgrammingTYBSc. CS.

Output:

Draw a Rectangle using Direct3D 11.

In this practical we are just learning to Draw a Rectangle and initializing a Direct3D device.

Step 1:

. Create new project, and select “Windows Forms Application”, select .NET

Framework as 2.0 in Visuals C#.

Right Click on properties Click on open click on build Select Platform Target and

Select x86.

Step 2:

Click on View Code of Form 1.

[USCSP5042]
6
Game ProgrammingTYBSc. CS.

Step 3:

Go to Solution Explorer, right click on project name, and select Add Reference. Click

on Browse and select the given .dll files which are “Microsoft.DirectX”,

“Microsoft.DirectX.Direct3D”, and “Microsoft.DirectX.DirectX3DX”.

Step 4:

Go to Properties Section of Form, select Paint in the Event List and enter as

Form1_Paint.

Step 5:

Edit the Form’s C# code file. Namespace must be as same as your project name.

Program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
namespace Practical2b
{
public partial class Form1 : Form
{
Microsoft.DirectX.Direct3D.Device device;
CustomVertex.PositionColored[] vertexes = new
CustomVertex.PositionColored[6];

public Form1()
{
InitializeComponent();
}
private void Form1_Paint(object sender, PaintEventArgs e)

[USCSP5042]
7
Game ProgrammingTYBSc. CS.

{
device.Clear(ClearFlags.Target, Color.PaleVioletRed, 1.0f,
0);
device.BeginScene();
device.VertexFormat = CustomVertex.PositionColored.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList,
vertexes.Length / 3,
vertexes);
device.EndScene();
device.Present();
}

private void Form1_Load(object sender, EventArgs e)


{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp);
device.Transform.Projection = Matrix.PerspectiveFovLH(3.14f /
4,
device.Viewport.Width / device.Viewport.Height, 1f, 1000f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0,
20), new
Vector3(),
new Vector3(0, 1, 0));
device.RenderState.Lighting = false;

vertexes[0] = new CustomVertex.PositionColored(new


Vector3(0,0,0),
Color.Blue.ToArgb());

vertexes[1] = new CustomVertex.PositionColored(new Vector3(3,


0, 0),
Color.Blue.ToArgb());
vertexes[2] = new CustomVertex.PositionColored(new Vector3(0,
3, 0),
Color.Blue.ToArgb());
vertexes[3] = new CustomVertex.PositionColored(new Vector3(0,
3, 0),
Color.Blue.ToArgb());
vertexes[4] = new CustomVertex.PositionColored(new Vector3(3,
0, 0),
Color.Blue.ToArgb());
vertexes[5] = new CustomVertex.PositionColored(new Vector3(3,
3, 0),
Color.Blue.ToArgb());

}
}
}

[USCSP5042]
8
Game ProgrammingTYBSc. CS.

Output:

D)Texture the triangle using Direct3D 11.


In this practical we are just learning the window framework and initializing a Direct3D
device.
Step 1:
. Create new project, and select “Windows Forms Application”, select .NET
Framework as 2.0 in Visuals C#.
i. Right Click on properties Click on open click on build Select Platform Target and
Select x86.
Step 2: Click on View Code of Form 1.
Step 3:
Go to Solution Explorer, right click on project name, and select Add Reference. Click

[USCSP5042]
9
Game ProgrammingTYBSc. CS.

on Browse and select the given .dll files which are “Microsoft.DirectX”,
“Microsoft.DirectX.Direct3D”, and “Microsoft.DirectX.DirectX3DX”.
Step 4:
Go to Properties Section of Form, select Paint in the Event List and enter as
Form1_Paint.
Step 5:

Edit the Form’s C# code file. Namespace must be as same as your project name.

Program:

using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;
using System;
using System.Drawing;
using System.Windows.Forms;

namespace p1_gp
{
public partial class Form4 : Form
{
private Microsoft.DirectX.Direct3D.Device device;
private CustomVertex.PositionTextured[] vertex = new
CustomVertex.PositionTextured[3];
private Texture texture;
public Form4()
{
InitializeComponent();
InitDevice();
}
private void InitDevice()
{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp);
device.Transform.Projection = Matrix.PerspectiveFovLH(3.14f /
4, device.Viewport.Width / device.Viewport.Height, 1f, 1000f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0,
20), new Vector3(), new Vector3(0, 1, 0));
device.RenderState.Lighting = false;
vertex[0] = new CustomVertex.PositionTextured(new Vector3(-5,
-6, 0), 0, 0);
vertex[1] = new CustomVertex.PositionTextured(new Vector3(5,
-6, 0), 0, 1);

[USCSP5042]
10
Game ProgrammingTYBSc. CS.

vertex[2] = new CustomVertex.PositionTextured(new Vector3(0,


7, 0), -1, 1);
texture = new Texture(device, new
Bitmap("D:\\Images\\graphic_art\\FlowerTexture2.jpeg"), 0, Pool.Managed);
}

private void Form1_Load(object sender, EventArgs e)


{
}

private void Form1_Paint(object sender, PaintEventArgs e)


{
device.Clear(ClearFlags.Target, Color.WhiteSmoke, 1, 0);
device.BeginScene();
device.SetTexture(0, texture);
device.VertexFormat = CustomVertex.PositionTextured.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList,
vertex.Length / 3, vertex);
device.EndScene();
device.Present();
}

}
}

Output:

[USCSP5042]
11
Game ProgrammingTYBSc. CS.

Texture the Rectangle using Direct3D 11.

In this practical we are just learning the window framework and initializing a Direct3D

device.

Step 1:

Create new project, and select “Windows Forms Application”, select .NET

Framework as 2.0 in Visuals C#.

Right Click on properties Click on open click on build Select Platform Target and

Select x86.

Step 2: Click on View Code of Form 1.

Step 3:

Go to Solution Explorer, right click on project name, and select Add Reference. Click

on Browse and select the given .dll files which are “Microsoft.DirectX”,

“Microsoft.DirectX.Direct3D”, and “Microsoft.DirectX.DirectX3DX”.

Step 4:

Go to Properties Section of Form, select Paint in the Event List and enter as

Form1_Paint.

Step 5:

[USCSP5042]
12
Game ProgrammingTYBSc. CS.

Edit the Form’s C# code file. Namespace must be as same as your project name.

Program:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Microsoft.DirectX;
using Microsoft.DirectX.Direct3D;

namespace WindowsFormsApp10
{
public partial class Form1 : Form
{
private Device device;
private CustomVertex.PositionColored[] vertex = new
CustomVertex.PositionColored[6];
private Texture texture;
public Form1()
{
InitializeComponent();
}

private void Form1_Load(object sender, EventArgs e)


{
PresentParameters pp = new PresentParameters();
pp.Windowed = true;
pp.SwapEffect = SwapEffect.Discard;
device = new Device(0, DeviceType.Hardware, this,
CreateFlags.HardwareVertexProcessing, pp);
device.Transform.Projection =Matrix.PerspectiveFovLH(3.14f / 4,
device.Viewport.Width / device.Viewport.Height, 1f, 1000f);
device.Transform.View = Matrix.LookAtLH(new Vector3(0, 0, 20), new
Vector3(), new Vector3(0, 1, 0));
device.RenderState.Lighting = false;

vertex[0] = new CustomVertex.PositionColored(new Vector3(),


Color.White.ToArgb());

vertex[1] = new CustomVertex.PositionColored(new Vector3(3, 0, 0),


Color.White.ToArgb());
vertex[2] = new CustomVertex.PositionColored(new Vector3(0, 3, 0),
Color.White.ToArgb());
vertex[3] = new CustomVertex.PositionColored(new Vector3(3, 0, 0),
Color.White.ToArgb());
vertex[4] = new CustomVertex.PositionColored(new Vector3(3, 3, 0),
Color.White.ToArgb());
vertex[5] = new CustomVertex.PositionColored(new Vector3(0, 3, 0),
Color.White.ToArgb());

[USCSP5042]
13
Game ProgrammingTYBSc. CS.

texture = new Texture(device, new


Bitmap("C:\\Users\\shubham\\Desktop\\images.jpg"), 0,
Pool.Managed);

private void Form1_Paint(object sender, PaintEventArgs e)


{
device.Clear(ClearFlags.Target, Color.Aqua,1, 0);
device.BeginScene();
device.SetTexture(0, texture);
device.VertexFormat = CustomVertex.PositionTextured.Format;
device.DrawUserPrimitives(PrimitiveType.TriangleList, vertex.Length / 3,
vertex);
device.EndScene();
device.Present();
}
}

Output:-

[USCSP5042]
14
Game ProgrammingTYBSc. CS.

PRACTICAL 2

AIM: Basics of pygame

A) Creating pygame window

To create a window using Python and Pygame, you need to follow these steps:

Install Pygame: If you haven't installed Pygame yet, you can do it using pip:

pip install pygame

Import Pygame: At the beginning of your Python script, import the Pygame module.

[USCSP5042]
15
Game ProgrammingTYBSc. CS.

import pygame

Initialize Pygame: Before creating the window, initialize Pygame.

pygame.init()

Set up the window: Define the width and height of the window, and create it using the
pygame.display.set_mode() function.

width, height = 800, 600


window=pygame.display.set_mode((width, height))

Main loop: To keep the window open and responsive, create a main loop where you can
handle events and update the display.

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Add your game logic and draw calls here

pygame.display.update()

Quit Pygame: After exiting the main loop, remember to quit Pygame properly.

pygame.quit()

Source code

[USCSP5042]
16
Game ProgrammingTYBSc. CS.

import pygame
pygame.init()
width, height = 800, 600
window = pygame.display.set_mode((width, height))

running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Add your game logic and draw calls here


pygame.display.update()
pygame.quit()

Output:

[USCSP5042]
17
Game ProgrammingTYBSc. CS.

B) Python pygame movements

1. you can install it using pip:


pip install pygame
.import the Pygame library:
import pygame
initialize Pygame and set up the window:
pygame.init()

# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Basic Movements with Pygame")

2. create a basic game loop that will handle user input and update the screen:
# Character settings
character_width, character_height = 50, 50
character_x, character_y = (WIDTH - character_width) // 2, (HEIGHT -
character_height) // 2
character_speed = 5

# Main game loop


clock = pygame.time.Clock()
running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

keys = pygame.key.get_pressed()

[USCSP5042]
18
Game ProgrammingTYBSc. CS.

if keys[pygame.K_LEFT]:
character_x -= character_speed
if keys[pygame.K_RIGHT]:
character_x += character_speed
if keys[pygame.K_UP]:
character_y -= character_speed
if keys[pygame.K_DOWN]:
character_y += character_speed

# Update the screen


screen.fill((255, 255, 255))
pygame.draw.rect(screen, (0, 0, 255), (character_x, character_y, character_width,
character_height))
pygame.display.flip()

clock.tick(60)

3. Quit Pygame: After exiting the main loop, remember to quit Pygame properly.
pygame.quit()

Complete source code

import pygame
import sys

pygame.init()

# Screen settings
WIDTH, HEIGHT = 800, 600
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Basic Movements with Pygame")

# Character settings

[USCSP5042]
19
Game ProgrammingTYBSc. CS.

character_width, character_height = 50, 50


character_x, character_y = (WIDTH - character_width) // 2, (HEIGHT - character_height) // 2
character_speed = 5

# Main game loop


clock = pygame.time.Clock()
running = True

while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
character_x -= character_speed
if keys[pygame.K_RIGHT]:
character_x += character_speed
if keys[pygame.K_UP]:
character_y -= character_speed
if keys[pygame.K_DOWN]:
character_y += character_speed

# Update the screen


screen.fill((255, 255, 255))
pygame.draw.rect(screen, (0, 0, 255), (character_x, character_y, character_width,
character_height))
pygame.display.flip()

clock.tick(60)

pygame.quit()
sys.exit()

Output:

[USCSP5042]
20
Game ProgrammingTYBSc. CS.

C)Pygame Text Display

To display text using pygame, you'll first need to install pygame and then use its functions to
create and render text on the screen.
Follow the given steps to display text on screen.

1. Import the Pygame library.


2. Initialize Pygame and create a window.
3. Create a font object to set the text style and size.
4. Render the text using the font object.
5. Blit the text surface onto the screen.
6. Update the display to show the text.

[USCSP5042]
21
Game ProgrammingTYBSc. CS.

import pygame
import sys

# Initialize Pygame
pygame.init()

# Set up the window


screen_width, screen_height = 800, 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Text Display Example")

# Set up the font


font = pygame.font.Font(None, 36) # You can choose your own font and
size here

# Set up the text content


text_content = "Hello, Pygame!"

# Render the text


text_surface = font.render(text_content, True, (255, 255, 255)) # White
color

# Main game loop


while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Clear the screen
screen.fill((0, 0, 0)) # Black background

# Blit the text surface onto the screen at position (x, y)


x, y = 300, 250
screen.blit(text_surface, (x, y))

# Update the display


pygame.display.flip()

Output:

[USCSP5042]
22
Game ProgrammingTYBSc. CS.

The code will create a Pygame window and display the text "Hello, Pygame!" at coordinates
(300, 250) with a white color on a black background. You can customize the text content,
font, size, and position to suit your needs

D) Display image on screen


1. Import the Pygame library
2. Initialize Pygame:
3. Set up the display window:
4. Load the image you want to display
5. write Main game loop to keep the window
6. Remember to replace "path/to/your/image.png" with the actual file path of the
image you want to display. You can adjust the image position by changing the x and y
variables.

[USCSP5042]
23
Game ProgrammingTYBSc. CS.

import pygame
pygame.init()
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Image Display")
image_path = "c:\\" # Replace with the actual image path
image = pygame.image.load(image_path)
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False

# Clear the screen


screen.fill((0, 0, 0))

# Display the image on the screen at a specified position


x, y = 100, 100 # Adjust these coordinates as needed
screen.blit(image, (x, y))

# Update the display


pygame.display.update()

# Quit Pygame
pygame.quit()

[USCSP5042]
24
Game ProgrammingTYBSc. CS.

Output:

E) Using mixer and and music module in pygame


Mixer module
the mixer module is used for handling audio.
The mixer module allows you to play and manipulate sound effects
Music module
the music module specifically deals with background music.
the music module focuses on playing music tracks, typically in formats like MP3

Following are steps to implement


Step 1:

[USCSP5042]
25
Game ProgrammingTYBSc. CS.

To use the mixer and music modules in Pygame, you need to import them like
this:
import pygame
from pygame import mixer

Step 2:

To initialize Pygame and the mixer module, call the following before using any
audio functionality:

pygame.init()

mixer.init()

Step 3:

To play a sound effect using the mixer module:

mixer.Sound("soundeffect.wav").play()

Step 4:

To play background music using the music module:

pygame.mixer.music.load("backgroundmusic.mp3")

pygame.mixer.music.play(-1) # The '-1' indicates looping indefinitely.

Step 5:

handle events and the main game loop to keep the audio playing and
responsive

Step 6:

pygame.mixer.music.stop()

[USCSP5042]
26
Game ProgrammingTYBSc. CS.

Note:

Above program sets up a Pygame window with a white background. It loads a


background music track named "backgroundmusic.mp3" and plays it in an infinite
loop. Whenever the spacebar is pressed, a sound effect named "soundeffect.wav" is
played using the mixer module. The main game loop ensures the window stays
responsive until the user closes it.

You should have the necessary sound files ("backgroundmusic.mp3" and


"soundeffect.wav") in the same directory as the Python script or provide the correct
paths to those files.

Complete source code

import pygame

from pygame import mixer

# Initialize Pygame and the mixer module

pygame.init()

mixer.init()

# Set up the display

screen_width, screen_height = 800, 600

screen = pygame.display.set_mode((screen_width, screen_height))

pygame.display.set_caption("Pygame Audio ")

# Load background music

pygame.mixer.music.load("DireDireDocks.mp3")

[USCSP5042]
27
Game ProgrammingTYBSc. CS.

pygame.mixer.music.play(-1) # Play music in an infinite loop

# Load sound effect

sound_effect = mixer.Sound("marioEffect.wav")

# Main game loop

running = True

while running:

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

elif event.type == pygame.KEYDOWN:

if event.key == pygame.K_SPACE:

# Play the sound effect when the spacebar is pressed

sound_effect.play()

# Update the display

screen.fill((255, 255, 255))

pygame.display.flip()

# Stop the background music and quit Pygame

pygame.mixer.music.stop()

pygame.quit()

Output:

Video showcasing BG music and sound effects:


https://drive.google.com/file/d/18LuE0yqWHnftRqvAiptmNuIltjVUElzZ/view?us
p=drive_link

[USCSP5042]
28
Game ProgrammingTYBSc. CS.

F) Animation

import pygame

pygame.init()

# Set up display dimensions

width = 800

height = 600

screen = pygame.display.set_mode((width, height))

pygame.display.set_caption("My Animation")

clock = pygame.time.Clock()

running = True

ball_radius = 20

ball_color = (255, 0, 0)

ball_x = width // 2

ball_y = height // 2

ball_velocity = [5, 5] # Change in x and y positions per frame

running = True

while running:

for event in pygame.event.get():

if event.type == pygame.QUIT:

running = False

# Update ball position

ball_x += ball_velocity[0]

[USCSP5042]
29
Game ProgrammingTYBSc. CS.

ball_y += ball_velocity[1]

# Bounce the ball off the edges

if ball_x <= 0 or ball_x >= width:

ball_velocity[0] = -ball_velocity[0]

# balls x coordinate is less than

# the radius and greater thn the screen width means ball has hit left

# or right edge so reverse x direction by negative value to speed

#causing ball to bounce

if ball_y <= 0 or ball_y >= height:

ball_velocity[1] = -ball_velocity[1]

# ball's x coordinate is less than

#the radius and greater thn the screen height means ball has hit top

#or bottom edge so reverse y direction by negative value to speed

#causing ball to bounce

# Clear the screen

screen.fill((0, 0, 0))

# Draw the ball

pygame.draw.circle(screen, ball_color, (ball_x, ball_y), ball_radius)

# Update the display

pygame.display.flip()

# Add a short delay to control frame rate

pygame.time.delay(30)

pygame.quit()

[USCSP5042]
30
Game ProgrammingTYBSc. CS.

Output:

[USCSP5042]
31
Game ProgrammingTYBSc. CS.

PRACTICAL 3

Aim: Develop Snake Game using PyGame.

Program:

import pygame

pygame.init()#imported and initialised pygame module

screen = pygame.display.set_mode((600, 500))

pygame.display.set_caption('Snake game!')#set up the screen and set up a


caption

import time

import random#imported random for random coordinates for food

snake_pos = [80, 30]#initial or start position of snake

snake_speed = 10 #snake moves with this speed for making the game
difficult increase this and play

clock = pygame.time.Clock()# object to set framerate later

snake_body = [[80, 30],[70, 30]] #snake's body

foodpos = [random.randrange(1, (600//10)) * 10, random.randrange(1,


(500//10)) * 10] #first random spot of food

[USCSP5042]
32
Game ProgrammingTYBSc. CS.

food = True #boolean to know when to change the food's position

score = 0# workin with score initial score is 0

def show_score(): #to display score just like text no calculation of


score is done in this function

font = pygame.font.SysFont('Georgia', 30)

Font = font.render('Score : ' + str(score), True, 'pink')

rect = Font.get_rect()

screen.blit(Font, rect)#just like displaying text on screen

def game_over():#also to diplay the 'game over' text

font = pygame.font.SysFont('Georgia', 50)

Font = font.render(

'GAME OVER Score: ' + str(score), True, 'purple')

rect = Font.get_rect()

rect.midtop = (600/2, 500/4)

screen.blit(Font, rect)

pygame.display.flip()

time.sleep(2)#to quit automatically when game over

pygame.quit()

quit()

#to handle movement of the snake

dir = 'RIGHT' #initial direction of movement of the snake before any


input

next_dir = dir #the input given

[USCSP5042]
33
Game ProgrammingTYBSc. CS.

while True: #the game loop covers actual movement handling, the game over
conditions, the figure and score functions

for event in pygame.event.get():#to know what key was pressed


and where to go next

if event.type == pygame.KEYDOWN:

if event.key == pygame.K_UP:

next_dir = 'UP'

if event.key == pygame.K_DOWN:

next_dir = 'DOWN'

if event.key == pygame.K_LEFT:

next_dir = 'LEFT'

if event.key == pygame.K_RIGHT:

next_dir = 'RIGHT'

#HANDLING THE MOVEMENTS

#updating dir with the input stored in next_dir

if next_dir == 'UP' and dir != 'DOWN':

dir = 'UP'

if next_dir == 'DOWN' and dir != 'UP':

dir = 'DOWN'

if next_dir == 'LEFT' and dir != 'RIGHT':

dir = 'LEFT'

if next_dir == 'RIGHT' and dir != 'LEFT':

dir = 'RIGHT'

# to move the snake change its position

if dir == 'UP':

snake_pos[1] -= 10

if dir == 'DOWN':

[USCSP5042]
34
Game ProgrammingTYBSc. CS.

snake_pos[1] += 10

if dir == 'LEFT':

snake_pos[0] -= 10

if dir == 'RIGHT':

snake_pos[0] += 10

snake_body.insert(0, list(snake_pos))#insert every coordinate


that the snake passes through

if snake_pos[0] == foodpos[0] and snake_pos[1] == foodpos[1]:


# snake meets the food score is increases and it is time to set up a new
food spot

score += 10

food = False

else:#if snake doesnot meet the food then pop the coordinates

snake_body.pop()

if not food:#if food is set false assign a new coordinate to


foodpos

foodpos = [random.randrange(1, (600//10)) *


10,random.randrange(1, (500//10)) * 10]

food = True

screen.fill('black')

for pos in snake_body: #draw the snake

pygame.draw.rect(screen, 'green',(pos[0], pos[1],


10, 10))

pygame.draw.circle(screen, 'dark red', (foodpos[0],


foodpos[1]),5)

[USCSP5042]
35
Game ProgrammingTYBSc. CS.

#THE GAME OVER CONDITIONS

if snake_pos[0] < 0 or snake_pos[0] > 600-10:#bumped into the


left or right wall

game_over()

if snake_pos[1] < 0 or snake_pos[1] > 500-10:#bumped into the


upper or bottom wall

game_over()

for block in snake_body[1:]:#snake bites itself

if snake_pos[0] == block[0] and snake_pos[1] ==


block[1]:

game_over()

show_score()#see score all the time on screen

pygame.display.update()

clock.tick(snake_speed)

Output:

[USCSP5042]
36
Game ProgrammingTYBSc. CS.

PRACTICAL 4

Aim: Develop 2 D shooting game using PyGame.

Program:

import pygame
import random
# Screen
pygame.init()
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Shooting Game")
# Colors
white = (255, 255, 255)
red = (255, 0, 0)
blue = (0, 0, 255)
# Character
character_size = 50
character_speed = 5
character = pygame.Rect(width // 2 - character_size // 2, height -
character_size, character_size, character_size)

[USCSP5042]
37
Game ProgrammingTYBSc. CS.

# Bullets (triangles) properties


bullet_size = 10
bullets = []
# Enemy (circle) properties
enemy_radius = 20
enemies = []
# Initialize score
score = 0
# Clock for controlling frame rate
clock = pygame.time.Clock()
# Main game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
bullet = pygame.Rect(character.centerx - bullet_size //
2, character.top, bullet_size, bullet_size)
bullets.append(bullet)
# Move bullets
for bullet in bullets:
bullet.y -= 10
if bullet.top < 0:
bullets.remove(bullet)
# Spawn enemies
if random.randint(1, 100) <= 2:
enemy_x = random.randint(enemy_radius, width - enemy_radius)
enemy = pygame.Rect(enemy_x - enemy_radius, 0, enemy_radius * 2,
enemy_radius * 2)
enemies.append(enemy)
# Move enemies
for enemy in enemies:
enemy.y += 5
if enemy.top > height:
enemies.remove(enemy)
# Move character
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
character.x -= character_speed
if keys[pygame.K_RIGHT]:
character.x += character_speed
# Check for collisions
for bullet in bullets:
for enemy in enemies:
if bullet.colliderect(enemy):
score += 1
bullets.remove(bullet)
enemies.remove(enemy)
# Check for character collision with enemies

[USCSP5042]
38
Game ProgrammingTYBSc. CS.

for enemy in enemies:


if character.colliderect(enemy):
running = False
# Clear the screen
screen.fill(white)
# Draw bullets
for bullet in bullets:
pygame.draw.polygon(screen, blue, [(bullet.left, bullet.bottom),
(bullet.centerx, bullet.top), (bullet.right, bullet.bottom)])
# Draw character
pygame.draw.rect(screen, red, character)
# Draw enemies
for enemy in enemies:
pygame.draw.circle(screen, red, enemy.center, enemy_radius)
# Display score
font = pygame.font.Font(None, 36)
score_text = font.render(f"Score: {score}", True, red)
screen.blit(score_text, (10, 10))
# Update display
pygame.display.flip()
# Limit frame rate to 60 FPS
clock.tick(60)
# Game over display
font = pygame.font.Font(None, 72)
game_over_text = font.render("Game Over", True, red)
screen.blit(game_over_text, (width // 2 - game_over_text.get_width() //
2, height // 2 - game_over_text.get_height() // 2))
pygame.display.flip()
# Wait for a few seconds before closing the game
pygame.time.wait(3000)
# Clean up
pygame.quit()

Output:

[USCSP5042]
39
Game ProgrammingTYBSc. CS.

PRACTICAL 5

Aim: Creating 2D Infinite Scrolling Background.

Program:

import pygame

[USCSP5042]
40
Game ProgrammingTYBSc. CS.

import math
pygame.init()
clock = pygame.time.Clock()
FPS = 60
SCREEN_WIDTH = 1500
SCREEN_HEIGHT = 600
#create game window
screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
pygame.display.set_caption("Endless Scroll")
#load image
bg = pygame.image.load("greenHill.jpg").convert()
bg_width = bg.get_width()
bg_rect = bg.get_rect()
#define game variables
scroll = 0
tiles = math.ceil(SCREEN_WIDTH / bg_width) + 1
#game loop
run = True
while run:
clock.tick(FPS)
#draw scrolling background
for i in range(0, tiles):
screen.blit(bg, (i * bg_width + scroll, 0))
bg_rect.x = i * bg_width + scroll
pygame.draw.rect(screen, (255, 0, 0), bg_rect, 1)

#- A for loop iterates over the range of tiles.


#- In each iteration, the background image bg is blitted (drawn) onto the
screen surface
at a position determined by the current value of scroll and the index i.

#scroll background
scroll -= 5
#reset scroll
if abs(scroll) > bg_width:
scroll = 0
#event handler
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.display.update()
pygame.quit()

Output:

[USCSP5042]
41
Game ProgrammingTYBSc. CS.

PRACTICAL 6

Aim: Using a unity3d software and making a 2d ufo game.

[USCSP5042]
42
Game ProgrammingTYBSc. CS.

Following are the steps to create a Camera Shake Effect in Unity: STEP 1 :

Start Unity

STEP 2 : Create new project 2D. Add project name

STEP 3 : Add folders such as Sprites, Scenes, Scripts, etc

[USCSP5042]
43
Game ProgrammingTYBSc. CS.

STEP 4 : Add Assets by right-click > Import Asset

[USCSP5042]
44
Game ProgrammingTYBSc. CS.

STEP 5 : Import the Following assets : Background and UFO

STEP 6 : Drag the assets to the Hierarchy > Click and hold asset and drag under
MainCamera SImilarly, Drag and add the UFO under the background

[USCSP5042]
45
Game ProgrammingTYBSc. CS.

STEP 7 : Adjust the MainCamera by changing the size

STEP 8 : Select the UFO from Hierarchy. To make the UFO layer appear above the
Background, Add a sorting layer, and select the layer. Update the following settings
for UFO. Add a circle collider and adjust the radius. Adjust gravity Scale

Rigidbodies are components that allow a GameObject to react to real-time physics.


This includes reactions to forces and gravity, mass, drag and momentum. You can
attach a Rigidbody to your GameObject by simply clicking on Add Component and
typing in Rigidbody2D in the search field.

[USCSP5042]
46
Game ProgrammingTYBSc. CS.

STEP 9 : Select the Background from Hierarchy. Add a box collider from Add
component > Box Collider 2D. Do this step 4 times for each border of the box
collider.
Also, set the Shake Frequency which set the intensity of the Shake Effect

STEP 10 : To implement the camera shake effect, add a new script as follows:

[USCSP5042]
47
Game ProgrammingTYBSc. CS.

On clicking on the new script, VS code Editor will open. Add the following code :

public Transform cameraTransform = default;


private Vector3 _orignalPosOfCam = default;
public float shakeFrequency = default;

void Start()
{
_orignalPosOfCam = cameraTransform.position;
}

void Update()
{
if (Input.GetKey(KeyCode.S))
{
CameraShake();
}
else if (Input.GetKeyUp(KeyCode.S))
{
StopShake();
}
}

private void CameraShake()


{
cameraTransform.position = _orignalPosOfCam +
Random.insideUnitSphere * shakeFrequency;
}

private void StopShake()


{
cameraTransform.position = _orignalPosOfCam;
}

[USCSP5042]
48
Game ProgrammingTYBSc. CS.

The final output will result in the Camera Shake Effect on pressing the key ‘S’:

[USCSP5042]
49
Game ProgrammingTYBSc. CS.

PRACTICAL 7

Aim: Design and Animate Game Character in Unity

Following are the steps to Animate a character in

STEP 1: Follow the previous practical till step 8.


STEP 2 : To implement the Animate method, add a new script ‘Animate’ from UFO
> Add Component > New Script

CODE:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class animate : MonoBehaviour
{
public float speed;
Rigidbody2D rb2d;
// Start is called before the first frame update
void Start()
{
rb2d = GetComponent<Rigidbody2D>();
}

// Update is called once per frame


void FixedUpdate()
{
float moveHorizontal = Input.GetAxis("Horizontal");
float moveVertical = Input.GetAxis("Vertical");
var movement = new Vector2(moveHorizontal, moveVertical).normalized
* speed * Time.deltaTime;
rb2d.AddForce(movement);
}
}

[USCSP5042]
50
Game ProgrammingTYBSc. CS.

STEP 3 : Adjust the following : Set animate Speed = 1500 and make the
Rigidbody2D > Gravity Scale = 0.

Run the code and the UFO should move with the Arrow Keys.

[USCSP5042]
51
Game ProgrammingTYBSc. CS.

PRACTICAL 8

Aim: Create Snowfall Particle Effect in Unity.

Following are the steps to Create Snowfall Particle Effect in Unity:

STEP 1: Follow Steps from practical number 7 till Step 8.

STEP 2 : To add Particle effect, right-click on Effects under Hierarchy and Select >
Particle System

[USCSP5042]
52
Game ProgrammingTYBSc. CS.

This is what the initial screen looks like.

STEP 3 : Scroll down in Inspector to the Shape and Change it to BOX from Cone

[USCSP5042]
53
Game ProgrammingTYBSc. CS.

STEP 4 : Adjust the ‘X” Scale under Shape to adjust the width of the effect.

It will the look like this after Adjusting:

[USCSP5042]
54
Game ProgrammingTYBSc. CS.

STEP 5 : Adjust ‘Y’ scale under Transform to move the particle upwards

STEP 6 : Now, rotate the particle using the rotate tool present on the scene
screen (third from top)
The final outcome would be like this :

[USCSP5042]
55

You might also like