오늘은 「java_an_introduction_to_problem_solving_and_programming_6th_edition」 564페이지 7번 문제를 풀어보겠습니다.
<문제>
tictactoe라는 게임을 만들어 보겠습니다.
tictactoe는 [3][3] 배열에서 가로, 세로 대각선 중 한 줄을 먼저 완성하는 사람이 이기는 게임입니다.
빙고와 유사하다고 생각하시면 됩니다.
import java.util.Scanner;
public class TicTacToe {
static char[][] board = new char[3][3];
char turn;
static int count;
public void addMove(int i, int j) {
board[i][j] = turn;
}
public void display() {
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
System.out.print(board[i][j]);
}
System.out.println();
}
}
public char turn() {
if(count%2==0) {
turn = 'x';
System.out.println("x turn");
}
else if(count%2!=0){
turn ='o';
System.out.println("o turn");
}
return turn;
}
public int winner() {
int result = 1;
if((board[0][0]=='x' && board[0][1]=='x' && board[0][2]=='x')||
(board[1][0]=='x' && board[1][1]=='x' && board[1][2]=='x')||
(board[2][0]=='x' && board[2][1]=='x' && board[2][2]=='x')||
(board[0][0]=='x' && board[1][0]=='x' && board[2][0]=='x')||
(board[0][1]=='x' && board[1][1]=='x' && board[2][1]=='x')||
(board[0][2]=='x' && board[1][2]=='x' && board[2][2]=='x')||
(board[0][0]=='x' && board[1][1]=='x' && board[2][2]=='x')||
(board[0][2]=='x' && board[1][1]=='x' && board[2][0]=='x')) {
System.out.println("x win");
result = 0;
}
else if((board[0][0]=='o' && board[0][1]=='o' && board[0][2]=='o')||
(board[1][0]=='o' && board[1][1]=='o' && board[1][2]=='o')||
(board[2][0]=='o' && board[2][1]=='o' && board[2][2]=='o')||
(board[0][0]=='o' && board[1][0]=='o' && board[2][0]=='o')||
(board[0][1]=='o' && board[1][1]=='o' && board[2][1]=='o')||
(board[0][2]=='o' && board[1][2]=='o' && board[2][2]=='o')||
(board[0][0]=='o' && board[1][1]=='o' && board[2][2]=='o')||
(board[0][2]=='o' && board[1][1]=='o' && board[2][0]=='o')) {
System.out.println("o win");
result = 0;
}
return result;
}
public void reinitialize() {
for(int i=0;i<3;i++) {
for(int j=0;j<3;j++) {
board[i][j]=0;
}
}
}
public static void main(String[] args) {
int i,j;
TicTacToe t1 = new TicTacToe();
while(true) {
t1.reinitialize();
for(count = 0; count<10;count++) {
t1.turn();
while(true) {
System.out.println("enter location(i,j<3): ");
Scanner keyboard = new Scanner(System.in);
i = keyboard.nextInt();
j = keyboard.nextInt();
if(i>2 || j>2)
System.out.println("bigger than 2");
else if(board[i][j]!=0)
System.out.println("already in");
else
break;
}
t1.addMove(i, j);
t1.display();
if(t1.winner() == 0)break;
if(count>=8) {
System.out.println("no winner or loser");
break;
}
}
char answer;
System.out.println("again[y/n]?: ");
Scanner keyboard = new Scanner(System.in);
answer = keyboard.next().charAt(0);
if(answer!='y')break;
}
}
}
[java] 상속(Inheritance) 연습문제 (0) | 2021.07.07 |
---|---|
[java] 배열 연습문제 #2 (0) | 2021.07.06 |
[java] 클래스(class) 연습문제 #3 (0) | 2021.07.03 |
[java] 클래스(class) 연습문제 #2 (0) | 2021.06.29 |
[java] 클래스(class) 연습문제 #1 (0) | 2021.06.28 |
댓글 영역