Friday, September 20, 2013

Case Study: Rock, Paper, Scissors

I want to look at the following code before you begin building your own.  Copy the code below to a new Class (RockPaperScissors) and then "Auto Format" the code to see how that works.

This is a VERY different approach than what we've been doing so far.  They use a few codes we haven't seen before (i.e. boolean, String, while, nextLine, toLowerCase, ||, concat, etc.).  What are they doing?  What is "broken" in the code below?

Rock, Paper, Scissors:

import java.util.Scanner;
public class RockPaperScissors {
public static void main(String[] args) {
CPU cpu1 = new CPU();
Scanner sc1 = new Scanner(System.in);
boolean validmove = false;
String userMove = "";
while(!validmove){
System.out.println("Input your move (rock, paper or scissors): ");
userMove = sc1.nextLine();
userMove = userMove.toLowerCase();
if(userMove.equals("rock") || userMove.equals("paper")||userMove.equals("scissors")){
validmove = true;
}
}
String CPUMove = cpu1.getCPUMove();
cpu1.comparemoves(CPUMove, userMove);
}
}
class CPU{
public void comparemoves(String CPUMove, String userMove){
if(userMove.equals("rock")){
if(CPUMove.equals("rock")){
outputmoves("rock", "Tie!");
}
if(CPUMove.equals("paper")){
outputmoves("paper", "I win!");
}
if(CPUMove.equals("scissors")){
outputmoves("scissors", "You win!");
}
}
if(userMove.equals("paper")){
if(CPUMove.equals("rock")){
outputmoves("rock", "You win!");
}
if(CPUMove.equals("paper")){
outputmoves("paper", "Tie!");
}
if(CPUMove.equals("scissors")){
outputmoves("scissors", "I win!");
}
}
if(userMove.equals("scissors")){
if(CPUMove.equals("rock")){
outputmoves("rock", "I win!");
}
if(CPUMove.equals("paper")){
outputmoves("paper", "You win!");
}
if(CPUMove.equals("Scissors")){
outputmoves("scissors", "Tie!");
}
}
}
public void outputmoves(String cpuout, String status){
String output = "I played ".concat(cpuout).concat(".").concat(status);
System.out.println(output);
}
public String getCPUMove(){
int choice = (int) Math.floor(Math.random()*3);
String rpsmove = "";
switch(choice){
case 0: rpsmove = "rock"; break;
case 1: rpsmove = "paper"; break;
default: rpsmove = "scissors"; break;
}
return rpsmove;
}
}

No comments:

Post a Comment