[java]代码库
package homework;
import java.util.ArrayList;
import java.util.Scanner;
public class 井字游戏{
//构建棋盘
static ArrayList bulidLine(int n){
ArrayList line = new ArrayList();
for(int i =0;i<2*n+1;i++)
line.add("-");
return line;
}
static ArrayList bulidBlanks(int n){
ArrayList blanks= new ArrayList();
for(int i=0;i<n;i++){
blanks.add("|");
blanks.add(" ");
}
blanks.add("|");
return blanks;
}
static ArrayList bulidPlaste(int n){
ArrayList plate = new ArrayList();
for (int i =0;i<n;i++){
plate.add(bulidLine(n));
plate.add(bulidBlanks(n));
}
plate.add(bulidLine(n));
return plate;
}
static void show(ArrayList plate){
for (int i = 0;i<plate.size();i++){
ArrayList row=(ArrayList)plate.get(i);
for(int j=0;j<row.size();j++)
System.out.print(row.get(j));
System.out.println();
}
}
//下棋
static boolean drop(ArrayList plate,int r,int c,String piece) {
r = 2 * r - 1;
c = 2 * c - 1;
ArrayList row = (ArrayList) plate.get(r);
if (row.get(c) == " "){
row.set(c, piece);
return true;
}
return false;
}
//判定胜负
public static boolean judge(ArrayList plate,int n,String piece){
//判断行
int r;
int count;
for(r=1;r<2*n+1;r+=2) {
//判断行
count=0;
ArrayList row = (ArrayList) plate.get(r);
for (int j = 1; j < 2 * n + 1; j += 2) {
if (row.get(j) == piece) {
count += 1;
if (count == n)
return true;
}
}
}
//判断列
for(int i=1;i<2*n+1;i+=2){
count=0;
ArrayList row=(ArrayList)plate.get(i);
for(int j=1;j<2*n+1;j+=2) {
if (row.get(j) == piece) {
count += 1;
if (count == n)
return true;
}
}
}
//判断捺
for(int i=1;i<2*n+1;i+=2){
count=0;
ArrayList row=(ArrayList)plate.get(i);
if (row.get(i)==piece){
count+=1;
if (count==n)
return true;
}
}
//判断撇
for (int i= 2*n-1;i>0;i-=2){
count=0;
ArrayList row=(ArrayList)plate.get(i);
if(row.get(i)==piece){
count+=1;
if(count==n)
return true;
}
}
return false;
}
public static void main(String[] args) {
Scanner reader = new Scanner(System.in);
System.out.println("输入棋盘阶数");
int n=reader.nextInt();
ArrayList plate= bulidPlaste(n);
show(plate);
String piece = "x";
int s=0;
while (true) {
System.out.println("请输入落子的行号");
int row = reader.nextInt();
System.out.println("请输入落子的列号");
int col = reader.nextInt();
if (!drop(plate, row, col, piece)){
System.out.println("该处已有棋子,重新落子");
continue;
}
s++;
if(s==n*n){
if(judge(plate,n,piece)){
System.out.println(piece+" win");
break;
}
else
System.out.println("平局");
break;
}
show(plate);
if(judge(plate,n,piece)){
System.out.println(piece+" win");
break;
}
piece=piece=="x"?"o":"x";
}
}
}
[代码运行效果截图]