Game Programming Tutorials
Part 9
Arrays
Arrays are very useful statements which can be used to create multiple objects in relatively few lines of codes. Arrays work by initializing however many objects you want to make, and calling them with a specific number.
This is a basic example of initializing an array
int [] intArray; // initializes a new array, and allocates its type to int’s
In this case, int is the type that will used in the array, and intArray is its name.
This is what the basic constructor and assignment of an array looks like
intArray = new int[3]; // constructor, allocates that this array will be
allowed to create 3 new int’s
intArray[0] = 1; // first assignment, sets int[0] equal to 1
intArray[1] = 2; // second assignment, sets int[1] equal to 2
intArray[2] = 3; // third assignment, sets int[2] equal to 3
When using arrays, the constructor and assignment states must be placed inside of another method (such as paint(), or init()) in order to not cause errors.
This constructor creates the new array (intArray) and tells it for as many numbers as it is allowed (3) to create a new int variable. As you will notice when java numbers the new variables it starts at 0 and counts up as many spaces as you allotted.
You can think about arrays like this.
type [] name; // type is the class, name is the name of the array,
name = new type[number of types to make] // creates a new type, how many
spaces available
name[0].someAction // a specific method that type could use.
It is extremely important to realize that arrays can be defined using just about any class, and are not just restricted to numbers. If we wanted to, we could go back and use arrays to define multiple turtles, and replace .someAction with a method like .forward.
Challenge
Expected = Have a code that prints the X Position and Y Position of the mouse whenever it is clicked. The code must also have at least 2 rectangles that can be drawn at separate locations when the mouse is clicked.
(It draws the first rectangle where the mouse was clicked first, and the second where the mouse was clicked second.)
Grade 1 = Have a code that prints the X Position, Y Position, and which Button of the mouse whenever it is clicked. The code must also have at least 3 images that can be drawn at separate locations when the mouse is clicked.
(It draws the first rectangle where the mouse was clicked first, and the second where the mouse was clicked second, etc. Images DO NOT have to be different)
Grade 2 = Have a code that prints the X Position, Y Position, which Button of the mouse whenever it is clicked, and what click number the program is on. The code must also have at least 4 images that can be drawn at separate locations when the mouse is clicked.
(It draws the first rectangle where the mouse was clicked first, and the second where the mouse was clicked second, etc. AT LEAST 2 different images must be used)