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() {
doubs.add(0.3);
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() {

bools.add(true);
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
  // map. where I read about the forumula it said
  // 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[10][10];

    // 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++ ){
   addrock();
  }

  new Thread(this).start();
     }

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

 public boolean addrock(){
  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[0][0] = 1;
     //debugrect[0][1] = x1;
     //debugrect[0][2] = y1;
     //debugrect[0][3] = w1;
     //debugrect[0][4] = h1;
     //debugrect[1][0] = 1;
     //debugrect[1][1] = x2;
     //debugrect[1][2] = y2;
     //debugrect[1][3] = w2;
     //debugrect[1][4] = 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 {
             Thread.sleep(10);
             }
             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][0] == 1){
    bufferGraphics.drawRect(debugrect[i][1],debugrect[i][2],debugrect[i][3],debugrect[i][4]);
   }
  }

       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[100][5];


 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;
    new Thread(this).start();
 }

 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[0][y]=1;
   map[ mapwidth - 1 ][y]=1;
  }
  for(int x = 0 ; x < mapwidth ; x++){
   map[x][0]=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 {
             Thread.sleep(10);
             }
             catch (InterruptedException e) {
             }
     }
 }

 public short rectcollision(double x,double y)
 {
  for(int i = 0 ; i<100 ; i++ ){
   debug[i][0]=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][0]=1;
        debug[cnt][1]=x3;
        debug[cnt][2]=y3;
        debug[cnt][3]=cellwidth;
        debug[cnt][4]=cellheight;
        cnt++;
        debug[cnt][0]=1;
        debug[cnt][1]=x1;
        debug[cnt][2]=y1;
        debug[cnt][3]=cellwidth;
        debug[cnt][4]=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][0]=1;
        debug[cnt][1]=x3;
        debug[cnt][2]=y3;
        debug[cnt][3]=cellwidth;
        debug[cnt][4]=cellheight;
        cnt++;
        debug[cnt][0]=1;
        debug[cnt][1]=x1;
        debug[cnt][2]=y1;
        debug[cnt][3]=cellwidth;
        debug[cnt][4]=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][0]=1;
       debug[cnt][1]=x3;
       debug[cnt][2]=y3;
       debug[cnt][3]=cellwidth;
       debug[cnt][4]=cellheight;
       cnt++;
       debug[cnt][0]=1;
       debug[cnt][1]=x1;
       debug[cnt][2]=y1;
       debug[cnt][3]=cellwidth;
       debug[cnt][4]=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][0] == 1){
     bufferGraphics.drawRect(debug[i][1],debug[i][2],debug[i][3],debug[i][4]);
    }
   }
  }

  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;
 }

}