Register   Login   About   Study   Enterprise   Share
Internet / AI Technology University (ITU/AITU)
Fast Login - available after registration







|

Top Links: >> 80. Technology >> Internet Technology Summit Program >> 3. Threads and Network >> 3.1. Threads
Current Topic: 3.1.2. Threads in graphics and game.
You have a privilege to create a quiz (QnA) related to this subject and obtain creativity score...
Threads in graphics and game

Consider a programming task that involves threads.

The program is a simple game with at least two threads.
One thread periodically generates an event to re-draw a rectangle making it a moving target.
Another thread is the main flow of the program waiting for user input.
User can control the movement, color and size of the moving target with the keyboard.
The end of game is when the user makes rectangle red and moves it to the top right corner.
The SimpleGame class extends the Applet class, which is a graphical component (Panel) and also implements KeyListener and Runnable interfaces.
As KeyListener this class can listen and handle key events.
As Runnable this class can run a thread.
Its run() method generates a key event and the listener, keyTyped() method, makes a move on each key event: generated or from a user.

If you are intrigued by this example and want to learn more ? it is there for you in the Java Graphics and Events section.

ITS, Inc. did not include these sections in the priority list for the following reasons:
- Java Applet is not supported by mobile devices, no iPhone and no Android can run them.
- In general, Java Graphics looks great on desktop machines but is not running on mobile devices.
- Internet Technology School focuses on server side of the story, which can provide sophisticated processing of massive data and support any mobile devices.
And here is the code of a simple game.


import java.applet.Applet;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Label;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;


/**
* The program is a simple game with two threads.
* One thread is periodically re-drawing a rectangle making it a moving target.
* Another thread is the main flow of the program waiting for user input.
* User can control the movement, color and size of the moving target with the keyboard.
* The end of game is when the user makes rectangle red and moves it to the top right corner.
*
* This class extends the Applet class, which is a graphical component (Panel) and also implements KeyListener and Runnable interfaces.
* As KeyListener this class can listen and handle key events.
* As Runnable this class can run a thread.
* Its run() method generates a key event and the listener keyTyped() method makes a move on each key event: generated or from a user.
* The game can work as an applet in an HTML page that would require the following applet tag:
*
* A browser will play the role of a frame.
* Make sure that your browser supports Java Applet and this support is enabled.
* The SimpleGame class must be located in the same directory with the HTML file.
* @author Jeff.Zhuk@javaschool.com
*
*/
public class SimpleGame extends Applet implements KeyListener, Runnable {
private int x,y; // coordinates of the target
private int weight = 20;
private char newChar = 'c';
private Color color = Color.CYAN;
private boolean endOfGame = false;
public void paint(Graphics g) {
g.setColor(color);
g.fillRect(x, y, x+weight, y+weight);
g.setColor(Color.red);
g.drawRect(540, 0, 600, 40);
}

/**
* This running thread will generate a KeyEvent every second
* Untill endOfGame is true
*/
public void run() {
for (;!endOfGame;) {
this.dispatchEvent(new KeyEvent(this, KeyEvent.KEY_TYPED, 0, 0, 0, newChar));
try {
Thread.sleep(1000); // this thread will sleep (do nothing) for 1 sec
} catch (Exception e) {
// never happen
}
}
}
/**
* As a KeyListener this class MUST implement three methods below.
* The program uses only one of them, keyTyped(), to handle key events
* Not all keys are handled, but some change the calculations of coordinates, color, and size of a target.
* On each key event, generated by a thread or initiated by a user, this method repaint the target.
* @param key event
*/
public void keyTyped(KeyEvent e) {
char command = e.getKeyChar();
if(command == '0') {
x = 0;
y = 0;
} else if(command == '>') {
weight +=5;
} else if(command == '<') {
weight -=5;
} else if(command == 'u') {
y -= 10;
color = Color.yellow;
} else if(command == 'd') {
y += 10;
color = Color.DARK_GRAY;
} else if(command == 'l') {
x -= 10;
color = Color.LIGHT_GRAY;
} else if(command == 'r') {
x += 10;
color = Color.red;
} else if(command == 'b') {
color = Color.blue;
} else {
x += 10;
y += 10;
}
if(x == 540 && y == 40 && weight == 40) {
endOfGame = true;
}
repaint();
}
// The program do not use these two potential key handlers, but must provide at least empty implementations
public void keyPressed(KeyEvent e) { }
public void keyReleased(KeyEvent e) { }

/**
* The init() method starts the thread and adds the listener to the Applet/panel
* It is called by main() or automatically by a browser if it is running in an HTML page
*/
public void init() {
Thread mover = new Thread(this);
mover.start();
addKeyListener(this);
}
/**
* The main() method creates a frame with the Applet/panel
* In the case of a running Applet, no main() is needed, a browser makes the frame and calls the init() automatically
* @param args
*/
public static void main(String[] args) {
SimpleGame panel = new SimpleGame();
Frame f = new Frame("Game");
f.setLayout(new BorderLayout());
f.add(panel, BorderLayout.CENTER);
Label label = new Label("Click above and use keyboard (d,u,r,l,<,>,...) make the square red to fit in its right top corner.");
f.add(label, BorderLayout.SOUTH);
panel.init();
f.setSize(600, 600);
f.setVisible(true);
}

}
Was it clear so far?


Assignments:
1. Create the SimpleGame class under your project in the default package. Right mouse click on src and select NEW ? CLASS (no package in Eclipse terms means default package).
2. Type this code in the class and get rid of red lines.
3. Run ? As Java Application and play the game. The application will start a Frame with a moving rectangle. Click on the frame to bring the focus to the frame. This allows this container to consume keyboard events. Now you can press any key and see what happen. Not all keys are really helpful. You soon discover what works and what not. Try to move the rectangle into the top right corner, so it fits into the red square. The game is over when the rectangle is there and its color is red.
4. Optional: Use Wordpad to create an HTML file, simple.html. Provide a single line (see below) in the file:


5. Store this file in C:\its-resources. Find the SimpleGame.class file in c:\ITS\week6.threads\bin ? folder and copy/paste this file to c:\its-resources. Now the applet class and the HTML file are in the same directory.
6. Navigate with a browser to c:\its-resources ? folder and open the simple.html file with a browser. There are chances that the Java applet will work in your browser.
Make sure that Java plugin is present and enabled in your browser.
Note: Windows 8 does not allow running plugins: read here.
If you can see the applet (lucky you!!!) click there and then use the keyboard (d,u,r,l,<,>,...) make the square red to fit in its right top corner.
7. Enhance SimpleGame with additional features: provide Business Requirements, Design Spec, and implementation with the Java program BetterGame.
8. Compress all files together and send as 3.1.2.BetterGame.Your.Name.zip to dean@ituniversity.us
9. Create 3 QnAs and email them in a single file 3.1.2.QnA.Your.Name.txt to dean@ituniversity.us
10. Check Game-based education and suggest good links to educational games and game engines.
-- Start with Scratch and Steam -- look for HTML5 (web-based) solutions
<br/>import java.applet.Applet;
<br/>import java.awt.BorderLayout;
<br/>import java.awt.Color;
<br/>import java.awt.Frame;
<br/>import java.awt.Graphics;
<br/>import java.awt.Label;
<br/>import java.awt.event.KeyEvent;
<br/>import java.awt.event.KeyListener;
<br/>
<br/>
<br/>/**
<br/> * The program is a simple game with two threads.
<br/> * One thread is periodically re-drawing a rectangle making it a moving target.
<br/> * Another thread is the main flow of the program waiting for user input. 
<br/> * User can control the movement, color and size of the moving target with the keyboard. 
<br/> * The end of game is when the user makes rectangle red and moves it to the top right corner.
<br/> * 
<br/> * This class extends the Applet class, which is a graphical component (Panel) and also implements KeyListener and Runnable interfaces.
<br/> * As KeyListener this class can listen and handle key events.
<br/> * As Runnable this class can run a thread. 
<br/> * Its run() method generates a key event and the listener keyTyped() method makes a move on each key event: generated or from a user.
<br/> * The game can work as an applet in an HTML page that would require the following applet tag:
<br/> * <applet code="SimpleGame.class" width="600" height="600">
<br/> * A browser will play the role of a frame. 
<br/> * Make sure that your browser supports Java Applet and this support is enabled.
<br/> * The SimpleGame class must be located in the same directory with the HTML file.
<br/> * @author Jeff.Zhuk@javaschool.com
<br/> *
<br/> */
<br/>public class SimpleGame extends Applet implements KeyListener, Runnable {
<br/>	private int x,y; // coordinates of the target
<br/>	private int weight = 20;
<br/>	private char newChar = 'c';
<br/>	private Color color = Color.CYAN;
<br/>	private boolean endOfGame = false;
<br/>	public void paint(Graphics g) {
<br/>        g.setColor(color);
<br/>        g.fillRect(x, y, x+weight, y+weight);
<br/>        g.setColor(Color.red);
<br/>        g.drawRect(540, 0, 600, 40);
<br/>    }
<br/>
<br/>	/**
<br/>	 * This running thread will generate a KeyEvent every second
<br/>	 * Untill endOfGame is true
<br/>	 */
<br/>	public void run() {
<br/>		for (;!endOfGame;) {
<br/>			this.dispatchEvent(new KeyEvent(this, KeyEvent.KEY_TYPED, 0, 0, 0, newChar));
<br/>			try {
<br/>				Thread.sleep(1000); // this thread will sleep (do nothing) for 1 sec
<br/>			} catch (Exception e) {
<br/>				// never happen
<br/>			}
<br/>		}
<br/>	}
<br/>	/**
<br/>	 * As a KeyListener this class MUST implement three methods below.
<br/>	 * The program uses only one of them, keyTyped(), to handle key events
<br/>	 * Not all keys are handled, but some change the calculations of coordinates, color, and size of a target.
<br/>	 * On each key event, generated by a thread or initiated by a user, this method repaint the target.
<br/>	 * @param key event
<br/>	 */
<br/>	public void keyTyped(KeyEvent e) {
<br/>        char command = e.getKeyChar();
<br/>        if(command == '0') {
<br/>        	x = 0;
<br/>        	y = 0;
<br/>        } else if(command == '>') {
<br/>        	weight +=5;
<br/>        } else if(command == '<') {
<br/>        	weight -=5;
<br/>        } else if(command == 'u') {
<br/>        	y -= 10;
<br/>        	color = Color.yellow;
<br/>        } else if(command == 'd') {
<br/>        	y += 10;
<br/>        	color = Color.DARK_GRAY;
<br/>        } else if(command == 'l') {
<br/>        	x -= 10;
<br/>        	color = Color.LIGHT_GRAY;
<br/>        } else if(command == 'r') {
<br/>        	x += 10;
<br/>        	color = Color.red;
<br/>        } else if(command == 'b') {
<br/>        	color = Color.blue;
<br/>        } else {
<br/>	        x += 10;
<br/>	        y += 10;
<br/>        }
<br/>        if(x == 540 && y == 40 && weight == 40) {
<br/>        	endOfGame = true;
<br/>        }
<br/>        repaint();	
<br/>    }
<br/>	// The program do not use these two potential key handlers, but must provide at least empty implementations
<br/>	public void keyPressed(KeyEvent e) {	}
<br/>	public void keyReleased(KeyEvent e) {	}
<br/>	
<br/>	/**
<br/>	 * The init() method starts the thread and adds the listener to the Applet/panel
<br/>	 * It is called by main() or automatically by a browser if it is running in an HTML page
<br/>	 */
<br/>	public void init() {
<br/>		Thread mover = new Thread(this);
<br/>		mover.start();			
<br/>		addKeyListener(this);
<br/>	}
<br/>	/**
<br/>	 * The main() method creates a frame with the Applet/panel
<br/>	 * In the case of a running Applet, no main() is needed, a browser makes the frame and calls the init() automatically
<br/>	 * @param args
<br/>	 */
<br/>	public static void main(String[] args) {
<br/>		SimpleGame panel = new SimpleGame();
<br/>		Frame f = new Frame("Game");
<br/>		f.setLayout(new BorderLayout());
<br/>		f.add(panel, BorderLayout.CENTER);
<br/>		Label label = new Label("Click above and use keyboard (d,u,r,l,<,>,...) make the square red to fit in its right top corner.");
<br/>		f.add(label, BorderLayout.SOUTH);
<br/>		panel.init();
<br/>		f.setSize(600, 600);
<br/>		f.setVisible(true);
<br/>	}
<br/>
<br/>}
<br/>






Was it clear so far?



Assignments:
1. Create the SimpleGame class under your project in the default package. Right mouse click on src and select NEW ? CLASS (no package in Eclipse terms means default package).
2. Type this code in the class and get rid of red lines.
3. Run ? As Java Application and play the game. The application will start a Frame with a moving rectangle. Click on the frame to bring the focus to the frame. This allows this container to consume keyboard events. Now you can press any key and see what happen. Not all keys are really helpful. You soon discover what works and what not. Try to move the rectangle into the top right corner, so it fits into the red square. The game is over when the rectangle is there and its color is red.
4. Optional: Use Wordpad to create an HTML file, simple.html. Provide a single line (see below) in the file:
<applet code="SimpleGame.class" width="600" height="600">

5. Store this file in C:\its-resources. Find the SimpleGame.class file in c:\ITS\week6.threads\bin ? folder and copy/paste this file to c:\its-resources. Now the applet class and the HTML file are in the same directory.
6. Navigate with a browser to c:\its-resources ? folder and open the simple.html file with a browser. There are chances that the Java applet will work in your browser.
Make sure that Java plugin is present and enabled in your browser.
Note: Windows 8 does not allow running plugins: read here.
If you can see the applet (lucky you!!!) click there and then use the keyboard (d,u,r,l,<,>,...) make the square red to fit in its right top corner.
7. Enhance SimpleGame with additional features: provide Business Requirements, Design Spec, and implementation with the Java program BetterGame.
8. Compress all files together and send as 3.1.2.BetterGame.Your.Name.zip to dean@ituniversity.us
9. Create 3 QnAs and email them in a single file 3.1.2.QnA.Your.Name.txt to dean@ituniversity.us
10. Check Game-based education and suggest good links to educational games and game engines.
-- Start with Scratch and Steam -- look for HTML5 (web-based) solutions


Have a suggestion? - shoot an email
Looking for something special? - Talk to me
Read: IT of the future: AI and Semantic Cloud Architecture | Fixing Education
Do you want to move from theory to practice and become a magician? Learn and work with us at Internet Technology University (ITU) - JavaSchool.com.

Technology that we offer and How this works: English | Spanish | Russian | French

Internet Technology University | JavaSchool.com | Copyrights © Since 1997 | All Rights Reserved
Patents: US10956676, US7032006, US7774751, US7966093, US8051026, US8863234
Including conversational semantic decision support systems (CSDS) and bringing us closer to The message from 2040
Privacy Policy