GameGrid: Game programming with Java

Research project PHBern  
HomePrintJava-Online

Program structure


1. if-else structure (selection)

Selections because of certain conditions are basic structures of each programming language.

    if (condition)
  {
    action  
  } 
  else
  {
    action
  }   
  The actions after if are only executed if the conditions are met. Otherwise the actions after else are peformed. Often only the if selection is used to check if the condtion is met.

Example 1: Left or right?
After each step the crab decides randomly if it wants to move left or right. Clicking the button Reset, the game can be restarted.

The method move() sets the object into one of the 8 neighbouring cells.

setDirection() sets the direction.

This example randomly uses the directions of 45° or 135°.

 

Run this example

Edit this example in the Online-Editor

 

// JGameEx5.java

import ch.aplu.jgamegrid.*;
import java.awt.Color;

public class JGameEx5 extends GameGrid
{
  private Actor crab = new Actor("sprites/crab.gif");
  
  public JGameEx5()
  {
    super(101060Color.red, "sprites/reef.gif");
    addActor(crab, new Location(40));
    show();
  }

  public void act()
  {
    double randomNumber = Math.random();
    if (randomNumber > 0.5)
      crab.setDirection(45);
    else
      crab.setDirection(135);
    crab.move();  
  }

  public static void main(String[] args)
  {
    new JGameEx5();
  }
}
Explaining the program code:
double randomNumber = Math.random() Returns a random decimal number between 0 and 1
if (randomNumber > 0.5) The crab moves right or left with a probability of 0.5

 

2. switch structure (multi-selection)

If there are more than two possibilities in a selection, the switch structure is used.

    switch (variable)
  {
    case value 1:
      action;
      break;
    case value 2:
      action;
      break;
    .....
    default:
      action;  
  }

Example 2: left, right, up or down
The crab randomly changes its direction after each step. If it reaches a border cell, the crab continues to move in the opposite direction.

Run this example

Edit this example in the Online-Editor

 
// JGameEx5a.java

import ch.aplu.jgamegrid.*;
import java.awt.Color;

public class JGameEx5a extends GameGrid
{
  private Actor crab = new Actor("sprites/crab.gif");

  public JGameEx5a()
  {
    super(101060Color.red, "sprites/reef.gif");
    addActor(crab, new Location(43));
    show();
  }

  public void act()
  {
    int randomNumber = (int)(Math.random() * 4);
    switch (randomNumber)
        {
          case 0:
            crab.setDirection(0);
            break;
          case 1:
            crab.setDirection(90);
            break;
          case 2:
            crab.setDirection(180);
            break;
          case 3:
            crab.setDirection(270);
            break;         
        }
    if (!crab.isMoveValid())
      crab.turn(180);
    crab.move();
  }

  public static void main(String[] args)
  {
    new JGameEx5a();
  }
}
Explaining the program code:
(int)(Math.random() * 4) + 1 Returns a random decimal number between 1 and 4
isMoveValid() Returns true if the next moving position is still inside the grid
break break allows to exit the switch structure after the actions of the selected case statement are executed

 

3. for loops (iteration / multiple execution of actions)


i = 0 : initial value
i < n : exit condition
i++  : value change

Initializing multiple crab objects
With the help of a for loop, 10 crabs are set to random locations inside the grid. Since the method act() is implemented inside the class Crab, its actions are executed for each crab instance simultaneously.

If the crab reaches a border cell it rotates 90° and since it still is in a border cell after this, it rotates again 90°.  

Run this example

Edit this example in the Online-Editor

 

// JGameEx6.java 

import ch.aplu.jgamegrid.*;
import java.awt.Color;

public class JGameEx6 extends GameGrid
{
  public JGameEx6()
  {
    super(101060Color.red, "sprites/reef.gif");
    for (int i = 0; i < 10; i++)
      addActor(new Crab()getRandomEmptyLocation());
    show();
  }

  public static void main(String[] args)
  {
    new JGameEx6();
  }
}

// ------------------- class Crab -----------------------
class Crab extends Actor
{
  public Crab()
  {
    super("sprites/crab.gif");
  }

  public void act()
  {
    if (isMoveValid())
      move();
    if (isNearBorder())
      turn(90);
  }
}
Explaining the program code:

int  i  =  0

Declaration and initialization of the numeral variable i

i  <  10

Loop condition. As long as the condition is met, the actions inside the loop are executed

i++

Is equal to i = i + 1
The value of the varible i is increased by 1

addActor(new Crab(), getRandomEmptyLocation())

Initializes a new crab in a random location

 

 

4. Nesting for loops


Example 4: Multiple crab objects are initialized with nesting for loops

Basic structure:

    for (int x = 0; x < n; x++)
  {
    for (int y = 0; y < m; y++)
    {
      Action;
    }
  }  

With two for loops both values of the coordinates (x, y) are looked at. In the folowing example the if structure, which checks if the sum of x + y is even, is droped. This way, a crab will be set into every other cell of the grid.

Run this example

Edit this example in the Online-Editor

 

// JGameEx6a.java

import ch.aplu.jgamegrid.*;
import java.awt.Color;

public class JGameEx6a extends GameGrid
{
  public JGameEx6a()
  {
    super(101060Color.red, "sprites/reef.gif");
    for (int x = 0; x < 10; x++)
      for (int y = 0; y < 10; y++)
      {
        if ((+ y) % 2 == 0)
        addActor(new Crab()new Location(x, y));
      }
    show();
  }

  public static void main(String[] args)
  {
    new JGameEx6a();
  }
}

// --------------------- class Crab ----------------------
class Crab extends Actor
{
  public Crab()
  {
    super("sprites/crab.gif");
  }

  public void act()
  {
    if (isMoveValid())
      move();
    if (isNearBorder())
      turn(90);
  }
}
Explaining the program code:

if ((x + y) % 2 == 0)

% is a modular division which returns the rest of the division (x + y)/2. This function is often used to check if a result is odd or even. If the sum of x + y is even, a crab is set to the location (x, y)

 

5. while structure (iteration)

Basic structure:

    int i = 0;           
    while (< n)    
    {
      Anweisungen;    
      i++;           
    }
  The while-structure often used by many programming languages to repeat certain program parts (actions). In JGameGrid,after pressing the button Run in the navigation bar of the game window or after calling the method doRun() inside the program code, the method act of all actors is executed preiodically with the help of a while structure. Because of this, the GameGrid tutorials do not use while structures much.

Example 5: 7 crabs are set randomly into different locations of the lower part of the grid.

In this case a while structure (loop) makes more sense, because we do not know in advance how many random locations have to be checked before having 7 different locations. (The method getRandomEmptyLocation() looks at the whole game grid and therefor is not used in this example.

Run this example

Edit this example in the Online-Editor

 
// JGameEx7.java

import ch.aplu.jgamegrid.*;
import java.awt.Color;

public class JGameEx7 extends GameGrid
{
  public JGameEx7()
  {
    super(101060Color.red, "sprites/reef.gif");
    int nb = 0;
    while (nb < 7)
    {
      Location loc = new Location((int)(10 * Math.random()),
                     5 + (int)(5 * Math.random()));
      if (isEmpty(loc))
      {
        addActor(new Crab(), loc);
        nb++;
      }
    }
    show();
  }

  public static void main(String[] args)
  {
    new JGameEx7();
  }
}

//---------------- class Crab -----------------------------
class Crab extends Actor
{
  public Crab()
  {
    super("sprites/crab.gif");
  }

  public void act()
  {
    if (isMoveValid())
      move();
    if (isNearBorder())
      turn(90);
  }
}
Explaining the program code
while (nb < 7) As long a the set amount of locations is not reached (in this case 7) the actions inside the while structure a repeated

if (isEmpty(loc))

A new crab is only initialized if the location is empty