Computer Bible Games with Java: A Java Swing Game Programming Tutorial For Christian Schools & Homeschools by BibleByte Books

Computer Bible Games with Java: A Java Swing Game Programming Tutorial For Christian Schools & Homeschools by BibleByte Books

Author:BibleByte Books [Books, BibleByte]
Language: eng
Format: azw3
ISBN: 9781937161040
Publisher: BibleByte Books
Published: 2017-09-23T04:00:00+00:00


The code to do a one card shuffle, or sort n integers, is placed in a general method named nRandomIntegers. The single argument is n the number of integers to sort. The method returns an array containing the randomly sorted integers. The returned array is zero-based, returning random integers from 0 to n - 1, not 1 to n. If you need integers from 1 to n, just simply add 1 to each value in the returned array! The code is:

private int[] nRandomIntegers(int n)

{

/ *

* Returns n randomly sorted integers 0 -> n - 1

*/

int[] nIntegers = new int[n];

int temp, s;

Random sortRandom = new Random();

// initialize array from 0 to n - 1

for (int i = 0; i < n; i++)

{

nIntegers[i] = i;

}

// i is number of items remaining in list

for (int i = n; i >= 1; i--)

{

s = sortRandom.nextInt(i);

temp = nIntegers[s];

nIntegers[s] = nIntegers[i - 1];

nIntegers[i - 1] = temp;

}

return(nIntegers);

}

You should be able to see each step of the shuffle method. This method is general (sorting n integers) and can be used in other projects requiring random lists of integers.

Add the nRandomIntegers method to your Bible Match Game project. Also, since we are using random numbers, we need this import statement:

import java.util.Random;

The shuffle method will be used to hide the 10 pictures behind the 20 picture box controls. In the project, we will use a class level array pictureIndex (dimensioned to 20) to hold the randomly sorted integers (the shuffled picture indices). Add this class level declaration to your project:

int[] pictureIndex = new int[20];

The snippet of code that does a shuffle (and adjusts the values greater than 10) is:

pictureIndex = nRandomIntegers(20);

for (int i = 0; i < 20; i++)

if (pictureIndex[i] > 9)

pictureIndex[i] -= 10;

Let’s look at an example of how this works. If I run this snippet of code through a little example, the 20 elements of pictureIndex returned from one particular call to nRandomIntegers are (arranged like our picture boxes):



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.