首页 > 试题广场 >

【编程题】 方块消除游戏 题目描述:如下

[问答题]
【编程题】
方块消除游戏


题目描述:如下图,有10*10个不同颜色的方块,每个方块可能是红、绿、蓝、黄、紫5种颜色之一。当点击其中某一个方块时,如果它有相邻的同颜色方块,则将所有与此方块连续同颜色相邻的方块消除;剩下的方块中,如果下方有空位则向下移动,如果左侧整列都为空位则向左移动。

输入:

输入数据有多组,每组占一行,包括一个或多个正整数,取值范围为1~100。每个数代表一次点击,数值为点击的方块编号。

上图中的方块初始值定义已为你写好,可以直接粘贴使用:

const int RED = 0, GREEN = 1, BLUE = 2, YELLOW = 3, PURPLE = 4;

int p[10][10] = {

{RED,RED,BLUE,BLUE,GREEN,YELLOW,BLUE,YELLOW,RED,PURPLE},

{GREEN,GREEN,GREEN,BLUE,RED,PURPLE,RED,YELLOW,YELLOW,BLUE},

{BLUE,RED,RED,YELLOW,YELLOW,PURPLE,BLUE,GREEN,GREEN,BLUE},

{YELLOW,RED,BLUE,YELLOW,BLUE,RED,PURPLE,GREEN,GREEN,RED},

{YELLOW,RED,BLUE,BLUE,PURPLE,GREEN,PURPLE,RED,YELLOW,BLUE},

{PURPLE,YELLOW,RED,RED,YELLOW,RED,PURPLE,YELLOW,RED,RED},

{YELLOW,YELLOW,GREEN,PURPLE,GREEN,RED,BLUE,YELLOW,BLUE,GREEN},

{RED,YELLOW,BLUE,BLUE,YELLOW,GREEN,PURPLE,RED,BLUE,GREEN},

{GREEN,GREEN,YELLOW,YELLOW,RED,RED,PURPLE,BLUE,BLUE,GREEN},

{PURPLE,BLUE,RED,RED,PURPLE,YELLOW,BLUE,RED,RED,GREEN}};

输出:

对于每个测试实例,要求输出连续各次点击全部完成之后,红、绿、蓝、黄、紫色方块的数量;每个测试实例的输出占一行。

样例输入:

6

6 1

样例输出:

26 18 22 21 13

24 18 22 21 13

<!DOCTYPE html> <html lang="en"> <head>  <meta charset="UTF-8">  <meta name="viewport"  content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">  <title>Document</title>  <style>  #game { display: block;  background: #fafafa;  margin: 100px auto;  border: 1px solid #ddd;  } </style> </head> <body> <canvas id="game" height="400" width="400">  Your browser does not support the HTML5 canvas tag. </canvas> <script type="text/javascript">  var obj = [
        ['red', 'red', 'blue', 'blue', 'green', 'yellow', 'blue', 'yellow', 'red', 'purple'],  ['green', 'blue', 'green', 'blue', 'red', 'purple', 'red', 'yellow', 'yellow', 'blue'],  ['blue', 'purple', 'red', 'yellow', 'yellow', 'purple', 'blue', 'green', 'green', 'blue'],  ['yellow', 'yellow', 'blue', 'yellow', 'blue', 'red', 'purple', 'green', 'green', 'red'],  ['yellow', 'green', 'blue', 'blue', 'purple', 'green', 'purple', 'red', 'yellow', 'blue'],  ['purple', 'yellow', 'red', 'red', 'yellow', 'red', 'purple', 'yellow', 'red', 'red'],  ['yellow', 'red', 'green', 'purple', 'green', 'red', 'blue', 'yellow', 'blue', 'green'],  ['red', 'green', 'blue', 'blue', 'yellow', 'green', 'purple', 'red', 'blue', 'green'],  ['green', 'green', 'yellow', 'yellow', 'red', 'red', 'purple', 'blue', 'blue', 'green'],  ['purple', 'red', 'red', 'red', 'purple', 'yellow', 'blue', 'red', 'red', 'green']
    ];  function clickDiamond(x, y) { console.log('click:' + obj[x][y] + ' x:' + x + ' y:' + y);  function up(x, y) {//获取上边方块值  if (x == 0) return false;  return obj[x - 1][y];  } function down(x, y) {//获取下边方块值  if (x == 9) return false;  return obj[x + 1][y];  } function left(x, y) {//获取左边方块值  if (y == 0) return false;  return obj[x][y - 1];  } function right(x, y) {//获取右边方块值  if (y == 9) return false;  return obj[x][y + 1];  } function moveLeft() {//方块整体向左移动  if (x == 9 || x == 8) {//只有点击的是第10行或第9行的方块,才有可能出现左侧列或者右侧列全部空出的情况  var arr = [];  for (var b = 0; b < 10; b++) { if (typeof(obj[9][b]) == 'undefined') {
                        arr.push(b);  }
                } for (var l = 0, len = arr.length; l < len; l++) { //整体左移  var temp;  for (var m = 0; m < 10; m++) { for (var n = arr[l]; n < 10; n++) {
                            temp = obj[m][n];  obj[m][n] = obj[m][n + 1];  obj[m][n + 1] = temp;  }
                        obj[m].length = 10;//补全右侧缺失  }
                }
            }
        } function moveDown() {//方块向下移动  //点击一次 只可能当前点击列和左列和右列出现上下调整  //先取出这三列  var middleCol = [], leftCol = [], rightCol = [];  for (var j = 9; j >= 0; j--) {//当前列  middleCol.push(obj[j][y]);  }
            middleCol = middleCol.filter(function (item) {//剔除undefined  return item !== undefined;  });  middleCol.length = 10;//补全数组  for (j = 0; j < 10; j++) {//还原obj数组  obj[j][y] = middleCol.pop();  } if (y > 0) {//如果有左列  for (j = 9; j >= 0; j--) {//当前列  leftCol.push(obj[j][y - 1]);  }
                leftCol = leftCol.filter(function (item) { return item != undefined;  });  leftCol.length = 10;  for (j = 0; j < 10; j++) {//还原obj数组  obj[j][y - 1] = leftCol.pop();  }
            } if (y < 9) {//如果有右列  for (j = 9; j >= 0; j--) {//当前列  rightCol.push(obj[j][y + 1]);  }
                rightCol = rightCol.filter(function (item) { return item != undefined;  });  rightCol.length = 10;  for (j = 0; j < 10; j++) {//还原obj数组  obj[j][y + 1] = rightCol.pop();  }
            }
        } function clear() {//消除函数  var hasSameColor = false;  if (up(x, y) === obj[x][y]) {//全等 因为false==0  obj[x - 1][y] = undefined;  hasSameColor = true;  } if (down(x, y) === obj[x][y]) {
                obj[x + 1][y] = undefined;  hasSameColor = true;  } if (left(x, y) === obj[x][y]) {
                obj[x][y - 1] = undefined;  hasSameColor = true;  } if (right(x, y) === obj[x][y]) {
                obj[x][y + 1] = undefined;  hasSameColor = true;  } if (hasSameColor == true) {//如果上下左右存在相同色块,消除自己  obj[x][y] = undefined;  //向下移动  moveDown();  //向左移动  moveLeft();  }
        } clear();   var str = obj.join();  var red = str.match(/red/g).length;  var green = str.match(/green/g).length;  var blue = str.match(/blue/g).length;  var yellow = str.match(/yellow/g).length;  var purple = str.match(/purple/g).length;  console.log('当前剩余色块:' + 'red' + red + ' green' + green + ' blue' + blue + ' yellow' + yellow + ' purple' + purple);  } var canvas = document.getElementById('game');  var ctx = canvas.getContext('2d');  ctx.shadowBlur = 10;  ctx.shadowOffsetX = 2;  ctx.shadowOffsetY = 2;  ctx.shadowColor = "black";  function drawDiamond(color, x, y) {//绘制一个方块  ctx.fillStyle = color;  ctx.fillRect(x, y, 40, 40);  } function drawBoard() {//绘制整个画布  for (var x = 0; x < 10; x++) { for (var y = 0; y < 10; y++) { var color = obj[x][y] ? obj[x][y] : 'white';  drawDiamond(color, y * 40, x * 40);  }
        }
    } drawBoard();//首次canvas绘画  canvas.onclick = function (e) {//添加点击事件  var x = e.offsetX;  var y = e.offsetY;  x = Math.ceil(x / 40) - 1;  y = Math.ceil(y / 40) - 1;  clickDiamond(y, x);  drawBoard();  } </script> </body> </html>
发表于 2017-10-25 15:22:06 回复(0)
package test6;

import java.util.ArrayList;
import java.util.Scanner;

public class Main {     final static int RED = 0, GREEN = 1, BLUE = 2, YELLOW = 3, PURPLE = 4;     static int[][] p = { { RED, RED, BLUE, BLUE, GREEN, YELLOW, BLUE, YELLOW, RED, PURPLE },             { GREEN, GREEN, GREEN, BLUE, RED, PURPLE, RED, YELLOW, YELLOW, BLUE },             { BLUE, RED, RED, YELLOW, YELLOW, PURPLE, BLUE, GREEN, GREEN, BLUE },             { YELLOW, RED, BLUE, YELLOW, BLUE, RED, PURPLE, GREEN, GREEN, RED },             { YELLOW, RED, BLUE, BLUE, PURPLE, GREEN, PURPLE, RED, YELLOW, BLUE },             { PURPLE, YELLOW, RED, RED, YELLOW, RED, PURPLE, YELLOW, RED, RED },             { YELLOW, YELLOW, GREEN, PURPLE, GREEN, RED, BLUE, YELLOW, BLUE, GREEN },             { RED, YELLOW, BLUE, BLUE, YELLOW, GREEN, PURPLE, RED, BLUE, GREEN },             { GREEN, GREEN, YELLOW, YELLOW, RED, RED, PURPLE, BLUE, BLUE, GREEN },             { PURPLE, BLUE, RED, RED, PURPLE, YELLOW, BLUE, RED, RED, GREEN } };     static ArrayList<Integer> list = new ArrayList<Integer>();     public static void main(String[] args) {         System.out.println("开始游戏吧");         Main main = new Main();         main.show();         int temp;         int x;         int y;         Scanner in = new Scanner(System.in);         while (in.hasNextInt()) {             temp = in.nextInt() - 1;             x = temp / 10;             y = temp % 10;             main.delete(x, y);             main.move();             main.show();         }     }     public void delete(int x,int y){         int color = p[x][y];         if (color==-1) {             return;         }         p[x][y] = -1;         list.clear();         list.add(x*10+y+1);         if (x!=0) {             if (p[x-1][y]==color&&!list.contains((x-1)*10+y+1)) {                 delete(x-1, y);             }         }         if (y!=9) {             if (p[x][y+1]==color&&!list.contains(x*10+y+2)) {                 delete(x, y+1);             }         }         if (x!=9) {             if (p[x+1][y]==color&&!list.contains((x+1)*10+y+1)) {                 delete(x+1, y);             }         }         if (y!=0) {             if (p[x][y-1]==color&&!list.contains(x*10+y)) {                 delete(x, y-1);             }         }     }     public void move() {         moveToLeft();         moveToDown();     }     public void moveToLeft(){         int a;         for (int i = 0; i < p.length; i++) {             a=0;             while(a<10&&p[a][i]==-1){                 a++;             }             if (a==10) {                 for (int j = 0; j < p.length; j++) {                     for (int j2 = i+1; j2 < p.length; j2++) {                         p[j][j2-1] = p[j][j2];                     }                 }                 for (int j = 0; j < p.length; j++) {                     p[j][9] = -1;                 }             }         }     }     public void moveToDown(){         ArrayList<Integer>arr;         for (int i = 0; i < p.length; i++) {             arr =new ArrayList<Integer>();             for(int j = 9; j >=0;j--){                 if (p[j][i]!=-1) {                     arr.add(p[j][i]);                 }             }             for (int j = 0; j < 16-arr.size(); j++) {                 arr.add(-1);             }             for (int k = 9; k >=0; k--) {                 p[k][i] = arr.get(9-k);             }         }     }     public void show() {         int temp;         for (int i = 0; i < p.length; i++) {             for (int j = 0; j < p.length; j++) {                 temp = p[i][j];                 System.out.print((temp != -1 ? temp : " ") + " ");             }             System.out.println();         }     }
}

发表于 2017-09-25 23:27:47 回复(0)
我牛但不酷
发表于 2017-10-29 16:27:59 回复(0)

package xiaoxiaole;


import java.lang.reflect.Array;

import java.util.Arrays;


public class Xiaoxiaole {


    public static void main(String[] args) {

        int RED = 0, GREEN = 1, BLUE = 2, YELLOW = 3, PURPLE = 4;

        int[][] p = new int[][]{

            {RED,RED,BLUE,BLUE,GREEN,YELLOW,BLUE,YELLOW,RED,PURPLE},

            {GREEN,GREEN,GREEN,BLUE,RED,PURPLE,RED,YELLOW,YELLOW,BLUE},

            {BLUE,RED,RED,YELLOW,YELLOW,PURPLE,BLUE,GREEN,GREEN,BLUE},

            {YELLOW,RED,BLUE,YELLOW,BLUE,RED,PURPLE,GREEN,GREEN,RED},

            {YELLOW,RED,BLUE,BLUE,PURPLE,GREEN,PURPLE,RED,YELLOW,BLUE},

            {PURPLE,YELLOW,RED,RED,YELLOW,RED,PURPLE,YELLOW,RED,RED},

            {YELLOW,YELLOW,GREEN,PURPLE,GREEN,RED,BLUE,YELLOW,BLUE,GREEN},

            {RED,YELLOW,BLUE,BLUE,YELLOW,GREEN,PURPLE,RED,BLUE,GREEN},

            {GREEN,GREEN,YELLOW,YELLOW,RED,RED,PURPLE,BLUE,BLUE,GREEN},

            {PURPLE,BLUE,RED,RED,PURPLE,YELLOW,BLUE,RED,RED,GREEN}};

        operate(p, 6);    

        operate(p, 1);

        

    }

    

    public static void operate(int p[][], int position) {        

        int[] count = new int[5]; //count[0] for number of red...count[4] for number of purple

        for(int i=0; i<p.length; i++) {

            for(int j=0;j<p[i].length;j++) {

                if(p[i][j] == 0) {

                    count[0]++;

                }else if (p[i][j] == 1) {

                    count[1]++;

                }else if (p[i][j] == 2) {

                    count[2]++;

                }else if (p[i][j] == 3) {

                    count[3]++;

                }else if (p[i][j] == 4) {

                    count[4]++;

                }

            }

        }

        

        //get the click position

        int i = (position-1)/10;

        int j = (position-1)%10;

        

        //up, down, left, right to compare

        int count_de_num = 1; // the number to decrease

        if(i!= 0) {

            if(p[i-1][j] == p[i][j]) {

                count_de_num++;

            }

        }

        if(i!= 9) {

            if(p[i+1][j] == p[i][j]) {

                count_de_num++;

            }

        }

        if(j!= 0) {

            if(p[i][j-1] == p[i][j]) {

                count_de_num++;

            }

        }

        if(j!= 9) {

            if(p[i][j+1] == p[i][j]) {

                count_de_num++;

            }

        }

        

        if(count_de_num != 1) {

            if(p[i][j] == 0) {

                count[0] = count[0] - count_de_num;

            }else if (p[i][j] == 1) {

                count[1] = count[1] - count_de_num;

            }else if (p[i][j] == 2) {

                count[2] = count[2] - count_de_num;

            }else if (p[i][j] == 3) {

                count[3] = count[3] - count_de_num;

            }else if (p[i][j] == 4) {

                count[4] = count[4] - count_de_num;

            }

        }

        

        System.out.println(Arrays.toString(count));

    }


}


发表于 2019-04-01 20:00:56 回复(1)
#include<iostream>
using namespace std;
int main()
{
    
}

发表于 2018-07-13 16:04:06 回复(0)
我题目都看不懂,谁能解释一下。
发表于 2020-03-15 22:54:03 回复(0)
import java.util.Arrays;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
import java.util.Set;
import java.util.TreeMap;

import org.omg.PortableInterceptor.INACTIVE;

public class Main{
    public static final int RED = 0, GREEN = 1, BLUE = 2, YELLOW = 3, PURPLE = 4;
    public static void input(){
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int[][] p = init();
            String s = sc.nextLine();
            String[] ss = s.split(" ");
            
            int[] result = getResult(p);
            for(int i=0;i<ss.length;i++){
                int position = Integer.parseInt(ss[i]);
                int row = position/10;
                int col = position%10-1;
                if(col<0){
                    col=9;
                    row = row-1;
                }
                int num = p[row][col];
                int length = 0;
                Map<Integer, LinkedList<Integer>> map = new TreeMap<>();
                method(map, row, col, p);
                if(!map.isEmpty()){//要清除
                    p[row][col]=-1;
                    Set<Integer> set = map.keySet();
                    Iterator<Integer> itr = set.iterator();
                    while (itr.hasNext()) {
                        int col1 = itr.next();
                        LinkedList<Integer> list = map.get(col1);
                        Collections.sort(list);
                        int last = list.getLast();
                        for(int j=last;j>=0;j--){
                            int k=j;
                            int n =j;
                            int count=0;
                            while(p[k][col1]==-1&&k>0){
                                k--;
                                count++;
                            }
                            if(count!=0){
                                for(int jj=last-count;jj>=0;jj--){
                                    p[n--][col1] = p[jj][col1];
                                }
                            }
                        }
                    }
                    while (itr.hasNext()) {
                        length += map.get(itr).size();
                    }
                    result[num]-=length;
                }
            }
            for(int iii=0;iii<result.length;iii++){
                if(iii==result.length-1){
                    System.out.println(result[iii]);
                }else {
                    System.out.print(result[iii]);
                    System.out.print(" ");
                }
            }
            
        }
    }
    
    //处理函数
    private static void  method(Map<Integer, LinkedList<Integer>> map,int row,int col,int[][] p){
        int num = p[row][col];
        if(num==up(row, col, p)){
            row--;
            p[row][col] =-1;
            if(map.containsKey(col)){
                LinkedList<Integer> list = map.get(col);
                list.add(row);
                map.put(col, list);
            }else {
                LinkedList<Integer> list = new LinkedList<>();
                list.add(row);
                map.put(col, list);
            }
            method(map, row, col, p);
        }
        if(num==down(row, col, p)){
            row++;
            p[row][col] =-1;
            if(map.containsKey(col)){
                LinkedList<Integer> list = map.get(col);
                list.add(row);
                map.put(col, list);
            }else {
                LinkedList<Integer> list = new LinkedList<>();
                list.add(row);
                map.put(col, list);
            }
            method(map, row, col, p);
        }
        if(num==left(row, col, p)){
            col--;
            p[row][col] =-1;
            if(map.containsKey(col)){
                LinkedList<Integer> list = map.get(col);
                list.add(row);
                map.put(col, list);
            }else {
                LinkedList<Integer> list = new LinkedList<>();
                list.add(row);
                map.put(col, list);
            }
            method(map, row, col, p);
        }
        if(num == right(row, col, p)){
            col++;
            p[row][col] =-1;
            if(map.containsKey(col)){
                LinkedList<Integer> list = map.get(col);
                list.add(row);
                map.put(col, list);
            }else {
                LinkedList<Integer> list = new LinkedList<>();
                list.add(row);
                map.put(col, list);
            }
            method(map, row, col, p);
        }
    }
    
    private static int[] getResult(int[][] p){
        
        int[] result = new int[5];
        for(int i=0;i<p.length;i++){
            for(int j=0;j<p[0].length;j++){
                if(p[i][j]==RED){
                    result[0]++;
                }else if (p[i][j]==GREEN) {
                    result[1]++;
                }else if (p[i][j]==BLUE) {
                    result[2]++;
                }else if (p[i][j]==YELLOW) {
                    result[3]++;
                }else if (p[i][j]==PURPLE) {
                    result[4]++;
                }
            }
        }
        return result;
    }
    private static int[][] init(){
        int p[][] = {

                {RED,RED,BLUE,BLUE,GREEN,YELLOW,BLUE,YELLOW,RED,PURPLE},

                {GREEN,GREEN,GREEN,BLUE,RED,PURPLE,RED,YELLOW,YELLOW,BLUE},

                {BLUE,RED,RED,YELLOW,YELLOW,PURPLE,BLUE,GREEN,GREEN,BLUE},

                {YELLOW,RED,BLUE,YELLOW,BLUE,RED,PURPLE,GREEN,GREEN,RED},

                {YELLOW,RED,BLUE,BLUE,PURPLE,GREEN,PURPLE,RED,YELLOW,BLUE},

                {PURPLE,YELLOW,RED,RED,YELLOW,RED,PURPLE,YELLOW,RED,RED},

                {YELLOW,YELLOW,GREEN,PURPLE,GREEN,RED,BLUE,YELLOW,BLUE,GREEN},

                {RED,YELLOW,BLUE,BLUE,YELLOW,GREEN,PURPLE,RED,BLUE,GREEN},

                {GREEN,GREEN,YELLOW,YELLOW,RED,RED,PURPLE,BLUE,BLUE,GREEN},

                {PURPLE,BLUE,RED,RED,PURPLE,YELLOW,BLUE,RED,RED,GREEN}};
        return p;
    }
    public static  int left(int row,int col,int[][] p){
        
        if(col>0){
            col--;
            return p[row][col];
        }else {
            return -2;
        }
    }
    
    public static  int right(int row,int col,int[][] p){
    
        if(col<p[0].length-1){
            col++;
            return p[row][col];
        }else {
            return -2;
        }
    }
    public static  int down(int row,int col,int[][] p){
        if(row<p.length-1){
            row++;
            return p[row][col];
        }else {
            return -2;
        }
    }
    public static int up(int row,int col,int[][] p){
        if(row>0){
            row--;
            return p[row][col];
        }else {
            return -2;
        }
    }
    public static void main(String[] args) {
        input();
    }
}

发表于 2018-04-27 10:20:57 回复(0)
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Software: PyCharm

import Queue,copy

global mp,dx,dy
dx = [-1,1,0,0]
dy = [0,0,1,-1]
mp = [
[0,0,2,2,1,3,2,3,0,4],
[1,1,1,2,0,4,0,3,3,2],
[2,0,0,3,3,4,2,1,1,2],
[3,0,2,3,2,0,4,1,1,0],
[3,0,2,2,4,1,4,0,3,2],
[4,3,0,0,3,0,4,3,0,0],
[3,3,1,4,1,0,2,3,2,1],
[0,3,2,2,3,1,4,0,2,1],
[1,1,3,3,0,0,4,2,2,1],
[4,2,0,0,4,3,2,0,0,1]
]
#bfs搜索同色
def bfs(beg):
    global mp,dx,dy
    q = Queue.Queue(maxsize=0)
    x = beg / 10
    y = (beg - 1) % 10
    block_color = mp[x][y]
    if block_color == -1:
        return False
    q.put((x,y))
    cnt = 0
    while q.qsize():
        x , y = q.get()
        for i in range(4):
            s = dx[i] + x
            t = dy[i] + y
            if s < 0 or s > 9 or t < 0 or t > 9 or mp[s][t] !=block_color:
                continue
            cnt += 1
            mp[s][t] = -1
            q.put((s,t))
    if cnt == 1:
        mp[beg/10][(beg - 1)%10] = block_color
        return False
    return True
#紧凑map
def merge_map():
    tmp_mp = [[-1 for i in range(10)] for j in range(10)]
    global mp
    for i in range(10):
        cnt = 0
        for j in range(10):
            if mp[j][i] == -1:
                cnt += 1
        if cnt != 10:
            for j in range(10):
                tmp_mp[j][i] = mp[j][i]
    mp = copy.deepcopy(tmp_mp)
    #print(tmp_mp)
#统计最终数量
def calc_block_num():
    red = 0
    green = 0
    blue = 0
    yellow = 0
    purple = 0
    for i in range(10):
        for j in range(10):
            if mp[i][j] == 0:
                red += 1
            elif mp[i][j] == 1:
                green += 1
            elif mp[i][j] == 2:
                blue += 1
            elif mp[i][j] == 3:
                yellow += 1
            elif mp[i][j] == 4:
                purple += 1
    print(str(red) + ' ' + str(green) + ' ' + str(blue) + ' ' + str(yellow) + ' ' + str(purple))
actions = map(str,raw_input())
for action in actions:
    if action !=' ':
        if bfs(int(action)):
            merge_map()
calc_block_num()
编辑于 2017-12-10 11:43:10 回复(2)