Showing newest 23 of 42 posts from December 2008. Show older posts
Showing newest 23 of 42 posts from December 2008. Show older posts

Tuesday, December 30, 2008

Creating a 3D Menu using FengGUI #4

Now we are going to start off by creating a main menu using the FengGUI. Under your project, you should have a src directory, a lib directory, and you should create an image directory.

In the image directory you should paste the following two images. These images will be used for our main menu. We are only going to initially create a menu with one button that says play. We can later add some more images to quit the game or do other functions.














You should create a package under the src directory called com.guid.asteroid3D and create two classes under that package called Asteroid3DStart.java and MainMenu.java. Paste the following code into those classes.

MainMenu.java

package com.guid.asteroid3D;

import org.fenggui.Container;
import org.fenggui.Display;
import org.fenggui.GameMenuButton;
import org.fenggui.background.PlainBackground;
import org.fenggui.composites.MessageWindow;
import org.fenggui.event.ButtonPressedEvent;
import org.fenggui.event.IButtonPressedListener;
import org.fenggui.layout.RowLayout;
import org.fenggui.layout.StaticLayout;
import org.fenggui.util.Color;
import org.fenggui.util.Spacing;

public class MainMenu
{

private GameMenuButton play;

public void buildGUI(Display display)
{
final Container c = new Container();
c.getAppearance().add(new PlainBackground(Color.BLACK));
display.addWidget(c);
c.getAppearance().setPadding(new Spacing(10, 10));
c.setLayoutManager(new RowLayout(false));

initButtons(c, display);

buildMainMenu(c, display);
}

private void initButtons(final Container c, final Display display)
{
play = new GameMenuButton("C:/Programming Tools/eclipse/workspace/JMENewProject/src/images/play.jpg", "C:/Programming Tools/eclipse/workspace/JMENewProject/src/images/play1.jpg");

play.addButtonPressedListener(new IButtonPressedListener()
{
public void buttonPressed(ButtonPressedEvent e)
{
MessageWindow mw = new MessageWindow("Nothing to play. Just a demo.");
mw.pack();
display.addWidget(mw);
StaticLayout.center(mw, display);
}
});

}

private void buildMainMenu(final Container c, final Display display)
{
c.removeAllWidgets();

c.addWidget(play);

c.pack();
StaticLayout.center(c, display);

}

}





Asteroid3DStart.java

package com.guid.asteroid3D;

import javax.media.opengl.GL;
import javax.media.opengl.GLAutoDrawable;
import javax.media.opengl.GLCanvas;
import javax.media.opengl.GLEventListener;
import javax.swing.JFrame;
import org.fenggui.Display;
import org.fenggui.FengGUI;
import org.fenggui.render.jogl.EventBinding;
import org.fenggui.render.jogl.JOGLBinding;

import com.sun.opengl.util.Animator;

public class Asteroid3DStart extends JFrame implements GLEventListener {

private static final long serialVersionUID=123l;
private GL gl = null;
private GLCanvas canvas = null;
private Display display = null;

public Asteroid3DStart() {

canvas = new GLCanvas();
canvas.addGLEventListener(this);
getContentPane().add(canvas, java.awt.BorderLayout.CENTER);
setSize(600, 400);
setTitle("Asteroid3D");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
Animator animator = new Animator(canvas);
animator.start();
}


public void init(GLAutoDrawable drawable) {
gl = drawable.getGL();
gl.glClearColor(1.0f, 0.8f, 0.2f, 0.0f);

display = FengGUI.createDisplay(new JOGLBinding(canvas));
new EventBinding(canvas, display);
MainMenu menu=new MainMenu();
menu.buildGUI(display);

}


public void display(GLAutoDrawable drawable) {
gl.glLoadIdentity();
gl.glClear(GL.GL_COLOR_BUFFER_BIT | GL.GL_DEPTH_BUFFER_BIT);
display.display();
}


public void displayChanged(GLAutoDrawable drawable, boolean modeChanged, boolean deviceChanged) {
// do nothing
}


public void reshape(GLAutoDrawable drawable, int x, int y, int width, int height) {
// do nothing
}

public static void main(String[] args) {
new Asteroid3DStart();
}

}


The Asteroid3DStart.java class contains the main method. We are also going to use it as the games JFrame, and we will use it for the GLEventListener. You create the canvas object which is need to paint the openGL objects. You also need the GLEventListener to keep track of the openGL events. You have to add the canvas to the Frames ContentPane. You also have to activate the animator to keep the canvas painted as events happen. The init method is required by the GLEventListener. In that class, you will create the FengGUI display. You will pass that object to the MainMenu which will build your FengGUI Menu.

In the MainMenu class, you call the method buildGUI. In this class you will create a container that will hold your menu objects. You will also set the layout information in this container. You will call the initButtons method which creates the GameMenuButton object and adds its listener. When the button is pressed, the listener is called. Make sure you set the correct path to the images you downloaded. The second image is the mouseover image. The buildMainMenu adds the object to the container.

Go To #5

Read more...

Monday, December 29, 2008

Installing FengGUI and JME Physics for a Game 3D in Java #3

Now we want to set up these technologies to help us develop our 3D game.  Remember, that the eclipse version I am using is Ganymede.

Here is how to install FengGUI and  JME Physics  

FengGUI:

Download FengGUI at: 
http://sourceforge.net/project/showfiles.php?group_id=178317

You should unzip it and copy all of the jar files into your lib folder.  Set your build path to have eclipse point to the new jar files.

JME Physics:

In eclipse, select Java>new Project->cvs->projects from CVS
 
Host: cvs.dev.java.net
Repository path: /cvs
User: guest
Password: leave blank
Connection type: pserver
Click save password and select finish

This would be the same cvs repository that you used to checkout JME.  So if you have already checked out JME, then you would already have this information in eclipse.

In the Package Explorer right-click the jMEphysics2 project → Properties → Java Complier and un-check Enable project specific settings.
To add ODEJava to jMEphysics2, right-click the jMEphysics2 project → Properties → Libraries tab → Add Library… → User Library → Next → User Libraries… → New…. In the pop-up enter ODEJava, click OK → Add JARs…, browse to jMEphysics2/impl/ode/lib/ and select odejava-jni.jar → Open. Expand odejava-jni.jar and select Native library location → Edit… → Workspace… → expand to jMEphysics2/impl/ode/lib → OK → OK → OK. Now check ODEJava and click Finish.
 
To add the JME physics to your project, go to the properties for the project using the JME physics, select java build path->projects tab->add->select jmephysics and press okay. 
 
Go To #4

Read more...

Saturday, December 27, 2008

Production Scheduling Software

Are you a company looking for Production Scheduling Software that will actually give you the tools to create an optimal and feasible production schedule?  Well you are in luck.  There is some software that can help you accomplish this task that uses the latest advancements in artificial intelligence.  With this software package, you can create an optimal schedules while it meets the number of important priorities.  If you want to see some professional reviews of this software, you should visit production-schedule.com.  They have articles that discusses production schedule software.  They even have a search on their website where you can search through their articles.  The current production software they are reviewing is the Tuppas software package.  These software systems uses Artificial Intelligence to take into account numerous constraints. Many companies have been implementing Advanced Planning Software (APS)  to improve their business, and that is the purpose of these articles. The intent is to help companies make intelligent decisions when purchasing an APS system.  An APS system allows optimization with custom filters and advanced planning functionality. So if you are looking for some software that can improved your productivity by allowing you to have an improved production schedule, then you need to visit the production schedule website and see how they can help you.  

 

Read more...

Wednesday, December 24, 2008

Adding Image with Onclick to Dom Tree using Ajax Step 50

Sometimes using Ajax you will need to add the objects to the DOM tree in your jsp page.

For example, if you have an image that is a calender and you want to display it using Ajax, you will need to add it to your DOM tree.

You have to becareful about how you implement this because different browsers operate in different ways.

Here is an example of that.

In my javascript function I have a loop where x is the value from the loop:

This code creates an input text box and sets its attributes. This box will hold the data from the calender. This code works correctly.

var td5=document.createElement("input");
td5.setAttribute("type","text")
td5.setAttribute("id","candidateProject.projectDeliverables[" +x+ "].neededByAsStr");
td5.setAttribute("name","candidateProject.projectDeliverables[" +x+ "].neededByAsStr");
td5.setAttribute("size","11");
td5.setAttribute("value",items[x]);
td5.setAttribute("readOnly","true");
document.getElementById("deliverable"+ x).appendChild(td5);

This code will add the calender object to the DOM tree. I want the calender to work in IE and Firefox and this code here only works in IE.

var newString="<img onclick="'displayCalendarDeliverable(this," height="'20'" alt="'Calendar'" src="resources/images/cal.gif" width="'20'" />";
td5=document.createElement(newString);
document.getElementById("deliverable"+ x).appendChild(td5);


The correct way would be to create an object like this:

var image = document.createElement("img");
image.setAttribute("alt","Calendar")
image.setAttribute("width",20)
image.setAttribute("height",20)
image.id="image"+ x
image.src ='resources/images/cal.gif';
document.getElementById("deliverable"+ x).appendChild(image);

This last bit of code is to be used to create the onclick functionality. However, this code works if the X wasn't a variable, but it is a variable, so it doesn't work.

document.getElementById("image"+x).onclick=function(){displayCalendarDeliverable(this,x);}

There are a few different ways to do this:

document.getElementById("image" +x).onclick=Function("displayCalendarDeliverable(this," +x+ ")"); }

or

document.getElementById("image" +x).onclick=function(){displayCalendarDeliverable(this, Number(this.id.substr(5))); }



Ajax SweetDev Tutorial for More Ajax
Go To Step 51

Read more...

Tuesday, December 23, 2008

Adding Object to List using Ajax and Struts Step 49

Now that you added the appropriate data to your url, you will need to grab that data from the server. You should add this code to your saveBookAjax method.


String bookname=request.getParameter("book");
String author=request.getParameter("author");
String publisher=request.getParameter("bookPublisher");
String category=request.getParameter("category");
userForm.setAuthor(author);
userForm.setBookPublisher(publisher);
userForm.setBook(bookname);
userForm.setCategoryId(category);
this.saveBook(mapping, form, request, response);


This code sets all the objects in the form just like you did when you submitted the form. Since you already have a method that creates the new book object, you can call the saveBook method to finish adding the book to the database.
Go To Step 50

Read more...

Configuring and Installing JME #2

Now you need to install the JME onto your computer. You should get the latest version from cvs. You can do this by opening up your eclipse, select Window->show view->other. Then you should select the CVS Repository. Under the CVS Repositories tab, you should right-click in its view space->New->repository location.

Host: cvs.dev.java.net
Repository path: /cvs
User: guest
Password: leave blank
Connection type: pserver
Click save password and select finish


Expand the Head from the cvs Repository menu. Find the jme folder, right click it and select checkout as...

In the check out as popup you should check the option check out as a project configured using the New Project Wizard, checkout subfolders should always be checked, and then click finish.

Select Java Project in the new project wizard.

Select create new project in workspace and put jme for project name.
Also select "user project folder as root for sources and class files" and
check the JRE you are using.

click next.

Select create new source folder under source tab.

Put src under the folder name.

select replace existing project source folder entry to solve nesting.

Select Allow output folders for source and put jme/bin in the default output folder. Press finish.

You now have successfully create your jme project.

In your current project where you will build your game you need to create a reference to the JME. You can do this by going to the projects Java Build Path and select the project tab. You can select add and select the jme from your project list. Press okay when you are done.

Your JME is ready for use.
Go To #3
 

Read more...

Passing Data to the Server Using Ajax, Converting it to HTML Step 48

Now that you have the data in your Ajax function, you will want to pass the data to the server to add the object to the database. You would first add the items to your URL like this.
url=url+"&book="+book+"&author="+author+"&publisher="+publisher+"&category="+category

You have to make sure the user doesn't input a & sign because you can't pass the & within the url. You will need to change it to the ascii code.

Here is a good page that explains all of the ascii codes
http://www.ascii.cl/htmlcodes.htm

You will also need to make sure you display the ascii codes onto the html page. For example, if you pass a < or a > sign to the html page, the html page will
think that it is an html code and will render it as html code. If you pass the ascii code to the page which is &lt; or &gt;, then you will actually see the symbol < or > appear on the page.

You can do this by using the replace function. For example, you can say book.replace("<","&lt;") when you display the items on the page in javascript. You can use the replace function when you pass the data to the server using Javascript, but when you are retrieving data from the server, you might want your Java code to have a html method to convert your data to html.
Here is an example:

public static String convertToHtml(String inputStr) {
if(inputStr==null)
{
return "";
}
String newString=inputStr;
newString=newString.replaceAll("&", "&amp;");
newString=newString.replaceAll("\r\n"," ");
newString=newString.replaceAll("'", "&#39;");
newString=newString.replaceAll("<","&lt;");
newString=newString.replaceAll("/","");
newString=newString.replaceAll(">","&gt;");
newString=newString.replaceAll("@","and");
newString=newString.replaceAll("\"","");
return newString;
}

Before sending your String Buffer back to the JSP page, you call this method to convert the string to html.

Go To Step 49

Read more...

Monday, December 22, 2008

3D Game Programming in Java using the jMonkeyEngine #1

I am going to start a tutorial to create a 3D game using jMonkeyEngine (JME), FengGUI,  JME Physics, JMF and Blender using eclipse.

If you wonder how Java can be used for game programming, see my prior post.

I am not an expert at all of these areas so I will be able to share with you any issues that I run across as I am using them.

I am assuming that you are familiar with Java and eclipse. I am also assuming you are using an XP or Window's Vista system. I am using eclipse version 3.4.0 and Java 1.5. If you haven't installed them yet, you can see my first post.

The first thing we need to do is to install some of these technologies.

Download and Install Blender:
http://www.blender.org/download/get-blender/
select the Windows 32 bit Blender 2.48a Installer
Install that onto your windows system. To use Blender, you also have to have python installed.
http://www.python.org/download/
I downloaded Python 2.6.1 Windows installer.
Install Python first, and then install Blender.

In eclipse you should create a project and in that project, create a directory call lib.

You will also need the lightweight java game library and you can download that here:
http://lwjgl.org/download.php
Download the latest version which is LWJGL 2.0.1
Unzip the zip folder you downloaded and locate the jar directory. Place all those jar files in your lib folder of your project and set your build path to point to them. If you don't know how to set your build path, you can visit one of my prior posts.

You will also need to download jogl.
You can download jogl at this website: https://jogl.dev.java.net/#NIGHTLY
You should download jogl-1.1.2-pre-20080523-windows-i586.zip. If you download the amd64 by accident and try to run your jogl programs, you will receive an error if you are using a 32bit system.

To set up jogl you should create a folder in your lib directory called resources. Locate the lib folder in the jogl you just downloaded. You need to unzip it first. Copy the jogl.jar and gluegen-rt.jar in your lib folder and copy the dll files in your resources folder. You need to set your build path to the jogl jar files. You also need to set the Native Libraries to the dll files. To do this you should press the right mouse button on your project and select properties. Select the Java Build Path and select the libraries tab. Under the libraries tab, select Native Library Location. You should select edit and select external folder. Locate the resource directory you put the dll files in and press okay. The path should say: ProjectName/lib/resources.

In my next post I will show you how to install
jMonkeyEngine (JME), FengGUI, and JME Physics

Go To #2

Read more...

Pulling Data to Pass to Ajax Function step 47

Now, we need to add the new book to the database using Ajax. We need to do this using javascript.

First, you need to add an id to the html:text forms so you can properly call the data. In struts, you will use the styleId. Next to the the property="book", you want to add a styleId="book", and next to the property="author", you want to add the styleId="author", and next to the property="bookPublisher", you want to add styleId="bookPublisher", and next to property="categoryId", you want to add styleId="category". Do not add this attribute to the html:optionsCollection because that would be invalid. You will add these in your addbook.jsp page. Some browsers don't require an id, but some do. If you don't put an id, then it won't work in firefox. Also, firefox is case sensitive so when you call the attribute, make sure you use the same case. In your retrieveURL function in your classiclayout.jsp page, you need to grab the elements that the user has inputted.

You will add thes to the beginning of the retrieveURL function.

book=document.getElementById("book").value
author=document.getElementById("author").value
publisher=document.getElementById("bookPublisher").value
category=document.getElementById("category").value

(Make sure they are the same case as the styleId)

These variables will grab the data you need to pass it to the Ajax call so you can add the new object to the database.

Go To Step 48

Read more...

Sunday, December 21, 2008

Asteroids in Java 2D Part 20

This class controls the graphics in the game.  It contains the paintComponent method that paints the objects on the screen.  It also checks if the space mine is activated, and if it is, it should draw a Bezier curve on the screen.

Display.java

//**********import statements***********

import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.Timer;
import java.awt.Point.*;
import java.awt.geom.AffineTransform;
import java.awt.Rectangle;


public class Display extends JPanel implements MouseListener,MouseMotionListener
{


private AsteroidGame game;
private Container container;

private static Point startPoint;
private static Point currentPoint;

private ControlPanel panel;

private int maxLevel;

private Random myRNG;

private int tempID;
private double epsilon;
private int[][] stars;
private int starCounter=0;

private AffineTransform Viewport;
private AffineTransform inVerse;
private boolean inV;

private double WL;
private double WR;
private double WB;
private double WT;


public Display(Container c,AsteroidGame g)
{
//*****WORLD INFORMATION*****
Viewport=new AffineTransform();
inVerse=new AffineTransform();
inV=true;
WL=0;
WR=1000;//sets witdth and height of asteroids
WT=800;
WB=0;
//*****************************

stars=new int[100][100];
maxLevel=6;
tempID=0;
game=g;
epsilon=.001;
myRNG=new Random();
startPoint=null;
currentPoint=null;
container=c;

this.setBackground(new Color(0,0,0));

container.add(this,BorderLayout.CENTER); //adds display to container


this.addMouseListener(this);
this.addMouseMotionListener(this);

}//ends constructor


public JPanel returnDisplay()
{
return this;

}//end JPanel panel

//PANNING WORLD COORDINATES, PANLEFT1 IS WITH SMALLER INCREMENTS
public void panLeft()
{
WT-=200;
WB-=200;
inV=true;

}

public void panRight()
{
WT +=200;
WB +=200;
inV=true;
}
public void panUp()
{
WL +=200;
WR +=200;
inV=true;

}
public void panDown()
{
WL-=200;
WR-=200;
inV=true;
}

public void panLeft1()
{
WT-=20;
WB-=20;
inV=true;


}
public void panRight1()
{
WT +=20;
WB =20;
inV=true;
}
public void panUp1()
{
WL +=20;
WR+=20;
inV=true;

}
public void panDown1()
{
WL-=20;
WR-=20;
inV=true;
}
//****get distance with world coordinates*****

public int getLengthsX()
{
return (int)(WR-WL);
}
public int getLengthsY()
{
return (int)(WT-WB);
}

//************************addControlPanel Method********
//purpose: to add reference to control panel
//preconditions: ControlPanel
//postconditions: none
//*****************************************************

public void addControlPanel(ControlPanel p)
{
panel=p;
}

//*****************MOUSE METHODS*******************

//************************mousePressed Method*******
//purpose: keeps track of plasma field while mouse is pressed
//preconditions: MouseEvent
//postconditions: none
//***************************************************
public void mousePressed(MouseEvent e)
{

Point ptp2=new Point();
ptp2.setLocation(e.getX(),e.getY());
inVerse.transform(ptp2,ptp2);
Point e3=new Point();
e3.setLocation(ptp2.getX(),this.getLengthsX()-ptp2.getY());

if(game.returnStart())
{
double[][] point=new double[4][2];
int direction5=0;
SpaceMines mine=new SpaceMines(this.getLengthsX(),this.getLengthsY());
Ships ship=new Ships(this.getLengthsX(),this.getLengthsY());
int z=game.size();

for(int y=0;y<z;y++ )
{
if(game.elementAt(y) instanceof SpaceMines)
{
mine=(SpaceMines)(game.elementAt(y));
if(mine.contains((int)e3.getX(),(int)e3.getY()))
{
mine.setSelected(true);
startPoint=new Point();
startPoint.setLocation(ptp2.getX(),ptp2.getY());
tempID=mine.getID();

//Plasma field
point[0][0]=ptp2.getX();
point[0][1]=ptp2.getY();
int tempso=0;

for(int o=1;o<4;o++ )
{

for(int r=0;r<2;r++ )
{

tempso=myRNG.nextInt(4);
if(tempso<2)
point[o][r]=(double)(myRNG.nextInt((int)(300)) +point[0][r]);
else
point[o][r]=(double)(-myRNG.nextInt((int)(300))+ point[0][r]);


}
}

mine.savePoint(point);
mine.setField(true);

//********end plasma field**********
}

else
{
mine.setSelected(false);

}

if(game.elementAt(y) instanceof Ships)
{
ship=(Ships)(game.elementAt(y));
if(ship.contains((int)e3.getX(),(int)e3.getY()))
{
ship.setSelected(true);

}
else
{
ship.setSelected(false);

}

}
}

}
}//if start is on or off

this.repaint();

}//end mousepressed method


//************************drawBezierCurve Method*************
//purpose: to draw a curve from plasma field
//preconditions: Array with 4 points, and the level of depth
//postconditions: none, recursive
//**********************************************************

private void drawBezierCurve (double[][] CPV,int Level,Graphics g)
{

g.setColor(new Color(128,128,128));
double[][] LeftSubVector=new double[4][2];
double[][] RightSubVector=new double[4][2];

if(straightEnough(CPV)||(Level>maxLevel))
{g.drawLine((int)CPV[0][0],(int)CPV[0][1],(int)CPV[3][0],(int)CPV[3][1]);
Point p=new Point();
Point p1=new Point();
Ships s;
p.setLocation(CPV[0][0],CPV[0][1]);
p1.setLocation(0,0);
int z=game.size();

//****Checks for collisions with the curve********
for(int y=0;y<z;y++ )
{
if(game.elementAt(y) instanceof Ships)
{
s=(Ships)(game.elementAt(y));
if(s.bounds(p,p1))
{
s.collision();
}
}
}

}

else
{
LeftSubVector[0][0]=CPV[0][0];
LeftSubVector[0][1]=CPV[0][1];
RightSubVector[3][0]=CPV[3][0];
RightSubVector[3][1]=CPV[3][1];

LeftSubVector[1][0]=((CPV[0][0] +CPV[1][0])/2);
LeftSubVector[1][1]=((CPV[0][1]+ CPV[1][1])/2);
RightSubVector[2][0]=((CPV[3][0] +CPV[2][0])/2);
RightSubVector[2][1]=((CPV[3][1]+ CPV[2][1])/2);

LeftSubVector[2][0]=((LeftSubVector[1][0]/2) +((CPV[1][0]+ CPV[2][0])/4));
LeftSubVector[2][1]=((LeftSubVector[1][1]/2) +((CPV[1][1] +CPV[2][1])/4));
RightSubVector[1][0]=((RightSubVector[2][0]/2)+ ((CPV[2][0]+ CPV[1][0])/4));
RightSubVector[1][1]=((RightSubVector[2][1]/2)+ ((CPV[2][1]+ CPV[1][1])/4));

LeftSubVector[3][0]=((LeftSubVector[2][0] +RightSubVector[1][0])/2);
LeftSubVector[3][1]=((LeftSubVector[2][1] +RightSubVector[1][1])/2);
RightSubVector[0][0]=((RightSubVector[1][0]+ LeftSubVector[2][0])/2);
RightSubVector[0][1]=((RightSubVector[1][1] +LeftSubVector[2][1])/2);


subdivideCurve(CPV,LeftSubVector,RightSubVector);

Level ++ ;
drawBezierCurve(LeftSubVector,Level,g);
drawBezierCurve(RightSubVector,Level,g);

}

}

//************************straightEnough Method*************
//purpose: to determine if line is straight enough for curve
//preconditions: double array with 4 points
//postconditions: returns boolean
//**********************************************************

private boolean straightEnough(double[][] CPV)
{
double d1=0.0;
double d2=0.0;
double p1=0.0;
double p2=0.0;

d1 +=(Math.sqrt(((CPV[1][0]-CPV[0][0])*(CPV[1][0]-CPV[0][0]))+ ((CPV[1][1]-CPV[0][1])*(CPV[1][1]-CPV[0][1])))+
Math.sqrt(((CPV[2][0]-CPV[1][0])*(CPV[2][0]-CPV[1][0]))+ ((CPV[2][1]-CPV[1][1])*(CPV[2][1]-CPV[1][1]))) +
Math.sqrt(((CPV[3][0]-CPV[2][0])*(CPV[3][0]-CPV[2][0]))+ ((CPV[3][1]-CPV[2][1])*(CPV[3][1]-CPV[2][1]))));

p1 +=((CPV[3][0]-CPV[0][0])*(CPV[3][0]-CPV[0][0]));
p2 +=((CPV[3][1]-CPV[0][1])*(CPV[3][1]-CPV[0][1]));

d2=Math.sqrt((p1 +p2));

if(Math.abs(d1-d2)<epsilon)
return true;
else
return false;

}

//************************subdivideCurve Method************
//purpose: to subdivide curve
//preconditions: sends in 3 valid arrays containing 4 points
//postconditions: none
//**********************************************************

private void subdivideCurve(double[][] Q, double[][] R, double[][] S)
{
R[0][0]=Q[0][0];
R[0][1]=Q[0][1];
R[1][0]=((Q[0][0] Q[1][0])/2.0);
R[1][1]=((Q[0][1] Q[1][1])/2.0);
R[2][0]=((R[1][0]/2.0)+ ((Q[1][0] Q[2][0])/4.0));
R[2][1]=((R[1][1]/2.0) +((Q[1][1] Q[2][1])/4.0));

S[3][0]=Q[3][0];
S[3][1]=Q[3][1];
S[2][0]=((Q[2][0] +Q[3][0])/2.0);
S[2][1]=((Q[2][1] +Q[3][1])/2.0);
S[1][0]=(((Q[1][0] +Q[2][0])/4.0)+ (S[2][0]/2.0));
S[1][1]=(((Q[1][1]+ Q[2][1])/4.0)+ (S[2][1]/2.0));

R[3][0]=((R[2][0]+ S[1][0])/2.0);
R[3][1]=((R[2][1] +S[1][1])/2.0);

S[0][0]=R[3][0];
S[0][1]=R[3][1];
}

//************************mouseDragged Method*****************
//purpose: to keep track of the mouse being dragged
//preconditions: mouse event
//postconditions: none
//**********************************************************

public void mouseDragged(MouseEvent e)
{

Point ptp2=new Point();
ptp2.setLocation(e.getX(),e.getY());
inVerse.transform(ptp2,ptp2);
Point e3=new Point();
e3.setLocation(ptp2.getX(),this.getLengthsY()-ptp2.getY());

if(game.returnStart())
{
currentPoint=new Point();
currentPoint.setLocation(ptp2.getX(),ptp2.getY());
Ships ship=new Ships(this.getLengthsX(),this.getLengthsY());
int z=game.size();
for(int y=0;y<z;y++ )
{
if(game.elementAt(y) instanceof Ships)
{

ship=(Ships)(game.elementAt(y));
ship.setSelected(false);

}
}
}
this.repaint();
}

//************************createStars Method*********
//purpose: to create Background stars
//preconditions: pass in Graphics
//postconditions: none
//*****************************************************
private void createStars(Graphics g)
{

g.setColor(new Color(255,255,255));

if(starCounter==0)
{
for(int q9=0;q9<100;q9++ )
{
stars[q9][0]=myRNG.nextInt(this.getWidth());
stars[q9][1]=myRNG.nextInt(this.getHeight());
g.drawLine(stars[q9][0],stars[q9][1],(stars[q9][0] 1),(stars[q9][1] +1));
}
}
else
{
for(int q9=0;q9<100;q9++ )
{
g.drawLine(stars[q9][0],stars[q9][1],(stars[q9][0]),(stars[q9][1]));

}

}
starCounter ++ ;
if(starCounter==30)
starCounter=0;

}//end starCounter method

//************************mouseClicked Method*********
//*****************************************************

public void mouseClicked(MouseEvent e)
{


Point ptp2=new Point();
ptp2.setLocation(e.getX(),e.getY());
inVerse.transform(ptp2,ptp2);
Point e3=new Point();
e3.setLocation(ptp2.getX(),this.getLengthsY()-ptp2.getY());

Ships ship=new Ships(this.getX(),this.getY());
SpaceMines mine=new SpaceMines(getX(),getY());
int curMouseX=(int)e3.getX();
int curMouseY=(int)e3.getY();

int z=game.size();
for(int y=0;y<z;y++ )
{

if(game.elementAt(y) instanceof SpaceMines)
{
mine=(SpaceMines)(game.elementAt(y));
if(mine.contains(curMouseX,curMouseY))
{
mine.setSelected(true);
Graphics g=this.getGraphics();

}
else
{
mine.setSelected(false);

}
}

if(game.elementAt(y) instanceof Ships)
{
ship=(Ships)(game.elementAt(y));
if(ship.contains(curMouseX,curMouseY))
{
ship.setSelected(true);

}
else
{
ship.setSelected(false);

}

}

}

}//end mouse clicked method

//************empty methods required for interface******************
public void mouseExited(MouseEvent e){}//empty, required for interface
public void mouseMoved(MouseEvent e){}
public void mouseEntered(MouseEvent e){}
//******************************************************************

//***************MouseReleased Method********************
//releases rubberbandline, removes spacemines if release
//is located on a ship.

public void mouseReleased(MouseEvent e)
{
Point ptp2=new Point();
ptp2.setLocation(e.getX(),e.getY());
inVerse.transform(ptp2,ptp2);
Point e3=new Point();
e3.setLocation(ptp2.getX(),this.getLengthsY()-ptp2.getY());

if(game.returnStart())
{
Graphics g;
Ships ship;
int curMouseX=(int)e3.getX();
int curMouseY=(int)e3.getY();
SpaceMines mine=new SpaceMines(this.getLengthsX(),this.getLengthsY());
int z=game.size();
int d=z;
int i;
Point pointLocation;

String temp2;
for(int y=0;y<z;y++ )
{

if(game.elementAt(y) instanceof SpaceMines)
{
mine=(SpaceMines)(game.elementAt(y));
mine.setField(false);
}

if(game.elementAt(y) instanceof Ships)
{

ship=(Ships)(game.elementAt(y));
if((ship.contains(curMouseX,curMouseY))&&(!(startPoint==null))&&(!(currentPoint==null)))
{

for(int q=0;q<d;q++ )
{
if(game.elementAt(q) instanceof SpaceMines)
{

mine=(SpaceMines)(game.elementAt(q));

if( (mine.getID()==tempID) && (!(mine.remove()) ))
{
i=mine.getID();
temp2=Integer.toString(i);
game.addScore(mine.returnValue());
mine.setRemove(true);

pointLocation=mine.getLocation();
ship=new Ships(this.getLengthsX(),this.getLengthsY(),(int)pointLocation.getX(),(int)pointLocation.getY());
ship.collision();
game.addElement(ship);
game.incrementTotal(2);



}
}
}
}}}

startPoint=null;
currentPoint=null;
}
this.repaint();
} //end mousepressed method



//*********************paintComponent method**************
//overiding paintcomponent

public void paintComponent(Graphics g)
{
super.paintComponent(g);


if(!game.returngameStarted())
{g.setColor(Color.orange);
String newString=new String("Created by Gregory A. Dias");
g.drawString(newString,(this.getWidth()/2)-(newString.length()),(this.getHeight()/2)-16);
newString=new String("Press Enter to Begin the Game");
g.drawString(newString,(this.getWidth()/2)-(newString.length()),this.getHeight()/2);
newString=new String("Current High Score "+ game.returnhighName() +" with "+; game.returnhighScore()+ " points");
g.drawString(newString,((this.getWidth()/2))-(newString.length()),(this.getHeight()/2) 16);
newString=new String("Game Over");
g.drawString(newString,((this.getWidth()/2))-(newString.length()),(this.getHeight()/2) +40);

}


createStars(g);
g.setColor(Color.green);
int z=game.size();
Missiles m;
Asteroids a;
Ships s;
SpaceMines mine;
Garbage gb;
EnemyShip tuv;

Graphics2D g2d=(Graphics2D)g;
Viewport.setToIdentity();
Viewport.scale(this.getWidth(),-this.getHeight());

Viewport.scale((1/(WR-WL)),(1/(WT-WB)));
Viewport.translate(-WB,-WL);

g2d.transform(Viewport);

if(inV)
{


try
{
inVerse=Viewport.createInverse();

}
catch(Exception e5)
{
}
}

if(game.returnStart())
{
//*******for rubberband******
if(startPoint!=null && currentPoint !=null)
g.drawLine((int)startPoint.getX(),(int)startPoint.getY(),(int)currentPoint.getX(),(int)currentPoint.getY());
}
//****end rubberbandline information****

Point e4=new Point();
Point ptp5=new Point();
Rectangle test=new Rectangle();



//************DRAWING OBJECTS IN THE WORLD*****************
for(int y=0;y<z;y++ )
{
//draws all the objects
if(game.elementAt(y) instanceof Missiles)
{
m=(Missiles)(game.elementAt(y));
m.draw(g2d);

}

if(game.elementAt(y) instanceof Ships)
{
s=(Ships)(game.elementAt(y));

if(game.returnStart())
{ s.setStart(false);
s.setWBWT(WB,WT);
s.draw(g2d);

//for ships to pan the world
if(s.getSpeed()==0)
{
test=g2d.getClipBounds();
ptp5=s.getLocation();
e4.setLocation(ptp5.getX(),ptp5.getY());

if((600-e4.getY())>((test.getY()+ test.getHeight()-50)))
this.panUp1();
if((600-e4.getY())<(test.getY()+ 50))
this.panDown1();
if(ptp5.getX()>(WT-50))
this.panRight1();
if(ptp5.getX()<(WB +50))
this.panLeft1();
}

if(s.getLeft())
this.panLeft();
if(s.getRight())
this.panRight();
if(s.getUp())
this.panUp();
if(s.getDown())
this.panDown();
}
else
{
s.setStart(true);
s.draw(g2d);
}

}

if(game.elementAt(y) instanceof Asteroids)
{
a=(Asteroids)(game.elementAt(y));
a.draw(g2d);
}
if(game.elementAt(y) instanceof EnemyShip)
{
tuv=(EnemyShip)(game.elementAt(y));

if(game.returnStart())
{ tuv.setStart(false);
tuv.draw(g2d);
}
else
{
tuv.setStart(true);
tuv.draw(g2d);
}
}
if(game.elementAt(y) instanceof Garbage)
{
gb=(Garbage)(game.elementAt(y));
gb.draw(g2d);
}



if(game.elementAt(y) instanceof SpaceMines)
{
mine=(SpaceMines)(game.elementAt(y));
if(mine.remove())
{
if(mine.blink(g2d))
{
y--;
z--;
game.removeElement(mine);

}
}
else
{
mine.draw(g2d);

//**********draws BezierCurve***********************

if(mine.returnField())
{
drawBezierCurve(mine.returnPoint(),0,g);
//draws curve if still active
}
}
}

}

}//end paintComponent


}//ends display class


 



Go To Part 21

Read more...

Florian Villa: Helping Veterans & Families

 Are you looking for a great place to to go on vacation? Maybe you should think about going to the Virgin Islands? Florian Villa is a great vacation spot, and they are offering 30% off all week through January 2009. Florian Villa  is located only 10 minutes from Cruz Bay which is near the Chocolate Hole and Rendezvous Bay. This would be a great place to have a wedding or honeymoon. Maybe you are looking for a great place to have a Yoga retreat. When you checkout their website, you can see pictures and a video on what the place is like. This is a good time to think about taking a vacation. There are all kinds of great hiking spots, and this is a great place to scuba dive. You can sign up for an adventure package that would include SCUBA, deep sea fishing, hiking, para-sailing, kayaking, hiking, boating and much more. For all the hard work you do, you should consider taking a vacation. 95% of this island is preserved National Forest so it has some of the best beaches in the world. So what are you waiting for? If you are looking for a great place to take a vacation, then you should definitely checkout Florian Villa.  

Florian Villa: Helping Veterans & Families
CONTACT
Scott Wahlen
Deborah Bernstein
Florian Villa on Gift Hill
Saint John, United States Virgin Islands
(617) 429-6182

info@florianvilla.com
http://www.florianvilla.com

Boston Celtics Will Honor Owners of Unparalleled Retreat in Caribbean
Deborah Bernstein and Scott Wahlen will receive a Heroes Among Us Award from the Boston Celtics on December 1, 2008 for their altruistic service.

Boston, November 30, 2008 – Deborah Bernstein and Scott Wahlen, owners of the Florian Villa, will receive one of the most coveted community service awards, the Heroes Among Us Award, from the Boston Celtics on December 1, 2008.

“It is truly an honor that we will cherish forever and we intend on sharing our award with every visitor to the Florian Villa,” stated Bernstein. Bernstein and Wahlen cannot believe that they were chosen for such a prestigious award for simply giving back to the community.

Bernstein and Wahlen provide weeklong, all-inclusive respites to families of fallen firefighters and returning wounded veterans at their exclusive Florian Villa on Saint John Island in the US Virgin Islands. Scott Wahlen, a captain with the Boston Fire Department and a former U.S. Marine, and Deborah Bernstein, a yoga instructor, founded the Florian Villa in 2007. Current residents of Boston, these two philanthropists routinely collaborate with other organizations, such as Soldiers Undertaking Disable Scuba (SUDS), to provide a well-rounded and supportive environment for the visiting families and veterans.

The Heroes Among Us program began in 1997 and has come to be recognized as one of the most prestigious community outreach programs in professional sports. A Heroes Among Us Award is presented at each Boston Celtics home game to individuals who have made tremendous impacts on the lives of others through their altruistic actions and contributions.

The Florian Villa was named after Saint Florian who is the patron saint of firefighters and their families. For additional information about the Florian Villa, visit http://www.FlorianVilla.com, http://florianyoga.blogspot.com or call (617) 429-6182.

Read more...

Asteroids in Java 2D Part 19

You should create a file called score.txt in your project. This class will be used to hold the highscore of the game. In the AsteroidGame.java class which I will be posting in my following post, you should change the path to this file so the game can hold your high score.

Go To Part 20 

Read more...

Thursday, December 18, 2008

Displaying Ajax in JSP Page Step 46

Now what we want to do is display the list of books dynamically using Ajax.
You would first go to your addBook.jsp page and select view source from your browser.
Copy the code from Current Book List to the end of the book list. You want to grap the html code that you want to display dynamically.

That html code would be this:


<tr><td>
Book Name:Lord of the Rings&nbsp;&nbsp;Category Name:science fiction
</td></tr>
<tr><td>
Book Name:greg test&nbsp;&nbsp;Category Name:science fiction
</td></tr>
<tr><td>
Book Name:new test&nbsp;&nbsp;Category Name:History
</td></tr>



You want the actual html code because that is what you will display on the page.
In your addbook.jsp page, remove this code:
<nested:iterate property="bookList">
<tr><td>
Book Name:<nested:write property="bookName"/>&nbsp;&nbsp;Category Name:<nested:write property="bookcategory.category"/>
</td></tr>
</nested:iterate>

We are now going to display it using Ajax.
Copy the html code from your view source and paste it into your UserAction.java class in the saveBookAjax method. You will need to modify it to display it the way you want in your jsp page. I already rewrote it below so all you need to do is replace the saveBookAjax method with the following code.


StringBuffer buffer=new StringBuffer("");
UserForm userForm=(UserForm)form;
List<Book> bookList=userForm.getBookList();
buffer.append("<tr><td>");
for(Book book:bookList)
{
buffer.append("Book Name: ").append(book.getBookName()).append("&nbsp;&nbsp;").append(book.getBookcategory().getCategory());
}
buffer.append("</tr></td>");
response.setContentType("text/html");
try {
PrintWriter out = response.getWriter();
out.println(buffer.toString());
out.flush();
} catch (Exception e) {
log.error("Error getting Writer from response");
}
return null;




Now when you run your application and press the submit button, all of the current categories will be display on the page except the one you were trying to add. I will show you how to do that in my next post.

Go To Step 47

Read more...

Implementing Ajax using Struts Step 45

When you enter your addBook page, make sure you have these methods in your addBook action class to load the category list.

List<Bookcategory> categoryList=service.getBookCategory();
userForm.setBookCategoryList(categoryList);


To test if your Ajax works, you would add this method to your action class.

public ActionForward saveBookAjax(ActionMapping mapping, ActionForm form,
HttpServletRequest request, HttpServletResponse response)
throws Exception {
StringBuffer buffer=new StringBuffer("");
buffer.append("This is Ajax Test");
response.setContentType("text/html");
try {
PrintWriter out = response.getWriter();
out.println(buffer.toString());
out.flush();
} catch (Exception e) {
log.error("Error getting Writer from response");
}
return null;
}

This method will print a string out to the response that will display on your JSP page using Ajax. You want to use the StringBuffer class because that is faster then concatenating a string with the + sign.

In your addbook.jsp page, you need to replace your submit button with this code.

<input type="button" value="Submit" onclick="retrieveURL('UserAction.do?action=saveBookAjax','searchpane');"/></td></tr>

You are changing your button to be of type submit to type button. This way the button doesn't submit automatically. You now will not submit your form, but will use Ajax to display your data.

This button will call the Ajax method, and the Ajax method will return the html code from the server and set the data using the innerHTML command using the id of 'searchpane'.

When you submit your form, you should see, "This is Ajax Test" appear on the page.

Go To Step 46

Read more...

Wednesday, December 17, 2008

The Future of Linux

Are you tired of all the problems you have with the Windows Operating System? I know I am. Are you tired of the fear of receiving a virus that will destroy all of your important data? Maybe you should consider getting yourself a Linux box. iMagic OS is the future of Linux and can solve many of your issues with your windows box. Why iMagic OS you might ask? First, iMagic can run any application created for Microsoft. Therefore, you don’t have to worry about compatibility issues. It has a great user friendly interface with state of the art technology. It allows you to organize your windows with the choice of four desktops. You will never get a virus using the iMagic OS because people don’t write viruses for Linux boxes. However, it still comes with three of the strongest firewalls available. What would be your reason not to get an iMagic OS? It isn’t because of the price because iMagic OS is inexpensive and comes pre-installed with Adobe Photoshop and Microsoft Office equivalent software. So what are you waiting for? You need to check them out now before you make a mistake purchasing a Windows Operating System like I did.

BuyBlogReviews.com

Read more...

Implementing Ajax with Struts Step 44

To use Ajax, paste this code under your <html> in your classiclayout.jsp page.
The retrieveURL function will be used to pull the html from the server. You have different conditions depending on which browser a user is using. The document.body.style.curser="wait" will make the cursor into an hourglass until the Ajax call is completed. In my next post I will show you how to use these methods. To change it back, you will use The document.body.style.curser="default".



<head>
<script language="JavaScript">
var newtableid
function retrieveURL(url,tableid) {
document.body.style.cursor = "wait";
newtableid=tableid;
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = processStateChange;
try {
req.open("GET", url, true);
} catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = processStateChange;
req.open("GET", url, true);
req.send();
}
}
}
function processStateChange() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById(newtableid).innerHTML = req.responseText;
document.body.style.cursor = "default";
}
}
}
</script>
</head>

Go To Step 45

Read more...

Tuesday, December 16, 2008

Benefits of Using Ajax Step 43

Here is a list of benefits of using Ajax on your website:

1) It makes the page feel faster because the data is exchanged with the server throughout the session instead of every time the page is reloaded by a user.

2) users related their experience with AJAX web pages to be more like a separate application than a standard web page.

3) It reduces the amount of click and wait time a user will experience

4) Client attractiveness: the more attractive and easy to use a website is, the more likely the user will return.

5) It fits well wtih existing HTML web sites/web applications

Ajax is here and many companies have already started to use it such as Google. Therefore, it is important for developers to be familiar with it.

Go To Step 44

Read more...

Asteroids Part 18 in Java 2D Moving Space Objects

This post is to explain the GFrame.java class from my last post. This class creates all of the menus that the user will use in the game. It creates a list of radio buttons for the difficulty level. It will also create some menu bars that you can use in the game to either quit the game or create a new game. The KeyboardFocusManager is the keystroke manager and will hold each key that the user presses. When a key is pressed, the dispatchKeyEvent method is called, and you can check which key the user pressed.

Go To Part 19

Read more...

Asteroids in Java 2D Part 17

This class is the JFrame class used to hold the frame of the game. All of the components will get attached to this class. I will explain what this class does in my next post.

GFrame.java



import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import java.awt.event.*;
import javax.swing.JOptionPane;
import javax.swing.event.*;
import java.util.Random;


public class GFrame extends JFrame implements KeyEventDispatcher
{

private JMenuBar bar;

private JMenu menu;
private JMenu menu1;
private JMenu sound;

private JMenuItem newGame;
private JMenuItem quit;
private JMenuItem difficulty;

private JRadioButtonMenuItem on;
private JRadioButtonMenuItem off;
private ButtonGroup soundGroup;
private Status statusBar;
private Display displayPanel;

private ControlPanel panel;

private Container container;

private FlowLayout layout;

private menuListener xlistener;

private JPopupMenu difficultMenu;
private ButtonGroup difficultGroup;
private JRadioButtonMenuItem items[];
private String levels[]={"1-Wimpy","2-Loser","3-Moron","4-Pee Wee","5-Sissy","6-Girly","7-Rocky","8-Mr. Muscles","9-Godzilla","10-You, the Man!"};
private ItemHandler handler;

private MyWindowListener myWinListener;

private AsteroidGame game;


public GFrame(AsteroidGame g)
{
super("ASTEROIDS THE PINK VIPER");
game=g;

//***********instantiate window listener*******

myWinListener=new MyWindowListener();
this.addWindowListener(myWinListener);

//**********sets up difficulty menu*************

difficultGroup=new ButtonGroup();
difficultMenu=new JPopupMenu();
items=new JRadioButtonMenuItem[10];
handler=new ItemHandler();

for(int count=0;count<items.length;count++ )
{
items[count]=new JRadioButtonMenuItem(levels[count]);
difficultMenu.add(items[count]);
difficultGroup.add(items[count]);
items[count].addActionListener(handler);
}

//****************sets up menu bar***************
bar=new JMenuBar();
setJMenuBar(bar);

//****************sets up the menu items*********
menu=new JMenu("File");
menu1=new JMenu("Options");
sound=new JMenu("Sound");

//*********sets up the menu items****************
newGame=new JMenuItem("New Game");
quit=new JMenuItem("Quit");
difficulty=new JMenuItem("Difficulty");

//*********sets up the submenu under sound******
on=new JRadioButtonMenuItem("On");
off=new JRadioButtonMenuItem("Off");

//*********sets up the soundGroup***************
soundGroup=new ButtonGroup();

//********sets up the sound submenu*************
sound.add(on);
sound.add(off);
soundGroup.add(on);
soundGroup.add(off);
on.setSelected(true); //sets the sound to be initially on

//*******adds menuItems and submenus to menus**
menu.add(newGame);
menu.addSeparator();
menu.add(quit);
menu1.add(difficulty);
menu1.add(sound);

//******adds menus to the menu bar************
bar.add(menu);
bar.add(menu1);

//********set up FlowLayout*******************
layout=new FlowLayout();
layout.setAlignment(FlowLayout.LEFT);


//******gets the ContentPane for the Frame*

container=getContentPane();

//***Instantiates the ControlPanel and
//***Display panel and status panel to be added to the GUI*

statusBar=new Status(container,game);
displayPanel=new Display(container,game);
panel=new ControlPanel(container,statusBar,game,displayPanel);
displayPanel.addControlPanel(panel);
//*************sets up listeners for the menu bar*********

xlistener = new menuListener();
newGame.addActionListener(xlistener);
quit.addActionListener(xlistener);
difficulty.addActionListener(xlistener);
on.addActionListener(xlistener);
off.addActionListener(xlistener);

//*******Sets up Frame to listen for keystrokes**********
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(this);

setDefaultCloseOperation(DO_NOTHING_ON_CLOSE);

//sets up window's location and sets size****

setLocation(0,0); //the default location
setSize(1000,800);
setVisible(true);


}//end constructor

public void setStatus(String temp)
{
statusBar.setStatus(temp);
}

public void repaintDisplay()
{
displayPanel.repaint();
}

public int getWidth()
{
return displayPanel.getLengthsX();
}

public int getHeight()
{
return displayPanel.getLengthsY();

}

//***********LISTENS FOR KEYSTROKES*******************
public boolean dispatchKeyEvent(KeyEvent event)
{
Ships ship=new Ships(displayPanel.getX(),displayPanel.getY());

if(game.returnStart())
{
if(event.getID()==KeyEvent.KEY_PRESSED)
{

//***********Starting game by pressing Enter********************
if(event.getKeyCode()==KeyEvent.VK_ENTER)
{
if(!game.returngameStarted())
{
game.setBegin();
game.newGame();
}
}



int z=game.size();
for(int y=0;y<z;y++ )
{

if(game.elementAt(y) instanceof Ships)
{
ship=(Ships)(game.elementAt(y));
if(ship.isSelected())
{

switch(event.getKeyCode())
{
case KeyEvent.VK_LEFT:

//***************Ship moving left******************************
ship.leftHeading();

break;
case KeyEvent.VK_SPACE:

// ****************adding a Missile******************************

game.incrementTotal(0);
Point po=ship.getTop();
Missiles myMissile=new Missiles((int)po.getX(),(int)po.getY(),ship.getHeading(),ship.getSpeed(),this.getWidth(),this.getHeight());
game.addElement((Object)myMissile);//panel

break;

case KeyEvent.VK_RIGHT:

//*********************ship moving right******************************

ship.rightHeading();

break;

case KeyEvent.VK_UP:

//********************Ship increasing speed***********************

ship.increaseSpeed();
ship.setincSpeed(true);

break;
case KeyEvent.VK_DOWN:

//*************Ship decreasing speed*****************************

ship.decreaseSpeed();
ship.setincSpeed(true);
break;
case KeyEvent.VK_H:

//*********HyperJump*********************************************
Random myRNG=new Random();
ship.setLocation(myRNG.nextInt(3000),myRNG.nextInt(3000));

break;

default:
}//end switch statement

}//end inner if statement
}//end if statement

displayPanel.repaint();

}//end for statement

}//end if statement

}

return false; //doesn't pass key pressed on to other listeners if true

}//end dispatchKeyEvent method



private class menuListener implements ActionListener
{


public void actionPerformed(ActionEvent e)
{
int x=1;

//*****checks which button was pressed
//and activates the action sequence


//***************NEW GAME ACTION*******************
if(e.getActionCommand().equals("New Game"))
{
game.newGame();
displayPanel.repaint();


}
//************QUIT ACTION**************************
if(e.getActionCommand().equals("Quit"))
{

x=JOptionPane.showConfirmDialog(null,
"Are you sure you want to quit?","Please Don't Quit", JOptionPane.YES_NO_OPTION);

if(x==0) //exits if zero, otherwise do nothing
{
System.exit(0);
}
}

//***********SETS DIFFICULTY LEVEL****************
if(e.getActionCommand().equals("Difficulty"))
{
difficultMenu.show(displayPanel.returnDisplay(),10,10);
}

//****************SETS SOUND ON AND OFF************
if(e.getActionCommand().equals("On"))
{
game.updateSound(true);

}
if(e.getActionCommand().equals("Off"))
{

game.updateSound(false);

}

}//end action Performend method


}//end ActionListener inner class

private class ItemHandler implements ActionListener
{
public void actionPerformed(ActionEvent event)
{

int y=game.returnDifficulty();

int[] totalg=new int[3];
totalg=game.returnTotal();

for(int i=0;i<items.length;i ++ )
{
if(event.getSource()==items[i])
{
game.updateDifficulty(i +1);
}

}

}//end actionperformed method

}//end ItemHandler class

private class MyWindowListener implements WindowListener
{
int x=1;

public void windowClosing(WindowEvent e)
{
x=JOptionPane.showConfirmDialog(null,
"Are you sure you want to quit?","Please Don't Quit", JOptionPane.YES_NO_OPTION);

if(x==0) //exits if zero, otherwise do nothing
{
System.exit(0);}
}

//****non used methods*******************
public void windowClosed(WindowEvent e){}
public void windowOpened(WindowEvent e){}
public void windowIconified(WindowEvent e){}
public void windowDeiconified(WindowEvent e){}
public void windowActivated(WindowEvent e){}
public void windowDeactivated(WindowEvent e){}



}//end myWinListener inner class



}//end GFrame class




Go To Part 18

Read more...

Asteroids Game Java 2D Part 16

This class contains the control panel. This is a JPanel object that will be attached to your JFrame to allow the user to pause the game or start the game.


ControlPanel.java




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

public class ControlPanel extends JPanel
{

private JPanel westSubPanel;
private myButtonListener listener;
private Status newStatus;
private AsteroidGame game;
private Display display;
private Random myRNG;


public ControlPanel(Container container,Status statusBar,AsteroidGame gr,Display d)
{
//*********sets up pointers and instantiates objects

westSubPanel=new JPanel();
newStatus=statusBar;
game=gr;
display=d;
myRNG=new Random();

//*****JButtons set up***********
JButton start=new JButton ("Start ");
JButton pause=new JButton ("Pause ");

start.setFocusable(false); //sets buttons to false, but
pause.setFocusable(false); //are still sent to listeners

//******Buttons and JCombo box added to panel*******

westSubPanel.add(start);
westSubPanel.add(pause);

westSubPanel.setLayout(new BoxLayout(westSubPanel,BoxLayout.Y_AXIS));

//*******adds Button's to Listeners***********************

listener=new myButtonListener();
start.addActionListener(listener);
pause.addActionListener(listener);

//******added Panel/Label to container********************

container.add(westSubPanel,BorderLayout.WEST);


}//end constructor


private class myButtonListener implements ActionListener
{

public void actionPerformed(ActionEvent e)
{


Ships myShips;
SpaceMines myMine;

String temp="";

if(e.getActionCommand().equals("Start "))
{
game.startGame();
}
if(e.getActionCommand().equals("Pause "))
{
game.stopGame();
}


}//end actionPerformed method

}//end myButtonListener innerclass

}//end ControlPanel class




Go To Part 17

Read more...

Asteroids in 2D Part 15 Tutorial

This class contains an enemy ship in the game.  It contains all of the same methods as the other ship.java class.  The difference is that the ship is shaped differently, and that it has some type of intelligence.


EnemyShip.java

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.Polygon;
import java.awt.geom.AffineTransform;
import java.util.Random;
import java.util.Vector;



public class EnemyShip extends MovingSpaceObject implements Collider,Moveable, Drawable
{


private boolean selected;
private Random myRNG;
private int xWidth;
private int yHeight;


private int base;
private int height;

private boolean incSpeed;

private AffineTransform myAT;
private AffineTransform inVerse;

private boolean collision;
private int collisioncounter;

private boolean start;

private Point line1;
private Point line2;
private Point line3;
private Point line4;
private Point line5;
private Point line6;
private Point line7;
private Point line8;


private int n=8;
private int[] x8=new int[n]; //points for polygon
private int[] y8=new int[n];
private Polygon po;

private Vector world;

private boolean lockedOn=false;
private int headingcount=0;

public EnemyShip(int u,int r, Vector wor)
{
world=wor;
incSpeed=false;
collision=false;
collisioncounter=0;
start=false;
xWidth=u;
yHeight=r;
selected=false;
myRNG=new Random();
int x=myRNG.nextInt(3000);
int y=myRNG.nextInt(3000);
setColor(new Color(255,0,175));
setSpeed(50);
setLocation(x,y);
x=myRNG.nextInt(359);
if(x==0)
x=1;
setHeading(x);

base=20;
height=35;

myAT=new AffineTransform();
inVerse=new AffineTransform();

line1=new Point();
line2=new Point();
line3=new Point();
line4=new Point();
line5=new Point();
line6=new Point();
line7=new Point();
line8=new Point();


po=new Polygon();
}//end constructor




//******draw Method*********************************
public void draw(Graphics2D g)
{

int height1=yHeight; //total height
if(!(collision))
{


AffineTransform saveAt=g.getTransform();


Point location=getLocation();

line1.setLocation((double)(-base/2),(double)((-height/2)-5) );
line2.setLocation((double)(0),(double)(height));
line3.setLocation((double)(base/2),(double)((-height/2)-5) );
line4.setLocation((double)(3),(double)((-height/2) +3) );
line5.setLocation((double)(double)(0),(double)(height));
line6.setLocation((double)(-3),(double)((-height/2) +3) );
line7.setLocation((double)(0),(double)((-height/2)-6) );
line8.setLocation((double)(3),(double)((-height/2) +3) );

myAT.setToIdentity();

myAT.translate((int)location.getX(),(int)location.getY());

myAT.rotate(Math.toRadians(getHeading()));

myAT.transform(line1,line1);
myAT.transform(line2,line2);
myAT.transform(line3,line3);
myAT.transform(line4,line4);
myAT.transform(line5,line5);
myAT.transform(line6,line6);
myAT.transform(line7,line7);
myAT.transform(line8,line8);

g.setColor(getColor());


x8[0]=(int)line1.getX();
y8[0]=(int)line1.getY();
x8[1]=(int)line2.getX();
y8[1]=(int)line2.getY();
x8[2]=(int)line3.getX();
y8[2]=(int)line3.getY();
x8[3]=(int)line4.getX();
y8[3]=(int)line4.getY();
x8[4]=(int)line5.getX();
y8[4]=(int)line5.getY();
x8[5]=(int)line6.getX();
y8[5]=(int)line6.getY();
x8[6]=(int)line7.getX();
y8[6]=(int)line7.getY();
x8[7]=(int)line8.getX();
y8[7]=(int)line8.getY();

po=new Polygon(x8,y8,n);
g.fillPolygon(po);

g.transform(this.myAT);

g.setTransform(saveAt);

}
else
{
Point location=getLocation();
g.setColor(getColor());
g.fillArc((int)location.getX(),(int)location.getY(),collisioncounter,collisioncounter,30,60);
if(!start)
collisioncounter++ ;
}

}//end draw Method


//********move Method*******************************
public void move(int elapsedMilliSecs)
{

if(!(collision))
{
Point p=getLocation();
double x=p.getX(); //original location
double y=p.getY();

Ships s=null;
double heading9=getHeading();
double tempHeading=0.0;
//***************INTELLIGENCE*********************
int z9=world.size();
Point location9=null;
try
{
for(int y9=0;y<z9;y9++ )
{
if(world.elementAt(y9) instanceof Ships)
{

s=(Ships)(world.elementAt(y9));
location9=s.getLocation();

if((heading9>0)&&(heading9<90)&&((location9.getX()>x))&&((location9.getY()>y)))
{ increaseSpeed();
if(this.getSpeed()>125)
decreaseSpeed();


}
else{
tempHeading=(heading9+ 10);
if(tempHeading>359)
tempHeading=0;
setHeading(tempHeading);
headingcount++ ;
if(headingcount==6)
{headingcount=0;
increaseSpeed();}
if(this.getSpeed()>125)
decreaseSpeed();


}

if((heading9<180)&&(heading9>89)&&((location9.getX()>x))&&(!(location9.getY()>y)))
{
increaseSpeed();
if(this.getSpeed()>125)
decreaseSpeed();



}
else{
tempHeading=(heading9 +10);
if(tempHeading>359)
tempHeading=0;
setHeading(tempHeading);
headingcount++ ;
if(headingcount==6)
{headingcount=0;
increaseSpeed();}
if(this.getSpeed()>125)
decreaseSpeed();



}


if((heading9<270)&&(heading9>179)&&(!(location9.getX()>x))&&(!(location9.getY()>y)))
{
increaseSpeed();
if(this.getSpeed()>125)
decreaseSpeed();



}
else{
tempHeading=(heading9+ 10);
if(tempHeading>359)
tempHeading=0;
setHeading(tempHeading);
headingcount++ ;
if(headingcount==6)
{headingcount=0;
increaseSpeed();}
if(this.getSpeed()>125)
decreaseSpeed();



}


if((heading9<360)&&(heading9>270)&&(!(location9.getX()>x))&&((location9.getY()>y)))
{
increaseSpeed();
if(this.getSpeed()>125)
decreaseSpeed();



}
else{
tempHeading=(heading9 +10);
if(tempHeading>359)
tempHeading=0;
setHeading(tempHeading);
headingcount++ ;
if(headingcount==6)
{headingcount=0;
increaseSpeed();}
if(this.getSpeed()>125)
decreaseSpeed();


}


}//end if instance of ship
}//end for loop
}//end try block
catch(Exception exception)
{
}
//************************************

double speed=(double)getSpeed();


if(speed!=0)
{

double heading=getHeading();

if(speed<0)
{
heading +=180;
if(heading>359)
heading-=359;
}
speed=Math.abs(speed);
speed=(speed/((double)elapsedMilliSecs));
double heading2=Math.toRadians(heading); //heading in radians



double x1=Math.sin(heading2);
double y1=Math.cos(heading2);

if((heading>0)&&(heading<90))
{
x1+ =x;
y1 +=y;
x1-=speed;
y1 =speed;
}
if((heading<180)&&(heading>90))
{
x1 =x;
y1 =y;
x1-=speed;
y1-=speed;
}
if((heading<270)&&(heading>180))
{
x1 +=x;
y1 +=y;
x1 +=speed;
y1-=speed;
}
if((heading<360)&&(heading>270))
{
x1+ =x;
y1+ =y;
x1+ =speed;
y1 +=speed;
}
if(heading==0)
{
x1+ =x;
y1 +=y;
y1 +=speed;
}
if(heading==90)
{
x1+ =x;
y1+ =y;
x1-=speed;
}
if(heading==180)
{
x1 +=x;
y1 +=y;
y1-=speed;
}

if(heading==270)
{
x1+ =x;
y1+ =y;
x1+ =speed;
}

if(x1>3000)
{
x1=-3000;
}
if(x1<-3000)
{
x1=3000;
}

if(y1>3000)
{
y1=-3000;
}
if(y1<-3000)
{
y1=3000;
}
setLocation((int)x1,(int)y1);


}//end if statement if speed==0

}
}//end move method

//********changeSpeed Method************************
public void changeSpeed(int amount)
{
setSpeed(amount);

}//end changeSpeed method

//********changeHeading Method***********************
public void changeHeading(int amount)
{
setHeading(amount);

}//end changeHeading method

//******************collision Method***********************
public void collision()
{

collision=true;

}

public Point getTop()
{
return line2;
}


public boolean returnCollision()
{
return collision;
}

//*****************removeCollision Method***************
public boolean removeCollision()
{
if(collisioncounter>40)
{
return true;
}
else
return false;
}


public void setStart(boolean a)
{
start=a;
}

//************************bounds Method********************
public boolean bounds(Point p5,Point p6)
{

if(po.intersects(p5.getX(),p5.getY(),p6.getX(),p6.getY()))
return true;
else return false;

}



}//end Ships class




Go To Part 16

Read more...

Friday, December 12, 2008

Asteroids in Java 2D Part 14

This is a Garbage class which will be the debris from the asteroids after they are destroyed. It contains similar methods to the missile class. It also will disappear after it has been in the game for a certain amount of time.

Garbage.java


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;


public class Garbage extends MovingSpaceObject implements Moveable, Drawable, Collider
{



private int xWidth; //keeps track of width of display
private int yHeight; //keeps track of height of display

//transform
private AffineTransform myAT;

private boolean collision;
private int collisioncounter;

Point finalPoint;

private int base;

public Garbage(int u,int r,int sp,Point xy,int base1,double heading2)
{
collision=false;
collisioncounter=0;
setHeading(heading2);
xWidth=u;
yHeight=r;
base=base1;

setColor(new Color(150,255,64));
if(sp<10)
sp=10;

setSpeed(sp);
setLocation((int)xy.getX(),(int)xy.getY());

myAT=new AffineTransform();

finalPoint=new Point();
}//end constructor

//******draw Method*********************************
public void draw(Graphics2D g)
{

int height1=yHeight; //total height
if(!(collision))
{

double heading2=getHeading();
heading2 +=2;
if(heading2>359)
heading2=(heading2-359);

AffineTransform saveAt=g.getTransform();

g.setColor(getColor());

Point location=getLocation();

finalPoint.setLocation((double)0,(double)base);

myAT.setToIdentity();
myAT.translate((int)location.getX(),(int)location.getY());
myAT.rotate(Math.toRadians(heading2));

myAT.transform(finalPoint,finalPoint);


g.drawLine((int)finalPoint.getX(),((int)finalPoint.getY()),
(int)location.getX(),((int)location.getY()));

g.transform(this.myAT);

g.setTransform(saveAt);

}


}//end draw Method


//********move Method*******************************
public void move(int elapsedMilliSecs)
{

if(!(collision))
{
double speed=(double)getSpeed();
if(speed!=0)
{
double heading=getHeading();
speed=(speed/((double)elapsedMilliSecs));
double heading2=Math.toRadians(heading); //heading in radians
Point p=getLocation();
double x=p.getX(); //original location
double y=p.getY();
double x1=Math.sin(heading2);
double y1=Math.cos(heading2);
x1+ =x;
y1+ =y;

if((heading>0)&&(heading<90))
{
x1 +=speed;
y1+ =speed;
}
if((heading<180)&&(heading>90))
{
x1 +=speed;
y1-=speed;
}
if((heading<270)&&(heading>180))
{ x1-=speed;
y1-=speed;
}
if((heading<360)&&(heading>270))
{
x1-=speed;
y1 +=speed;
}
if(heading==0)
{
y1 +=speed;
}
if(heading==90)
{
x1 +=speed;
}
if(heading==180)
{
y1-=speed;
}

if(heading==270)
{
x1-=speed;
}

setLocation((int)x1,(int)y1);

}//end if statement if speed==0

}
}//end move method

public void changeSpeed(int amount)
{
setSpeed(amount);

}//end changeSpeed method

public void changeHeading(int amount)
{
setHeading(amount);

}//end changeHeading method

//*************collision method**********************************

public void collision()
{

collision=true;

}
public boolean removeCollision()
{
Point location=getLocation();
if(location.getX()>3000)
collision=true;
else if(location.getX()<-3000)
collision=true;
else if(location.getY()>3000)
collision=true;
else if(location.getY()<-3000)
collision=true;

return collision;


}

public boolean bounds(Point p1,Point p2)
{
return true;
}

}//end Garbage Class


Go To Part 15

Read more...

Asteroids Java 2D Part 13 The Missle

This class contains the missiles that will be fired from the ship. This class contains all the methods as the other classes except that it has a power variable. The power variable will decrease as the missile is fired. After the power is out, it will be removed from the game.

Missile.java


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.geom.AffineTransform;



public class Missiles extends MovingSpaceObject implements Moveable,Drawable
{

private int power;
private AffineTransform myAT;

private int xWidth;
private int yHeight;

private Point top;
private Point bottom;

private int height;
private int base;

public Missiles(int x, int y, double heading,int speed,int u,int r)
{
base=15;
height=25;

xWidth=u;
yHeight=r;
power=80;
setLocation(x,y);

setHeading(heading);
setColor(new Color(190,240,190));
int w;
float t;
if(speed==0)
speed=2; //calculates speed 20% faster then ship
t=(float)(speed*.2);
t +=(float)speed;
t +=Math.ceil(t);
setSpeed((int)t);

myAT=new AffineTransform();
top=new Point();
bottom=new Point();

}//end constructor


//************************returnPower Method ********
//purpose: to return the amount of power this missle has
//preconditions: none
//postconditions: returns int
//**************************************************
public int returnPower()
{
return power;
}

//************************decrementPower Method*********
//purpose: subtracts one from power
//preconditions: none
//postconditions: none
//********************************************************
public void decrementPower()
{
power-=1;
}

//************************getBounds1 Method******************
//purpose:to return the location of this bounding box
//preconditions: none
//postconditions: returns Point
//**********************************************************
public Point getBounds1()
{
Point top=getLocation();
double x=top.getX();
double y1=top.getY();
double y=(yHeight-y1);
Point p2=new Point();
p2.setLocation(x,y);
return p2;

}

public Point getBounds2()
{
Point p5=new Point();
p5.setLocation(2,2);
return p5;
}

//********draw Method********************
public void draw(Graphics2D g)
{

g.setColor(getColor());
AffineTransform saveAt=g.getTransform();
int height1=yHeight; //total height
Point location=getLocation();

top.setLocation(0,height/2);
double heading2=Math.toRadians((getHeading())); //heading in radians
double x=Math.sin(heading2);
double y=Math.cos(heading2);
x +=top.getX();
y +=top.getY();
double heading=getHeading();

if((heading>0)&&(heading<90))
{bottom.setLocation((x-2),(y+ 2));

}
if((heading<180)&&(heading>90))
{ bottom.setLocation((x-2),(y-2));

}
if((heading<270)&&(heading>180))
{ bottom.setLocation((x +2),(y-2));

}
if((heading<360)&&(heading>270))
{bottom.setLocation((x+ 2),(y+ 2));

}
if(heading==0)
{
bottom.setLocation((x),(y+ 2));

}
if(heading==90)
{bottom.setLocation((x-2),(y));

}
if(heading==180)
{bottom.setLocation((x),(y-2));

}

if(heading==270)
{bottom.setLocation((x +2),(y));

}

myAT.setToIdentity();
myAT.translate((int)location.getX(),(int)location.getY());
myAT.rotate(Math.toRadians(getHeading()));

myAT.transform(top,top);
myAT.transform(bottom,bottom);


g.drawLine((int)top.getX(),(height1-((int)top.getY())),
(int)bottom.getX(),(height1-((int)bottom.getY())));

g.setTransform(saveAt);

}//end draw Method

//*********move Method******************
public void move(int elapsedMilliSecs)
{

double speed=(double)getSpeed();
speed=Math.abs(speed);
if(speed<80)
speed=80;
speed=(speed/((double)elapsedMilliSecs));
double heading=getHeading();
double heading2=Math.toRadians(heading); //heading in radians
Point p=getLocation();
double x=p.getX(); //original location
double y=p.getY();
double x1=Math.sin(heading2);
double y1=Math.cos(heading2);
x1+ =x;
y1+ =y;

if((heading>0)&&(heading<90))
{
x1-=speed;
y1+ =speed;
}
if((heading<180)&&(heading>90))
{
x1-=speed;
y1-=speed;
}
if((heading<270)&&(heading>180))
{ x1 +=speed;
y1-=speed;
}
if((heading<360)&&(heading>270))
{
x1 +=speed;
y1 +=speed;
}
if(heading==0)
{
y1 +=speed;
}
if(heading==90)
{
x1-=speed;
}
if(heading==180)
{
y1-=speed;
}

if(heading==270)
{
x1 +=speed;
}



setLocation((int)x1,(int)y1);


}//end move Method



}//end Missiles class




Go To Part 14

Read more...