TETRIS
大概一年半以前闲着无聊,于是就写了一个俄罗斯方块自娱自乐,程序运行如下图1所示:
图 1
完整的source code可以在这里下载。该程序使用WTL实现的,代码本身非常简单,无非是一些碰撞,变形等情况的判断调整。比较有意思的是程序使用了Factory Method用于创建方块,控制方块的变形。创建方块部分的设计类图如下所示:
Factory的code如下:
/*************************************
* author:hgf_starlovecpp@hotmail.com
* version:1.0
* description: just for fun
* todo: hard code exists need to fixed
**************************************/
#pragma once
#include <map>
#include "Tetris.h"
#include "OneTetris.h"
#include "TwoTetris.h"
#include "ThreeTetris.h"
#include "FourTetris.h"
#include "FiveTetris.h"
#include "SixTetris.h"
#include "SevenTetris.h"
class TetrisFactory
{
public:
TetrisFactory(void)
{
m_sel2TetrisMap[0] = &TetrisFactory::CreateOneTetris;
m_sel2TetrisMap[1] = &TetrisFactory::CreateTwoTetris;
m_sel2TetrisMap[2] = &TetrisFactory::CreateThreeTetris;
m_sel2TetrisMap[3] = &TetrisFactory::CreateFourTetris;
m_sel2TetrisMap[4] = &TetrisFactory::CreateFiveTetris;
m_sel2TetrisMap[5] = &TetrisFactory::CreateSixTetris;
m_sel2TetrisMap[6] = &TetrisFactory::CreateSevenTetris;
}
public:
~TetrisFactory(void)
{
}
Tetris* CreateTetris(char sel)
{
return (this->*(m_sel2TetrisMap.find(sel)->second))();
}
private:
Tetris* CreateOneTetris()
{
static OneTetris tetris;
tetris.InitPos();
return & tetris;
}
Tetris* CreateTwoTetris()
{
static TwoTetris tetris;
tetris.InitPos();
return & tetris;
}
Tetris* CreateThreeTetris()
{
static ThreeTetris tetris;
tetris.InitPos();
return & tetris;
}
Tetris* CreateFourTetris()
{
static FourTetris tetris;
tetris.InitPos();
return & tetris;
}
Tetris* CreateFiveTetris()
{
static FiveTetris tetris;
tetris.InitPos();
return & tetris;
}
Tetris* CreateSixTetris()
{
static SixTetris tetris;
tetris.InitPos();
return & tetris;
}
Tetris* CreateSevenTetris()
{
static SevenTetris tetris;
tetris.InitPos();
return & tetris;
}
private:
typedef Tetris*(TetrisFactory::*PMA)();
std::map<char,PMA> m_sel2TetrisMap;
};
有兴趣的朋友可以下下来改改玩玩。
That’s all!
Peter