控制台的五子棋

import java.util.Scanner; public class FiveChess { char[][] chess = new char[16][16]; boolean isBlack = true; public FiveChess() { for (int i = 0; i < chess.length; i++) { for (int j = 0; j < chess[i].length; j++) { chess[i][j] = '*'; } } Scanner s = new Scanner(System.in); printChess(); while (true) { System.out.println("请" + (isBlack ? "黑" : "白") + "方落子:"); String str = s.next(); int r = fromCharToInt(str.charAt(0)); int c = fromCharToInt(str.charAt(1)); if (chess[r][c] != '*') { System.out.println("该位置已经有棋子,请重新输入!"); continue; } else { chess[r][c] = isBlack ? '@' : 'O'; printChess(); if (wasWin(r, c)) { System.out.println((isBlack ? "黑" : "白") + "方获胜!"); break; } } isBlack = !isBlack; } } private char alph(int i) { return (char) ('a' + i - 10); } public void printChess() { for (int i = 0; i < chess.length; i++) { System.out.print(i < 10 ? " " + i : " " + alph(i)); } System.out.println(); for (int i = 0; i < chess.length; i++) { System.out.print(i < 10 ? i + " " : alph(i) + " "); for (int j = 0; j < chess[i].length; j++) { System.out.print(chess[i][j] + " "); } System.out.println(); } } public int fromCharToInt(char c) { return c >= '0' && c <= '9' ? c - '0' : c - 'a' + 10; } public boolean wasWin(int r, int c) { return wasWinAtV(r, c) || wasWinAtH(r, c) || wasWinAtLD(r, c) || wasWinAtRD(r, c); } public boolean wasWinAtV(int r, int c) { char ch = isBlack ? '@' : 'O'; int i = c; while (i >= 0 && chess[r][i] == ch) {// 向左找到第一个不是ch的字符 i--; } int num = 0; i++; while (i < chess.length && chess[r][i] == ch) { num++; i++; } return num >= 5; } public boolean wasWinAtH(int r, int c) { char ch = isBlack ? '@' : 'O'; int i = r; while (i >= 0 && chess[i][c] == ch) {// 向左找到第一个不是ch的字符 i--; } int num = 0; i++; while (i < chess.length && chess[i][c] == ch) { num++; i++; } return num >= 5; } public boolean wasWinAtLD(int r, int c) { char ch = isBlack ? '@' : 'O'; int i = r; int j = c; while (i >= 0 && j < chess.length && chess[i][j] == ch) {// 向左找到第一个不是ch的字符 i--; j++; } int num = 0; i++; j--; while (i < chess.length && j >= 0 && chess[i][j] == ch) { num++; i++; j--; } return num >= 5; } public boolean wasWinAtRD(int r, int c) { char ch = isBlack ? '@' : 'O'; int i = r; int j = c; while (i >= 0 && j >= 0 && chess[i][j] == ch) {// 向左找到第一个不是ch的字符 i--; j--; } int num = 0; i++; j++; while (i < chess.length && j < chess.length && chess[i][j] == ch) { num++; i++; j++; } return num >= 5; } public static void main(String[] args) { new FiveChess(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值