1 / 56

Java Tools: Rock, Paper, Scissors Implementation Lab

Dive into Java fundamentals with a focus on implementing the classic game of Rock, Paper, Scissors. Learn looping, logical operators, and more.

joang
Download Presentation

Java Tools: Rock, Paper, Scissors Implementation Lab

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CSC 211 Java I Tools for implementing a game: Rock, Paper, Scissors

  2. The usual drill • Go to COL and download the Material For Lab 5 zip file from the Documents or Assignments • Unzip it • Rename it YourLastName_L5 • Open CSC211_L5 and L5 • Open Classroom presenter • Please remember to remove the files from the computer AND PLUG IT IN when you return it to the cart

  3. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  4. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  5. Midterm • The midterm is Monday, May 4th, 1:30-4:45. Location TBA, but most likely in this room – I will e-mail you. • You must work alone • There are two parts: • Pen/pencil and paper questions • Computer-based questions • You can bring 2 sheets (single-sided) of notes • A midterm study guide has been posted

  6. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  7. Logic of a while loop condition evaluated true false statement 7

  8. Features of the while loop • Note that if the condition of a while loop is false initially, the body of the loop is never executed • i.e. The body of a loop executes 0 or more times • Notice that you do NOT have to know in advance how many times you will execute the loop

  9. Are you with me? What is wrong with this loop? Trace it and write an explanation import java.util.Scanner; public class LoopExample1 { public static void main(String [] args) { int sum = 0; int count = 1; Scanner numScan = new Scanner(System.in); System.out.print("Enter the largest number to print: "); int high = numScan.nextInt(); while (count <= high) { System.out.println(count); } } }

  10. Let me out of here! The body of the loop MUST contain one or more statements that affect the loop condition, making it eventually false Otherwise we enter an infinite loop The machine will go on forever…. The needed statement in our example is an increment of the variable count count = count + 1; 10

  11. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  12. A couple of random but very important reminders:

  13. Textpad or BlueJ? If you are working with a project with multiple files, use BlueJ If you are using a single java class (most of the time in 211), Textpad is probably much better.

  14. A class to practice with: import java.util.Scanner; public class Test { public static void main(String[] args) { Scanner input = new Scanner(System.in); //do your learning / practicing here... input.close(); } //end method main() } //end class This class (or something like it) should be open EVERY time you are learning / practicing Java…

  15. The right (and wiser) way to program Algorithm JEnglish Code Period.

  16. Example – section 5 of asst #5: Note: Any parts of these steps can and should be revised as you go through!!!!!! • Algorithm • Display menu of choices (# runs, total mileage, length, etc, quit) • If user quits, end program • If user doesn’t quit, display menu and repeat • JEnglish • SOP( menu) • while (user does not enter quit)  { display menu } • SOP(any final info if necessary) • End program • Code • Probably a good idea to begin by taking sections from JEnglish and writing them in as comments to delineate sections of your code.

  17. Increment and Decrement Operators Java allows us to write the statement count = count + 1; in a compact form as follows count++; The ++ is called the increment operator The increment operator++ adds one to its operand 17

  18. Increment and Decrement Operators There is a corresponding decrement operator -- The decrement operator-- subtracts one from its operand 18

  19. Increment and Decrement Operators The increment and decrement operators can be applied in postfix form (i.e. after the variable, as in count++) or in prefix form (i.e. before the variable as in ++count ) Postfix form is preferred. Stick with it. When used ALONE in a statement, the prefix and postfix forms are equivalent. That is, count++; is equivalent to ++count; 19

  20. Increment and Decrement Operators When used in a larger expression, for example in assignment statement as in total = count++; total = ++count; the prefix and postfix forms have a different effect 20

  21. Increment and Decrement Operators In both cases the variable is incremented (decremented) but AFTER (count++) or BEFORE (++count) the assignment statement 21

  22. Increment and Decrement Operators If count currently contains 45, then total = count++; assigns 45 to total and 46 to count FIRST do the assignment THEN do the increment 22

  23. Increment and Decrement Operators If count currently contains 45, then total = ++count; assigns the value 46 to both total and count FIRST do the increment THEN do the assignment 23

  24. Assignment Operators Often we perform an operation then store the result back into that variable Java provides more special operators, besides ++ and -- that are a combination of arithmetic AND assignment 24

  25. Assignment Operators For example, the statement count += 2; is equivalent to count = count + 2; 25

  26. Assignment Operators There are many assignment operators, including the following: Operator += -= *= /= %= Example x += y x -= y x *= y x /= y x %= y Equivalent To x = x + y x = x - y x = x * y x = x / y x = x % y 26

  27. Are you with me? Ink the value of x and y after each line of code x | y int x = 5, y = 10; x = --y; ___|___ x %= y; ___|___

  28. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  29. Rock, Paper, Scissors • Go to the lab materials and open the project RPS • Read the code and understand it • Run the program several times • Now we want to fill in the missing pieces • Before coding, what do we do? • Yes, JEnglish (only for the inside of the while loop) • Go to CSC211_Lab5 and work on Part 1.1

  30. Machine generates a random number between 1 and 3. 1 = Paper stored as a char ‘P’ 2 = Rock stored as a char ‘R’3 = Scissors stored as a char ‘S’ • Ask user to enter “P” or “R” or “S” • Keep asking as long as the user has not entered one of the above (e.g. if user enters ‘w’) • Need a while loop and a compound condition • While input is not equal P and not equal R and not equal S

  31. If machine weapon is the same as the user weapon • Print “it’s a tie” • Otherwise • If one of the following conditions is true the machine wins: Machine: P and User: RMachine: R and User: SMachine: S and User: P • Else the user wins • Ask the user if she wants to play again

  32. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  33. Logical AND and logical OR • The logical ANDa && b is true if and only if both a and b are true, false otherwise • The logical ORa || b is true as long as one of the two is true. && and || • Takes 2 boolean values • Return a boolean value

  34. Are you with me? Ink whether the following conditions are T or F char x = ‘p’ ; char y = ‘P’; int z = 3; int q = ++z; x == y && z == q T F x == y || z == q T F q > 4 && x != y T F z < 2 || q>1 || x != y T F

  35. Short circuiting • The two operands of && and || are evaluated in order (left to right) • If the first operand for && is false, the second is never evaluated • If the first operand for || is true, the second is never evaluated • This can be very tricky if your operands change state – Be careful!

  36. Exercise • It is time to start coding the RPS game • Do Parts 1.2 and 1.3 of Lab 5 • For Part 1.2, hard code the machine’s choice (no randomness) and ask the user to enter a choice of weapons • For Part 1.3, validate the user’s choice of weapon, repeatedly re-prompting in the case of invalid input

  37. String answer; charmachine, player; while (answer.toLowerCase().charAt(0) == 'y' || answer.toLowerCase().equals("yes")) { machine = 'P'; //Hard-Coded the machine’s weapon System.out.println("I have picked my weapon “ + "\n now pick yours P,R,S"); player = console.next().toUpperCase().charAt(0); System.out.println("Player choice: "+ player); while (player != 'R' && player !='P' && player !='S') { System.out.println("You entered an invalid character. Please try again (P, R, or S):"); player = console.next().toUpperCase().charAt(0); } System.out.println(“Would you like to play again ? (yes/no): "); answer = console.next(); }

  38. Exercise • Work more on the RPS game • Do Parts 1.4 (and time permitting, 1.5) of Lab 5 • For Part 1.4 add code that reports the outcome of the round • Program’s choice of weapon still fixed for ease of testing • (Challenge) For Part 1.5 keep statistics for all rounds

  39. Today’s plan • Assignment Q/A • Midterm • Looping review • Increment and decrement operators • Tools for implementing Rock, Paper, Scissors • Writing JEnglish • Logical operators • Fancy input/output • Loop practice

  40. Fancier input/ouput So far we have done input/output using the terminal window, System.out.print() and Scanner Today we’ll look at graphical input/output using the JOptionPane class

  41. JOptionPane JOptionPaneis a predefined graphic class. (API http://java.sun.com/javase/6/docs/api/ ) It allows you to use dialog windows It has a series of method for graphic input and output. It is part of set of classes grouped in the Swing library (package) i.e. import javax.swing.JOptionPane;

  42. Packages The classes of the Java standard class library are organized into packages

  43. Packages The classes of the Java standard class library are organized into packages • import javax.swing.*;

  44. I/O (input/output) with JOptionPane The primary methods we will use for input and output are showMessageDialog used for output, equivalent to print, displays a String in a dialog box

  45. I/O with JOptionPane The primary methods we will use for input and output are showMessageDialog() used for output, equivalent to the print methods we’ve been using, displays a String in a dialog box showInputDialog() used for input, equivalent to .next() from the Scanner class, collects data from the user in the form of Strings in a dialog box, allows you to also display a String

  46. JOptionPane output String to be shown Component containing the output: nullis the default window frame Class name(swing package) Class Output method(JOptionPane class) import javax.swing.*; JOptionPane.showMessageDialog (null, “Hello”); • The dialog window disappears when we click ok, but the program is still managing the window. • Use the exit method of the System class to stop it. • The number 0 means normal termination • Only do so at the very end of your program System.exit(0);

  47. JOptionPane input Variable declaration (inputs are Strings) Save the input in a variable (String) Input method of the JOPtionPane class Message displayed in the dialog window import javax.swing.*; String fName; fName = JOptionPane.showInputDialog(“Type in your name”); System.exit(0); //don’t forget this line!

  48. Exercise – “fancify” I/O Do Part 2.1 of Lab 5

  49. From Strings to Numbers Input from a dialog window is always a string. What if you are trying to read in a number??? There are certain classes that have methods to convert strings to numbers. These methods will only work if the strings contain numbers (and only numbers!) String to Integer Integer.parseInt(variable_name); String to DoubleDouble.parseDouble(variable_name);

  50. Exercise – “fancify” I/O Do Part 2.2 of Lab 5

More Related