面向对象版五子棋小游戏

面向对象五子棋版

package com.qf.test;

import java.util.Scanner;

public class Test {

	/**
	 * 知识点:面向对象版五子棋
	 */
	public static void main(String[] args) {
		
		Gobang gobang = new Gobang();
		
		Scanner scan = new Scanner(System.in);
		boolean flag = true;//true-黑子  false-白子
		
		while(true){
			
			//输入坐标
			System.out.println("请" + ((flag)?"黑":"白") + "子输入坐标:");
			int x = scan.nextInt() - 1;//-1是因为用户看到的界面是坐标(从1开始),数组是下标(从0开始)
			int y = scan.nextInt() - 1;//-1是因为用户看到的界面是坐标(从1开始),数组是下标(从0开始)
			
			//落子
			int play = gobang.play(x, y, flag);
			if(play == -1){
				System.out.println("坐标错误 - 坐标超出棋盘范围,请重新输入");
				continue;
			}else if(play == -2){
				System.out.println("坐标错误 - 坐标上已有棋子,请重新输入");
				continue;
			}
			
			//打印棋盘
			gobang.printGobang();
			
			//置反
			flag = !flag;
		}		
	
		
		
	}
}
package com.qf.test;

public class Gobang {

	//棋盘长度
	private int length = 20;
	//棋盘容器
	private String[][] gobang = new String[length][length];
	//棋盘坐标
	private String[] nums = {"⒈","⒉","⒊","⒋","⒌","⒍","⒎","⒏","⒐","⒑","⒒","⒓","⒔","⒕","⒖","⒗","⒘","⒙","⒚","⒛"};
	//棋盘符号
	private String add = "┼";
	private String black = "●";
	private String white = "○";
	
	public Gobang() {
		this.init();
		this.printGobang();
	}
	
	//初始化棋盘
	private void init(){
		for (int i = 0; i < gobang.length; i++) {
			for (int j = 0; j < gobang[i].length; j++) {
				if(j == length-1){//每行的一列,设置行数

					gobang[i][j] = nums[i];
					
				}else if(i == length-1){//最后一行,设置列数
					
					gobang[i][j] = nums[j];
					
				}else{
					gobang[i][j] = add;
				}
			}
		}
	}
	
	//打印棋盘
	public void printGobang(){
		for (String[] strings : gobang) {
			for (String str : strings) {
				System.out.print(str);
			}
			System.out.println();
		}
	}
	
	//判断坐标是否在棋盘内
	public boolean isIndexOutOfGobang(int x,int y){
		if(x<0 || x>length-2 || y<0 || y>length-2){
			return false;
		}
		return true;
	}
	
	//判断坐标上是否有棋子
	public boolean isPiece(int x,int y){
		if(!gobang[x][y].equals(add)){
			return false;
		}
		return true;
	}
	
	//落子
	public int play(int x,int y,boolean flag){
		
		if(!isIndexOutOfGobang(x, y)){
			return -1;
		}
		
		if(!isPiece(x, y)){
			return -2;
		}
		
		String piece = (flag)?black:white;
		gobang[x][y] = piece;
		return 1;
	}
	
}

  • 5
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值