[英]Tic-Tac-Toe Game In Java
我正在嘗試在Java上編寫井字游戲。
這是我到目前為止(有效)的代碼,我不太了解如何繪制圓圈而不是十字:
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++;
}
}
}
而不是使用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可能不是很好。
該API提供了方法filledCircle
和filledRectangle
。
public static void filledCircle(double x, double y, double r) ;
繪制以(x,y)為中心的半徑r的實心圓。
參數:
-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
...基本上具有相同的思想,但參數中的值相同。
就像是
//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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.