0% found this document useful (0 votes)
14 views14 pages

Ilovepdf Merged

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)
14 views14 pages

Ilovepdf Merged

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/ 14

Ram Krishna Dharmarth Foundation

University, Bhopal , M.P.

Semester-5
Practical on :
Computer Graphics
BCA-501/M1T
Submitted By

Student Name :- - - - - - - - - - - - - -

Enrollment No. :- - - - - - - - - - - - - -

Dr.N.K.Shrivastava Mr. Anand Kumar


Head Assistant Professor

Faculty of Computer Application


Session-2024-25
1. Write a Program to draw basic graphics construction
like line, circle, arc, ellipse and rectangle.
import turtle
# Set up the turtle window
turtle.setup(width=600, height=600)
t = turtle.Turtle()
# Draw a line
t.penup()
t.goto(-100, 0)
t.pendown()
t.forward(200) # Draw line of length 200
# Draw a circle
t.penup()
t.goto(0, -100)
t.pendown()
t.circle(100) # Draw a circle with radius 100
# Draw an arc (half-circle)
t.penup()
t.goto(-50, 50)
t.setheading(0)
t.pendown()
t.circle(50, 180) # Draw an arc with radius 50 and extent 180 degree
# Draw an ellipse
t.penup()
t.goto(0, 0)
t.pendown()
for i in range(2): # Ellipse using semi-circles
t.circle(50, 90)
t.circle(25, 90)
# Draw a rectangle
t.penup()
t.goto(-100, -150)
t.pendown()
for _ in range(2): # Draw rectangle by iterating for sides
t.forward(200)
t.right(90)
t.forward(100)
t.right(90)
# Hide the turtle and display the result
t.hideturtle()
turtle.done()
2. Write a program of Translation, Rotation, and Scaling using
Composite Transformation.
import numpy as np
def translation_matrix(tx, ty):
"""Creates a translation matrix."""
return np.array([[1, 0, tx],
[0, 1, ty],
[0, 0, 1]])
def rotation_matrix(theta):
"""Creates a rotation matrix."""
return np.array([[np.cos(theta), -np.sin(theta), 0],
[np.sin(theta), np.cos(theta), 0],
[0, 0, 1]])
def scaling_matrix(sx, sy):
"""Creates a scaling matrix."""
return np.array([[sx, 0, 0],
[0, sy, 0],
[0, 0, 1]])
def apply_transformations(points, transformation_matrix):
"""Applies a transformation matrix to a set of points."""
homogeneous_points = np.hstack((points, np.ones((points.shape[0],
1))))
transformed_points = np.dot(homogeneous_points,
transformation_matrix.T)
return transformed_points[:, :2]
# Example usage:
points = np.array([[0, 0], [1, 0], [1, 1], [0, 1]]) # A square

# Define transformations
translation = translation_matrix(2, 3)
rotation = rotation_matrix(np.pi/4)
scaling = scaling_matrix(2, 1.5)

# Combine transformations
composite_transform = np.dot(translation, np.dot(rotation, scaling))

# Apply the composite transformation


transformed_points = apply_transformations(points,
composite_transform)

print(transformed_points)
3. Write a program to draw a Circle using midpoint
implementation Method.
import matplotlib.pyplot as plt
import numpy as np
def midpoint_circle_algorithm(radius, center_x, center_y):
Draws a circle using the Midpoint Circle Algorithm.

Args:
radius: Radius of the circle.
center_x: x-coordinate of the center.
center_y: y-coordinate of the center.
x=0
y = radius
p = 1 - radius
points = []

while x <= y:
points.append((center_x + x, center_y + y))
points.append((center_x - x, center_y + y))
points.append((center_x + x, center_y - y))
points.append((center_x - x, center_y - y))
points.append((center_x + y, center_y + x))
points.append((center_x - y, center_y + x))
points.append((center_x + y, center_y - x))
points.append((center_x - y, center_y - x))
x += 1
if p < 0:
p += 2 * x + 1
else:
y -= 1
p += 2 * (x - y) + 1
x_coords, y_coords = zip(*points)
plt.plot(x_coords, y_coords, 'o')
plt.axis('equal')
plt.grid(True)
plt.show()
# Example usage:
radius = 10
center_x = 50
center_y = 50

midpoint_circle_algorithm(radius, center_x, center_y)


4. Write a program to draw Bezier curve.
import numpy as np
import matplotlib.pyplot as plt
def bezier_curve(control_points, t):
Calculates a point on a Bézier curve for a given parameter t.

Args:
control_points: A list of control points.
t: A parameter between 0 and 1.
Returns:
A point on the curve.
n = len(control_points) - 1
point = np.zeros(2)
for i in range(n + 1):
coefficient = np.math.factorial(n) / (np.math.factorial(i) *
np.math.factorial(n - i))
point += coefficient * t**i * (1 - t)**(n - i) * control_points[i]
return point

def draw_bezier_curve(control_points, num_points=100):

Draws a Bézier curve.

Args:
control_points: A list of control points.
num_points: The number of points to calculate on the curve.

t_values = np.linspace(0, 1, num_points)


curve_points = [bezier_curve(control_points, t) for t in t_values]
x_coords, y_coords = zip(*curve_points)

plt.plot(x_coords, y_coords)
plt.scatter(*zip(*control_points), color='red')
plt.axis('equal')
plt.show()

# Example usage:
control_points = [(10, 10), (30, 50), (70, 50), (90, 10)]
draw_bezier_curve(control_points)
5. Program to rotate a rectangle about its midpoint.
import numpy as np
import matplotlib.pyplot as plt
def rotate_rectangle(rect, angle):
Rotates a rectangle around its midpoint.
Args:
rect: A list of four points representing the corners of the
rectangle.
angle: The angle of rotation in radians.

Returns:
A list of four points representing the rotated rectangle.
# Find the midpoint of the rectangle
midpoint = np.mean(rect, axis=0)

# Translate the rectangle to the origin


translated_rect = rect - midpoint

# Rotation matrix
rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])

# Rotate the rectangle


rotated_rect = np.dot(translated_rect, rotation_matrix)

# Translate the rectangle back


rotated_rect += midpoint

return rotated_rect

# Example usage:
rectangle = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
angle = np.pi / 4 # 45 degrees

rotated_rect = rotate_rectangle(rectangle, angle)


# Plot the original and rotated rectangles
plt.plot(*zip(*rectangle), 'b-')
plt.plot(*zip(*rotated_rect), 'r-')
plt.axis('equal')
plt.grid(True)
plt.show()
6. Program to clip a line using Liang Barsky Method.
def liang_barsky_clip(x1, y1, x2, y2, xmin, ymin, xmax, ymax):
Clips a line segment using the Liang-Barsky algorithm.
Args:
x1, y1: Coordinates of the first endpoint of the line segment.
x2, y2: Coordinates of the second endpoint of the line segment.
xmin, ymin: Coordinates of the lower-left corner of the clipping window.
xmax, ymax: Coordinates of the upper-right corner of the clipping window.
Returns:
A tuple of two points representing the clipped line segment, or None if the line is
completely outside the clipping window.
dx = x2 - x1
dy = y2 - y1
p = [-dx, dx, -dy, dy]
q = [x1 - xmin, xmax - x1, y1 - ymin, ymax - y1]
u1 = 0
u2 = 1
for i in range(4):
if p[i] == 0:
if q[i] < 0:
return None # Line is outside the clipping window
else:
t = q[i] / p[i]
if p[i] < 0:
u1 = max(u1, t)
else:
u2 = min(u2, t)
if u1 > u2:
return None # Line is outside the clipping window
x1_new = x1 + u1 * dx
y1_new = y1 + u1 * dy
x2_new = x1 + u2 * dx
y2_new = y1 + u2 * dy
return (x1_new, y1_new), (x2_new, y2_new)
# Example usage:
x1, y1 = 10, 10
x2, y2 = 50, 50
xmin, ymin = 20, 20
xmax, ymax = 40, 40
clipped_line = liang_barsky_clip(x1, y1, x2, y2, xmin, ymin, xmax, ymax)
if clipped_line:
print("Clipped line endpoints:", clipped_line)
else:
print("Line is completely outside the clipping window.")
7. Program to implement Standard Perspective
Projection in 3- Dimensions.
import numpy as np
import matplotlib.pyplot as plt

def perspective_projection(points, d):


Performs perspective projection on a set of 3D points.
Args:
points: A numpy array of shape (n, 3) representing the 3D points.
d: The distance between the camera and the projection plane.
Returns:
A numpy array of shape (n, 2) representing the 2D projected
points.
projected_points = []
for point in points:
x, y, z = point
x_proj = x * d / (d + z)
y_proj = y * d / (d + z)
projected_points.append([x_proj, y_proj])

return np.array(projected_points)
# Example usage:
points = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
d=5

projected_points = perspective_projection(points, d)
# Plot the 3D points and their 2D projections
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:, 0], points[:, 1], points[:, 2])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')

plt.figure()
plt.scatter(projected_points[:, 0], projected_points[:, 1])
plt.xlabel('X')
plt.ylabel('Y')
plt.axis('equal')
plt.show()
8. Program to implement Parallel Projection in 3-
Dimensions
import numpy as np
import matplotlib.pyplot as plt

def parallel_projection(points):
Performs parallel projection on a set of 3D points.

Args:
points: A numpy array of shape (n, 3) representing the 3D
points.

Returns:
A numpy array of shape (n, 2) representing the 2D
projected points.
projected_points = points[:, :2]
return projected_points
# Example usage:
points = np.array([[1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4]])
projected_points = parallel_projection(points)

# Plot the 3D points and their 2D projections


fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(points[:, 0], points[:, 1], points[:, 2])
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax_set_zlabel('Z')

plt.figure()
plt.scatter(projected_points[:, 0], projected_points[:, 1])
plt.xlabel('X')
plt.ylabel('Y')
plt.axis('equal')
plt.show()
9. Write a Program to implement Digital Clock.

import time
import tkinter as tk

def update_time():
"""Updates the time label on the GUI."""
current_time = time.strftime("%H:%M:%S")
time_label.config(text=current_time)
time_label.after(1000, update_time) # Update every 1
second

# Create the main window


window = tk.Tk()
window.title("Digital Clock")

# Create a label to display the time


time_label = tk.Label(window, font=("Arial", 48),
fg="black", bg="white")
time_label.pack(pady=20)

# Start the time update


update_time()

window.mainloop()
10. Write a Program to draw animation using
increasing circles filled with different colors and
patterns.
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

def update_plot(num, circles, ax):


Updates the plot for each frame of the animation.

Args:
num: The current frame number.
circles: A list of circle patches.
ax: The axes object.
for i, circle in enumerate(circles):
circle.set_radius(num + i * 5)
circle.set_facecolor(plt.cm.viridis(i / len(circles)))
circle.set_hatch(hatch_patterns[i % len(hatch_patterns)])

ax.set_title(f"Frame {num}")
# Define hatch patterns
hatch_patterns = ['/', '\\', '|', '-', '+', 'x', 'o', 'O', '.', '*']

# Create a figure and axis


fig, ax = plt.subplots()
ax.set_xlim(-100, 100)
ax.set_ylim(-100, 100)

# Create a list of circle patches


circles = []
for i in range(5):
circle = plt.Circle((0, 0), radius=i * 5, fill=False, edgecolor='black',
linewidth=2)
circles.append(circle)
ax.add_patch(circle)

# Create the animation


ani = animation.FuncAnimation(fig, update_plot, frames=50,
fargs=(circles, ax), interval=100)

plt.show()
11. Write a Program control a ball using arrow
keys.
import pygame
pygame.init()

# Screen dimensions
screen_width = 800
screen_height = 600

# Create the screen


screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Ball Game")

# Ball properties
ball_radius = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_x = 0
ball_speed_y = 0

# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Handle key presses
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
ball_speed_x = -5
elif event.key == pygame.K_RIGHT:
ball_speed_x = 5
elif event.key == pygame.K_UP:
ball_speed_y = -5
elif event.key == pygame.K_DOWN:
ball_speed_y = 5

if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key ==
pygame.K_RIGHT:
ball_speed_x = 0
elif event.key == pygame.K_UP or event.key ==
pygame.K_DOWN:
ball_speed_y = 0

# Update ball position


ball_x += ball_speed_x
ball_y += ball_speed_y

# Keep ball within screen boundaries


if ball_x < ball_radius:
ball_x = ball_radius
elif ball_x > screen_width - ball_radius:
ball_x = screen_width - ball_radius
if ball_y < ball_radius:
ball_y = ball_radius
elif ball_y > screen_height - ball_radius:
ball_y = screen_height - ball_radius

# Fill the screen with black


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

# Draw the ball


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

pygame.display.update()

pygame.quit()
12 . Write a Program to implement Bouncing Ball in vertical
direction.
import pygame
pygame.init()

# Screen dimensions
screen_width = 800
screen_height = 600
# Create the screen
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("Bouncing Ball")

# Ball properties
ball_radius = 20
ball_x = screen_width // 2
ball_y = screen_height // 2
ball_speed_y = 5
gravity = 0.2

# Game loop
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
# Update ball position
ball_y += ball_speed_y
ball_speed_y += gravity

# Bounce off the floor


if ball_y + ball_radius >= screen_height:
ball_y = screen_height - ball_radius
ball_speed_y *= -1
# Fill the screen with black
screen.fill((0, 0, 0))

# Draw the ball


pygame.draw.circle(screen, (255, 255, 255), (ball_x, ball_y),
ball_radius)
pygame.display.update()
pygame.quit()

You might also like