Race game

さっそく、レースゲームを作ってみた。基本的には「Javaゲームプログラミング アルゴリズムとフレームワーク 長久 勝 (著)」に書いてあるものと同じだが、壁クラスを作ったり、Viewとなるクラスの仕事を増やしたりして、もう少しオブジェクト指向らしくしてみた。コメントは書いていないのですが、やっていることは大体わかるでしょう。

package org.sssg.four.game;
import java.applet.Applet;
import java.awt.AWTEvent;
import java.awt.TextArea;
import java.awt.event.KeyEvent;

public class Race extends Applet implements Runnable {
private int fieldWidth = 38;
private int carX = fieldWidth / 2;
private GameField field;
private Wall wall = new Wall();
private volatile Thread runner;

class Wall {
private int left = 14;
private int length = 10;
int getLeft() {
return left;
}
int getRight() {
return left+length;
}
void setLeft(int left) {
this.left = left;
}
void setLength(int length) {
this.length = length;
}
void left() {
if (left > 0) {
left–;
}
}
void right() {
if (left+length < fieldWidth) {
left++;
}
}
boolean isIntersect(int x) {
return getLeft() < x && x < getRight();
}
}

class GameField extends TextArea {
public GameField(int width, int height) {
super(“”, height, width, TextArea.SCROLLBARS_NONE);
enableEvents(AWTEvent.KEY_EVENT_MASK);
setEditable(false);
}

public void processKeyEvent(KeyEvent e) {
if (e.getID() != KeyEvent.KEY_PRESSED) {
return;
}
switch (e.getKeyCode()) {
case KeyEvent.VK_LEFT :
if (carX > 0) {
carX–;
}
break;
case KeyEvent.VK_RIGHT :
if (carX < 38) {
carX++;
}
break;
}
}

private String WALL = “#”;
private String CAR = “*”;
private String LOAD = ” “;
public void draw() {
String str;
str = “”;
for (int i = 0; i < 40; i++) {
if (i == wall.getLeft() || i == wall.getRight()) {
str += WALL;
}
else if (i == carX) {
str += CAR;
}
else {
str += LOAD;
}
}
str += “\n”;
field.insert(str, 0);
}

public void drawGameOver(int score) {
insert(“Crash!!\n”, 0);
insert(“Score : ” + score + “\n”, 0);
}
}

public void init() {
field = new GameField(35, 10);
add(field);
}

public void start() {
if (runner == null) {
runner = new Thread(this);
}
runner.start();
}

public void stop() {
runner = null;
}

public void run() {
int speed = 200;
int score = 0;
Thread current = Thread.currentThread();
field.requestFocus();

while (runner == current) {
if (isGameOver(carX)) {
field.drawGameOver(score);
break;
}
else {
field.draw();
}

if ((int) (Math.random() * 2.) % 2 == 0) {
wall.left();
} else {
wall.right();
}

if (speed > 100) {
speed–;
}
score++;
try {
Thread.sleep(speed);
} catch (Exception e) {
}
}
}

public boolean isGameOver(int x) {
return !wall.isIntersect(x);
}
}

アプレットなので、動作させるには HTMLファイルが必要です。

<html>
<head>
<title>Race</title>
</head>
<applet code=”org.sssg.four.game.Race.class” width=”300″ height=”180″>
</applet>
</html>
同じカテゴリの記事: Java