消灭星星java控制台版实现
最近喜欢玩消灭星星,打算自己弄一个出来,为了验证可能性,所以先弄了一个控制台版的来测试一下
消灭星星逻辑主要有这几个
- 随机生成星星
- 找到所有与选中的星星相邻且颜色相同的其他星星
- 消去所有相连的星星
- 如消去的星星上方有其他星星,则需要下沉
- 算分
话不多说,直接上代码(注:下面说的坐标是相对于二维数组来说的)
import java.util.*;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
public class Main {
/*
* 1.红色
* 2.蓝色
* 3.黄色
* 4.绿色
* 模拟星星颜色
* */
//定义一个二维数组(主界面)
private int [][] forms ;
//总分
private int totalPoint = 0;
//定义控制台输入变量
static Scanner scanner = new Scanner(System.in);
//定义一个map,临时存放与目标点相连的点
Map<Integer,Integer> map ;
//存放目标点的所有值相同且相连的点的映射集合(对比作用,避免重复存放,死循环)
MultiValueMap<Integer,Integer> totalMap ;
//存放目标点的所有值相同且相连的点
Stack<Map<Integer,Integer>> stack;
//统计相连个数(用来计分)
static int sum =0;
//初始化(不传参数默认是10*10)
public Main(){
forms = new int[10][10];
map = new HashMap<>();
totalMap = new LinkedMultiValueMap<>();
stack = new Stack<>();
for (int i = 0;i<forms.length;i++){
for (int j = 0;j<forms[i].length;j++){
forms[i][j] = (int)(Math.random()*4+1);
}
}
}
//初始化
public Main(int x,int y ){
forms = new int[x][y];
map = new HashMap<>();
totalMap = new LinkedMultiValueMap<>();
stack = new Stack<>();
for (int i = 0;i<forms.length;i++){
for (int j = 0;j<forms[i].length;j++){
forms[i][j] = (int)(Math.random()*4+1);
}
}
}
//判断一个点的相连点的值是否相同
private boolean judgeValue(int[][] arr,int x,int y){
//0不判断,0代表消去的点
if (arr[x][y] == 0)
return false;
//坐标原点
if (x==0 && y==0){
//跟下点比较
if (arr[x][y] == arr[x+1][y]){
if (totalMap.containsKey(x+1)){
if (!judgeMap(x+1,y)){
totalMap.add(x+1,y);
map.put(x+1,y);
stack.push(map);
map = new HashMap<>();
}
}
else {
totalMap.add(x+1,y);
map.put(x+1,y);
stack.push(map);
map = new HashMap<>();
}
}
//跟右点比较
if (arr[x][y] == arr[x][y+1]){
if (totalMap.containsKey(x)){
if (!judgeMap(x,y+1)){
totalMap.add(x,y+1);
map.put(x,y+1);
stack.push(map);
map = new HashMap<>();
}
}
else {
totalMap.add(x,y+1);
map.put(x,y+1);
stack.push(map);
map = new HashMap<>();
}
}
}
//坐标末端点
else if (x==arr.length-1 && y==arr.length-1){
//跟上点比较
if (arr[x][y] == arr[x-1][y]){
if (totalMap.containsKey(x-1)){
if (!judgeMap(x-1,y)){
totalMap.add(x-1,y);
map.put(x-1,y);
stack.push(map);
map = new HashMap<>();
}
}
else {
totalMap.add(x-1,y);
map.put(x-1,y);
stack.push(map);
map = new HashMap<>();
}
}
//跟左点比较
if (arr[x][y] == arr[x][y-1]){
if (totalMap.containsKey(x)){
if (!judgeMap(x,y-1)){
totalMap.add(x,y-1);
map.put(x,y-1);
stack.push(map);
map = new HashMap<>();
}
}
else {
totalMap.add(x,y-1);
map.put(x,y-1);
stack.push(map);
map = new HashMap<>();
}
}
}
//右上端点
else if ( x==0 && y==arr.length-1 ){
if (arr[x][y] == arr[x][y-1]){
if