diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..412eeda --- /dev/null +++ b/.gitattributes @@ -0,0 +1,22 @@ +# Auto detect text files and perform LF normalization +* text=auto + +# Custom for Visual Studio +*.cs diff=csharp +*.sln merge=union +*.csproj merge=union +*.vbproj merge=union +*.fsproj merge=union +*.dbproj merge=union + +# Standard to msysgit +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b9d6bd9 --- /dev/null +++ b/.gitignore @@ -0,0 +1,215 @@ +################# +## Eclipse +################# + +*.pydevproject +.project +.metadata +bin/ +tmp/ +*.tmp +*.bak +*.swp +*~.nib +local.properties +.classpath +.settings/ +.loadpath + +# External tool builders +.externalToolBuilders/ + +# Locally stored "Eclipse launch configurations" +*.launch + +# CDT-specific +.cproject + +# PDT-specific +.buildpath + + +################# +## Visual Studio +################# + +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. + +# User-specific files +*.suo +*.user +*.sln.docstates + +# Build results + +[Dd]ebug/ +[Rr]elease/ +x64/ +build/ +[Bb]in/ +[Oo]bj/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +*_i.c +*_p.c +*.ilk +*.meta +*.obj +*.pch +*.pdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.log +*.scc + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opensdf +*.sdf +*.cachefile + +# Visual Studio profiler +*.psess +*.vsp +*.vspx + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# NCrunch +*.ncrunch* +.*crunch*.local.xml + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.Publish.xml +*.pubxml + +# NuGet Packages Directory +## TODO: If you have NuGet Package Restore enabled, uncomment the next line +#packages/ + +# Windows Azure Build Output +csx +*.build.csdef + +# Windows Store app package directory +AppPackages/ + +# Others +sql/ +*.Cache +ClientBin/ +[Ss]tyle[Cc]op.* +~$* +*~ +*.dbmdl +*.[Pp]ublish.xml +*.pfx +*.publishsettings + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file to a newer +# Visual Studio version. Backup files are not needed, because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm + +# SQL Server files +App_Data/*.mdf +App_Data/*.ldf + +############# +## Windows detritus +############# + +# Windows image file caches +Thumbs.db +ehthumbs.db + +# Folder config file +Desktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Mac crap +.DS_Store + + +############# +## Python +############# + +*.py[co] + +# Packages +*.egg +*.egg-info +dist/ +build/ +eggs/ +parts/ +var/ +sdist/ +develop-eggs/ +.installed.cfg + +# Installer logs +pip-log.txt + +# Unit test / coverage reports +.coverage +.tox + +#Translations +*.mo + +#Mr Developer +.mr.developer.cfg diff --git a/Assignment 1/src/HeatIndexCalculator.java b/Assignment 1/src/HeatIndexCalculator.java new file mode 100644 index 0000000..cf11e4d --- /dev/null +++ b/Assignment 1/src/HeatIndexCalculator.java @@ -0,0 +1,58 @@ +/* ********************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Assignment title: Program 1: Creating A Java Application From A UML Diagram + * Date: January 30, 2013 + * ********************** */ + +import java.util.Scanner; + +public class HeatIndexCalculator { + + private int temperature; + private double humidity, heatIndex; + + public static void main(String[] args) { + // Create a new HeatIndexCalculator object and a Scanner object + HeatIndexCalculator h = new HeatIndexCalculator(); + Scanner input = new Scanner(System.in); + + // Ask for inputs and store results + System.out.println("Please enter the current temperature in degrees Fahrenheit:"); + h.temperature = input.nextInt(); + System.out.println("Please enter the current humidity as a percentage:"); + h.humidity = input.nextDouble(); + + // We're done asking for inputs, so close the scanner + input.close(); + + // Calculate the heat index and store it in heatIndex + h.heatIndex = calculateHeatIndex(h.temperature, h.humidity); + + // Finally, print the results + printHeatIndex(h.temperature, h.humidity, h.heatIndex); + } + + private static double calculateHeatIndex(int currentTemp, double currentHumidity) { + // Initialize an array of constants for ease of calculation + final double[] c = {-42.379, 2.04901523, 10.14333127, -0.22475541, -.00683783, -.05481717, .00122874, .00085282, -.00000199}; + + // Perform the calculation + double calculation = c[0]+c[1]*currentTemp + c[2]*currentHumidity+c[3]*currentTemp*currentHumidity + c[4]*currentTemp*currentTemp + + c[5]*currentHumidity*currentHumidity +c[6]*currentTemp*currentTemp*currentHumidity + + c[7]*currentTemp*currentHumidity*currentHumidity + c[8]*currentTemp*currentTemp*currentHumidity*currentHumidity; + + // Return the resulting number + return calculation; + + + } + + private static void printHeatIndex(int currentTemp, double currentHumidity, double calculatedHeatIndex) { + // Print the final output + System.out.println("At a temperature of "+currentTemp+"F and a humidity of "+currentHumidity+" percent . . ."); + // Use printf instead of println to make formatting the number to two decimal places simpler. + System.out.printf("It actually feels like: %.2fF\n", calculatedHeatIndex); + } + +} diff --git a/Assignment 1/src/test.java b/Assignment 1/src/test.java new file mode 100644 index 0000000..ace388d --- /dev/null +++ b/Assignment 1/src/test.java @@ -0,0 +1,16 @@ + +public class test { + + public static void main(String[] args) { + int total; + System.out.println("start"); + total = 2; + if(total = 1) + System.out.println("What!"); + + System.out.println(total); + System.out.println("done"); + + } + +} diff --git a/Assignment 2/src/TaxCalculator.java b/Assignment 2/src/TaxCalculator.java new file mode 100644 index 0000000..241223c --- /dev/null +++ b/Assignment 2/src/TaxCalculator.java @@ -0,0 +1,93 @@ +/* ********************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 2: Computing Tax + * Date: February 6, 2013 + * ********************** */ + +import java.util.Scanner; + +public class TaxCalculator { + + // If the length of this rates array is changed, then the bracket arrays in findBracket() must also be changed + private final static int[] rates = {10, 15, 25, 28, 33, 35}; + + // Instance Variables + private int filingStatus, income; + private double tax; + private int[] taxBracket; + + public static void main(String[] args) { + + // Create a new TaxCalculator object and a Scanner object + TaxCalculator t = new TaxCalculator(); + Scanner input = new Scanner(System.in); + + // Ask for inputs and store results + System.out.printf("Enter the filing status: "); + t.filingStatus = input.nextInt(); + System.out.printf("Enter the taxable income: "); + t.income = input.nextInt(); + + // We're done asking for inputs, so close the scanner + input.close(); + + // Find the tax brackets based on filingStatus and fill the taxBrackets array with the correct dollar values + t.taxBracket = findBracket(t.filingStatus); + + //Calculate the tax + t.tax = calculateTax(t.income, t.taxBracket, rates); + + // Finally, print the results + System.out.printf("Tax is %.2f\n", t.tax); + } + + // Returns a reference to the proper tax bracket array + private static int[] findBracket(int filingStatus){ + // Setup the tax bracket values for each filing status based on the maximum dollar amount to fit in a bracket + // Set each as final, though they could be changed to be set as instance variables if this class was needed in a larger tax program with varying brackets. + final int[] single = {8350, 33950, 82250, 171550, 372950}; + final int[] joint = {16700, 67900, 137050, 208850, 372950}; + final int[] separately = {8350, 33950, 68525, 104425, 186475}; + final int[] headOfHousehold = {11950, 45500, 117450, 190200, 372950}; + + // Based on the passed variable filingStatus, return the correct array + if(filingStatus == 0) + return single; + if(filingStatus == 1) + return joint; + if(filingStatus == 2) + return separately; + if(filingStatus == 3) + return headOfHousehold; + + // If we have a filingStatus we don't know how to handle, warn the user and just resort to returning the single tax brackets + System.out.println("Warning: Unable to match filing status to a tax bracket. Please enter 0, 1, 2, or 3 next time. Assuming 0 (Single) for now."); + return single; + } + + // Calculates the amount of tax owed based on the given income, tax bracket maximums, and tax rates for those brackets. + private static double calculateTax(int income, int[] taxBrackets, int[] rates){ + double tax = 0; + int index = taxBrackets.length-1; // By using the array length, this function will scale to any size tax brackets, not just the 6 brackets we currently use + + // Loop through the calculation, taxing each part of the income by its respective bracket and then setting income to the next lowest bracket + while(index>=0){ + // This will move down a bracket each loop until the given income fits inside of a bracket. + if(income>taxBrackets[index]){ + // Calculate income tax for this bracket only + tax += (income-taxBrackets[index])*(rates[index+1]/100.00); + // Set income to the next lowest bracket. + income = taxBrackets[index]; + } + index--; + } + + // Include the final base tax bracket not calculated in the loop that also would handle an instance of having a flat tax. + tax += income*(rates[0]/100.00); + + // Return the amount of tax owed + return tax; + } + +} \ No newline at end of file diff --git a/Assignment 3/src/Deck.java b/Assignment 3/src/Deck.java new file mode 100644 index 0000000..539b6d6 --- /dev/null +++ b/Assignment 3/src/Deck.java @@ -0,0 +1,67 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 3: Cards - Deck Handler + * Date: March 1, 2013 + * **************************************** */ + +import java.util.Random; + +public class Deck { + + private static final int NUM_CARDS = 52; + private static final Random randomNumbers = new Random(); + private int[] deck; + + // the index of the current position in the deck + private int cardIndex = 0; + + // Creates a new shuffled deck of cards + public Deck() { + // Initialize a new deck of cards + deck = new int[NUM_CARDS]; + + // Populate the deck in order + for(int i = 0; i < deck.length; i++) + deck[i] = i; + + // Shuffle the deck + int temp, swapIndex; + for(int i = 0; i < deck.length; i++){ + // Select a random index from 0 to NUM_CARDS-1 + swapIndex = randomNumbers.nextInt(NUM_CARDS); + + // Swap the numbers + temp = deck[i]; + deck[i] = deck[swapIndex]; + deck[swapIndex] = temp; + } + } + + /** + * + * @return Returns the int representation of the current card and increments cardIndex. + * If there are no more cards to be dealt, this returns -1 + */ + public int dealCard(){ + if(cardIndex < deck.length) + return deck[cardIndex++]; + else + return -1; + } + + /** + * @param card + * The int representation of a card to be named. + * @return + * The the spoken name of the given card, e.g. 0 would return "Two of Clubs" + */ + public String cardName(int card){ + // Names are in ranked order from least-value to greatest. + String[] name = {"Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King", "Ace"}; + String[] suit = {"Clubs", "Spades", "Diamonds", "Hearts"}; + + + return name[card%13]+" of "+suit[card/13]; + } +} diff --git a/Assignment 3/src/Game.java b/Assignment 3/src/Game.java new file mode 100644 index 0000000..a64ab35 --- /dev/null +++ b/Assignment 3/src/Game.java @@ -0,0 +1,128 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 3: Cards - Game Playing Class + * Date: March 1, 2013 + * **************************************** */ + +public class Game { + + private static Hand[] hands; + private static Deck deck; + + // Game constants + private static final int CARDS_PER_HAND = 5; + private static final int NUM_HANDS = 2; // NOTE: This game can only handle up 10 5-card hands because Deck is limited to 52 cards + + public static void main(String[] args) { + // First, create a new Deck object + deck = new Deck(); + + // Then create the hands by creating an array of Hand objects + hands = new Hand[NUM_HANDS]; + + // Next, initialize the cards array in each hand and then deal out cards + for (int i=0; i winningRank){ + winningRank = rank; + winningHand = i; + winningHighPair = highPair; + winningHighCard = highCard; + tieFlag = false; + } + // If the ranks are equal, investigate further to determine the winner + else if(rank == winningRank){ + // If the highPair is higher, make it the new winner + if(highPair > winningHighPair){ + winningRank = rank; + winningHand = i; + winningHighPair = highPair; + winningHighCard = highCard; + tieFlag = false; + } + // Else if the highPairs are equal but the highCard is higher, make it the new winner + else if(highPair==winningHighPair && highCard > winningHighCard){ + winningRank = rank; + winningHand = i; + winningHighPair = highPair; + winningHighCard = highCard; + tieFlag = false; + } + // Otherwise, if the hands are exactly tied, flag it. + else if(highPair == winningHighPair && highCard == winningHighCard) + tieFlag = true; + } + } + + if(tieFlag){ + System.out.printf("There was a tie between Hands "); + // Loop through all the hands again, printing each hand that exactly matches the tied hand + for(int i=0; ihighestNumOfAKind){ + highestNumOfAKind = freq[i]; + highPair = i; + } + + // If highestNumOfAKind is 3, look for a pair for full house as well. No need to update highPair, since having one set of three means there can't be any other pairs of the same kind + if(highestNumOfAKind == 3) + for(int i=0; ihighPair) + highPair = i; + } + } + + /** + * + * @return Returns true if the cards are all royal cards + */ + private boolean isRoyal(){ + // Loop through each card, breaking if any card is not royal + for(int i=0; i 10){ + if(i == cards.length-1) + return true; + } + else break; + } + // If this didn't return during the for loop, the hand isn't royal + return false; + } + + /** + * + * @return Returns the rank of the hand + */ + public int getRank(){ + return handRank; + } + + /** + * + * @return Returns the number value of the highest card to be used as a comparison to break ties + */ + public int getHighCard(){ + return highCard; + } + + /** + * + * @return Returns the number value of the highest pair or triplet to be used as a comparison to break ties involving two pairs or full houses + */ + public int getHighPair(){ + return highPair; + } +} diff --git a/Assignment 4/src/TicTacToe.java b/Assignment 4/src/TicTacToe.java new file mode 100644 index 0000000..2da8968 --- /dev/null +++ b/Assignment 4/src/TicTacToe.java @@ -0,0 +1,211 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 4: Tic Tac Toe + * Date: March 24, 2013 + * **************************************** */ + +import java.util.Scanner; +import java.util.Random; + +public class TicTacToe { + + // constant to set the size of the board + private final int BOARD_SIZE = 3; + // number of empty spots remaining in the game + private int numMovesLeft = BOARD_SIZE*BOARD_SIZE; + // turn flag, FALSE for X and TRUE for O. + private boolean turn = false; + private boolean computerPlayer = false; + private Random randomNums; + private Scanner input; + // enumerator constants for each box in the board + private enum Box { + X, O, EMPTY + } + private Box[][] board = new Box[BOARD_SIZE][BOARD_SIZE]; + + public TicTacToe(){ + // Set the game to all empty spots when the game is created. + for(int i = 0; i=BOARD_SIZE || row<0 || column>=BOARD_SIZE || column<0){ + System.out.println("You are trying to place a marker out of bounds. Please enter a valid move."); + return false; + } + + // If the spot at row and column is empty, the move is valid + if(board[row][column] == Box.EMPTY) + return true; + else + System.out.println("There is already a marker there. Please enter a valid move"); + + // If we get here, then it by default isn't a valid move + return false; + } + + /** + * Checks to see if the game has been won, and if it has, prints out the winner. + * @return false if the game has not been won, true if it has been won. + */ + public boolean isWon(){ + // Check all of the winning possibilities. Currently only works for a 3x3 grid. Thanks MyProgrammingLab for saving my answer, so I didn't have to write this out again. + if( + (board[0][0] == board[0][1] && board[0][1] == board[0][2] && board[0][0] == board[0][2] && board[0][0] != Box.EMPTY) // Across Row 1 + || (board[1][0] == board[1][1] && board[1][1] == board[1][2] && board[1][0] == board[1][2] && board[1][0] != Box.EMPTY) // Across Row 2 + || (board[2][0] == board[2][1] && board[2][1] == board[2][2] && board[2][0] == board[2][2] && board[2][0] != Box.EMPTY) // Across Row 3 + + || (board[0][0] == board[1][0] && board[1][0] == board[2][0] && board[2][0] == board[0][0] && board[0][0] != Box.EMPTY) // Down Column 1 + || (board[0][1] == board[1][1] && board[1][1] == board[2][1] && board[2][1] == board[0][1] && board[0][1] != Box.EMPTY) // Down Column 2 + || (board[0][2] == board[1][2] && board[1][2] == board[2][2] && board[2][2] == board[0][2] && board[0][2] != Box.EMPTY) // Down Column 3 + + || (board[0][0] == board[1][1] && board[1][1] == board[2][2] && board[2][2] == board[0][0] && board[1][1] != Box.EMPTY) // Diagonal from 0,0 to 2,2 + || (board[0][2] == board[1][1] && board[1][1] == board[2][0] && board[2][0] == board[0][2] && board[1][1] != Box.EMPTY))// Diagonal from 0,2 to 2,0 + { + // The game has been won. Print out the board one final time. + printBoard(); + + // Print out the winner + System.out.print("That's three in a row! The winner is "); + + // Because the winning move was made last turn, the winner was the last person to move. Because turn is switched at the end of a turn, that makes X the winner if turn is true, otherwise it's O. + if(turn) + System.out.println("X!"); + else + System.out.println("O!"); + + // Now that the game is over, close the scanner + input.close(); + + return true; + } + + // Check if the game is a tie, as signaled by there being no moves left to make + if(numMovesLeft == 0){ + System.out.println("The game is a tie! Better luck next time!"); + return true; + } + + return false; + } + +} diff --git a/Assignment 4/src/TicTacToeTest.java b/Assignment 4/src/TicTacToeTest.java new file mode 100644 index 0000000..367d148 --- /dev/null +++ b/Assignment 4/src/TicTacToeTest.java @@ -0,0 +1,30 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 4: Tic Tac Toe + * Date: March 24, 2013 + * **************************************** */ + +public class TicTacToeTest { + + /** + * @param args + */ + public static void main(String[] args) { + // Create the game + TicTacToe game = new TicTacToe(); + + // Start the main game loop + do{ + // Print the board + game.printBoard(); + + // Start the next turn by asking for input so the player can take their turn + game.takeTurn(); + + // Check if that move ended the game, and assign winner to true to break the loop if the game has been won. + //winner = game.isWon(); + } + while(!game.isWon()); + } +} diff --git a/Assignment 5/comets.cfg b/Assignment 5/comets.cfg new file mode 100644 index 0000000..0a9d571 --- /dev/null +++ b/Assignment 5/comets.cfg @@ -0,0 +1,2 @@ +Large 20 20 1.2 -0.6 +Large 400 250 -0.2 0.7 \ No newline at end of file diff --git a/Assignment 5/src/comets/Comet.java b/Assignment 5/src/comets/Comet.java new file mode 100644 index 0000000..aefaddd --- /dev/null +++ b/Assignment 5/src/comets/Comet.java @@ -0,0 +1,30 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 5: Comets + * Class: Comet + * Date: April 19, 2013 + * **************************************** */ + +package comets; + +public abstract class Comet extends SpaceObject { + + /** + * Creates a new comet in the specified place, with the specified velocity and size + * @param xPos The location of the comet in the x direction + * @param yPos The location of the comet in the y direction + * @param xVel The velocity of the comet in the x direction + * @param yVel The velocity of the comet in the y direction + * @param radius The distance from the center of the comet to its outer edge + */ + public Comet(double xPos, double yPos, double xVel, double yVel, double radius){ + super(xPos, yPos, xVel, yVel, radius); + } + + /** + * This indicates to the comet that it has been shot and should break into pieces. + * @return A (possibly empty) vector of the comets spawned by the destruction of this comet, or null if the comet refuses to die yet + */ + public abstract java.util.Vector explode(); +} diff --git a/Assignment 5/src/comets/CometsMain.java b/Assignment 5/src/comets/CometsMain.java new file mode 100644 index 0000000..c292b5f --- /dev/null +++ b/Assignment 5/src/comets/CometsMain.java @@ -0,0 +1,421 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 5: Comets + * Class: CometsMain + * Date: April 19, 2013 + * **************************************** */ + +package comets; + +import java.awt.*; +import java.awt.event.*; + +import javax.swing.*; +import java.util.*; +import java.io.*; + +// This class is primarily responsible for organizing the game of Comets +public class CometsMain implements KeyListener +{ + // GUI Data + private JFrame frame; // The window itself + private Canvas playArea; // The area where the game takes place + + private final int playWidth = 500; // The width of the play area (in pixels) + private final int playHeight = 500; // The height of the play area (in pixels) + + // Game Data + private Ship ship; // The ship in play + private Vector shots; // The shots fired by the player + private Vector comets; // The comets floating around + + private boolean shipDead; // Whether or not the ship has been blown up + private long shipTimeOfDeath; // The time at which the ship blew up + + // Keyboard data + // Indicates whether the player is currently holding the accelerate, turn + // left, or turn right buttons, respectively + private boolean accelerateHeld = false; + private boolean turnLeftHeld = false; + private boolean turnRightHeld = false; + + // Indicates whether the player struck the fire key + private boolean firing = false; + + // Scoreboard Variables + private int shipDeaths = 0; + public static int numShots = 0; + + // Set up the game and play! + public CometsMain() + { + // Get everything set up + configureGUI(); + configureGameData(); + + // Display the window so play can begin + frame.setVisible(true); + + // Start the gameplay + playGame(); + } + + // Set up the initial positions of all space objects + private void configureGameData() + { + // Configure the play area size + SpaceObject.playfieldWidth = playWidth; + SpaceObject.playfieldHeight = playHeight; + + // Create the ship + ship = new Ship(playWidth/2, playHeight/2, 0, 0); + + // Create the shot vector (initially, there shouldn't be any shots on the screen) + shots = new Vector(); + + // Read the comets from comets.cfg + comets = new Vector(); + + try + { + Scanner fin = new Scanner(new File("comets.cfg")); + + // Loop through each line of the file to read a comet + while(fin.hasNext()) + { + String cometType = fin.next(); + double xpos = fin.nextDouble(); + double ypos = fin.nextDouble(); + double xvel = fin.nextDouble(); + double yvel = fin.nextDouble(); + + if(cometType.equals("Large")) + comets.add(new LargeComet(xpos, ypos, xvel, yvel)); + else if(cometType.equals("Medium")) + comets.add(new MediumComet(xpos, ypos, xvel, yvel)); + else + comets.add(new SmallComet(xpos, ypos, xvel, yvel)); + } + + // Close the scanner to prevent a memory leak + fin.close(); + } + // If the file could not be read correctly for whatever reason, abort + // the program + catch(FileNotFoundException e) + { + System.err.println("Unable to locate comets.cfg"); + System.exit(0); + } + catch(Exception e) + { + System.err.println("comets.cfg is not in a proper format"); + System.exit(0); + } + } + + // Set up the game window + private void configureGUI() + { + // Create the window object + frame = new JFrame("Comets"); + frame.setSize(playWidth+20, playHeight+35); + frame.setResizable(false); + + // The program should end when the window is closed + frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); + + // Set the window's layout manager + frame.setLayout(new FlowLayout()); + + // Create the play area + playArea = new Canvas(); + playArea.setSize(playWidth, playHeight); + playArea.setBackground(Color.BLACK); + playArea.setFocusable(false); + frame.add(playArea); + + // Make the frame listen to keystrokes + frame.addKeyListener(this); + } + + // The main game loop. This method coordinates everything that happens in + // the game + private void playGame() + { + while(true) + { + // Measure the current time in an effort to keep up a consistent + // frame rate + long time = System.currentTimeMillis(); + + // If the ship has been dead for more than 3 seconds, revive it + if(shipDead && shipTimeOfDeath + 3000 < time) + { + shipDead = false; + ship = new Ship(playWidth/2, playHeight/2, 0, 0); + } + + // Process game events, move all the objects floating around, + // and update the display + if(!shipDead) + handleKeyEntries(); + handleCollisions(); + moveSpaceObjects(); + + + // Sleep until it's time to draw the next frame + // (i.e. 32 ms after this frame started processing) + try + { + long delay = Math.max(0, 32-(System.currentTimeMillis()-time)); + + Thread.sleep(delay); + } + catch(InterruptedException e) + { + } + + } + } + + // Deal with objects hitting each other + private void handleCollisions() + { + // Anything that is destroyed should be erased, so get ready + // to erase stuff + Graphics g = playArea.getGraphics(); + g.setColor(Color.BLACK); + + // Deal with shots blowing up comets + for(int i = 0; i < shots.size(); i++) + { + Shot s = shots.elementAt(i); + for(int j = 0; j < comets.size(); j++) + { + Comet c = comets.elementAt(j); + + // If a shot has hit a comet, destroy both the shot and comet + if(s.overlapping(c)) + { + // Erase the bullet + shots.remove(i); + i--; + this.drawSpaceObject(g, s); + + // If the comet was actually destroyed, replace the comet + // with the new comets it spawned (if any) + Vector newComets = c.explode(); + if(newComets != null) + { + this.drawSpaceObject(g, c); + comets.remove(j); + j--; + comets.addAll(newComets); + } + break; + } + } + } + + // Deal with comets blowing up the ship + if(!shipDead) + { + for(Comet c : comets) + { + // If the ship hit a comet, kill the ship and mark down the time + if(c.overlapping(ship)) + { + shipTimeOfDeath = System.currentTimeMillis(); + shipDead = true; + // Add 1 to the death cound + shipDeaths++; + drawShip(g, ship); + } + } + } + } + + // Check which keys have been pressed and respond accordingly + private void handleKeyEntries() + { + // Ship movement keys + if(accelerateHeld) + ship.accelerate(); + + // Shooting the cannon + if(firing) + { + firing = false; + shots.add(ship.fire()); + numShots++; + } + } + + // Deal with moving all the objects that are floating around + private void moveSpaceObjects() + { + Graphics g = playArea.getGraphics(); + + // Handle the movements of all objects in the field + if(!shipDead) + updateShip(g); + updateShots(g); + updateComets(g); + + // MY EDITS + drawScoreboard(g); + } + + // Move all comets and draw them to the screen + private void updateComets(Graphics g) + { + for(Comet c : comets) + { + // Erase the comet at its old position + g.setColor(Color.BLACK); + drawSpaceObject(g, c); + + // Move the comet to its new position + c.move(); + + // Draw it at its new position + g.setColor(Color.CYAN); + drawSpaceObject(g, c); + + } + } + + // Move all shots and draw them to the screen + private void updateShots(Graphics g) + { + + for(int i = 0; i < shots.size(); i++) + { + Shot s = shots.elementAt(i); + + // Erase the shot at its old position + g.setColor(Color.BLACK); + drawSpaceObject(g, s); + + // Move the shot to its new position + s.move(); + + // Remove the shot if it's too old + if(s.getAge() > 180) + { + shots.remove(i); + i--; + } + // Otherwise, draw it at its new position + else + { + g.setColor(Color.RED); + drawSpaceObject(g, s); + } + } + } + + // Draws the space object s to the the specified graphics context + private void drawSpaceObject(Graphics g, SpaceObject s) + { + // Figure out where the object should be drawn + int radius = (int)s.getRadius(); + int xCenter = (int)s.getXPosition(); + int yCenter = (int)s.getYPosition(); + + // Draw the object + g.drawOval(xCenter - radius, yCenter - radius, radius*2, radius*2); + } + + // Moves the ship and draws it at its new position + private void updateShip(Graphics g) + { + // Erase the ship at its old position + g.setColor(Color.BLACK); + drawShip(g, ship); + + // Ship rotation must be handled between erasing the ship at its old position + // and drawing it at its new position so that artifacts aren't left on the screen + if(turnLeftHeld) + ship.rotateLeft(); + if(turnRightHeld) + ship.rotateRight(); + ship.move(); + + // Draw the ship at its new position + g.setColor(Color.WHITE); + drawShip(g, ship); + } + + // Draws this ship s to the specified graphics context + private void drawShip(Graphics g, Ship s) + { + // Figure out where the ship should be drawn + int radius = (int)s.getRadius(); + int xCenter = (int)s.getXPosition(); + int yCenter = (int)s.getYPosition(); + + // Draw the ship body + g.drawOval(xCenter - radius, yCenter - radius, radius*2, radius*2); + + // Draw the gun turret + int guntipXoffset = (int)(radius * 1.5 * Math.sin(s.getAngle())); + int guntipYoffset = (int)(radius * 1.5 * Math.cos(s.getAngle())); + g.drawLine(xCenter, yCenter, xCenter + guntipXoffset, yCenter + guntipYoffset); + } + + // Deals with keyboard keys being pressed + public void keyPressed(KeyEvent key) + { + // Mark down which important keys have been pressed + if(key.getKeyCode() == KeyEvent.VK_UP) + this.accelerateHeld = true; + if(key.getKeyCode() == KeyEvent.VK_LEFT) + this.turnLeftHeld = true; + if(key.getKeyCode() == KeyEvent.VK_RIGHT) + this.turnRightHeld = true; + if(key.getKeyCode() == KeyEvent.VK_SPACE) + this.firing = true; + } + + // Deals with keyboard keys being released + public void keyReleased(KeyEvent key) + { + // Mark down which important keys are no longer being pressed + if(key.getKeyCode() == KeyEvent.VK_UP) + this.accelerateHeld = false; + if(key.getKeyCode() == KeyEvent.VK_LEFT) + this.turnLeftHeld = false; + if(key.getKeyCode() == KeyEvent.VK_RIGHT) + this.turnRightHeld = false; + } + + // This method is not actually used, but is required by the KeyListener interface + public void keyTyped(KeyEvent arg0) + { + } + + + public static void main(String[] args) + { + // A GUI program begins by creating an instance of the GUI + // object. The program is event driven from that point on. + new CometsMain(); + } + + // MY EDITS + private void drawScoreboard(Graphics g){ + g.setColor(Color.BLACK); + g.drawString("Deaths: "+(shipDeaths-1), 10, 40); + g.setColor(Color.GREEN); + g.drawString("Deaths: "+shipDeaths, 10, 40); + + g.setColor(Color.BLACK); + g.drawString("Shots: "+(numShots-1), 10, 60); + g.setColor(Color.GREEN); + g.drawString("Shots: "+numShots, 10, 60); + } + +} diff --git a/Assignment 5/src/comets/LargeComet.java b/Assignment 5/src/comets/LargeComet.java new file mode 100644 index 0000000..ac2a9ea --- /dev/null +++ b/Assignment 5/src/comets/LargeComet.java @@ -0,0 +1,66 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 5: Comets + * Class: LargeComet + * Date: April 19, 2013 + * **************************************** */ + +package comets; + +import java.util.Vector; +import java.util.Random; + +public class LargeComet extends Comet { + + /** + * The radius of a large comet + */ + private static final double LARGE_COMET_RADIUS = 40; + + /** + * The number of medium comets a large comet explodes into when explode() is called. + */ + private static final int NUM_BREAKAWAY_COMETS = 2; + + /** + * A random number object to be used in the explode() method + */ + private Random random = new Random(); + + /** + * Creates a new large comet. Large comets should have radius 40. + * @param xPos The location of the comet in the x direction + * @param yPos The location of the comet in the y direction + * @param xVel The velocity of the comet in the x direction + * @param yVel The velocity of the comet in the y direction + */ + public LargeComet(double xPos, double yPos, double xVel, double yVel){ + super(xPos, yPos, xVel, yVel, LARGE_COMET_RADIUS); + } + + /** + * Splits this comet into pieces. + * @return A vector containing two medium comets with the same location as this comet, but randomly chosen velocities. + */ + public Vector explode() { + // Create a vector to hold the new comets + Vector comets = new Vector(); + + for(int i = 0; i explode() { + // Create a vector to hold the new comets + Vector comets = new Vector(); + + for(int i = 0; i MAX_SHIP_SPEED){ + xVelocity *= MAX_SHIP_SPEED / speed; + yVelocity *= MAX_SHIP_SPEED / speed; + } + } + + /** + * Produces a new shot originating from the center of the ship. + * The shot's velocity is equal to three pixels per frame in the direction that the ship is pointing added to the ship's current velocity. + * @return the new shot + */ + public Shot fire(){ + double shotXVel = xVelocity + 3*Math.sin(angle); + double shotYVel = yVelocity + 3*Math.cos(angle); + Shot shot = new Shot(this.getXPosition(), this.getYPosition(), shotXVel, shotYVel); + return shot; + } + + /** + * Returns the direction that the ship is facing. + * @return Angle the ship is facing in radians. + */ + public double getAngle(){ + return angle; + } + + /** + * Slightly increases this ship's angle. + */ + public void rotateLeft(){ + angle += SHIP_TURNING_RATE; + } + + /** + * Slightly decreases this ship's angle. + */ + public void rotateRight(){ + angle -= SHIP_TURNING_RATE; + } +} diff --git a/Assignment 5/src/comets/Shot.java b/Assignment 5/src/comets/Shot.java new file mode 100644 index 0000000..1dddd73 --- /dev/null +++ b/Assignment 5/src/comets/Shot.java @@ -0,0 +1,49 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 5: Comets + * Class: Shot + * Date: April 19, 2013 + * **************************************** */ + +package comets; + +public class Shot extends SpaceObject { + + /** + * The radius of a shot + */ + private static final double radius = 3; + + /** + * The age of the shot, i.e. the number of times move() has been called for this shot + */ + private int age = 0; + + /** + * Creates a new shot. Shots have radius 3. New shots have age 0. + * @param xPos The location of the shot in the x direction + * @param yPos The location of the shot in the y direction + * @param xVel The velocity of the shot in the x direction + * @param yVel The velocity of the shot in the y direction + */ + public Shot(double xPos, double yPos, double xVel, double yVel){ + super(xPos, yPos, xVel, yVel, radius); + } + + /** + * Returns the age of the shot, i.e. the number of times that it has had move() called on it. + * @return the age of the shot + */ + public int getAge(){ + return age; + } + + /** + * In addition to moving the shot, the age of the shot should be incremented by one. + */ + public void move(){ + super.move(); + age++; + } +} diff --git a/Assignment 5/src/comets/SmallComet.java b/Assignment 5/src/comets/SmallComet.java new file mode 100644 index 0000000..127a038 --- /dev/null +++ b/Assignment 5/src/comets/SmallComet.java @@ -0,0 +1,40 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 5: Comets + * Class: SmallComet + * Date: April 19, 2013 + * **************************************** */ + +package comets; + +import java.util.Vector; + +public class SmallComet extends Comet { + + /** + * The radius of a small comet + */ + private static final double SMALL_COMET_RADIUS = 20; + + /** + * Creates a new small comet. Small comets should have radius 20. + * @param xPos The location of the comet in the x direction + * @param yPos The location of the comet in the y direction + * @param xVel The velocity of the comet in the x direction + * @param yVel The velocity of the comet in the y direction + */ + public SmallComet(double xPos, double yPos, double xVel, double yVel){ + super(xPos, yPos, xVel, yVel, SMALL_COMET_RADIUS); + } + + /** + * Since this is the smallest category of comet, it should be completely destroyed if hit. As such, it does not spawn more comets. + * @return An empty vector + */ + public Vector explode() { + // Because we aren't making any new comets, just return an empty vector; + Vector comets = new Vector(); + return comets; + } +} diff --git a/Assignment 5/src/comets/SpaceObject.java b/Assignment 5/src/comets/SpaceObject.java new file mode 100644 index 0000000..afffe94 --- /dev/null +++ b/Assignment 5/src/comets/SpaceObject.java @@ -0,0 +1,114 @@ +/* **************************************** + * Name: Justin Bisignano + * COP 3330 – Spring 2013 + * Program 5: Comets + * Class: SpaceObject + * Date: April 19, 2013 + * **************************************** */ + +package comets; + +public abstract class SpaceObject { + + /** + * The size of the play area in the y direction + */ + public static double playfieldHeight; + + /** + * The size of the play area in the x direction + */ + public static double playfieldWidth; + + /** + * The rate at which the object is moving in the x direction + */ + protected double xVelocity; + + /** + * The rate at which the object is moving in the y direction + */ + protected double yVelocity; + + private double xPosition; + private double yPosition; + private double radius; + + /** + * Creates a space object in the specified place, with the specified speed, and the specified size. + * @param xPos The location of the object in the x direction + * @param yPos The location of the object in the y direction + * @param xVel The velocity of the object in the x direction + * @param yVel The velocity of the object in the y direction + * @param radius The distance from the center of the object to its outer edge + */ + public SpaceObject(double xPos, double yPos, double xVel, double yVel, double objectRadius){ + xPosition = xPos; + yPosition = yPos; + xVelocity = xVel; + yVelocity = yVel; + radius = objectRadius; + } + + /** + * Returns the size of the object. + * @return the object's radius + */ + public double getRadius(){ + return radius; + } + + /** + * Returns the position of the object in the x direction. + * @return the object's x position + */ + public double getXPosition(){ + return xPosition; + } + + /** + * Returns the position of the object in the y direction. + * @return the object's y position + */ + public double getYPosition(){ + return yPosition; + } + + /** + * Updates the position of the object based on its velocity, and wraps it around to the other side of the play field if it goes off the edge. + */ + public void move(){ + xPosition += xVelocity; + yPosition += yVelocity; + + // Check to see if the positions are off screen, and if they are, wrap them around + // If it's too far left, wrap it to the right + if(xPosition < 0) + xPosition = xPosition + playfieldWidth; + // If it's too far right, wrap it to the left + if(xPosition > playfieldWidth) + xPosition = xPosition - playfieldWidth; + // If it's too far up, wrap it around the bottom + if(yPosition > playfieldHeight) + yPosition = yPosition - playfieldHeight; + // If it's too far below, wrap it around the top + if(yPosition < 0) + yPosition = yPosition + playfieldWidth; + } + + /** + * Determines whether this object is overlapping with another object. + * @param otherObject The other object that we're comparing this one against + * @return true if the objects overlap and false otherwise + */ + public boolean overlapping(SpaceObject otherObject){ + double otherX = otherObject.getXPosition(); + double otherY = otherObject.getYPosition(); + double otherRadius = otherObject.getRadius(); + + if(Math.sqrt(Math.pow((xPosition-otherX), 2) + Math.pow((yPosition-otherY), 2)) < radius+otherRadius) + return true; + else + return false; + } +} diff --git a/README b/README new file mode 100644 index 0000000..0ae42b4 --- /dev/null +++ b/README @@ -0,0 +1,7 @@ +COP 3330 - Object Oriented Programming +University of Central Florida - Spring 2013 + +This repo contains programs written by me for COP 3330 +They exist here as a reference and as an online backup of my work. + +Enjoy! \ No newline at end of file