这是一个井字棋游戏的java实现。摘录于stackoverflow。
游戏规则很简单,只要一方棋子在水平线,垂直线或者对角线任意一条线上排列成功即为获胜。
作者原先的代码存在着一些问题:
代码如下:
一共有几个类: play, player, human, computer, set
Play类:
import java.util.Scanner;
public class play {
public static void main(String[] args) {
System.out.println("Welcome to Tickle Tackle Toe!!! :D");
System.out.println();
//creat markers
String marker1 = "x";
String marker2 = "o";
boolean playAgain = true;
Scanner s = new Scanner(System.in);
//create player objects
Human human = new Human();
Computer computer = new Computer();
while(playAgain){
//run board setup
set Setup = new set();
Setup.createBoard();
Setup.printBoard();
System.out.println("please choose your marker");
System.out.println("type 1 for 'x' or 2 for 'o'");
//set markers
if(s.nextInt() == 1){
// create player objects
human.setMarker("x");
computer.setMarker("o");
}
else
{
human.setMarker("o");
computer.setMarker("x");
}
// determine who goes first
int first = (int) (Math.random() * 2);
boolean won = false;
int turns = 0;
if(first == 0){
System.out.println("You go first!");
System.out.println();
while(!won){
human.takeTurn(Setup.getBoard());
turns++;
Setup.printBoard();
if(Setup.hasWon(Setup.getBoard())){
won = true;
System.out.println("Congrats you won!");
}
if(turns == 9){
won = true;
System.out.println("Its a draw!");
break;
}
if(!won){
computer.takeTurn(Setup.getBoard(), human);
turns++;
System.out.println();
Setup.printBoard();
System.out.println();
if(Setup.hasWon(Setup.getBoard())){
won = true;
System.out.println("You lost!");
}
if(turns == 9){
won = true;
System.out.println("Its a draw!");
break;
}
}
} // close while 1
}
else {