Computer graphics program to rotate a triangle

0
4279

Computer graphics program in Python graphics.py and c++ graphics.

Python

from graphics import *
from random import randint
from math import sin, cos, radians
import time
 
def rotateTriangle(triangle, degrees):
   angle = radians(degrees)
   cosang, sinang = cos(angle), sin(angle)
 
   points = triangle.getPoints()
   n = len(points)
   cx = sum(p.getX() for p in points) / n
   cy = sum(p.getY() for p in points) / n
 
   new_points = []
   for p in points:
       x, y = p.getX(), p.getY()
       tx, ty = x-cx, y-cy
       new_x = ( tx*cosang + ty*sinang) + cx
       new_y = (-tx*sinang + ty*cosang) + cy
       new_points.append(Point(new_x, new_y))
 
   rotated_ploygon = triangle.clone()
   rotated_ploygon.points = new_points
   return rotated_ploygon
 
 
win = GraphWin('Rotate Triangle', 600, 600)
 
print("Point 1")
x1=int(input("Enter x:"))
y1=int(input("Enter y:"))
 
print("Point 2")
x2=int(input("Enter x:"))
y2=int(input("Enter y:"))
print("Point 3")
x3=int(input("Enter x:"))
y3=int(input("Enter y:"))
p1 = Point(x1,y1)
p2 = Point(x2,y2)
p3 = Point(x3, y3)
triangle = Polygon(p1,p2,p3)
triangle.setFill('cyan')
triangle.draw(win)
angle=int(input("Enter the angle of rotation"))
triangle = rotateTriangle(triangle,angle)
triangle.setFill('blue')
triangle.draw(win)
Computer graphics program to rotate a triangle

C++

#include<bits/stdc++.h>
#include<graphics.h>
#include<conio.h>
using namespace std;
 
int main(){ 
    int gd=0,gm = DETECT,x1,y1,x2,y2,x3,y3;  
    x1 = 200, y1 = 200, x2 = 100, y2 = 200, x3 = 200, y3 = 100;
 
    double s,c, angle;  
    initgraph(&gd, &gm, "");  
    // printf("Enter coordinates of triangle: ");  
    // scanf("%d%d%d%d%d%d",&x1,&y1,&x2,&y2, &x3, &y3);  
    
    line(x1,y1,x2,y2);  
    line(x2,y2, x3,y3);  
    line(x3, y3, x1, y1);  
 
    printf("Enter rotation angle: ");  
    scanf("%lf", &angle);  
 
    cout << " Enter Pivot ";
    int xpiv, ypiv;
    cin >> xpiv >> ypiv;
 
    x1 -= xpiv;
    x2 -= xpiv;
    x3 -= xpiv;
 
    y1 -= ypiv;
    y2 -= ypiv;
    y3 -= ypiv;
 
 
    c = cos(angle * M_PI/180);  
    s = sin(angle * M_PI/180);  
    x1 =  xpiv + floor(x1 * c + y1 * s);  
    y1 = ypiv + floor(-x1 * s + y1 * c);  
    x2 =  xpiv + floor(x2 * c + y2 * s);  
    y2 = ypiv + floor(-x2 * s + y2 * c);  
    x3 = xpiv +  floor(x3 * c + y3 * s);  
    y3 = ypiv + floor(-x3 * s + y3 * c);  
    cleardevice();  
    line(x1, y1 ,x2, y2);  
    line(x2,y2, x3,y3);  
    line(x3, y3, x1, y1);  
    getch();  
    closegraph();  
    return 0;  
}

Before Rotation 

Computer graphics program to rotate a triangle

After rotation

 

Computer graphics program to rotate a triangle

LEAVE A REPLY