Coding Projects
Shapes
Creates random vector art with Python and turtle graphics. Calculates and prints the total area of all shapes when done.
'''
Steven Wiltse, 100 CSC 115, 10/14/2018
Program 6, filename: Shapes
Description: Prints 15 random shapes using turtle graphics and basic class inheritance.
Prints total area of all shapes at the end of the program.
'''
import random
from turtle import Turtle
class Shape(): #asigns the turtle object to the Shape class.
turtle = Turtle()
class Circle(Shape): #Passes the turtle object to the Circle class.
def __init__(self, center, radius):
self.center = center
self.radius = radius
def get_area(self):
return 3.14* self.radius*self.radius
def draw(self):
Shape.turtle.penup()
Shape.turtle.setposition(self.center[0], self.center[1]-self.radius)
Shape.turtle.pendown()
Shape.turtle.circle(self.radius)
Shape.turtle.penup()
class Rectangle(Shape): #Passes the turtle object to the Rectangle class.
def __init__(self,upper_left, lower_right):
self.upper_left = upper_left
self.lower_right = lower_right
def get_area(self):
length = Shape.turtle.distance(self.upper_left,(self.lower_right[0], self.upper_left[1])) #Uses the distance method in the turtle
width = Shape.turtle.distance((self.lower_right[0], self.upper_left[1]),self.lower_right) #class to find the length and width.
area = length * width
return area
def draw(self):
Shape.turtle.penup()
Shape.turtle.setposition(self.upper_left) # Upper left.
Shape.turtle.pendown()
Shape.turtle.setposition(self.lower_right[0], self.upper_left[1]) # Upper right.
Shape.turtle.setposition(self.lower_right) #Lower right.
Shape.turtle.setposition(self.upper_left[0], self.lower_right[1]) # Lower right.
Shape.turtle.setposition(self.upper_left) #Returns to start. Finishes rectangle.
Shape.turtle.penup()
class RightTriangle(Shape):
def __init__(self, pointA, pointB):
self.pointA = pointA
self.pointB = pointB
def get_area(self):
length = Shape.turtle.distance(self.pointA,(self.pointB[0], self.pointA[1]))
width = Shape.turtle.distance((self.pointB[0], self.pointA[1]),self.pointB)
area = (length * width)/2
return area
def draw(self):
Shape.turtle.penup()
Shape.turtle.setposition(self.pointA)
Shape.turtle.pendown()
Shape.turtle.setposition(self.pointB) # Point A to B forms the hypotenuse.
Shape.turtle.setposition(self.pointA[0],self.pointB[1])
Shape.turtle.setposition(self.pointA)
Shape.turtle.penup()
def random_shapes(count):
def random_point():
return (random.randint(-200,200), random.randint(-200,200)) # Picks a random x and y coordinate.
shapes = [] # Stores random shapes to be used in the main function.
for i in range(1, count+1):
shape_type = random.randint(1,3) # Used to choose 1 of the 3 random shape.
if shape_type == 1:
shapes += [Circle(random_point(), random.randint(1,200))]
elif shape_type == 2:
shapes += [Rectangle(random_point(), random_point())]
else:
shapes += [RightTriangle(random_point(), random_point())]
return shapes
def main():
shapes = random_shapes(15)
total_area = 0 # Total area of all shapes
for s in shapes:
s.draw () # calls draw method from each object.
total_area += s.get_area()
input("Hit enter key to end.")
print("Total area = ", total_area)
input("Good bye!")
main()
Television
OOP using Java classes and objects to make a television.
// The purpose of this class is to model a television
// Steven Wiltse 02/24/19
public class Television {
//The brand of TV for an object. Can't be changed once initialized.
private final String MANUFACTURER;
//The size of the TV screen for an object. Can't be changed once initialized.
private final int SCREEN_SIZE;
private boolean powerOn;//Changes the power on and off for an object.
//Holds the value for the current channel an object is on.
private int channel;
private int volume;//Holds the value for the current volume of an object.
//Takes in manufacturer and screen size parameters and uses them to create
//a new Television object.
Television(String newManufacturer, int newScreen){
MANUFACTURER = newManufacturer;
SCREEN_SIZE = newScreen;
powerOn = false;
channel = 2;
volume = 20;
}
//Returns the current volume of a Television object.
public int getVolume(){
return volume;
}
//Returns the current channel of a Television object.
public int getChannel() {
return channel;
}
//Returns the manufacturer of a Television object.
public String getManufacturer() {
return MANUFACTURER;
}
//Returns the screen size of a Television object.
public int getScreenSize() {
return SCREEN_SIZE;
}
//Sets the channel of a Television object to the specified integer.
public void setChannel(int newChannel) {
channel = newChannel;
}
//Changes the boolean value of the powerOn data field to the opposite of what
//it is for a Television object.
public void power() {
powerOn = !powerOn;
}
//Increments the current volume of a Television object by 1.
public void increaseVolume() {
volume++;
}
//Decrements the current volume of a Television object by 1.
public void decreaseVolume() {
volume--;
}
}
// This class demonstrates the Television class
// Amitava Karmaker
// Modified by YOUR NAME HERE, TODAY'S DATE HERE
// INDICATE WHAT YOU ADDED/MODIFIED
import java.util.Scanner;
public class TelevisionDemo
{
public static void main(String[] args)
{
//create a Scanner object to read from the keyboard
Scanner keyboard = new Scanner (System.in);
//declare variables
int station; //the user’s channel choice
//declare and instantiate a television object
Television bigScreen = new Television("Toshiba", 55);
//turn the power on
bigScreen.power();
//display the state of the television
System.out.println("A " + bigScreen.getScreenSize() +
bigScreen.getManufacturer() + " has been turned on.");
//prompt the user for input and store into station
System.out.print("What channel do you want? ");
station = keyboard.nextInt();
//change the channel on the television
bigScreen.setChannel(station);
//increase the volume of the television
bigScreen.increaseVolume();
//display the the current channel and volume of the television
System.out.println("Channel: " + bigScreen.getChannel() +
" Volume: " + bigScreen.getVolume());
System.out.println("Too loud!! I am lowering the volume.");
//decrease the volume of the television
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
bigScreen.decreaseVolume();
//display the current channel and volume of the television
System.out.println("Channel: " + bigScreen.getChannel() +
" Volume: " + bigScreen.getVolume());
System.out.println(); //for a blank line
//HERE IS WHERE YOU DO TASK #5
}
}
SSN Validator
Validates social sercurity numbers with Java using exception handling.
/* Steven Wiltse
* 100 CSC 222 Intro to Java
* 03/02/2019
*/
//A custom exception class for invalid social security numbers.
public class SocSecException extends Exception {
public SocSecException(String ssn) {
super("Invalid social security number, " + ssn);
}
}
/*
* Steven Wiltse
* 100 CSC 222 Intro to Java
* 03/02/2019
*/
/*
* Driver program to test SocSecException class. Enter name and SSN returns and
* valid message if okay. Prints error message if thrown SocSecException.
*/
import java.util.Scanner;
public class SocSecProcessor {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
// Main block for program. Runs on loop until user selects n.
String loopCheck = "y";// Ends loop if user selects n.
while (!loopCheck.equals("n")) {
System.out.print("Name? ");
String name = input.nextLine();
System.out.print("SSN? ");
String ssn = input.nextLine();
// Checks for SocSecException.
try {
if (isValid(ssn))
System.out.println(name + " " + ssn + " is valid");
} catch (SocSecException ex) {
System.out.println(ex.getMessage());
}
System.out.print("Continue? ");// Checks if user wants to continue.
loopCheck = input.nextLine().toLowerCase();
}
}
// Method checks the length, dash locations, and that there are only
// digits for the SSN.
public static boolean isValid(String num) throws SocSecException {
boolean valid = true;
boolean dashCheck = true;
boolean onlyDigits = true;
// Block checks if SSN is right length. Done first to not cause errors
// when checking the 3rd and 6th elements for dashCheck if it is too short.
if (num.length() != 11) {
valid = false;
throw new SocSecException("wrong number of characters");
}
// Block checks that dashes are in the right place.
// Checks that the first dash is in the right place.
if (num.charAt(3) != '-') {
dashCheck = false;
// Checks that the second dash is in the right place.
} else if (num.charAt(6) != '-') {
dashCheck = false;
// Checks there are no extra dashes.
} else {
for (int count = 0; count < num.length(); count++) {
if (num.charAt(count) == '-' && (count != 3 && count != 6))
dashCheck = false;
}
}
// Block checks that only digits are used for the SSN.
for (int count = 0; count < num.length(); count++) {
if (num.charAt(count) != '-' && !Character.isDigit(num.charAt(count)))
onlyDigits = false;
}
// Block throws error if SSN did not pass dashCheck and onlyDigits.
// return valid otherwise.
if (!dashCheck) {
valid = false;
throw new SocSecException("dashes at wrong positions");
} else if (!onlyDigits) {
valid = false;
throw new SocSecException("contains a character that is not a digit");
} else
return valid;
}
}
jQeury Calculator
Basic HTML calculator using Javascript and jQeury.
<!--
index.html (Calculator using HTML, CSS, and jQuery)
Steven Wiltse, Wiltses@csp.edu, L00417968100 CSC 135 Modern Web Design, Project Week 5
04/11/2019
Updated
04/13/2019
04/14/2019
-->
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta charset="UTF-8">
<title>Project 5</title>
<style>
form {
width: 210px;
background-color: darkslategray;
border-radius: 20px;
margin: auto;
text-align: center;
padding-bottom: 10px;
padding-top: 5px;
}
#display {
margin: auto;
height: 25px;
background-color: blanchedalmond;
display: block;
border-radius: 5px;
margin-bottom: 15px;
font-weight: bold;
}
h3 {
color: white;
}
input {
background-color: darkgrey;
}
input[type="button"] {
width: 40px;
height: 35px;
border-radius: 10px;
margin: 1px;
font-weight: bold;
}
.memory {
background-color: darkorchid;
}
.operator {
background-color: darkorange;
}
.clear {
background-color: red;
}
.equal {
background-color: green;
}
</style>
</head>
<body>
<form>
<h3>Calculator</h3>
<input type="text" id="display" value="" readonly>
<input type="button" value="mrc" class="memory">
<input type="button" value="m+" class="memory">
<input type="button" value="m-" class="memory">
<input type="button" value="/" class="operator">
<input type="button" value="7">
<input type="button" value="8">
<input type="button" value="9">
<input type="button" value="*" class="operator">
<input type="button" value="4">
<input type="button" value="5">
<input type="button" value="6">
<input type="button" value="+" class="operator">
<input type="button" value="1">
<input type="button" value="2">
<input type="button" value="3">
<input type="button" value="-" class="operator">
<input type="button" value="0">
<input type="button" value=".">
<input type="button" value="C" class="clear">
<input type="button" value="=" class="equal">
</form>
<script>
$(document).ready(function(){
$(':button').not('.equal').click(function(){
$('#display').attr('value', $('#display').attr('value') + $(this).attr('value'));
})
$('.equal').click(function(){
$('#display').attr('value', eval($('#display').val()));
})
$('.clear').click(function(){
$('#display').attr('value','');
})
})
</script>
</body>
</html>