This site requires JavaScript, please enable it in your browser!
Greenfoot back
bbwf
bbwf wrote ...

2013/2/4

How to move random y value 50% of the time?

bbwf bbwf

2013/2/4

#
Hi, I am wondering how I would move a random Y value 50% of the time? This is for my fish actor. Here's the code I have. import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo) /** * Write a description of class Fish here. * * @author (your name) * @version (a version number or a date) */ public class Fish extends Actor { /** * Act - do whatever the Fish wants to do. This method is called whenever * the 'Act' or 'Run' button gets pressed in the environment. */ public void act() { move(); // death(); { // If object reaches right boundary, reset to the left if (getX() >= getWorld().getWidth() - 1) { setLocation(0, getY()); } setLocation (getX() + 1, getY()); } } public void move() /** * This method move the fish. * (not part of the lesson) */ { setLocation(getX()+1,getY()); } }
danpost danpost

2013/2/4

#
There are two things involved with a even random chance of y motion. (1) move or do not move; and (2) up or down. Both have only two possibilities and can be randomly chosen with:
boolean choice = Greenfoot.getRandomNumber(100)<50;
which produces a 50/100 random chance of 'true' or 'false'.
actinium actinium

2013/2/4

#
Lol, would never of thought of using
boolean choice = Greenfoot.getRandomNumber(100)<50; 
as Greenfoot.getRandomNumber(100) returns an int between 0 and 99. But looking more closely, first choice =getRandomNumber(100) is executed then (choice < 50) is evaluated and returned as a boolean. Neat.
danpost danpost

2013/2/5

#
actinium wrote...
But looking more closely, first choice =getRandomNumber(100) is executed then (choice < 50) is evaluated and returned as a boolean. Neat.
More precisely, 'Greenfoot.getRandomNumber(100) is executed first, than compared to 50 returning a boolean value that is then assigned to a new boolean field named 'choice'. The value is not assigned to the field on the left until the expression on the right is evaluated and checked to ensure that the type of value to be assigned equals the field type. (it should be obvious that 'getRandomNumber(100)' cannot be assigned to 'choice' because it is of 'int' type, not 'boolean'.
actinium actinium

2013/2/5

#
What's not obvious is that a method that returns an int looks like an overloaded method for getRandomNumber that returns a boolean. Never noticed getRandomNumber being used in that context.
You need to login to post a reply.