俄罗斯方块源码解析(带下载)[2]

在说源码之前俺 先说说,这个俄罗斯方块的“基本原理”,莫打我哈 ^_^

1首先那个方块是由4个格子组合成的形状, 对吧

2方块有两种情况会 卡住 ,一种是到底了 第二种是 跟其他堆积起来的方块产生“边界接触”。对吧

3方块会自动下落,对吧 如果卡住了 又会在顶上出现新的方块

4下落的过程中可以旋转(空间允许的情况下)

5如果在堆积起来的方块中出现 “一整行联通”的情况,那一行消失 然后上面的下移一行

6如果在空中的时候 卡住了 ,是说明代码有问题 机器硬件有问题 或者人品有问题, 对吧

废话讲完了,我们用什么来实现程序逻辑捏,到现在一句代码没见到。

首先我们把游戏区理解为15X10的矩阵,这个嘛可以用二维数组来表示。

方块理解为 矩阵中的像素,在下落的过程中 我们只需 不停的“擦除像素”,跟“绘制像素”即可

写像素的方式为 改写对应二维数组的值为 true 或者 false

我们要实现游戏逻辑只需在这个基础上实现 即可,就算没有前台显示 实际上游戏逻辑依然在运转。

shape类 部分代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tetris
{
    //方块的形状 四种 三角 长条 四方形 弯角  随机出现(如果不希望出现哪种把对应的注释掉 然后把random的参数改下 即可)
    public class shape
    {
        public bool[,] transform;//方块
        
        public  shape()//初始化操作 返回四种形状任意一种
        {
            transform = new bool[gameArea.height, gameArea.height];

            gameArea.initArea(ref transform);

            int i =  new Random().Next(12);

            switch (i)
            {
                case 0://交错
                    {
                        transform[0, 4] = true;
                        transform[0, 5] = true;
                        transform[1, 4] = true;
                        transform[1, 3] = true;
                        break;
                    }
                case 1://方形
                    {
                        transform[0, 4] = true;
                        transform[0, 5] = true;
                        transform[1, 4] = true;
                        transform[1, 5] = true;
                        break;
                    }
}}}}

gameArea类 负责初始化画布(游戏区域),还负责存放堆积起来的 方块。

gameArea部分代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Tetris
{
    //游戏区域 矩形的 用来存放方块
    public class gameArea
    {
        //容器宽度 默认为10格如果你想换些不一样的玩法^_^调节这个参数即可
        //别忘了把form1里的panel1对应调宽点哦;
        public const int width = 10;
         public const int height = 15;//容器高度 

         public    bool[,] gameAreaArray;

         public gameArea()//初始化游戏区
         {
             gameAreaArray = new bool[height,width];

             for (int i = 0; i < height; i++)
             {
                 for (int j = 0; j < width; j++)
                     gameAreaArray[i,j] = false;
                 
             }
         }

         public static void initArea(ref bool [,] area)//供外部调用的 初始化方法
         {

             for (int i = 0; i < area.GetLength(0); i++)
             {
                 for (int j = 0; j < area.GetLength(1); j++)
                     area[i, j] = false;
             }
         }

       
    }
}

欲知后事如何

请看第三章

原文地址:https://www.cnblogs.com/assassinx/p/1833679.html