Thursday, March 4, 2010

space invaders game

In this and following tutorials you will learn about Applets, Threads, Graphics and a few other things. By the end of this tutorial you should have the skills to make basic games in Java. For this tutorial you will be making a simple ‘space invaders’ type game.

I assume that you have basic knowledge of Java as I wont be going into the basic details of how some things work.

First we will be starting by creating an applet and drawing a circle to the applet area.

1. Create a file called ‘Game.java’.
2. Open the file.

The next step is to import the necessary packages. For now we will only be requiring 2 packages:
import java.applet.*;
import java.awt.*;

Now that the importing has been taken care of we will need to set up the Java applet by the following:

public class Game extends Applet implements Runnable
{
}

This basically gives access to the Applet class and the ‘Runnable’ makes it so we can implement threads.

The variables come next as we wish to make these ones global:

Thread gameThread;
int width=400, height=400, MAX=1;
int currentX[] = new int[MAX];
int currentY[] = new int[MAX];

I have decided to use arrays for the X and Y cords now because they will be used at a later stage. It makes it easier to set it up now rather than changing it later.
Next comes the methods. I have included methods that are currently not used at this stage but they are used later.

Start() is used for starting a new thread for the class.

public void start()
{
Thread gameThread = new Thread(this);
gameThread.start();
}


init() is used for setting the initial values

public void init()
{
currentX[0]=0;
currentY[0]=0;
}

run() is the main method we will use later. It is initialised after a new thread is started.

public void run()
{
}


paint() calls update().

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

update () is where all the actual drawing is done.

public void update(Graphics g)
{
Graphics2D g2 = (Graphics2D)g;

// Set the background color.
g2.setBackground(Color.black);

// Clear the applet.
g2.clearRect(0, 0, width, height);

// Set the drawing color to green.
g2.setColor(Color.green);

//(X pos, Y pos, Width, Height)
g2.fillOval(currentX[0], currentY[0], 20,20);
}


* Note this is an applet which means you must run it from a HTML file. The HTML code to run this applet is as follows and I will use the same code throughout this series of tutorials.

Thursday, January 7, 2010

Set Column name

File: Professor.java


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
//@Table(name="EMP", schema="HR")
@Table(name="EMP")
public class Professor {
@Id
@Column(name = "EMP_ID")
private int id;
@Column(name = "COMM")
private String name;
@Column(name = "SAL")
private long salary;

public Professor() {
}

public Professor(int id) {
this.id = id;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public long getSalary() {
return salary;
}

public void setSalary(long salary) {
this.salary = salary;
}

public String toString() {
return "Professor id: " + getId() + " name: " + getName() + " salary: " + getSalary();
}
}


File: ProfessorService.java

import java.util.Collection;

import javax.persistence.EntityManager;
import javax.persistence.Query;

public class ProfessorService {
protected EntityManager em;

public ProfessorService(EntityManager em) {
this.em = em;
}

public Professor createProfessor(int id, String name, long salary) {
Professor emp = new Professor(id);
emp.setName(name);
emp.setSalary(salary);
em.persist(emp);
return emp;
}

public void removeProfessor(int id) {
Professor emp = findProfessor(id);
if (emp != null) {
em.remove(emp);
}
}

public Professor raiseProfessorSalary(int id, long raise) {
Professor emp = em.find(Professor.class, id);
if (emp != null) {
emp.setSalary(emp.getSalary() + raise);
}
return emp;
}

public Professor findProfessor(int id) {
return em.find(Professor.class, id);
}

public Collection findAllProfessors() {
Query query = em.createQuery("SELECT e FROM Professor e");
return (Collection) query.getResultList();
}
}


File: JPAUtil.java

import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class JPAUtil {
Statement st;

public JPAUtil() throws Exception{
Class.forName("org.hsqldb.jdbcDriver");
System.out.println("Driver Loaded.");
String url = "jdbc:hsqldb:data/tutorial";

Connection conn = DriverManager.getConnection(url, "sa", "");
System.out.println("Got Connection.");
st = conn.createStatement();
}
public void executeSQLCommand(String sql) throws Exception {
st.executeUpdate(sql);
}
public void checkData(String sql) throws Exception {
ResultSet rs = st.executeQuery(sql);
ResultSetMetaData metadata = rs.getMetaData();

for (int i = 0; i < metadata.getColumnCount(); i++) { System.out.print("\t"+ metadata.getColumnLabel(i + 1)); } System.out.println("\n----------------------------------"); while (rs.next()) { for (int i = 0; i < metadata.getColumnCount(); i++) { Object value = rs.getObject(i + 1); if (value == null) { System.out.print("\t "); } else { System.out.print("\t"+value.toString().trim()); } } System.out.println(""); } } } File: Main.java import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class Main { public static void main(String[] a) throws Exception { JPAUtil util = new JPAUtil(); EntityManagerFactory emf = Persistence.createEntityManagerFactory("ProfessorService"); EntityManager em = emf.createEntityManager(); ProfessorService service = new ProfessorService(em); em.getTransaction().begin(); Professor emp = service.createProfessor(158, "AAA", 45000); em.getTransaction().commit(); System.out.println("Persisted " + emp); util.checkData("select * from EMP"); // remove an employee em.getTransaction().begin(); service.removeProfessor(158); em.getTransaction().commit(); System.out.println("Removed Professor 158"); util.checkData("select * from EMP"); em.close(); emf.close();
}
}
File: persistence.xml










Monday, August 3, 2009

Ants





























Free JavaScripts provided

by The JavaScript Source



Clock

import java.applet.*;

import java.awt.*;

import java.util.*;


public class ClockApplet extends Applet implements Runnable{
Thread t,t1;
public void start(){
t = new Thread(this);
t.start();
}

public void run(){
t1 = Thread.currentThread();
while(t1 == t){
repaint();
try{
t1.sleep(1000);
}catch(InterruptedException e){}
}
}

public void paint(Graphics g){
Calendar cal = new GregorianCalendar();
String hour = String.valueOf(cal.get(Calendar.HOUR));
String minute = String.valueOf(cal.get(Calendar.MINUTE));
String second = String.valueOf(cal.get(Calendar.SECOND));
g.drawString(hour + ":" + minute + ":" + second, 20, 30);
}
}

Calculator

/**
This is a simple calculator program can any one take and use.

@author sathish_ssmca
@param nothing */
import javax.swing.*;
import javax.swing.JOptionPane;
import java.awt.*;
import java.awt.event.*;
//
public class Calculator extends JApplet {
public void init() {
CalculatorPanel calc=new CalculatorPanel();
getContentPane().add(calc);
}
}

class CalculatorPanel extends JPanel implements ActionListener {
JButton
n1,n2,n3,n4,n5,n6,n7,n8,n9,n0,plus,minus,mul,div,dot,equal;
static JTextField result=new JTextField("0",45);
static String lastCommand=null;
JOptionPane p=new JOptionPane();
double preRes=0,secVal=0,res;

private static void assign(String no)
{
if((result.getText()).equals("0"))
result.setText(no);
else if(lastCommand=="=")
{
result.setText(no);
lastCommand=null;
}
else
result.setText(result.getText()+no);
}

public CalculatorPanel() {
setLayout(new BorderLayout());
result.setEditable(false);
result.setSize(300,200);
add(result,BorderLayout.NORTH);
JPanel panel=new JPanel();
panel.setLayout(new GridLayout(4,4));

n7=new JButton("7");
panel.add(n7);
n7.addActionListener(this);
n8=new JButton("8");
panel.add(n8);
n8.addActionListener(this);
n9=new JButton("9");
panel.add(n9);
n9.addActionListener(this);
div=new JButton("/");
panel.add(div);
div.addActionListener(this);

n4=new JButton("4");
panel.add(n4);
n4.addActionListener(this);
n5=new JButton("5");
panel.add(n5);
n5.addActionListener(this);
n6=new JButton("6");
panel.add(n6);
n6.addActionListener(this);
mul=new JButton("*");
panel.add(mul);
mul.addActionListener(this);

n1=new JButton("1");
panel.add(n1);
n1.addActionListener(this);
n2=new JButton("2");
panel.add(n2);
n2.addActionListener(this);
n3=new JButton("3");
panel.add(n3);
n3.addActionListener(this);
minus=new JButton("-");
panel.add(minus);
minus.addActionListener(this);

dot=new JButton(".");
panel.add(dot);
dot.addActionListener(this);
n0=new JButton("0");
panel.add(n0);
n0.addActionListener(this);
equal=new JButton("=");
panel.add(equal);
equal.addActionListener(this);
plus=new JButton("+");
panel.add(plus);
plus.addActionListener(this);
add(panel,BorderLayout.CENTER);
}
public void actionPerformed(ActionEvent ae)
{
if(ae.getSource()==n1) assign("1");
else if(ae.getSource()==n2) assign("2");
else if(ae.getSource()==n3) assign("3");
else if(ae.getSource()==n4) assign("4");
else if(ae.getSource()==n5) assign("5");
else if(ae.getSource()==n6) assign("6");
else if(ae.getSource()==n7) assign("7");
else if(ae.getSource()==n8) assign("8");
else if(ae.getSource()==n9) assign("9");
else if(ae.getSource()==n0) assign("0");
else if(ae.getSource()==dot)
{
if(((result.getText()).indexOf("."))==-1)
result.setText(result.getText()+".");
}
else if(ae.getSource()==minus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="-";
result.setText("0");
}
else if(ae.getSource()==div)
{
preRes=Double.parseDouble(result.getText());
lastCommand="/";
result.setText("0");
}
else if(ae.getSource()==equal)
{
secVal=Double.parseDouble(result.getText());
if(lastCommand.equals("/"))
res=preRes/secVal;
else if(lastCommand.equals("*"))
res=preRes*secVal;
else if(lastCommand.equals("-"))
res=preRes-secVal;
else if(lastCommand.equals("+"))
res=preRes+secVal;
result.setText(" "+res);
lastCommand="=";
}
else if(ae.getSource()==mul)
{
preRes=Double.parseDouble(result.getText());
lastCommand="*";
result.setText("0");
}
else if(ae.getSource()==plus)
{
preRes=Double.parseDouble(result.getText());
lastCommand="+";
result.setText("0");
}

}
}

Thursday, July 30, 2009

Second Synchronized Example

class TwoStrings {
static void print(String str1, String str2) {
System.out.print(str1);
try {
Thread.sleep(500);
} catch (InterruptedException ie) {
}
System.out.println(str2);
}
}

class PrintStringsThread implements Runnable {
Thread thread;
String str1, str2;
TwoStrings ts;
PrintStringsThread(String str1, String str2, TwoStrings ts)
{
this.str1 = str1;
this.str2 = str2;
this.ts = ts;
thread = new Thread(this);
thread.start();
}
public void run() {
synchronized (ts) {
ts.print(str1, str2);
}
}
}

class TestThread {
public static void main(String args[]) {
TwoStrings ts = new TwoStrings();
new PrintStringsThread("Hello ", "there.", ts);
new PrintStringsThread("How are ", "you?", ts);
new PrintStringsThread("Thank you ", "very much!", ts);
}
}

Producer-Consumer Example

The following example is an implementation of the Producer-Consumer problem. A class which provides the methods for generating and consuming an integer value is separated from the Producer and the Consumer thread classes.

class SharedData {
int data;
synchronized void set(int value) {
System.out.println("Generate " + value);
data = value;
}
synchronized int get() {
System.out.println("Get " + data);
return data;
}
}

class Producer implements Runnable {
SharedData sd;
Producer(SharedData sd) {
this.sd = sd;
new Thread(this, "Producer").start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sd.set((int)(Math.random()*100));
}
}
}

class Consumer implements Runnable {
SharedData sd;
Consumer(SharedData sd) {
this.sd = sd;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 10 ; i++) {
sd.get();
}
}
}

class TestProducerConsumer {
public static void main(String args[]) throws Exception {
SharedData sd = new SharedData();
new Producer(sd);
new Consumer(sd);
}
}

Here is a sample output of the program.

Generate 8
Generate 45
Generate 52
Generate 65
Get 65
Generate 23
Get 23
Generate 49
Get 49
Generate 35
Get 35
Generate 39
Get 39
Generate 85
Get 85
Get 85
Get 85
Generate 35
Get 35
Get 35

This is not what we wanted the program to do. For every value produced by the producer, we expect the consumer to get each value. Here is the output we expect instead.

Generate 76
Get 76
Generate 25
Get 25
Generate 34
Get 34
Generate 84
Get 84
Generate 48
Get 48
Generate 29
Get 29
Generate 26
Get 26
Generate 86
Get 86
Generate 65
Get 65
Generate 38
Get 38
Generate 46
Get 46

To fix the problem with this code, we use the methods for interthread communication.
The following implementation of the Producer-Consumer problem uses the methods for interthread communication.

class SharedData {
int data;
boolean valueSet = false;
synchronized void set(int value) {
if (valueSet) { //has just produced a value
try {
wait();
} catch (InterruptedException ie) {
}
}
System.out.println("Generate " + value);
data = value;
valueSet = true;
notify();
}
synchronized int get() {
if (!valueSet) { //producer hasn't set a value yet
try {
wait();
} catch (InterruptedException ie) {
}
}
System.out.println("Get " + data);
valueSet = false;
notify();
return data;
}
}

/* The remaining part of the code doesn't change. */
class Producer implements Runnable {
SharedData sd;
Producer(SharedData sd) {
this.sd = sd;
new Thread(this, "Producer").start();
}
public void run() {
for (int i = 0; i < 10; i++) {
sd.set((int)(Math.random()*100));
}
}
}

class Consumer implements Runnable {
SharedData sd;
Consumer(SharedData sd) {
this.sd = sd;
new Thread(this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 10 ; i++) {
sd.get();
}
}
}

class TestProducerConsumer {
public static void main(String args[]) throws Exception {
SharedData sd = new SharedData();
new Producer(sd);
new Consumer(sd);
}
}