ソリティア・ゲームのソースコード
※「img0.gif」「img1.gif」「img2.gif」に、それぞれ「何もない状態」「コマがある状態」「コマが選択された状態」のイメージを作成し、「res」フォルダに入れてください。
import com.nttdocomo.io.ConnectionException;
import com.nttdocomo.ui.*;
public class SampleIApp extends IApplication {
public void start() {
Display.setCurrent(new MainCanvas(this));
}
}
class MainCanvas extends Canvas {
IApplication iapp;
int[][] data;
int x,y,selx,sely;
Image[] img;
MainCanvas(IApplication app){
super();
this.iapp = app;
data = new int[][]{
{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}};
this.setSoftLabel(Frame.SOFT_KEY_1, "NEW");
this.setSoftLabel(Frame.SOFT_KEY_2, "QUIT");
try {
img = new Image[]{null,null,null,null};
MediaImage mi0 =MediaManager.getImage("resource:///img0.gif");
mi0.use();
img[0] = mi0.getImage();
MediaImage mi1 =MediaManager.getImage("resource:///img1.gif");
mi1.use();
img[1] = mi1.getImage();
MediaImage mi2 =MediaManager.getImage("resource:///img2.gif");
mi2.use();
img[2] = mi2.getImage();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (UIException e) {
e.printStackTrace();
} catch (ConnectionException e) {
e.printStackTrace();
}
}
public void init(){
for(int i = 0;i < 5;i++)
for(int j = 0;j < 5;j++)
data[i][j] = 1;
x = 2;
y = 2;
selx = 2;
sely = 2;
data[x][y] = 0;
this.repaint();
}
public void select(){
if (x == selx && y == sely){
} else {
boolean f = true;
f = data[x][y] == 0 ? f : false;
f = data[selx][sely] == 1 ? f : false;
f = (Math.abs(x - selx) == 0 || Math.abs(x - selx) == 2) ? f : false;
f = (Math.abs(y - sely) == 0 || Math.abs(y - sely) == 2) ? f : false;
int midx = (x + selx) / 2;
int midy = (y + sely) / 2;
f = data[midx][midy] == 1 ? f : false;
if (f){
data[midx][midy] = 0;
data[selx][sely] = 0;
data[x][y] = 1;
}
}
selx = x;
sely = y;
this.repaint();
}
public void move(int dx,int dy){
x = x + dx;
y = y + dy;
x = x < 0 ? 0 : x;
x = x > 4 ? 4 : x;
y = y < 0 ? 0 : y;
y = y > 4 ? 4 : y;
this.repaint();
}
public void paint(Graphics g) {
if (img[0] == null) return;
g.lock();
g.setColor(Graphics.getColorOfRGB(255, 255, 255));
g.fillRect(0, 0, 250, 250);
for(int i = 0;i < 5;i++)
for(int j = 0;j < 5;j++){
switch(data[i][j]){
case 0:
g.drawImage(img[0],i * 32, j * 32);
break;
case 1:
if (i == selx && j == sely){
g.drawImage(img[2],i * 32, j * 32);
} else {
g.drawImage(img[1],i * 32, j * 32);
}
break;
}
}
g.setColor(Graphics.getColorOfRGB(255, 0, 0));
g.drawRect(x * 32, y * 32, 32, 32);
g.unlock(true);
}
public void processEvent(int type, int param) {
super.processEvent(type, param);
switch(type){
case Display.KEY_PRESSED_EVENT:
switch(param){
case Display.KEY_SOFT1:
init();
break;
case Display.KEY_SOFT2:
iapp.terminate();
break;
case Display.KEY_UP:
move(0,-1);
break;
case Display.KEY_DOWN:
move(0,1);
break;
case Display.KEY_RIGHT:
move(1,0);
break;
case Display.KEY_LEFT:
move(-1,0);
break;
case Display.KEY_SELECT:
select();
break;
}
}
}
}