vrijdag 27 januari 2012

Rotate Polygon around center Example



This example I constructed after looking through sourcecode by Brain Postma. He has several good sourcecodes on his site that is perfect to learn things from. Here I made a polygon that rotates around its center and rotates with the a and d keys. At first I did not understand why the rotation was not around its center but it was that you need to build the polygon from the center. So that half of it is in negative numbers.
I will be studying Brian Postma's sourcecode further and will probably lead to more examples on this blog.

 

import java.applet.Applet;
import java.awt.*;
public class RotatePolygonaroundcenter001 extends Applet  implements Runnable{
 Graphics bufferGraphics;
 Image offscreen;
    int[] XArray = {0, -15, 15};
    int[] YArray = {-15, 15, 15};
 double polangle;
 double polx = 320/2-15;
 double poly = 240/2-15;
 int[] xcoord = new int[3];
   int[] ycoord = new int[3];
 boolean rotleft = false;
 boolean rotright = false;
 public void init() {
        setBackground(Color.black);
        offscreen = createImage(getSize().width,getSize().height);
        bufferGraphics = offscreen.getGraphics();
     makecoords(polx,poly,polangle);
  new Thread(this).start();
 }
    public void run() {
        for(;;) { // animation loop never ends
         repaint();
         try {
    if ( rotleft == true ) {
        polangle -= 3;
     if ( polangle < 0 ) {
      polangle = 360;
     }
    }
    if ( rotright == true ) {
     polangle += 3;
     if ( polangle > 360 ) {
      polangle = 0;
     }
    }
          makecoords(polx,poly,polangle);
             Thread.sleep(16);
             }
             catch (InterruptedException e) {
             }
     }
    }

 public void makecoords(double x, double y, double angle)
   {
     int  i;
  angle = Math.toRadians(angle);
     for (i=0; i<3; i++)
     {
        xcoord[i] = (int)(x+(XArray[i]*Math.sin(angle)-YArray[i]*Math.cos(angle)));
        ycoord[i] = (int)(y+(XArray[i]*Math.cos(angle)+YArray[i]*Math.sin(angle)));
     }
  }

     public void update(Graphics g){
     bufferGraphics.clearRect(0,0,getSize().width,getSize().height);
     bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("Rotate polygon around center.",10,10);
  bufferGraphics.drawString("a/d to rotate.",10,237);
     bufferGraphics.fillPolygon (xcoord, ycoord, 3);

        g.drawImage(offscreen,0,0,this);
     }
  public boolean keyDown (Event e, int key){
   if(key==97) // a key
        {
         rotleft = true;
        }
        if(key==100) // d key
        {
   rotright = true;
        }

   return true;
  }

 public boolean keyUp (Event e, int key){
    if( key == 97 ) // a key
        {
          rotleft = false;
        }
        if( key == 100 ) // d key
        {
          rotright = false;
        }

  return true;
 }

}

Point in Circle Collision Example


This example shows how a collision can be found between a point and a circle. Change the values in the sourcecode and compile to see the effect.

 


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

public class PointInCircleCollision001 extends Applet {

 int pointx = 50;
 int pointy = 50;
 int circlex = 50;
 int circley = 50;
 int circlew = 150;

 public void init() {
 }
 // x point , y point, circlex, circley, circle size
 public boolean pointincircle( int x , int y , int cx , int cy , int cw ){
  int x1 = x;
  int y1 = y;
  int x2 = cx + cw/2;
  int y2 = cy + cw/2;
  boolean retval = false;
  int distance=(int)Math.sqrt( ( x1 - x2 ) * ( x1 - x2 ) + ( y1 - y2 ) * ( y1 - y2 ) ) ;
  if ( distance < cw/2 ) {
   retval = true;
  }
  return retval;
 }

 public void paint(Graphics g) {
        g.setColor(Color.red);
  g.drawString("Point in Circle Collision example.", 10, 10 );
        g.setColor(Color.black);
  g.fillOval(circlex,circley,circlew,circlew);
        g.setColor(Color.yellow);
        g.fillRect(pointx-5,pointy-5,10,10);
        g.setColor(Color.black);
  if ( pointincircle( pointx , pointy , circlex , circley , circlew ) == true ) {
   g.drawString("Collision.", 10, 210 );
  }else{
   g.drawString("No Collision.", 10, 210 );
  }
 }
}

HiScore Screen Example



Here a simple HiScore screen example. It shows 10 names and scores in sorted order. The sorting is done through the array setup. Pretty Simple example.

 


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

public class hiscorescreenexample001 extends Applet  implements Runnable{
 Graphics bufferGraphics;
    Image offscreen;
 String[] hiscore_s = new String[10];
 int[] hiscore_i = new int[10];

 public void init() {
  setBackground(Color.black);
     offscreen = createImage(getSize().width,getSize().height);
     bufferGraphics = offscreen.getGraphics();
     // create the hiscore names.
     hiscore_s[ 0 ] = "Joe";
     hiscore_s[ 1 ] = "Bill";
     hiscore_s[ 2 ] = "Jenny";
     hiscore_s[ 3 ] = "Steve";
     hiscore_s[ 4 ] = "Jan";
     hiscore_s[ 5 ] = "Penny";
     hiscore_s[ 6 ] = "Gary";
     hiscore_s[ 7 ] = "William";
     hiscore_s[ 8 ] = "John";
     hiscore_s[ 9 ] = "Carol";
     // create the hiscore scores.
     hiscore_i[ 0 ] = 100000;
     hiscore_i[ 1 ] =  90000;
     hiscore_i[ 2 ] =  80000;
     hiscore_i[ 3 ] =  70000;
     hiscore_i[ 4 ] =  60000;
     hiscore_i[ 5 ] =  50000;
     hiscore_i[ 6 ] =  40000;
     hiscore_i[ 7 ] =  30000;
     hiscore_i[ 8 ] =  20000;
     hiscore_i[ 9 ] =  10000;
     // Start the runnable thread.
  new Thread(this).start();
 }
    public void run() {
     for(;;) { // animation loop never ends
         repaint();
         try {
             Thread.sleep(16);
            }
             catch (InterruptedException e) {
             }
     }
    }
    public void update(Graphics g){
     bufferGraphics.clearRect(0,0,getSize().width,getSize().width);
        bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("HiScore Screen Example",10,10);
        bufferGraphics.setColor(Color.white);
  // Draw the hiscore text to screen.
  for ( int i = 0 ; i < 10 ; i++ ) {
   bufferGraphics.drawString(hiscore_s[i],90,i*12+70);
   bufferGraphics.drawString(""+hiscore_i[i],190,i*12+70);
  }
  // Draw the Graphics buffer
       g.drawImage(offscreen,0,0,this);
    }


}

vrijdag 20 januari 2012

Platformer Spiders Example



In platform games you can sometimes see spiders that hang on the ceiling and then spin down from a thread of webbing and then go back up again. I made something similair above. There are a number of spiders in the level and when you touch them your position gets reset.

 


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

public class PlatformerSpidersExample001 extends Applet implements Runnable {
 Graphics     bufferGraphics;
    Image      offscreen;
 private int map[][] =  new int[][]{
 {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,1,1,1,0,0,0,0,1},
 {1,0,0,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,1},
 {1,0,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,0,0,1},
 {1,0,0,1,1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1},
 {1,0,0,0,0,0,0,0,0,0,2,0,0,0,0,2,0,0,0,1},
 {1,1,1,1,1,1,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,1,1,1,1,1,1,0,0,1},
 {1,0,0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,0,0,1},
 {1,0,0,0,1,1,1,1,0,0,0,0,0,0,0,2,0,0,0,1},
 {1,1,1,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,1,1,1,1,1,1,1,1,1,1},
 {1,1,1,1,1,0,0,0,0,0,0,0,2,0,0,0,2,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},
 };
 int mapwidth = 20;
 int mapheight = 15;
 int cellwidth = 16;
 int cellheight = 16;
 double     px =     132;
 double    py =    200;
 int     pwidth =    cellwidth/2;
 int     pheight =    cellheight;
 boolean    isjumping =   false;
 boolean    isfalling =   false;
 double    gravity =    0;
 boolean    ismovingright =  false;
 boolean    ismovingleft =   false;
 double    jumpforce =   3;

 int[][] spider = new int[32][16]; // active, x, y , direction/down/up, offsety
 long[] spiderdelay = new long[32];

 public void init() {
  setBackground(Color.black);
     offscreen = createImage(getSize().width,getSize().height);
     bufferGraphics = offscreen.getGraphics();
     // initiate the spiders
     int spidercount = 0;
     for ( int y = 0 ; y < mapheight ; y++ ) {
      for ( int x = 0 ; x < mapwidth ; x++ ) {
       if ( map[y][x] == 2 ) {
        spider[ spidercount ][ 0 ] = 1;
        spider[ spidercount ][ 1 ] = x * cellwidth;
        spider[ spidercount ][ 2 ] = y * cellheight;
        spider[ spidercount ][ 4 ] = (int)(Math.random() * 24);
        spiderdelay[ spidercount ] = System.currentTimeMillis();
        spidercount++;
       }
      }
     }
  new Thread(this).start();
 }

    public void run() {
     for(;;) { // animation loop never ends
         repaint();
         try {
       updateplayer();
       updatespiders();
       spiderplayercollision();
             Thread.sleep(16);
            }
             catch (InterruptedException e) {
             }
     }
    }

    public void update(Graphics g){
     bufferGraphics.clearRect(0,0,getSize().width,getSize().width);
        bufferGraphics.setColor(Color.white);

        // Draw map
        for( int y = 0 ; y < mapheight ; y++ ){
         for ( int x = 0 ; x < mapwidth ; x++){
          if( map[y][x] == 1 ){
           bufferGraphics.fillRect( x * cellwidth , y * cellheight , cellwidth , cellheight );
          }
         }
        }
        // Draw player
        bufferGraphics.fillRect( (int)px , (int)py , pwidth , pheight );

  // Draw spiders
  bufferGraphics.setColor(Color.yellow);
  for (int i = 0 ; i < 32 ; i++){
   if ( spider[i][0] == 1){
    bufferGraphics.fillOval( spider[ i ][ 1 ] , spider[ i ][ 2 ] + spider[ i ][ 4 ] ,
           cellwidth/2 , cellheight/2);
    bufferGraphics.drawLine( spider[ i ][ 1 ] + 4 , spider[ i ][ 2 ] ,
           spider[ i ][ 1 ] + 4 , spider[ i ][ 2 ] + spider[ i ][ 4 ]);
   }
  }

        bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("Platformer Spiders Example.",10,10);
        bufferGraphics.drawString("a - left, d - right, space to jump.",10,240);

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

    private void spiderplayercollision(){
     for ( int i = 0 ; i < 32 ; i++ ) {
      if ( spider[ i ][ 0 ] == 1 ) {
       Rectangle rec1 = new Rectangle( (int)px , (int)py , pwidth , pheight );
    Rectangle rec2 = new Rectangle( spider[ i ][ 1 ] , spider[ i ][ 2 ] + spider[ i ][ 4 ] ,
            8 , 8 );
    if(rec1.intersects(rec2)){
     px = 132;
     py = 200;
    }
      }
     }
    }

 public void updatespiders(){

  // spidermovement
  for ( int i = 0 ; i < 32 ; i++ ) {
   if ( spider[i][0] == 1 ) {
    if ( spiderdelay[i] < System.currentTimeMillis() ) {
     spiderdelay[i] = System.currentTimeMillis() + 20;
     if ( spider[i][3] == 0 ) {
      spider[i][4]++;
      if ( spider[i][4] > 24 ) {
       spider[i][3] = 1;
       spiderdelay[i] = System.currentTimeMillis() + (int)( Math.random() * 2000 );
      }
     }
     if ( spider[i][3] == 1 ) {
      spider[i][4]--;
      if ( spider[i][4] < 1 ) {
       spider[i][3] = 0;
       spiderdelay[i] = System.currentTimeMillis() + (int)( Math.random() *  2000 );
      }
     }
    }
   }
  }
 }

    public void updateplayer(){

  if ( isjumping == false && isfalling == false ){
   if( mapcollision( (int)px , (int)py+1 , pwidth , pheight ) == false ){
    isfalling = true;
    gravity = 0;
   }
  }
  if (ismovingright){
   if ( mapcollision( (int)(px + 1) , (int)py , pwidth , pheight ) == false ){
    px += 1;
   }
  }
  if (ismovingleft){
   if ( mapcollision( (int)(px - 1) , (int)py , pwidth , pheight ) == false ){
    px -= 1;
   }
  }

  if ( isfalling == true && isjumping == false ){
   for ( int i = 0 ; i < gravity ; i++ ){
    if ( mapcollision ( (int)px , (int)(py + 1) , pwidth , pheight ) == false ){
     py += 1;
    }else{
     gravity = 0;
     isfalling = false;
    }
   }
   gravity += .1;
  }

  if ( isjumping == true && isfalling == false ){
   for ( int i = 0 ; i < gravity ; i++){
    if ( mapcollision ( (int)px , (int)(py - 1) , pwidth , pheight ) == false ){
     py -= 1;
     //System.out.print("still jumping : " + gravity);
    }else{
     gravity = 0;
     isfalling = true;
     isjumping = false;
    }
   }
   if( gravity < 1 ) {
    gravity = 0;
    isfalling = true;
    isjumping = false;
   }
   gravity -= .1;
  }
    }

  public boolean mapcollision( int x , int y , int width , int height ){
   int mapx = x / cellwidth;
   int mapy = y / cellheight;
   for ( int y1 = mapy - 1 ; y1 < mapy + 2 ; y1++ ){
    for ( int x1 = mapx - 1 ; x1 < mapx + 2 ; x1++ ){
     if ( x1 >= 0 && x1 < mapwidth && y1 >= 0 && y1 < mapheight ){
      if ( map[y1][x1] == 1 ){
       Rectangle rec1 = new Rectangle( x , y , width , height );
      Rectangle rec2 = new Rectangle( x1 * cellwidth,
              y1 * cellheight,
              cellwidth,
              cellheight);
      if( rec1.intersects( rec2 )) return true;
      }
     }
    }
   }
  return false;
  }
  public boolean keyDown (Event e, int key){
    if( key == 97 ) // a key
        {
         ismovingleft = true;
        }
        if(key== 100) // d key
        {
          ismovingright = true;
        }

      if( key == 32 ) // space bar for jump
      {
        if( isfalling == false && isjumping == false )
        {
            isjumping = true;
            gravity = jumpforce;
        }
      }

        System.out.println (" Integer Value: " + key);

   return true;
  }

 public boolean keyUp (Event e, int key){
    if( key == 97 ) // a key
        {
          ismovingleft = false;
        }
        if( key == 100 ) // d key
        {
          ismovingright = false;
        }

  return true;
 }


}

Missile Commander Partly Example



Simple Example of how Missile commander works. In missile commander a missile is shot towards the position of a incomming missile and the explosion of the intercepting missile destroys the incomming missile. In this example I programmed a missile that shoots towards the mouse pressed position and it explodes there. You can only fire one missile a the time.

 


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

public class MissileCommanderExample001 extends Applet implements Runnable{
 Graphics bufferGraphics;
    Image offscreen;
    boolean missilefired;
 int missileangle;
 double mx1; // missile variables.
 double my1;
 double mx2;
 double my2;
 long mld; // missile line point 2 delay.
 int mtx; // missile target variables.
 int mty;
 boolean explosionactive;
 int ex; // Explosion variables.
 int ey;
 int er; // explosion radius.
 boolean explosiongrowing;
 long edelay;
 long turnoffmissiletime;
 boolean turnoffmissile;
 public void init() {
        setBackground(Color.black);
        offscreen = createImage(getSize().width,getSize().height);
        bufferGraphics = offscreen.getGraphics();
  new Thread(this).start();
 }
    public void run() {
        for(;;) { // animation loop never ends
         runmissile();
         repaint();
         try {
             Thread.sleep(16);
             }
             catch (InterruptedException e) {
             }
     }
    }
    public void runmissile(){
     if ( missilefired == true ){
      if ( explosionactive == false ) {
        Rectangle rec1 = new Rectangle((int)mx1-2,(int)my1-2,4,4);
    Rectangle rec2 = new Rectangle(mtx-2,mty-2,4,4);
    if(rec1.intersects(rec2)){ // if missile reached target coordinates
     explosionactive = true;
     explosiongrowing = true;
     ex = mtx;
     ey = mty;
     er = 0;
     edelay = System.currentTimeMillis() + 10;
     turnoffmissile = true;
     turnoffmissiletime = System.currentTimeMillis() + 1000;
    }
      }
      if ( explosionactive == false ) {
       mx1 += 1 * Math.sin(Math.toRadians(missileangle));
       my1 += 1 * Math.cos(Math.toRadians(missileangle));
      }
      if ( mld < System.currentTimeMillis() ) {
       mx2 += 1 * Math.sin(Math.toRadians(missileangle));
       my2 += 1 * Math.cos(Math.toRadians(missileangle));
      }
     }
     // code for the explosion.
     if ( explosionactive == true ) {
      if ( edelay < System.currentTimeMillis() ) {
       edelay = System.currentTimeMillis() + 10;
       if ( explosiongrowing == true ) {
        er++;
        if ( er > 48 ) {
         explosiongrowing = false;
        }
       }else{
        er--;
        if ( er < 1 ) {
         explosionactive = false;
        }
       }
      }
     }

     // code for turning off missile
     if ( turnoffmissile == true ) {
      if ( turnoffmissiletime < System.currentTimeMillis() ) {
       missilefired = false;
       turnoffmissile = false;
      }
     }
    }
 public void update(Graphics g){
     bufferGraphics.clearRect(0,0,getSize().width,getSize().height);
     bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("Missile Commander Example.",10,10);
        bufferGraphics.drawString("Press mouse to launch missile.",10,220);
        bufferGraphics.setColor(Color.white);
        bufferGraphics.drawLine(0,200,320,200);
      // Draw the missile
      if ( missilefired == true ) {
       bufferGraphics.drawLine((int)mx1,(int)my1,(int)mx2,(int)my2);
      }
      if ( explosionactive == true ) {
       bufferGraphics.fillOval(ex-er/2,ey-er/2,er,er);
      }
        g.drawImage(offscreen,0,0,this);
     }
   public boolean mouseMove(Event e, int x, int y){
  return true;
 }
  public boolean mouseUp (Event e, int x, int y) {
        if (e.modifiers == Event.META_MASK) {
            //info=("Right Button Pressed");
        } else if (e.modifiers == Event.ALT_MASK) {
            //info=("Middle Button Pressed");
        } else {
            //info=("Left Button Pressed");
            if ( missilefired == false && y < 190 ) {
    mtx = x;
    mty = y;
          missileangle = (int)Math.toDegrees(Math.atan2( 160 - x , 200 - y ));
     missileangle = missileangle - 180;
     if (missileangle > 360 ){
     missileangle = missileangle - 360;
     }else if ( missileangle < 0) {
      missileangle = missileangle + 360;
     }

             missilefired = true;
    mld = System.currentTimeMillis() + 1000;
    mx1 = 320/2;
    my1 = 200;
    mx2 = 320/2;
    my2 = 200;
            }
        }
        return true;
    }


}

Blocks Shooting with Artificial Intelligence Example



I programmed something like this before after seeing a game by popcaps. I can not remember the game name though. In this example a paddle moves towards a random spot on the screen and shoots a bullet up. If the bullet hits a block then that block dissapears. Randomly one in every 3 the lower blocks are targeted. If the lowest line of blocks is empty then the blocks move one position down and the top line gets new blocks. This way the game should last forever.  


 


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

public class BlocksShooterExample001 extends Applet implements Runnable {
 Graphics bufferGraphics;
    Image offscreen;

 int[][] blocks = new int[10][10];
 int px = 320/2; // the paddle variables.
 int py = 220;
 int bx = 0; // bullet variables.
 double by = 0;
 int ptx = 0; // paddle target variable.
 boolean isshooting = false; // if bullet is on the screen.

 public void init() {
        setBackground(Color.black);
        offscreen = createImage(getSize().width,getSize().height);
        bufferGraphics = offscreen.getGraphics();
        // Initialize blocks  1 is block
  for (int y = 0 ; y < 10 ; y++){
   for (int x = 0 ; x < 10 ; x++){
    blocks[x][y] = 1;
   }
  }

  new Thread(this).start();
 }

    public void run() {
        for(;;) { // animation loop never ends
         runpaddle();
         runbullet();
         repaint();
         try {
             Thread.sleep(16);
             }
             catch (InterruptedException e) {
             }
     }
    }

    public void runpaddle(){

     if ( px < ptx ) {
      px++;
     }
     if ( px > ptx ) {
      px--;
     }
     if ( px == ptx && isshooting == false) {
      // shoot
      bx = px + 16;
      by = py;
      isshooting = true;
      // if one in three then shoot at lowest rightest block.
      // else shoot at random block.
      if ( (int)(Math.random() * 3) == 1 ) {
       for ( int zx = 0 ; zx < 10 ; zx++ ) {
        if ( blocks[zx][9] == 1 ) {
         ptx = zx*32;
        }
       }
       }else{
       ptx = (int)(Math.random()* 10) * 32;
      }
     }
     // if lowest blocks line is empty then shift blocks down by 1.
     boolean isempty = true;
     for ( int x = 0 ; x < 10 ; x++){
      if ( blocks[x][9] == 1 ) isempty = false;
     }
     if ( isempty == true ){
      for ( int y = 8 ; y > 0 ; y--){
       for ( int x = 0 ; x < 10 ; x++){
        blocks[x][y+1]=blocks[x][y];
       }
      }
      for (int x = 0 ; x < 10 ; x++){
       blocks[x][0] = 1;
      }
     }

    }

 public void runbullet(){
  // move the bullet up.
  if ( isshooting == true ) {
   by-=1;
  }
  // check collision with blocks.
  if ( isshooting == true ) {
   for ( int y = 0 ; y < 10 ; y++){
    for ( int x = 0 ; x < 10 ; x++){
     if ( blocks[x][y] == 1 ) {
      Rectangle rec1 = new Rectangle(x*32,y*12,32,12);
      Rectangle rec2 = new Rectangle(bx,(int)by,4,4);
      if(rec1.intersects(rec2)){
       isshooting = false;
       blocks[x][y] = 0;
      }
     }
    }
   }
  }
  // if bullet of the screen.
  if ( by < 0 ) {
   isshooting = false;
  }
 }

     public void update(Graphics g){
     bufferGraphics.clearRect(0,0,getSize().width,getSize().height);
     bufferGraphics.setColor(Color.white);
  // Draw Blocks
  for (int y = 0 ; y < 10 ; y++){
   for (int x = 0 ; x < 10 ; x++){
    if ( blocks[x][y] == 1 ){
     bufferGraphics.fillRect(x*32,y*12,30,10);
    }
   }
  }
  // Draw paddle
  bufferGraphics.fillRect(px,py,32,12);
   // Draw Bullet
   if ( isshooting == true ) {
    bufferGraphics.fillRect(bx,(int)by,4,4);
   }
     bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("Blocks Shooter Example.",10,10);
        g.drawImage(offscreen,0,0,this);
     }


}

donderdag 12 januari 2012

Topdown Movement Example


I made a Topdown 2d Player Movement Example. In this example you can move through a 2d map. You can not move through the walls. I had a problem with the collision but it turned out I needed to increase the collision zone check by one to get the collision working. The sourcecode is below.


 


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

public class TopdownMovementExample001 extends Applet implements Runnable{

 Graphics bufferGraphics;
 Image offscreen;
 boolean ismovingleft;
 boolean ismovingright;
 boolean ismovingup;
 boolean ismovingdown;
 private int map[][] =  new int[][]{
 {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,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,0,1},
 {1,0,0,0,1,0,0,1,0,0,0,0,1,0,0,1,0,0,0,1},
 {1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,1,0,1,0,1},
 {1,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1},
 {1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1},
 {1,0,0,0,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1},
 {1,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1},
 {1,0,1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,0,1},
 {1,0,1,0,1,0,0,1,1,0,0,1,1,0,0,1,0,1,0,1},
 {1,0,0,0,1,0,0,1,0,0,0,0,1,0,0,1,0,0,0,1},
 {1,0,1,1,1,1,0,1,0,0,0,0,1,0,1,1,1,1,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},
 };
 int mapwidth = 20;
 int mapheight = 15;
 int cellwidth = 16;
 int cellheight = 16;
 int playerx = 10*cellwidth;
 int playery = 13*cellheight;
 public void init() {
        setBackground(Color.black);
        offscreen = createImage(getSize().width,getSize().height);
        bufferGraphics = offscreen.getGraphics();
  new Thread(this).start();
 }
    public void run() {
        for(;;) { // animation loop never ends
   moveplayer();
         repaint();
         try {
             Thread.sleep(10);
             }
             catch (InterruptedException e) {
             }
     }
    }

    public boolean ismapcollision(int x, int y){

  int pcx = x / cellwidth;
  int pcy = y / cellheight;
  for (int y1 = pcy - 1 ; y1 < pcy + 2 ; y1++){
   for (int x1 = pcx - 1 ; x1 < pcx + 2 ; x1++){
    if( x1 >= 0 && x1 < mapwidth && y1 >= 0 && y1 < mapheight ){
     if ( map[y1][x1] == 1 ){
      Rectangle rec1 = new Rectangle(  x1 * cellwidth ,
                y1 * cellheight ,
                cellwidth ,
                cellheight );
      Rectangle rec2 = new Rectangle(  x,
               y,
               cellwidth,
               cellheight);
      if(rec1.intersects(rec2)) return true;
     }
    }
   }
  }
  return false;
    }

    public void moveplayer(){
     if (ismovingright == true && ismapcollision(playerx + 1,playery) == false){
      playerx++;
     }
     if (ismovingup == true && ismapcollision(playerx,playery-1) == false){
      playery--;
     }
     if (ismovingdown == true && ismapcollision(playerx,playery+1) == false){
      playery++;
     }
     if (ismovingleft == true && ismapcollision(playerx-1,playery) == false){
      playerx--;
     }

    }

     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[y][x] == 1 ){
           bufferGraphics.fillRect( x * cellwidth , y * cellheight , cellwidth , cellheight );
          }
         }
        }

     bufferGraphics.setColor(Color.red);

  bufferGraphics.fillOval(playerx,playery,cellwidth,cellheight);

        bufferGraphics.drawString("2D Topdown Movement.",10,10);
  bufferGraphics.drawString("w/s/a/d to move player.",10,237);

        g.drawImage(offscreen,0,0,this);
     }
  public boolean keyDown (Event e, int key){
   if(key==97)
        {
         ismovingleft = true;
        }
        if(key==100)
        {
         ismovingright = true;
        }
        if(key==119)
        {
         ismovingup = true;
        }
        if(key==115)
        {
         ismovingdown = true;
        }

   return true;
  }
 public boolean keyUp (Event e, int key){

   if(key==97)
        {
         ismovingleft = false;
        }
        if(key==100)
        {
         ismovingright = false;
        }
        if(key==119)
        {
         ismovingup = false;
        }
        if(key==115)
        {
         ismovingdown = false;
        }
//  System.out.println(""+key);
  return true;
 }


}

woensdag 11 januari 2012

Turn Based Unit Movement Example.


I programmed a turn based unit movement example. The instructions are on the applet screen. The example has 5 units on the screen that can be moved around. You can only move units 2 spaces until the next unit is activated. When no moves are left then there is a message that it is the end of turn and that you need to press the enter key. When that is done then the moves are reset and then you can move the units again. Oh, press on a unit to activate it. There could probably be a few bugs with that mouse selecting since I did not check that feature yet. 


Anyways. Below is the sourcecode. There are around 200 rows of code.

 


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

public class turnbased_example extends Applet  implements Runnable{

 Graphics bufferGraphics;
    Image offscreen;
    int numunits = 5;
    int unitwidth = 16;
    int unitheight = 16;
    int blinkingunit = 0;
 long blinktime;
 int gameturn = 0;
 boolean endofturn = false;
 int[][] unit = new int[numunits][10]; //unit , exists x y visible moves

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

        // create units
        for (int i = 0 ; i < numunits ; i++){
         unit[i][0] = 1;
         findgoodunitpos(i);
   unit[i][3] = 1;
   unit[i][4] = 2;
        }
  new Thread(this).start();
 }

 public void findgoodunitpos(int i){

     boolean exitloop = false;
     boolean unitontop = false;
     int newx = 0;
     int newy = 0;
     while ( exitloop == false ) {
      newx = (int)(Math.random()* 15 );
         newy = (int)((Math.random()* 12) + 1);
   // is unit not ontop of other unit then exit loop
   unitontop = false;
       for (int ii = 0 ; ii < numunits ; ii++){
        if (newx == unit[ii][1] && newy == unit[ii][2]){
         unitontop = true;
        }
       }
       if (unitontop == false ) exitloop = true;
     }
     unit[i][1] = newx;
     unit[i][2] = newy;
 }

 public void dounitblinking(){
  if ( System.currentTimeMillis() > blinktime ){
   if ( unit[blinkingunit][3] == 1 ) {
    unit[blinkingunit][3] = 0 ;
   } else {
    unit[blinkingunit][3] = 1;
   }
   blinktime = System.currentTimeMillis() + 500;
  }
 }
 public void resetblink(){
   blinktime = System.currentTimeMillis() + 500;
   unit[blinkingunit][3] = 1;
 }

    public void run() {
        for(;;) { // animation loop never ends
         repaint();
         try {
          if ( endofturn == false ) {
              dounitblinking();
          }
             Thread.sleep(10);
             }
             catch (InterruptedException e) {
             }
     }
    }
     public void update(Graphics g){
     bufferGraphics.clearRect(0,0,getSize().width,getSize().height);
     bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("Turn based movement Example.",10,10);
        bufferGraphics.drawString("w/s/a/d to move unit. click on unit to activate.",10,237);
        bufferGraphics.drawString("Unit : " + blinkingunit , getSize().width - 64 , 54);
        bufferGraphics.drawString("X : " + unit[blinkingunit][1] , getSize().width - 64 , 64);
        bufferGraphics.drawString("Y : " + unit[blinkingunit][2] , getSize().width - 64 , 74);
  bufferGraphics.drawString("Moves : " + unit[blinkingunit][4] , getSize().width - 64 , 84);
  bufferGraphics.drawString("Turn : " + gameturn , getSize().width - 64 , 94);
        bufferGraphics.drawRect(0,16,getSize().width-64,getSize().height-32);


  // if end of turn
  if ( endofturn == true ) {
   bufferGraphics.drawString("End of Turn" , getSize().width - 64 , 124);
   bufferGraphics.drawString("Press Enter" , getSize().width - 64 , 134);
  }

        // Draw units
        for (int i = 0 ; i < numunits ; i++){
         if ( unit[i][0] == 1 && unit[i][3] == 1){
          bufferGraphics.fillRect(unit[i][1] * unitwidth ,
                unit[i][2] * unitheight ,
                unitwidth ,
                unitheight);
         }
        }

        g.drawImage(offscreen,0,0,this);
     }
    public boolean occupied(int x, int y){
     for (int i = 0 ; i < numunits ; i++){
      if ( unit[i][1] == x ){
      if ( unit[i][2] == y ){
       return true;
      }
      }
     }
     return false;
    }


    public boolean nextmovableunit(){
     for ( int i = 0 ; i < numunits ; i++ ) {
      if ( unit[i][4] > 0 ) {
       resetblink();
       blinkingunit = i;
       resetblink();
       return true;
      }
     }
     return false;
    }


 public void nextturn(){
  boolean allmovesgone = true;
  for ( int i = 0 ; i < numunits ; i++ ) {
   if ( unit[i][4] > 0 ) {
    allmovesgone = false;
   }
  }
  if ( allmovesgone == true ) {
   endofturn = true;
  }
 }

 public boolean keyUp (Event e, int key){
        //System.out.println (" Integer Value: " + key);

  if ( endofturn == true ) {
   if( key == 10 ) // Return/Enter key / end of turn
         {
          gameturn++;
    for ( int i = 0 ; i < numunits ; i++ ) {
     unit[i][4] = 2;
    }
    nextmovableunit();
          endofturn = false;
         }
  }
  if ( endofturn == false ) {

     if( key == 119 ) // w key , up
         {
          if (unit[blinkingunit][2] > 1 &&
           occupied(unit[blinkingunit][1],unit[blinkingunit][2]-1) == false &&
           unit[blinkingunit][4] > 0 ) {
           unit[blinkingunit][2]--;
           unit[blinkingunit][4]--;
           resetblink();
     if (unit[blinkingunit][4] == 0 ){
      nextmovableunit();
     }
     nextturn();
           }
         }
         if( key == 97 ) // a key , left
         {
          if (unit[blinkingunit][1] > 0 &&
            occupied(unit[blinkingunit][1]-1,unit[blinkingunit][2]) == false &&
           unit[blinkingunit][4] > 0 ) {
           unit[blinkingunit][1]--;
           unit[blinkingunit][4]--;
           resetblink();
     if (unit[blinkingunit][4] == 0 ){
      nextmovableunit();
     }
     nextturn();
           }
          }
          if( key == 100 ) // d key , right
          {
           if (unit[blinkingunit][1] < 15 &&
           occupied(unit[blinkingunit][1]+1,unit[blinkingunit][2]) == false &&
            unit[blinkingunit][4] > 0 ) {
           unit[blinkingunit][1]++;
           unit[blinkingunit][4]--;
           resetblink();
     if (unit[blinkingunit][4] == 0 ){
      nextmovableunit();
     }
     nextturn();
          }
         }
         if( key == 115 ) // s key , down
          {
           if ( unit[blinkingunit][2] < 13 &&
           occupied(unit[blinkingunit][1],unit[blinkingunit][2]+1) == false &&
           unit[blinkingunit][4] > 0 ) {
           unit[blinkingunit][2]++;
           unit[blinkingunit][4]--;
           resetblink();
     if (unit[blinkingunit][4] == 0 ){
      nextmovableunit();
     }
     nextturn();
          }
         }
  } // end of endofturn boolean
        return true;
 }

  public boolean mouseUp (Event e, int x, int y) {
        if (e.modifiers == Event.META_MASK) {
            //info=("Right Button Pressed");
        } else if (e.modifiers == Event.ALT_MASK) {
            //info=("Middle Button Pressed");
        } else {
            //info=("Left Button Pressed");
   int mx = x / unitwidth;
   int my = y / unitheight;
   for ( int i = 0 ; i < numunits ; i++ ) {
    if (unit[i][1] == mx && unit[i][2] == my ) {
     resetblink();
     blinkingunit = i;
     resetblink();
    }
   }
        }
        return true;
    }


}