package com.titian.bean; import java.awt.CardLayout; import java.awt.Point; public class Grid { char content; boolean state; Point point; public char getContent() { return content; } public void setContent(char content) { this.content = content; } public boolean isState() { return state; } public void setState(boolean state) { this.state = state; } public Point getPoint() { return point; } public void setPoint(Point point) { this.point = point; } }
package com.titian.core; import java.awt.Point; import java.util.Random; import com.titian.bean.Grid; public class Game { Grid[][] grid = new Grid[9][9]; int count = 10; Random r = new Random(); public void addGrid() { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { grid[i][j] = new Grid(); grid[i][j].setContent(' '); grid[i][j].setState(false); grid[i][j].setPoint(new Point(i,j)); } } } public void paint() { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { if(grid[i][j].isState()) { System.out.print(grid[i][j].getContent() + " "); }else { System.out.print("■ "); } } System.out.println(); } } public void setMine() { int i = 0; do { int x = r.nextInt(9); int y = r.nextInt(9); if(grid[x][y].getContent() != '*') { grid[x][y].setContent('*'); i++; } }while(i < count); } public Point[] getPoint(int x, int y) { Point[] point = new Point[8]; point[0] = new Point(x - 1, y); point[1] = new Point(x - 1, y - 1); point[2] = new Point(x, y - 1); point[3] = new Point(x + 1, y - 1); point[4] = new Point(x + 1, y); point[5] = new Point(x + 1, y + 1); point[6] = new Point(x, y + 1); point[7] = new Point(x - 1, y + 1); return point; } public void setNumber() { for (int i = 0; i < grid.length; i++) { for (int j = 0; j < grid[i].length; j++) { int sum = 0; if(grid[i][j].getContent() == '*') { continue; }else { Point[] point = getPoint(i, j); for (int k = 0; k < point.length; k++) { Point p = point[k]; if(p.x >=0 && p.y >= 0 && p.x < 9 && p.y < 9) { if(grid[p.x][p.y].getContent() == '*') { sum++; } } } } if(sum > 0) { grid[i][j].setContent((char)(48 + sum)); } } } } public void stamp(int x, int y) { if(grid[x][y].getContent() == '*') { System.out.println("game over"); }else { grid[x][y].setState(true); if(grid[x][y].getContent() == ' ') { Point[] point = getPoint(x, y); for (int k = 0; k < point.length; k++) { Point p = point[k]; if(p.x >=0 && p.y >= 0 && p.x < 9 && p.y < 9) { if(grid[p.x][p.y].getContent() == ' ' && grid[p.x][p.y].isState() == false) { stamp(p.x,p.y); }else if(grid[p.x][p.y].getContent() != ' ') { grid[p.x][p.y].setState(true); } } } } } } }
package com.titian.test; import java.util.Scanner; import com.titian.core.Game; public class Test1 { public static void main(String[] args) { Game g = new Game(); g.addGrid(); g.setMine(); g.setNumber(); Scanner s = new Scanner(System.in); g.paint(); while(true) { System.out.println("x坐标"); int x = s.nextInt(); System.out.println("y坐标"); int y = s.nextInt(); g.stamp(x, y); g.paint(); } } }