Please follow me here!

Tuesday, June 24, 2014

Rock Paper Scissors Lizard Spock (JAVA Program)

Rock Paper Scissors Lizard Spock (JAVA Program) It's time for another JAVA program to exhibit for new programmers; this time, with Rock Paper Scissors Lizard Spock!

It's another fine day here in the countryside outside of Montreal. We got gorgeous sun right above us, even though yesterday was technically the summer solstice, in which now I'm feeling kind of down because I wasn't able to get together with my friends and have a wonderful time hanging out; it's a way for me to earn a better self-esteem and social living, because eventually I'll be with multiple classmates at University of Waterloo.

In case you're wondering about me with the FIFA World Cup 2014, technically I'm not watching it because I am more interested in paying attention to video games and working on building massive audiences for crowdfunding and public attention. In addition, I don't have enough money to build a concert at my town, participate in a drama or vocals show, join up with a television team, or even learn the secrets behind mass media and how to earn attention and promotion.

Anyway, what I want to show you today is a program I've worked on last night that I have just completed; it's a way for me to get my intelligence in JAVA back because I'll need to use programming and different kinds of talent from my time at college to be used in my first-year classes at University of Waterloo. It won't be easy, but with the kind of advice and treatment, I can earn a wonderful time and be so integrated with the people around me.

This is my own text-based program of Rock-Paper-Scissors-Lizard-Spock, which is a change in Rock Paper Scissors, and it was created, according to Wikipedia, Sam Kass and Karen Bryla. It was used in one episode of the Big Bang Theory; Raj and Sheldon did this kind of draw to decide which show they should watch together. Sheldon is up for Saturn 3, while Raj is up for Deep Space Nine. After Sheldon gives out the details of the draw with some non-verbal communication to show which sign is which in the game, he and Raj give out a shot in which they both end up using Spock.

Here's what Sheldon said, which is pretty much the details of the draw (originally written by teleplay writers David Goetsch and Jennifer Glickman): "Scissors cuts paper. Paper covers rock. Rock crushes lizard. Lizard poisons Spock. Spock smashes scissors. Scissors decapitates Lizard. Lizard eats paper. Paper disproves Spock. Spock vaporizes rock, and as it always has, rock crushes scissors." 

The program I wrote is a console-based application; all the graphics used in this implementation are Unicode characters predetermined within the Java Virtual Machine. What I'll do is show you a quick visual example of how the program works, and then I'll give you the code for it. Take note that I'm running this program on an IDE called Eclipse Kepler; more specifically, Eclipse JAVA EE IDE for Web Developers.


In starting the program, we get a two-second pause before we get a message saying the computer makes its move first. And then after another two-second pause, we get a message to enter a character corresponding to one of the five different moves of this game. Type in either, 0, 1, 2, 3, or 4, and press the Enter button.

Typed in 0. Oh, too bad; the CPU wins. Paper covers rock. Time to play again!


Computer goes first again; time to type in our move!


Type in 6: error. Type in 55: error again! Pay attention to the messages!


I type in 4, as in Spock, and it looks like I win! Spock vaporizes rock!


After asked to play again, in which I do, I type in nothing at the start. Ah, error detected! And so now, I type in 3, where I make my stance for Lizard.


Oh, dear! It looks like we have no winner! One last try in playing!


I make my move for paper, and I win. Paper disproves Spock. And it looks like I don't want to play again, so it's quit, and good-bye!


With the photographs now out of the way, let me share with you now the source code of this program and how it actually works. Modifications are done so that way you can see what it is I'm talking about.

To make understanding much easier, let me give you a description of what you are expected to see in the source code of this program. I've colored-coded the elements of the code so that way as soon as you see them the first time, you'll know what is that feature and what color is used to distinct it.

The text highlighted in black is the details on how the full program works. The text highlighted in dark green are technical details.



This is the source code of this text-based Rock Paper Scissors Lizard Spock program. There are other ways to implement this, but this is how I've implemented it myself. These are the instructions you feed into the Java Virtual Machine to execute and perform. Feeding instructions in any computer involves a programming language.

Programming has so many worldwide applications that it is now part of most of natural and service jobs all around the world. The biggest use of programming is, of course, in the computer gaming and telecommunications industries.

Anyway, let's continue on with going through the source code.

// Written on June 21 - 22, 2014
Anything you see in a greenish color with two forward slashes is a single-line comment. You can write anything in a single-line comment as long as two forward slashes precede it. Usually, when you type in something in a source code file, the compiler is supposed to compile everything that's in the file. However, the compiler ignores comments, just as long as there is a combination of symbols to denote which is which.

import java.util.Random;
import java.util.Scanner;

Any word highlighted in blue is a keyword. Text highlighted in olive is a package name, since certain instructions can be stored as data recipes, or classes, on their own. And a name in tan is a class name.

Here, we're loading access to two different classes, Random and Scanner. Because the default package used in JAVA programming is java.lang., we must import other packages if we want to consider using a specific class belonging to those individual packages. Simply put, it's to let the compiler know, "Okay, this code requires the use of those classes," and thus the libraries holding those classes are loaded into the compiler accordingly.

java.util.Random is a programming entity containing methods that return a value by using randomization algorithms. java.util.Scanner is a basic data entry for file input, or keyboard input through the console.

public class RockPaperScissorsLizardSpock

"RockPaperScissorsLizardSpock," colored in pink, is the name of the main class for which the compiler is to convert text into a binary format compatible with the Java Virtual Machine.

"public" is an access specifier, on the fact that in object-oriented programming, instructions are to interact with the main code of other classes, as well as the objects that these classes may store on purpose.

"class" is pretty straightforward; it's simply telling the compiler that there is a data recipe to be compiled.

In JAVA, any program that has an execution method is defined as a class; simply, a blueprint of what is to be instantiated during execution.

{
// Constants
public static final String[] CONSTANT_MESSAGES =

A name italicized and purple is a static variable. Because we have a constant where the value assigned to that variable is not changed at all, the name is also in capitals.

The keyword "final" is to tell the compiler that the value assigned to the variable is a constant and cannot be changed any way during execution.

Instead of using multiple String variables, or constants, for use in the program, to offer some flexibility and easier handling, most of the messages used in the program are stored in this pre-assigned String array.

This array holds most of the messages you see during gameplay. It's designed to have a bank of messages, all carefully indexed and categorized, so that way there can be more than one message of the same thing accordingly. This opens flexibility for the computer to decide randomly which message to use for the particular phase of the game.

{
/*
    *  Who goes first?
    */

Anything in orange is a comment block. Like single-line comments, the compiler ignores it as long as you have the proper syntax for it. Start with /*, and end with */. The advantage of a multi-line comment block is that you won't have to type in // for every single line. All you have to do is make sure that the comments are typed preceding the tag */.

Anything you see in red is a string literal. A string is a computer entity consisting of a character or more, including special Unicode characters.

// Player goes first (0 - 6)
"You make your move first.",
"You go first.",
"I'll let you go first.",
"Go for your move!",
"Why don't you go first?",
"Please, make your first move.",
"Alright, let's see what your move is.",
// CPU goes first (7 - 15)
"Why don't I go first?",
"I'm going first.",
"I go first.",
"I shall go first.",
"It will be my prior to make a move first.",
"You let me go first.",
"Mr. Computer shall go first.",
"Your CPU decides what move to pick primarily.",
"Let's see what my move will be...",
/*
   *  Winner Messages (16 - 20)
    */
"Awesome; you win! ",
"CPU surrenders! ",
"White flag for the CPU; ",
"Winner! ",
"WIN. ",
/*
    *  Loser Messages (21 - 25)
    */
"Too bad, you lose! ",
"You lost. ",
"You lose! ",
"You are forced to surrender. ",
"LOSE. ",
/*
    *  No Winner Messages (26 - 31)
    */
"No winner in this case!",
"We have a draw!",
"It looks like no one wins!",
"No winner!",
"A winner is ceased to exist!",
"Uh-oh, no winner.",
/*
    * Command Messages (32 - 41)
    */
"Scissors cuts paper.",
"Paper covers rock.",
"Rock crushes lizard.",
"Lizard poisons Spock.",
"Spock smashes scissors.",
"Scissors decapitates lizard.",
"Lizard eats paper.",
"Paper disproves Spock.",
"Spock vaporizes rock.",
"Rock crushes scissors."
};
Anything that is colored in light blue is a number literal.

public static final byte CHOICE_IS_ROCK = 0,
CHOICE_IS_PAPER = 1,
CHOICE_IS_SCISSORS = 2,
CHOICE_IS_LIZARD = 3,
CHOICE_IS_SPOCK = 4;

"byte" is a primitive data type, in the sense that it is directly stored in the RAM as a sequence of bytes without using a reference address. In JAVA, most of the primitive data types are signed, and thus a variable of type byte can hold a value between -128 and 127.

In this program, the values 0 to 4 are used to represent the five different movements a player can make in Rock Paper Scissors Lizard Spock.
public static final Random aiObject = new Random();
public static final Scanner keyboardInput = new Scanner(System.in);
Although the objects aiObject and keyboardInput are static constants where their variable names should be capitalized and the underscore is used, they are left in conventional format for variables that are not constants because

public static void main(String[] args)

Any text preceding the left curved bracket, or left parenthesis, and colored in a maroon-like brown is the name of a method. Except for static variables, text colored in light green is an object reference pointer, or reference variable.

This is the header of the prime method the JVM executes upon running: the "main" method, with an array of command-line arguments passed as the method argument. When you run your program through the computer terminal, such as Command Prompt on Microsoft Windows, any additional text you add, separated by spaces, after the name of the class file to execute, are the arguments that this method takes in.

You don't necessarily have to type in a command. In this case, there is no command to type in for the functionality of the program, so what happens is, this array is created, but of fixed size 0.

"void" is a return type for a method, where the method is not forced to return a value or a reference address. Primitive data types, arrays, and names of classes from respective packages are compatible as return types of methods.

{
/*
     *  Declaration and Construction Phase
  */
String messageString;
byte playersChoice, computersChoice;
boolean playAgain = false;

There are only two values used in a boolean variable: true, and false.

Text colored in gray is a primitive data type variable. Text in black is therefore syntax.
// Starting Message
System.out.println("Hello there!");

"Hello there!" is the first message you see in the output of this program.

pauseProgram();

As soon as the first message is displayed, this program is paused for about two seconds by calling this method. 
do
{

            /*
        *  Input Phase
        */

The first thing the program does is, it makes a draw to who should go first and make their move. Technically, both players choose a move instantly, but because the computer needs to register the player's input, which does take some time, the input is sequential instead of instant. As such, we want to deal with two different kinds of input and processing, but the rules of the game are definitely followed anyway because the outcome is not displayed until the very end.

if (aiObject.nextBoolean()) // AI goes first
{
System.out.println(CONSTANT_MESSAGES[aiObject.nextInt(9) + 7] + "\n\n");
There is a 7 to add to the value returned from the "nextInt" method because it is to make sure that if the computer decides to go first, then no matter what message is displayed from this array, it's always a message saying that the computer makes its move first.

computersChoice = computerMakesMove();
pauseProgram();
playersChoice = playerMakesMove();
}
else
{
System.out.println(CONSTANT_MESSAGES[aiObject.nextInt(7)] + "\n\n");
pauseProgram();
playersChoice = playerMakesMove();
System.out.println("Please wait as the computer decides.\n");
computersChoice = computerMakesMove();
pauseProgram();

Technically, the value is returned from the method computerMakesMove and assigned to computersChoice right away; the call for the pauseProgram method is simply there to let the user think that the CPU is deciding its move.

}
/*
         *  Process Phase
        */
Whatever the way on who is first, once the decisions are set, the program goes through a case-by-case decision structure to determine the proper message to be displayed on output based on the player's movements. "nextInt" is a method that returns a random value from 0 to 5 exclusively, and thus it is used in sum with a constant to get a winning, losing, or tie message. If the player is winning or losing, an associated message comes with it to display as well, giving out one of the rules of the game.

There are two sets of decision structures, along with an "else" at the very end to deduce that no one has won the game.

The first set of if-else-if clauses are for the player's chance of winning.

The program uses the equals operator and the logical AND operator to determine what were the moves chosen in the game by comparing the chosen values with the constants corresponding to the rules of the game.

// Player's Streak
if (playersChoice == CHOICE_IS_SCISSORS && computersChoice == CHOICE_IS_PAPER)  
               // Scissors cuts paper
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[32];
else if (playersChoice == CHOICE_IS_PAPER && computersChoice == CHOICE_IS_ROCK)  
               // Paper covers rock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[33];
else if (playersChoice == CHOICE_IS_ROCK && computersChoice == CHOICE_IS_LIZARD)  
               // Rock crushes lizard
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[34];
else if (playersChoice == CHOICE_IS_LIZARD && computersChoice == CHOICE_IS_SPOCK
               // Lizard poisons Spock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[35];
else if (playersChoice == CHOICE_IS_SPOCK && computersChoice == CHOICE_IS_SCISSORS
               // Spock smashes scissors
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[36];
else if (playersChoice == CHOICE_IS_SCISSORS && computersChoice == CHOICE_IS_LIZARD)
               // Scissors decapitates lizard
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[37];
else if (playersChoice == CHOICE_IS_LIZARD && computersChoice == CHOICE_IS_PAPER
               // Lizard eats paper
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[38];
else if (playersChoice == CHOICE_IS_PAPER && computersChoice == CHOICE_IS_SPOCK)  
               // Paper disproves Spock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[39];
else if (playersChoice == CHOICE_IS_SPOCK && computersChoice == CHOICE_IS_ROCK)  
               // Spock vaporizes rock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[40];
else if (playersChoice == CHOICE_IS_ROCK && computersChoice == CHOICE_IS_SCISSORS)
               // Rock crushes scissors
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 16] + CONSTANT_MESSAGES[41];

The next set of if-else-if clauses are for the computer's chance of winning.

// CPU Streak
else if (playersChoice == CHOICE_IS_PAPER && computersChoice == CHOICE_IS_SCISSORS
               // Scissors cuts paper
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[32];
else if (playersChoice == CHOICE_IS_ROCK && computersChoice == CHOICE_IS_PAPER)  
               // Paper covers rock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[33];
else if (playersChoice == CHOICE_IS_LIZARD && computersChoice == CHOICE_IS_ROCK)  
               // Rock crushes lizard
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[34];
else if (playersChoice == CHOICE_IS_SPOCK && computersChoice == CHOICE_IS_LIZARD) 
               // Lizard poisons Spock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[35];
else if (playersChoice == CHOICE_IS_SCISSORS && computersChoice == CHOICE_IS_SPOCK
               // Spock smashes scissors
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[36];
else if (playersChoice == CHOICE_IS_LIZARD && computersChoice == CHOICE_IS_SCISSORS)
               // Scissors decapitates lizard
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[37];
else if (playersChoice == CHOICE_IS_PAPER && computersChoice == CHOICE_IS_LIZARD
               // Lizard eats paper
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[38];
else if (playersChoice == CHOICE_IS_SPOCK && computersChoice == CHOICE_IS_PAPER)  
               // Paper disproves Spock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[39];
else if (playersChoice == CHOICE_IS_ROCK && computersChoice == CHOICE_IS_SPOCK)  
               // Spock vaporizes rock
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[40];
else if (playersChoice == CHOICE_IS_SCISSORS && computersChoice == CHOICE_IS_ROCK)
               // Rock crushes scissors
messageString = CONSTANT_MESSAGES[aiObject.nextInt(5) + 21] + CONSTANT_MESSAGES[41];
// No winner

If there are no winners at all, the last if-else-if clause is executed.

else
messageString = CONSTANT_MESSAGES[aiObject.nextInt(6) + 26];
/*
         *  Output Phase
         */

System.out.println(messageString);

When the proper message is assigned to the corresponding reference variable "messageString," it is displayed to tell the user who has won the game, or that the game was a draw.
pauseProgram();
playAgain = playGameAgain();

After another two-second pause, the user is asked whether to play the game again. If he does, we run the same algorithm starting after the left brace of this post-test loop, known as a do-while loop, where the inside of that loop is executed at least once. If not, the loop ceases to have another iteration executed and thus we move on to closing the program.
} while(playAgain);
// Closing Phase
System.out.println("\nThank you for playing!");
keyboardInput.close();

Before the program is terminated, we close the input.

}
public static void pauseProgram()
{
try
{
Thread.sleep(2000);

A computerized task is simply a list of instructions that is assigned to a CPU to execute. A thread holds this task awaiting for a timely execution along the CPU. You can run any number of threads in a program you write to do, let's say, some sorting by chunks, known as multithreading, because you create multiple tasks that the CPU can execute at the same time.

You have several thread management options at your disposal. In this case, we're making the thread running this program to pause for 2 seconds, or 2000 milliseconds. This method is called in a block that is actually there to watch out for any potential errors that can occur when it is called. Such errors in programming that are thrown by data entries are called exceptions.

This block makes an attempt to call the method, and "catch" any potential error this method can throw.

}
catch (InterruptedException ex)
{

"InterruptedException" is a JAVA-based error class that an object is created and thus "thrown" into the executing code when the only thread running in this program is called to sleep, but is currently sleeping, or has its task completed.

ex.printStackTrace();
System.exit(1);

Passing on the value "1" as an argument of the static method exit denotes that the program is to be terminated based on abnormal status.

Anytime the program encounters an error while executing the method to sleep for two seconds, what happens is, as soon as this method catches it, a method is called to display details on what is the error, where did it come from, and what line is it fired from the corresponding source code. In addition, the JVM executes a method for which the program it's currently running is forced to be terminated.

}
}
public static byte playerMakesMove()

This is where you type in your move.

{
String inputString;
boolean entryIsValid = true;
do
{
System.out.print("\n\n\nEnter a number corresponding to your move:\n\n"
+ "0: Rock\n"
+ "1: Paper\n"
+ "2: Scissors\n"
+ "3: Lizard\n"
+ "4: Spock\n\n"
+ "Your entry: ");
inputString = keyboardInput.nextLine();

The "nextLine" method takes input directly from the console, whether it is the computer terminal, such as Command Prompt on Microsoft Windows, or the white text area of integrated development environments that are named "Console." On Eclipse IDE, it has a tab to denote which element is which opened aside from the source code alone.

This is where you type in an index corresponding to one of the five different movements in the game.
if (!inputString.equals(""))
{
if (inputString.length() > 1)
System.out.println("\nInput error: Too long. Please enter only one character.");

Because the input used in this program is not really limited in terms of how long it can be, if it's more than one character, you'll have to type it in again, because the entire input is considered for this method to return an index corresponding to your move later on.

else
{
entryIsValid = true;
if (inputString.charAt(0) < 48 || inputString.charAt(0) > 52)
{
entryIsValid = false;
System.out.println("\nInput error: Does not correspond to the choices given. Please "
                            + "enter a value corresponding to one of them.");
}

If your input is not one of the five indexes, being a number from 0 to 4 inclusively, you get this message and thus you have to type in your input again.

}
}
else
System.out.println("\nInput error: No input. Please enter again.");

You can't make a move without typing in a character; as such, this message appears.
} while(inputString.equals("") || inputString.length() > 1 || !entryIsValid);
System.out.println("\nInput accepted.\n\n");
A case-by-case decision structure causes this method to return a value representing a move accordingly.

if (inputString.equals("0"))
return CHOICE_IS_ROCK;
else if (inputString.equals("1"))
return CHOICE_IS_PAPER;
else if (inputString.equals("2"))
return CHOICE_IS_SCISSORS;
else if (inputString.equals("3"))
return CHOICE_IS_LIZARD;
else
return CHOICE_IS_SPOCK;
}
public static byte computerMakesMove()
{
return (byte)(aiObject.nextInt(5));

There is a cast to downside the amount of space a value takes up in the RAM, because there are only five different moves. There is no method in the Random class that returns a signed byte (a number with eight binary digits that holds values in the range of -128 - 127). As such, we call nextInt, given a specified range where 4 is the maximum, where the method returns a signed four-byte integer (within the range of -[2^31] to 2^31-1), and then take the first eight binary digits to be assigned as a byte.

All this method does is, it returns a random index that represents one of the five movements the player or the CPU can make.

}
public static boolean playGameAgain()

This is where the program asks you to whether or not you want to play the game again.

{
String inputString;
boolean inputIsGood = true;
do
{
System.out.print("\n\n\nWould you like to play the game again?\n\n"
+ "Please enter a character corresponding to one of the choices:\n"
+ "0: Yes\n"
+ "1: No\n\nYour entry: ");
inputString = keyboardInput.nextLine();
Just like the input for making your move, you'll have to type your input again if there is more than one character, there is nothing in the input, or if the character is invalid.

if (inputString.equals(""))
System.out.println("\nInput error: No input. Please enter again.");
else
{
inputIsGood = true;
if (inputString.length() > 1)
System.out.println("\nInput error: Too long. Please enter only one character.");
else if (inputString.charAt(0) != '0' && inputString.charAt(0) != '1')
{
System.out.println("\nInput error: Does not correspond to the choices given. Please enter a "
                       + "value corresponding to one of them.");
inputIsGood = false;
}
} while(inputString.equals("") || inputString.length() > 1 || !inputIsGood);
if (inputString.charAt(0) == '0')
return true;

Using the input for "yes" will cause the main loop of this program to repeat again, allowing you to play the game once more.

else
return false;

If you decide not to play the game once again, the main loop does not repeat; instead, the last message of the program is displayed, the input is closed, and thus the program is terminated.

}
}


I think that will do for this blog. This one took me a lot of time to put together; it took me over eight hours in a two-day period to work on this! But I'm pretty sure this is some first experience in learning what a Rock Paper Scissors Lizard Spock JAVA implementation would be like, although it does differ from program to program!

Anyway, have a wonderful night, and I'll talk to you later!



Please read up my blog on my volunteering! http://gregorypdesrosiersmontreal.blogspot.ca/2015/08/my-mission-to-volunteer-for-reaching-my.html


Please follow my blogger by going to the top of this page, and click on "Join this site," big blue button with the Google logo!

 Click here to follow me on Facebook: https://www.facebook.com/gregorypdesrosiersuwaterloose
 Please follow me on Twitter: https://twitter.com/GregoryDes
You can also follow me on Instagram! @gregpdesig

No comments:

Post a Comment

Popular Posts by Gregory