📄 maingame.java
字号:
/*
*游戏画面
*作者:肖昶
*
*/
package fivegame;
import java.io.*;
import javax.microedition.lcdui.*;
import javax.microedition.rms.*;
public class MainGame extends Canvas implements Runnable, CommandListener {
private static byte board[][];// 棋盘
private static final int N = 15;// 棋盘大小15*15
private static int width;// 屏幕宽
private static int height;// 屏幕高
// 光标位置
private static byte cursorX;
private static byte cursorY;
private static Command exitCmd;
private static Command viewCmd;
private static Image waitYouImage = null;
private static Image waitSelfImage = null;
private boolean isServer;
private boolean myTurn;
private static final int dxs[] = { 1, 1, 0, -1, -1, -1, 0, 1 };
private static final int dys[] = { 0, 1, 1, 1, 0, -1, -1, -1 };
private short myWLData[];
private String myName;
private short yourWLData[];
private String yourName;
public static MainGame instance;// 本类实例
boolean IsShowDisconnectionInfo;
MainGame(boolean isServer) {
width = getWidth();// 屏幕宽
height = getHeight();// 屏幕高
try {
waitYouImage = Image.createImage("/WaitYou.PNG");
waitSelfImage = Image.createImage("/WaitSelf.PNG");
} catch (IOException x) {
System.out.println("Load Image Error!" + x.getMessage());
}
this.isServer = isServer;// 是否是服务器
myTurn = !isServer;// 客户端先下
IsShowDisconnectionInfo = true;
board = new byte[N][N];// 棋盘
exitCmd = new Command("退出", 7, 2);
viewCmd = new Command("战绩", 5, 1);
addCommand(exitCmd);
addCommand(viewCmd);
setCommandListener(this);
clearBoard();// 棋盘清理
exchangeUserInfo();// 交换用户信息
(new Thread(this)).start();// 开始游戏线程
}
// 棋盘清理
private void clearBoard() {
cursorX = 7;
cursorY = 7;
for (int i = 0; i < 15; i++) {
for (int j = 0; j < 15; j++)
board[i][j] = 0;
}
repaint();
}
// 交换用户信息
private void exchangeUserInfo() {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore("UserInfo", false);
} catch (RecordStoreException e) {
e.printStackTrace();
}
// 自己信息从本地记录读取
myName = Setting.readUserName(rs);
myWLData = new short[2];
Setting.readWLData(rs, myWLData);
try {
rs.closeRecordStore();
} catch (RecordStoreException e) {
e.printStackTrace();
}
try {
// 向对方发送自己的信息
ConnectionControler.sendUserInfo(myName, myWLData);
} catch (IOException e) {
e.printStackTrace();
}
// 接受对方的信息
yourName = ConnectionControler.readUserName();
yourWLData = ConnectionControler.readUserWL();
}
// 检查游戏是否结束
public void checkWin(byte abyte0[][], int i, int j) {
StringBuffer stringbuffer = new StringBuffer();
boolean flag = false;
boolean flag1 = false;
for (int k = 0; k < dxs.length; k++) {
int dx = dxs[k];
int dy = dys[k];
stringbuffer.delete(0, stringbuffer.length());
int x = i - dx * 6;
int y = j - dy * 6;
for (int s = 0; s < 12; s++, x += dx, y += dy) {
char c = 'X';
if (x >= 0 && x < 15 && y >= 0 && y < 15)
if (abyte0[x][y] == 0)
c = '.';
else if (abyte0[x][y] == 1)
c = 'M';
else if (abyte0[x][y] == 2)
c = 'W';
stringbuffer.append(c);
}
String s = stringbuffer.toString();
if (s.indexOf("MMMMM") >= 0)
flag = true;
else if (s.indexOf("WWWWW") >= 0)
flag1 = true;
}
if (flag) {
clearBoard();
String info;
if (isServer) {
myTurn = false;
info = "你胜利了!";
updateData(true);
myWLData[0]++;
yourWLData[1]++;
} else {
myTurn = true;
info = "你输了!";
updateData(false);
myWLData[1]++;
yourWLData[0]++;
}
Alert alt = new Alert(info, null, null, AlertType.CONFIRMATION);
alt.setString("再来一次吧?");
alt.setTimeout(-2);
alt.addCommand(new Command("是", 4, 1));
alt.addCommand(new Command("否", 3, 1));
alt.setCommandListener(this);
FiveGame.display.setCurrent(alt, this);
}
if (flag1) {
clearBoard();
String info;
if (!isServer) {
myTurn = false;
info = "你胜利了!";
updateData(true);
myWLData[0]++;
yourWLData[1]++;
} else {
myTurn = true;
info = "你输了!";
updateData(false);
myWLData[1]++;
yourWLData[0]++;
}
Alert alt = new Alert(info, null, null, AlertType.CONFIRMATION);
alt.setString("再来一次吧?");
alt.setTimeout(-2);
alt.addCommand(new Command("是", 4, 1));
alt.addCommand(new Command("否", 3, 1));
alt.setCommandListener(this);
FiveGame.display.setCurrent(alt, this);
}
}
// 负责通信线程
public void run() {
try {
int type = 0;
do {
type = ConnectionControler.readMessageType();// 读取信息类型
if (type == 1) {// 收到的信息是着棋信息
byte chess[] = ConnectionControler.readChess();
cursorX = chess[0];
cursorY = chess[1];
// 根据信息更新棋盘
if (isServer)
board[cursorX][cursorY] = 2;
else
board[cursorX][cursorY] = 1;
myTurn = true;
checkWin(board, cursorX, cursorY);
repaint();
} else if (type == 2) {// 收到的是对方要求再来一局的请求
Alert alt = new Alert("确认", null, null,
AlertType.CONFIRMATION);
alt.setString("对方要再来一局,同意否?");
alt.setTimeout(Alert.FOREVER);
alt.addCommand(new Command("同意", 4, 1));
alt.addCommand(new Command("不同意", 3, 1));
alt.setCommandListener(this);
FiveGame.display.setCurrent(alt, this);
} else if (type == 3) {// 收到的是对方同意再来一局的回复
Alert alt = new Alert("提示", null, null,
AlertType.CONFIRMATION);
alt.setString("对方同意再来一局!");
alt.setTimeout(2000);
FiveGame.display.setCurrent(alt, this);
}
} while (true);
} catch (Exception e) {// 对方拒绝再来一局或者连接意外中断
e.printStackTrace();
Alert exitInfo = new Alert("错误", "对方不想再来一局或者连接意外中断!", null,
AlertType.INFO);
exitGame();
System.gc();
FiveGame.display.setCurrent(exitInfo, MainMenu.getInstance());
}
}
// 命令动作响应, CommandListener接口必须实现的方法
public void commandAction(Command cmd, Displayable display) {
if (cmd.getLabel().equalsIgnoreCase("是")) {// 再来一局
try {
// 给对方发送请求
ConnectionControler.dos.writeByte(2);
ConnectionControler.dos.flush();
} catch (IOException e) {
FiveGame.fiveGame.notifyDestroyed();
}
Alert alt = new Alert("提示", null, null, AlertType.CONFIRMATION);
alt.setString("已经发送请求,等待回应中...");
alt.setTimeout(-2);
FiveGame.display.setCurrent(alt, this);
} else if (cmd.getLabel().equalsIgnoreCase("否")) {// 不再进行下一局
exitGame();
instance = null;
System.gc();
FiveGame.display.setCurrent(MainMenu.getInstance());
} else if (cmd.getLabel().equalsIgnoreCase("同意")) {// 回复同意再来一局
try {
// 给对方发送同意的回复
ConnectionControler.dos.writeByte(3);
ConnectionControler.dos.flush();
} catch (IOException e) {
FiveGame.fiveGame.notifyDestroyed();
}
FiveGame.display.setCurrent(this);
} else if (cmd.getLabel().equalsIgnoreCase("不同意")) {// 回复不同意再来一局
exitGame();
System.gc();
FiveGame.display.setCurrent(MainMenu.getInstance());
} else if (cmd == viewCmd) {// 查看双方信息
Alert alt = new Alert("双方信息", null, null, AlertType.INFO);
alt.setTimeout(-2);
StringBuffer sb = new StringBuffer(" 玩家名称:");
sb.append(yourName).append('\n');
sb.append(" Wins : ").append(yourWLData[0]).append('\n');
sb.append(" Losts : ").append(yourWLData[1]).append('\n');
sb.append("\n 玩家:");
sb.append(myName).append('\n');
sb.append(" Wins : ").append(myWLData[0]).append('\n');
sb.append(" Losts : ").append(myWLData[1]);
alt.setString(sb.toString());
FiveGame.display.setCurrent(alt, this);
} else if (cmd == exitCmd) {// 离开游戏
exitGame();
System.gc();
FiveGame.display.setCurrent(MainMenu.getInstance());
}
}
// 屏幕绘制
public void paint(Graphics g) {
g.setClip(0, 0, width, height);
g.setColor(0xf9a902);
g.fillRect(0, 0, width, height);
int a = (height - 6 - waitSelfImage.getHeight()) < width ? (height - 6 - waitSelfImage
.getHeight())
: width;// 棋盘正方形的边长
a = a - 8;// 留出边界空隙
int d = a / 14;// 小格子边长
int startX = (width - (14 * d)) / 2;
int startY = (height - 6 - waitSelfImage.getHeight() - (14 * d)) / 2
+ (6 + waitSelfImage.getHeight());
g.setColor(0);// 画网格
for (int i = 0; i < 15; i++) {
g.drawLine(startX + i * d, startY, startX + i * d, startY + 14 * d);
g.drawLine(startX, startY + i * d, startX + 14 * d, startY + i * d);
}
g.setColor(0xff0000);
int x = startX + cursorX * d;
int y = startY + cursorY * d;
int r = d / 2;
// 画光标
g.drawLine(x - r, y - r, x + r, y - r);
g.drawLine(x - r, y - r, x - r, y + r);
g.drawLine(x + r, y + r, x + r, y - r);
g.drawLine(x + r, y + r, x - r, y + r);
// 画棋子
for (int i = 0; i < 15; i++)
for (int j = 0; j < 15; j++) {
if (board[i][j] == 1)
g.setColor(0xffffff);
else if (board[i][j] == 2)
g.setColor(0);
else
continue;
g.fillArc((startX + i * d) - (r - 1), (startY + j * d)
- (r - 1), 2 * (r - 1), 2 * (r - 1), 0, 360);
}
// 画提示栏
if (myTurn)
g.drawImage(waitSelfImage,
(getWidth() - waitSelfImage.getWidth()) / 2, 3, 0);
else
g.drawImage(waitYouImage,
(getWidth() - waitYouImage.getWidth()) / 2, 3, 0);
}
// 离开游戏的清理
public final void exitGame() {
try {
ConnectionControler.dis.close();
ConnectionControler.dos.close();
if (isServer)
Server.instance = null;
else
Client.instance = null;
instance = null;
} catch (Exception e) {
e.printStackTrace();
}
}
// 按键响应
protected void keyPressed(int key) {
if (!myTurn)// 没有轮到自己下则屏蔽按键响应
return;
int k = getGameAction(key);
switch (k) {
case UP: // 上
if (cursorY > 0)
cursorY--;
break;
case DOWN: // 下
if (cursorY < 14)
cursorY++;
break;
case LEFT: // 左
if (cursorX > 0)
cursorX--;
break;
case RIGHT: // 右
if (cursorX < 14)
cursorX++;
break;
case FIRE: // 着棋
if (board[cursorX][cursorY] != 0)// 非空白不能着棋
break;
if (isServer)
board[cursorX][cursorY] = 1;
else
board[cursorX][cursorY] = 2;
ConnectionControler.sendChess(cursorX, cursorY);// 发送自己的着棋位置
myTurn = false;// 轮到对方下了
checkWin(board, cursorX, cursorY);
break;
}
repaint();
}
// 更新胜负信息
public void updateData(boolean isWin) {
RecordStore rs = null;
try {
rs = RecordStore.openRecordStore("UserInfo", false);
Setting.writeWLData(rs, false, false, isWin);
} catch (RecordStoreException e) {
e.printStackTrace();
}
try {
rs.closeRecordStore();
} catch (RecordStoreException e) {
e.printStackTrace();
}
}
// 返回本类的实例
public static MainGame getInstance(boolean isServer) {
if (instance == null)
instance = new MainGame(isServer);
return instance;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -