donderdag 31 maart 2011

Skeleton game code.

I found this code on java gaming.


import java.applet.*;
import java.awt.*;
public class Game extends Applet implements Runnable {
    Image buffer; // faster than BufferedImage, I've experienced
    Thread me;
    public void init() {
        buffer = createImage(getWidth(),getHeight());
        me = new Thread(this);
        me.start();
    }
    public void run() {
        while (me.isAlive()) {
            // game logic here
            if (getGraphics() != null) paint(getGraphics());
            try {
                Thread.sleep(10);
            }
            catch (InterruptedException e) {}
        }
    }
    public void paint(Graphics g) {
        Graphics gfx = buffer.getGraphics();
        // work your drawing magic here
        g.drawImage(buffer,0,0,null);
    }
}

Falling Ball (Balldrop) example (modified code)

The applet below shows how to drop a oval from the top of the screen. Gravity is used.




Below the sourcecode. I am still new at programming. I have no idea if this is the right way to do this and if I made mistakes.

 

import java.awt.*;
import java.awt.event.*;
import javax.swing.*;

public class BallDrop extends JApplet implements MouseListener, MouseMotionListener, Runnable {
    Graphics bufferGraphics;
  Image offscreen;

    private double xpos;
    private double ypos;
    private int radius;
    private int appletSize_x;
    private int appletSize_y;
    private double time;
    private double height;
    private final int GRAVITY = -10;
    private boolean isFalling = false;

    public void init() {

        xpos = getSize().width/2-10;
        ypos = 0;
        height = appletSize_y - ypos;
        time = 0;
        radius = 20;
        appletSize_x = getSize().width;
        appletSize_y = getSize().height;
        addMouseListener(this);
        addMouseMotionListener(this);
  setBackground(Color.black);
      offscreen = createImage(getSize().width,getSize().height);
       bufferGraphics = offscreen.getGraphics();
        new Thread(this).start();
    }

    public void run() {

        for(;;) { // animation loop never ends
            if (isFalling) {
                if(height - radius > 0) {
                    height =  height + (.5 * GRAVITY * (time * time) );
                    ypos = appletSize_y - height;
                    time += .02;
                } else {
                    isFalling = false;
                    time = 0;
                }
            }
            repaint();
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
            }
        }
    }

    //Overriding the paint method
    public void paint(Graphics g) {
     bufferGraphics.clearRect(0, 0, getSize().width,getSize().height);
        bufferGraphics.setColor (Color.RED);
        bufferGraphics.drawString("Balldrop - press mouse to drop/redrop",10,10);
        int x = (int) xpos;
        int y = (int) ypos;
        bufferGraphics.fillOval (x, y, 2 * radius, 2 * radius);
   g.drawImage(offscreen,0,0,this);
    }
    //Listeners
    public void mousePressed (MouseEvent e) {}
    public void mouseDragged (MouseEvent e) {}
    public void mouseReleased(MouseEvent e) {
        ypos = 0;
        height = appletSize_y - ypos;
        if (height > 0) { isFalling = true; }
    }
    public void mouseExited(MouseEvent e)  {}
    public void mouseMoved   (MouseEvent e) {}
    public void mouseEntered (MouseEvent e) {}
    public void mouseClicked (MouseEvent e) {}
}

Converting a float value into a integer - value intx = (int) floatx

In the code that I am modyfying and studying I found that you can convert float values into integer values by using the (int) characters.

intx = (int) floatx

for(;;) // animation loop never ends

I am studying and cleaning up a java source. I found that if you do the for(;;) in your code you get a neverending loop.

Researching player character Jumping.

I am searching the Internet trying to find information on how to let my rectangle jump in a java applet.

Until now I read that you should not use more then one timer.

 

boolean jumping:
long startTime;
if(!jumping)
{
 if(keyJump )
  startTime=System.currentTimeMillis();
}
else
{
   long jumpTime=System.currentTimeMillis()-startTime;
  //update player jump
}


Above is a little snippet that I found. It does not work if you compile it with java but shows that you can use System.currentTimeMillis() for getting timing that you can use to smoothly animate a jump.

I just found http://www.java4k.com I found it before but I forgot about it. I found a game that has jumping in it and am about to look through it. I am also looking through the other games to see if there is anything useful in it. The sourcecode suplied with the games can be pasted into the java editor.

Update :
I spend a hour or so trying to find a simple applet gravity bouncing ball/object but I could not find anything. I am now trying to find information on timers.

Creating an Image and drawing into a Image.

It took me a while. This is one of the first times that I actually started programming in java. I tried to create a image in memory and to draw in that created image.

The applet below shows a red block. This is a Image that was created in java and then drawin into using the red color. It is drawn only once into the applet.









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

public class MyCreateImage extends Applet
{
     Graphics bufferGraphics;
     Image offscreen;
     Image image2;

     Dimension dim;

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

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


     }

      public void paint(Graphics g)
     {
        bufferGraphics.clearRect(0,0,dim.width,dim.width);
        bufferGraphics.setColor(Color.red);
        bufferGraphics.drawString("CreateImageExample",10,10);
        g.drawImage(offscreen,0,0,this);
  g.drawImage(image2,30,30,this);

     }

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



 }



You can copy and paste this code into a java editor. Be sure to name the project as the same name as the class.

Double Buffering in applet source code/listing

Below is a applet that has double buffering. It draws a rectangle beneath your mouse pointer. i found the original source on the internet and removed the comments. This example is one of the things you need to program games.





 


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

public class DoubleBuffering extends Applet implements MouseMotionListener
{
     Graphics bufferGraphics;
     Image offscreen;
     Dimension dim;
     int curX, curY;

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

      public void paint(Graphics g)
     {
          bufferGraphics.clearRect(0,0,dim.width,dim.width);
          bufferGraphics.setColor(Color.red);
          bufferGraphics.drawString("Move the mouse in this applet",10,10);
          bufferGraphics.fillRect(curX,curY,20,20);
          g.drawImage(offscreen,0,0,this);
     }

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


     public void mouseMoved(MouseEvent evt)
     {
          curX = evt.getX();
          curY = evt.getY();
          repaint();
     }


     // The necessary methods.
     public void mouseDragged(MouseEvent evt)
     {
     }

 }




If you copy and paste this in your java editor be sure to have the name of the project the same as the class name. In this case DoubleBuffering. Also note that java is case sensitive and a applet will not be loaded if the characters of the filename are not completly the same.

Simple random obstacle avoidance method.

I found this trick while looking through books on google books. If you can not get past a obstacle then place the game character on a random location next to its former location. If you repeat this process then the character will eventually bypass the obstacle. It can take quite a number of moves until the obstacle is bypassed.

Slopes. some information that i found.

If you move a character horizontally and if a higher point is collided with then move the character up and check for collision again. Also check if there is a wall on the next horizontal location.

- Problem with shape/form of the character and slopes(non horizontal and non vertical screen regions) How do you place a character on a slope. Where do you place the feet? I have never programmed slopes before.I need to look this up.

Learning 3d game programming by learning 2d game programming.

I was a great fan of the videogame quake. The game is a 3d videogame. I read about one of the makers was programming 2d games before he started programming 3d games. I think a lot of knowledge of 2d game programming comes usefull when programming 3d games. I have programmed a couple of simple 3d games and found it pretty easy. Before I started programming in 3 dimensions I made a lot of 2d games.

A first person shooter looks and feels a little like the 2d platformer games.

Storing level data in a array.

From what I can find it seems that you can use the java array to store game level data. I am familiar with arrays in other programming languages.

I also found a listing/source showing how to directly build the game level using a array.

I found documentation showing that arrays have automating sorting build in.

Java still difficult to understand.

I still do not understand a lot of the java language. It will take me a while until I understand how to make something in java. What I find difficult at this moment is how to work with multiple classes and how to use them with each other. The book that I have shows a lot of lines are needed to let parts of the program work together.

I read somewhere that it takes months to learn java. I have used more then one programming language but I always directly started coding. I probably forgot to use a lot of language features. This time I am reading/researching a lot and am doing things step by step. I search/read little bits at the time. Things that are needed to make games in applets. I am starting with 2 dimensional games.

Selecting a Arraylist for object collision detection.

I read about the arraylist being used for speeding up collision detection in games. By adding objects into the arraylist that are near the player and looping/iterating through that list you do not have to check every object in the game. The arraylist item of a game object that leaves the direct vicinity of a player should be removed.

In my last games I looped through every game item with every other game item and checked the distance with the collided area before doing more checks with it.

Marching squares - reading about this for the first time. (collision with game level tiles)

I am using the http://www.java-gaming.org search to read through the collision posts. I found something called Marching squares. What I figure is that this generates a line on top of the maptiles (2d view) where the player walks on.

A wikipedia page in english on marching sqaures shows square cell grids where a line step by step is rounded around filled cells. I think I can also create game tiles that are somewhat rounded that way.

I have 'marched' player characters on graphics and learned this by programming lemmings. (look at Lemmings(mobygames/youtube)) By reading one pixel out of a image where the character is you can see if it is on or not on the map. By reading more pixels at the same time you can make the characters march vertically.

Preparing/thinking about game examples / snippets

I was thinking of creating a bunker bombing game where you drop a bouncing bomb that blows up a dyke where then the water then floods a battlefield causing a victory for your side. I was thinking what I will add to the game. Mixing and remaking lemmings with wings of fury.

I am taking apart the game and will make working parts of the game and will put the working applets and sourcecode on this blog.

I also am thinking about how to do more examples/nippets. A rolling ball of a hill that runs over ai. Throwing grenades, opening doors, A grappling hook. And more.

Combining / Mixing games to create new games. Ideas.

When I wrote music I sometimes remixed exsisting music. I also do this with game programming. Once I made a partial First person shooter combined with space invaders.

Yesterday I was thinking of thinking how I would combine the game asteroids and space invaders or turrican. I almost thought that the game pang was a combination of space invaders and asteroids. It is close I think.

Mixing or combining games might let you end up with  new original games.

Path finding / a* / shortest distance still a problem.

I have used path finding code made by others. I still do not understand how a complete path finding routine works. I have made partial working route planning by myself. This I did by looping thru all elements(all combinations) and finding the shortest one from point a to point b.

I am looking through a book on google books called "programming game ai by example" but it is in english and is difficult to understand.

Reading about Spatial partitioning / cell space partitioning.

I have spend  a good amount of time yesterday thinking what kind of examples/snippets I am going to make. I also have been reading in my java book. And have also been looking through examples/tutorials/snippets for mainly platformer games.

I have made a dozen or so platform games and was trying to put things out of existing games in. I have programmed movable blocks, disapearing tiles, springs, gravity, ladders/ropes, bullets, moving tiles,  lifts, water, ai and a lot more. I have been thinking how I would do things that I have not done yet. Things like climbing/sticking/moving on walls and ceilings and platforms and springs that launch you in other directions.

It has been a while since I programmed a game and I can not seem to remember entirely how I did the collision with objects and such. I remember making loops that loop thru all elements(slow) but also checking a short distance of the player for object collision/intersect checks. That kind of checking is called spatial partitioning. I am reading about it. It says something  about using lists. I am also looking at that.

dinsdag 29 maart 2011

The player moving through tiles or in tiles problem

When a game character falls down and falls faster per turn then the height of a tile then you wont be able to catch it with your collision detection code if you did not include that possibility..

I had the same problem a number of times and what I did was to loop through the step value and check each position with the character and the tiles. (The step value being the number of pixels per turn that the character falls down) This way it would always find the edge of a tile.

So it might be useful to check for collision with the most nearest map elements per 1 pixel movement change.

My back pains are a problem.

I get back pains if I sit for to long. The solution I have is to go rest on my bed. I can sit for a while before my back starts hurting. Long coding sessions I think will be a problem in the future.

Google code search as a learning resource

I got a Asteroids game compiling from the google code search results. The code search looks like a good resource for learning java.

Using html code tag to display sourcecode in posts

 

Code goes in here.

Testing text area in blog




There are linebreak characters in the textarea and I can not find how to remove them.

Testing - placing a applet in a blogger post.





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

public class test extends Applet {

public void init() {
}

public void paint(Graphics g) {

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

}
} 


FAIL.

It seems that it is not possible to show applets in blogger posts. I guess I will have to put them on a website.

Update...

It took me hours to figure out how to put a applet into blogger. I now use google sites to host the java files.

The biggest error I had was that I had to put a codebase tag in the blogpost html part. You have to have the folder there present. This without // behind it.

I also opened a fileden account which I also got working with blogger showing java applets.

maandag 28 maart 2011

still learning java.

I spend this weekend reading thru my java book.

Today I have been searching the internet for things that I needed in java. Collision is build into java. I still have to search for more performance information.

Java has Area collision detection. You can use polygon area's to check collisions with.

I also searched for image manipulation methods. setrgb and getrgb can be used to modify bufferedimages. There are also faster ways that got to do with rasters.

zaterdag 19 maart 2011

Studying from Java book and watching war on cnn

I have been reading thru my only java programming book. I wish I had a better one. I have read that classes are objects- i think.

Libia is being attacked by the millitary of several countries. cruise missiles have been used. Why do we pick agressive leaders to lead our nations.

donderdag 17 maart 2011

Spending time studying from a java programming book. Planet earth not that evolved yet.

I bought a beginners java programming book a couple of years ago and spend time reading thru it. The book is not that well organized and lacks the needed details but I am starting to learn. This weekend I will have more time to read thru the book. I will also study from a javascript book.

I also spend some time looking to find out if there were more info on good books. But the quality is low and bad reviews seem to dominate. Humans can barely prevent a nuclear disaster. Google will not show how the needed information to prevent disasters on top. Bad results.  Sharing the good things is problematic. I hope better politicians start to appear in the future and will start to introduce things that will boost the intelligence of people. I will not vote on dumb politicians. When will they place their raport cards online. They barely understand how to connect with people. If you write them smart emails then they will pass them thru to other politicians. But email is so hidden.
I am worried that agressive people will stay agressive for many years to come. The education system is not good at all. Bad books and bad teachers and bad students and bad parents. A lot of people that cause problems in the future. Huge badly organized religious cults. Few people influencing the way things are going to be done. Recently a political party suggested that certain schools should let the students and parents know how effective a certain study direction would be in the future. Unemployment is a big problem and what should you do in order to be succesfull. The search engines are difficult to use.

I hope the Internet and computers will help the evolution of the human race. I hope it is not a waste of time learning how to use computers and the internet. Hell it is better learning on the internet about criminals then being angry at them and wanting to kill them. Thousands of years we punished (tortured and killed) people and now we can begin to find the needed information on how the human body works and how to fix it. Do you smash a computer if it makes mistakes. I did when I was younger. Dumb thing to do. I am still not that smart. I to feel anger.

Be smart and keep studying.

Studying the good things to be able to make the good things.

I have read on the internet that succesfull people study in detail how a succesull something is make and write this down..  What is learning.

dinsdag 15 maart 2011

Amiga game parts remaking - lemonamiga.com

I browsed thru the entire amiga game titles on lemonamiga.com yesterday. I used youtube to view gameplay footage of games that caught my eye. I have several titles that I forgot the names of that I want to use to remake parts out of. To bad you can not place the titles in favourites on the site.

btw. I plan to release the source code of every game part remake on this blog and the example java applet.

Still researching java

I have used google to search for more information on java. I can not find anything good. It seems that I will have to learn how to make those parts of games myself.

Writing music for games

I have been writing music since the early ninetees. I can write music in tracker software and midi software. Back in the early ninetees I even got a letter from dr awesome(bjorn lynne) asking me if I could write music for his disk magazine. I can write music pretty well. But I never got good enough(still working on that)
What I have learned in writing music  is that you should memorize parts of populair music and use those parts to make your own music. You can hear this in the movie amadeus where mozart plays a song that someone else wrote. He used parts of his own populair music in it to make it sound better.
I spend a lot of time softly whisteling populair parts of music and changing and mixing that.

In better music from the top 40's you can clearly hear parts of other music in it.

zondag 13 maart 2011

c64 games. What parts can I remake.

Lemon64.com has a database of view of videogames of the commodore 64 computer. I am going thru the titles to see if there are interesting games there for remake programming. I use youtube to view the gameplay video's.

I already looked at the amazing spiderman on youtube and it looks like an interesting challenge. You can walk up walls and can walk on ceilings. The webbing looks interesting to. In the reactions I can read that there is an interest in the game.

Java game sourcecode on the internet

The search words brain postma show a result with serevel good games with source code in java. The most results in google that I have this far is dissapointing. The tutorial quality is low and few.

Writing errors

I found a couple of writing errors in the last post. I think I will leave them as is.

Research into language switch and availability of resources

I got interested in programming when I had a Amiga 500 computer. A Amiga 500 had only a 7 mhz processor and 512 kilobytes of memory. This was in the years of the late eigthies and early ninetees. I was interested in Assembler programming but since there was no internet yet I could not figure out how to program with this language. I bought Blitz Basic and started programming in that. I did not learn a lot about programming.
I got a pc and started programming in qbasic and visual basic. I switched to Blitz Basic for the pc. Computers got faster.

At the moment I have a Netbook which has a Atom processor at 1.6 ghz. The GPU for the graphics runs at 200Mhz. The electricity usage is lower then that of more expensive Notepads. You can pay up to 30 euro's a month for using a desktop with monitor that uses a lot of electricity. I remember the bills. A netbook can run a game like quake 3 which was played in the late ninetees and early twothousands. I checked demoscene demo's and a good selection of demo's and intro's work on the netbook.

I stopped using Blitz Basic and spend time looking into different languages. I found that Java is the most used language at this moment. There is a game programming forum on the internet which has about 30000 registrered users. The Minecraft inventor and programmer is a member of it to.

I spend hours looking up tutorials and sourcecode for java but could not find very good material. I used google. In the future I would like to be a good allround game programmer. The last searches I did was into flocking behaviours. I had the idea to program a battlefield and need to move troops(ovals) into position. I could not find sourcecode yet. I would like to learn more about real time strategy game programming. I did find several applet internet pages which contained a little bit of information. I need to search into how to find the individual coordinates out of a drawn line. This so I can move troops(ovals) with it. I also need to search how to drawn lines the have bends and how to get the individual coordinates from it.

I could not find good particle tutorials or sourcecode for java yet. Particles seem to be a good way to improve the goodlookiness of games. I have never programmed effects like particles that look blurry and smudgy and that seem to give of light. I hope to find a good resource.

There is something underneath the s key. I not always responds correctly.

The Monkey language of Blitz Research was released a couple of weeks ago and I follow the information on that. The language does not have image containers in memory so I decided not to use that language since i want to createand modify  images from code.. It looks like a load and paste kind of language. The language seem difficult to learn to. The documentation is bad since there is no example per language command. The lack of good examples make it hard to learn to. There is almost nothing to find on the internet that you can use to learn how to use the programming language.

I checked and blogger can contain java applets so in the future I will be able to put real time strategy game parts and platformer game parts and turn based strategy and action game parts and other game sorts parts as applets in the posts. All with sourcecode. I also did a quick lookup with google into free hosting and unlimited bandwith and webspace is available for free at this moment.

I also look at books as a source of information on programming but find that game programming books are not good enough. There is not a good book with descent gaming knowledge in the basic and c++ and java language. I would like to learn more about platformers. 8 bit game like spiderman, the part where you web and swing is something I want to make. Also physics is something I want to learn. I made a first part of level 1 of the Amiga game the Adams family and most books do not master that level of programming. I do read the reviews of books. And I check google books. I will continue to investigate game programming ebooks and books in the hope of finding that quality level material.

the website freecountry has a lot of programming language references. I was not able to find anything in it.

At this moment I am bothered by stomach acid. It feels anoying. My back sometimes also hurts. I do want to continue researching learning game programming in java and Monkey. I also keep track of news sites. The earthquake in japan was something big. It is still going on.

I do believe that I will stop using Blitz Basic 3d and +. Java seems more mature and faster to. I found information that it is as fast or close to as fast as c++. I also find information that the language is a lot slower.

Old java Applets seem to be badly supported by the google chrome browser. Language differences over the years seems a bad thing.

I have a java programming book. It is written in the dutch language. It is not that good but it might be usefull for when I am not using the internet and have spare time.

Well this is the first post.