I am very new to Greenfoot, and basically I'm making a snakes and ladders game. What happens is, first the user clicks a button to being the game, which asks them how many people are playing (I have not done anything yet with the number of players), and then asks them to click on the game piece they would like to play with, which are these animals that are already on the board. When they click it, the object moves to the start position of the board. Now what is supposed to happen is, when they click the golden ball on the board, it should generate a random number, print it out as a "showMessageDialog", and then the game piece should move a certain distance according to the number generated by the dice. I tried to debug by printing out the random number again after the message dialog displays it, and it was a different random number. I'm trying to keep the number the same but I can't seem to figure it out....The first code below is the the object which,when clicked should show a random number..This is the code for the World...
import greenfoot.*; import javax.swing.*; import java.util.Random; public class DiceRoll extends Actor { Random rand = new Random(); public DiceRoll() { roll(); } public int roll() { int randNumber = 1 + Greenfoot.getRandomNumber(6); return randNumber; } }
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) import javax.swing.*; public class GameBoard extends World { private DiceRoll dice = new DiceRoll(); Hippo p1 = new Hippo(); public GameBoard() { super(1350, 1050, 1); addObject(new Start_Button(), 215, 200); addObject(new PlayerOne(), 85, 350); //addObject(new Hippo(), 200, 350); addObject(p1, 200, 350); addObject(new PlayerTwo(), 85, 430); addObject(new Wombat(), 200, 430); addObject(new PlayerThree(), 85, 510); addObject(new Pelican(), 200, 510); addObject(new PlayerFour(), 85, 590); addObject(new Fish(), 200, 590); addObject(new PlayerFive(), 85, 670); addObject(new Spider(), 200, 670); addObject(new Welcome(), 150, 65); addObject(new ClickHere(), 94, 200); //addObject(new DiceRoll(), 125, 840); addObject(dice, 125, 840); addObject(new RollDie(), 130, 770); addObject(new Start(), 228, 945); } public void act() { if(Greenfoot.mouseClicked(dice)) { JOptionPane.showMessageDialog(new JInternalFrame(), "You have rolled a: " + dice.roll(),"Dice Roll", JOptionPane.INFORMATION_MESSAGE); if (dice.roll() == 1) { //p1.setLocation(350, 980); p1.move(100); } if (dice.roll() == 2) { //p1.setLocation(450, 980); p1.move(200); } if (dice.roll() == 3) { //p1.setLocation(550, 980); p1.move(300); } if (dice.roll() == 4) { //p1.setLocation(650, 980); p1.move(400); } if (dice.roll() == 5) { //p1.setLocation(750, 980); p1.move(500); } if (dice.roll() == 6) { //p1.setLocation(850, 980); p1.move(600); } //p1.setLocation(650, 1000); System.out.println(dice.roll()); } } }