[go: up one dir, main page]

0% found this document useful (0 votes)
6 views43 pages

GP Journal

The document outlines a series of practical exercises for a computer science course, focusing on setting up DirectX 11 and developing games using Pygame. It includes detailed steps for initializing Direct3D, creating a Windows Forms application, and coding basic games like Snake and a target shooting game. Each practical exercise provides code examples and aims to teach fundamental programming and game design techniques.

Uploaded by

mayuripawar927
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views43 pages

GP Journal

The document outlines a series of practical exercises for a computer science course, focusing on setting up DirectX 11 and developing games using Pygame. It includes detailed steps for initializing Direct3D, creating a Windows Forms application, and coding basic games like Snake and a target shooting game. Each practical exercise provides code examples and aims to teach fundamental programming and game design techniques.

Uploaded by

mayuripawar927
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 43

TY BSC CS

ROLL NO: 18
PRACTICAL: 1

AIM: - Setup DirectX 11, Window Framework and Initialize Direct3D Device,
Loading models into DirectX 11 and rendering

CODE: -
Step 1: Download the DirectX SDK
1. Visit the Microsoft DirectX SDK Download Page:
o Go to the DirectX SDK (June 2010) Download.
2. Click the "Download" button and select the DXSDK_Jun10.exe file.

Step 2: Install the DirectX SDK


1. Run the downloaded file (DXSDK_Jun10.exe).
o Follow the on-screen instructions to install the DirectX SDK.
o Choose the location where you want to install it.
2. Install it to the default location, which should be something like:
C:\Program Files (x86)\Microsoft DirectX SDK (June 2010)

Step 3: Launch Visual Studio 2022

Step 4: Create a New Windows Forms Application Project

1. Start a new project:


o On the Visual Studio start screen, click Create a new project.
2. Select the Windows Forms App template:
o In the Create a new project dialog, use the search bar to search for
"Windows Forms App."
o Select the Windows Forms App (.NET) template from the list (C#
language).
o Click Next.

Step 5: Configure the Project


1. Name the project:
o Enter a name for your project in the Project name field (e.g.,
"MyWindowsApp").
o Choose a location to save the project under Location.
o Set a Solution name or use the same name as the project.
2. Select the target framework:
o In the Framework dropdown, select the desired .NET Framework
version.
o Click Create.

Step 6: Set the Platform Target to x86


1. Open Solution Explorer:

1
TY BSC CS
ROLL NO: 18
o In Visual Studio, if the Solution Explorer pane is not visible, go to
View > Solution Explorer.
2. Right-click on your project:
o Right-click on the project (not the solution) in the Solution Explorer
and select Properties.
3. Set the platform target:
o In the Properties window, click on the Build tab.
o Under Platform target, set the dropdown to x86 (or x64 if you are
targeting 64-bit systems).
4. Save the changes:
o Press Ctrl + S to save the changes.

Step 7: Add Reference to DirectX Libraries


1. Right-click on the project:
o In the Solution Explorer, right-click the project and select Add >
Reference.
2. Add a new reference:
o In the Reference Manager dialog that appears, select the Browse
section on the left.
3. Browse to the DirectX SDK folder:
o Click on the Browse button and navigate to the folder where you
installed the DirectX SDK (if you installed the standalone DirectX SDK)
4. Select the DirectX DLL files:
o Inside the selected folder, locate and select the DirectX-related DLL
files that you need, such as:
 Direct3D.dll
 Direct3DX.dll
 DirectX.dll
5. Click Add:
o After selecting the required DLL files, click the Add button to add them
as references in your project.

Step 8: Open Form1.cs


1. Locate Form1.cs in Solution Explorer:
o In the Solution Explorer, find and click on the file named Form1.cs
(this is the main form of your application).
o Double-click on Form1.cs to open the form designer and code.

Step 9: Access the Properties Window


1. Select the form (Form1):
o In the Designer view of Form1.cs, click anywhere on the form to select
it (or click on Form1 in the dropdown at the top of the Properties
window).
2. Open the Properties window:

2
TY BSC CS
ROLL NO: 18
o If the Properties window is not visible, press F4 or go to View >
Properties Window in the menu.

Step 10: Access the Events Tab


1. Switch to the Events tab:
o In the Properties window, there are two tabs at the top: one for
Properties (a gear icon) and one for Events (a lightning bolt icon).
o Click the Events tab (the lightning bolt icon) to view available events
for Form1.

Step 11: Handle the Paint Event


1. Find the Paint event:
o Scroll through the events list in the Events tab of the Properties
window until you find the Paint event.
2. Double-click the Paint event:
o Double-click on the empty field next to the Paint event to automatically
generate a method and open the Form1_Paint event handler in
Form1.cs.

Step 12: Access the Form1_Load Event


1. Go back to the Events tab (if needed):
o If you are still in the Events tab of the Properties window, find the
Load event.
2. Handle the Load event:
o Double-click on the empty field next to the Load event to generate the
Form1_Load event handler.

Step 13: Scroll Between Methods in Form1.cs


1. Scroll between Paint and Load methods:
o If both the Paint and Load event methods are now open in the
Form1.cs file, you can scroll down or up to view and edit these
methods.

Now, write the code to render graphics in DirectX. The following code sets up a
Direct3D device, clears the screen, and prepares the application for rendering
graphics in a Windows Forms environment:

3
TY BSC CS
ROLL NO: 18

OUTPUT: -

4
TY BSC CS
ROLL NO: 18
PRACTICAL: 2

AIM: - Learn Basic Game Designing Techniques with pygame.

CODE:

import pygame
import sys
# Initialize Pygame
pygame.init()
# Set up display
width, height = 800, 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Move Rectangle with Arrow Keys")
# Set up rectangle properties
rect_width, rect_height = 50, 50
rect_x, rect_y = width // 2, height // 2
rect_speed = 5
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
# Main game loop
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Get keys pressed
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT]:
rect_x -= rect_speed
if keys[pygame.K_RIGHT]:
rect_x += rect_speed
if keys[pygame.K_UP]:
rect_y -= rect_speed
if keys[pygame.K_DOWN]:
rect_y += rect_speed
# Ensure the rectangle stays within the window boundaries
if rect_x < 0:
rect_x = 0
if rect_x > width - rect_width:
rect_x = width - rect_width
if rect_y < 0:
rect_y = 0
if rect_y > height - rect_height:
rect_y = height - rect_height
5
TY BSC CS
ROLL NO: 18
# Fill screen with black
screen.fill(black)
# Draw the rectangle
pygame.draw.rect(screen, white, (rect_x, rect_y, rect_width, rect_height))
# Update the display
pygame.display.flip()
# Control the frame rate
pygame.time.Clock().tick(60)

OUTPUT: -

6
TY BSC CS
ROLL NO: 18
PRACTICAL: 3

AIM: - Develop Snake Game using pygame

CODE: -

import pygame
import random
# Initialize Pygame
pygame.init()
# Display settings
width = 600
height = 400
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Game")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# Clock and speed
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
# Draw the snake
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(screen, black, [x[0], x[1], snake_block, snake_block])
def gameLoop():
game_over = False
game_close = False
# Game variables initialization
x1 = width / 2
y1 = height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
# Food initialization
foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close:
screen.fill(white)
font_style = pygame.font.SysFont(None, 50)
7
TY BSC CS
ROLL NO: 18

mesg = font_style.render("You lost! Press Q-Quit or C-Play Again", True, red)


screen.blit(mesg, [width / 6, height / 3])
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 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill(white)
pygame.draw.rect(screen, 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()
8
TY BSC CS
ROLL NO: 18
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - snake_block) / 10.0) *
10.0
foody = round(random.randrange(0, height - snake_block) / 10.0) *
10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()

OUTPUT: -

9
TY BSC CS
ROLL NO: 18

PRACTICAL: 4

AIM: - Create 2D Target Shooting Game

CODE: -

import pygame
import random
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
WHITE = (255, 255, 255)
BLACK = (0, 0, 0)
ENEMY_COLOR = (255, 0, 0)
PLAYER_COLOR = (0, 255, 0)
BULLET_COLOR = (0, 0, 255)
# Set up the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("Space Invaders")
# Game variables
player_pos = [WIDTH // 2, HEIGHT - 50]
player_speed = 5
enemies = []
bullets = []
score = 0
level = 1
enemy_count = 10
game_over = False
enemy_speed = 1
# Font
font = pygame.font.SysFont(None, 35)
# Functions
def spawn_enemies(count):
for _ in range(count):
x_pos = random.randint(0, WIDTH - 50)
y_pos = random.randint(-150, -50)
enemies.append([x_pos, y_pos])
def draw_player():
pygame.draw.rect(screen, PLAYER_COLOR, (player_pos[0], player_pos[1],
50, 30))
def draw_enemies():
for enemy in enemies:

10
TY BSC CS
ROLL NO: 18
pygame.draw.rect(screen, ENEMY_COLOR, (enemy[0], enemy[1], 50,
30))
def draw_bullets():
for bullet in bullets:
pygame.draw.rect(screen, BULLET_COLOR, (bullet[0], bullet[1], 5, 10))
def move_enemies():
for enemy in enemies:
enemy[1] += enemy_speed
def move_bullets():
for bullet in bullets:
bullet[1] -= 10
def check_collisions():
global score
for bullet in bullets:
for enemy in enemies:
if bullet[0] in range(enemy[0], enemy[0] + 50) and bullet[1] in
range(enemy[1], enemy[1] + 30):
bullets.remove(bullet)
enemies.remove(enemy)
score += 1
break
def check_game_over():
for enemy in enemies:
if enemy[1] > HEIGHT - 50:
return True
return False
def display_score():
score_text = font.render(f"Score: {score}", True, BLACK)
screen.blit(score_text, [10, 10])

def display_level():
level_text = font.render(f"Level: {level}", True, BLACK)
screen.blit(level_text, [10, 50])
# Main game loop
clock = pygame.time.Clock()
spawn_enemies(enemy_count)
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_SPACE:
bullets.append([player_pos[0] + 22, player_pos[1]])
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and player_pos[0] > 0:
player_pos[0] -= player_speed
11
TY BSC CS
ROLL NO: 18
if keys[pygame.K_RIGHT] and player_pos[0] < WIDTH - 50:
player_pos[0] += player_speed
screen.fill(WHITE)
move_enemies()
move_bullets()
check_collisions()
if check_game_over():
game_over_text = font.render("GAME OVER", True, WHITE)
screen.blit(game_over_text, [WIDTH // 2 - 100, HEIGHT // 2 - 20])
pygame.display.flip()
pygame.time.wait(2000)
game_over = True
continue
draw_player()
draw_enemies()
draw_bullets()
display_score()
display_level()
if not enemies:
level += 1
enemy_count += 5
enemy_speed += 1
spawn_enemies(enemy_count)
bullets = [bullet for bullet in bullets if bullet[1] > 0]
pygame.display.flip()
clock.tick(30)
pygame.quit()

OUTPUT: -

12
TY BSC CS
ROLL NO: 18

PRACTICAL: 5

AIM: - Creating 2D Infinite Scrolling Background

CODE: -
import pygame
import sys
# Initialize Pygame
pygame.init()
# Constants
WIDTH, HEIGHT = 800, 600
FPS = 60
# Load background image
background = pygame.image.load('game.jpg')
background = pygame.transform.scale(background, (WIDTH, HEIGHT)) #
Scale to fit the window
# Set up the screen
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("2D Infinite Scrolling Background")
# Variables for background scrolling
y1 = 0
y2 = -HEIGHT # Second background image positioned above the first one
# Main game loop
clock = pygame.time.Clock()
while True:
13
TY BSC CS
ROLL NO: 18
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
# Scroll the background
y1 += 1
y2 += 1
# Reset background positions when they move off screen
if y1 >= HEIGHT:
y1 = -HEIGHT
if y2 >= HEIGHT:
y2 = -HEIGHT
# Draw the background images
screen.blit(background, (0, y1))
screen.blit(background, (0, y2))
# Update the display
pygame.display.flip()
# Cap the frame rate
clock.tick(FPS)

OUTPUT: -

14
TY BSC CS
ROLL NO: 18

15
TY BSC CS
ROLL NO: 18
PRACTICAL: 6

AIM: Create Camera Shake Effect in Unity

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


1.Start Unity
2.Create new project 2D. Add project name

3.Add folders such as Sprites, Scenes, Scripts, etc

4.Add Assets by right-click > Import Asset

16
TY BSC CS
ROLL NO: 18

5. Import the Following assets: Background and UFO

6: Drag the assets to the Hierarchy > Click and hold asset and drag under
MainCamera

17
TY BSC CS
ROLL NO: 18

SImilarly, Drag and add the UFO under the background

7.Adjust the MainCamera by changing the size

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.
18
TY BSC CS
ROLL NO: 18
Adjust gravity Scale

19
TY BSC CS
ROLL NO: 18
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.

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

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

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


Add the following code :

20
TY BSC CS
ROLL NO: 18

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;
}

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

OUTPUT: -

`
21
TY BSC CS
ROLL NO: 18

PRACTICAL: 7

AIM: Design and Animate Game Character in Unity

Requirements: 3 images in png files


1. Scene
2. Gamecharacter
3. Coin

Here right click each image and save as picture in a particular folder given below

Gamecharacter Coin

Scene

1.Open UnityHub and select 2D template and Name it as


2.Project Name: CoinCollectionGame
3.Create Project

22
TY BSC CS
ROLL NO: 18

4.This is our scene

5.Now In Project section we have Assets here we have to Create 3 Folders and name
it
23
TY BSC CS
ROLL NO: 18
1. Scripts
2. Sprites
3. Scenes

6.In Sprites Folder – Right Click - Import New Asset


Select the 3 images – scene, gamecharacter and coin

24
TY BSC CS
ROLL NO: 18

7.Later renamed it as scene in hierarchy – no issues


Now drag and drop the scene properly inside white border by resizing in it

Now drag and drop gamecharacter

25
TY BSC CS
ROLL NO: 18

Then drag and drop coin in front of gamecharacter

By selecting the first coin, press Ctrl + C then Ctrl + V and drag near one after other
as shown in the image

Here our designing the screen part is done

8.Now in Scripts Folder we have to add 3 C# Scripts


1. coinscript
2. movescript
3. scorescript

9.Open Script Folder – Right Click – Create – C# Script


Rename it all
1. coinscript
26
TY BSC CS
ROLL NO: 18
2. movescript
3. scorescript

First - Double Tap – coinscript and write the following code in Visual Studio 2022
Filename: coinscript.cs
Program:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class coinscript : MonoBehaviour


{
void OnTriggerEnter2D(Collider2D col)

27
TY BSC CS
ROLL NO: 18
{
scorescript.coinAmount += 1;
Destroy(gameObject);
}
}
Second - Double Tap – movescript and write the following code in Visual
Studio 2022
Filename: movescript.cs
Program:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class movescript : MonoBehaviour


{
float dirX, dirY;
public float moveSpeed = 5f;
Rigidbody2D rb;

void Start()
{
rb = GetComponent<Rigidbody2D>();
}
void Update()
{
dirX = Input.GetAxis("Horizontal");
dirY = Input.GetAxis("Vertical");
}

void FixedUpdate()
{
rb.velocity = new Vector2(dirX * moveSpeed, dirY * moveSpeed);

28
TY BSC CS
ROLL NO: 18
}
}

Third - Double Tap – scorescript and write the following code in Visual Studio 2022
Filename: scorescript.cs
Program:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;

public class scorescript : MonoBehaviour


{
Text text;
public static int coinAmount;

void Start()
{
text = GetComponent<Text>();
}

void Update()
{
text.text = coinAmount.ToString();
}
}
So far our screen designing and its scripting done
10.Now we have to configure all objects from Hierarchy to its Inspector
window
Here, are our scene object, gamecharacter object and 6 coins then we will create
text file under Canvas object
By Right Click – Create Empty
GameObject will be created then rename it as Canvas
29
TY BSC CS
ROLL NO: 18
Now for Canvas – Right Click – UI – Legacy - Text

Here is our Text Object

Select Text and Edit its Inspector Window

We have Edit the Text as “Score:0”, Font and Font Size


then drag and drop scorescript.
30
TY BSC CS
ROLL NO: 18
And our score text will visible by zooming out from mouse scrolling down
like this below image

Now Coin
(Added 6 Times Coins with its Components and its Configuration needed)
Coin

Select 1st Coin from Hierarchy and from Inspector Window of Coin
Add Component – Circle Collider 2D then

31
TY BSC CS
ROLL NO: 18

Drag and Drop coinscript from Script folder to Inspector Window of the Coin

32
TY BSC CS
ROLL NO: 18
Now after adding the Coin that is first Coin we have configure its component
Sprite Renderer – Sorting Layer – New Layer 1
Circle Collider – is Trigger checked
Drag and Drop – coinscript

Now the same configurations for rest of the coins to be done

After adding all the components and its configurations for the coin

33
TY BSC CS
ROLL NO: 18

Now,
Gamecharacter
We have to add components to gamecharacter and configure it
Select gamecharacter then add Sorting Layer – New Layer 1
Add components – Rigidbody 2D and Box Collider 2D – Check and its properties then
drag and drop movescript

34
TY BSC CS
ROLL NO: 18

Now all set and we have completed all screen designing, scripting and
configurations to all objects.
To run the game, save and by pressing Ctrl + S and play

On pressing Right Arrow Button >


the gamecharacter moves to right and collects the coins and the score updates

Output:

35
TY BSC CS
ROLL NO: 18
PRACTICAL: 8

AIM: - Create Snowfall Particle effect in Unity

Requirements: 2 Images
Snow land

Snow particle

Create New Project: 2D Template


Project Name: Snowfall

Game Scene

36
TY BSC CS
ROLL NO: 18

Now in Project Window – Under Assets -> Right Click -> Import New Assets

Select 2 Images and Import

Drag and drop snowland to Hierarchy

37
TY BSC CS
ROLL NO: 18
Now fit the snowland background image into rectangle white border

Now zoom by pressing ctrl +scroll up roll from mouse and fit in screen

Now to get the snowfall effect – we have to create Particle Effect


From Hierarchy -> Right Click -> Effect -> Particle System

This will present the Particle System in the center that is trying to emit objects

38
TY BSC CS
ROLL NO: 18

To get the particle emit from sky. Go to Transform Change the Rotation value X = -
270 and Position value Z: 0. It will reverse the Particle System downwards shown
below.

From Here we have to keep Particle System selected for each change to updates
its properties in its Inspector Window.
To position the Particle System above the snowland background, select the Shape
module transform editing mode

39
TY BSC CS
ROLL NO: 18

Select on down side blue arrow, it will turn yellow arrow and then drag it upward

Now the Transform Values automatically changes these below values.

Particle System – Inspector window


Check and update the below properties
1. Particle System
2. Emission
3. Shape
4. Texture Sheet Animation
5. Renderer

40
TY BSC CS
ROLL NO: 18

1. Particle System - Duration: 10, Looping Checked and

Start Size – Click on right most dropdown arrow and select Random Between Two
Constants and edit its values between 0.1 and 1.

2. Emission – Rate over Time: 20

3. Shape – Shape: Cone, Angle:25 and Radius:7

41
TY BSC CS
ROLL NO: 18

4. Texture Sheet Animation – Here we have to add our snow particle image
into this texture sheet animation.

First, we have to change the Mode from Grid to Sprites

Then drag and drop our snow particle image from Assets to the texture sheet
animation

Here, this is the update and changes done in Texture Sheet Animation

5. Renderer – Maximum Particle Size: 0.5

42
TY BSC CS
ROLL NO: 18

Now our Screen Designing and Particle System Configurations done, Save the
Project and Play

Output:

43

You might also like