手机上一个坦克游戏
源代码在线查看: bitarray.java
package demo;
/*
* Created on 2004-1-14
*
*/
/**
* @author Dabao
*/
public class BitArray {
private int _width, _height;
private byte[] content = null;
public int m_nX = 0, m_nY = 0;
/**
* 设置数组的宽度和高度
* @param width
* @param height
*/
public BitArray(int w, int h, int cx, int cy) {
this._width = w;
this._height = h;
this.m_nX = cx;
this.m_nY = cy;
if (w > 0 && h > 0) {
int temp = w * h;
if (temp % 7 != 0) {
temp = temp / 7 + 1;
}
else {
temp = temp / 7;
}
content = new byte[temp];
for (int i = 0; i < content.length; i++) {
content[i] = 0;
}
}
}
/**
* 参数是按照数组的坐标来计算的,都是从0 到width-1
* 从0 到height -1
* @param col
* @param row
* @return
*/
public byte get(int x, int y) {
int tranlatedX = x - m_nX;
int tranlatedY = y - m_nY;
if ( (tranlatedX * tranlatedY) >= (_width * _height)) {
System.out.println(tranlatedX);
System.out.println(tranlatedY);
return -1;
}
if (tranlatedX >= 0
&& tranlatedX < _width
&& tranlatedY >= 0
&& tranlatedY < _height) {
byte temp = content[getCursor(tranlatedX, tranlatedY)];
return (byte)
( (temp >> getOffset(tranlatedX, tranlatedY)) & 1);
}
return 0;
}
public void set(int x, int y) {
int tranlatedX = x - m_nX;
int tranlatedY = y - m_nY;
if (tranlatedX >= 0
&& tranlatedX < _width
&& tranlatedY >= 0
&& tranlatedY < _height) {
//int temp = (tranlatedX * _height + tranlatedY + 1) / 7;
int temp = getCursor(tranlatedX, tranlatedY);
try {
content[temp] =
(byte) (content[temp]
| (1 }
catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void reSet(int x, int y) {
int tranlatedX = x - m_nX;
int tranlatedY = y - m_nY;
if (tranlatedX >= 0
&& tranlatedX < _width
&& tranlatedY >= 0
&& tranlatedY < _height) {
int temp = getCursor(tranlatedX, tranlatedY);
byte max = Byte.MAX_VALUE;
max =
(byte) (max
^ (1 content[temp] = (byte) (content[temp] & max);
}
}
public int getWidth() {
return _width + m_nX;
}
public int getHeight() {
return _height + m_nY;
}
private int getCursor(int tx, int ty) {
if (tx < 0 || ty < 0 || tx >= _width || ty >= _height) {
return -1;
}
int cur = tx * _height + ty + 1;
if (cur % 7 == 0) {
return cur / 7 - 1;
}
else {
return cur / 7;
}
}
private int getOffset(int tx, int ty) {
if (tx < 0 || ty < 0 || tx >= _width || ty >= _height) {
return -1;
}
int cur = tx * _height + ty + 1;
if (cur % 7 == 0) {
return 6;
}
else {
return cur % 7 - 1;
}
}
}