GAMES LESSON Twenty-two: Endless Terrain Loop
This demo shows you how to create a recycling terrain loop. This sort of set
up might be useful in certain types of games. Especially notice that the
array which contains a map of the terrain is larger than the portion of that
map which can be displayed on the screen at any given time. Of course, you
could make the map even larger if you wanted.
The most interesting portion of the code for this applet is found at the end
of the keyPressed method. Make sure you understand how the map array is used
within this method. Expecially make sure you understand how vertical changes
in the position of the player are controlled.
import java.awt.*;
import java.applet.*;
import java.awt.event.*;
public class TERR extends Applet{
Dimension d;
//brick=0, sky=1, guy=2
int[][] map = {
{ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1},
{ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,1,1,1,1,1,1,1,1,1},
{ 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,0,0,0,1,1,1,1,1,1,1,1},
{ 1,1,1,1,1,0,1,1,1,1,1,1,1,1,1,1,0,0,0,0,0,1,1,1,1,1,1,1},
{ 1,1,1,1,0,0,0,1,1,1,1,2,1,1,1,0,0,0,0,0,0,0,1,1,1,1,1,1},
{ 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0},
};
//28x8
int xguy=11;
int yguy=6;
int xedge = xguy - 5;
Image[] sps = new Image[3];
Image offI;
public void init(){
d = getSize();
offI=createImage(d.width,d.height);
sps[0] = getImage(getDocumentBase(), "brick.jpg");
sps[1] = getImage(getDocumentBase(), "sky.jpg");
sps[2] = getImage(getDocumentBase(), "guy.jpg");
requestFocus();
this.addKeyListener(new KeyAdapter(){
public void keyPressed(KeyEvent k) {
if(k.getKeyCode() == KeyEvent.VK_LEFT){
if(xguy>0){
map[yguy][xguy]=1;
xguy--;
if(map[yguy][xguy]==1) map[yguy][xguy]=2;
else{
yguy--;
map[yguy][xguy]=2;
}
}
else{
map[yguy][xguy]=1;
xguy=27;
if(map[yguy][xguy]==1) map[yguy][xguy]=2;
else{
yguy--;
map[yguy][xguy]=2;
}
}
}
else if(k.getKeyCode() == KeyEvent.VK_RIGHT){
map[yguy][xguy]=1;
xguy++;
xguy%=28;
if(map[yguy][xguy]==1) map[yguy][xguy]=2;
else{
yguy--;
map[yguy][xguy]=2;
}
}
if(map[yguy+1][xguy]==1){
map[yguy][xguy]=1;
yguy++;
map[yguy][xguy]=2;
}
xedge = xguy-5;
if(xedge<0) xedge=28+xedge;
repaint();
}
});
}
public void update(Graphics g){
paint(g);
}
public void paint(Graphics g){
Graphics offG = offI.getGraphics();
offG.setColor(Color.black);
offG.fillRect(0,0,d.width,d.height);
int hori=0;
for(int y=0; y
ASSIGNMENT: