Ilovepdf Merged
Ilovepdf Merged
Semester-5
Practical on :
Computer Graphics
BCA-501/M1T
Submitted By
Student Name :- - - - - - - - - - - - - -
Enrollment No. :- - - - - - - - - - - - - -
# 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))
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
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
Args:
control_points: A list of control points.
num_points: The number of points to calculate on the curve.
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)
# Rotation matrix
rotation_matrix = np.array([[np.cos(angle), -np.sin(angle)],
[np.sin(angle), np.cos(angle)]])
return rotated_rect
# Example usage:
rectangle = np.array([[0, 0], [1, 0], [1, 1], [0, 1]])
angle = np.pi / 4 # 45 degrees
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)
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
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
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', '.', '*']
plt.show()
11. Write a Program control a ball using arrow
keys.
import pygame
pygame.init()
# Screen dimensions
screen_width = 800
screen_height = 600
# 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
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