GAMES TWO: LESSON Twelve: Cantris: Columns
This game is really not much of a game, but it gives us a preliminary
mock-up which we can use to develop a more interesting game. Go ahead and
play with this applet. You should try out the arrow keys. They are the only
keys that are used in the game. You should also figure out how scoring works
in this game.
There are two classes used in this game. The first class we will look at is
called the CAN class:
import java.awt.*;
class CAN{
Color[] cr={Color.white, Color.white, Color.white};
int x, y, col;
CAN(Color A, Color B, Color C){
//CONSTRUCTOR
cr[0] = A;
cr[1] = B;
cr[2] = C;
y = 10;
x = 60;
col =3;
}
public void moveX(int n){
//CHANGE VALUE OF X TO MOVE CAN SIDE TO SIDE
if(x>30 && n == -1){
x-=10;
col--;
}
else if(x<80 && n == 1){
x+=10;
col++;
}
}
public void moveY(){
//CHANGE VALUE OF Y TO MOVE CAN DOWNWARD
y+=3;
}
public boolean score(Color sc){
//CHECK TO SEE IF CAN LANDED ON RIGHT COLOR LANDING PAD
if(sc.equals(cr[2])) return true;
else return false;
}
public boolean hit_bottom(){
//CHECK TO SEE IF CAN HIT BOTTOM OF PLAY AREA
if(y>190){
y=190;
return true;
}
else return false;
}
public void draw(Graphics g){
//DRAW THE CAN
g.setColor(cr[0]);
g.fillRect(x,y,10,10);
g.setColor(cr[1]);
g.fillRect(x,y+10,10,10);
g.setColor(cr[2]);
g.fillRect(x,y+20,10,10);
}
}
Here is the code for the applet class:
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
import java.util.*;
public class CC1 extends Applet implements Runnable{
Dimension d;
Thread tm;
Random r = new Random();
Image offI;
CAN can;
int speed = 100;
int score = 0;
Color sel[] = { Color.red, Color.blue, Color.cyan,
Color.green, Color.magenta, Color.yellow };
String title[] = { "C", "A", "N", "T", "R", "I", "S" };
public void init(){
d = getSize();
offI=createImage(d.width,d.height);
reset();
spawn();
tm = new Thread(this);
tm.start();
requestFocus();
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_RIGHT){
can.moveX(1);
}
else if(k.getKeyCode() == KeyEvent.VK_LEFT){
can.moveX(-1);
}
else if(k.getKeyCode() == KeyEvent.VK_DOWN){
speed=20;
}
else if(k.getKeyCode() == KeyEvent.VK_UP){
speed=100;
}
repaint();
}
});
}
public void reset(){
}
public void spawn(){
Color c[] = new Color[3];
speed = 100;
int x = 0;
for(int i = 0; i
Make sure that you can trace the following events in this applet and answer
the questions:
- creation of new cans
- checking to see if can landed on correct landing pad
- speeding up and slowing down of can descent
- How is can kept from going to far to the left or right?
- Could the score method be rewritten to work from the applet class
instead of from within the CAN class?
- Could we get rid of either the x or the col variable in the CAN
class?
ASSIGNMENT:
Figure out how to make the can fall on its side. Also enhance the scoring so
as to check for alignment between each section of the can and the scoring
pads.