我正在尝试在java上编写一个tic-tac-toe游戏。
这是我到目前为止的代码(有效),我真的不明白如何绘制圆圈而不是交叉:
public static void main(String[] args) {
//Declare variables
int[][] board = new int[3][3];
int turns = 0, x, y, mode, score = 0;
String dec;
Scanner s = new Scanner(System.in);
//Constants
final int EMPTY = 0;
final int FILL_O = 1;
final int FILL_X = 2;
//Ask user for game type
System.out.println("TicTacToe\n=========");
System.out.print("(1) or (2) players? ");
mode = s.nextInt();
//Draw the board
StdDraw.setScale(0, 3);
StdDraw.setPenRadius(0.008);
for (int c = 0; c <= 3; c++) {
StdDraw.line(c, 0, c, 3);
}
for (int c = 0; c <= 3; c++) {
StdDraw.line(0, c, 3, c);
}
//Two-player Game
if (mode == 2) {
//X goes first
StdDraw.setPenColor(Color.BLUE);
while (turns < 9) {
//Draw Os on odd turns
if (turns % 2 == 1) {
if (StdDraw.mousePressed()) {
x = (int) Math.floor(StdDraw.mouseX());
y = (int) Math.floor(StdDraw.mouseY());
if (board[x][y] == EMPTY) {
StdDraw.circle(x + 0.5, y + 0.5, 0.5);
board[x][y] = FILL_O;
mode = FILL_O; //Since mode is no longer in use, I
reinstate it to track turns
StdDraw.show(500);
turns++;
}
}
}
答案 0 :(得分:0)
而不是使用StdDraw.text(x, y, board[x][y] + "");
测试board[x][y]
的值,并调用在坐标x或y处绘制正方形或圆形的函数。
为了说明这一点,请替换
for (int x = 0; x < board.length; x++) {
for (int y = 0; y < board[x].length; y++) {
StdDraw.text(x, y, board[x][y] + "");
}
}
与
for (int x = 0; x < board.length; x++) {
for (int y = 0; y < board[x].length; y++) {
if (board[x][y] == 'X') {
StdDraw.filledSquare(x, y, 0.5 );
}
else if (board[x][y] == 'O') {
StdDraw.filledCircle(x, y, 0.5 );
}
}
}
进行一些测试以找到半径的漂亮值,0.5可能不会很好。
答案 1 :(得分:0)
该API提供了方法filledCircle
和filledRectangle
。
public static void filledCircle(double x, double y, double r) ;
绘制半径为r的实心圆,以(x,y)为中心。
参数:
- x圆心的x坐标 - y圆心的y坐标
- r圆的半径
public static void filledRectangle(double x, double y, double halfWidth, double halfHeight);
绘制一个给定半宽和半高的实心矩形,以(x,y)为中心。
参数:
- x矩形中心的x坐标 - y矩形中心的y坐标
- halfWidth是矩形的宽度的一半 - halfHeight是矩形高度的一半
或者看filledSquare
...基本相同的rectamgle概念,但参数值相同..
像
这样的东西//CENTER
int x = (int) Math.floor(StdDraw.mouseX());
int y = (int) Math.floor(StdDraw.mouseY());
int r = 10; //radius
StdDraw.filledcircle(x, y, r);
并且
//CENTER
int x = (int) Math.floor(StdDraw.mouseX());
int y = (int) Math.floor(StdDraw.mouseY());
int width = 10;
int height = 10;
//The method use the center of the shape and half of both "length"
StdDraw.filledRectangle(x, y, height / 2, height / 2);