## zondag 24 april 2011

### Get Angle between 2 points Method

public double getangle( double x1, double y1, double x2 , double y2 ){
double at = Math.toDegrees(Math.atan2( x1 - x2 , y1 - y2 ));
at = at - 180;
if (at > 360 ){
at = at - 360;
}else if ( at < 0) {
at = at + 360;
}
return at;
}

to move from the x1 and y1 coordinates to the x2 to the y2 coordinates then.

double movement x per step  = Math.sin(math.toRadians(ang)); // ang is the at value returned by the method above.
double movement y per step  = Math.cos(Math.toRadians(ang));

I used this code for shooting lasers towards mouse coordinates. It was a sort of missile defender game.

### Weirdness with Atan2

I am trying to convert some of my older code to Java and discovered that the Atan2 command returns polar coordinates in stead of degrees. You can fix this by doing Math.toDegrees(Math.atan2())

### Double ArrayList Example

I could not get Doubles working with ArrayList so I looked up how to do it on Internet.

Below a example.

import java.awt.*;
import java.applet.*;
import java.util.ArrayList;

public class doubleArrayList01 extends Applet {
ArrayList<Double> doubs = new ArrayList<Double>();

public void init() {
System.out.println(doubs.get(0));
}

public void paint(Graphics g) {

g.drawString("Welcome to Java!!", 50, 60 );

}
}

### Boolean ArrayList example

I could not get Arraylists with Booleans working so I looked it up on the Internet.

Below a example of how to use Boolean ArrayLists.

import java.awt.*;
import java.applet.*;
import java.util.ArrayList;

public class BooleanArrayList01 extends Applet {

ArrayList<Boolean> bools = new ArrayList<Boolean>();

public void init() {

System.out.println(""+bools.get(0));

}

public void paint(Graphics g) {

g.drawString("Welcome to Java!!", 50, 60 );

}

### Cellular Automata - Map/Level/Land/Island Generator Example.

I spend a while looking around for level generating methods and found out about cellular automata. You basically create a map with random values on it and change values if there are less then 5 of those values are around them. You end up with a interesting picture. It kind of looks like cow skin patterns.

Below is the code. It is pretty simple. It should compile after you paste it in your editor if the class name is the same as the project name.

``````
import java.awt.*;
import java.applet.*;
import java.util.Random;

public class MapClustering01 extends Applet {

Random r = new Random();
int mapwidth = 320;
int mapheight = 200;
int[][] map = new int[mapwidth][mapheight];
String info = "";

public void init() {
generateclustermap(r.nextInt(5),r.nextInt(2));
}

public void generateclustermap(int passes, int mode){
passes++;
System.out.println("Mode : " + mode + " Passes :"+passes);
info = "Mode : " + mode + " Passes :"+passes;
//
// I modified the formula, i do not add 0 to the
// to fill the map with 0 1 and 3 but the map
// looks neater when only using 1 and 2.

// fill map with random 1's and 2's.
for (int y = 0 ; y < mapheight ; y++ ){
for (int x = 0 ; x < mapwidth ; x++ ){
map[x][y] = r.nextInt(2)+1;
if (mode == 1 && r.nextInt(15) < 1 ) map[x][y]=1;

}
}

// cluster
for(int i = 0 ; i < passes ; i++){
int bcolor = 0;
int scount = 0;
for (int y = 0 ; y < mapheight ; y++ ){
for (int x = 0 ; x < mapwidth ; x++ ){
scount = 0;
bcolor = map[x][y];
for (int y1 = -1 ; y1 < 2 ; y1++ ){
for (int x1 = -1 ; x1 < 2 ; x1++ ){
if ( x + x1 >= 0 && x + x1 < mapwidth && y + y1 >= 0 && y + y1 < mapheight ){
if (map[x+x1][y+y1] == bcolor ) scount++;
}
}
}
if( scount < 5 && bcolor == 1 ) map[x][y] = 2;
if( scount < 5 && bcolor == 2 ) map[x][y] = 1;
}
}
}

}

public boolean mouseUp( Event evt, int x, int y){
generateclustermap(r.nextInt(5),r.nextInt(2));
repaint();
return true;
}

public void paint(Graphics g) {

g.drawString("Click to create new image..", 10, getSize().height-5 );
g.drawString(info, 10, getSize().height-25 );
int sx = getSize().width / mapwidth;
int sy = getSize().height / mapheight;
for(int y = 0 ; y < mapheight ; y++ ){
for( int x = 0 ; x < mapwidth ; x++){
if ( map[x][y] == 1 ) g.setColor(Color.black);
if ( map[x][y] == 2 ) g.setColor(Color.white);
g.fillRect(x*sx,y*sy,sx,sy);
}
}
}
}
``````

### Rocks Game Example - throwing/carying/picking up

I downloaded a videogame remake called Chuck Rock. In that game there are rocks that you can carry, pickup and put down and throw. I spend a while recreating that.

Not everything is ok. The rock being carried is not moved correctly and you move at a same speed with small and bug rocks. I also made the code a bit longer than it could of been.

I also had no Internet access this weekend and could not get arraylists working with booleans and Doubles so I had to use regular arrays.

Here is the code. It should compile if you paste it in your java editor and have the right project name assigned to it.

``````
import java.applet.*;
import java.awt.event.*;
import java.awt.*;
import java.util.Random;

public class RocksGameExample01 extends Applet implements Runnable
{
private boolean  debugmode   = true;

Random     r     = new Random();

// Graphics for double buffering.
Graphics    bufferGraphics;
Image     offscreen;

// The Images for the blocks that can be picked up
// and thrown and jumped on.
Image     rock1;
private int   rock1height   = 20;
private int   rock1width   = 16;
Image     rock2;
private int    rock2height   = 8;
private int   rock2width   = 16;
private int   numrocks   = 10;
private boolean[]  rockexists   = new boolean[numrocks];
private int[]   rockx    = new int[numrocks];
private int[]   rocky    = new int[numrocks];
private int[]   rockwidth   = new int[numrocks];
private int[]   rockheight   = new int[numrocks];
private double[] rockincy   = new double[numrocks];
private double[] rockvely   = new double[numrocks];
private int[]   rocktype   = new int[numrocks];
private boolean[] rockisfalling  = new boolean[numrocks];
// ArrayList< Integer > rockx   = new ArrayList< Integer >();
// ArrayList< Integer > rocky   = new ArrayList< Integer >();
// ArrayList< Integer > rocktype  = new ArrayList< Integer >();
// ArrayList< Integer > rockincy  = new ArrayList< Integer >();

// Player Image
Image player;
private int   playerwidth   = 16;
private int   playerheight  = 32;
Image     playersquat;
private int   playersquatwidth = playerwidth;
private int   playersquatheight = playerheight/2;

private int[][]  debugrect   = new int;

// Player position
private int   xpos    = 0;
private int   ypos    = 0;
private int   groundlevel   = 0;
private boolean  isjumping   = false;
private boolean  isfalling   = false;
private double   gravity    = 0.0;
private double   gravityinc   = 0.08;
private boolean  playermoveright  = false;
private boolean  playermoveleft  = false;
private boolean  playerfacingleft = false;
private boolean  playerfacingright = true;
private int   startingjumpspeed = 2;
private boolean  playerpickuprock = false;
private boolean  playersquated  = false;
private boolean  isonrock   = false;
private boolean  playercaryingrock = false;
private int   rockbeingcarried = 0;
private boolean  playerthrowrock  = false;
private boolean  playerputrockback   = false;
private int   rockbeingthrowed = 0;
private boolean  rockisbeingthrowed = false;
private int   rockthrowheight  = 0;
private double   rockthrowx   = 0;
private double   rockthrowy   = 0;
private double   rockthrowvelx  = 0;
private double  rockthrowvely  = 0;
private double  rockthrowincx  = 0;
private double  rockthrowincy  = 0;
private boolean  rockgoingup   = false;
private boolean  rockgoingdown  = false;
private boolean  rockgoingright  = false;
private boolean  rockgoingleft  = false;
private boolean  rockliftingmode  = false;
private boolean  rockputtingdownmode = false;
private int   rockdesty   = 0;
private boolean  startsquat   = false;
private boolean  endsquat   = false;

public void init()
{
setBackground(Color.black);
offscreen = createImage(getSize().width,getSize().height);
bufferGraphics = offscreen.getGraphics();
// create the player image
player = createImage(playerwidth,playerheight);
Graphics test1 = player.getGraphics();
test1.setColor(Color.red);
test1.fillRect(0,0,playerwidth,playerheight);
// create the player image
playersquat = createImage(playersquatwidth,playersquatheight);
Graphics test4 = playersquat.getGraphics();
test4.setColor(Color.red);
test4.fillRect(0,0,playersquatwidth,playersquatheight);

// create block 1 image
rock1 = createImage(rock1width,rock1height);
Graphics test2 = rock1.getGraphics();
test2.setColor(new Color(100,100,100));
test2.fillRect(0,0,rock1width,rock1height);
// create block 2 image
rock2 = createImage(rock2width,rock2height);
Graphics test3 = rock2.getGraphics();
test3.setColor(new Color(100,100,100));
test3.fillRect(0,0,rock2width,rock2height);

xpos    = getSize().width / 2;
ypos    = getSize().height / 2 + 32 - playerheight ;
groundlevel   = getSize().height / 2 + 32;

for (int i = 0 ; i < 10 ; i++ ){
}

}

public int getfreerock(){
for ( int i = 0 ; i < numrocks ; i++ ){
if( rockexists[i] == false ) return i;
}
return -1;
}

int tp = r.nextInt(2);
tp++;
int n = getfreerock();
//System.out.println("block "+n);
if( n == -1 ) return false;
rockexists[n] = true;
rocktype[n] = tp;
int x1=0;
int y1=0;
boolean exitthis = false;
while(exitthis == false ){
x1 = r.nextInt(getSize().width)-74;
y1 = groundlevel-getrockheight(n);
if(rockrockcollide(x1,y1,tp) == false){
rockx[n] = x1;
rocky[n] = y1;
rockwidth[n] = getrockwidth(n);
rockheight[n] = getrockheight(n);
rocktype[n] = tp;
rockincy[n] = .1;
rockvely[n] = 1;
exitthis = true;
}
}
return true;
}

public boolean playeronrock(int x , int y){
// only the bottom of the player and the
// top of the rocks need to be checked.
int x1 = xpos+x;
int y1 = ypos+y+playerheight;
int w1 = playerwidth;
int h1 = 1;
int x2 = 0;
int y2 = 0;
int w2 = 0;
int h2 = 0;
for(int n = 0 ; n < numrocks ; n++){
if( rockexists[n] == true ){
x2 = rockx[n];
y2 = rocky[n];
w2 = rockwidth[n];
h2 = rockheight[n];
Rectangle rec1 = new Rectangle(x1,y1+h1-1,w1,1);
Rectangle rec2 = new Rectangle(x2,y2,w2,1);
if(rec1.intersects(rec2)) return true;
}
}
return false;
}

public int getrockheight(int num){
if(rocktype[num] == 1){
return rock1height;
}else{
return rock2height;
}
//  return 0;
}

public int getrockwidth(int num){
if(rocktype[num] == 1){
return rock1width;
}else{
return rock2width;
}
//return 0;
}

public boolean dorockfall(){
int x1,y1,w1,h1;
for( int i = 0 ; i < numrocks ; i++ ){
if(i != rockbeingcarried ){

if( rockisfalling[i] == false){
if( rocky[i] + rockheight[i] < groundlevel && rocktopcollide(rockx[i],rocky[i],rocktype[i]) == false){
//System.out.println("floater.");
rockisfalling[i] = true;
rockvely[i] = 1;
}
}
if( rockisfalling[i] == true ){
boolean falld = true;
for( int n = 0 ; n < rockvely[i] ; n++ ){

if (rocktopcollide(rockx[i],rocky[i],rocktype[i])){
//System.out.println("rock landed on other rock top");
rockisfalling[i] = false;
falld = false;
}
if( rocky[i] + rockheight[i]+1 > groundlevel ){
//System.out.println("Rock landed on ground.");
rockisfalling[i] = false;
falld = false;
}
if (falld == true){
rocky[i]++;
rockvely[i] += rockincy[i];
}
}
}
}
}
return true;
}

public boolean rocktopcollide(int x , int y, int tp2){
// get the rock n variables
int w1 = 0;
int h1 = 0;
int w2 = 0;
int h2 = 0;
int x2 = x;
int y2 = y;
if(tp2 == 1){
w2 = rock1width;
h2 = rock1height;
}else{
w2 = rock2width;
h2 = rock2height;
}
// loop through all rocks
for(int i = 0 ; i < numrocks ; i++ ){
if(rockexists[i] == true ){
int x1 = rockx[i];
int y1 = rocky[i];
int tp1 = rocktype[i];
if((x1 != x2) && (y1 != y2)){
if(tp1 == 1){
w1 = rock1width;
h1 = rock1height;
}else{
w1 = rock2width;
h1 = rock2height;
}
//System.out.println(""+w1+","+h1+":"+w2+","+h2);
//debugrect = 1;
//debugrect = x1;
//debugrect = y1;
//debugrect = w1;
//debugrect = h1;
//debugrect = 1;
//debugrect = x2;
//debugrect = y2;
//debugrect = w2;
//debugrect = h2;
Rectangle rec1 = new Rectangle(x1,y1-1,w1,1);
Rectangle rec2 = new Rectangle(x2,y2+h2-1,w2,1);
if(rec1.intersects(rec2)) return true;
}
}
}
return false;
}

public boolean rockrockcollide(int x , int y, int tp2){
// get the rock n variables
int w1 = 0;
int h1 = 0;
int w2 = 0;
int h2 = 0;
int x2 = x;
int y2 = y;
if(tp2 == 1){
w2 = rock1width;
h2 = rock1height;
}else{
w2 = rock2width;
h2 = rock2height;
}
// loop through all rocks
for(int i = 0 ; i < numrocks ; i++ ){
int x1 = rockx[i];
int y1 = rocky[i];
int tp1 = rocktype[i];
if(tp1 == 1){
w1 = rock1width;
h1 = rock1height;
}else{
w1 = rock2width;
h1 = rock2height;
}
Rectangle rec1 = new Rectangle(x1,y1,w1,h1);
Rectangle rec2 = new Rectangle(x2,y2,w2,h2);
if(rec1.intersects(rec2)) return true;
}

return false;
}

public int moveplayer(int x, int y, int callloc){
if(iscollision(xpos + x , ypos + y ) == true ) return callloc;
xpos += x;
ypos += y;
return callloc;
}

public boolean iscollision(int x, int y){
if(x < 0 || x > getSize().width - playerwidth ) return true;
if(y < 0 || y > groundlevel-playerheight ) return true;
return false;
}

public int playerinfrontofrock(){
int x1 = xpos;
int y1 = ypos;
int w1 = playersquatwidth;
int h1 = playersquatheight;
int x2 = 0;
int y2 = 0;
int w2 = 0;
int h2 = 0;
int[] rc = new int[numrocks];
int rccnt = 0;
for(int n = 0 ; n < numrocks ; n++){
if( rockexists[n] == true ){
x2 = rockx[n];
y2 = rocky[n];
w2 = rockwidth[n];
h2 = rockheight[n];
Rectangle rec1 = new Rectangle(x1,y1,w1,h1);
Rectangle rec2 = new Rectangle(x2,y2,w2,h2);
if( rec1.intersects(rec2) == true ) {
rc[rccnt] = n;
rccnt++;
//System.out.println("Number of rocks :"+rccnt+" rock:"+n);
}
}
}
if(rccnt > 0){
int lowest = 0;
int rockval = 0;
for ( int i = 0 ; i < rccnt ; i++ ){
//System.out.println("looping :"+i);
if( rocky[rc[i]] > lowest ){
//System.out.println("checking:"+rc[i]);
lowest = rocky[rc[i]];
rockval = rc[i];
}
}
return rockval;
}
return -1;
}

public boolean pickuprock(){
//System.out.println("pickup rock method..");
int z = playerinfrontofrock();
if(z == -1) return false;
//playercaryingrock = true;
rockbeingcarried = z;
rockdesty = ypos-rockheight[rockbeingcarried];
//System.out.println("rockdesty : " + rockdesty + " rocky " + rocky[rockbeingcarried]);
rockliftingmode = true;
rockx[rockbeingcarried] = xpos;
//rocky[rockbeingcarried] = ypos-rockheight[rockbeingcarried];
//System.out.println("Picked up " + z);
return true;
}

public boolean putrockback(){
rockx[rockbeingcarried] = xpos;
//rocky[rockbeingcarried] = groundlevel-rockheight[rockbeingcarried];
rockdesty = groundlevel-rockheight[rockbeingcarried];
rockputtingdownmode = true;
//playercaryingrock = false;
//rockbeingcarried = -1;
return true;
}

public boolean rockthrow(){
if( rockisbeingthrowed == false) return false;
if(rockgoingright){
rockthrowx += rockthrowvelx;
rockthrowvelx -= rockthrowincx;
}else{
rockthrowx -= rockthrowvelx;
rockthrowvelx -= rockthrowincx;
}
if(rockgoingup){
rockthrowy -= rockthrowvely;
rockthrowvely -= rockthrowincy;
}else{ // rockgoingdown

for(int t = 0 ; t < (int)rockthrowvely ; t++){
if( rocky[rockbeingthrowed] + rockthrowheight > groundlevel){
//System.out.println("Rock landed on gourndlevel");
rockgoingdown = false;
rocky[rockbeingthrowed] = groundlevel-rockthrowheight;
rockisbeingthrowed = false;
return true;
}
if(rocktopcollide( rockx[rockbeingthrowed] , rocky[rockbeingthrowed]+t , rocktype[rockbeingthrowed] ) == true    ) {
//System.out.println("collided rock vs rock");
rockgoingdown = false;
rockisbeingthrowed = false;
rocky[rockbeingthrowed] = rocky[rockbeingthrowed]+t;
return true;
}
}
rockthrowy += rockthrowvely;
rockthrowvely += rockthrowincy;
}
if(rockthrowvelx < 0){
rockthrowvelx = 0;
rockthrowincx = 0;
rockgoingright = false;
rockgoingleft = false;
}
if(rockthrowvely < 0 && rockgoingup){
rockthrowvely = 0;
rockgoingup = false;
rockgoingdown = true;
}

//System.out.println("velx:"+rockvelx+"vely:"+rockvely);
rockx[rockbeingthrowed] = (int)rockthrowx;
rocky[rockbeingthrowed] = (int)rockthrowy;
return true;
}

public void playercode(){

if(startsquat){
startsquat = false;
playersquated = true;
ypos += playerheight/2;
playerheight = playerheight/2;
}
if(endsquat && rockputtingdownmode == false && rockliftingmode == false){
endsquat = false;
playersquated = false;
ypos -= playerheight;
playerheight = playerheight * 2;
}

if(rockliftingmode){
rocky[rockbeingcarried]--;
if( rocky[rockbeingcarried] == rockdesty){
rockliftingmode = false;
//System.out.println("rock has been lifted up");
playercaryingrock = true;
}
}

if(rockputtingdownmode){
rocky[rockbeingcarried]++;
//System.out.println(""+rocky[rockbeingcarried]);
if(rocky[rockbeingcarried] == rockdesty){
rockputtingdownmode = false;
playercaryingrock = false;
//System.out.println("Rock has been put down.");
rockbeingcarried = -1;
}
}

if( playerputrockback ){
playerputrockback = false;
putrockback();
}

if( playerthrowrock ){
//System.out.println("In setup pf throw rock..");
playerthrowrock = false;
rockgoingdown = false;
rockgoingleft = false;
rockgoingright = false;
rockgoingup = true;
if( playerfacingright ){
rockgoingright = true;
}else{
rockgoingleft = true;
}
rockthrowvelx = 3;
rockthrowvely = 2;
rockthrowincx = .05;
rockthrowincy = .1;
rockthrowx = rockx[rockbeingcarried];
rockthrowy = rocky[rockbeingcarried];
if(rocktype[rockbeingcarried]==1){
rockthrowheight = rock1height;
}else{
rockthrowheight = rock2height;
}
rockisbeingthrowed = true;
rockbeingthrowed = rockbeingcarried;
playercaryingrock = false;
}

if(playercaryingrock && rockputtingdownmode == false){
rockx[rockbeingcarried] = xpos;
rocky[rockbeingcarried] = ypos-rockheight[rockbeingcarried];
}

if(playerpickuprock){
pickuprock();
playerpickuprock = false;
//System.out.println("player picked up rock done.");
}

if( isonrock && isjumping == false && isfalling == false){
if(playeronrock(0,1) == false ){
//System.out.println("Falling down - is not on rock");
isfalling = true;
gravity = 0;
isonrock = false;
}
}

if(playermoveright && rockputtingdownmode == false && rockliftingmode == false){
moveplayer(1,0,1);
}
if(playermoveleft && rockputtingdownmode == false && rockliftingmode == false){
moveplayer(-1,0,2);
}
if(isjumping){
gravity -= gravityinc;
for(int z = 0 ; z < gravity ; z++ ){
moveplayer(0,-1,3);
}
if( gravity <= 0 ){
isjumping = false;
isfalling = true;
gravity = 0;
//System.out.println("End of jumping");
}
}
if(isfalling){
int zz=0;
gravity += gravityinc;
for( int z = 0 ; z < gravity ; z++){
moveplayer(0,1,3);
if(iscollision(xpos,ypos+1) == true) zz=1;
if(playeronrock(0,1) == true) zz=2;
if(zz > 0){
isfalling = false;
if(zz == 2) isonrock = true;
if(zz == 1) isonrock = false;
//System.out.println("End of falling " + zz);
break;
}
}
}

}

public void run() {

for(;;) { // animation loop never ends
dorockfall();
playercode();
rockthrow();
repaint();
try {
}
catch (InterruptedException e) {
}
}

}

public void paint(Graphics g)
{

}

public boolean mouseMove(Event e, int x, int y)
{
//mouseX = x;
//mouseY = y;
//System.out.println( rocktopcollide(x,y,1) );
return true;
}

public void update(Graphics g)
{
bufferGraphics.clearRect(0,0,getSize().width,getSize().width);
bufferGraphics.setColor(Color.red);
bufferGraphics.drawString("Rocks Game Example",10,10);
bufferGraphics.drawString("Use cursor left and right and z to jump and x to crouch.",10,getSize().height-12);
bufferGraphics.drawString("Use a to pick up while crouched rock and throw.",10,getSize().height-3);

if(playersquated == false ){
bufferGraphics.drawImage(player,xpos,ypos,this);
}else{
bufferGraphics.drawImage(playersquat,xpos,ypos,this);
}
bufferGraphics.drawLine(0,groundlevel,getSize().width,groundlevel);

// draw rocks;
for(int n = 0 ; n < numrocks ; n++){
//System.out.println("locy in draw : " + rocky.get(n));
if( rocktype[n] == 1 ){
bufferGraphics.drawImage( rock1 , rockx[n] , rocky[n] , this);
}else{
bufferGraphics.drawImage( rock2 , rockx[n] , rocky[n] , this);
}
}
bufferGraphics.setColor(Color.white);
for(int i = 0; i<10 ; i++){
if (debugrect[i] == 1){
bufferGraphics.drawRect(debugrect[i],debugrect[i],debugrect[i],debugrect[i]);
}
}

g.drawImage(offscreen,0,0,this);

}

public boolean keyUp (Event e, int key){
if(key == Event.LEFT){
playermoveleft = false;
}
if(key == Event.RIGHT){
playermoveright = false;
}
if(key == 120 && isjumping == false && isfalling == false){ // x key
endsquat = true;
}
// pick up rock..
if(key == 97 && playersquated && playercaryingrock == false){ //97 . a key
playerpickuprock = true;
}
// throw rock
if(key == 97 && playersquated == false && playercaryingrock){ // a key
playerthrowrock = true;
}
// put rock back on the ground
if( key == 97 && playersquated && playercaryingrock && playerpickuprock == false){ // a key
playerputrockback = true;
//System.out.println("Put rock back on the ground..");
}

return true;
}

public boolean keyDown (Event e, int key){

// move left
if(key==Event.LEFT && playersquated == false ){
playermoveleft = true;
playermoveright = false;
playerfacingleft = true;
playerfacingright = false;
}
// move right
if(key==Event.RIGHT && playersquated == false ){
playermoveright = true;
playermoveleft = false;
playerfacingright = true;
playerfacingleft = false;

}
// squat
if(key == 120 && isjumping == false && isfalling == false && playersquated == false){ // x key // squat
startsquat = true;
}

// Jump
if(key == 122 && isjumping == false && isfalling == false){//z key / jump
if(playersquated == false ){
//System.out.println("Jump key pressed");
isjumping = true;
gravity = startingjumpspeed;
}
}
//if(debugmode) System.out.println("Key touched : " + key);
return true;
}

}

``````

## donderdag 21 april 2011

### Scrolling TileMap Example.

(Press on the Applet to activate and to generate a new map..)

``````

import java.awt.*;
import java.applet.*;
import java.awt.geom.Area;
import java.util.Random;

public class ScrollingTileMap03 extends Applet implements Runnable{
private boolean debugmode    = false;
Random r = new Random();
private int mapvisiblex;
private int mapvisibley;
private short mapwidth     = 250;
private short mapheight     = 250;
private short map[][]      = new short[ mapwidth ][ mapheight ];
private int cellwidth     = 16;
private int cellheight     = 16;
Graphics bufferGraphics;
Image bufferimage;
private double mouseX;
private double mouseY;
private boolean playerMoveRight   = false;
private boolean playerMoveLeft    = false;
private double xPos      = 0;
private double yPos      = 0;
private boolean isFalling     = false;
private boolean isJumping     = false;
private double gravity;
private boolean playerFacingLeft;
private boolean playerFacingRight  = true;
private int tileposx     = 0;
private int tileposy     = 0;
private int screenposx     = 0;
private int screenposy     = 0;
int[][] debug = new int;

public void init() {
setBackground(Color.black);
bufferimage = createImage( getSize().width , getSize().height );
bufferGraphics = bufferimage.getGraphics();
generatemap();
// find starting spot for the player
findplayerstartposition();
xPos = getSize().width / 2;
yPos = getSize().height / 2;
}

public void generatemap(){

tileposx     = 0;
tileposy     = 0;
screenposx     = 0;
screenposy     = 0;
int size      = r.nextInt(12)+4;
cellwidth     = size;
cellheight     = size;
mapvisiblex     = (int)getSize().width / cellwidth;
mapvisibley     = (int)(getSize().height / cellheight);
if(mapvisiblex > mapwidth ) mapvisiblex = mapwidth;
if(mapvisibley > mapheight ) mapvisibley = mapheight;

// erase old map
for(int y = 0 ; y < mapheight ; y++){
for(int x = 0 ; x < mapwidth ; x++){
map[x][y] = 0;
}
}

// create drunken lines
for(int lne = 0; lne < mapheight-6 ; lne += 6 )
{
int turtley=5;
int yoffset = lne;
for (int i = 0 ; i < mapwidth ; i++){
if(turtley + yoffset < mapheight - 1 && r.nextInt(10) > 8 ) turtley++;
if(turtley + yoffset > 0 && r.nextInt(10) > 8 ) turtley--;

map[i][turtley + yoffset] = 1;
if(r.nextInt(10) > 8 && i < ( mapwidth - 2 ) ) {
map[i][turtley+yoffset] = 0;
map[i+1][turtley+yoffset] = 0;
i += 1;
}
}

}

// put slopes in
int mx1=0;
int my1=0;
int mx2=0;
int my2=0;
for( int y = 0 ; y < mapheight ; y++){
for (int x = 0 ; x < mapwidth ; x++){
mx1 = x+1;
my1 = y-1;
mx2 = x;
my2 = y-1;
if(mx1 >= 0 && mx1 < mapwidth && my1 >= 0 && my1 < mapheight ){
if(mx2 >= 0 && mx2 < mapwidth && my2 >= 0 && my2 < mapheight ){
if(map[x][y] == 1 && map[mx1][my1] == 1 && map[mx2][my2] == 0){
map[mx2][my2] = 3;
}
}
}
mx1 = x-1;
my1 = y-1;
mx2 = x;
my2 = y-1;
if(mx1 >= 0 && mx1 < mapwidth && my1 >= 0 && my1 < mapheight ){
if(mx2 >= 0 && mx2 < mapwidth && my2 >= 0 && my2 < mapheight ){
if(map[x][y] == 1 && map[mx1][my1] == 1 && map[mx2][my2] == 0){
map[mx2][my2] = 2;
}
}
}

}
}

// Put a wall around the map..
for(int y = 0 ; y < mapheight ; y++){
map[y]=1;
map[ mapwidth - 1 ][y]=1;
}
for(int x = 0 ; x < mapwidth ; x++){
map[x]=1;
map[x][ mapheight - 1 ]=1;
}

}

public boolean scrollmap(int x, int y){
if(x > 0){
for(int z = 0 ; z < x ; z++){
if(tileposx == 0){
}else{

if(moveplayer(1,0,11) == true) screenposx++;
if(screenposx > cellwidth){
tileposx--;
screenposx = 0;
}
}
}
}
if(x < 0){
for(int z = 0 ; z > x ; z--){
if(tileposx + mapvisiblex == mapwidth ){
}else{

if(moveplayer(-1,0,12)==true) screenposx--;;
if(screenposx < 0) {
tileposx++;
screenposx = cellwidth;
}
}
}
}
if(y > 0){
for( int z = 0 ; z < y ; z++){
if (tileposy == 0){
}else{
screenposy++;
moveplayer(0,1,13);

if(screenposy > cellheight){
tileposy--;
screenposy = 0;
}
}
}
}
if(y < 0){
for(int z = 0 ; z > y ; z--){
if(tileposy + mapvisibley == mapheight ){
}else{
screenposy--;
moveplayer(0,-1,14);
if(screenposy < 0 ) {
tileposy++;
screenposy = cellheight;
}
}
}
}
return true;
}

public boolean moveplayer(int x,int y,int orig){
if( rectcollision(xPos+x,yPos+y)!= 0 ) {
return false;
}
xPos += x;
yPos += y;
return true;
}

public void run() {
for(;;) { // animation loop never ends

if(xPos < getSize().width / 2 ) scrollmap(1,0);
if(xPos > getSize().width / 2 ) scrollmap(-1,0);
if(yPos < getSize().height / 2 ) scrollmap(0,1);
if(yPos > getSize().height / 2 ) scrollmap(0,-1);

if(rectcollision(xPos,yPos+1)==0)
{
if(isFalling==false && isJumping==false)
{
isFalling=true;
gravity=0;
}
}
if(playerMoveRight)
{
if(rectcollision(xPos+1,yPos)==0){
scrollmap(-1,0);
moveplayer(1,0,2);;
}

if(rectcollision(xPos+1,yPos)==3)
{
moveplayer(1,-1,2);
scrollmap(1,-1);
}
}
if(playerMoveLeft)
{
if(rectcollision(xPos-1,yPos)==0){
scrollmap(1,0);
moveplayer(-1,0,3);
}

if(rectcollision(xPos-1,yPos)==2)
{
moveplayer(-1,-1,3);
scrollmap(-1,-1);
}
}

if(isJumping)
{
gravity = gravity - .1;
if(gravity < 0){
isJumping=false;
isFalling=true;

}
for(int z = 0 ; z < Math.abs(gravity) ; z++){
if(rectcollision(xPos,yPos-1)==0){
moveplayer(0,-1,4);
}else{
isJumping=false;
isFalling=true;
break;
}
}
}
if(isFalling)
{

gravity = gravity + .1;
for(int z = 0 ; z < gravity ; z++){
if(rectcollision(xPos,yPos+1)==0){
moveplayer(0,1,5);
scrollmap(0,-1);
}else{
isFalling = false;
break;
}
}
}

repaint();
try {
}
catch (InterruptedException e) {
}
}
}

public short rectcollision(double x,double y)
{
for(int i = 0 ; i<100 ; i++ ){
debug[i]=0;
}
int chkx=(int)x/cellwidth+tileposx;
int chky=(int)y/cellheight+tileposy;
int x1=(int)(x);
int y1=(int)(y);
int cnt=0;
for(int y2=-1;y2<3;y2++)
{
for(int x2=-1;x2<3;x2++)
{
if (chkx+x2>=0 && chkx + x2 < mapwidth && chky+y2>=0 && chky+y2 < mapheight)
{

if(map[chkx+x2][chky+y2]==2)
{
int x3=((chkx-tileposx)+x2)*cellwidth+screenposx;
int y3=((chky-tileposy)+y2)*cellheight+screenposy;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
int[] XArray = {x3,x3,x3+cellwidth};
int[] YArray = {y3,y3+cellheight,y3+cellheight};
int[] XArray2= {x1,x1+cellwidth,x1+cellwidth,x1};
int[] YArray2= {y1,y1,y1+cellheight,y1+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);
Polygon abc2= new Polygon(XArray2,YArray2,4);
Area a1 = new Area(abc);
Area a2 = new Area(abc2);
if(debugmode){
debug[cnt]=1;
debug[cnt]=x3;
debug[cnt]=y3;
debug[cnt]=cellwidth;
debug[cnt]=cellheight;
cnt++;
debug[cnt]=1;
debug[cnt]=x1;
debug[cnt]=y1;
debug[cnt]=cellwidth;
debug[cnt]=cellheight;
cnt++;
}
a1.intersect(a2);
if (!a1.isEmpty())
{
return 2;
}

}
}

if(map[chkx+x2][chky+y2]==3)
{
int x3=((chkx-tileposx)+x2)*cellwidth+screenposx;
int y3=((chky-tileposy)+y2)*cellheight+screenposy;

Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
int[] XArray = {x3,x3+cellwidth,x3+cellwidth};
int[] YArray = {y3+cellheight,y3+cellheight,y3};
int[] XArray2= {x1,x1+cellwidth,x1+cellwidth,x1};
int[] YArray2= {y1,y1,y1+cellheight,y1+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);
Polygon abc2= new Polygon(XArray2,YArray2,4);
Area a1 = new Area(abc);
Area a2 = new Area(abc2);
if(debugmode){
debug[cnt]=1;
debug[cnt]=x3;
debug[cnt]=y3;
debug[cnt]=cellwidth;
debug[cnt]=cellheight;
cnt++;
debug[cnt]=1;
debug[cnt]=x1;
debug[cnt]=y1;
debug[cnt]=cellwidth;
debug[cnt]=cellheight;
cnt++;
}
a1.intersect(a2);
if (!a1.isEmpty())
{
return 3;
}

}
}

if (map[chkx+x2][chky+y2]==1)
{
int x3=((chkx-tileposx)+x2)*cellwidth+screenposx;
int y3=((chky-tileposy)+y2)*cellheight+screenposy;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(debugmode){
debug[cnt]=1;
debug[cnt]=x3;
debug[cnt]=y3;
debug[cnt]=cellwidth;
debug[cnt]=cellheight;
cnt++;
debug[cnt]=1;
debug[cnt]=x1;
debug[cnt]=y1;
debug[cnt]=cellwidth;
debug[cnt]=cellheight;
cnt++;
}
if(rec1.intersects(rec2))
{
return 1;
}
}
}
}
}
return 0;
}

public void update (Graphics g)
{
bufferGraphics.clearRect(0, 0, getSize().width , getSize().height );
bufferGraphics.setColor (Color.white);
int drawx = 0;
int drawy = 0;
int mx = 0;
int my = 0;

for(int y=-1;y < mapvisibley + 1 ;y++){
for(int x=-1;x < mapvisiblex + 1;x++){
drawx = x*cellwidth+screenposx;
drawy = y*cellheight+screenposy;
mx = x + tileposx;
my = y + tileposy;
if(mx >= 0 && mx < mapwidth && my >= 0 && my < mapheight ){
if(map[mx][my]==1)
{
bufferGraphics.fillRect(drawx,drawy,cellwidth,cellheight);
}
if(map[mx][my]==2)
{
int[] XArray = {drawx,drawx,drawx+cellwidth};
int[] YArray = {drawy,drawy+cellheight,drawy+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);

bufferGraphics.fillPolygon(abc);
}
if(map[mx][my]==3)
{
int[] XArray = {drawx,drawx+cellwidth,drawx+cellwidth};
int[] YArray = {drawy+cellheight,drawy+cellheight,drawy};
Polygon abc = new Polygon(XArray, YArray, 3);

bufferGraphics.fillPolygon(abc);
}
}
}
}
bufferGraphics.setColor(Color.black);
bufferGraphics.fillRect(3,getSize().height - 30 , getSize().width , 12);
bufferGraphics.setColor(Color.white);
bufferGraphics.drawString("Scrolling platformer example - z = jump - Cursors l and r",3,getSize().height - 20 );
int x = (int) xPos;
int y = (int) yPos;

// This is the player graphic
bufferGraphics.fillOval (x, y, cellwidth, cellheight);

if(debugmode){
bufferGraphics.setColor(Color.blue);
for(int i=0; i < 100 ; i++){
if(debug[i] == 1){
bufferGraphics.drawRect(debug[i],debug[i],debug[i],debug[i]);
}
}
}

g.drawImage(bufferimage,0,0,this);
}

public void paint(Graphics g) {
}

public boolean mouseMove(Event e, int x, int y)
{
mouseX = x;
mouseY = y;
return true;
}

public boolean keyUp (Event e, int key){
if(key==114)  // r key
{
xPos = 150;
yPos = 150;
}
if(key==Event.LEFT)
{
playerMoveLeft = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = false;
}

return true;

}

public boolean keyDown (Event e, int key){

if(key==Event.LEFT)
{
playerMoveLeft = true;
playerFacingLeft = true;
playerFacingRight = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = true;
playerFacingRight = true;
playerFacingLeft = false;
}

if(key==122) // z key
{
if(isFalling==false && isJumping==false)
{
if(rectcollision(xPos,yPos-3)==0){
isJumping = true;
gravity = 3;
}
}
}

if(key==100 && debugmode){ // d key
generatemap();
}
return true;
}

public void findplayerstartposition()
{
while(rectcollision(xPos,yPos)!= 0 ){
xPos = r.nextInt( getSize().width - 50 ) + 50;
yPos = r.nextInt( getSize().height - 50 ) + 50;
}

}
public boolean mouseUp (Event e, int x, int y)
{
generatemap();
findplayerstartposition();
return true;
}

}
``````

### FloodFill example

I got stack overflow error messages when I was testing the simple recursive flood fill method so I used a floodfill method that uses two lists. It is more code but it gives no error.

``````

import java.awt.*;
import java.applet.*;
import java.util.ArrayList;

public class FloodFill01 extends Applet {

int mapwidth   = 100;
int mapheight   = 100;
int cellwidth   = 0;
int cellheight   = 0;
int[][] map   = new int[ mapwidth ][ mapheight ];

public void init() {
// I tried placing these lines in the main class but it
// did not work...
cellwidth   = getSize().width/100;
cellheight   = getSize().height/100;
// make a line on the map
for(int x=0;x<50;x++){
map[x]=1;
}
// make another line on the map
for(int y=50;y<100;y++){
map[y]=1;
}
// floodfill the map
FloodFill(10,10);
}

public void paint(Graphics g) {
g.drawString("FloodFill example..", 50, getSize().height-5 );
for(int y = 0 ; y < mapheight ; y++){
for(int x = 0 ; x < mapwidth ; x++){
if(map[x][y]==1) g.fillRect(x*cellwidth,y*cellheight,cellwidth,cellheight);
}
}

}

public boolean FloodFill(int x, int y){
// with these arraylists we store and process the unflooded
ArrayList< Integer > x1 = new ArrayList< Integer >();
ArrayList< Integer > y1 = new ArrayList< Integer >();
ArrayList< Integer > x2 = new ArrayList< Integer >();
ArrayList< Integer > y2 = new ArrayList< Integer >();
// add start location to x1 list 1
boolean doloop=true;
// Here we flood the map
while (doloop){
// find new fill spaces..
for(int i=0 ; i < x1.size() ;i++){
for(int y3 = -1 ; y3 < 2 ; y3++){
for(int x3 = -1 ; x3 < 2 ; x3++){
int xtemp = x1.get(i);
int ytemp = y1.get(i);
if(xtemp + x3 >= 0 && xtemp + x3 < mapwidth){
if(ytemp + y3 >=0 && ytemp + y3 < mapheight){
if(map[ xtemp + x3 ][ ytemp + y3 ] == 0 ){
map[ xtemp + x3 ][ ytemp + y3 ]=1;
}}}
}}}
// If there are no 0'ss left then stop loop by modyfing doloop variable
if( x2.size() == 0 ) doloop=false;
// erase old list
x1.clear();
y1.clear();
// copy list 2 into list 1
for (int ii = 0 ; ii < x2.size() ; ii++){
}
// erase list 2
x2.clear();
y2.clear();

}

return true;
}

}

``````

### ArrayList that can hold Integers.

I could not figure out how to use integers and arraylists. I was using arrays instead.

below a example of how to use arraylists with integers.

``````
import java.awt.*;
import java.applet.*;
import java.util.ArrayList;

public class intarraylist03 extends Applet {

public void init() {
ArrayList< Integer > list=new ArrayList< Integer >();
int arr1[]={11,12,13,14,15};
for (int i = 0; i < arr1.length; i++) {
}
for (int i = 0; i < arr1.length; i++) {
System.out.println((i+1)+" : "+(list.get(i)+10));
}
}

public void paint(Graphics g) {

g.drawString("Welcome to Java!!", 50, 60 );

}
}
``````

### Maze Generator Example - (Ported code).

(Click on the applet to create new maze)

I ported the code from another language. I think there might be bugs since I think I have seen mazes that have errors in them. I still have to spend more time studying this.

Anyways I have already used the maze maps to create 3d levels.

Below is the sourcecode.

``````

import java.awt.*;
import java.applet.*;
import java.util.Random;

public class MazeGenerator01 extends Applet {

int SizeX = 32;
int SizeY = 32;
private short[][] map = new short[ SizeX ][ SizeY ];
Random r = new Random();

public void init() {
generatemaze(r.nextInt(70)+30);
}

public boolean mouseUp( Event evt, int x, int y)
{
generatemaze(r.nextInt(70)+30);
repaint();
return true;
}

public void paint(Graphics g) {

g.drawString("Press mouse in Applet to create new maze", 0, getSize().height-12 );
for(int x=0;x<32;x++)
{
for(int y=0;y<32;y++)
{
if(map[x][y]==4)
{
g.fillRect(x*10,y*7,10,7);
}
}
}
}

public void generatemaze(int straightness)
{
// Maze Generator original by John Chase
short Wall     = 4;
short Flr     = 5;
int NotChecked    = 0;
int Checked    = 1;
int Open          = 2;
int NotOpen       = 3;
int AllChecked    = SizeX * SizeY;
int LastDirection   = r.nextInt(4);
int North         = Open;
int South         = Open;
int East          = Open;
int West          = Open;
boolean TimeUp     = false;
boolean Moved   = false;
int NumFailedMoves   = 0;
boolean ChangeDirection = false;
boolean tocheckdirection= false;
int CurrentX   = 0;
int CurrentY   = 0;
int Dir     = 0;
long LastDrawTimer  = 0;
boolean Done   = false;
//make map array fill with walls
for(int x=0;x < SizeX - 1 ; x++ )
{
for(int y=0;y < SizeY - 1 ; y++ )
{
map[x][y] = Wall;
}
}

//pick a random cell and mark it as Flr hold in 1 cell from the edge
CurrentX = r.nextInt( SizeX - 3 ) + 2;
CurrentY = r.nextInt( SizeY - 3 ) + 2;

while(TimeUp != true)
{
if(tocheckdirection!=true)
{

//pick a direction
Moved = false;
NumFailedMoves = 0;
ChangeDirection = true;

//check strightness factor
//otherwise random percent chance
if(r.nextInt(100) < straightness)
{
ChangeDirection = false;
Dir = LastDirection;
}

//keep trying till you find a direction open
while(Moved != true)//Repeat
{
//pick a direction to move at random
if(ChangeDirection == true)
{
Dir = r.nextInt(4);//see here for bugs
LastDirection = Dir;
}

ChangeDirection = true;

switch(Dir)
{
//north
case 0:
if(North == Open)
{
Moved = true;
CurrentY--;
}
break;
//south
case 1:
if(South == Open)
{
Moved = true;
CurrentY++;
}
break;
//east
case 2:
if(East == Open)
{
Moved = true;
CurrentX++;
}
break;
//West
case 3:
if(West == Open)
{
Moved = true;
CurrentX--;
}
break;
}

}//Until Moved = True
//mark the map
map[CurrentX][CurrentY] = Flr;
LastDrawTimer = System.currentTimeMillis();
}

tocheckdirection = false;
//step 3 from current cell check N,S,E,W in a random style
//first set all direction Direction checked
North = NotOpen;
South = NotOpen;
East  = NotOpen;
West  = NotOpen;

//check all 4 directions
//;north
//;out of bounds?
if(CurrentY-2 < 0)
{
North = NotOpen;
}
else if(map[CurrentX][CurrentY-1] == Wall && map[CurrentX][CurrentY-2] == Wall)
{
if(map[CurrentX-1][CurrentY-1] == Wall && map[CurrentX+1][CurrentY-1] == Wall)
{
North = Open;
}
else
{
North = NotOpen;
}
}

//south
//out of bounds?
if(CurrentY+2 > SizeY - 1 )
{
South = NotOpen;
}
else if(map[CurrentX][CurrentY+1] == Wall && map[CurrentX][CurrentY+2] == Wall)
{
if(map[CurrentX-1][CurrentY+1] == Wall && map[CurrentX+1][CurrentY+1] == Wall)
{
South = Open;
}
else
{
South = NotOpen;
}
}
//;east
if(CurrentX+2 > SizeX - 1 )
{
East = NotOpen;
}
else if(map[CurrentX+1][CurrentY] == Wall && map[CurrentX+2][CurrentY] == Wall )
{
if(map[CurrentX+1][CurrentY-1] == Wall && map[CurrentX+1][CurrentY+1] == Wall)
{
East = Open;
}
else
{
East = NotOpen;
}
}
//west
//out of bounds?
if(CurrentX-2 < 0)
{
West = NotOpen;
}
else if(map[CurrentX-1][CurrentY] == Wall && map[CurrentX-2][CurrentY] == Wall)
{
if(map[CurrentX-1][CurrentY-1] == Wall && map[CurrentX-1][CurrentY+1]== Wall)
{
West = Open;
}
else
{
West = NotOpen;
}
}

//;if time passes without finding anything we are done
if( System.currentTimeMillis() - LastDrawTimer > 100 ) TimeUp = true;
//now what happens if all directions are not open
if(North == NotOpen && South == NotOpen && East == NotOpen && West == NotOpen && TimeUp == false)
{
Done = false;
//pick a random already floored location and try again
while(Done !=true)
{
CurrentX = r.nextInt( SizeX - 2 ) + 1;
CurrentY = r.nextInt( SizeY - 2 ) + 1;
if(map[CurrentX][CurrentY] == Flr) Done = true;
}
//goto checkdirection
tocheckdirection=true;
}

}

}

}
``````

### Midpoint displacement algorithm example

(Click on the applet screen to generate new midpoint graphic.)

I used this code to generate isometric maps. I converted it to Java.

In Paint.net and maybe other drawing programs like Gimp this kind of graphics is called Clouds.
``````

import java.awt.*;
import java.applet.*;
import java.util.Random;

public class MidPoint01 extends Applet {

// In this array the drawing will be made and stored
int[][] map = new int;
// use r.nextInt() in the code for random numbers
Random r = new Random();

public void init() {
// When starting up do the midpoint drawing one time
domidpoint();
}

// Here the midpoint code begins.
public void domidpoint(){
// Erase the old map array..
for(int y=0;y<100;y++){
for(int x=0;x<100;x++){
map[x][y]=0;
}
}
// Setup points in the 4 corners of the map.
map = 128;
map = 128;
map = 128;
map = 128;
// Do the midpoint
midpoint(0,0,99,99);
}

// This is the actual mid point displacement code.
public boolean midpoint(int x1,int y1, int x2, int y2 ){
//  If this is pointing at just on pixel, Exit because
//  it doesn't need doing}
if(x2-x1<2 && y2-y1<2) return false;

// Find distance between points and
// use when generating a random number.
int dist=(x2-x1+y2-y1);
int hdist=dist / 2;
// Find Middle Point
int midx=(x1+x2) / 2;
int midy=(y1+y2) / 2;
// Get pixel colors of corners
int c1=map[x1][y1];
int c2=map[x2][y1];
int c3=map[x2][y2];
int c4=map[x1][y2];

// If Not already defined, work out the midpoints of the corners of
// the rectangle by means of an average plus a random number.
if(map[midx][y1]==0) map[midx][y1]=((c1+c2+r.nextInt(dist)-hdist) / 2);
if(map[midx][y2]==0) map[midx][y2]=((c4+c3+r.nextInt(dist)-hdist) / 2);
if(map[x1][midy]==0) map[x1][midy]=((c1+c4+r.nextInt(dist)-hdist) / 2);
if(map[x2][midy]==0) map[x2][midy]=((c2+c3+r.nextInt(dist)-hdist) / 2);

// Work out the middle point...
map[midx][midy] = ((c1+c2+c3+c4+r.nextInt(dist)-hdist) / 4);

// Now divide this rectangle into 4, And call again For Each smaller
// rectangle
midpoint(x1,y1,midx,midy);
midpoint(midx,y1,x2,midy);
midpoint(x1,midy,midx,y2);
midpoint(midx,midy,x2,y2);

return true;
}

public boolean mouseUp( Event evt, int x, int y)
{
// redraw the applet with a new midpoint graphic each mouseclick.
domidpoint();
repaint();
return true;
}

public void paint(Graphics g) {

int x1=(getSize().width/2)-100;
int y1=(getSize().height/2)-100;

for(int y=0;y<100;y++){
for(int x=0;x<100;x++){
g.setColor(new Color(map[x][y],map[x][y],map[x][y]));
g.fillRect(x*2+x1,y*2+y1,2,2);
}
}

}
}
``````

## dinsdag 19 april 2011

### Map Generator using a BushFire method.

(Click on the applet to create a new map..)

Above a example of a generated map. I was looking into this and found a webite that showed a example of how BushFires burn the surface. The result looked like usable maps. What the code does is it marks a number of points in a array as 2 and loops a number of times through the map and selects the squares around and decides if they will catch fire based on a random percentage. The old 2 is set to 0 and the loop continues.

The maps surfaces do not connect yet so I have to do some work before I can use them for platformer levels.

Below the code.

``````

import java.awt.*;
import java.applet.*;
import java.util.Random;

public class BushFireMap02 extends Applet {

int[][] map = new int;
Random r = new Random();

public void init() {
makemap(0,0,r.nextInt(10)+15,r.nextInt(20)+60,80);
}

public void makemap(int x1,int y1, int numfires, int burncycles, int chanceofburning)
{
//System.out.println("" + numfires + "," + burncycles + ","+chanceofburning);
for(int y=0;y<100;y++){
for(int x=0;x<100;x++){
map[x][y]=1;
}
}
// number of fires
for(int an=0;an < numfires ;an++){
map[r.nextInt(90)+5][r.nextInt(90)+5]=2;
}

// do the burn loop
for(int burned=0;burned < burncycles ; burned++){
for(int y=0;y<100;y++){
for(int x=0;x<100;x++){
// if fire on map location
if(map[x][y]==2){
//ignite around if tree there and random met
if(x-1 >= 0){
if(map[x-1][y]==1 && r.nextInt(100) > chanceofburning){
map[x-1][y]=2;
map[x][y]=0; // turn off fire
}
}
if(y-1 >= 0){
if(map[x][y-1]==1 && r.nextInt(100) > chanceofburning){
map[x][y-1]=2;
map[x][y]=0;
}
}
if(x+1 < 100){
if(map[x+1][y]==1 && r.nextInt(100) > chanceofburning){
map[x+1][y]=2;
map[x][y]=0;
}
}
if(y+1 < 100){
if(map[x][y+1]==1 && r.nextInt(100) > chanceofburning){
map[x][y+1]=2;
map[x][y]=0;
}
}

}
}
}

}
}

public boolean mouseUp( Event evt, int x, int y)
{
makemap(0,0,r.nextInt(10)+15,r.nextInt(20)+60,80);
repaint();
return true;
}

public void paint(Graphics g) {

//g.drawString("Welcome to Java!!", 50, 60 );
int w,h;
w=getSize().width/100;
h=getSize().height/100;
for (int y=0;y<100;y++){
for (int x=0;x<100;x++){
if(map[x][y]==1){
g.fillRect(x*w,y*h,w,h);
}
}
}
}
}
``````

## maandag 18 april 2011

### Creating and rotating a image with double buffering.

Here a example of how to rotate a image. The example code has a thread that rotates a image and draws the original image and the rotated image on the buffer that then gets drawn to the appet.

I was suprised that the rotating is so fast since the other language that I used could not rotate images in realtime.

``````
import java.awt.geom.AffineTransform;
import java.applet.*;
import java.awt.event.*;
import java.awt.*;

public class rotateimage01 extends Applet implements Runnable
{
Graphics bufferGraphics;
Image offscreen;
Image image2;
int im2angle=0;

public void init()
{
setBackground(Color.black);
offscreen = createImage(getSize().width,getSize().height);
bufferGraphics = offscreen.getGraphics();

image2 = createImage(32,32);
Graphics test = image2.getGraphics();
test.setColor(Color.red);
test.fillRect(0,0,32,32);
}

public void run() {

for(;;) { // animation loop never ends
im2angle++;
if(im2angle>360) im2angle=0;
repaint();
try {
} catch (InterruptedException e) {
}
}
}

public void paint(Graphics g)
{
bufferGraphics.clearRect(0,0,getSize().width,getSize().width);
bufferGraphics.setColor(Color.red);
bufferGraphics.drawString("Rotate Image Example",10,10);
// I have no idea if recreating this section slows down
// the program. maybe it should be done different.
Graphics2D  graphics = (Graphics2D) offscreen.getGraphics();
graphics.drawImage(image2, 60, 60, this);
graphics.dispose();

bufferGraphics.drawImage(image2,10,20,this);
g.drawImage(offscreen,0,0,this);

}

public void update(Graphics g)
{
paint(g);
}

}

``````

### Modifying / Editing polygons in stead of creating new polygons.

I was recreating polygons in my programs and read that that might slow down the performance so I looked up how to modify / edit polygons.

See example of how this can be done below.

``````

import java.awt.*;
import java.applet.*;

public class changepolygonpoints extends Applet {

public void init() {
}

public void paint(Graphics g) {

g.drawString("Modifying polygons", 50, 60 );

Polygon p = new Polygon(new int[]{100,100,150},new int[]{100,200,150},3);

g.drawPolygon(p);

//loop through the x array of the polygon
for(int x=0;x < p.npoints ; x++)
{
p.xpoints[x] = p.xpoints[x]+100;
}
g.drawPolygon(p);

}
}

``````

## zondag 17 april 2011

### Looking through planet source code

I had not really checked planet source code for java code but I am now and there are a couple of good examples there.

### Found a lot of Java Game source code on java4k.com

I did a site search with google and found a whole bunch of sourcecode.

The google search instructions I did were : site:www.java4k.com/  import

This resulted in a results page with 22 pages with game sourcecode that I can study and use with google desktop search.

### Getting Left and Right and Middle mouse buttons.

(Above is an Applet that informs you what mouse button was pressed.)

I was able to find an example of how to read the mouse buttons in Java and now know how to do it. Below some example code of how it can be done..

``````

import java.awt.*;
import java.applet.*;

public class MouseButton01 extends Applet {
String info="Press one of the mouse buttons in the applet";
public void init() {
}

public void paint(Graphics g) {

g.drawString(""+info, 50, 60 );

}
public boolean mouseDown (Event e, int x, int y) {
info=("Right Button Pressed");
} else if (e.modifiers == Event.ALT_MASK) {
info=("Middle Button Pressed");
} else {
info=("Left Button Pressed");
}
repaint();
return true;
}

}

``````

### Linked Lists to store classes into - Example

The applet above uses Linked Lists to store classes into. I think I remember that being called instances of classes? I have no idea if when you remove a linkedlist item from the List if then the class is closed to.

I was looking through the java source code that I downloaded in the last few weeks. I discovered that I downloaded a Dijkstra path finding example and was studying how it uses open and closed lists. I was working on a path finding example and could not figure out how to do the open and closed lists. I see that Java has Linked Lists. .

Below are several lines of code the I think are needed for setting up the linked lists.

//Placed in the main class

//Placed in the init() part

//Usage
openlist.remove(best) ;

I have gotten it working. I can add classes to a linked list and remove them to. I also took a look at Lists that Java has but I could not get it working with classes.

I have no idea if this is the best way to create the sprites and particles ect.. in Java. I found a tutorial and found it uses regular arrays to store sprite classes in but arrays can not be resized. Linked Lists can have their contents removed and added to. I also found the Lists feature but do not understand it yet.

Below is the source code of the example applet.

``````

import java.awt.*;
import java.applet.*;
import java.util.Random;

public class ListTest02 extends Applet {

Random r1 = new Random();

public void init()
{
for(int i = 0 ; i <= 30 ; i++){
}
// Test removing of item from linked list.
enemies.remove(0);
}

public void paint(Graphics g)
{

g.drawString("Welcome to Java!!", 50, 60 );

theEnemies theenemies;
for (int i = 0 ; i < enemies.size();i++) {
theenemies = (theEnemies)enemies.get(i);
g.drawRect(theenemies.getx(),theenemies.gety(),32,32);
}

}

class theEnemies
{
private int x;
private int y;
private int w;
private int h;
public theEnemies(int x1,int y1)
{
x=x1;
y=y1;
}
public int getx()
{
return x;
}
public int gety()
{
return y;
}
}

}

``````

### Slopes Tilemap Platformer Example

(Press mouse into applet window and use cursor left and right to move and x to jump)

I have gotten to understand that slopes are the triangular block shapes in platform games. I tried to program the triangular block types into a platformer before a couple of years ago but it was to difficult. Yesterday I managed to get the slopes working with the game character. The code (below) is maybe a bit big for such a small example but that was caused becourse I had difficulties getting it worrking.
There are a number of debugging routines in the update method that I used to find when a collision was occuring.

I used area collision for finding the collision between the player and the slopes. I check a series of blocks around the player for rectangular collision before going into area collision.

``````

import java.awt.*;
import java.applet.*;
import java.awt.geom.Area;

public class SlopesPlatformer extends Applet implements Runnable{

// This is the drawn map; 1 = redblock
private short map[][]={
{1,1,1,1,1,1,1,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,0,0,0,0,0,2,1,1,1,1,1},
{1,0,0,0,0,0,0,0,2,1,1,1,1},
{1,0,0,1,0,0,0,0,0,1,1,1,1},
{1,0,0,1,0,0,0,0,0,1,1,1,1},
{1,0,0,1,0,0,0,0,3,1,1,1,1},
{1,0,0,0,0,0,0,3,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,0,0,0,0,0,1,1,1,1,1,1},
{1,0,0,0,0,0,0,2,1,1,1,1,1},
{1,0,0,0,0,0,0,0,2,1,1,1,1},
{1,0,0,0,0,0,0,0,0,2,1,1,1},
{1,0,0,0,0,0,0,0,0,0,2,1,1},
{1,0,0,0,0,0,0,0,0,0,0,2,1},
{1,0,0,0,0,0,0,1,0,0,0,0,1},
{1,0,0,0,0,0,0,1,0,0,0,0,1},
{1,0,0,0,0,0,0,1,0,0,0,0,1},
{1,0,0,0,0,0,0,1,0,0,0,0,1},
{1,1,1,1,1,1,1,1,1,1,1,1,1}
};

private short cellwidth=16;
private short cellheight=16;
private short mapheight = 13;
private short mapwidth = 20;
Graphics bufferGraphics;
Image bufferimage;
Graphics debugGraphics;
Image debugimage;
private double mouseX;
private double mouseY;
private boolean playerMoveRight = false;
private boolean playerMoveLeft = false;
private double xPos=20;
private double yPos=96;
private boolean isFalling = false;
private boolean isJumping = false;
private double gravity;
private double groundLevel = 100;
private boolean playerFacingLeft;
private boolean playerFacingRight=true;
private boolean moverightup = false;
private boolean moveleftup = false;
private int mousecol=0;

public void init() {
setBackground(Color.black);
bufferimage = createImage(getSize().width,getSize().height);
bufferGraphics = bufferimage.getGraphics();
debugimage = createImage(getSize().width,getSize().height);
debugGraphics = debugimage.getGraphics();

}

public void run() {
for(;;) { // animation loop never ends
mousecol=0;
if(rectcollision(xPos,yPos+1)==0)
{
if(isFalling==false && isJumping==false)
{
System.out.print("Off the ground,");
isFalling=true;
gravity=0;
}
}
if(playerMoveRight)
{
if(rectcollision(xPos+1,yPos)==0)xPos++;
if(rectcollision(xPos+1,yPos)==3)
{
xPos++;
yPos--;
}
}
if(playerMoveLeft)
{
if(rectcollision(xPos-1,yPos)==0)xPos--;
if(rectcollision(xPos-1,yPos)==2)
{
yPos--;
xPos--;
}
}

if(isJumping)
{
yPos = (int)yPos - gravity;
gravity = gravity - .1;
if(gravity<0 || rectcollision(xPos,yPos-1)!=0)
{
isJumping=false;
isFalling=true;
}
}
if(isFalling)
{
yPos = (int)yPos + gravity;
gravity = gravity + .1;
if(rectcollision(xPos,yPos)!=0)
{
System.out.print("collided. ending gravity");
isFalling = false;
//yPos = (yPos/32)*32;
while(rectcollision(xPos,yPos)!=0)
{
yPos--;
}
gravity=0;
}
}

repaint();
try {
}
catch (InterruptedException e) {
}
}
}

public short rectcollision(double x,double y)
{
int chkx=(int)x/cellwidth;
int chky=(int)y/cellheight;

for(int y2=-1;y2<3;y2++)
{
for(int x2=-1;x2<3;x2++)
{
if (chkx+x2>=0 && chkx+x2 < mapwidth && chky+y2>=0 && chky+y2 < mapheight)
{

if(map[chkx+x2][chky+y2]==2)
{
int x1=(int)x;
int y1=(int)y;
int x3=(chkx+x2)*cellwidth;
int y3=(chky+y2)*cellheight;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
mousecol=2;
int[] XArray = {x3,x3,x3+cellwidth};
int[] YArray = {y3,y3+cellheight,y3+cellheight};
int[] XArray2= {x1,x1+cellwidth,x1+cellwidth,x1};
int[] YArray2= {y1,y1,y1+cellheight,y1+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);
Polygon abc2= new Polygon(XArray2,YArray2,4);
Area a1 = new Area(abc);
Area a2 = new Area(abc2);

a1.intersect(a2);
if (!a1.isEmpty())
{
//System.out.print("collided with tile 3");
return 2;
//g.drawString("Two Polygons collided", 20, 20 );
}

}
}

if(map[chkx+x2][chky+y2]==3)
{
int x1=(int)x;
int y1=(int)y;
int x3=(chkx+x2)*cellwidth;
int y3=(chky+y2)*cellheight;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
mousecol=3;
int[] XArray = {x3,x3+cellwidth,x3+cellwidth};
int[] YArray = {y3+cellheight,y3+cellheight,y3};
int[] XArray2= {x1,x1+cellwidth,x1+cellwidth,x1};
int[] YArray2= {y1,y1,y1+cellheight,y1+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);
Polygon abc2= new Polygon(XArray2,YArray2,4);
Area a1 = new Area(abc);
Area a2 = new Area(abc2);

a1.intersect(a2);
if (!a1.isEmpty())
{
//System.out.print("collided with tile 3");
return 3;
//g.drawString("Two Polygons collided", 20, 20 );
}

}
}

if(map[chkx+x2][chky+y2]==2)
{
int x1=(int)x;
int y1=(int)y;
int x3=(chkx+x2)*cellwidth;
int y3=(chky+y2)*cellheight;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
//System.out.print("collided with tile 2");

}
}
if (map[chkx+x2][chky+y2]==1)
{
int x1=(int)x;
int y1=(int)y;
int x3=(chkx+x2)*cellwidth;
int y3=(chky+y2)*cellheight;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
return 1;
}
}
}
}
}
return 0;
}

public short mapcollision(double x,double y)
{
int[] XArray = {20, 160, 120, 160, 20, 60};
int[] YArray = {20, 20, 90, 160, 160, 90};
int[] XArray2 = {20, 160, 120, 160, 20, 60};
int[] YArray2 = {20, 20, 90, 160, 160, 90};

Polygon abc = new Polygon(XArray, YArray, 6);
Polygon abc2= new Polygon(XArray2,YArray2,6);
//g.drawPolygon(abc);
//g.drawPolygon(abc2);

Area a1 = new Area(abc);
Area a2 = new Area(abc2);

a1.intersect(a2);
if (!a1.isEmpty())
{
//g.drawString("Two Polygons collided", 20, 20 );
}
return 0;
}

public void update (Graphics g)
{
bufferGraphics.clearRect(0, 0, getSize().width,getSize().height);
bufferGraphics.setColor (Color.white);
for(int y=0; y < mapheight ;y++){
for(int x=0; x < mapwidth ;x++){
if(map[x][y]==1)
{
bufferGraphics.fillRect(x*cellwidth,y*cellheight,cellwidth,cellheight);
}
if(map[x][y]==2)
{
int[] XArray = {x*cellwidth,x*cellwidth,x*cellwidth+cellwidth};
int[] YArray = {y*cellheight,y*cellheight+cellheight,y*cellheight+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);

bufferGraphics.fillPolygon(abc);
}
if(map[x][y]==3)
{
int[] XArray = {x*cellwidth,x*cellwidth+cellwidth,x*cellwidth+cellwidth};
int[] YArray = {y*cellheight+cellheight,y*cellheight+cellheight,y*cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);

bufferGraphics.fillPolygon(abc);
}

}
}

bufferGraphics.drawString("Slopes platformer example - x - jump - cursors l and r",3,getSize().height-20);
bufferGraphics.drawString("moveleftup:"+moveleftup+" moverightup:"+moverightup,3,getSize().height-10);
bufferGraphics.drawString("mousecol :"+mousecol,3,getSize().height-5);

int x = (int) xPos;
int y = (int) yPos;
bufferGraphics.fillOval (x, y, cellwidth, cellheight);
//if(mouseY<100)
//{

x=(int)xPos;
y=(int)yPos;
int chkx=(int)x/cellwidth;
int chky=(int)y/cellheight;

for(int y2=-1;y2<3;y2++)
{
for(int x2=-1;x2<3;x2++)
{
if (chkx+x2>=0 && chkx+x2 < mapwidth && chky+y2>=0 && chky + y2 < mapheight )
{
if(map[chkx+x2][chky+y2]==1)
{
int x1=(int)x;
int y1=(int)y;
int x3=(chkx+x2)*cellwidth;
int y3=(chky+y2)*cellheight;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
bufferGraphics.setColor(Color.yellow);
bufferGraphics.drawRect(rec1.x,rec1.y,rec1.width,rec1.height);
bufferGraphics.drawRect(rec2.x,rec2.y,rec2.width,rec2.height);
if(rec1.intersects(rec2))
{
// return 1;
}
}
if(map[chkx+x2][chky+y2]==3)
{

int x1=(int)x;
int y1=(int)y;
int x3=(chkx+x2)*cellwidth;
int y3=(chky+y2)*cellheight;
Rectangle rec1 = new Rectangle(x1,y1,cellwidth,cellheight);
Rectangle rec2 = new Rectangle(x3,y3,cellwidth,cellheight);
if(rec1.intersects(rec2))
{
//stem.out.print("yeah");
mousecol=3;
int[] XArray= {x3,x3+cellwidth,x3+cellwidth};
int[] YArray= {y3+cellheight,y3+cellheight,y3};
int[] XArray2= {x1,x1+cellwidth,x1+cellwidth,x1};
int[] YArray2= {y1,y1,y1+cellheight,y1+cellheight};
Polygon abc = new Polygon(XArray, YArray, 3);
Polygon abc2= new Polygon(XArray2,YArray2,4);
bufferGraphics.setColor(Color.yellow);
bufferGraphics.fillPolygon(abc);
bufferGraphics.fillPolygon(abc2);
Area a1 = new Area(abc);
Area a2 = new Area(abc2);

a1.intersect(a2);
if (!a1.isEmpty())
{
//System.out.print("collided with tile 3");
//return 3;
//g.drawString("Two Polygons collided", 20, 20 );
}

}
}
}
}
}

g.drawImage(bufferimage,0,0,this);
//}else
//{
//g.drawImage(debugimage,0,0,this);
//}
}

// Not used becourse update is being used for screen drawing
public void paint(Graphics g) {
//g.drawString("Welcome to Java!!", 50, 60 );
}

public boolean mouseMove(Event e, int x, int y)
{
mouseX = x;
mouseY = y;
mousecol = rectcollision(x,y);
//xPos=x;
//yPos=y;
//System.out.println("On the "+map[(int)mouseX/cellwidth][(int)mouseY/cellheight]);

return true;
}

public boolean keyUp (Event e, int key){
if(key==Event.LEFT)
{
playerMoveLeft = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = false;
}
return true;
}

public boolean keyDown (Event e, int key){

if(key==Event.LEFT)
{
playerMoveLeft = true;
playerFacingLeft = true;
playerFacingRight = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = true;
playerFacingRight = true;
playerFacingLeft = false;
}

if(key==120)
{
if(isFalling==false && isJumping==false)
{
isJumping = true;
gravity = 3;
}
}

//System.out.println ("Charakter: " + (char)key + " Integer Value: " + key);
return true;
}

}

``````

### FloodFill pathfinding example (Shortest path)

(Press any mouse button on the applet screen to create a new path/route.)

I never understood how to make a path finding program. I find the documents and code that I found on the Internet hard to understand. I did remember a couple of things that I was thinking about. Things like open and closed list, flooding and neighbooring cells.
I downloaded a simple pathfinding example in the basic language and converted it to Java and got it working but the paths were not always the shortest paths.

I then started thinking about how I could make my own path finding program. I was thinking about using a map flood where you store the distance traveled by the flood in a different map. I got that working. I could read on the map that where the destination is located you could count back number by number to the start position. I tried to count back and it worked. I read the 8 blocks around the current position and select the lowest block for the next location and do this again until the start position is found.

It took me hours to get the program working right.

I have 4 arrays of coordinates. (x1[],y1[],x2[],y2[]) I have a loop that increases a distance variable by one by each loop. I loop through the x1 and y1 array and close the map positions of those coordinates and write to an other buffer map with the distance variable. When the x1 and y1 loop is done then I loop through it again and find nearest unused coordinates and place those in x2 and y2 arrays, I check the buffer map if it is closed, and when done I copy that list into the x1 and y1 array and the loop is continued until every map coordinate is closed.

I then have a other loop further in the method where I count back from the end coordinates until it reaches the start coordinates. If there is no lower surrounding value then the loop ends and exits the method with false.

The path created always seems to be the shortest path.

I am still new to Java and could not get Arraylists or Lists working so I used arrays. I still have to study more sourcecode that uses arraylists and other list type containers.

(Here below is the complete code of the example..)

``````

import java.awt.*;
import java.applet.*;

public class pathfind07 extends Applet {

// stores the map ; it is rotated, weird
int map[][] ={
{0,0,0,0,0,1,0,1,0,0},
{0,1,1,1,0,1,0,1,0,1},
{0,0,0,0,0,0,0,0,0,0},
{1,1,1,1,1,1,1,0,1,1},
{1,1,0,0,0,0,1,0,1,0},
{0,1,1,1,0,0,1,0,0,0},
{1,0,0,1,0,1,1,0,1,0},
{1,1,0,1,0,0,0,0,1,0},
{0,0,1,1,1,1,1,1,1,0},
{0,0,1,0,0,0,0,0,0,0}
};
int[][][] map2 = new int;
int mystartx=0;
int mystarty=0;
int myendx=9;
int myendy=9;
// Maximum length of path here is 100
int[] pathx = new int;
int[] pathy = new int;
int cw=22;//draw cell width
int ch=22;//draw cell height
public void init() {

}

public void paint(Graphics g) {

//draw map
g.setColor(Color.black);
for(int x=0;x<10;x++){
for(int y=0;y<10;y++){
// draw the distance map
g.drawString(""+map2[x][y],x*cw+cw/2,y*ch+ch/2);
// draw the tile map
if(map[x][y]==1){
g.fillRect(x*cw,y*ch,cw,ch);
}
}}

// draw the start and end locations
g.setColor(Color.red);
g.drawRect(mystartx*cw+cw/4,mystarty*ch+ch/4,cw/2,ch/2);
g.setColor(Color.green);
g.drawRect(myendx*cw+cw/4,myendy*ch+ch/4,cw/2,cw/2);
// draw path
g.setColor(Color.black);
for(int cnt3=1;cnt3<100;cnt3++)
{
if(pathx[cnt3-1]!=-1 && pathx[cnt3]!=-1)
{
g.drawLine(pathx[cnt3-1]*cw+cw/2,pathy[cnt3-1]*ch+ch/2,pathx[cnt3]*cw+cw/2,pathy[cnt3]*ch+ch/2);
}
}
g.drawString("Press on the map to create path",0,230);
}

public boolean findpath(int startx,int starty,int endx,int endy)
{
System.out.println("Looking for path at :"+startx+":"+starty+":"+endx+":"+endy);
if(startx<0) return false;
if(startx>9) return false;
if(starty<0) return false;
if(starty>9) return false;
if(map[startx][starty]==1)return false;
if(map[endx][endy]==1)return false;

//erase the old path
for(int i=0;i<100;i++)
{
pathx[i]=-1;
pathy[i]=-1;
}
//erase the path finding buffer map. [][]=donewith[][]=distance
for(int y=0;y<20;y++){
for(int x=0;x<20;x++){
map2[x][y]=0;
map2[x][y]=0;
}
}
//Make arrays to store closeby cells in (open list and closed list)
int[] x1 = new int;
int[] y1 = new int;
int[] x2 = new int;
int[] y2 = new int;
int cnt,x,y;
int dist=0;
int numitems = 0;
int numitems2 = 0;
// set all cell values to unused
for(int i=0;i<500;i++){
x1[i]=-1;
y1[i]=-1;
x2[i]=-1;
y2[i]=-1;
}
// start location
x1=startx;
y1=starty;
numitems = 1;
// loop 120 times to fill the map
for(int bbb=0;bbb<120;bbb++)
{
// increase the distance of the flood
dist++;

// fill done map
for(int i=0;i < numitems ;i++){
map2[x1[i]][y1[i]]=1;
map2[x1[i]][y1[i]]=dist;
}
// Find neighboords for list 2
cnt=0;
x=0;
y=0;
for(int i=0; i < numitems ;i++){
x=x1[i];
y=y1[i];
if(x-1>=0 && y-1>=0 && map[x-1][y-1]!=1 && map2[x-1][y-1]!=1)
{
x2[cnt]=x-1;
y2[cnt]=y-1;
map2[x-1][y-1]=1;
cnt++;
}
if(x>=0 && y-1>=0 && map[x][y-1]!=1 && map2[x][y-1]!=1)
{
x2[cnt]=x;
y2[cnt]=y-1;
map2[x][y-1]=1;
cnt++;
}
if(x+1<10 && y-1>=0 && map[x+1][y-1]!=1 && map2[x+1][y-1]!=1)
{
x2[cnt]=x+1;
y2[cnt]=y-1;
map2[x+1][y-1]=1;
cnt++;
}
if(x-1>=0 && y>=0 && map[x-1][y]!=1 && map2[x-1][y]!=1)
{
x2[cnt]=x-1;
y2[cnt]=y;
map2[x-1][y]=1;
cnt++;
}
if(x+1<10 && y>=0 && map[x+1][y]!=1 && map2[x+1][y]!=1)
{
x2[cnt]=x+1;
y2[cnt]=y;
map2[x+1][y]=1;
cnt++;
}
if(x-1>=0 && y+1<10 && map[x-1][y+1]!=1 && map2[x-1][y+1]!=1)
{
x2[cnt]=x-1;
y2[cnt]=y+1;
map2[x-1][y+1]=1;
cnt++;
}
if(x>=0 && y+1<10 && map[x][y+1]!=1 && map2[x][y+1]!=1)
{
x2[cnt]=x;
y2[cnt]=y+1;
map2[x][y+1]=1;
cnt++;
}
if(x+1<10 && y+1<10 && map[x+1][y+1]!=1 && map2[x+1][y+1]!=1)
{
x2[cnt]=x+1;
y2[cnt]=y+1;
map2[x+1][y+1]=1;
cnt++;
}

}
numitems2 = cnt;
//erase list 1
for(int i=0; i < numitems ;i++){
x1[i]=-1;
y1[i]=-1;
}
//copy list 2 to list 1
for(int i=0; i < numitems2 ;i++)
{
x1[i]=x2[i];
y1[i]=y2[i];
x2[i]=-1;
y2[i]=-1;
}
numitems = numitems2;

}

// Find path Count back / trace back
System.out.println("Tracing back");
int lx=endx;//store the end location here to count back to start
int ly=endy;
//int[] nums = new int;
int nums[] ={1000,1000,1000,1000,1000,1000,1000,1000,1000,1000};
int cnt2=1;//for numbering the surrounding blocks
int cnt3=0;//path index
boolean exitloop=false;
while(exitloop==false)
{
if(lx==startx && ly==starty) break;
// erase the nums array (nums stores the distance value in the buffer map2[][]
for(int cc=0;cc<10;cc++)
{
nums[cc]=1000;
}
cnt2=1;
// Read the surrounding map cells into the nums array.
if(lx-1>=0 && ly-1>=0 && map[lx-1][ly-1]!=1)
{
nums[cnt2]=map2[lx-1][ly-1];
}
cnt2++;
if(lx>=0 && ly-1>=0 && map[lx][ly-1]!=1)
{
nums[cnt2]=map2[lx][ly-1];
}
cnt2++;
if(lx+1<10 && ly-1>=0 && map[lx+1][ly-1]!=1)
{
nums[cnt2]=map2[lx+1][ly-1];
}
cnt2++;
if(lx-1>=0 && ly>=0 && map[lx-1][ly]!=1)
{
nums[cnt2]=map2[lx-1][ly];
}
cnt2++;
if(lx+1<10 && ly>=0 && map[lx+1][ly]!=1)
{
nums[cnt2]=map2[lx+1][ly];
}
cnt2++;
if(lx-1>=0 && ly+1<10 && map[lx-1][ly+1]!=1)
{
nums[cnt2]=map2[lx-1][ly+1];
}
cnt2++;
if(lx<10 && ly+1<10 && map[lx][ly+1]!=1)
{
nums[cnt2]=map2[lx][ly+1];
}
cnt2++;
if(lx+1<10 && ly+1<10 && map[lx+1][ly+1]!=1)
{
nums[cnt2]=map2[lx+1][ly+1];
}
cnt2++;

int lowest = 1000;//used to find lowest value
int thenextloc=-1;
// loop through all surrounding cells and find lowest value
for(int i=1;i<10;i++)
{
System.out.print(""+nums[i]+",");
if(nums[i] < lowest )
{
lowest = nums[i];
thenextloc = i;//this is the next direction we travel in
}
}
// if no next direction is found then clear path and exit method
if(lowest == 1000 || lowest == 0)
{
System.out.println("quited 0 or 1000");
for(int i=0;i<100;i++)
{
pathx[i]=-1;
pathy[i]=-1;
}
return false;
}
System.out.println(" lowest value " + lowest + " thenextloc : "+thenextloc);
// The thenextloc variable has the next direction we travel in
// 1=leftabove 2=above 3=rightabove
// 4=left 5 = right 6 = left below
// 7=below 8 = right below
if(thenextloc==1){
lx--;
ly--;
}
if(thenextloc==2){
ly--;
}
if(thenextloc==3){
lx++;
ly--;
}
if(thenextloc==4){
lx--;
}
if(thenextloc==5){
lx++;
}
if(thenextloc==6){
lx--;
ly++;
}
if(thenextloc==7){
ly++;
}
if(thenextloc==8){
lx++;
ly++;
}
//store the next coordinates in the path arrays
pathx[cnt3]=lx;
pathy[cnt3]=ly;
// next slot in the path array if the path gets longer
cnt3++;
}
// if the path was found then stop
System.out.println("path found");
return true;
}

public boolean mouseUp (Event e, int x, int y)
{
// divide the mouse coordinates with the width and
// height of the screen map blocks
int thex=x/cw;
int they=y/ch;
mystartx=thex;
mystarty=they;
//try to find the path
findpath(thex,they,myendx,myendy);
//repaint the screen
repaint();

return true;
}

}

``````

### Using Switch in Java.

I could not remember how to use switch in Java. So I will place a example on my blog.

Example 1

switch(Variable) {
case VariableContents: Do things...
default: Do things..
}

Example 2

switch (month)
{
case 11:
numDays = 30;
break;
default:
System.out.println("Invalid month.");
break;
}

## donderdag 14 april 2011

### Still learning java - classes in lists

I still find it hard to program in java. I have no idea how to put classes into lists. Searching the Internet for this.

### Distance method - needs java.lang.Math.*;

``````

public int distance(int x1,int y1,int x2,int y2)
{
double xd=Math.abs(x2-x1);
double yd=Math.abs(y2-y1);
return (int)Math.sqrt((xd*xd)+(yd*yd));
}

``````

### Tilemap with Multidimensional array example

I was looking through sourcecode and discovered how to use multidimensional arrays to store map data. Below the example.

``````

import java.awt.*;
import java.applet.*;

public class Pathfinding01 extends Applet {

short map[][] ={{0,0,0,0,1,0,0,0,0,0},
{0,0,0,0,1,0,1,1,1,0},
{0,1,1,1,1,0,1,0,1,0},
{0,0,0,0,1,0,1,0,1,0},
{0,1,1,0,1,0,1,0,1,0},
{0,0,1,0,1,0,1,0,1,0},
{0,0,1,0,0,0,1,0,1,0},
{0,0,1,1,1,1,1,0,1,0},
{0,0,0,0,0,0,0,0,0,0},
{0,0,0,0,0,0,0,0,0,0}};

public void init() {
}

public void paint(Graphics g) {

//g.drawString("Welcome to Java!!", 50, 60 );
for(int x = 0; x < map.length; x++){
for(int y = 0; y < map.length; y++){
if(map[x][y]==1){
g.fillRect(x*32,y*32,32,32);
}
}}
}
}

``````

## dinsdag 12 april 2011

PlayerShooting.class

``````

import java.awt.*;
import java.applet.*;

public class PlayerShooting extends Applet implements Runnable {
Graphics bufferGraphics;
Image offscreen;
private double mouseX;
private double mouseY;
private boolean playerMoveRight = false;
private boolean playerMoveLeft = false;
private double xPos=100;
private double yPos=100;
private boolean isFalling = false;
private boolean isJumping = false;
private double gravity;
private double groundLevel = 100;
private boolean isShooting;
private boolean playerFacingLeft;
private boolean playerFacingRight=true;
private Shot [] shots;

public void init() {

setBackground(Color.black);
offscreen = createImage(getSize().width,getSize().height);
bufferGraphics = offscreen.getGraphics();

shots = new Shot;

}

public void run() {
for(;;) { // animation loop never ends

if(playerMoveRight && xPos0)
{
xPos--;
}
if(isJumping)
{
yPos = (int)yPos - gravity;
gravity = gravity - .1;
if(gravity<0)
{
isJumping=false;
isFalling=true;
}
}
if(isFalling)
{
yPos = (int)yPos + gravity;
gravity = gravity + .1;
if(yPos>groundLevel)
{
isFalling = false;
yPos = groundLevel;
gravity=0;
}
}

for(int i=0; i < shots.length; i++)
{
if(shots[i] != null)
{
// move shot
shots[i].moveShot();
// test if shot has left the game area
// if true, delete from array
if(shots[i].getYPos() < 0)
{
shots[i] = null;
break;
}
if(shots[i].getYPos() > getSize().height)
{
shots[i] = null;
break;
}
if(shots[i].getXPos() < 0)
{
shots[i] = null;
break;
}
if(shots[i].getXPos() > getSize().width)
{
shots[i] = null;
break;
}

}
}

repaint();
try {
}
catch (InterruptedException e) {
}
}
}

public void update (Graphics g)
{
bufferGraphics.clearRect(0, 0, getSize().width,getSize().height);
bufferGraphics.setColor (Color.white);
bufferGraphics.drawString("Player Shooting Example - Press z to shoot. x - jump",10,10);
int x = (int) xPos;
int y = (int) yPos;
bufferGraphics.fillOval (x, y, 16, 16);

// draw shots
for(int i=0; i < shots.length; i++)
{
if(shots[i] != null)
{
shots[i].drawShot(bufferGraphics);
}
}

g.drawImage(offscreen,0,0,this);

}

//Overriding the paint method
public void paint(Graphics g) {
}

public boolean mouseMove(Event e, int x, int y)
{
mouseX = x;
mouseY = y;
return true;
}

public boolean keyUp (Event e, int key){
if(key==Event.LEFT)
{
playerMoveLeft = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = false;
}
return true;
}

public boolean keyDown (Event e, int key){

if(key==Event.LEFT)
{
playerMoveLeft = true;
playerFacingLeft = true;
playerFacingRight = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = true;
playerFacingRight = true;
playerFacingLeft = false;
}

if(key==120)
{
if(isFalling==false && isJumping==false)
{
isJumping = true;
gravity = 3;
}
}
if(key==122)//z key
{
isShooting = true;

// generate new shot and try to store it in shots array
for(int i=0; i < shots.length; i++)
{
// only store shot if there is a place left in the array
if(shots[i] == null)
{
if(playerFacingLeft)
{
shots[i] = new Shot(xPos,yPos,-2,0);
}else
{
shots[i] = new Shot(xPos+16,yPos,2,0);

}
break;
}
}

}
System.out.println ("Charakter: " + (char)key + " Integer Value: " + key);
return true;
}

}

``````

Shot.class

``````

import java.awt.Graphics;
import java.awt.Color;

public class Shot
{
private double xLoc;
private double yLoc;
private double velX;
private double velY;

public Shot(double x, double y,double vx, double vy)
{
xLoc = x;
yLoc = y;
velX = vx;
velY = vy;
}

public int getYPos()
{
return (int)yLoc;
}
public int getXPos()
{
return (int)xLoc;
}
public void moveShot()
{
xLoc = (xLoc + velX);
yLoc = (yLoc + velY);
}
public void drawShot(Graphics bufferGraphics)
{
bufferGraphics.setColor(Color.green);
bufferGraphics.fillOval((int)xLoc,(int)yLoc,8,8);
}
}

``````

## maandag 11 april 2011

### Player TIleMap Collision Example

The code is messy since I just wanted to finish this example. There are better ways of doing the collision with the map and there are a lot of lines that can be saved from the code below. But it works.

Press the mouse in the applet to activate it and then use the cursor keys left and right to move and the space bar to jump.

This is the source code of the applet.

``````
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class PlayerTileMapCollision extends Applet implements Runnable {
Graphics bufferGraphics;
Image offscreen;
Graphics bufferLevel;
Image levelgraphic;
Image image2;
private double mouseX;
private double mouseY;
private boolean playerMoveRight = false;
private boolean playerMoveLeft = false;
private double xpos=100;
private double ypos=100;
private int appletSize_x;
private int appletSize_y;
private double time;
private double height;
private final int GRAVITY = -10;
private boolean isFalling = true;
private boolean isJumping = false;

final short map[] ={
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,1,1,1,1,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,
1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
};

public void init() {

height = appletSize_y - ypos;
time = 0;
appletSize_x = getSize().width;
appletSize_y = getSize().height;
height=appletSize_y - ypos;
setBackground(Color.black);
offscreen = createImage(getSize().width,getSize().height);
bufferGraphics = offscreen.getGraphics();
levelgraphic = createImage(getSize().width,getSize().height);
bufferLevel = levelgraphic.getGraphics();

image2 = createImage(16,16);
Graphics test = image2.getGraphics();
test.setColor(Color.red);
test.fillRect(0,0,16,16);
test.setColor(Color.black);
test.drawRect(0,0,16,16);

// Here the map is drawn
int n=0;
for(int y=0;y<=11;y++){
for(int x=0;x<=19;x++){
if(map[n]==1) bufferLevel.drawImage(image2,x*16,y*16,this);
n++;
}
}

}

public void run() {
int pos;
short ch;
int val;
for(;;) { // animation loop never ends
pos = (int)((xpos+8)/16)+20*(int)((ypos+16)/16);
ch = map[pos];
if(ch==0 && isJumping==false)isFalling=true;
if (isJumping) {
pos = (int)((xpos+8)/16)+20*(int)((ypos-1)/16);
ch = map[pos];
if((height - radius < getSize().height) && (ch==0) && (time<1.7)) {
height =  height - (.2 * GRAVITY * (time * time) );
ypos = appletSize_y - height;
time += .02;
} else {
isJumping = false;
isFalling = true;
time=0;
}
}

if (isFalling) {
pos = (int)(xpos/16)+20*(int)((ypos+16)/16);
ch = map[pos];
if(ch==0){
height =  height + (.5 * GRAVITY * (time * time) );
ypos = appletSize_y - height;
time += .02;
} else {
isFalling = false;
val=(int)ypos/16;
ypos=val*16;
time = 0;
}
}

if(playerMoveLeft){
pos = (int)((xpos-1)/16)+20*(int)((ypos)/16);
ch = map[pos];
if(ch==0)
{
xpos--;
}
}
if(playerMoveRight){
pos = (int)((xpos+16)/16)+20*(int)((ypos)/16);
ch = map[pos];
if(ch==0) xpos++;
}

repaint();
try {
} catch (InterruptedException e) {
}
}
}

public void update (Graphics g)
{
bufferGraphics.clearRect(0, 0, getSize().width,getSize().height);
bufferGraphics.drawImage(levelgraphic,0,0,this);
bufferGraphics.setColor (Color.RED);
bufferGraphics.drawString("Jump Example - Press Spacebar to Jump",10,10);
int x = (int) xpos;
int y = (int) ypos;
g.drawImage(offscreen,0,0,this);

}

//Overriding the paint method
public void paint(Graphics g) {
}

public boolean mouseMove(Event e, int x, int y)
{
mouseX = x;
mouseY = y;

return true;
}

public boolean keyUp (Event e, int key){
if(key==Event.LEFT)
{
playerMoveLeft = false;
}
if(key==Event.RIGHT)
{
playerMoveRight = false;
}
return true;
}

public boolean keyDown (Event e, int key){

if(key==Event.LEFT)
{
playerMoveLeft = true;
//System.out.println (movingLeft);
}
if(key==Event.RIGHT)
{
playerMoveRight = true;
}

if(key==32)
{
if(isFalling==false && isJumping==false)  {
height = appletSize_y - ypos;
isJumping = true;
time=1;
}
}
//System.out.println ("Charakter: " + (char)key + " Integer Value: " + key);
return true;
}

}
``````