在二维数组中表示索引的更简单方法 [英] Easier way to represent indicies in a 2D array
问题描述
我是编程新手,我已经创建了一个简单的井字游戏.它接受了二维数组的行和列的输入.但是,我想让它更简单,而是使用 1-9
的值来表示板上的每个方块.
I'm new to programming and I've created a simple tic-tac-toe game. It took an input of the row and column of a 2d array. However, I want to make it simpler and use a value of 1-9
instead to represent each square on the board.
我的方法似乎相当漫长和复杂.因为我想节省空间,所以很抱歉格式不正确.
The way I've gone about this seems rather long and complex. Sorry about the bad formatting since I wanted to save space.
if (pos >= 0 && pos <= 9) { //checks if number is a valid position on the board
if (pos == 1 && board[0][0] == ' ') { board[0][0] = xo; return true; }
if (pos == 2 && board[0][1] == ' ') { board[0][1] = xo; return true; }
if (pos == 3 && board[0][2] == ' ') { board[0][2] = xo; return true; }
if (pos == 4 && board[1][0] == ' ') { board[1][0] = xo; return true; }
if (pos == 5 && board[1][1] == ' ') { board[1][1] = xo; return true; }
if (pos == 6 && board[1][2] == ' ') { board[1][2] = xo; return true; }
if (pos == 7 && board[2][0] == ' ') { board[2][0] = xo; return true; }
if (pos == 8 && board[2][1] == ' ') { board[2][1] = xo; return true; }
if (pos == 9 && board[2][2] == ' ') { board[2][2] = xo; return true; }
}
return false;
内部 if 语句检查索引是否为空,然后根据输入的数字分配 x
或 o
.如果有人知道这样做的任何更清洁"和更简单的方法,将不胜感激.
The inner if statements check if the index is empty and then assigns the x
or o
depending on the number entered. If anyone knows any 'cleaner' and easier ways of doing this it would be much appreciated.
推荐答案
/
- 除法运算符%
- 余数运算符
/
- Division operator%
- Remainder operator
你可以在没有循环的情况下获得单元格[i][j]
的坐标,只使用1<范围内的一个变量
pos
/code> 到 9
:
You can get the coordinates of the cell [i][j]
without loops at all, using only one variable pos
in the range from 1
to 9
:
public static boolean isValid(int pos, char xo) {
int i = (pos - 1) / 3; // row
int j = (pos - 1) % 3; // column
if (board[i][j] == ' ') {
board[i][j] = xo;
return true;
}
return false;
}
这篇关于在二维数组中表示索引的更简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!