JAVA编程训练——Game: connect four

来源:转载

     Connect four is a two-player board game in which the players alternately drop colored disks into a seven-column, six-row vertically-suspended grid.

     The objective of the game is to connect four same-colored disks in a row, a column, or a diagonal before your opponent can do likewise. The program prompts two players to drop a RED or YELLOW disk alternately. Whenever a disk is dropped, the program redisplays the board on the console and determines the status of the game (win, draw, or continue).


import java.util.Date;import java.util.Scanner;import java.util.Calendar;import javax.swing.JFrame;public class TicIacIoe{ char[][] block={{' ',' ',' ',' ',' ',' ',' '},{' ',' ',' ',' ',' ',' ',' '},{' ',' ',' ',' ',' ',' ',' '},{' ',' ',' ',' ',' ',' ',' '},{' ',' ',' ',' ',' ',' ',' '},{' ',' ',' ',' ',' ',' ',' '}}; TicIacIoe(){} public void show() { for (int i = 0; i < 6; ++i) { for (int j = 0; j < 7; ++j) System.out.print("|" + block[i][j]); System.out.println("|"); } System.out.println("---------------"); } public void playr() { int i=0,j=0; Scanner input = new Scanner(System.in); while(true) { System.out.print("Drop a red disk at column (0-6):"); i=input.nextInt(); if(i>6) System.out.println("Your input is wrong!"); else if(block[0][i]!=' ') System.out.println("This column is full"); else break; } for(j=5;j>=0;--j) { if(block[j][i]==' ') { block[j][i]='R'; break; } } } public void playy() { int i=0,j=0; Scanner input = new Scanner(System.in); while(true) { System.out.print("Drop a yellow disk at column (0-6):"); i=input.nextInt(); if(i>6) System.out.println("Your input is wrong!"); else if(block[0][i]!=' ') System.out.println("This column is full"); else break; } for(j=5;j>=0;--j) { if(block[j][i]==' ') { block[j][i]='Y'; break; } } } public boolean check(char n) { for(int i=0;i<5;++i) for(int j=0;j<6;++j) if(block[i][j]==n&&block[i+1][j]==n&&block[i][j+1]==n&&block[i+1][j+1]==n) return true; return false; } public static void main(String[] args) { TicIacIoe ticIacIoe =new TicIacIoe(); int cnt=0; while(true) { ticIacIoe.show(); ticIacIoe.playr(); ticIacIoe.show(); if(ticIacIoe.check('R')) { System.out.println("The red palyer won"); break; } cnt++; ticIacIoe.playy(); ticIacIoe.show(); if(ticIacIoe.check('Y')) { System.out.println("The yellow palyer won"); break; } cnt++; if(cnt==42) { System.out.println("It is a draw"); break; } } }}



分享给朋友:
您可能感兴趣的文章:
随机阅读: