天天看点

从0开始 Java实习 黑白棋

黑白棋的设计

代码如下:

import java.util.*;
public class Chess{
	char[][] chess = new char[16][16];
	public static void main(String args[])
	{		
		Scanner in = new Scanner(System.in);
		Chess ch = new Chess();
	    ch.init();	
		ch.output();
		int tag = 0;
		int nn = 0;
		while(nn < 225){
			System.out.println("please enter your place to put the chess");
			int x = in.nextInt();
			int y = in.nextInt();
			if(ch.set(x,y,nn) == false)
				continue;
			if(ch.judgeColumn(x,y)==true){
				System.out.println(ch.chess[x][y] + "win");
				tag = 1;
				break;
			}else if(ch.judgeRow(x,y)==true){
				System.out.println(ch.chess[x][y] + "win");
				tag = 1;
				break;
			}else if(ch.judgeLUtoRD(x,y)==true){
				System.out.println(ch.chess[x][y] + "win");
				tag = 1;
				break;
			}else if(ch.judgeRUtoLD(x,y)==true){
				System.out.println(ch.chess[x][y] + "win");
				tag = 1;
			    break;
			}
			else
				nn++;		
		}
		if(tag == 0)
			System.out.println("平局");
		in.close();

	}
	boolean set(int ii, int jj,int nn){
		if(ii <1 || jj > 15 || ii > 15 || jj <1)
			return false;
		else{
			if(chess[ii][jj] == '+'){
				if(nn%2 == 1){
					chess[ii][jj] = '●';
				}else{
					chess[ii][jj] = '○';
				}
				output();
				return true;
			}else{
				System.out.println("you can't put your chess on this place");
				return false;
			}			
		}		
	}
	void init(){
		System.out.println("this is a 15*15 chess ");
		for(int i = 1; i <= 15; i++){
			for(int j = 1 ; j <= 15; j++){
				chess[i][j] = '+';
			}
		}
	}
	void output(){
		for(int i = 1 ; i <= 15; i++){
			for(int j = 1 ; j <= 15; j++){
				System.out.print(chess[i][j] + "  ");
			}
			System.out.println();
		}
		System.out.println();
	}
	//judge column
	boolean judgeColumn(int ii,int jj){
		int i = 1;
		int j = 1; 
		while(ii-i >= 1 && chess[ii-i][jj] == chess[ii][jj]){
			i += 1;
		}
		while(ii+j <= 15 && chess[ii+j][jj] == chess[ii][jj]){
			j += 1;
		}
		if(i+j-1>=5)
			return true;
		else
			return false;
	}
	//judge row
	boolean judgeRow(int pi, int pj){
		int i = 1;
		int j = 1;
		while(pj-i>=1&&chess[pi][pj-i]==chess[pi][pj])
			i+=1;
		while(pj+j<=15&&chess[pi][pj+j]==chess[pi][pj])
			j+=1;
		if(i+j-1 >= 5)
			return true;
		else
			return false;
	}
	//judge from left up to right down
	boolean judgeLUtoRD(int pi, int pj){
		int i = 1;
		int j = 1;
		while(pi+i<=15 && pj-i>=0 && chess[pi+i][pj-i] == chess[pi][pj])
			i+=1;
		while(pi-j>=0 && pj+j <= 15 && chess[pi-j][pj+j] == chess[pi][pj])
			j++;
		if(i+j-1>=5)
			return true;
		else
			return false;		
	}
	//jduge from right up to left down
	boolean judgeRUtoLD(int pi,int pj){
		int i = 1;
		int j = 1;
		while(pi+i <= 15 && pj+i <= 15 && chess[pi+i][pj+i] == chess[pi][pj])
			i+=1;
		while(pi-j >= 0 && pj-j >= 0 && chess[pi-j][pj-j] == chess[pi][pj])
			j+=1;
		if(i+j-1>=5)
			return true;
		else
			return false;
	}
}
           

代码改变世界

下一篇: Shell编程