Sunday, November 8, 2009

Programming the pong game with Java

The game has only two class. One JFrame to show the game window and one JPane to render the Graphics

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

public class MainWin extends JFrame {

    private JPanel jContentPane = null;
   
    private GamePanel panel = null; // This is the panel of the game class
   
    private GamePanel getPanel() {
        if (panel == null) {
            panel = new GamePanel(); // The panel is created
        }
        return panel;
    }

    /**
     * This is the default constructor
     */
    public Main() {
        super();
        initialize();
        this.addKeyListener(new KeyAdapter() {
            public void keyPressed(KeyEvent evt) {
                formKeyPressed(evt);
            }
            public void keyReleased(KeyEvent evt) {
                formKeyReleased(evt);
            }
        });
       
    }
   
    private void formKeyPressed(KeyEvent evt)
    {
        panel.keyPressed(evt);
    }
    private void formKeyReleased(KeyEvent evt)
    {
        panel.keyReleased(evt);
    }

    private void initialize() {
        this.setResizable(false);
        this.setBounds(new Rectangle(312, 184, 250, 250)); // Position on the desktop
        this.setMinimumSize(new Dimension(250, 250));
        this.setMaximumSize(new Dimension(250, 250));
        this.setContentPane(getJContentPane());
        this.setTitle("Pong");
    }
    private JPanel getJContentPane() {
        if (jContentPane == null) {
            jContentPane = new JPanel();
            jContentPane.setLayout(new BorderLayout());
            jContentPane.add(getPanel(), BorderLayout.CENTER);
        }
        return jContentPane;
    }
   
    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                Main thisClass = new Main();
                thisClass.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                thisClass.setVisible(true);
            }
        });
    }
}
 The second class contains the code for the game logic and the game rendering
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;


public class GamePanel extends JPanel implements Runnable {
   
    private static final long serialVersionUID = 1L;
        // Positions on X and Y for the ball, player 1 and player 2
    private int pelotaX = 10, pelotaY = 100, jug1X=10, jug1Y=100, jug2X=230, jug2Y=100;
    Thread hilo;
    int derecha=5; // to the right
    int izquierda= -5; //to the left
    int arriba=5; // upward
    int abajo= -5; // down
    int ancho, alto; // Width and height of the ball
    // Scores
    int contPlay1=0, contPlay2=0;
    boolean player1FlagArr,player1FlagAba, player2FlagArr, player2FlagAba;
    boolean juego, gameOver;
   
    public GamePanel(){
        juego=true;
        hilo=new Thread(this);
        hilo.start();
    }
   
    // Draw ball and ships
    public void paintComponent(Graphics gc){
        setOpaque(false);
        super.paintComponent(gc);
       
        // Draw ball
        gc.setColor(Color.black);
        gc.fillOval(pelotaX, pelotaY, 8,8);
       
        // Draw ships
        gc.fillRect(jug1X, jug1Y, 10, 25);
        gc.fillRect(jug2X, jug2Y, 10, 25);
       
        //Draw scores
        gc.drawString("Jugador1: "+contPlay1, 25, 10);
        gc.drawString("Jugador2: "+contPlay2, 150, 10);
       
        if(gameOver)
            gc.drawString("Game Over", 100, 125);
    }
   
    // Positions on X and Y for the ball
    public void dibujarPelota (int nx, int ny)
    {
        pelotaX= nx;
        pelotaY= ny;
        this.ancho=this.getWidth();
        this.alto=this.getHeight();
        repaint();
    }
   
    // Here we receive from the game container class the key pressed
    public void keyPressed(KeyEvent evt)
    {
        switch(evt.getKeyCode())
        {
            // Move ship 1
            case KeyEvent.VK_W :
                player1FlagArr = true;
                break;
            case KeyEvent.VK_S :
                player1FlagAba = true;
                break;
                       
            // Move ship 2
            case KeyEvent.VK_UP:
                player2FlagArr=true;
                break;
           case KeyEvent.VK_DOWN:
               player2FlagAba=true;
                break;
        }
    }
   
    //    Here we receive from the game container class the key released
    public void keyReleased(KeyEvent evt)
    {
        switch(evt.getKeyCode())
        {
            // Mover Nave1
            case KeyEvent.VK_W :
                player1FlagArr = false;
                break;
            case KeyEvent.VK_S :
                player1FlagAba = false;
                break;
                       
            // Mover nave 2
            case KeyEvent.VK_UP:
                player2FlagArr=false;
                break;
            case KeyEvent.VK_DOWN:
               player2FlagAba=false;
                break;
        }
    }
   
    // Move player 1
    public void moverPlayer1()
    {
        if (player1FlagArr == true && jug1Y >= 0)
            jug1Y += abajo;
        if (player1FlagAba == true && jug1Y <= (this.getHeight()-25))
            jug1Y += arriba;
        dibujarPlayer1(jug1X, jug1Y);
    }
   
    // Move player 2
    public void moverPlayer2()
    {
        if (player2FlagArr == true && jug2Y >= 0)
            jug2Y += abajo;
        if (player2FlagAba == true && jug2Y <= (this.getHeight()-25))
            jug2Y += arriba;
        dibujarPlayer2(jug2X, jug2Y);
    }
   
    // Position on Y for the player 1
    public void dibujarPlayer1(int x, int y){
        this.jug1X=x;
        this.jug1Y=y;
        repaint();
    }
    // Position on Y for the player 2  
    public void dibujarPlayer2(int x, int y){
        this.jug2X=x;
        this.jug2Y=y;
        repaint();
    }
   
    public void run() {
        // TODO Auto-generated method stub
        boolean izqDer=false;
        boolean arrAba=false;
       
        while(true){
           
            if(juego){
           
            // The ball move from left to right
               if (izqDer)
            {
                // a la derecha
                pelotaX += derecha;
                if (pelotaX >= (ancho - 8))
                    izqDer= false;
            }
            else
            {
                // a la izquierda
                pelotaX += izquierda;
                if ( pelotaX <= 0)
                    izqDer =  true;
            }
              
              
            // The ball moves from up to down
               if (arrAba)
            {
                // hacia arriba
                pelotaY += arriba;
                if (pelotaY >= (alto - 8))
                    arrAba= false;
                   
            }
            else
            {
                // hacia abajo
                pelotaY += abajo;
                if ( pelotaY <= 0)
                    arrAba =  true;
            }
               dibujarPelota(pelotaX, pelotaY);
              
            // Delay
            try
            {
                Thread.sleep(50);
            }
            catch(InterruptedException ex)
            {
               
            }
           
            // Move player 1
            moverPlayer1();
           
            // Move player 2
            moverPlayer2();
           
            // The score of the player 1 increase
            if (pelotaX >= (ancho - 8))
                contPlay1++;
                           
            // The score of the player 2 increase
            if ( pelotaX == 0)
                contPlay2++;
                                       
            // Game over. Here you can change 6 to any value
                        // When the score reach to the value, the game will end
            if(contPlay1==6 || contPlay2==6){
                juego=false;
                gameOver=true;
            }
           
            // The ball stroke with the player 1
            if(pelotaX==jug1X+10 && pelotaY>=jug1Y && pelotaY<=(jug1Y+25))
                izqDer=true;
           
            // The ball stroke with the player 2
            if(pelotaX==(jug2X-5) && pelotaY>=jug2Y && pelotaY<=(jug2Y+25))
                izqDer=false;
            }
        }
    }
   
}

First Person Shooter Game

3D game development is an exciting activity for many students. But getting a handle on 3D game development for novices may be a daunting task. We take this opportunity to present a quick introduction to 3D game development through a few tutorials. For the next few columns a set of tutorials for a 3D first person shooter game developed by graduate and undergraduate students under the guidance of a faculty member from the University of West Florida will be presented. These tutorials were developed with 3D game Studio by Conitec. To follow along, download the software from www.conitec.com. These tutorials include all elements of game development such as modeling and animation, lighting, collision detection, sound and scripting. Each tutorial will focus on one or more of these aspects. This week we start out with creating a room and adding some objects to the room. The instructions for this are presented below.



1  IMPORTING A MODEL

Importing a Model is easy and fun! Models can include your character, non-player characters, level objects, weapons, health supplies, etc. To make a working entity in GameStudio, you must first import a 3D model and then assign functions, or behaviors, to the model. These functions give models unique properties. For example; if you import a model of an elf, you can assign player functions to the model that will allow you to control the elf. Likewise, if you import a health pack, the functions you assign to it will make the model act like a health pack. Things can get really crazy if you assign functions to models incorrectly! How funny would it be if you ran into the elf and it healed you while you controlled the movement of a health pack!
  1. First open the WED (World Editor Program), and click Object -> Load Entity

  1. It is very important that your model is saved into GameStudio's "Work folder"
    This folder is usually under
    "C:\Program Files\GStuido6\work"
    – this is the default folder in the popup menu

  1. From here, select your model and Click Open (open "cbabe.mdl" or "warlock.mdl" )

  1. Notice that "cbabe" may be outside of your room. To get her within the room, simply click the Move button (on the toolbar) and drag her into the room. Be sure to examine all windows to make sure that she's properly aligned

  1. Your model is now inserted into your level. Wow! That was easy! You can now continue to move this model wherever you want it in your level. You can resize and rotate it!

2 ASSIGNING A FUNTION/BEHAVIOR

Once you have the model in your level, you probably want it to do something. In order for your model to have some sort of properties, you must assign a function, or Behavior, to the model. To begin with, make sure that you have assigned a script to the game that you are making. The script, which is written in a programming language called C-Script, is what contains all the variables, functions, and other bits of code that will add to making your game awesome!

Code1.wdl

Open the SED (Script Editor) and copy & paste this code into it. Save the file as "Code1.wdl" into the work folder (usually under " C:\Program Files\GStuido6\work ")



  1. To add a script to your game, click on File à Map Properties

  1. A pop-up menu entitled Map Properties will appear. As you can see in the Script Box, no script has been defined. To do this, click the Folder icon to the right of the Script Box

  1. A pop-up menu will open that defaults to the "Work Folder." From here, select the script file (".wdl") that contains the code for your game. We will use "Code1.wdl"

  1. Now you will return to the Map Properties dialog box. As you can see, the script file is now inside the Script Box

  1. Then close this menu out simply by clicking the close button. Clicking the red X to the right of the Script Box will remove the script you just added to your game

  1. Now select the model that you want to add a Behavior to. When selected, your model will appear in a red wire frame

  1. Right-Click the selected model and choose Behavior

  1. A pop-up menu will appear. In this menu, you can select the Behavior that you want your model to have. The Behaviors are described in your script. For example, if you want your model to be the character that you play as, choose "my_player" for a health pack, choose "health_pack," etc. You can customize any Behavior and even create your own in the script. But for now, simply select "my_player" and press OK

  1. Your model now has the Behavior that you chose for it! See how easy and fun that was? You now should have learned all the basic elements of creating a game. If you want to Build and Run your game, you can do so now!

3  COMPLILING AND RUNNING

In order to test a game out, it needs to be Compiled. Compiling takes all the code, models, and levels that have been put together and converts it into a language that the computer can readily understand: machine language !
Please take note that this doesn't create your executable file. This simply allows you to "run" your game
  1. First, Click the Build button

  1. A pop-up menu will appear that lets you adjust what exactly you want to compile or update. If you're just doing a quick test, make sure that your Visibility Calculations and Light Calculations are set to Off and Low Quality. This will dramatically reduce the time it takes to compile your game. You shouldn't be able to see a difference between these settings, and (for productivity purposes) you should wait to turn these on until you have finished tweaking your game

  1. Make sure that the Build Level button is selected and click OK

  1. A Map Compiler dialog box will appear and, depending on the complexity of your game, the time it takes to compile your game will vary.

  1. Click the Run button

  1. Click the Ok Button once more in the "Run Level" dialog box

  1. Your game will now start! Now how have some fun!

Congratulations you now have all the basic skills to make your own game using GameStudio! Now begin making your own fun games!

source www.jot.fm/issues/issue_2008_01/column5

Flash MX First Person Shooter Game Tutorial


In this Flash tutorial we shall set out the basics for a First Person Shooter Game (hereafter called an fps).

  • We shall do the basics of attaching the gun sights to the mouse movement and hiding the standard mouse icon,
  • Making bullet holes in the background,
  • creating a gun firing sound,
  • and testing for a hit on a very basic moving target.
Later on, I will write a more complex tutorial to fill in the details.
Flash Tutorials in Video Format - Watch them now at LearnFlash.com  

Create the hit area button for the game

Let's start.

  1. Choose the rectangle tool and drag a rectangle to cover the whole stage.
  2. Select the rectangle and hit key F8 and create a button. Call it "hitArea".
  3. Open the library and double click on the hitArea button.
  4. Go to the first frame and hit key F6 to create 3 more keyFrames.
  5. Delete the first 3 frames of the button and leave the "hit" frame. This is going to be an invisible button and when the mouse is clicked , the gunfire sound will play and a bullet hole will appear in the background.
  6. Select the hitArea button on the main stage and in its properties window, call its instance name "hit1".

Load the gunfire Sound


  1. Find or edit a gunfire sound.
  2. Select menu item "File" - "Import to library" and select the audio file. The audio file will appear in the library.
  3. Right click on the audio file and select "linkage".
  4. Tick the "export for Actionscript" textbox and in the identifier box, write "gunfire".
  5. Lock the frame that the hit button is on and create another layer and call it "code".
  6. Hit the F9 key to open the Actions window. Write this code :
  7. // gunfire sounds
    var gunfire = new Sound();
    gunfire.attachSound("gunfire");
    // When mouse is clicked, start sound 
    _root.hit1.onPress = function() {
     gunfire.start();
    }
    

Create the Gun Sights for the game


  1. Create another layer and call it "sights".
  2. Draw a gun sight however you want.
  3. Select the drawing and press F8 to make a movieclip.
  4. Call it "gun".
  5. With the gun still selected name it "gun" in the instance name texbox in the properties window.
  6. Lock its frame and go to the "code" layer and add this under the code we entered earlier :
  7. // initialise the movie
    _root.onLoad = function() {
     // hide the mouse
     Mouse.hide();
    };
    // loop code
    _root.onEnterFrame = function() {
     //put cross hairs to mouse coords
     _root.gun._x = _root._xmouse;
     _root.gun._y = _root._ymouse;
    };
    
    
  8. Hit keys Control + Enter to test the movie. The gunshights should follow the mouse. and when you click the mouse, your gunshot sound should play.

Make the bullet holes


  1. Create a new layer and draw a 20 pixel circle.
  2. Select it and hit key F8 , create a new MovieClip, call it "bullet".
  3. Name it "bull" in the instanceName textbox.
  4. With the bullet hole movieclip selected, write this code in the Actions Window:

  5. onClipEvent(load){
     this._x = _root._xmouse;
     this._y = _root._ymouse;
    }
    
  6. It should say "Actions - Movie Clip" at the top of the Actions window and not "Actions - Frame".
  7. Now select The "code" layer and rewrite the code to this:

  8. var i;
    // gunfire sounds
    var gunfire = new Sound();
    gunfire.attachSound("gunfire");
    _root.hit1.onPress = function() {
     gunfire.start();
     i++;
     //  create bullet holes
     _root.bull.duplicateMovieClip("bulletNew", i);
     if (i == 10) {
      i = 0;
     }
     
    };
    // initialise stuff
    _root.onLoad = function() {
     // hide the mouse
     Mouse.hide();
    };
    //loop
    _root.onEnterFrame = function() {
     //put cross hairs to mouse coords
     _root.gun._x = _root._xmouse;
     _root.gun._y = _root._ymouse;
      
    };
    

Make the Target MovieClip


  1. Make a new layer and call it target.
  2. On it , draw some sort of target. I just made a square 50x50.
  3. Select it and create a Movieclip, call it target_mc in the InstanceName textbox.

Make the explosion for the game


  1. In the library , double clik on the gunsight movieclip.
  2. Select the first frame and hit key F6 to create another keyframe on frame 2.
  3. Delete the contents on frame 2 and draw some sort of explosion. Just a red splash should do.
  4. Create another layer ,
  5. make a keyframe on frame 1 and
  6. put this code in :

  7. stop();
     
Now lets finish off the coding for the hitTest on the target and the moving of the target. For now , we will just move it across the screen.
Go back to the main timeline and select the code layer and delete what was in there and put this in:

var i;
// gunfire sounds
var gunfire = new Sound();
gunfire.attachSound("gunfire");
_root.hit1.onPress = function() {
 gunfire.start();
 i++;
 // make bullet holes 
 _root.bull.duplicateMovieClip("bulletNew", i);
 if (i == 10) {
  i = 0;
 }
 // hit test on target
 if (_root.target_mc.hitTest(_root._xmouse, _root._ymouse, false)) {
  // play explosion
  _root.gun.gotoAndPlay(2);
  // send target off stage
  _root.target_mc._x = 0;
  _root.target_mc._y = random(400);
 }
};
// initialise stuff
_root.onLoad = function() {
 // hide the mouse
 Mouse.hide();
};
//loop
_root.onEnterFrame = function() {
 //put cross hairs to mouse coords
 _root.gun._x = _root._xmouse;
 _root.gun._y = _root._ymouse;
 // target move
 _root.target_mc._x += 10;
 // if it goes offstage, send it stage left
 if (_root.target_mc._x<0 || _root.target_mc._x>Stage.width) {
  _root.target_mc._x = 0;
  _root.target_mc._y = random(400);
 }
};

It is a pretty lame movie but it shows you the basics of a first person shooter game in Flash MX. Next tutorial, we will refine it a lot more and make a real game. So have a good think about it and experiment with it by yourselves in the meantime. Create some targets and make them pop up here and there. Experiment with a scoring system and think about adding further levels. Do it yourself and impress us all with your efforts.

Game Resources

Flash MX2004 tutorials
"Flash MX Bible" by Robert Reinhardt
Download the file here

source www.video-animation.com/flash_32.shtml

Programming a Multiplayer First Person Shooter in DirectX

by Vaughan Young


Programming a Multiplayer First Person Shooter in DirectX Cover
ISBN13: 9781584503637
ISBN10: 1584503637

Synopses & Reviews

Publisher Comments:

If you have experience with C++ and DirectX and have always wanted to program your own game, this is the book for you. Programming a Multiplayer FPS in DirectX takes you from the basic game design to a fully functioning game! All of the source code, assets, and tools are included- you just work through the tutorial-based chapters and watch the game come to life as you develop it. And as new features are added, you can begin playing with them to see them in action. Following a typical game development process, the book is separated into two distinct parts: Part One focuses on the design and development of the game engine, and Part Two concentrates on putting the game together using the engine. The theory has been kept to a minimum, so that you are following a hands-on approach and adding new functionality to your engine as you proceed. In the first part, you'll learn about the many facets of DirectX, C++, and object-oriented programming. You'll also learn how to design the engine and put the infrastructure into place. The next chapters will each add a new module to your engine including input, scripting, 3D rendering, sound, networking, and scene management. The second part covers the final development stages, including everything from game play to player management; it culminates with the complete multiplayer FPS game. Throughout the book you'll learn key topics that will bring you up to speed with industry proven techniques, while improving your confidence as a developer. And because DirectX is the most prevalent game development tool available, once you master this project, you'll have the skills you need to create a variety of games!

Book News Annotation:

Intended for beginning programmers familiar with C++ and DirectX, this guide walks through the design and development of a 3D game engine for the first person shooter (FPS) genre, then builds sample game play on top of it. It covers engine control, scripting, Direct3D rendering, sound, networking, meshes, objects, scene management, players, and weapons. The CD-ROM contains source code and the DirectX SDK 9.
Annotation �2004 Book News, Inc., Portland, OR (booknews.com)

Synopsis:

This book teaches beginning C++ programmers how to develop their own first person shooter game from scratch. The book uses DirectX and helps prepare users for future game development. Using a tutorial approach, each chapter builds upon the next as the game evolves from the basic design to a fully functioning game.J

Synopsis:

Teaches aspiring game programmers and students how to program a complete FPS game using DirectX and C++.

About the Author

Vaughan Young (Queensland, Australia) is an experienced C++ and DirectX programmer. His degree in IT is complemented by further studies in software developm

Table of Contents

Part I The Engine 1 1 Engine Design 2 Framework 3 Engine Control 4 Scripting 5 Rendering 6 Sound 7 Networking 8 Materials and Meshes 9 Objects 10 Scene Management Part II The Game 389 11 Foundations 12 Players 13 Weapons Appendix A: About the CD-ROM Appendix B: Competition

Saturday, November 7, 2009

Resident Evil 5 PC


The PC game that i played this month is Resident Evil 5 from Capcom. The new sequel from the from the well known survival horror series contains a very interesting plot with some of the classic characters  involved in it and goes the genre one step forward. What is new and remarkable about this game;
For the first time in the game series there is co-op action and you can play it in multilayer mode. I have played any Resident Evil have been produced for PC and i was very familiar with the characters and the plot but since the first Resident Evil created 13 years earlier programmers/designers have inserted logs about the game history for the new gamers.and provide a briefing about the past. and the characters  So if you are new gamer you will get a pretty good idea about what is going on.
You control Chris Redfield one of the protagonist characters of the Arklay Mansion case from the first Resident Evil. In this lifetime Chris has joined a worldwide military group known as the Bioterrorism Security Assessment Alliance that fights against terrorists that spread biological weapons. After the Raccoon city incident (Resident Evil 2,3) the Umbrella corporation has been shut down but viruses has gone to the hands of terrorists and are spreading to Africa. So Chris is sent to a fictional African Region to investigate what is going on. Chris is not alone in this case, at the beggining of the mission you meet yout new partner Sheva Alomar. During the game you will meet faces from the past like Albert Wesker and you will go against a threat that you have never met before. All these in 6 chapters. that takes about 20 hours to finish The game follows a cinematographic style of view, something that is obvious through the game cuteness that are full of "Matrix" effects :-).

As i said this game is played in co-op mode. In single player mode you control Chris and computer controls Sheva. There are two different inventories with nine slots at each one that you must store weapons, bullets, medicines, Because of the fact of the two characters and the co-op mode you have to deride witch staff goes to Chris and which to your partner. You have to take care of enemies that are about to kill your partner etc. And off course your partner will help you during the battle and when monsters are over you. The perspective of the game is the same with Resident Evil 4, camera is behind Chris 's b ack and follows him all the time. You control Chris with the mouse to turn around and with the keys "w","a","s","d "to move forward,left,back and right. When you press shift Chris runs. By pressing the "t" key Chris make a slash with his knife, space aims with the knife, right mouse button aims with the gun and left mouse button is the fire.
Resident Evil 5 as the previous on has left behind any adventure elements that existing in the the first three titles. The game is based almost 100% on action and fighting. Except an extremely easy part with mirrors  you will keep on shooting and shooting monsters. This is not bad but i miss the essence of the first one. Probably this is the only thing that i did not like on Resident Evil 5 (and 4). Something else that RE 5 kept from the 4 is the zombies. These zombies are not stupid, they have weapons like rifles, shotguns or even and rocket lancers. Now they have even bullet proof armor. You will face many different  enemies in the game like mutated dogs, incests, giants and you need to follow specific combat strategies to take care each of them.

In this game there is not the known save system with the ink ribbons, there are just checkpoints with auto save. When you implement some part of your mission without any user action the game is just saved.
During the missions you collect coins,jewels etc. and after any chapter or dieing you can sell them to buy or upgrade weapons and medicines. You can buy and find many weapons during the game like handguns, Kalashnikov Ak-47, magnum, rocket lancer etc. Like the previous game there are bosses that you can wipe out only with one rocket.
As you can see from the images the graphics are amazing and the cut-scenes even better. I have played the game on a Inter core 2 quad 2.8Ghz with 4GB of ram and the nvidia 9800Gt with everything on full and the game runs smoothly. I do not know the exactly system requirements of the game but if you have a system like mine you will not have any problems. The sound is not something special but is good and gives the proper atmosphere to the game.



I am thinking about to start giving a rank to every game that i reviw so for Resident evil i will give a 9/10
The game is fun, the graphics are very good, plot is well written the only thing that i did not like is that there are no adventure elements. Probably it could be a little bit bigger.