# bezier1.py

Created by ews31415

Created on May 02, 2021

1.95 KB

The script bezier1 plots a Bezier curve of degree 1, 2, or 3 in one of four colors: black (0), red (1), green (2), and blue (3). The script uses the ion module, which allows input directly from the keyboard.

Edward Shore 5/2/2021

```# Bezier Curve
# 2021-05-02 EWS

from ion import *
from math import *
from matplotlib.pyplot import *

# functions

# key press
def key():
while True:
if keydown(KEY_ONE):
return 1
if keydown(KEY_TWO):
return 2
if keydown(KEY_THREE):
return 3

# linear plot
def linbez(x0,y0,x1,y1):
xlist=[x0]
ylist=[y0]
t=0
while t<1:
t+=0.05
xlist.append(x0*(1-t)+x1*t)
ylist.append(y0*(1-t)+y1*t)
return [xlist,ylist]

xlist=[x0]
ylist=[y0]
t=0
while t<1:
t+=0.05
x=x0*(1-t)**2+2*x1*t*(1-t)+x2*t**2
y=y0*(1-t)**2+2*y1*t*(1-t)+y2*t**2
xlist.append(x)
ylist.append(y)
return [xlist,ylist]

# cubic plot
def cubbez(x0,y0,x1,y1,x2,y2,x3,y3):
xlist=[x0]
ylist=[y0]
t=0
while t<1:
t+=0.05
x=x0*(1-t)**3+3*x1*t*(1-t)**2+3*x2*t**2*(1-t)+x3*t**3
y=y0*(1-t)**3+3*y1*t*(1-t)**2+3*y2*t**2*(1-t)+y3*t**3
xlist.append(x)
ylist.append(y)
return [xlist,ylist]

# color selection
def colsel():
print("Choose a color:")
print("0: black, 1: red \n2: green, 3: blue")
while True:
if keydown(KEY_ZERO):
return 'black'
if keydown(KEY_ONE):
return 'red'
if keydown(KEY_TWO):
return 'green'
if keydown(KEY_THREE):
return 'blue'

# main program
print("Bezier Curve Plot")
print("Order? Press 1, 2, or 3.")
n=key()
x0=float(input("x0? "))
y0=float(input("y0? "))
x1=float(input("x1? "))
y1=float(input("y1? "))
if n==1:
clist=linbez(x0,y0,x1,y1)
if n>1:
x2=float(input("x2? "))
y2=float(input("y2? "))
if n==2:
if n==3:
x3=float(input("x3? "))
y3=float(input("y3? "))
clist=cubbez(x0,y0,x1,y1,x2,y2,x3,y3)
# color section
ch=colsel()
# plotting
xlist=clist[0]
ylist=clist[1]
xa=min(xlist)-1.5
xb=max(xlist)+1.5
ya=min(ylist)-1.5
yb=max(ylist)+1.5
# set axis and turn it on
axis((xa,xb,ya,yb))
axis("on")
# plot the curve
plot(xlist,ylist,color=ch)
show()```