Kilobolt
  • Home
  • Tutorials
    • Game Development Tutorial >
      • Unit 1: Beginning Java >
        • Before you begin...
        • Day 1: Setting Up
        • Day 2: Java Basics
        • Day 3: More Basics
        • Day 4: Java Math
        • Day 5: More Math
        • Day 6: If... else...
        • Day 7: More Control Flow
        • Day 8: Looping
        • Day 9: More on Looping
        • Day 10: Inheritance, Interface
        • Day 11: Threads and Graphics
      • Unit 2: Creating a Game I >
        • Day 1: Foundations
        • Day 2: Basic Framework
        • Day 3: Taking User Input
        • Day 4: Enter the Robot
        • Day 5: Background and Sprites
        • Day 6: Adding Enemies
        • Day 7: Shooting Bullets
        • Day 8: Animations
        • Day 9: 2D-Arrays
        • Day 10: Painting the Tilemap
      • Unit 3: Creating a Game II >
        • Day 1: Level Creation - Part 1
        • Day 2: Level Creation - Part 2
        • Day 3: Level Creation - Part 3
        • Collision Detection Basics
        • Day 4: Collision Detection Part 1
        • Day 5: Collision Detection Part 2
        • Day 6: Collision Detection Part 3
        • Day 7: Health System & Death
        • Day 8: Basic AI & Final Touches
      • Unit 4: Android Game Development >
        • Day 1: Introduction to Android
        • Day 2: Setting up for Development
        • Day 3: Creating our First Android Application
        • Day 4: Parts of an Android Application
        • Day 5: The Android Game Framework: Part I
        • Day 6: The Android Game Framework: Part II
        • Create an Android Game From Scratch (or port your existing game)
        • Day 7: Creating an Android Game (From Start to Finish)
      • Reference Sheet
    • Zombie Bird Tutorial (Flappy Bird Remake) >
      • Unit 1: Building the Game >
        • Introduction
        • Day 1: Flappy Bird - An In-depth Analysis
        • Day 2: Setting up libGDX
        • Day 3: Understanding the libGDX Framework
        • Day 4: GameWorld and GameRenderer and the Orthographic Camera
        • Day 5: The Flight of the Dead - Adding the Bird
        • Day 6: Adding Graphics - Welcome to the Necropolis
        • Day 7: The Grass, the Bird and the Skull Pipe
        • Day 8: Collision Detection and Sound Effects
        • Day 9: Finishing Gameplay and Basic UI
        • Day 10: GameStates and High Score
        • Day 11: Supporting iOS/Android + SplashScreen, Menus and Tweening
        • Day 12: Completed UI & Source Code
    • Android Application Development Tutorial >
      • Unit 1: Writing Basic Android Apps >
        • Before you begin...
        • Day 1: Android 101
        • Day 2: Getting to Know the Android Project
        • Day 3: The Development Machine
        • Day 4: Building a Music App - Part 1: Building Blocks
        • Day 5: Building a Music App - Part 2: Intents
        • Day 6: Building a Music App - Part 3: Activity Lifecycles
  • New Forum
  • About Us
    • Contact Us
  • Our Games
    • TUMBL: FallDown
  • Facebook
  • Twitter

GAME DEVELOPMENT TUTORIAL: DAY 1-6: If... else...

9/16/2012

77 Comments

 
Picture
Lesson #1-9: If and else statements

In Java, we can control the "flow" of the program by using conditional statements.
Let's take a look at this simple example. 
Picture
This is a pretty simple class. Let me explain some of the things we have here.

1. class DrinkingAgeTest creates a class called DrinkingAgeTest.
2. We then create a static integer age (this does not have to be static if it is placed inside the main method).
3. Of course we create a main method, as all Java programs will look for this as a starting point.
4. Now the interesting parts: 
Picture
Meet the if statement. It is written like so: 
Picture
When Java encounters the if statement, it checks each condition to see if it is satisfied (true).
If so, it carries out everything inside the braces for that if statement. If not, the statement is completely skipped.

Applying this to the example class, the compiler checks if age, which is 18, is greater than or equal to 21.
It is not, so it skips the line: 
Picture
Since none of the previous conditions are met, it automatically goes into the else statement, which outputs: 
Picture
Note: If you have multiple "if" statements, each of them is checked to see if true. If only one of the conditions can be true (i.e. the conditions you are testing for are mutually exclusive), it is therefore  
Picture
Now we are going to apply this to simulate probability.


Lesson #1-10: Simulating Probability: Relational Operators

In the lesson #1-8, we created a random object called rand and invoked the method "nextInt." 
Picture
Recall that the above generates a number between 0 and 10 (11 numbers starting with zero).

Now let's simulate probability, starting with a simple example. 
import java.util.Random;

//Let's simulate a coin toss!
public class Simulation {
    public static void main(String[] args){
       
        Random rand = new Random();
       
        int result = rand.nextInt(2);
           
        if (result == 0){
            System.out.println("heads");
        }
       
        else if(result == 1){
            System.out.println("tails");
        }
       
        else if(result == 3){
            System.out.println("side. fix your random number generator");
        }
       
    }
}
 
This is also a pretty straightforward class. We use the random number generator to create an number between 0 and 1 (inclusive) and set it equal to a newly created integer: result.

We arbitrarily decide that the value of 1 is equal to heads and the value of 0 is equal to tails. Now we test the value of result using else if statements (mutually exclusive events) and display the appropriate string (text).

Since the value of result should never (theoretically) be 3, I created a third statement that is only read if result does somehow become 3 (it should be as common as landing a coin on its side).

In these two lessons, we used two operators: == and >=. 


Here are all six relational operators: 
Picture
Lesson #1-11: Conditional Operators and Our First Game

In this lesson, we are going to create a simple game. Oh, don't get too excited. By simple, I mean simple.
Before we do that, here's a quick lesson on conditional operators: 
Picture
When you have an if statement like below: 
Picture
Then if either conditionOne or conditionTwo is true, it will invoke the "doThis()" method;

When you have a statement like this:
Picture
Then both conditionOne and conditionTwo must be satisfied before "doThat" method is called.
NOTE: When you just write a boolean (variables with value of either true or false, such as conditionOne) without stating: == true or == false, it is assumed that you actually wrote boolean = true.

In other words:
Picture
and
Picture
Are equivalent.

Now back to our game!
Here is how the game works. You roll a 6-sided die. If you land a 1 or 2 you lose. If you get a 3, 4, or 5, you roll again. If you get a 6, you win.

To write good programs, you have to plan beforehand. You should think the following:

1. I need a random number generator.
2. I should test if:

I. a number is less than or equal to 2.
II. if not, I should test whether if that number is between 3 and 5 (inclusive)
III. if not, I should test whether if that number is 6.

3. I should carry out an appropriate response.

Simple. Now let's create this class.

figure 3: BySimpleIMeanSimple class, Complete

 import java.util.Random;

//The greatest game ever made follows.
class BySimpleIMeanSimple {


static int dieValue;

public static void main(String[] args) {

rollDie();

} // ends main


static void rollDie() {

Random rand = new Random();

// Assign a random number between 1 and 6 as dieValue
dieValue = rand.nextInt(6) + 1;

System.out.println("You rolled a " + dieValue);

// Why add 1? Think about it.
testDieValue(dieValue);

} // ends rollDie()


static void testDieValue(int dieValue) {

if (dieValue <= 2) {
System.out.println("You Lose.");
} // ends if

else if (dieValue == 3 || dieValue == 4 || dieValue == 5) {
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
} // ends else if

else if (dieValue == 6) {
System.out.println("You win! Congratulations!");
} // ends else if

} // ends testDieValue()

} // ends BySimpleIMeanSimple Class
I want you to spend time with this class. Copy and paste it into eclipse and play around with it.
We will discuss this class in detail in tomorrow's lesson!

You might be surprised by what you have already learned! 

A tip: if you don't know what the purpose of a certain line of code is, it is a good idea to remove it temporarily (comment it out and run it). You can compare results with and without the statement =)
You can also modify the code and see how it works differently.

If you have any questions:
Comment below!
Go to Day 5: More Math
Go to Day 7: More Control Flow
77 Comments
Brad
11/3/2012 01:36:32 pm

I followed another tutorial and I didn't like it as much. I've enjoyed this one so far. I made a little Rock, Paper, Scissors game. I probably did it the hard way, but It works :D

//Imports
import java.util.Scanner;
import java.util.Random;

public class RPS {

public static void main(String[] args){

//Creating the scanner and Randomizer
Scanner input = new Scanner(System.in);
Random rand = new Random();
int cpick = 2;

System.out.println("Welcome to Rock Paper Scissors!!!");
System.out.println(" ");
System.out.println(" ");
System.out.println(" ");
System.out.println("Choose your weapon by typing Rock, Paper or Scissors...");

//Player inputs his/her selection
String Player = input.nextLine();


//Computer's turn
//Results for Rock
if(rand.nextInt(2) == 0){
System.out.println("Computer Picks Rock...");
System.out.println("");
cpick = 0;
if(Player.equals("Rock") && cpick == 0){
System.out.println("Stalemate, Nobody wins!");
}
else if(Player.equals("Paper") && cpick == 0){
System.out.println("Paper Covers Rock, You Win :D");
}
else if(Player.equals("Scissors") && cpick == 0){
System.out.println("Rock Breaks Scissors, You Lose :(");
}
}
//Results for Paper
else if(rand.nextInt(2) == 1){
System.out.println("Computer Picks Paper...");
System.out.println("");
cpick = 1;
if(Player.equals("Rock") && cpick == 1){
System.out.println("Paper Covers Rock, You Lose :(");
}
else if(Player.equals("Paper") && cpick == 1){
System.out.println("Stalemate, Nobody wins !");
}
else if(Player.equals("Scissors") && cpick == 1){
System.out.println("Scissors Cuts Paper, You Win :D");
}
}
//Results for Scissors
else if(rand.nextInt(2) >= 1){
System.out.println("Computer Picks Scissors...");
System.out.println("");
cpick = 2;
if(Player.equals("Rock") && cpick == 2){
System.out.println("Rock Breaks Scissors, You Win :D");
}
else if(Player.equals("Paper") && cpick == 2){
System.out.println("Scissors Cuts Paper, You Lose :(");
}
else if(Player.equals("Scissors") && cpick == 2){
System.out.println("Stalemate, Nobody Wins!");
}
}
}
}

Reply
James C.
11/6/2012 04:41:25 pm

Slightly complicated, but it looks good! :)
Thank you for sharing.

Reply
Jibran
1/12/2013 10:55:51 pm

y wud u use cpick variable here?

Reply
Reece
11/14/2012 02:21:41 pm

Great stuff Thank you!

Reply
Dabo Ross link
11/26/2012 03:17:55 am

I have been looking at these tutorials, and they look very awesome!
I know c# and c++, and I am wanting to learn java. I managed to make this application without really looking at what you had written in that post! I have known no java before I started looking at these tutorials.


import java.util.Random;

public class Game1 {
public static int randomInt(int max) {
return (new Random().nextInt(max));
}

public static int diceRoll() {
int diceRoll = Game1.randomInt(5);
diceRoll +=1;
return diceRoll;
}

public static String winChecker(int diceroll) {
if (diceroll == 1 || diceroll == 2) {
return "lose";
}
if (diceroll == 3 || diceroll == 4 || diceroll == 5) {
return "reroll";
}
return "win";
}

public static Boolean gameRoller() {
Boolean won = true;
int numberOfRolls=0;
Boolean reroll=null;
for ( ; ; ) {
numberOfRolls++;
System.out.println("Rolling");
int diceRoll = Game1.diceRoll();
System.out.println("You rolled a " + diceRoll);
String action = Game1.winChecker(diceRoll);
if (action == "reroll") {
reroll = true;
}
else if (action == "lose") {
reroll = false;
won = false;
}
else if (action == "win") {
reroll = false;
won = true;
}
if (reroll == false) {
System.out.println("You rolled the dice " + numberOfRolls + " times");
return won;
}
}
}

public static void main(String[] args) {
Boolean won = Game1.gameRoller();
if (won == true) {
System.out.println("You won!");
}
if (won == false) {
System.out.println("You lost!");
}
}
}

I really am liking the way you are teaching this~!

Reply
Dabo Ross link
11/26/2012 03:19:20 am

Just because that formating didn't work, here is the formatted version in a pastbin: http://pastebin.com/yU7ner9A

Reply
Dabo Ross link
11/26/2012 03:23:34 am

I just realized an error in my code XD!
I fixed having you not be able to roll a 6 by changing int diceRoll = Game1.randomInt(5); to int diceRoll = Game1.randomInt(6);
That was a mistake.

Thanks for this tutorial, it is really helpfull!

Reply
Chris Sch
11/29/2012 09:39:30 am

Well that was a fun game! xD

Its 2:37 in the morning and I'm hungry, lets call it a night. xD

Thank you for the tutorials. I'll be sure to mention you and your website in each game I make, and I'll donate as soon as I earn something.

If you don't count my lunch money, I'm flat broke. ( -_-)

Reply
nlightnedkc
12/2/2012 08:27:45 pm

HI, thanks for the awesome tutorial, and i am a complete noob so i find this very easy to learn. i made a little Janken game too but i am unable to input strings or convert memory locations from the random generator into names like "rock" or "paper", but i got the logic right and here is the code. Thanks a lot and please make more awesome tutes! :D i have used only the functions thought in this tutorial.

import java.util.Random;
public class Janken {
static int A;
static int B;
public static void main(String[] args){
randomising();
}
static void randomising(){

Random rand = new Random();
A = rand.nextInt(3);
B = rand.nextInt(3);

//0 means rock
//1 means paper
//2 means scissor - fill these with code

System.out.println("A is " + A);
System.out.println("B is " + B);
logic();
}
static void logic(){


if(A==B){
System.out.println("replaying");
randomising();
}
else if (A == 0 && B == 1 || A == 1 && B == 2 || A == 2 && B == 0){
System.out.println("B wins!");
}

else if (B == 0 && A == 1 || B == 1 && A == 2 || B == 2 && A == 0){
System.out.println("A wins!");
}


}
}

Reply
Chris
2/17/2014 05:45:18 am

you can do that easily with cases .next tutorial

Reply
Brett
12/4/2012 02:46:52 pm

Very impressive tutorials. I wish there was a guide like this for every programming language!
I do have a small issue with your coin toss example, however. Since you are using the .nextInt() method as the condition for the if statements, the 3 if statements are each generating their own random number.

if (rand.nextInt(2) == 1){...}
else if (rand.nextInt(2) == 0){...}
else if (rand.nextInt(2) == 2){...}

This could mean that in some instances, none of the if blocks are evaluated at all. For example, if the .nextInt() in the first if statement generates a 0, the code block is ignored and the else if condition will be evaluated. Since the else if condition itself calls nextInt() again, a new random number is generated. If the second nextInt() returns a 1, it will not execute the code block there either. This would then cause the final else if condition to generate a 3rd random number and compare it with 2. Since the random numbers generated will only be 0s and 1s, this third code block is not executed either.
While this may seem trivial, I thought it would be good to point out since someone trying your example may wonder why there is no output occasionally when running the code.
A simple solution would be to assign the random value to a separate int variable and use that variable in the condition blocks instead.

int randomNumber = rand.nextInt(2);
if (randomNumber == 1){...}
else if (randomNumber == 0){...}
else if (randomNumber == 2){...}

Reply
James C.
12/6/2012 08:08:00 am

Oops! Sorry about that! I am glad you pointed this out to me!

Reply
Matthew
12/6/2012 06:08:05 am

The Lesson Says:

"This is also a pretty straightforward class. We use the random number generator to create an number between 0 and 1 (inclusive) and set it equal to a newly created integer: coinInt.

We arbitrarily decide that the value of 1 is equal to heads and the value of 0 is equal to tails. Now we test the value of coinInt using else if statements (mutually exclusive events) and display the appropriate string (text).

Since the value of coinInt should never (theoretically) be 2, I created a third statement that is only read if coinInt does somehow become 2 (it should be as common as landing a coin on its side)."


I thought i'd let you know that "coinInt" is mentioned when you explain the code that preceded it, however, in the preceding code, coinInt is nowhere to be found. Just letting you know so you can fix that, if you choose, and avoid having people be confused. :-)

Reply
James C.
12/6/2012 08:14:10 am

Thanks for letting me know. Apparently I posted the wrong code because I described it properly but it was missing in the image.

Reply
Matthew
12/6/2012 06:42:31 am

I was just playing around with the code and added a few of the commands that you explained, but that we haven't worked with or played around with thus far by changing the class a little.

i added:
<=
>=
&&

//BEFORE
static void testDieValue(int dieValue) {
if (dieValue <= 2) {
System.out.println("You Lose.");
}

else if (dieValue == 3 || dieValue == 4 || dieValue == 5) {
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
}


else if (dieValue == 6) {
System.out.println("You win! Congratulations!");
}
}

//AFTER
static void testDieValue(int dieValue) {
if (dieValue == 1 || dieValue == 2) {
System.out.println("You Lose.");
}

else if (dieValue >= 3 && dieValue <= 5) {
// extra empty line? System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
}

else if (dieValue == 6) {
System.out.println("You win! Congratulations!");
}
}

Reply
Matthew
12/6/2012 07:21:10 am

oops, never mind. i hadn't gotten to the next lesson yet (where you show exactly what i commented)
:-( :-D

Reply
Steve
12/10/2012 08:49:14 am

I'm a little concerned that I'm falling behind. I think I have a grasp of the concepts shown so far, but I'm having difficulty applying them as done above. Should I be able to make my own rock papers scissors bit of code by now?

Reply
Amos
1/1/2013 10:33:42 am

Thanks for the tutorials! Your Simulation class code block seems wrong and doesn't do what the descriptive text does. You should be setting result to rand.nextInt(2) and then using 0, 1, and 2 for your comparisons.

Reply
James C.
1/1/2013 12:03:19 pm

Thanks for letting me know!

Reply
Reagan McClellan
1/3/2013 09:49:37 am

"Note: If you have multiple "if" statements, each of them is checked to see if true. If only one of the conditions can be true (i.e. the conditions you are testing for are mutually exclusive), it is therefore "

so many errors in that sentance!

Reply
vwade79
1/7/2013 02:16:25 pm

in your dice simulator there is an error. For the main method, you forgot to make the (Strings args) like (String[] args). my cde wasn't working with the first way. I spent 15 minutes trying to see what was wrong until I figured it out. -_-

Reply
vwade79
1/8/2013 12:48:04 pm

sorry I meant coin toss simulator

Reply
Jon Jansen Campos link
2/4/2013 06:07:50 pm

Made a simple rock, paper, scissor game. Can anyone give me pointers on how to make this more simpler?

import java.util.Random;

class Warcraft {
static int humanattack;
static int attack;
static int orcattack;

public static void main(String[] args) {
battle();
}

static void battle() {

human();
orc();
skirmish();
}

static void human(){

Random rand = new Random();
humanattack = rand.nextInt(3);

if (humanattack == 0){
System.out.println("Rolled a " + (humanattack + 1) + ", Human used Sword!");
}
else if (humanattack == 1){
System.out.println("Rolled a " + (humanattack + 1) + ", Human used Shield!");
}
else if (humanattack == 2){
System.out.println("Rolled a " + (humanattack + 1) + ", Human used Magic!");
}
}

static void orc(){

Random rand = new Random();
orcattack = rand.nextInt(3);

if (orcattack == 0){
System.out.println("Rolled a " + (orcattack + 1) + ", Orc used Sword!");
}
else if (orcattack == 1){
System.out.println("Rolled a " + (orcattack + 1) + ", Orc used Shield!");
}
else if (orcattack == 2){
System.out.println("Rolled a " + (orcattack + 1) + ", Orc used Magic!");
}
}

static void skirmish() {

if (humanattack == orcattack){
System.out.println("Battle is a Draw!");
}
else if (humanattack == 0 && orcattack == 1){
System.out.println("Orc blocks Human's attack with a Shield! Orc Wins!");
}
else if (humanattack == 0 && orcattack == 2){
System.out.println("Human slashes Orc with a Sword while chanting! Human Wins!");
}
else if (humanattack == 1 && orcattack == 0){
System.out.println("Human blocks Orc's attack with a Shield! Human Wins!");
}
else if (humanattack == 1 && orcattack == 2){
System.out.println("Orc burns Human when attempting to block with a Shield! Orc Wins");
}
else if (humanattack == 2 && orcattack == 0){
System.out.println("Orc decapitates Human with a Sword while chanting! Orc Wins!");
}
else if (humanattack == 2 && orcattack == 1){
System.out.println("Human paralyzes Orc when attempting to block with a Shield! Human Wins");
}
}
}

Reply
Chuck
2/7/2013 01:31:04 pm

I wonder if you could use counters...
I might have to give this a swing too.

Reply
Vlaxx
2/17/2014 03:31:18 am

I think that your part in the code:

static int attack;

is not needed for code to run. You are only using "orcattack", and "humanattack". Nice code for beginner like me tho! :D..Learned a lot! Tnx!

Reply
fir
2/13/2013 09:32:56 am

what you mean nextInt()

Reply
Daniel
2/19/2013 12:18:16 pm

well I have a question, i'm not really sure what does the "rollDie();" do or how does it work...
Could you help me with this one?

Reply
David
3/27/2013 04:50:01 am

At the beginning you say:
"We then create a static integer age (this does not have to be static if it is placed inside the main method)."

Why is that? From my understanding so far making it static means that changing age for one DrinkingAgeTest object changes age for all DrinkingAgeTest objects. I don't understand why putting age in main would achieve the same thing.

Reply
Lk
4/1/2013 01:08:16 am

Hello i follow your topic but i get error when i run the script. It say that
Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method rollDie() from the type BySimpleIMeanSimple refers to the missing type viod

at BySimpleIMeanSimple.main(BySimpleIMeanSimple.java:7)
and here the Code:


import java.util.Random;


public class BySimpleIMeanSimple {
static int dieValue;
public static void main(String[]args){
rollDie();

}

static viod rollDie(){
Random rand = new Random();
dieValue = rand.nextlnt(6)+ 1;
System.out.println("You rolled a" + dieValue);
testDieValue(dieValue);

}

static void testDieValue(int dieValue){
if(dieValue <= 2){
System.out.println("You Lose.");
}

else if(dieValue == 3||dieValue == 4|| dieValue == 5){
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();

}
else if(dieValue == 6){
System.out.println("You win! Congratulation!");
}
}

}


Reply
mohsin
5/29/2013 05:24:07 pm

dude correct you're spelling of void...
static viod rollDie(){
Random rand = new Random();
dieValue = rand.nextlnt(6)+ 1;
System.out.println("You rolled a" + dieValue);
testDieValue(dieValue);

}

Reply
joresnik
12/25/2013 11:55:41 pm

I find it humorous that you said correct 'you're' spelling. I think you meant 'your' lol.

Archie
4/8/2013 09:02:16 pm

You are awesome Bandhu... :D

Reply
Ashish K
4/15/2013 04:25:44 am

In your example of the die rolling class, in function testDieValue(),
instead of writing

else if (dieValue == 3 || dieValue == 4 || dieValue == 5)

you could've just written

else if(dieValue<6)

and left the last else statement as just a simple else:

else { ...}


because already the more than or equal to 2 statement had been checked, and therefore if the dieValue was indeed 3 or 4 or 5, this else if would've catched it. And since the dieValue is definitely going to be between 1 and 6, the last else catching the control would mean that the dieValue is 6.

I would understand though if you wrote it from the perspective of making the beginner learn it clearly. But I hope the beginner understands what I'm saying.

Reply
Leevi L.
5/27/2013 03:47:28 am

Hi, I copied that code you made for the dice game and when I run the script it gave me an error and it said:

"Exception in thread "main" java.lang.NoClassDefFoundError: d
Caused by: java.lang.ClassNotFoundException: d
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
"

What have I done wrong?

Reply
Leevi L.
5/27/2013 04:15:01 am

Never mind, stupid mistake from me!!! IGNORE THAT MESSAGE!

Reply
Albert
5/28/2013 10:05:07 pm

Hi James! It's me again the same one from Day 4 :d

I wanna answer this question (Don't know if i'm right or wrong tho haha..) :

dieValue = rand.nextInt(6) + 1;
System.out.println("You rolled a " + dieValue);
// Why add 1? Think about it.

If it's not +1 the dice will only have 0,1,2,3,4,5 as the numbers on each sides.
If we add +1, it will go like this (0+1), (1+1), (2+1), (3+1), (4+1), (5+1). Thus, creating a dice with 1, 2, 3, 4, 5, 6 on each sides :D

Am i right? :S

Reply
JC
5/29/2013 01:32:48 am

That's exactly right.

Reply
barkx
7/12/2013 07:37:41 pm

Hi, just started yesterday on this tutorial and its excellent thanks for youre time and effort. After reading what you have said in unit 1 day 5 i have made a few alterations that i thought might be better practice could you tell me if it is or not as ive never done it before?
1 - i changed the roll again line to make it less code and moved it to the top as it is statistically the most frequent also if its looped to roll again it needs to be as fast as possible? i also altered if its 6 code to reduce the code?
i know its a small programme but would this be better practice if im writing big programmes? thanks barkx

import java.util.Random;


//The greatest game ever made follows.
class BySimpleIMeanSimple {
static int dieValue;
public static void main(String[] args) {
rollDie();
}

static void rollDie() {
Random rand = new Random();
// Assign a random number between 1 and 6 as dieValue
dieValue = rand.nextInt(6) + 1;
System.out.println("You rolled a " + dieValue);
// Why add 1? Think about it.
testDieValue(dieValue);
}

static void testDieValue(int dieValue) {

if (dieValue >= 3 && dieValue <= 5) {
System.out.println();
System.out.println("Rerolling.");
System.out.println();
rollDie();
}

else if (dieValue <= 2) {
System.out.println("You Lose.");
}

else {
System.out.println("You Win! Congratulations!");

}
}
}

Reply
Rohit Mishra
7/21/2013 01:00:42 am

I found your website from xda..
Your teaching style is really cool
here's my code. Wrote it without looking :-)

import java.util.Random;

class studyspace
{
static int dieValue;
public static void main(String[] args){
rollDie();
if(dieValue<2){
System.out.println("You Rolled "+dieValue);
System.out.println("You Lose!!!");
}
else if(dieValue>2 && dieValue<6){
System.out.println("You Rolled "+dieValue+" !!, Roll Again!!");
rollDie();
}
else if(dieValue == 6){
System.out.println("You Rolled "+dieValue);
System.out.println("You Win!!!!");
}
}

static void rollDie(){
Random ran = new Random();
dieValue=ran.nextInt(6)+1;
}
}

Reply
Jonathan
7/25/2013 05:52:34 pm

Hello, Im trying to create a Russian Roulette game from what we have learned so far but im having a couple problems. its not letting me use an else statement and both if statements run when I run the program, what am I doing wrong.

import java.util.Random;

public class Russian {

static int chambernumberLoaded;
static int chambernumber;

public static void main(String[] args) {
load();
}

static void load() {
Random rand = new Random();
chambernumberLoaded = rand.nextInt(5) + 1;
System.out.println("chamber" + chambernumberLoaded + "LOADED!");
spin();
}

static void spin() {
Random rand = new Random();
chambernumber = rand.nextInt(5) + 1;
System.out.println("chamber# is" + chambernumber);
System.out.println("PULL TRIGGER");

if (chambernumber == chambernumberLoaded)
;
{
System.out.println("YOUR DEAD");

}
if (chambernumber != chambernumberLoaded)
;

System.out.println("YOU LIVE");

}

}

Reply
Stefan
8/10/2013 04:53:39 pm

Can't runt the BySimpleIMeanSimple class.
It appears under the KilboltTutorialProject but not at the run button.
It runs only the MathLearning class.
I don't know what's wrong.
Please help.

Reply
Stefan
8/10/2013 07:17:31 pm

It worked, sorry, my bad, misspelled "main", wrote mian so the class had no main method.

Reply
Cong Tenorio link
9/7/2013 09:35:00 am

LOL Never in aThousand years would have I thought of what you did, I tinekered with the Simulation part and came up with this

import java.util.Random;

//Let's simulate a coin toss!
public class Simulation {
public static void main(String[] args){

Random rand = new Random();

int result = rand.nextInt(6) + 1;

if (result == 1 || result == 2){
System.out.println(result);
System.out.println("Lose");
}

else if(result == 3 || result == 4 || result == 5){
System.out.println(result);
System.out.println("Roll Again");
}

else if(result == 6){
System.out.println(result);
System.out.println("Champion");
}

}
}


Thoug I did understand your code, can you tell me its difference ? Anyways thanks much for this :D

Reply
D Arthur
2/25/2014 03:09:12 am

New to this only about 3 days. But from what I Can see. You did not create a "rollDie" method in your code.
So even if you hit a "2, 3 or 4". It will just tell you roll again. You would have to run the program again.

On the other hand. With a "rollDie();" this simulates the automatic rolling of the die until you either win or lose. I wondered why as well until I read through the whole Unit 1. multiple times.

Please correct me if im wrong. (and I know this is old just testing my knowledge)

Reply
Troels Christensen
11/26/2013 09:35:16 pm

Hello, very nice tutorial.

When i copypaste the die roller ( The: class BySimpleIMeanSimple ) Im not able to run it. In eclipse when I try to run it, it says: none aplicable.

When i type in the whole thing myself it works though:)

Thought you should know.

Reply
joresnik
12/26/2013 12:01:25 am

One thing you might want to stress a little more: You had them create the Hello_World project, and now you suggest that they copy/paste the dice game into Eclipse. It won't work if they're copying over the Hello_World class, and if they copy it below, it won't do anything. I think some beginners will be a bit confused by this.

I think you should stress a little more that they either need to create a new class object, or change the class name to Hello_World and add it to the current page.

Reply
John
2/8/2014 05:53:11 am

You can replace this piece of code:
else if (dieValue == 3 || dieValue == 4 || dieValue == 5) {

with:
else if (dieValue >= 3 && dieValue <= 5) {

for less code.

Reply
S.Teal
4/1/2014 04:29:28 pm

Hey Jonh,

else if (dieValue >2 && dieValue < 6) {

is even sorter. lots of ways to skin that varmit lol

Reply
Chris
2/17/2014 05:40:03 am

Hi, im just wondering why we need the testDievalue method in this case. It serves no purpose ran the program fine without it

Reply
Newb Tester
2/22/2014 03:26:12 am

By the end of this lesson , should I be able to recreate a simple Dice game without referring back to looking at the original example?

Reply
Newb Tester
2/25/2014 03:11:51 am

No worries. Re reading does help..I read couple times. and on my 3rd time rereading unit one...this simple dice game is second nature now.

Reply
tejas
3/15/2014 04:00:17 pm

thank you very much for this lessons,i have learnt java before just to pass the exam, but it wasn't with this kind of fun..i have a question
i tampered the game code as follows..

import java.util.Random;

//The greatest game ever made follows.
class BySimpleIMeanSimple {


static int dieValue;

public static void main(String[] args) {

rollDie();

} // ends main


static void rollDie() {

Random rand = new Random();

// Assign a random number between 1 and 6 as dieValue
dieValue = rand.nextInt(6) + 1;

System.out.println("You rolled a " + dieValue);

// Why add 1? Think about it.
testDieValue(dieValue);

} // ends rollDie()


static void testDieValue(int dieValue) {

if (dieValue <= 6) {
System.out.println("You Lose.");
} // ends if
}
}


and even when i removed the half of the code..and kept the

if (dievalue<=6){
system.out.println("you lose");
}

the continued to give result of

You rolled a 6
You win! Congratulations!

how is that even possible,i don understand..
even when code is completely removed,it continued to display same statements!!

help me out 'm stuck!!

Reply
RikTheCoder
4/20/2014 02:31:30 am

I wonder if ITS can use the same code for game development with some other editor like netbeans and I'M am talking about the 3rd chapter of your page. Please reply soon... :/

Reply
Alend
4/23/2014 04:09:16 am

Here is how I did and it seams working fine, I put "int Dievalue" (without static)inside the main method, Please tell me if I am missing anything because the code is working.
Thanks.

import java.util.Random;


public class BySympleIMeanSymple {

public static void main(String[] args){

int Dievalue;
Random rand = new Random();
Dievalue = rand.nextInt(6) + 1;

if (Dievalue <= 2){
System.out.println("You last, good luck next time");

}

else if (Dievalue == 3 || Dievalue==4||Dievalue==5){
System.out.println("Have another go");
}

else if (Dievalue==6){
System.out.println("You Won, well done");

}
}


}

Reply
Stretch
5/17/2014 06:42:37 pm

First off thanks for the awesome tutorials. you make it all simple and understandable. really enjoying this. So i followed through on your example, then i tried to use what i learnt so far and make my own sort of game, and it worked......yay:)

was just wondering if perhaps there was a slightly simpler way of doing what i did, obviously though using what i have learnt so far and no new stuff. thanks though.

code:


import java.util.Random;


public class MultiplayerRockPaperScissors {

static int handMove;
static int handMove2;

public static void main(String[] args){

shuffle();
}

static void shuffle(){

Random rand = new Random();

handMove = rand.nextInt(3);
handMove2 = rand.nextInt(3);

if (handMove == 0){
System.out.println("Player one " + "scissors");
}
if (handMove == 1){
System.out.println("Player one " + "rock");
}
if (handMove == 2){
System.out.println("Player one " + "paper");
}
if (handMove2 == 0){
System.out.println("Player two " + "scissors");
}
if (handMove2 == 1){
System.out.println("Player two " + "rock");
}
if (handMove2 == 2){
System.out.println("Player two " + "paper");
}

testShuffle(handMove + handMove2);


}
static void testShuffle(int shuffle){
if (handMove == handMove2){
System.out.println("play again");
System.out.println();
shuffle();
}
else if (handMove == 0 && handMove2 == 1){
System.out.println();
System.out.println("player two wins. well done!!");
}
else if (handMove == 0 && handMove2== 2){
System.out.println();
System.out.println("player one wins. good choice!!");
}
else if (handMove == 1 && handMove2==0){
System.out.println();
System.out.println("player one wins. whoop whoop!!");
}
else if (handMove == 1 && handMove2 == 2){
System.out.println();
System.out.println("player two wins. in your face!!");
}
else if (handMove == 2 && handMove2 == 0){
System.out.println();
System.out.println("player two wins. oh yeah!!");
}
else if (handMove == 2 && handMove2 == 1){
System.out.println();
System.out.println("player one wins. show them who's boss");
}


}


}

Reply
Yash Tandon
7/4/2014 03:25:51 pm

I must sy you people are doing well
i have gone through many tutorials on android as well as java but they are all not like this....
Thank you very much...
there is a humble request please add more for android....

Reply
Srath
7/6/2014 05:33:53 am

I don't think that in the coin toss the result can ever be 3.

else if(result == 3){
System.out.println("side. fix your random number generator");

it can only take the values 0,1,2 as we specify in

int result = rand.nextInt(2);

Correct?

Reply
Srath
7/9/2014 09:46:21 pm

No my idiotic former self.
int result = rand.nextInt(2); means its will take the values of 0 and 1. You got misled by your brain... read that method again!

Hahahaha

Reply
Srath link
7/9/2014 09:46:33 pm

No my idiotic former self.
int result = rand.nextInt(2); means its will take the values of 0 and 1. You got misled by your brain... read that method again!

Hahahaha

Reply
Srath link
7/9/2014 09:46:49 pm

No my idiotic former self.
int result = rand.nextInt(2); means its will take the values of 0 and 1. You got misled by your brain... read that method again!

Reply
Srath link
7/9/2014 09:47:03 pm

No my idiotic former self.
int result = rand.nextInt(2)
means its will take the values of 0 and 1. You got misled by your brain... read that method again!

Reply
Rahul Gupta link
7/25/2014 03:28:17 am

You are right buddy!! it should be rand.nextInt(7) to make this program work correctly..

Dane
7/11/2014 12:53:59 pm

Hey, I programmed a slightly different dice game, and just wondering what the extra lines you have do, like the "static void dieRoll" lines and the "testDieValue". I ask because I did not need them for mine...as follows:

import java.util.Random;


class Randomisation {

public static void main(String[] args){

Random guess = new Random();

int dieValue = guess.nextInt(6) + 1;

System.out.println("You rolled a " + dieValue);

if (dieValue <= 2){
System.out.println("Haha, You lose &/");
}

else if (dieValue >= 3 && dieValue <= 5){
System.out.println("Roll again!");
}

else if (dieValue == 6){
System.out.println("You won &)");
}
}

}

Reply
Dane
7/11/2014 01:10:49 pm

Ok, so I just figured out what "rollDie" does, enables you to automatically re-roll upon rolling a 3-5, but what of "testDieValue"?
Couldn't you just include the code underneath the "rollDie"?

import java.util.Random;


class Randomisation {

public static void main(String[] args){

rollDie();
}

static void rollDie(){

Random guess = new Random();

int dieValue = guess.nextInt(6) + 1;

System.out.println("You rolled a " + dieValue);

if (dieValue <= 2){
System.out.println("Haha, You lose &/");
}

else if (dieValue >= 3 && dieValue <= 5){
System.out.println("Rerolling");
rollDie();
}

else if (dieValue == 6){
System.out.println("You won &)");
}
}

}

Reply
Rahul Gupta link
7/25/2014 03:25:55 am

There is an error in your code, rand.nextInt(6) generates no's between 0-5 including 0 and 5 i.e 6 no's so it will never take 6 (NEVER WIN). It should be rand.nextInt(7) to make it work correctly.

Reply
Annie Yeung link
8/17/2014 10:37:31 am

I just started exploring Java and these tutorials are so helpful!!! Thank you!

Reply
Time
9/8/2014 02:44:00 am

Hey I copied your code exactly for #1-9 and it doesn't give the correct output. Instead I get the output from Day 5. Could you please give me some information as to why this is?

Reply
Mubeen Ali link
9/21/2014 07:27:43 pm

Can I export this project as PC app?

Reply
Krzysztof link
10/28/2014 06:37:33 am

I wrote before I look at your code:
import java.util.Random;

public class DiceGame{
static int liczba=3;

public static void main(String[] args){
Random rand = new Random();
while(liczba==3||liczba==4||liczba==5){
liczba = rand.nextInt(6)+1;
System.out.println("["+liczba+"]");
if(liczba<3){
System.out.println("LOSE");
}
else if(liczba==6){
System.out.println("WIN");
}
}
}
}

Reply
Abhishek Pathak
11/23/2014 03:26:11 pm

Author, you are so good with your skills and way of presenting them, including punches and humorous statements, you doesn't let our intrest down. HATS OFF for you hard-work. GOOD LUCK!!!

Reply
adit
12/10/2014 12:27:16 pm

i have a question,why when i run the roll dice program it always say:"Error: Could not find or load main class Simulation".
help please :(

Reply
Shahzeb Jadoon link
12/30/2014 04:28:47 pm

Easy one you can easily understand this code

import java.util.Random;
public class Dice {
public static void main(String[] args){
Random diceObj= new Random();
int rlt= diceObj.nextInt(6);
if (rlt==0)
System.out.println("one");
else if(rlt==1)
System.out.println("two");
else if(rlt==2)
System.out.println("three");
else if(rlt==3)
System.out.println("four");
else if(rlt==4)
System.out.println("five");
else if(rlt==5)
System.out.println("Six");
else
System.out.println("lose");
}
}

Reply
Justin
2/25/2016 11:41:41 am

I am currently trying to use a random object in my game. The way I want it to work is that when you win, it will show you one of the 2 win scenes, and the one shown is chosen randomly. Here is what I have
else if (state == GameState.Win) {{

Random win = new Random();

winValue = win.nextInt(2);



testWinValue(winValue);
}


if(winValue == 0){
g.drawImage(winScene, getCenterX() - 400, getCenterY() - 240, this);
//g.fillRect(0, 0, 800, 480);
g.setColor(Color.BLACK);
g.drawString("P.S. Bandana Dee 4 Smash", 210, 390);
g.drawString("Score: " + score,360, 180);
g.drawString(" Congrats, you win!", 260, 140);
System.out.println("Win Scene 1 now showing");
}

else if(winValue == 1){
//g.setColor(Color.RED);
g.drawImage(winScene2, getCenterX() - 400, getCenterY() - 240, this);
//g.fillRect(0, 0, 800, 480);
g.setColor(Color.BLACK);
//g.drawString("P.S. Bandana Dee 4 Smash", 210, 390);
g.drawString("Score: " + score,360, 180);
g.drawString(" Congrats, you win!", 260, 140);
System.out.println("Win Scene 2 now showing");

}

//g.setColor(Color.RED);
//g.drawImage(winScene2, getCenterX() - 400, getCenterY() - 240, this);
//g.fillRect(0, 0, 800, 480);
//g.setColor(Color.BLACK);
//g.drawString("P.S. Bandana Dee 4 Smash", 210, 390);
//g.drawString("Score: " + score,360, 180);
//g.drawString(" Congrats, you win!", 260, 140);

}

}

The problem is that it keeps coming up with the random number, when I only want it to do it once. This causes it to flicker between end screens instead of picking one and leaving it at that. Does anyone know how I can fix this

Reply
Incerto
5/15/2016 10:53:35 am

"When Java encounters the if statement, it checks each condition to see if it is satisfied (true).
If so, it carries out everything inside the braces for that if statement. If not, the statement is completely skipped."


I really enjoyed the tutorial so far!
If you write "If ... If ... else ..." then shouldn't it say "if ... else if ... else ..."? Later on it is correct ... I think...

Please correct me if I am wrong!


-Incerto

Reply
Incerto
5/15/2016 11:05:46 am

Nvm. I'm stupid.

Reply
Pranay
4/7/2018 04:44:52 am

I am not able to import.
There is no option like that in quick fix in eclipse

Reply
Vincent link
12/22/2020 06:07:30 pm

Thhank you for being you

Reply



Leave a Reply.

    Author

    James Cho is the lead developer at Kilobolt Studios. He is a college student at Duke University and loves soccer, music, and sharing knowledge. 


© 2014 Kilobolt, LLC. All rights reserved.