The
class java.util.Random
should be used to generate pseudo-random numbers for this application.
The nextDouble
method returns a double selected uniformly
from the interval [0, 1).
This method can be used to generate initial poses by multiplying the
generated values by the desired upper bound for each component of the
pose.
In order to create a block that occurs with a particular probability,
you can compare the output of nextDouble
to the desired
probability. For example:
if (generator.nextDouble() < .75) { // This block will execute with probability .75. }
StdDraw
places (0,0) at the lower-left
corner of the screen. The basic units established
in GameDriver
are pixels, so that (10, 30) would
represent a position near the lower-left corner of the screen, 10
pixels from the left and 30 pixels from the bottom.
StdDraw
library documentation as well as the
other provided classes.
You may find it convenient to store your game elements in one or
more ArrayList
s. When the elements are destroyed,
you will then want to remove them. Unfortunately, modifying Java
collections during iteration can lead to problems. For example,
the following code will will result in
a ConcurrentModificationException
:
ArrayList<String> words = new ArrayList<>(); words.add("tree"); words.add("car"); words.add("house"); // Attempt to remove "tree" from the list. for (String word : words) { if (word.equals("tree")) { words.remove(word); // Throws exception! } }
Iterators may be used to safely remove objects. The following code works correctly.
ArrayList<String> words = new ArrayList<>(); words.add("tree"); words.add("car"); words.add("house"); Iterator<String> it = words.iterator(); // Remove "tree" from the list. while (it.hasNext()) { String current = it.next(); if (current.equals("tree")) { it.remove(); // Safely removes the most recent item. } }
Another possiblity is to use an indexed for loop that indexes backwards through the collection:
ArrayList<String> words = new ArrayList<>(); words.add("tree"); words.add("car"); words.add("house"); // Remove "tree" from the list. for (int i = words.size() - 1; i >= 0; i--) { if (words.get(i).equals("tree")) { words.remove(i); } }
It is necessary to work backwards because removing an element from an arraylist changes the index of all subsequent elements: they end up being shifted down by one position. A loop that works forward through the list will end up skipping elements after a removal.