如何在基于2D的游戏中生成随机点(令牌,石头...)?
令牌是点的二维数组:
Token[][] gameBoard;
玩家只是绘画对象。它包含以下标记的颜色:Paint bluePaint, redPaint;
在初始化时,我可以手动将令牌任意地放置在板上,如下所示(通过MainActivity的onCreate方法):
bluePlayer = new Token(1,bluePaint, bgrBluePaint);
redPlayer = new Token(2, redPaint, bgrRedPaint);
gameBoard = new Token[100][100];
gameBoard[47][47]= redPlayer;
gameBoard[46][47]= bluePlayer;
gameBoard[44][48] = redPlayer;
gameBoard[44][49]= redPlayer;
gameBoard[45][47]= redPlayer;
gameBoard[45][48]= bluePlayer;
gameBoard[45][49]= bluePlayer;
gameBoard[45][50]= redPlayer;
gameBoard[46][50]= bluePlayer;
gameBoard[46][49]= redPlayer;
gameBoard[46][48]= redPlayer;
gameBoard[47][50]= bluePlayer;
gameBoard[47][48]= bluePlayer;
gameBoard[47][49]= redPlayer;
gameBoard[48][50]= redPlayer;
gameBoard[48][49]= redPlayer;
gameBoard[48][48]= redPlayer;
gameBoard[49][50]= bluePlayer;
gameBoard[48][51]= redPlayer;
所以我的问题是,如何在给定的坐标范围内随机放置redPlayer和bluePlayer?我是说我希望将它们随机放置在板中心周围的单元格中
class Token {
private int _player;
private Paint _paint, _bgrPaint;
Token(int player, Paint paint, Paint bgrPaint) {
_player = player;
_paint = paint;
_bgrPaint = bgrPaint;
}
Paint getPaint() {
return _paint;
}
Paint get_bgrPaint() {
return _bgrPaint;
}
int setPlayer(int _player, int _paint) {
this._player = _paint;
return _player;
}
int getPlayer() {
return _player;
}
}
以上是令牌类
答案 0 :(得分:3)
您可以使用Random
类:
import java.util.Random;
// ...
void generateTokens(int count) {
Random random = new Random();
boolean isRed = false;
for (int i = 0; i < count; i++) {
int x = random.nextInt(100);
int y = random.nextInt(100);
gameBoard[x][y] = isRed ? redPlayer : bluePlayer;
isRed = !isRed;
}
}
如果要将令牌的放置位置限制在棋盘中心附近,最直接的方法是仅限制上述功能分配给的正方形。这种方法的问题在于,随着中心的大小变小,您写入已写入的图块的机会变得更大。
相反,您可以预生成将包含令牌的所有图块的列表。然后,将列表随机化,然后对其进行遍历,将每个图块分配为红色或蓝色:
class Point {
public int X;
public int Y;
public Point(int x, int y) {
this.X = x;
this.Y = y;
}
}
// ...
void generateTokens(int centerRadius) {
Random random = new Random();
ArrayList<Point> positions = new ArrayList<>();
for (int x = 49 - centerRadius; x <= 50 + centerRadius; x++) {
for (int y = 49 - centerRadius; y <= 50 + centerRadius; y++) {
postions.add(new Point(x, y));
}
}
Collections.shuffle(positions);
boolean isRed = true;
for (int i = 0; i < positions.GetLength(); i++) {
Point p = positions.get(i);
gameBoard[p.X][p.Y] = isRed ? redPlayer : bluePlayer;
isRed = !isRed;
}
}
(我不在可以测试此代码的地方,因此可能需要进行一些调整才能使其正常工作。)