VC++ 6.0 MFC 俄罗斯方块 自动求解 代码 源程序
vc6.0中用MFC编写计算器代码
// CKcalculateDlg.cpp : implementation file//#include "stdafx.h"#include "math.h"#include "CKcalculate.h"#include "CKcalculateDlg.h"#ifdef _DEBUG#define new DEBUG_NEW#undef THIS_FILEstatic char THIS_FILE[] = __FILE__;#endif// double m_first; //存储一次运算的第一个操作数及一次运算的结果// double m_second; //存储一次运算的第二个操作数// CString m_operator; //存储运算符// double m_coff; //存储小数点的系数权值/////////////////////////////////////////////////////////////////////////////// CAboutDlg dialog used for App About/////////////////////////////////////////////////////////////////////////////class CAboutDlg : public CDialog{public:CAboutDlg();// Dialog Data//{{AFX_DATA(CAboutDlg)enum { IDD = IDD_ABOUTBOX };//}}AFX_DATA// ClassWizard generated virtual function overrides//{{AFX_VIRTUAL(CAboutDlg)protected:virtual void DoDataExchange(CDataExchange* pDX);// DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected://{{AFX_MSG(CAboutDlg)//}}AFX_MSGDECLARE_MESSAGE_MAP()};CAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD){//{{AFX_DATA_INIT(CAboutDlg)//}}AFX_DATA_INIT}void CAboutDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CAboutDlg)//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CAboutDlg, CDialog)//{{AFX_MSG_MAP(CAboutDlg)// No message handlers//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CCKcalculateDlg dialogCCKcalculateDlg::CCKcalculateDlg(CWnd* pParent /*=NULL*/) : CDialog(CCKcalculateDlg::IDD, pParent){// void UpdateDisplay(double);// void Calculate(void);//{{AFX_DATA_INIT(CCKcalculateDlg)/////////////////////////////////////////////////////////////////////////////////////////////////// //isXdeY=false;m_display = _T("");m_PI=3.14159265358979323846;m_first=0.0;m_second=0.0;m_operator=_T("+");m_coff=0;m_display=_T("0.0");//}}AFX_DATA_INIT// Note that LoadIcon does not require a subsequent DestroyIcon in Win32m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}void CCKcalculateDlg::DoDataExchange(CDataExchange* pDX){CDialog::DoDataExchange(pDX);//{{AFX_DATA_MAP(CCKcalculateDlg)DDX_Text(pDX, IDC_DISPLAY, m_display);//}}AFX_DATA_MAP}BEGIN_MESSAGE_MAP(CCKcalculateDlg, CDialog)//{{AFX_MSG_MAP(CCKcalculateDlg)ON_WM_SYSCOMMAND()ON_WM_PAINT()ON_WM_QUERYDRAGICON()ON_BN_CLICKED(IDC_BUTTON0, OnButton0)ON_BN_CLICKED(IDC_BUTTON1, OnButton1)ON_BN_CLICKED(IDC_BUTTON2, OnButton2)ON_BN_CLICKED(IDC_BUTTON3, OnButton3)ON_BN_CLICKED(IDC_BUTTON4, OnButton4)ON_BN_CLICKED(IDC_BUTTON5, OnButton5)ON_BN_CLICKED(IDC_BUTTON6, OnButton6)ON_BN_CLICKED(IDC_BUTTON7, OnButton7)ON_BN_CLICKED(IDC_BUTTON8, OnButton8)ON_BN_CLICKED(IDC_BUTTON9, OnButton9)ON_BN_CLICKED(IDC_BUTTON_ADD, OnButtonAdd)ON_BN_CLICKED(IDC_BUTTON_MINUS, OnButtonMinus)ON_BN_CLICKED(IDC_BUTTON_MUTIPL Y, OnButtonMutiply) ON_BN_CLICKED(IDC_BUTTON_DIV, OnButtonDiv)ON_BN_CLICKED(IDC_BUTTON_SIGH, OnButtonSigh)ON_BN_CLICKED(IDC_BUTTON_POINT, OnButtonPoint)ON_BN_CLICKED(IDC_BUTTON_CLEAR, OnButtonClear)ON_BN_CLICKED(IDC_BUTTON_SQRT, OnButtonSqrt)ON_BN_CLICKED(IDC_BUTTON_RECI, OnButtonReci)ON_BN_CLICKED(IDC_BUTTON_EQUAL, OnButtonEqual)ON_BN_CLICKED(IDC_BUTTON_SIN, OnButtonSin)ON_BN_CLICKED(IDC_BUTTON_COS, OnButtonCos)ON_BN_CLICKED(IDC_BUTTON_LOG, OnButtonLog)ON_BN_CLICKED(IDC_BUTTON_XDEY, OnButtonXdeY)//}}AFX_MSG_MAPEND_MESSAGE_MAP()/////////////////////////////////////////////////////////////////////////////// CCKcalculateDlg message handlers/////////////////////////////////////////////////////////////////////////////BOOL CCKcalculateDlg::OnInitDialog(){CDialog::OnInitDialog();// Add "About..." menu item to system menu.// IDM_ABOUTBOX must be in the system command range.ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);ASSERT(IDM_ABOUTBOX < 0xF000);CMenu* pSysMenu = GetSystemMenu(FALSE);if (pSysMenu != NULL){CString strAboutMenu;strAboutMenu.LoadString(IDS_ABOUTBOX);if (!strAboutMenu.IsEmpty()){pSysMenu->AppendMenu(MF_SEPARATOR);pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);}}// Set the icon for this dialog. The framework does this automatically// when the application's main window is not aSetIcon(m_hIcon, TRUE); // Set big iconSetIcon(m_hIcon, FALSE); // Set small icon// TODO: Add extra initialization herereturn TRUE;// return TRUE unless you set the focus to a control}void CCKcalculateDlg::OnSysCommand(UINT nID, LPARAM lParam){if ((nID & 0xFFF0) == IDM_ABOUTBOX){CAboutDlg dlgAbout;dlgAbout.DoModal();}else{CDialog::OnSysCommand(nID, lParam);}}// If you add a minimize button to your dialog, you will need the code below// to draw the icon. For MFC applications using the document/view model,// this is automatically done for you by the framework.void CCKcalculateDlg::OnPaint(){if (IsIconic()){CPaintDC dc(this); // device context for paintingSendMessage(WM_ICONERASEBKGND, (WPARAM) dc.GetSafeHdc(), 0);// Center icon in client rectangleint cxIcon = GetSystemMetrics(SM_CXICON);int cyIcon = GetSystemMetrics(SM_CYICON);CRect rect;GetClientRect(&rect);int x = (rect.Width() - cxIcon + 1) / 2;int y = (rect.Height() - cyIcon + 1) / 2;// Draw the icondc.DrawIcon(x, y, m_hIcon);}else{CDialog::OnPaint();}}// The system calls this to obtain the cursor to display while the user drags// the minimized window.HCURSOR CCKcalculateDlg::OnQueryDragIcon(){return (HCURSOR) m_hIcon;}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////按键代码//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////void CCKcalculateDlg::OnButton0(){// TODO: Add your control notification handler code hereonButtonN(0);}void CCKcalculateDlg::OnButton1(){// TODO: Add your control notification handler code hereonButtonN(1);}void CCKcalculateDlg::OnButton2(){// TODO: Add your control notification handler code hereonButtonN(2);}void CCKcalculateDlg::OnButton3(){// TODO: Add your control notification handler code hereonButtonN(3);}void CCKcalculateDlg::OnButton4(){// TODO: Add your control notification handler code hereonButtonN(4);}void CCKcalculateDlg::OnButton5(){// TODO: Add your control notification handler code hereonButtonN(5);}void CCKcalculateDlg::OnButton6(){// TODO: Add your control notification handler code hereonButtonN(6);}void CCKcalculateDlg::OnButton7(){// TODO: Add your control notification handler code hereonButtonN(7);}void CCKcalculateDlg::OnButton8(){// TODO: Add your control notification handler code hereonButtonN(8);}void CCKcalculateDlg::OnButton9(){// TODO: Add your control notification handler code hereonButtonN(9);}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////计算按键代码//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////void CCKcalculateDlg::OnButtonAdd(){// TODO: Add your control notification handler code here Calculate();m_operator="+";}void CCKcalculateDlg::OnButtonMinus(){// TODO: Add your control notification handler code here Calculate();m_operator="-";}void CCKcalculateDlg::OnButtonMutiply(){// TODO: Add your control notification handler code here Calculate();m_operator="*";}void CCKcalculateDlg::OnButtonDiv(){// TODO: Add your control notification handler code here Calculate();m_operator="/";}void CCKcalculateDlg::OnButtonSigh(){// TODO: Add your control notification handler code here m_second=-m_second;UpdateDisplay(m_second);}void CCKcalculateDlg::OnButtonPoint(){// TODO: Add your control notification handler code here m_coff =0.1;}void CCKcalculateDlg::OnButtonClear(){// TODO: Add your control notification handler code here m_first=0.0;m_second=0.0;m_operator="+";m_coff = 1.0;UpdateDisplay(0.0);}void CCKcalculateDlg::OnButtonSqrt(){// TODO: Add your control notification handler code here if( m_second==0 ){m_first=sqrt(m_first);UpdateDisplay(m_first);}else{m_second=sqrt(m_second);UpdateDisplay(m_second);}}void CCKcalculateDlg::OnButtonReci(){// TODO: Add your control notification handler code here if( fabs(m_second ) < 0.000001 && fabs( m_first )<0.000001) {m_display="除数不能为零";UpdateDisplay(false);return;}if( fabs(m_second ) < 0.000001){m_first=1.0/m_first;UpdateDisplay(m_first);}else{m_second=1.0/m_second;UpdateDisplay(m_second);}}void CCKcalculateDlg::OnButtonEqual(){// TODO: Add your control notification handler code hereXdeY();Calculate();}void CCKcalculateDlg::UpdateDisplay(double ck){m_display.Format(_T("%f"),ck);int i=m_display.GetLength();//格式化输出,将输出结果后的零截去while(m_display.GetAt(i-1)=='0'){m_display.Delete(i-1,1);i--;}//更新编辑框变量m_displayUpdateData(false);}void CCKcalculateDlg::Calculate(void){//将前一次数据与当前数据进行运算,作为下次的第一操作数,并在编辑框显示switch(m_operator.GetAt(0)){case '+': m_first+=m_second;break;case '-': m_first-=m_second;break;case '*': m_first*=m_second;break;case '/':if( fabs(m_second ) <= 0.000001){m_display="除数不能为0";UpdateData(false);return;}m_first/=m_second;break;}m_second=0.0;m_coff=1.0;m_operator=_T("+");//更新编辑框显示内容UpdateDisplay(m_first);}void CCKcalculateDlg::onButtonN(int n){if(m_coff==1.0)//作为整数输入数字时m_second=m_second*10+n;else{//作为小数输入数字m_second=m_second+n*m_coff;m_coff*=0.1;}//更新编辑框的数字显示UpdateDisplay(m_second);}void CCKcalculateDlg::OnButtonSin(){// TODO: Add your control notification handler code here m_second=m_second*m_PI/180;m_second=sin(m_second);UpdateDisplay(m_second);}void CCKcalculateDlg::OnButtonCos(){// TODO: Add your control notification handler code here m_second=m_second*m_PI/180;m_second=cos(m_second);UpdateDisplay(m_second);}void CCKcalculateDlg::OnButtonLog(){// TODO: Add your control notification handler code here m_second=log10(m_second);UpdateDisplay(m_second);}void CCKcalculateDlg::OnButtonXdeY(){// TODO: Add your control notification handler code here temp=m_second;m_second=0.0;UpdateDisplay(m_second);isXdeY=true;}void CCKcalculateDlg::XdeY(){if(isXdeY){m_second=m_second;m_second=pow(temp,m_second);}}////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// ////////////以下是CKcalculateDlg.h代码// /////////CKcalculateDlg.h : header file//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////#if !defined(AFX_CKCALCULATEDLG_H__8DEB211E_CFCF_44C8_895C_BEF4E77EBE6C __INCLUDED_)#defineAFX_CKCALCULATEDLG_H__8DEB211E_CFCF_44C8_895C_BEF4E77EBE6C__INCLUD ED_#if _MSC_VER > 1000#pragma once#endif // _MSC_VER > 1000/////////////////////////////////////////////////////////////////////////////// CCKcalculateDlg dialogclass CCKcalculateDlg : public CDialog{// Constructionpublic:void XdeY(void);bool isXdeY;double temp;double m_PI;void onButtonN(int n);void UpdateDisplay(double ck);void Calculate();CCKcalculateDlg(CWnd* pParent = NULL); // standard constructor// Dialog Data//{{AFX_DATA(CCKcalculateDlg)enum { IDD = IDD_CKCALCULATE_DIALOG };CString m_display;//}}AFX_DATAdouble m_first;//存储一次运算的第一个操作数及一次运算的结果double m_second;//存储一次运算的第二个操作数CString m_operator;//存储运算符double m_coff;//存储小数点的系数权值// ClassWizard generated virtual function overrides// {{AFX_VIRTUAL(CCKcalculateDlg)protected:virtual void DoDataExchange(CDataExchange* pDX);// DDX/DDV support//}}AFX_VIRTUAL// Implementationprotected:HICON m_hIcon;// Generated message map functions//{{AFX_MSG(CCKcalculateDlg)virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg void OnButton0();afx_msg void OnButton1();afx_msg void OnButton2();afx_msg void OnButton3();afx_msg void OnButton4();afx_msg void OnButton5();afx_msg void OnButton6();afx_msg void OnButton7();afx_msg void OnButton8();afx_msg void OnButton9();afx_msg void OnButtonAdd();afx_msg void OnButtonMinus();afx_msg void OnButtonMutiply();afx_msg void OnButtonDiv();afx_msg void OnButtonSigh();afx_msg void OnButtonPoint();afx_msg void OnButtonClear();afx_msg void OnButtonSqrt();afx_msg void OnButtonReci();afx_msg void OnButtonEqual();afx_msg void OnButtonSin();afx_msg void OnButtonCos();afx_msg void OnButtonLog();afx_msg void OnButtonXdeY();//}}AFX_MSGDECLARE_MESSAGE_MAP()};//{{AFX_INSERT_LOCA TION}}// Microsoft Visual C++ will insert additional declarations immediately before the previous line.#endif// !defined(AFX_CKCALCULATEDLG_H__8DEB211E_CFCF_44C8_895C_BEF4E77EBE6C_ _INCLUDED_)。
VC++6.0俄罗斯方块代码
俄罗斯方块是我大学一年级刚学VC++时的课程设计,当时的课程设计有三种,单文档、多文档和俄罗斯方块。
我选择俄罗斯方块,就是因为它是游戏。
之前我是玩过俄罗斯方块的,一种是单人的(单人版),一种是两人对战的(对战版),还有一种是网络版的,由于我还不了解网络,所以就决定编前两种。
可是,这样没有新意,我就想到了另外一种,配合游戏,或者称为情侣版。
这里我先介绍三种,而网络版,由于我们将介绍五子棋的网络游戏,鉴于它的简单性,我们将不介绍。
说明:以下三部分,可以以三章看待。
一、单人版1、游戏实现俄罗斯方块,或称积木游戏,它是利用一些形状各异却又是用正方形组成的方块,经过不同位置不同角度的变化之后,堆积在一起的一种智力游戏。
而从我们编程的角度讲,我们只需要提供各种方块的图形,提供几个键盘操作键以供方块的形状和位置的变化,提供几个功能函数以供游戏的正常进行。
各种方块图形:利用数组定形,然后利用随机函数随机地不按顺序地按游戏的需要而出现。
键盘操作键:就是四个方向键。
其中左、右、下三个键意思一样,上键的功能不是使方块向上,而是使方块的下落角度改变。
功能函数将在变量函数里面介绍。
新建单文档工程4_1。
2、资源编辑封面: IDB_BITMAP1背景: IDB_BITMAP2方块: IDB_BITMAP3添加菜单:开始: ID_MENU_START3、变量函数接着就是定义变量了,但是,由于这个游戏要添加的变量和函数太多了,我们要建一个新类。
是否应该先添加应该类呢?最好是这样。
因为新类将会涉及到变量。
添加普通类Crussia,见下图。
图4-1-1添加变量函数:由于两个类一共有很多变量函数,列举如下:// 4_1View.h ://俄罗斯类CRussia russia;//开始标志bool start;//封面CBitmap fenmian;//暂停BOOL m_bPause;//开始菜单afx_msg void OnMenuStart();//计时器afx_msg void OnTimer(UINT nIDEvent);//键盘操作afx_msg void OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags); // Russia.h://游戏数组int Russia[100][100];// 当前图形int Now[4][4];//上一图形int Will[4][4];//变换后的图形int After[4][4];//当前图形的左上角位置CPoint NowPosition; //当前可能出现的图形形状数,int Count; //游戏结束bool end;//级别int m_Level;//速度int m_Speed;//分数int m_Score;//行列数int m_RowCount,m_ColCount; //方块CBitmap fangkuai;//背景CBitmap jiemian;//显示分数等内容void DrawScore(CDC*pDC);//消行void LineDelete();//方块移动void Move(int direction);//方块变化,即方向键上键操作bool Change(int a[][4],CPoint p,int b[][100]); //是否与原来方块接触,或与边界接触bool Meet(int a[][4],int direction,CPoint p); //显示下一个方块void DrawWill();//显示界面void DrawJiemian(CDC*pDC);//开始void Start();4、具体实现然后,我们就可以一步一步地实现游戏了。
俄罗斯方块c语言源代码
俄罗斯方块c语言源代码俄罗斯方块游戏是一款非常受欢迎的游戏,使用C语言编写源代码实现其功能。
下面是俄罗斯方块游戏的C语言源代码:1. 创建窗口函数: // 创建窗口函数 void CreateWindow(int width, int height) { // 使用SDL库创建窗口 SDL_Init(SDL_INIT_EVERYTHING); SDL_Window *window = SDL_CreateWindow("Tetris",SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,width, height, 0); // 设置刷新时间SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1"); }2. 创建游戏函数: // 创建游戏函数 void CreateGame() { // 设置随机数种子srand((unsigned int)time(NULL)); // 加载游戏资源 LoadResources(); // 初始化游戏数据InitGameData(); // 初始化游戏界面InitGameUI(); // 开始游戏循环 GameLoop(); // 清理游戏资源 CleanupGame(); }3. 绘图函数: // 绘图函数 void Draw(int x, inty, Color color) { // 使用SDL库在指定位置绘制指定颜色的矩形 SDL_Rect rect; rect.x = x;rect.y = y; rect.w = BLOCK_SIZE; rect.h = BLOCK_SIZE; SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);SDL_RenderFillRect(renderer, &rect); }。
俄罗斯方块源代码
C语言俄罗斯方块源代码Vc6.0编译通过#include<windows.h>#include<stdio.h>#include<time.h>#include<stdlib.h>#include<malloc.h>#include<conio.h>#define MAP_WIDTH10#define MAP_HEIGHT20#define BLOCKM"■"#define BKBLOCK"□"#define OUTSTD GetStdHandle(STD_OUTPUT_HANDLE)typedef int(*PFUN)(void *pData);void ShowMapArray(int map[MAP_HEIGHT][MAP_WIDTH]);//生成方块int xyIsInarrBlock(int arrBlock[4][2], int x, int y) //有返回1 没有返回0 {int i;for (i = 0;i<4;i++)if (arrBlock[i][0] == x && arrBlock[i][1] == y)return 1;return 0;}void GetTransBlocks(int arrBlock[4][2])//坐标模式4*4方块{int nTmp, x, y;int nCount = 1;int i;int nMinx = 0, nMiny = 0;memset(arrBlock, 0, 8 * sizeof(int));while (nCount < 4){nTmp = rand() % nCount;x = arrBlock[nTmp][0];y = arrBlock[nTmp][1];nTmp = rand() % 4;switch (nTmp){case 0:x--;break;case 1:y--;break;case 2:x++;break;case 3:y++;break;}if (xyIsInarrBlock(arrBlock, x, y))continue;arrBlock[nCount][0] = x;arrBlock[nCount][1] = y;if (nMinx > x)nMinx = x;if (nMiny > y)nMiny = y;nCount++;}for (i = 0;i<4;i++){if (nMinx < 0)arrBlock[i][0] -= nMinx;if (nMiny < 0)arrBlock[i][1] -= nMiny;}}//旋转void Ratat(int arrBlock[4][2], int Direct) // driect 1 顺时针方向旋转,-1 逆时针方向旋转{int i;int nMinx, nMiny;int nTmp;for (i = 0;i<4;i++){nTmp = arrBlock[i][0];arrBlock[i][0] = arrBlock[i][1] * (-1)*Direct;arrBlock[i][1] = nTmp*Direct;if (i == 0){nMinx = arrBlock[i][0];nMiny = arrBlock[i][1];}else{if (nMinx > arrBlock[i][0])nMinx = arrBlock[i][0];if (nMiny > arrBlock[i][1])nMiny = arrBlock[i][1];}}for (i = 0;i<4;i++){if (nMinx < 0)arrBlock[i][0] -= nMinx;if (nMiny < 0)arrBlock[i][1] -= nMiny;}}void gotoxy(int x, int y){COORD pos = { x,y };SetConsoleCursorPosition(OUTSTD, pos);}void showxy(int x, int y, int bShow){COORD pos = { x * 2 + 2,y + 2 };SetConsoleCursorPosition(OUTSTD, pos);if (bShow)printf(BLOCKM);elseprintf(BKBLOCK);}void DisShowCursor(){CONSOLE_CURSOR_INFO cci;GetConsoleCursorInfo(OUTSTD, &cci);cci.bVisible = FALSE;SetConsoleCursorInfo(OUTSTD, &cci);}int CheckBlockPlace(int map[MAP_HEIGHT][MAP_WIDTH], int x, int y, int block[4][2], int bShow) //判断位置是否可用{int i;if (x < 0 || y < 0 || x >= MAP_WIDTH || y >= MAP_HEIGHT)return 0;for (i = 0;i<4;i++){if (map[y + block[i][1]][x + block[i][0]] == 1 && bShow)return 0;if (y + block[i][1] >= MAP_HEIGHT || x + block[i][0] >= MAP_WIDTH)return 0;}return 1;}int ShowBlock(int x, int y, int block[4][2], int bShow){int i;for (i = 0;i<4;i++)showxy(block[i][0] + x, block[i][1] + y, bShow);return 1;}void LoadMap(int map[MAP_HEIGHT][MAP_WIDTH]){int i, j;DisShowCursor();system("cls");printf("----------------俄罗斯方块v0.1--------------");printf("\n\n");for (i = 0;i<MAP_HEIGHT;i++){printf(" ");for (j = 0;j<MAP_WIDTH;j++){if (map[i][j])printf(BLOCKM);elseprintf(BKBLOCK);}printf("\n");}gotoxy(MAP_WIDTH * 2 + 6, 4);printf("按s开始\n");gotoxy(MAP_WIDTH * 2 + 6, 5);printf("Next:");gotoxy(MAP_WIDTH * 2 + 6, 12);printf("分数:");}int gameDown(int map[MAP_HEIGHT][MAP_WIDTH], int blockxy[4][2], int nSec, PFUN OnFun, void *pOnData){int i, j, k;int nSelect;int x = 3, y = 0;static int maxy = 20;int missrow = 0;int xsum = 0;while (1){nSelect = OnFun(pOnData);if (nSelect){switch (nSelect){case 75:{if (CheckBlockPlace(map, x - 1, y, blockxy, 1))x--;}break;case 72:{Ratat(blockxy, 1);if (!CheckBlockPlace(map, x, y, blockxy, 1)){Ratat(blockxy, -1);}}break;case 77:{if (CheckBlockPlace(map, x + 1, y, blockxy, 1))x++;}break;}}else{if (CheckBlockPlace(map, x, y, blockxy, 1)){ShowBlock(x, y, blockxy, 1);Sleep(nSec);if (CheckBlockPlace(map, x, y + 1, blockxy, 1)){ShowBlock(x, y, blockxy, 0);y++;}else{for (i = 0;i<4;i++){map[y + blockxy[i][1]][x + blockxy[i][0]] = 1;}if (y < maxy)maxy = y;break;}}elsereturn -1;}}for (i = maxy;i<MAP_HEIGHT;i++){xsum = 0;for (j = 0;j<MAP_WIDTH;j++){xsum += map[i][j];}if (xsum == MAP_WIDTH){for (k = i;k >= maxy;k--)for (j = 0;j<MAP_WIDTH;j++)map[k][j] = map[k - 1][j];missrow++;LoadMap(map);}}return missrow;}// help functionvoid ShowMapArray(int map[MAP_HEIGHT][MAP_WIDTH]){int i, j;for (i = 0;i<MAP_HEIGHT;i++){COORD pos = { MAP_WIDTH * 2,i };SetConsoleCursorPosition(OUTSTD, pos);for (j = 0;j<MAP_WIDTH;j++){printf("%d", map[i][j]);}}}int GetInfo(void *pData){while (kbhit()){char ch1 = getch();if (ch1 < 0){ch1 = getch();}return ch1;}while (kbhit())getch();return 0;}int main(){int map[MAP_HEIGHT][MAP_WIDTH] = { 0 };int blockarrnow[4][2] = { 0 }, blockarrnext[4][2] = { 0 };int ch, nRe, i, j, nScro = 0, nSpeed = 300;BOOL bRun = TRUE;LoadMap(map);srand((unsigned)time(NULL));while (bRun){if (kbhit()){ch = getch();}if (ch == 's' || ch == 'S'){GetTransBlocks(blockarrnow);while (bRun){GetTransBlocks(blockarrnext);ShowBlock(MAP_WIDTH + 2, 5, blockarrnext, 1);nRe = gameDown(map, blockarrnow, nSpeed, GetInfo, NULL);for (i = 0;i<4;i++){blockarrnow[i][0] = blockarrnext[i][0];blockarrnow[i][1] = blockarrnext[i][1];}for (i = 0;i <= 4;i++)for (j = 0;j <= 4;j++){gotoxy(MAP_WIDTH * 2 + 4 + j * 2, 7 + i);printf(" ");}if (nRe < 0){bRun = FALSE;break;}else{nScro += (nRe * 100);gotoxy(MAP_WIDTH * 2 + 11, 12);printf("%d", nScro);}}}}return 0;}Vs2015 编译运行配图。
C语言程序设计-俄罗斯方块源程序
其中的主要逻辑有:(1)由于c的随机性函数不好,所以每次游戏开始根据bios时间设置种子。
(2)得分越高,方块下降速度越快(每200分为单位)。
(3)每下落一个方块加1分,每消除一行加10分,两行加30分,三行加70分,四行加150分。
初试分数为100分。
游戏控制:up-旋转;空格-下落到底;左右下方向键-控制方向。
P-开始或暂停游戏。
ESC-退出。
特点:(1)由于tc不支持中文,所以基本都是英文注释。
(2)函数命名尽可能规范的表达其内部处理目的和过程。
(3)代码加上注释仅有577行。
(我下载过的两个俄罗斯方块代码一个在1087行,一个在993行,我的比它们代码少)。
(4)除了消除空格时算法比较复杂,其他算法都比较简单易读。
(5)绘图效率和局部代码效率扔有待提高。
(6)FrameTime参数可能依据不同硬件环境进行具体设置,InitGame需要正确的TC路径。
俄罗斯方块源于大约9年前上大一时的一个梦,我们在学习c语言时,我的同寝室友邀请我合作一起完成俄罗斯方块(课外作业性质),但是当时限于我们的水平比较菜和学习状态比较懒散,我们没有完成。
大一的时候我在机房里无意发现别人留下的俄罗斯方块程序,运行,老师发现后激动的问我是我写的吗,我惭愧的摇摇头。
那时看到别人做c的大程序深感羡慕(自己只是写几十行的程序)。
数年后我仍然看到有不同样式的实现,但是我一直没有实现它,知道今天忽然有这个想法去做,算是弥补多年前的遗憾和心愿吧。
---------------------------------------------Q&A:----------------------------------------------Q:我编译时出现错误:fatal error C1083: Cannot open include file: 'bios.h': Nosuch file or directory,该如何解决?A:正文中的代码,是使用Borland公司的TC2.0编译的,编译结果运行在Windows的16位虚拟机上。
C语言编程俄罗斯方块的算法及源代码
//俄罗斯方块#include "stdio.h"#include "conio.h"#include "stdlib.h"#include "windows.h"#include "time.h"#define N 17#define M 13#define K 19int s[N][M]={{0,0,0},{0,0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}, {1},{1,0,0,1},{1,1,1,1,1,1,0,1,1,0,0,1,1}};/*当前状态*/inta[K][3][3]={{0,2,0,2,2,2},{0,2,0,2,2,0,0,2},{0,2,0,0,2,2,0,2},{2,2,2,0,2},{2,2,2,0,0,2 ,0},{2,0,0,2,2,2},{2,0,0,2,0,0,2,2},{0,0,2,0,0,2,0,2,2},{0,0,2,2,2,2},{2,2,2,2,0,0}, {2,2,0,0,2,0,0,2,0},{0,2,2,0,2,0,0,2,0},{{2},{2},{2}},{2,2,2},{2,2,0,2,2,0},{2,0,0,2,2,0,0,2},{0,0,2,0,2,2,0,2},{2,2,0,0,2,2},{0,2,2,2,2,0}};void Disp(){int i,j;for(i=0;i<N;i++){for(j=0;j<M;j++)printf("%c",s[i][j]?48+s[i][j]:' ');printf("┃\n");}printf("━━━━━━━━");printf("\n\n操作说明:A-->左移,D-->右移,W-->变形,ESC-->退出\n");}void Down(){int i,j,k;for(j=0;j<M;j++)if(s[N-1][j]==2)break;/*判断是否在下边界*/if(j<M)/*若方块在下边界则将方块由2变1;因为用两种不同的符号,容易判断方块是否“着陆”及左右移动时,是否碰壁*/{for(i=0;i<N;i++)for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=1;for(i=N-1;i>=0;i--){for(j=0;j<M;j++)//判断第i行是否有空格if(s[i][j]==0)break;if(j==M)/*若第i行没空格消去第i行*/for(k=i++-1;k>=0;k--)//?for(j=0;j<M;j++)s[k+1][j]=s[k][j];}return;}for(i=0;i<N-1;i++){for(j=0;j<M;j++)if(s[i][j]==2)if(s[i+1][j]!=0&&s[i+1][j]!=2)break;/*方块下方不空说明触到1了退出内循环*/ if(j<M)break;/*方块下方不空退出外循环*/}if(i<N-1||j<M){for(i=0;i<N;i++)//若已触到1则将方块由 2变1*/for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=1;for(i=N-1;i>=0;i--){for(j=0;j<M;j++)if(s[i][j]==0)break;//判断第i行是否有空格if(j==M)/*若第i行没空格消去第i行*/for(k=i++-1;k>=0;k--)for(j=0;j<M;j++)s[k+1][j]=s[k][j];}return;}for(i=N-1;i>=0;i--)for(j=0;j<M;j++)if(s[i][j]==2)s[i+1][j]=s[i][j],s[i][j]=0;/*方块下移*/}void Right(){int i,j;for(i=0;i<N;i++)if(s[i][M-1]==2)return;/* 已经在右边界退出 */for(i=0;i<N;i++)for(j=0;j<M-1;j++)if(s[i][j]==2)if(s[i][j+1]!=0&&s[i][j+1]!=2)return;/* 方块右方不空,即方块右边有1 退出 */ for(j=M-2;j>=0;j--)for(i=0;i<N;i++)if(s[i][j]==2)s[i][j+1]=s[i][j],s[i][j]=0;/* 方块右移 */}void Left(){int i,j;for(i=0;i<N;i++)if(s[i][0]==2)return;/* 已经在左边界退出 */for(i=0;i<N;i++)for(j=1;j<M;j++)if(s[i][j]==2)if(s[i][j-1]!=0&&s[i][j-1]!=2)return;/* 方块左方不空退出 */ for(j=1;j<M;j++)for(i=0;i<N;i++)if(s[i][j]==2)s[i][j-1]=s[i][j],s[i][j]=0;/* 方块左移 */}int Have()/*判断是否有可移动方块,没有返回1,否则返回0*/{int i,j;for(i=0;i<N;i++)for(j=1;j<M;j++)if(s[i][j]==2)return 0;return 1;}int Add()/*随机生成方块*/{int t,x;/*生成两随机数t和x分别作为第t种方块和第x位置出现*/int i,j;srand((unsigned int)time(NULL));t=rand()%K;x=rand()%(M-3);if(x<0) x=-x%(M-3);//?for(i=0;i<3;i++)for(j=x;j<x+3;j++)//把生成的方块存到初状态中s[i][j]=a[t][i][j-x];}void bianxing(int t,int n){int i,j,k,m,x,y;for(i=0;i<N;i++)//首先扫描是否有移动方块;及方块变形前的位置“行、列”{m=-1;for(j=0;j<M;j++)if(s[i][j]==2){m=i,x=j,y=i;break;//y,x记录所在行、列;并退出内循环}if(m!=-1)//m!=-1证明有移动方块break;//退出外循环}if(m!=-1)//m!=-1证明有移动方块{if(x+3>M||y+3>N) return;//判断是否有可变形空间,没有就返回for(i=y;i<y+3;i++)//判断是否有3*3的变形空间,没有就返回for(j=x;j<x+3;j++)if(s[i][j]==1) return;/*擦除当前移动方块;因为上面判断3*3的移动空间,是从上面开始扫描,遇到第一个小格子时,依他为基点向右下方扫描是否有3*3的空间;显然只进行下面的变形--存储是不行的;如:002002022-->2220020时,显然前面的方格倒数第二个2,留在了3*3变形空间的外面,输出图形将多一个格子,所以要在变形-->存储操作前进行擦除操作*/for(i=y;i<y+3;i++)for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=0;//变形并把它存储到当前状态中if(t<=3&&t>=0){static int h1;if(h1>n)h1=0;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h1][i-y][j-x];h1++;}else if(t<=11&&t>=4){static int h2=4;if(h2>n)h2=4;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h2][i-y][j-x];h2++;}else if(t<=13&&t>=12){static int h3=12;if(h3>n)h3=12;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h3][i-y][j-x];h3++;}else if(t<=18&&t>=15){static int h4=15;if(h4>n)h4=0;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h4][i-y][j-x];h4++;}}void main(){char c;int i=0,t;char str[][50]={" ((`'-\"``\"\"-'`))"," ) - - ( "," / (o _ o) \ "," \ ( 0 ) /"," _'-.._'='_..-'_ "," /`;#'#'#.-.#'#'#;`\ "," \_)) '#' ((_/ "," #. ☆ Game ☆ # "," '#. Over! .#' "," / '#. .#' \ "," _\ \'#. .#'/ /_"," (((___) '#' (___) ",""};system("color 0a");while(1)/*判断是否有按键,没有循环输出i,否则停,conio.h*/{if(!kbhit())/*kbhit用来判断是否有按键输入,若有按键返回非零值,否则返回零;没有按键时c被赋予一个“非操作键值”,它将一直下移;有按键是调用getch函数,读取键值*/c='2';elsec=getch();if(c=='p')//停止键;按任意键可解除停止getch();system("CLS");/*清屏,TC用clrscr();,VC用system("CLS");*/if(Have())//Have()判断是否有可移动方块,没有返回1,否则返回0t=Add();switch(c){case 'a':Left();break; /*左移*/case 'd':Right();break; /*右移*/case 27: system("pause");return; /*按Esc(=27)另存后退出*/default:;}//变形if(c=='w')if(t>=0&&t<=3) bianxing(t,3);else if(t>=4&&t<=11) bianxing(t,11);else if(t==12||t==13) bianxing(t,13);else if(t>=15&&t<=18) bianxing(t,18);c='2';Down();//判断方块的停、走和消除//判断顶层是否有1 有:游戏结束for(i=0;i<M;i++)if(s[0][i]==1){system("CLS");i=0;while(1){if(strlen(str[i])==0)break;printf("%s\n",str[i++]);}system("pause");exit(0);}Disp();//刷屏Sleep(500);/*睡眠ms,windows.h*/}}***********************************************************。
VC++6.0俄罗斯方块代码讲解
}
//显示背景
else
russia.DrawJiemian(pDC);
}
开始时我们是设start为假,它就会在OnDraw()函数中画封面,而当我们开始游戏,start为真,那么,它干什么呢?画背景!其函数如下:
界面函数:
还是那个道理,当有一些客户区生效(被挡住或最小化)时,它必须重画,而如果游戏只是玩了一半,它必然在重画时必须把原先已经出现的方块、分数等也显示出来,怎么办?就必须在画封面的同时也画出它们。当然,刚开始时它们是不会符合条件的。
{
AfxMessageBox("Can't Create Font");
}
pDC->SelectObject(&font);
//设置字体颜色及其背景颜色
CString str;
pDC->SetTextColor(RGB(39,244,10));
pDC->SetBkColor(RGB(255,255,0));
case 1:
Will[0][0]=1;
Will[0][1]=1;
Will[1][0]=1;
Will[2][0]=1;
break;
case 2:
Will[0][0]=1;
Will[0][1]=1;
Will[1][1]=1;
Will[2][1]=1;
break;
case 3:
Will[0][1]=1;
if(m_Score>=0)
pDC->TextOut(440,2,str);
pDC->RestoreDC(nOldDC);
}
至此,可以看的都画完了。程序一般都是会先处理图形界面,因为这样在编核心内容时能够让人有一个检查的机会。
C语言实现俄罗斯方块源代码
C语⾔实现俄罗斯⽅块源代码本⽂实例为⼤家分享了C语⾔实现俄罗斯⽅块的具体代码,供⼤家参考,具体内容如下GitHub:Head.h#ifndef _HEAD_H_#define _HEAD_H_#include<graphics.h>#include<stdio.h>#include<conio.h>#include<stdlib.h>#include<time.h>#include<string.h>#define _CRT_SECURE_NO_WARNINGS 1//界⾯的相关的参数#define WALL_SQUARE_WIDTH 10 //围墙⽅块的宽度#define xWALL_SQUARE_NUM 30 //x轴⽅向的⽅块的数⽬#define yWALL_SQUARE_WIDTH 46 //y轴⽅向的⽅块的数⽬#define GAME_WALL_WIDTH (WALL_SQUARE_WIDTH*xWALL_SQUARE_NUM) //游戏区域的宽度 300#define GAME_WALL_HTGH (WALL_SQUARE_WIDTH*yWALL_SQUARE_WIDTH) //游戏区域的⾼度 460#define WINDOW_WIDTH 480 // 游戏总窗⼝宽度 480#define WINDOW_HIGH 460 // 游戏总窗⼝⾼度 460//定义俄罗斯⽅块的相关参数#define ROCK_SQUARE_WIDTH (2*WALL_SQUARE_WIDTH) //俄罗斯⽅块的⼤⼩是围墙的两倍 20#define xROCK_SQUARE_NUM ((GAME_WALL_WIDTH -20)/ROCK_SQUARE_WIDTH) // 游戏区x轴放的⽅块数⽬:14 #define yROCK_SQUARE_NUM ((GAME_WALL_HTGH -20)/ROCK_SQUARE_WIDTH) // 游戏区y轴放的⽅块数⽬:22 //定义移动⽅块的相关操作#define DIRECT_UP 3#define DIRECT_DOWN 2#define DIRECT_LEFT -1#define DIRECT_RIGHT 1/*数据结构-线性表(结构体数组)*/typedef struct ROCK{//⽤来表⽰⽅块的形状(每⼀个字节是8位,⽤每4位表⽰⽅块中的⼀⾏)unsigned short rockShapeBits;int nextRockIndex; //下⼀个⽅块,在数组中的下标} RockType;//⽅块在图形窗⼝中的位置(即定位4*4⼤块的左上⾓坐标)typedef struct LOCATE{int left;int top;} RockLocation_t;//全局变量-游戏板的状态描述(即表⽰当前界⾯哪些位置有⽅块)//0表⽰没有,1表⽰有(多加了两⾏和两列,形成⼀个围墙,便于判断⽅块是否能够移动)int game_board[yROCK_SQUARE_NUM + 2][xROCK_SQUARE_NUM + 2] = { 0 };int game_socres = 0; //全局分数// 把俄罗斯⽅块的19种类放到数组中int rockTypeNum = 19;RockType RockArray[19] = { (0, 0) };//预览区的⽅块的位置RockLocation_t preRockLocation = {GAME_WALL_WIDTH+70,70};//每次⽣成初始化⽅块的位置RockLocation_t initRockLocation = { (WALL_SQUARE_WIDTH + 100), WALL_SQUARE_WIDTH };//分数显⽰的位置//各个⽂件中的函数void DisplayRock(int rockIdx, RockLocation_t* LocatePtr, bool displayed);//初始化Init源⽂件void InitGame();//game.hvoid PlayGame();bool IsGameOver();#endifDraw.h#include"Head.h"//画出游戏界⾯void DrawGameWindow(){//先画出围墙setcolor(BLUE);setlinestyle(PS_SOLID,NULL,0);setfillcolor(BLUE);//画出上下围墙for (int x = WALL_SQUARE_WIDTH; x <= GAME_WALL_WIDTH; x += WALL_SQUARE_WIDTH){fillrectangle(x - WALL_SQUARE_WIDTH, 0, x, WALL_SQUARE_WIDTH); //上fillrectangle(x - WALL_SQUARE_WIDTH, GAME_WALL_HTGH - WALL_SQUARE_WIDTH, x, GAME_WALL_HTGH);//下 }//画出左右围墙for (int y = WALL_SQUARE_WIDTH; y <= GAME_WALL_HTGH; y += WALL_SQUARE_WIDTH){fillrectangle(0, y, WALL_SQUARE_WIDTH, y + WALL_SQUARE_WIDTH);//左fillrectangle(GAME_WALL_WIDTH - WALL_SQUARE_WIDTH, y, GAME_WALL_WIDTH, y + WALL_SQUARE_WIDTH);//右 }//画出右边统计分数及相关东西//画出分割线setcolor(WHITE);setlinestyle(PS_DASH,2);line(GAME_WALL_WIDTH + 20, 0, GAME_WALL_WIDTH + 20, GAME_WALL_HTGH);//设置字体LOGFONT font;gettextstyle(&font);settextstyle(18, 0, _T("宋体"));font.lfQuality = ANTIALIASED_QUALITY;//设置输出效果为抗锯齿//1显⽰预览形状outtextxy(GAME_WALL_WIDTH + 80, 30, _T("预览"));outtextxy(GAME_WALL_WIDTH + 80, 170, _T("分数"));outtextxy(GAME_WALL_WIDTH + 65, 250, _T("操作说明"));outtextxy(GAME_WALL_WIDTH + 40, 290, _T("w a s d控制⽅向"));outtextxy(GAME_WALL_WIDTH + 40, 335, _T("空格暂停"));//显⽰分数setcolor(RED);outtextxy(GAME_WALL_WIDTH + 90, 200, '0');}//在游戏区显⽰编号为rockIdx的⽅块void DisplayRock(int rockIdx, RockLocation_t* LocatePtr, bool displayed){int color;//⽅块的填充颜⾊int lineColor = WHITE;//线的颜⾊int boardFalg = 0;int xRock = 0;int yRock = 0;unsigned short rockCode = RockArray[rockIdx].rockShapeBits;//如果displayed为true的话,将⽅块块颜⾊设置为white,game_board对应的位置设置为1;//如果displayed为false的话,将⽅块块颜⾊设置为black,game_board对应的位置设置为0;displayed ? (color = RED, boardFalg = 1) : (color = BLACK,lineColor = BLACK, boardFalg = 0);setcolor(lineColor);setlinestyle(PS_SOLID);//设置为实线,xRock = LocatePtr->left;yRock = LocatePtr->top;int count = 0;//每4个换⾏,记录坐标偏移量unsigned short mask = 1;for (int i = 1; i <= 16; ++i){mask = 1 << (16 - i);if ((rockCode & mask) != 0) //如果不为0的话,就画出⼩⽅块{fillrectangle(xRock , yRock, xRock + ROCK_SQUARE_WIDTH, yRock + ROCK_SQUARE_WIDTH); }if (i % 4 == 0) //换⾏{yRock = yRock + ROCK_SQUARE_WIDTH;xRock = xRock = LocatePtr->left;}else{xRock += ROCK_SQUARE_WIDTH;}}}Init.h#include"Head.h"static void ShapeStrToBit(unsigned char *rockShapeStr, unsigned short& rockShapeBit);static void ReadRcok();void InitGame(){//把全局游戏游戏版初始化,边界初始化为1for (int i = 0; i < xROCK_SQUARE_NUM + 2; i++){game_board[0][i] = 1; //上边界game_board[yROCK_SQUARE_NUM + 1][i] = 1; //下边界}for (int i = 0; i < yROCK_SQUARE_NUM + 2; i++){game_board[i][0] = 1 ; //左边界game_board[i][xROCK_SQUARE_NUM + 1] = 1; //右边界}//读取俄罗斯⽅块ReadRcok();}//从⽂件中读取⽅块的形状存储到rockArray中void ReadRcok(){FILE* fp = fopen("RockShape.ini","r");if (NULL == fp){printf("打开⽂件失败\n");return;}unsigned char readBuf[1024]; //fp读取到字符串readbuf中unsigned short rockShapeBit = 0;//存放⽅块形状,占16⽐特位unsigned char rockShapeStr[16];//存放⽅块字符串int ShapeStrIdx = 0;int rockNum = 0;//统计⽅块的个数以及存放⽅块数组RockArray的下标int rocknext = 0;//⽅块数组中下⼀个形状int rockShapeStart = 0;//同⼀类型的形状while (true){size_t readSize = fread(readBuf, 1, 1024, fp);if (readSize == 0)break;//处理readbuffor (size_t idx = 0; idx < readSize; ++idx){//将字符存放到rockShapeStr中if (readBuf[idx] == '@' || readBuf[idx] == '#'){rockShapeStr[ShapeStrIdx] = (unsigned char)readBuf[idx];++ShapeStrIdx;}++idx; //可能idx == readSize了if (readBuf[idx] == '*')//修改上⼀次⽅块的next值{idx += 5;RockArray[--rockNum].nextRockIndex = rockShapeStart;rockNum++;rockShapeStart = rockNum;rocknext = rockShapeStart ;}}//可能没有填满if (ShapeStrIdx < 16){break;}else //填满shapestr{ShapeStrIdx = 0;//置0//将rockShapeStr 转为rockShapeBitShapeStrToBit(rockShapeStr, rockShapeBit);rocknext++;RockArray[rockNum].rockShapeBits = rockShapeBit;RockArray[rockNum].nextRockIndex = rocknext;rockNum++;}}}fclose(fp);}//将从⽂件中读取的字符串(长度默认为16)转换成 unsigned shortvoid ShapeStrToBit(unsigned char *rockShapeStr, unsigned short& rockShapeBit){rockShapeBit = 0;for (size_t idx = 0; idx < 16; ++idx){if (rockShapeStr[idx] == '@') //1{rockShapeBit |= (1 << (16 - idx - 1));}// #为0 不需要处理}}game.h#include"Head.h"#define _CRT_SECURE_NO_WARNINGS 1bool MoveAble(int rockIndex, RockLocation_t* currentLocatePtr, int f_direction);void SetGameBoardFlag(int rockIdx, RockLocation_t* curRockLocation);void UserHitKeyBoard(char userHit, int* RockIndex, RockLocation_t* curRockLocation); void FullLine();void UpdateSocres(int scores);void DelCurLine(int rowIdx);bool IsGameOver();void PlayGame(){char userHit = 0;//⽤户敲击键盘int curRockIndex = 0;//当前⽅块的rockArray下标int nextRockIndex = 0;//下次RockLocation_t curRockLocation;curRockLocation.left = initRockLocation.left;curRockLocation.top = initRockLocation.top;DWORD oldtime = 0;srand((unsigned int)time(NULL));curRockIndex = rand() % rockTypeNum;nextRockIndex = rand() % rockTypeNum;//画出预览区初始化⽅块//在初始位置和预览区显⽰⽅块形状bool moveAbled = false;while (true){//判断当前⽅块是否落地(判断能否再下移):如果落地,判断是否满⾏,再判断是否结束游戏,改变game_board ,画出下次初始化的⽅块,以及⽣成新的预览⽅块 //moveAbled = MoveAble(curRockIndex, &curRockLocation, DIRECT_DOWN);if (!moveAbled) //判断是否落地,不能下移表⽰落地{//修改game_board的值SetGameBoardFlag(curRockIndex, &curRockLocation);FullLine();if (IsGameOver()){MessageBox(NULL, _T("游戏结束"), _T("GAME OVER"), MB_OK);exit(0);}//为下次⽣成模块开始准备DisplayRock(nextRockIndex, &preRockLocation, false);//擦除旧的⽅块curRockIndex = nextRockIndex;nextRockIndex = rand() % rockTypeNum; //⽣成新的预览⽅块DisplayRock(curRockIndex, &initRockLocation, 1);DisplayRock(nextRockIndex, &preRockLocation, 1);FlushBatchDraw();//修改curRockLocation的值curRockLocation.left = initRockLocation.left;curRockLocation.top = initRockLocation.top;}if (kbhit()) //如果敲击键盘了就处理按键{userHit = getch();UserHitKeyBoard(userHit, &curRockIndex, &curRockLocation);}//没有就⾃动下移⼀个单位 :不能⽤else,因为可能按键不是上下左右DWORD newtime = GetTickCount();if (newtime - oldtime >= (unsigned int)(300) && moveAbled == TRUE){oldtime = newtime;DisplayRock(curRockIndex, &curRockLocation, false);curRockLocation.top += ROCK_SQUARE_WIDTH; //下落⼀格}//AutomaticDownMove(curRockIndex, &curRockLocation);//画出新⽅块DisplayRock(curRockIndex, &curRockLocation, 1);FlushBatchDraw();Sleep(20);}}//响应键盘命令时间void UserHitKeyBoard(char userHit, int* RockIndex, RockLocation_t* curRockLocation){switch (userHit){case 'W':case 'w'://↑if (MoveAble(RockArray[*RockIndex].nextRockIndex, curRockLocation, DIRECT_UP)){DisplayRock(*RockIndex, curRockLocation, false);*RockIndex = RockArray[*RockIndex].nextRockIndex;}break;case 'S':case 's'://↓if (MoveAble(*RockIndex, curRockLocation, DIRECT_DOWN)){DisplayRock(*RockIndex, curRockLocation, false);curRockLocation->top += 2 * (ROCK_SQUARE_WIDTH);if (!MoveAble(*RockIndex, curRockLocation, DIRECT_DOWN)){curRockLocation->top -= ROCK_SQUARE_WIDTH;}}break;case 'A':if (MoveAble(*RockIndex, curRockLocation, DIRECT_LEFT)){DisplayRock(*RockIndex, curRockLocation, false);curRockLocation->left -= ROCK_SQUARE_WIDTH;}break;case 'D':case 'd': //→if (MoveAble(*RockIndex, curRockLocation, DIRECT_RIGHT)){DisplayRock(*RockIndex, curRockLocation, FALSE);curRockLocation->left += ROCK_SQUARE_WIDTH;}break;case ' ': //暂停while (1){userHit = getch();if (userHit == ' ')break;}break;default:break;}}//判断是否满⾏,满⾏消除,然后计算得分void FullLine(){bool linefull = true;int idx = yROCK_SQUARE_NUM;//从最后⼀⾏往上查找 22int count = 0;while (count != xROCK_SQUARE_NUM ) //遇到空⾏ 14{linefull = true;count = 0;for (int i = 1; i <= xROCK_SQUARE_NUM; ++i){if (game_board[idx][i] == 0){linefull = false;count++;}}if (linefull) //满⾏,消除当前⾏,更新分数{DelCurLine(idx);game_socres += 3;UpdateSocres(game_socres);idx++;//因为下⾯要减1}idx--;}}void UpdateSocres(int scores){setcolor(RED);TCHAR s[10];_stprintf(s, _T("%d"), scores);outtextxy(GAME_WALL_WIDTH + 90, 200, s);}//消除当前⾏void DelCurLine(int rowIdx){//擦除当前⾏setcolor(BLACK);setfillcolor(BLACK);for (int i = 1; i < xROCK_SQUARE_NUM; ++i){fillrectangle(WALL_SQUARE_WIDTH + (i - 1)*ROCK_SQUARE_WIDTH, (rowIdx - 1)*ROCK_SQUARE_WIDTH + WALL_SQUARE_WIDTH, WALL_SQUARE_WIDTH + i*ROCK_SQUARE_WIDTH, rowIdx*ROCK_SQUARE_WIDTH + WALL_SQUARE_WIDTH);}//把上⾯的向下移int cnt = 0;while (cnt != xROCK_SQUARE_NUM) //直到遇到是空⾏的为⽌cnt = 0;for (int i = 1; i <= xROCK_SQUARE_NUM; i++){game_board[rowIdx][i] = game_board[rowIdx - 1][i];//擦除上⾯的⼀⾏setcolor(BLACK);setfillcolor(BLACK);fillrectangle(WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*i - ROCK_SQUARE_WIDTH , WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*(rowIdx - 1) - ROCK_SQUARE_WIDTH , WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*i,WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*(rowIdx - 1));//显⽰下⾯的⼀⾏if (game_board[rowIdx][i] == 1){setcolor(WHITE);setfillcolor(RED);fillrectangle(WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*i - ROCK_SQUARE_WIDTH , WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*rowIdx - ROCK_SQUARE_WIDTH ,WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*i,WALL_SQUARE_WIDTH + ROCK_SQUARE_WIDTH*rowIdx);}if (game_board[rowIdx][i] == 0)cnt++; //统计⼀⾏是不是都是空格}//forrowIdx--;}}//是否可以移动⽅块bool MoveAble(int rockIndex, RockLocation_t* currentLocatePtr, int f_direction){int mask;int rockX;int rockY;rockX = currentLocatePtr->left;rockY = currentLocatePtr->top;mask = (unsigned short)1 << 15;for (int i = 1; i <= 16; i++){//与掩码相与为1的即为⽅块上的点if ((RockArray[rockIndex].rockShapeBits & mask) != 0){//判断能否移动(即扫描即将移动的位置是否与设置的围墙有重叠)//若是向上(即翻滚变形)if (f_direction == DIRECT_UP){//因为此情况下传⼊的是下⼀个⽅块的形状,故我们直接判断此⽅块的位置是否已经被占//判断下⼀个⽅块if (game_board[(rockY - WALL_SQUARE_WIDTH) / ROCK_SQUARE_WIDTH + 1][(rockX - WALL_SQUARE_WIDTH) / ROCK_SQUARE_WIDTH + 1] == 1)return false;}//如果是向下⽅向移动else if (f_direction == DIRECT_DOWN){if (game_board[(rockY - WALL_SQUARE_WIDTH) / ROCK_SQUARE_WIDTH + 2][(rockX - WALL_SQUARE_WIDTH) / ROCK_SQUARE_WIDTH + 1] == 1)return false;}else //如果是左右⽅向移动{ //f_direction的DIRECT_LEFT为-1,DIRECT_RIGHT为1,故直接加f_direction即可判断。
C语言源码实现俄罗斯方块
C语⾔源码实现俄罗斯⽅块介绍俄罗斯⽅块(Tetris,俄⽂:Тетрис)是⼀款电视游戏机和掌上游戏机游戏,它由俄罗斯⼈阿列克谢·帕基特诺夫发明,故得此名。
俄罗斯⽅块的基本规则是移动、旋转和摆放游戏⾃动输出的各种⽅块,使之排列成完整的⼀⾏或多⾏并且消除得分。
由于上⼿简单、⽼少皆宜,从⽽家喻户晓,风靡世界。
源码#include <stdio.h>#include <string.h>#include <stdlib.h>#include <time.h>#include <conio.h>#include <windows.h>#ifdef _MSC_VER // M$的编译器要给予特殊照顾#if _MSC_VER <= 1200 // VC6及以下版本#error 你是不是还在⽤VC6?!#else // VC6以上版本#if _MSC_VER >= 1600 // 据说VC10及以上版本有stdint.h了#include <stdint.h>#else // VC10以下版本,⾃⼰定义int8_t和uint16_ttypedef signed char int8_t;typedef unsigned short uint16_t;#endif#ifndef __cplusplus // 据说VC都没有stdbool.h,不⽤C++编译,⾃⼰定义booltypedef int bool;#define true 1#define false 0#endif#endif#else // 其他的编译器都好说#include <stdint.h>#ifndef __cplusplus // 不⽤C++编译,需要stdbool.h⾥的bool#include <stdbool.h>#endif#endif// =============================================================================// 7种⽅块的4旋转状态(4位为⼀⾏)static const uint16_t gs_uTetrisTable[7][4] ={{ 0x00F0U, 0x2222U, 0x00F0U, 0x2222U }, // I型{ 0x0072U, 0x0262U, 0x0270U, 0x0232U }, // T型{ 0x0223U, 0x0074U, 0x0622U, 0x0170U }, // L型{ 0x0226U, 0x0470U, 0x0322U, 0x0071U }, // J型{ 0x0063U, 0x0264U, 0x0063U, 0x0264U }, // Z型{ 0x006CU, 0x0462U, 0x006CU, 0x0462U }, // S型{ 0x0660U, 0x0660U, 0x0660U, 0x0660U } // O型};// =============================================================================// 初始状态的游戏池// 每个元素表⽰游戏池的⼀⾏,下标⼤的是游戏池底部// 两端各置2个1,底部2全置为1,便于进⾏碰撞检测// 这样⼀来游戏池的宽度为12列// 如果想要传统的10列,只需多填两个1即可(0xE007),当然显⽰相关部分也要随之改动// 当某个元素为0xFFFFU时,说明该⾏已被填满// 顶部4⾏⽤于给⽅块,不显⽰出来// 再除去底部2⾏,显⽰出来的游戏池⾼度为22⾏static const uint16_t gs_uInitialTetrisPool[28] ={0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U,0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U,0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U,0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xC003U, 0xFFFFU, 0xFFFFU};#define COL_BEGIN 2#define COL_END 14// ============================================================================= typedef struct TetrisManager // 这个结构体存储游戏相关数据{uint16_t pool[28]; // 游戏池int8_t x; // 当前⽅块x坐标,此处坐标为⽅块左上⾓坐标int8_t y; // 当前⽅块y坐标int8_t type[3]; // 当前、下⼀个和下下⼀个⽅块类型int8_t orientation[3]; // 当前、下⼀个和下下⼀个⽅块旋转状态unsigned score; // 得分unsigned erasedCount[4]; // 消⾏数unsigned erasedTotal; // 消⾏总数unsigned tetrisCount[7]; // 各⽅块数unsigned tetrisTotal; // ⽅块总数bool dead; // 挂} TetrisManager;// ============================================================================= typedef struct TetrisControl // 这个结构体存储控制相关数据{bool pause; // 暂停bool clockwise; // 旋转⽅向:顺时针为trueint8_t direction; // 移动⽅向:0向左移动 1向右移动// 游戏池内每格的颜⾊// 由于此版本是彩⾊的,仅⽤游戏池数据⽆法存储颜⾊信息// 当然,如果只实现单⾊版的,就没必要⽤这个数组了int8_t color[28][16];} TetrisControl;HANDLE g_hConsoleOutput; // 控制台输出句柄// ============================================================================= // 函数声明// 如果使⽤全局变量⽅式实现,就没必要传参了void initGame(TetrisManager *manager, TetrisControl *control); // 初始化游戏void restartGame(TetrisManager *manager, TetrisControl *control); // 重新开始游戏void giveTetris(TetrisManager *manager); // 给⼀个⽅块bool checkCollision(const TetrisManager *manager); // 碰撞检测void insertTetris(TetrisManager *manager); // 插⼊⽅块void removeTetris(TetrisManager *manager); // 移除⽅块void horzMoveTetris(TetrisManager *manager, TetrisControl *control); // ⽔平移动⽅块void moveDownTetris(TetrisManager *manager, TetrisControl *control); // 向下移动⽅块void rotateTetris(TetrisManager *manager, TetrisControl *control); // 旋转⽅块void dropDownTetris(TetrisManager *manager, TetrisControl *control); // ⽅块直接落地bool checkErasing(TetrisManager *manager, TetrisControl *control); // 消⾏检测void keydownControl(TetrisManager *manager, TetrisControl *control, int key); // 键按下void setPoolColor(const TetrisManager *manager, TetrisControl *control); // 设置颜⾊void gotoxyWithFullwidth(short x, short y); // 以全⾓定位void printPoolBorder(); // 显⽰游戏池边界void printTetrisPool(const TetrisManager *manager, const TetrisControl *control); // 显⽰游戏池void printCurrentTetris(const TetrisManager *manager, const TetrisControl *control); // 显⽰当前⽅块void printNextTetris(const TetrisManager *manager); // 显⽰下⼀个和下下⼀个⽅块void printScore(const TetrisManager *manager); // 显⽰得分信息void runGame(TetrisManager *manager, TetrisControl *control); // 运⾏游戏void printPrompting(); // 显⽰提⽰信息bool ifPlayAgain(); // 再来⼀次// ============================================================================= // 主函数int main(){TetrisManager tetrisManager;TetrisControl tetrisControl;initGame(&tetrisManager, &tetrisControl); // 初始化游戏do{printPrompting(); // 显⽰提⽰信息printPoolBorder(); // 显⽰游戏池边界runGame(&tetrisManager, &tetrisControl); // 运⾏游戏if (ifPlayAgain()) // 再来⼀次{SetConsoleTextAttribute(g_hConsoleOutput, 0x7);system("cls"); // 清屏restartGame(&tetrisManager, &tetrisControl); // 重新开始游戏else{break;}} while (1);gotoxyWithFullwidth(0, 0);CloseHandle(g_hConsoleOutput);return 0;}// ============================================================================= // 初始化游戏void initGame(TetrisManager *manager, TetrisControl *control){CONSOLE_CURSOR_INFO cursorInfo = { 1, FALSE }; // 光标信息g_hConsoleOutput = GetStdHandle(STD_OUTPUT_HANDLE); // 获取控制台输出句柄SetConsoleCursorInfo(g_hConsoleOutput, &cursorInfo); // 设置光标隐藏SetConsoleTitleA("俄罗斯⽅块控制台版——By: NEWPLAN");restartGame(manager, control);}// ============================================================================= // 重新开始游戏void restartGame(TetrisManager *manager, TetrisControl *control){memset(manager, 0, sizeof(TetrisManager)); // 全部置0// 初始化游戏池memcpy(manager->pool, gs_uInitialTetrisPool, sizeof(uint16_t [28]));srand((unsigned)time(NULL)); // 设置随机种⼦manager->type[1] = rand() % 7; // 下⼀个manager->orientation[1] = rand() & 3;manager->type[2] = rand() % 7; // 下下⼀个manager->orientation[2] = rand() & 3;memset(control, 0, sizeof(TetrisControl)); // 全部置0giveTetris(manager); // 给下⼀个⽅块setPoolColor(manager, control); // 设置颜⾊}// ============================================================================= // 给⼀个⽅块void giveTetris(TetrisManager *manager){uint16_t tetris;manager->type[0] = manager->type[1]; // 下⼀个⽅块置为当前manager->orientation[0] = manager->orientation[1];manager->type[1] = manager->type[2];// 下下⼀个置⽅块为下⼀个manager->orientation[1] = manager->orientation[2];manager->type[2] = rand() % 7;// 随机⽣成下下⼀个⽅块manager->orientation[2] = rand() & 3;tetris = gs_uTetrisTable[manager->type[0]][manager->orientation[0]]; // 当前⽅块// 设置当前⽅块y坐标,保证刚给出时只显⽰⽅块最下⾯⼀⾏// 这种实现使得玩家可以以很快的速度将⽅块落在不显⽰出来的顶部4⾏内if (tetris & 0xF000){manager->y = 0;}else{manager->y = (tetris & 0xFF00) ? 1 : 2;}manager->x = 6; // 设置当前⽅块x坐标if (checkCollision(manager)) // 检测到碰撞manager->dead = true; // 标记游戏结束}else // 未检测到碰撞{insertTetris(manager); // 将当前⽅块加⼊游戏池}++manager->tetrisTotal; // ⽅块总数++manager->tetrisCount[manager->type[0]]; // 相应⽅块数printNextTetris(manager); // 显⽰下⼀个⽅块printScore(manager); // 显⽰得分信息}// ============================================================================= // 碰撞检测bool checkCollision(const TetrisManager *manager){// 当前⽅块uint16_t tetris = gs_uTetrisTable[manager->type[0]][manager->orientation[0]];uint16_t dest = 0;// 获取当前⽅块在游戏池中的区域:// 游戏池坐标x y处⼩⽅格信息,按低到⾼存放在16位⽆符号数中dest |= (((manager->pool[manager->y + 0] >> manager->x) << 0x0) & 0x000F);dest |= (((manager->pool[manager->y + 1] >> manager->x) << 0x4) & 0x00F0);dest |= (((manager->pool[manager->y + 2] >> manager->x) << 0x8) & 0x0F00);dest |= (((manager->pool[manager->y + 3] >> manager->x) << 0xC) & 0xF000);// 若当前⽅块与⽬标区域存在重叠(碰撞),则位与的结果不为0return ((dest & tetris) != 0);}// ============================================================================= // 插⼊⽅块void insertTetris(TetrisManager *manager){// 当前⽅块uint16_t tetris = gs_uTetrisTable[manager->type[0]][manager->orientation[0]];// 当前⽅块每4位取出,位或到游戏池相应位置,即完成插⼊⽅块manager->pool[manager->y + 0] |= (((tetris >> 0x0) & 0x000F) << manager->x);manager->pool[manager->y + 1] |= (((tetris >> 0x4) & 0x000F) << manager->x);manager->pool[manager->y + 2] |= (((tetris >> 0x8) & 0x000F) << manager->x);manager->pool[manager->y + 3] |= (((tetris >> 0xC) & 0x000F) << manager->x);}// ============================================================================= // 移除⽅块void removeTetris(TetrisManager *manager){// 当前⽅块uint16_t tetris = gs_uTetrisTable[manager->type[0]][manager->orientation[0]];// 当前⽅块每4位取出,按位取反后位与到游戏池相应位置,即完成移除⽅块manager->pool[manager->y + 0] &= ~(((tetris >> 0x0) & 0x000F) << manager->x);manager->pool[manager->y + 1] &= ~(((tetris >> 0x4) & 0x000F) << manager->x);manager->pool[manager->y + 2] &= ~(((tetris >> 0x8) & 0x000F) << manager->x);manager->pool[manager->y + 3] &= ~(((tetris >> 0xC) & 0x000F) << manager->x);}// ============================================================================= // 设置颜⾊void setPoolColor(const TetrisManager *manager, TetrisControl *control){// 由于显⽰游戏池时,先要在游戏池⾥判断某⼀⽅格有⽅块才显⽰相应⽅格的颜⾊// 这⾥只作设置即可,没必要清除// 当移动⽅块或给⼀个⽅块时调⽤int8_t i, x, y;// 当前⽅块uint16_t tetris = gs_uTetrisTable[manager->type[0]][manager->orientation[0]];for (i = 0; i < 16; ++i)y = (i >> 2) + manager->y; // 待设置的列if (y > ROW_END) // 超过底部限制{break;}x = (i & 3) + manager->x; // 待设置的⾏if ((tetris >> i) & 1) // 检测的到⼩⽅格属于当前⽅块区域{control->color[y][x] = (manager->type[0] | 8); // 设置颜⾊}}}// ============================================================================= // 旋转⽅块void rotateTetris(TetrisManager *manager, TetrisControl *control){int8_t ori = manager->orientation[0]; // 记录原旋转状态removeTetris(manager); // 移⾛当前⽅块// 顺/逆时针旋转manager->orientation[0] = (control->clockwise) ? ((ori + 1) & 3) : ((ori + 3) & 3);if (checkCollision(manager)) // 检测到碰撞{manager->orientation[0] = ori; // 恢复为原旋转状态insertTetris(manager); // 放⼊当前⽅块。
C语言俄罗斯方块游戏源代码
C语言俄罗斯方块游戏源代码/*学无止境*/ #include#include#include#define ESC 27#define UP 328#define DOWN 336#define LEFT 331#define RIGHT 333#define BLANK 32#define BOTTOM 2#define CANNOT 1#define CAN 0#define MAX 30#define F1 315#define ADD 43#define EQUAL 61#define DEC 45#define SOUNDs 115#define SOUNDS 83#define PAUSEP 80#define PAUSEp 112void Init();void Down();void GoOn();void ksdown();void Display(int color);void Give();int Touch(int x,int y,int dx,int dy);int GeyKey();void Select();void DetectFill();void GetScores();void Fail();void Help();void Quit();void DrawBox(int x,int y,int Color);void OutTextXY(int x,int y,char *String); void DispScore(int x,int y,char Ch);void DrawNext(int Color);int Heng=12,Shu=20; /*横竖*/int Position[MAX][MAX];int middle[MAX][MAX];int ActH,ActS;int Act,Staus;int i,j,k;int Wid=10;int NoPass=CAN;float Delays=15000;int BeginH=250,BeginS=7;float Seconds=0;int Scores=0;int flag=1;int Sounds=CAN;int PreAct,NextAct;int a[8][4][4][4]={{{1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0}, {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0},{1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}},{{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0}},{{1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0}}, {{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}, {0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0}, {1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}, {0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0}}, {{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0}, {1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0}, {0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0}, {1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0}}, {{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0}, {1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0}, {1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0}}, {{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}, {1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0}, {1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0}}, {{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}}; int b[4][4];main(int argc,char *argv[]){if (argc!=1){if (argv[1]!="")Heng=atoi(argv[1]);if (argv[2]!="")Shu=atoi(argv[2]);}Init(); /*初始化界面*/PreAct=random(8); /*取得当前的方块*/for(;;) /*以下是游戏流程*/{NextAct=random(8); /*取得下一个方块*/ DrawNext(1); /*画出下一个方块*/Act=PreAct;if (Heng%2==0) ActH=Heng/2;else ActH=(Heng-1)/2;ActS=0; /*方块开始从游戏空间的中间下落*/ Staus=0; /*取开始的状态*/NoPass=CAN; /*物体可以下落*/Give(); /*取得当前的方块*/Display(Act+1); /*显示当前的方块,每种方块的颜色不同*/ GoOn(); /*游戏的算法精髓所在*/PreAct=NextAct; /*方块下落完毕,取得下一个方块*/ DrawNext(0);}}void Init(){int GraphDriver=DETECT,GraphMode;registerbgidriver(EGAVGA_driver);initgraph(&GraphDriver,&GraphMode,"");if (kbhit()) Sounds=CANNOT;setcolor(1);OutTextXY(10,10,"T etris");OutTextXY(30,30,"Version 2.0");OutTextXY(10,120,"Help:");OutTextXY(20,140,"+ :Faster");OutTextXY(20,160,"- :Slower");OutTextXY(20,180,"Esc :Quit");OutTextXY(20,200,"F1 :Help");OutTextXY(10,310,"Copyright(c) 1998.2.22"); OutTextXY(10,320,"By Mr. Unique");outtextxy(10,250,"Score: 00000");rectangle(BeginH-3,BeginS-3,BeginH+Heng*(Wid+2)+2,BeginS+Sh u*(Wid+2)+2);rectangle(BeginH-5,BeginS-5,BeginH+Heng*(Wid+2)+4,BeginS+Sh u*(Wid+2)+4);rectangle(BeginH+(Heng+4)*(Wid+2)-2,BeginS+10,BeginH+(Heng+8)*(Wid+2)+2,BeginS+12+4*(Wid+2));for (i=0;i<max;i++)< bdsfid="173" p=""></max;i++)<>for (j=0;j<max;j++)< bdsfid="175" p=""></max;j++)<>{Position[i][j]=1;middle[i][j]=-1;}for (i=0;i<heng;i++)< bdsfid="180" p=""></heng;i++)<> for (j=0;j<shu;j++)< bdsfid="182" p=""></shu;j++)<>Position[i][j]=0;for (i=0;i<heng;i++)< bdsfid="185" p=""></heng;i++)<> for (j=0;j<shu;j++)< bdsfid="187" p=""></shu;j++)<>DrawBox(i,j,0);randomize();}void GoOn(){for(;;){Seconds+=0.2; /*控制方块的下落速度*/ if (Seconds>=Delays) {Down();Seconds=0;if (NoPass==BOTTOM){DetectFill();middle[ActH][ActS]=Act;if (ActS==0)Fail();return;}}if (kbhit())Select();}}void Down() /*方块下降*/{Display(0);if (Touch(ActH,ActS,0,1)==CAN)ActS++;elsemiddle[ActH][ActS]=Act;Display(Staus+1);}int Touch(int x,int y,int dx,int dy) {NoPass=CAN;for (i=0;i<4;i++)for (j=0;j<4;j++)Position[x+dx+i][y+dy+j]+=b[i][j]; for (i=0;i<max;i++)< bdsfid="226" p=""></max;i++)<>for (j=0;j<max;j++)< bdsfid="228" p=""></max;j++)<>if (Position[i][j]>1)NoPass=CANNOT;for (i=0;i<4;i++)for (j=0;j<4;j++){Position[x+dx+i][y+dy+j]-=b[i][j];middle[x+dx+i][y+dy+j]=Act;if (NoPass==CANNOT && dx==0 && dy==1) { for (i=0;i<4;i++)for (j=0;j<4;j++)Position[x+i][y+j]+=b[i][j];NoPass=BOTTOM;}return NoPass;}int GetKey(void){int Ch,Low,Hig;Ch=bioskey(0);Low=Ch&0x00ff;Hig=(Ch&0xff00)>>8;return(Low==0?Hig+256:Low);}void Select(){int OldStaus,acts=ActS;switch(GetKey())case ESC :Quit();break;case DOWN :Seconds+=14500;break;case LEFT :Display(0);if (ActH>0 && Touch(ActH,ActS,-1,0)==CAN) { ActH--;}Display(Act+1);break;case RIGHT :Display(0);if (ActH<="" bdsfid="262" p="" touch(acth,acts,1,0)="=CAN)" {="">Display(Act+1);break;case BLANK : Display(0);ksdown();Display(Act+1);break;case F1 :Help();break;case EQUAL :case ADD :if (Delays>300) Delays-=100;break; case DEC :if (Delays<3000) Delays+=100;break; case PAUSEP :case PAUSEp :getch();break;case SOUNDS :case SOUNDs :if (Sounds==CAN)Sounds=CANNOT;elseSounds=CAN;break;case UP :if(Act==7){while(acts<shu-1&&position[acth][acts]!=1)< bdsfid="280" p=""></shu-1&&position[acth][acts]!=1)<>acts++;Position[ActH][acts]=0;DrawBox(ActH,acts,0);acts=ActS;break;}else{Display(0);OldStaus=Staus;switch(Act){case 0:case 3:case 4:if (Staus==1) Staus=0;else Staus=1;break; case 1:break;case 2:case 5:case 6:if (Staus==3) Staus=0;else Staus++;break; } Give();if (Touch(ActH,ActS,0,0)==CANNOT){Staus=OldStaus;Give();}Display(Act+1);break;}}}void ksdown(){while(flag){if(Touch(ActH,ActS,0,0)==CAN){ActS++;}else {ActS--;flag=0;}}flag=1;}void Quit(){int ch,TopScore;FILE *fp;if ((fp=fopen("Russian.scr","r+"))!=NULL) {fscanf(fp,"%d",&T opScore);if (Scores>TopScore){setcolor(1);outtextxy(470,80,"Hello !");outtextxy(470,100,"In all the players,"); outtextxy(470,120,"You are the First !"); outtextxy(470,140,"And your score will"); outtextxy(470,160,"be the NEW RECORD !"); fseek(fp,0L,0);fprintf(fp,"%d",Scores);fclose(fp);}setcolor(1);OutTextXY(470,220,"Are You Sure (Yes/no)?"); ch=getch();if (ch=='y'||ch=='Y'){closegraph();delay(20);exit(0);}setcolor(0);outtextxy(470,220,"Are You Sure (Yes/no)?"); }void OutTextXY(int x,int y,char *String) {int i=0;char a[2];moveto(x,y);a[1]='\0';while (*(String+i)!='\0')a[0]=*(String+i);outtext(a);if (Sounds==CAN && a[0]!=' ') {sound(3000);delay(50);nosound();}i++;}}void Help(){unsigned Save;void *Buf;Save=imagesize(160,120,500,360); Buf=malloc(Save);getimage(160,120,500,360,Buf); setfillstyle(1,1);bar(160,120,500,280);setcolor(0);OutTextXY(170,130," About & Help");OutTextXY(170,150," # # # ########## # # # "); OutTextXY(170,160," # ## # # # # # # ###### ### "); OutTextXY(170,170," ########## ########## ## # # ");OutTextXY(170,180," # # # # # # # ## #### "); OutTextXY(170,190," # ## # #### ## # # # "); OutTextXY(170,200," # ## # # # # # ## # # # "); OutTextXY(170,210," # # # ## ## # ###### # # # "); OutTextXY(170,220," ## # ## # ## # # # # "); OutTextXY(170,230," # ## # #### # ## # "); OutTextXY(170,260," Good Luckly to You ");getch();putimage(160,120,Buf,0);free(Buf);}void GetScores(){int Sec10000,Sec1000,Sec100,Sec10,Sec1;setfillstyle(0,1);bar(60,250,109,260);Sec1=Scores%10;Sec10=(Scores%100-Scores%10)/10;Sec100=(Scores%1000-Scores%100)/100;Sec1000=(Scores%10000-Scores%1000)/1000;Sec10000=(Scores%100000-Scores%10000)/10000; DispScore(60,250,'0'+Sec10000);DispScore(70,250,'0'+Sec1000);DispScore(80,250,'0'+Sec100);DispScore(90,250,'0'+Sec10);DispScore(100,250,'0'+Sec1);DispScore(110,250,'0');DispScore(120,250,'0');}void DispScore(int x,int y,char Ch)char a[2];a[1]='\0';a[0]=Ch;outtextxy(x,y,a);}void Give(){for (i=0;i<4;i++)for (j=0;j<4;j++)b[i][j]=a[Act][Staus][i][j];}void Display(int color){for (i=0;i<4;i++)for (j=0;j<4;j++)if (b[i][j]==1) DrawBox(ActH+i,ActS+j,color); } void DrawBox(int x,int y,int Color){x=BeginH+x*(Wid+2);y=BeginS+y*(Wid+2);setfillstyle(1,Color);bar(x+2,y+2,x+Wid-1,y+Wid-1);if (Color==0)setcolor(9);elsesetcolor(Act+1);rectangle(x+4,y+4,x+Wid-4,y+Wid-4);}void DrawNext(int Color)。
VC++ 6.0 MFC 俄罗斯方块 自动求解 代码 源程序
#include <windows.h>#include <time.h>#include <stdlib.h>#include <stdio.h>#define tDown 1 //方块下落定时器的标识(编号)#define tPaint 2 //重绘定时器的标识(编号)#define tDownTime 500 //方块下落一行位置的时间间隔#define tPaintTime 50 //窗口重绘的时间间隔#define ROW 24 //地图的行数目(第23行不用)#define COL 14 //地图的列数目(第0列和第13列不用)#define MAX_CLASS 7 //方块形状数目#define LEN 20 //每个方格大小为20×20像素#define StartY -1 * LEN + 5 //-15,绘制俄罗斯方块地图时的边界起始位置#define StartX -1 * LEN + 5 //-15int iDeleteRows = 0; //总共清除的行int iTotalNum = 0; //总得分char WindowTxt[100] = "俄罗斯方块游戏自动求解已关闭"; //窗口标题char s1[] = "关闭", s2[] = "启动"; //用于启动/关闭自动求解功能时显示不同的标题bool bAuto; //是否自动求解的标志bool Pause; //是否暂停的标志int Map[ROW][COL]; //俄罗斯方块的地图(被占据的方格为1,否则为0) int CurrentBox[4][4]; //当前落下的方块int CurrentY, CurrentX; //当前落下方块的当前位置(指左上角位置)int NextBox[4][4]; //下一个将落下的方块int Box[MAX_CLASS][4][4] = //7种方块形状{{{0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0}},{{0,0,0,0},{0,1,0,0},{1,1,1,0},{0,0,0,0}},{{0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0}},{{0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0}},{{0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0}},{{0,1,1,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}{{0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0}}};void InitMap( ); //初始化地图int NewFall( ); //新的方块落下void BuildNextBox( ); //产生下一个随机的方块int Test( int y, int x, int box[4][4] ); //测试在(y,x)位置是否能放置方块box,能放置返回1,否则返回0int Drop( ); //定时时间到,当前方块下降一行位置void PutBox( ); //放置当前方块int Move( int Right ); //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动void Clear( ); //清除满足条件的行int Rotate( ); //测试旋转是否可行,如果可行则旋转当前方块int RotateTest( int Box1[4][4], int Box2[4][4] ); //旋转当前方块int count1( int y, int x, int box[4][4] ); //新增函数int BestStartX( ); //新增函数LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); //窗口处理函数声明int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow ) //入口函数{static TCHAR szAppName[ ] = TEXT ("Russion");HWND hwnd;MSG msg;WNDCLASS wndclass;wndclass.style = CS_HREDRAW | CS_VREDRAW;wndclass.lpfnWndProc = WndProc;wndclass.cbClsExtra = 0;wndclass.cbWndExtra = 0;wndclass.hInstance = hInstance;wndclass.hIcon = LoadIcon( NULL, IDI_APPLICATION );wndclass.hCursor = LoadCursor( NULL, IDC_ARROW );wndclass.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );wndclass.lpszMenuName = NULL;wndclass.lpszClassName = szAppName;if( !RegisterClass( &wndclass ) ){MessageBox( NULL, TEXT ("Program requires Windows NT!" ),szAppName, MB_ICONERROR );return 0;}hwnd = CreateWindow( szAppName, WindowTxt,WS_OVERLAPPED | WS_SYSMENU | WS_BORDER,CW_USEDEFAULT, CW_USEDEFAULT,(COL + 4) * LEN, //窗口宽度:(14+4)×20=360像素ROW * LEN, //窗口高度:24×20=480像素(包括标题栏部分)NULL, NULL, hInstance, NULL );ShowWindow( hwnd, iCmdShow );UpdateWindow( hwnd );while( GetMessage( &msg, NULL, 0, 0 ) ){TranslateMessage( &msg );DispatchMessage( &msg );}return msg.wParam;}//初始化地图(将第0列和第13列、第23行设置为1(被占据),其他位置设置为0) void InitMap( ){int y, x;for( y = 0; y < ROW; y++ ){for( x = 0; x < COL; x++ ){//第0列、第13列、第23行设置为1(被占据)if( x < 1 || x > COL - 2 || y > ROW - 2 )Map[y][x] = 1;else Map[y][x] = 0;}}}//计算在(y,x)位置(左上角位置)上放置方块box后空出的方格数int count1( int y, int x, int box[4][4] ){if( !Test(y,x,box) ) return 100; //不能在(y,x)位置放置box,返回∞if( Test(y+1,x,box) ) return 100; //如果box还能下降,也返回∞int tmpy, tmpx;int c = 0; //空出的方格数for( tmpx = 0; tmpx < 4; tmpx++ ) //考虑第0~3列{for( tmpy = 3; tmpy >= 0; tmpy-- ){if( box[tmpy][tmpx] ) break;}tmpy++;if( tmpy>0 ){for( ; tmpy<4; tmpy++ ){if( tmpy+y<0 || tmpy+y>=ROW || tmpx+x<0 || tmpx+x>=COL ) continue;if(!Map[tmpy+y][tmpx+x]) c++; //空出的方格}}}return c;}//当启动自动求解功能时,求下一个方块的最佳下降位置//策略1为:放置后,空出的方格数最少,为MinC1,此时能达到最高位置为MaxY1,该位置为BestX1;//策略2为:放置后,能下降的位置最高,为MaxY2,此时空出的方格数为MinC2,该位置为BestX2;//必有MaxY1<=MaxY2, MinC1>=MinC2//取二者的折衷,策略为:优先采取策略1,但如果MinC2==MinC1或MaxY2>=MaxY1+2,则取策略2int BestStartX( ){int X, Y, tmpx, tmpy; //循环变量int BestX = 0, MaxY = 0, MinC = 100;//最终所求的最佳下降位置int BestX1, MaxY1, MinC1; //策略1:MinC:最佳位置处放置方块时,空出的空格最少,BestX:最佳下降位置,MaxY:能下降到的位置int BestX2, MaxY2, MinC2; //策略2:最佳位置为能下降的位置最高int c; //以上策略求最值时用到的辅助变量int tBox1[4][4], tBox2[4][4]; //tBox2为实现旋转时用到的临时变量int Rotates = 0, Rotates1 = 0, Rotates2 = 0;//找到最佳位置后,当前方块需要旋转的次数int Last1, Last2; //Last1为下一个方块未旋转时最下一个方格所在的行,Last2为旋转后最下一个方格所在的行memcpy(tBox1, NextBox, sizeof(tBox1)); memcpy(tBox2, NextBox, sizeof(tBox1)); for( tmpy=3; tmpy>=0; tmpy-- ) //统计tBox1中最下一个方格所在的行{for( tmpx=0; tmpx<4; tmpx++ ) if(tBox1[tmpy][tmpx]) break;if(tmpx<4) break;}Last1 = tmpy;BestX1 = 0, MaxY1 = 0, MinC1 = 100; BestX2 = 0, MaxY2 = 0, MinC2 = 100;//枚举从第0~COL-4列下落for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last1>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last1;if( Y+Last1>MaxY2 || Y+Last1==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last1;}//第1次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 1;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 1;}//第2次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 2;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 2;}//第3次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 3;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 3;}MinC = MinC1, BestX = BestX1, MaxY = MaxY1, Rotates = Rotates1;if( MinC2==MinC1 || MaxY2>=MaxY1+2 )MinC = MinC2, BestX = BestX2, MaxY = MaxY2, Rotates = Rotates2;if( Rotates>0 ){for( int i=0; i<Rotates; i++ ){RotateTest(NextBox, tBox1);memcpy(NextBox, tBox1, sizeof(tBox1));}}return BestX;}int NewFall( ) //新的方块落下(如果能落下返回1,否则不能落下返回0(程序就该结束了)) {int y, x;CurrentY = 0; //当前方块的当前位置是指该方块(4×4大小)的左上角所在位置if(bAuto) CurrentX = BestStartX( );else CurrentX = COL / 2 - 2; //初始为(0,5)for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = NextBox[y][x];}BuildNextBox( ); //产生下一个随机的方块return Test( CurrentY, CurrentX, CurrentBox );}int no[400] = {3,3,5,1};void BuildNextBox( ) //产生下一个随机的方块{static int j=0;int i, y, x;i = rand()%MAX_CLASS; //随机生成0~6的整数for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )NextBox[y][x] = Box[i][y][x];}}//测试在(y,x)位置(左上角位置)是否能放置方块box,能放置返回1,否则返回0int Test( int y, int x, int box[4][4] ){int tmpy, tmpx;for( tmpy = 0; tmpy < 4; tmpy++ ){for( tmpx = 0; tmpx < 4; tmpx++ ){if( Map[tmpy + y][tmpx + x] && box[tmpy][tmpx] )return 0;}}return 1;}int Drop( ) //定时时间到,当前方块下降一行位置(如果能下降返回1,否则返回0){int NewY;NewY = CurrentY + 1;if( Test( NewY, CurrentX, CurrentBox ) ){CurrentY = NewY;return 1;}return 0;}void PutBox( ) //在当前位置(CurrentY,CurrentX)放置当前方块(此时当前方块已经不能下降了){int y, x;for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] )Map[CurrentY + y][CurrentX + x] = CurrentBox[y][x];}}}int Move( int Right ) //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动{int x;if( Right ) x = CurrentX + 1; //向右移动一列位置else x = CurrentX - 1; //向左移动一列位置if( Test( CurrentY, x, CurrentBox ) ){CurrentX = x;return 1;}return 0;}void Clear( ) //清除满足条件的行{int y, x; //循环变量int DelY, DelX; //循环变量int Full; //一行是否满的标志for( y = 0; y < ROW - 1; y++ ) //检查第0~22行{Full = 1;for( x = 1; x < COL - 1; x++ ) //检查每行的第1~12列{if( !Map[y][x] ){Full = 0; break;}}if( Full ) //第y行满了,删除该行,该行以上的其他行下移一行{iDeleteRows++; iTotalNum = iDeleteRows*100; //更新得分for( DelY = y; DelY > 0; DelY-- ){for( DelX = 1; DelX < COL - 1; DelX++ )Map[DelY][DelX] = Map[DelY-1][DelX];}for( DelX = 1; DelX < COL - 1; DelX++ ) //第0行置为0Map[0][DelX] = 0;}}}int Rotate( ) //测试旋转是否可行,如果可行则旋转当前方块{int y, x;int TmpBox[4][4];RotateTest( CurrentBox, TmpBox );if( Test( CurrentY, CurrentX, TmpBox ) ){for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = TmpBox[y][x];}return 1;}else return 0;}/*0000 0000 0000 //旋转规律是:Box3[y][x] = Box1[y][3-x] -> 方块绕竖直方向对称变换0100-> 0010-> 0010 //Box2[x][y] = Box3[y][x] -> 沿着主对角线对称变换(相当于矩阵转置)1110 0111 01100000 0000 0010 */int RotateTest( int Box1[4][4], int Box2[4][4] ) //旋转当前方块{ //新增返回值为:旋转后的Box2中最下一个方格所在的行int y, x;for( y = 0; y < 4; y++ ){for( x = 3; x >=0; x-- )Box2[x][y] = Box1[y][3 - x];}for( y=3; y>=0; y-- ) //统计Box2中最下一个方格所在的行{for( x=0; x<4; x++ ){if(Box2[y][x]) break;}if(x<4) break;}return y;}LRESULT CALLBACK WndProc( HWND hwnd, UINT message, //窗口处理函数WPARAM wParam, LPARAM lParam ){HDC hdc, hdcMem;int y, x;PAINTSTRUCT ps;HBITMAP hBitMap;HPEN hPen;HBRUSH hBrush;static int cxClient, cyClient; //窗口客户区宽度和高度char str[20]; //用于显示得分的变量switch( message ){case WM_CREATE:SetTimer( hwnd, tDown, tDownTime, NULL ); //开启两个定时器SetTimer( hwnd, tPaint, tPaintTime, NULL );srand( (unsigned)time( NULL ) );bAuto = false;Pause = false;InitMap( );BuildNextBox( ); //先随机产生一个方块NewFall( ); //方块落下并随机产生下一个方块sprintf( str, " 得分:%d", iTotalNum ); strcat( WindowTxt, str );SetWindowText(hwnd,WindowTxt);return 0;case WM_SIZE:cxClient = LOWORD( lParam ); //取得窗口客户区宽度和高度cyClient = HIWORD( lParam );return 0;case WM_TIMER:switch( wParam ){case tDown: //下降定时器if( !Drop( ) ) //如果不能下降则放置当前方块{PutBox( );MessageBeep( -1 );Clear( ); //清除//刷新得分sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}}break;case tPaint: //重绘定时器InvalidateRect(hwnd, NULL, FALSE); //强制重绘窗口工作区break;}case WM_KEYDOWN:switch( wParam ){case VK_LEFT: //"向左"方向键if(bAuto) break;Move(0); break;case VK_RIGHT: //"向右"方向键if(bAuto) break;Move(1); break;case VK_UP: //"向上"方向键:旋转if(bAuto) break;Rotate( ); break;case VK_DOWN: //"向下"方向键:当前方块下移一行位置if(bAuto) break;MessageBeep( -1 ); Drop( ); break;case VK_RETURN: //回车键:暂停Pause = !Pause;if( Pause ) //暂停、自动求解时也可以暂停KillTimer( hwnd, tDown );else //启动{if(bAuto) SetTimer( hwnd, tDown, tDownTime/5, NULL );else SetTimer( hwnd, tDown, tDownTime, NULL );}break;case VK_SPACE:if(bAuto) break;while( 1 ) //使用永真循环,使得当前方块一直下降到不能下降为止{if( !Drop( ) ){PutBox( ); Clear( );sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}break;}}break;case VK_F1:bAuto = !bAuto;if(bAuto) //自动求解{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime/5, NULL );memcpy( WindowTxt+25, s2, strlen(s2) ); //修改标题}else{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime, NULL );memcpy( WindowTxt+25, s1, strlen(s1) ); //修改标题}SetWindowText(hwnd,WindowTxt);break;}case WM_PAINT: //重绘窗口工作区hdc = BeginPaint( hwnd, &ps );hdcMem = CreateCompatibleDC( hdc );hBitMap = CreateCompatibleBitmap( hdc, cxClient, cyClient );SelectObject( hdcMem, hBitMap );//画地图最外面的矩形(4, 4, 246, 446)Rectangle( hdcMem, StartX + LEN * 1 - 1,StartY + LEN * 1 - 1,StartX + LEN * (COL - 1) + 1, StartY + LEN * (ROW - 1) + 1 );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) );SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(250, 250, 250) );SelectObject( hdcMem, hBrush );for( y = 1; y < ROW - 1; y++ ) //画地图中的每一格{for( x = 1; x < COL - 1; x++ ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX + LEN * (x + 1), StartY + LEN * (y + 1) );}}DeleteObject( hPen );DeleteObject( hBrush );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) ); SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(255, 100, 100) );SelectObject(hdcMem, hBrush);for( y = 1; y < ROW - 1; y++ ) //画出地图中每个被占据的方格{for( x = 1; x < COL - 1; x++ ){if( Map[y][x] ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX +LEN * (x + 1), StartY + LEN * (y + 1) );}}}for( y = 0; y < 4; y++ ) //画当前方块{for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] ){if( y + CurrentY > 0 ){Rectangle( hdcMem, (x + CurrentX) * LEN + StartX,(y + CurrentY) * LEN +StartY,(x + CurrentX + 1) * LEN + StartX,(y + CurrentY + 1) * LEN + StartY );}}}}for( y = 0; y < 4; y++ )//在窗口右边区域画下一个方块{for( x = 0; x < 4; x++ ){if( NextBox[y][x] ){Rectangle( hdcMem, (x + COL) * LEN + StartX,(y + 2) * LEN + StartY,(x+ COL + 1) * LEN + StartX, (y + 3) * LEN + StartY );}}}DeleteObject( hPen );DeleteObject( hBrush );DeleteObject( hBitMap );BitBlt( hdc, 0, 0, cxClient, cyClient, hdcMem, 0, 0, SRCCOPY );DeleteDC( hdcMem );EndPaint( hwnd, &ps );return 0;case WM_DESTROY:KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );PostQuitMessage( 0 );return 0;}//end of switch( message )return DefWindowProc( hwnd, message, wParam, lParam );}。
VC+俄罗斯方块课程设计报告源代码
课程设计报告文档题目:俄罗斯方块一.引言1、编写目的:通过本课程设计,使学生巩固面向对象程序设计的基本概念、原理和技术,学会使用Visual C++开发工具进行简单面向对象程序的开发,将理论与实际相结合,完成一个小型面向对象程序的设计与实现,并在此基础上强化学生的实践意识,提高其实际动手能力和创新能力。
2、.定义:无3、参考资料:郑莉.C++语言程序设计.北京:清华大学出版社,2003罗建军.大学Visual C++程序设计案例教程.北京:高等教育出版社,2004刘路放.Visual C++与面向对象程序设计教程.北京:高等教育出版社,2000David J.Visual C++技术内幕.潘爱民印译.北京:清华大学出版社,1999侯俊杰.深入浅出MFC.武汉:华中科技大学出版社,2001二.任务的描述:1.目标:编写基于VC++开发工具并能通过键盘和鼠标进行人机交流俄罗斯方块游戏,界面友好,容易操作的游戏。
2.功能描述:通过控制键盘可以进行游戏的开始、暂停、结束;能够控制方块的移动、变形;具有进行经典的俄罗斯方块游戏的一般功能。
3.性能描述(1)数据精确度:无(2)时间特性:无4.运行环境:windows98以上操作系统5.条件与限制:硬件:装有Windows操作系统的计算机软件:Microsoft Visual Studio 6.0、Microsoft Visual Studio 2005三.任务设计1、程序的整个流程图2NN4(1)类1:(2)类2:数据成员: 成员函数:1、 2、 3、 4、(3)类3:数据成员:int m_oldArea; 区域大小 int m_o ldLevel;等级int m_oldBlockSytle;背景风格 BOOL m_oldDrawGrid; 成员函数:1、COptionDlg ()初始化界面:用户选择的区域大小代码,及级别代码,方块样式2、DoDataExchange3、Onok ()OK 按钮(ID 是IDOK 按钮动作。
俄罗斯方块代码
VC6.0环境下的俄罗斯方块C语言源代码2011-5-15 12:31提问者:wobuzy1|浏览次数:2804次我来帮他解答2011-5-15 12:35满意回答#include <stdlib.h>#include <graphics.h>#include <bios.h>#define mDRAW 5#define mLINE 6#define mADOWN 7#define mGEN 8#define mLEFT 75#define mRIGHT 77#define mSPACE 57#define mDOWN 80#define mESC 1#define TIMEINT 2#define MAXX 9#define MAXY 30#define BACKCOLOR BLACK#define WINX 50#define WINY 470#define GAP 6#define AREAX (WINX+GAP)#define AREAY (WINY-GAP)#define BOXW 15int oldarea[MAXY+1][MAXX];int area[MAXY+1][MAXX];int actW,actH,actX,actY;int curX,curY,curColor,curW,curH;int newX,newY,newColor,newW,newH; int active;int box[4][4];int FORCOLOR;int MESSAGE;int BOX[7][4][4]={{{1,1,1,1},{0,0,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,1,0}, {1,0,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,1,0}, {0,0,1,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,1,0}, {0,1,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,0,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0} },{{0,1,1,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,0,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0}}};void init(); void draw(); int genBox(); int getKey(); void lineFull(); int moveLeft();int moveRight();int moveDown();int rotate();int getW();int getH();void clearOldBox();void putNewBox();int collisionRotate(int box[][4]); void getMessage();void dispatchMessage();int timeCome();void fallDown();int gameOver();main(){int i;init();do{getMessage(); dispatchMessage();}while(!gameOver());getch();closegraph();}void getMessage(){if(MESSAGE) return;if(timeCome()){MESSAGE=mADOWN; return;}if(bioskey(1)){MESSAGE=bioskey(0)>>8; return;}}void dispatchMessage(){switch(MESSAGE){case mLEFT: moveLeft();break; case mRIGHT: moveRight();break; case mADOWN: moveDown();break; case mSPACE: rotate();break;case mDOWN: fallDown(); break; case mDRAW: draw();break;case mLINE: lineFull();break;case mGEN: genBox();break; case mESC: closegraph(); exit(0); default: MESSAGE=0;}}void fallDown(){while(active){moveDown(); draw();}MESSAGE=mLINE;}int timeCome(){static long tm, old;tm=biostime(0,tm);if(tm-old<TIMEINT) return 0;else{old=tm; return 1;}}void init(){int i,j,x1,y1,x2,y2;int driver=DETECT, mode=0; randomize();registerbgidriver(EGAVGA_driver);initgraph(&driver,&mode,"");cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(0,0,639,479);x1=AREAX;y1=AREAY-BOXW*MAXY;x2=AREAX+MAXX*BOXW;y2=AREAY;rectangle(--x1,--y1,++x2,++y2);setfillstyle(SOLID_FILL,BLACK);bar(++x1,++y1,--x2,--y2);y1=AREAY-MAXY*BOXW; y2=AREAY; setcolor(DARKGRAY);for(i=0;i<MAXX;i++){x1=AREAX+i*BOXW;line(x1,y1,x1,y2);}x1=AREAX; x2=x1+MAXX*BOXW;for(j=0;j<MAXY;j++){y1=AREAY-j*BOXW;line(x1,y1,x2,y1);}for(j=0;j<MAXY;j++)for(i=0;i<MAXX;i++)area[j][i]=oldarea[j][i]=0;actX=0; actY=0; actW=MAXX-1; actH=MAXY-1; draw();MESSAGE=mGEN;}int genBox(){int i,j,boxidx;boxidx=random(7); FORCOLOR=random(7)+1; for(j=0;j<4;j++)for(i=0;i<4;i++)box[j][i]=BOX[boxidx][j][i];curW=getW(); curH=getH();curX=(MAXX+curW)/2;if(curX+curW>=MAXX)curX=MAXX-1-curW;curY=MAXY-1-curH;newX=curX; newY=curY; actX=curX;actY=curY;actW=newW=curW; actH=newH=curH;active=1;if(collision(box)) return 0;putNewBox();draw(); MESSAGE=0;return 1;}void lineFull(){int row,col, rowEnd,full,i,j;rowEnd=newY+newH;if(rowEnd>=MAXY-1) rowEnd=MAXY-2;for(row=newY; row<=rowEnd;){full=1;for(col=0;col<MAXX;col++)if(!area[row][col]){full=0; break;}if(!full){++row; continue;}for(j=row; j<MAXY-1;j++)for(i=0;i<MAXX;i++)area[j][i]=area[j+1][i];actX=0;actY=row; actW=MAXX-1; actH=MAXY-1-row;draw(); rowEnd--;}MESSAGE=mGEN;}void draw(){int row,col,x1,y1,x2,y2;for(row=actY;row<=actY+actH;row++)for(col=actX;col<=actX+actW;col++)if(area[row][col]!=oldarea[row][col]){if(area[row][col]==0)setfillstyle(SOLID_FILL,BACKCOLOR);elsesetfillstyle(SOLID_FILL,FORCOLOR);x1=AREAX+col*BOXW; x2=x1+BOXW;y1=AREAY-(row+1)*BOXW; y2=y1+BOXW;bar(++x1,++y1,--x2,--y2);oldarea[row][col]=area[row][col];}MESSAGE=0;}int moveLeft(){newX=curX-1; clearOldBox();if(collision(box)){newX=curX;putNewBox();MESSAGE=0;return 0;}putNewBox();actW=curW+1; actX=curX=newX; MESSAGE=mDRAW;return 1;}int moveRight(){newX=curX+1; clearOldBox();if(collision(box)){newX=curX;putNewBox();MESSAGE=0;return 0;}putNewBox();actW=curW+1; actX=curX; curX=newX; MESSAGE=mDRAW;return 1;}int moveDown(){int i,j;newY=curY-1;clearOldBox();if(collision(box)){newY=curY;putNewBox();active=0;MESSAGE=mLINE;return 0;}putNewBox();actH=curH+1; actY=newY; curY=newY;MESSAGE=mDRAW;return 1;}int rotate(){int newBox[4][4];int i,j;clearOldBox();for(j=0;j<4;j++)for(i=0;i<4;i++)newBox[j][i]=0;for(j=0;j<4;j++)for(i=0;i<4;i++)newBox[curW-i][j]=box[j][i];newW=curH; newH=curW;if(collisionRotate(newBox)){newW=curW; newH=curH; newX=curX; newY=curY;putNewBox();MESSAGE=0;return 0;}for(j=0;j<4;j++)for(i=0;i<4;i++)box[j][i]=newBox[j][i];putNewBox();actH=newH>curH? newH:curH;actW=curX+actH-newX;actX=newX; actY=newY; curX=newX;curY=newY; curW=newW; curH=newH;MESSAGE=mDRAW;return 1;}int getW(){int i,j;for(i=3;i>0;i--)for(j=0;j<4;j++)if(box[j][i]) return i;return 0;}int getH(){int i,j;for(j=3;j>0;j--)for(i=0;i<4;i++)if(box[j][i]) return j;return 0;}void clearOldBox(){int i,j;for(j=0;j<=curH; j++)for(i=0;i<=curW; i++)if(box[j][i])area[curY+j][curX+i]=0;}void putNewBox(){int i,j;for(j=0;j<=newH;j++)for(i=0;i<=newW;i++)if(box[j][i])area[newY+j][newX+i]=FORCOLOR; }int collision(int cbox[][4]){int i,j;if(newX<0) return 1;if(newX+newW>=MAXX) return 1;if(newY<0) return 1;for(j=0;j<=newH;j++)for(i=0;i<=newW;i++)if(area[newY+j][newX+i]&&cbox[j][i]) return 1;return 0;}int collisionRotate(int cbox[][4]){int i,j;if(newX+newW>=MAXX) newX=MAXX-1-newW; if(newY+newH>=MAXY) newY=MAXY-1-newH; if(collision(cbox)) return 1;for(i=0;i<=newW;i++)for(j=0;j<=newH;j++)if(area[newY+j][newX+i]){newX-=newW-i+1; goto L;}L: return collision(cbox);}int gameOver(){if(!active &&(curY+curH>MAXY-3)) return 1; else return 0;}追问能有注释的不?。
俄罗斯方块python源代码
俄罗斯方块python源代码以下是一个简单的俄罗斯方块游戏的 Python 源代码。
该代码实现了以下功能:1. 游戏开始时随机生成一个俄罗斯方块方块。
2. 方块可以通过键盘上的箭头键进行移动,向下箭头键可以加速方块的下降速度。
3. 方块到达底部或者与其他方块重叠时,会固定在底部或其他方块上。
4. 当一行被填满时,该行会被删除,并增加玩家的得分。
5. 游戏在方块超过底部边界时结束。
以下是源代码:```import pygameimport random# 初始化 Pygamepygame.init()# 游戏窗口的宽度和高度WIDTH = 640HEIGHT = 480# 方块的大小BLOCK_SIZE = 20# 定义颜色BLACK = (0, 0, 0)WHITE = (255, 255, 255)BLUE = (0, 0, 255)RED = (255, 0, 0)GREEN = (0, 255, 0)# 创建游戏窗口screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("俄罗斯方块")# 创建字体对象font = pygame.font.SysFont(None, 30)# 定义方块的形状SHAPES = [[[1, 1],[1, 1]],[[1, 0],[1, 0],[1, 1]],[[0, 1],[0, 1],[1, 1]],[[1, 1, 0],[0, 1, 1]],[[0, 1, 1],[1, 1, 0]],[[1, 1, 1, 1]]]# 定义方块的颜色COLORS = [BLUE,RED,GREEN,WHITE,BLACK,BLUE]class Block:def __init__(self, x, y):self.x = xself.y = yself.shape = random.choice(SHAPES)self.color = random.choice(COLORS)def draw(self):for i in range(len(self.shape)):for j in range(len(self.shape[i])):if self.shape[i][j] != 0:pygame.draw.rect(screen, self.color, (self.x + j * BLOCK_SIZE, self.y + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))def move_down(self):self.y += BLOCK_SIZEdef move_left(self):self.x -= BLOCK_SIZEdef move_right(self):self.x += BLOCK_SIZEdef rotate(self):self.shape = [[self.shape[j][i] for j in range(len(self.shape))] for i in range(len(self.shape[0])-1, -1, -1)]def is_colliding(self, blocks):for i in range(len(self.shape)):for j in range(len(self.shape[i])):if self.shape[i][j] != 0:x = self.x + j * BLOCK_SIZEy = self.y + i * BLOCK_SIZEif y >= HEIGHT or x < 0 or x >= WIDTH:return Truefor block in blocks:if block != self and block.x == x and block.y == y: return Truereturn Falseclass Game:def __init__(self):self.score = 0self.blocks = []def new_block(self):self.blocks.append(Block(WIDTH // 2 - BLOCK_SIZE, 0))def remove_full_lines(self):y_values = [block.y for block in self.blocks]full_y_values = []for i in range(HEIGHT, 0, -BLOCK_SIZE):if y_values.count(i) == WIDTH // BLOCK_SIZE:full_y_values.append(i)if len(full_y_values) > 0:full_y_values.sort()for y in full_y_values:self.blocks = [block for block in self.blocks if block.y != y] for block in self.blocks:if block.y < y:block.move_down()self.score += 10def game_over(self):if any([block.y <= BLOCK_SIZE for block in self.blocks]):return Truereturn Falsedef draw(self):screen.fill(WHITE)for block in self.blocks:block.draw()pygame.draw.rect(screen, BLACK, (0, 0, WIDTH, HEIGHT), 4) score_text = font.render("Score: " + str(self.score), True, BLACK) screen.blit(score_text, (10, 10))pygame.display.update()def run(self):clock = pygame.time.Clock()running = Trueself.new_block()while running:clock.tick(10)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:self.blocks[-1].move_left()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_right()elif event.key == pygame.K_RIGHT:self.blocks[-1].move_right()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_left()elif event.key == pygame.K_DOWN:self.blocks[-1].move_down()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_up()elif event.key == pygame.K_UP:self.blocks[-1].rotate()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].y -= BLOCK_SIZEself.blocks.append(Block(WIDTH // 2 - BLOCK_SIZE, 0)) self.remove_full_lines()if self.game_over():running = Falseself.blocks[-1].move_down()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_up()self.blocks.append(Block(WIDTH // 2 - BLOCK_SIZE, 0)) self.remove_full_lines()if self.game_over():running = Falseself.draw()pygame.quit()if __name__ == "__main__":game = Game()game.run()```代码列表:1. 初始化 Pygame 和定义游戏窗口的宽度和高度。
用C语言写俄罗斯方块 源代码
// 程序名称:俄罗斯方块// 编译环境:Visual C++ 6.0,EasyX 2011惊蛰版// 程序编写:krissi <zhaoh1987@>// 最后更新:2010-12-18//#include "graphics.h"#include <conio.h>#include <time.h> /////////////////////////////////////////////// 定义常量、枚举量、结构体、全局变量/////////////////////////////////////////////#define WIDTH 10 // 游戏区宽度#define HEIGHT 22 // 游戏区高度#define SIZE 20 // 每个游戏区单位的实际像素// 定义操作类型enum CTRL{CTRL_ROTATE, // 方块旋转CTRL_LEFT, CTRL_RIGHT, CTRL_DOWN, // 方块左、右、下移动CTRL_SINK, // 方块沉底CTRL_QUIT // 退出游戏};// 定义绘制方块的方法enum DRAW{SHOW, // 显示方块HIDE, // 隐藏方块FIX // 固定方块};// 定义七种俄罗斯方块struct BLOCK{WORD dir[4]; // 方块的四个旋转状态COLORREF color; // 方块的颜色} g_Blocks[7] = { {0x0F00, 0x4444, 0x0F00, 0x4444, RED}, // I{0x0660, 0x0660, 0x0660, 0x0660, BLUE}, // 口{0x4460, 0x02E0, 0x0622, 0x0740, MAGENTA}, // L{0x2260, 0x0E20, 0x0644, 0x0470, YELLOW}, // 反L{0x0C60, 0x2640, 0x0C60, 0x2640, CYAN}, // Z{0x0360, 0x4620, 0x0360, 0x4620, GREEN}, // 反Z{0x4E00, 0x4C40, 0x0E40, 0x4640, BROWN}}; // T// 定义当前方块、下一个方块的信息struct BLOCKINFO{byte id; // 方块IDchar x, y; // 方块在游戏区中的坐标byte dir:2; // 方向} g_CurBlock, g_NextBlock;// 定义游戏区BYTE g_World[WIDTH][HEIGHT] = {0}; /////////////////////////////////////////////// 函数声明/////////////////////////////////////////////void Init(); // 初始化游戏void Quit(); // 退出游戏void NewGame(); // 开始新游戏void GameOver(); // 结束游戏CTRL GetControl(bool _onlyresettimer = false); // 获取控制命令void DispatchControl(CTRL _ctrl); // 分发控制命令void NewBlock(); // 生成新的方块bool CheckBlock(BLOCKINFO _block); // 检测指定方块是否可以放下void DrawBlock(BLOCKINFO _block, DRAW _draw = SHOW); // 画方块void OnRotate(); // 旋转方块void OnLeft(); // 左移方块void OnRight(); // 右移方块void OnDown(); // 下移方块void OnSink(); // 沉底方块/////////////////////////////////////////////// 函数定义/////////////////////////////////////////////// 主函数void main(){Init(); CTRL c;while(true){c = GetControl();DispatchControl(c); // 按退出时,显示对话框咨询用户是否退出if (c == CTRL_QUIT){HWND wnd = GetHWnd();if (MessageBox(wnd, "您要退出游戏吗?", "提醒", MB_OKCANCEL | MB_ICONQUESTION) == IDOK)Quit();}}}// 初始化游戏void Init(){initgraph(640, 480);srand((unsigned)time(NULL)); // 显示操作说明setfont(14, 0, "宋体");outtextxy(20, 330, "操作说明");outtextxy(20, 350, "上:旋转");outtextxy(20, 370, "左:左移");outtextxy(20, 390, "右:右移");outtextxy(20, 410, "下:下移");outtextxy(20, 430, "空格:沉底");outtextxy(20, 450, "ESC:退出"); // 设置坐标原点setorigin(220, 20); // 绘制游戏区边界rectangle(-1, -1, WIDTH * SIZE, HEIGHT * SIZE);rectangle((WIDTH + 1) * SIZE - 1, -1, (WIDTH + 5) * SIZE, 4 * SIZE); // 开始新游戏NewGame();}// 退出游戏void Quit(){closegraph();exit(0);}// 开始新游戏void NewGame(){// 清空游戏区setfillstyle(BLACK);bar(0, 0, WIDTH * SIZE - 1, HEIGHT * SIZE - 1);ZeroMemory(g_World, WIDTH * HEIGHT); // 生成下一个方块g_NextBlock.id = rand() % 7;g_NextBlock.dir = rand() % 4;g_NextBlock.x = WIDTH + 1;g_NextBlock.y = HEIGHT - 1; // 获取新方块NewBlock();}// 结束游戏void GameOver(){HWND wnd = GetHWnd();if (MessageBox(wnd, "游戏结束。
C语言课程设计俄罗斯方块源代码
函数和模块化编程
函数定义:C语言中的函数 是完成特定任务的独立代码
块
添加标题
函数参数:函数可以接受参 数,参数可以是变量、常量
或表达式
添加标题
模块化编程:将大型程序分 解为多个模块,每个模块完
成特定的任务
模块测试:对每个模块进行 单独测试,确保其正确性和
稳定性
添加标题Βιβλιοθήκη 添加标题添加标题添加标题
函数调用:通过函数名和参 数列表来调用函数
游戏界面:包括游戏区域、得分、等级、 下一块等元素
等级:使用全局变量记录,每消除一定 行增加一级
游戏区域:使用二维数组表示,每个元 素对应一个方块
下一块:使用数组表示,每次随机生成 一个新的方块
得分:使用全局变量记录,每次消除一 行增加一定分数
游戏结束:当游戏区域被填满时,游戏 结束,显示游戏结束界面
调试过程和方法
确定问题:找出俄罗斯方块游戏中存在的问题 定位问题:确定问题的具体位置和原因 修复问题:根据问题原因进行修复 测试修复:测试修复后的游戏是否正常运行 重复以上步骤,直到游戏运行正常 记录调试过程和方法,以便于后续维护和改进
测试结果的分析和总结
测试方法:单元测试、集成 测试、系统测试
游戏规则和玩法
游戏目标:消除方块,避免堆积到顶部 游戏操作:通过移动、旋转和下落方块来消除 游戏结束:当方块堆积到顶部时,游戏结束 游戏得分:根据消除的方块数量和难度来计算得分
游戏历史和发展
俄罗斯方块诞生于1984年,由苏联程序员阿列克谢·帕基特诺夫发明
1989年,俄罗斯方块被移植到任天堂Game Boy游戏机上,成为全球最畅 销的游戏之一
测试工具:JUnit、 TestNG、Se lenium 等
俄罗斯方块C语言源代码
}
}
/* 在图形模式下的清屏 */
void cls()
{
setfillstyle(SOLID_FILL,0);
setcolor(0);
bar(0,0,640,480);
}
/*在图形模式下的高级清屏*/
void clscr(int a,int b,int c,int d,int color){
{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}},
{
{1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},
{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},
{1,1,1,0,0,0,1,0,0,0,0,0,(SOLID_FILL,color);
setcolor(color);
bar(a,b,c,d);
}
/*最小方块的绘制*/
void minbox(int asc,int bsc,int color,int bdcolor){
int a=0,b=0;
a=SCCOL+asc;
#define VK_ESC 0x011b
#define VK_ENTER 0x1c0d
/* 定义俄罗斯方块的方向(我定义他为4种)*/
#define F_DONG 0
#define F_NAN 1
#define F_XI 2
#define F_BEI 3
#define NEXTCOL 20 /* 要出的下一个方块的纵坐标*/
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include <windows.h>#include <time.h>#include <stdlib.h>#include <stdio.h>#define tDown 1 //方块下落定时器的标识(编号)#define tPaint 2 //重绘定时器的标识(编号)#define tDownTime 500 //方块下落一行位置的时间间隔#define tPaintTime 50 //窗口重绘的时间间隔#define ROW 24 //地图的行数目(第23行不用)#define COL 14 //地图的列数目(第0列和第13列不用)#define MAX_CLASS 7 //方块形状数目#define LEN 20 //每个方格大小为20×20像素#define StartY -1 * LEN + 5 //-15,绘制俄罗斯方块地图时的边界起始位置#define StartX -1 * LEN + 5 //-15int iDeleteRows = 0; //总共清除的行int iTotalNum = 0; //总得分char WindowTxt[100] = "俄罗斯方块游戏自动求解已关闭"; //窗口标题char s1[] = "关闭", s2[] = "启动"; //用于启动/关闭自动求解功能时显示不同的标题bool bAuto; //是否自动求解的标志bool Pause; //是否暂停的标志int Map[ROW][COL]; //俄罗斯方块的地图(被占据的方格为1,否则为0) int CurrentBox[4][4]; //当前落下的方块int CurrentY, CurrentX; //当前落下方块的当前位置(指左上角位置)int NextBox[4][4]; //下一个将落下的方块int Box[MAX_CLASS][4][4] = //7种方块形状{{{0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0}},{{0,0,0,0},{0,1,0,0},{1,1,1,0},{0,0,0,0}},{{0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0}},{{0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0}},{{0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0}},{{0,1,1,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}{{0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0}}};void InitMap( ); //初始化地图int NewFall( ); //新的方块落下void BuildNextBox( ); //产生下一个随机的方块int Test( int y, int x, int box[4][4] ); //测试在(y,x)位置是否能放置方块box,能放置返回1,否则返回0int Drop( ); //定时时间到,当前方块下降一行位置void PutBox( ); //放置当前方块int Move( int Right ); //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动void Clear( ); //清除满足条件的行int Rotate( ); //测试旋转是否可行,如果可行则旋转当前方块int RotateTest( int Box1[4][4], int Box2[4][4] ); //旋转当前方块int count1( int y, int x, int box[4][4] ); //新增函数int BestStartX( ); //新增函数LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); //窗口处理函数声明int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow ) //入口函数{static TCHAR szAppName[ ] = TEXT ("Russion");HWND hwnd;MSG msg;WNDCLASS wndclass;wndclass.style = CS_HREDRAW | CS_VREDRAW;wndclass.lpfnWndProc = WndProc;wndclass.cbClsExtra = 0;wndclass.cbWndExtra = 0;wndclass.hInstance = hInstance;wndclass.hIcon = LoadIcon( NULL, IDI_APPLICATION );wndclass.hCursor = LoadCursor( NULL, IDC_ARROW );wndclass.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );wndclass.lpszMenuName = NULL;wndclass.lpszClassName = szAppName;if( !RegisterClass( &wndclass ) ){MessageBox( NULL, TEXT ("Program requires Windows NT!" ),szAppName, MB_ICONERROR );return 0;}hwnd = CreateWindow( szAppName, WindowTxt,WS_OVERLAPPED | WS_SYSMENU | WS_BORDER,CW_USEDEFAULT, CW_USEDEFAULT,(COL + 4) * LEN, //窗口宽度:(14+4)×20=360像素ROW * LEN, //窗口高度:24×20=480像素(包括标题栏部分)NULL, NULL, hInstance, NULL );ShowWindow( hwnd, iCmdShow );UpdateWindow( hwnd );while( GetMessage( &msg, NULL, 0, 0 ) ){TranslateMessage( &msg );DispatchMessage( &msg );}return msg.wParam;}//初始化地图(将第0列和第13列、第23行设置为1(被占据),其他位置设置为0) void InitMap( ){int y, x;for( y = 0; y < ROW; y++ ){for( x = 0; x < COL; x++ ){//第0列、第13列、第23行设置为1(被占据)if( x < 1 || x > COL - 2 || y > ROW - 2 )Map[y][x] = 1;else Map[y][x] = 0;}}}//计算在(y,x)位置(左上角位置)上放置方块box后空出的方格数int count1( int y, int x, int box[4][4] ){if( !Test(y,x,box) ) return 100; //不能在(y,x)位置放置box,返回∞if( Test(y+1,x,box) ) return 100; //如果box还能下降,也返回∞int tmpy, tmpx;int c = 0; //空出的方格数for( tmpx = 0; tmpx < 4; tmpx++ ) //考虑第0~3列{for( tmpy = 3; tmpy >= 0; tmpy-- ){if( box[tmpy][tmpx] ) break;}tmpy++;if( tmpy>0 ){for( ; tmpy<4; tmpy++ ){if( tmpy+y<0 || tmpy+y>=ROW || tmpx+x<0 || tmpx+x>=COL ) continue;if(!Map[tmpy+y][tmpx+x]) c++; //空出的方格}}}return c;}//当启动自动求解功能时,求下一个方块的最佳下降位置//策略1为:放置后,空出的方格数最少,为MinC1,此时能达到最高位置为MaxY1,该位置为BestX1;//策略2为:放置后,能下降的位置最高,为MaxY2,此时空出的方格数为MinC2,该位置为BestX2;//必有MaxY1<=MaxY2, MinC1>=MinC2//取二者的折衷,策略为:优先采取策略1,但如果MinC2==MinC1或MaxY2>=MaxY1+2,则取策略2int BestStartX( ){int X, Y, tmpx, tmpy; //循环变量int BestX = 0, MaxY = 0, MinC = 100;//最终所求的最佳下降位置int BestX1, MaxY1, MinC1; //策略1:MinC:最佳位置处放置方块时,空出的空格最少,BestX:最佳下降位置,MaxY:能下降到的位置int BestX2, MaxY2, MinC2; //策略2:最佳位置为能下降的位置最高int c; //以上策略求最值时用到的辅助变量int tBox1[4][4], tBox2[4][4]; //tBox2为实现旋转时用到的临时变量int Rotates = 0, Rotates1 = 0, Rotates2 = 0;//找到最佳位置后,当前方块需要旋转的次数int Last1, Last2; //Last1为下一个方块未旋转时最下一个方格所在的行,Last2为旋转后最下一个方格所在的行memcpy(tBox1, NextBox, sizeof(tBox1)); memcpy(tBox2, NextBox, sizeof(tBox1)); for( tmpy=3; tmpy>=0; tmpy-- ) //统计tBox1中最下一个方格所在的行{for( tmpx=0; tmpx<4; tmpx++ ) if(tBox1[tmpy][tmpx]) break;if(tmpx<4) break;}Last1 = tmpy;BestX1 = 0, MaxY1 = 0, MinC1 = 100; BestX2 = 0, MaxY2 = 0, MinC2 = 100;//枚举从第0~COL-4列下落for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last1>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last1;if( Y+Last1>MaxY2 || Y+Last1==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last1;}//第1次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 1;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 1;}//第2次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 2;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 2;}//第3次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 3;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 3;}MinC = MinC1, BestX = BestX1, MaxY = MaxY1, Rotates = Rotates1;if( MinC2==MinC1 || MaxY2>=MaxY1+2 )MinC = MinC2, BestX = BestX2, MaxY = MaxY2, Rotates = Rotates2;if( Rotates>0 ){for( int i=0; i<Rotates; i++ ){RotateTest(NextBox, tBox1);memcpy(NextBox, tBox1, sizeof(tBox1));}}return BestX;}int NewFall( ) //新的方块落下(如果能落下返回1,否则不能落下返回0(程序就该结束了)) {int y, x;CurrentY = 0; //当前方块的当前位置是指该方块(4×4大小)的左上角所在位置if(bAuto) CurrentX = BestStartX( );else CurrentX = COL / 2 - 2; //初始为(0,5)for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = NextBox[y][x];}BuildNextBox( ); //产生下一个随机的方块return Test( CurrentY, CurrentX, CurrentBox );}int no[400] = {3,3,5,1};void BuildNextBox( ) //产生下一个随机的方块{static int j=0;int i, y, x;i = rand()%MAX_CLASS; //随机生成0~6的整数for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )NextBox[y][x] = Box[i][y][x];}}//测试在(y,x)位置(左上角位置)是否能放置方块box,能放置返回1,否则返回0int Test( int y, int x, int box[4][4] ){int tmpy, tmpx;for( tmpy = 0; tmpy < 4; tmpy++ ){for( tmpx = 0; tmpx < 4; tmpx++ ){if( Map[tmpy + y][tmpx + x] && box[tmpy][tmpx] )return 0;}}return 1;}int Drop( ) //定时时间到,当前方块下降一行位置(如果能下降返回1,否则返回0){int NewY;NewY = CurrentY + 1;if( Test( NewY, CurrentX, CurrentBox ) ){CurrentY = NewY;return 1;}return 0;}void PutBox( ) //在当前位置(CurrentY,CurrentX)放置当前方块(此时当前方块已经不能下降了){int y, x;for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] )Map[CurrentY + y][CurrentX + x] = CurrentBox[y][x];}}}int Move( int Right ) //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动{int x;if( Right ) x = CurrentX + 1; //向右移动一列位置else x = CurrentX - 1; //向左移动一列位置if( Test( CurrentY, x, CurrentBox ) ){CurrentX = x;return 1;}return 0;}void Clear( ) //清除满足条件的行{int y, x; //循环变量int DelY, DelX; //循环变量int Full; //一行是否满的标志for( y = 0; y < ROW - 1; y++ ) //检查第0~22行{Full = 1;for( x = 1; x < COL - 1; x++ ) //检查每行的第1~12列{if( !Map[y][x] ){Full = 0; break;}}if( Full ) //第y行满了,删除该行,该行以上的其他行下移一行{iDeleteRows++; iTotalNum = iDeleteRows*100; //更新得分for( DelY = y; DelY > 0; DelY-- ){for( DelX = 1; DelX < COL - 1; DelX++ )Map[DelY][DelX] = Map[DelY-1][DelX];}for( DelX = 1; DelX < COL - 1; DelX++ ) //第0行置为0Map[0][DelX] = 0;}}}int Rotate( ) //测试旋转是否可行,如果可行则旋转当前方块{int y, x;int TmpBox[4][4];RotateTest( CurrentBox, TmpBox );if( Test( CurrentY, CurrentX, TmpBox ) ){for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = TmpBox[y][x];}return 1;}else return 0;}/*0000 0000 0000 //旋转规律是:Box3[y][x] = Box1[y][3-x] -> 方块绕竖直方向对称变换0100-> 0010-> 0010 //Box2[x][y] = Box3[y][x] -> 沿着主对角线对称变换(相当于矩阵转置)1110 0111 01100000 0000 0010 */int RotateTest( int Box1[4][4], int Box2[4][4] ) //旋转当前方块{ //新增返回值为:旋转后的Box2中最下一个方格所在的行int y, x;for( y = 0; y < 4; y++ ){for( x = 3; x >=0; x-- )Box2[x][y] = Box1[y][3 - x];}for( y=3; y>=0; y-- ) //统计Box2中最下一个方格所在的行{for( x=0; x<4; x++ ){if(Box2[y][x]) break;}if(x<4) break;}return y;}LRESULT CALLBACK WndProc( HWND hwnd, UINT message, //窗口处理函数WPARAM wParam, LPARAM lParam ){HDC hdc, hdcMem;int y, x;PAINTSTRUCT ps;HBITMAP hBitMap;HPEN hPen;HBRUSH hBrush;static int cxClient, cyClient; //窗口客户区宽度和高度char str[20]; //用于显示得分的变量switch( message ){case WM_CREATE:SetTimer( hwnd, tDown, tDownTime, NULL ); //开启两个定时器SetTimer( hwnd, tPaint, tPaintTime, NULL );srand( (unsigned)time( NULL ) );bAuto = false;Pause = false;InitMap( );BuildNextBox( ); //先随机产生一个方块NewFall( ); //方块落下并随机产生下一个方块sprintf( str, " 得分:%d", iTotalNum ); strcat( WindowTxt, str );SetWindowText(hwnd,WindowTxt);return 0;case WM_SIZE:cxClient = LOWORD( lParam ); //取得窗口客户区宽度和高度cyClient = HIWORD( lParam );return 0;case WM_TIMER:switch( wParam ){case tDown: //下降定时器if( !Drop( ) ) //如果不能下降则放置当前方块{PutBox( );MessageBeep( -1 );Clear( ); //清除//刷新得分sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}}break;case tPaint: //重绘定时器InvalidateRect(hwnd, NULL, FALSE); //强制重绘窗口工作区break;}case WM_KEYDOWN:switch( wParam ){case VK_LEFT: //"向左"方向键if(bAuto) break;Move(0); break;case VK_RIGHT: //"向右"方向键if(bAuto) break;Move(1); break;case VK_UP: //"向上"方向键:旋转if(bAuto) break;Rotate( ); break;case VK_DOWN: //"向下"方向键:当前方块下移一行位置if(bAuto) break;MessageBeep( -1 ); Drop( ); break;case VK_RETURN: //回车键:暂停Pause = !Pause;if( Pause ) //暂停、自动求解时也可以暂停KillTimer( hwnd, tDown );else //启动{if(bAuto) SetTimer( hwnd, tDown, tDownTime/5, NULL );else SetTimer( hwnd, tDown, tDownTime, NULL );}break;case VK_SPACE:if(bAuto) break;while( 1 ) //使用永真循环,使得当前方块一直下降到不能下降为止{if( !Drop( ) ){PutBox( ); Clear( );sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}break;}}break;case VK_F1:bAuto = !bAuto;if(bAuto) //自动求解{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime/5, NULL );memcpy( WindowTxt+25, s2, strlen(s2) ); //修改标题}else{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime, NULL );memcpy( WindowTxt+25, s1, strlen(s1) ); //修改标题}SetWindowText(hwnd,WindowTxt);break;}case WM_PAINT: //重绘窗口工作区hdc = BeginPaint( hwnd, &ps );hdcMem = CreateCompatibleDC( hdc );hBitMap = CreateCompatibleBitmap( hdc, cxClient, cyClient );SelectObject( hdcMem, hBitMap );//画地图最外面的矩形(4, 4, 246, 446)Rectangle( hdcMem, StartX + LEN * 1 - 1,StartY + LEN * 1 - 1,StartX + LEN * (COL - 1) + 1, StartY + LEN * (ROW - 1) + 1 );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) );SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(250, 250, 250) );SelectObject( hdcMem, hBrush );for( y = 1; y < ROW - 1; y++ ) //画地图中的每一格{for( x = 1; x < COL - 1; x++ ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX + LEN * (x + 1), StartY + LEN * (y + 1) );}}DeleteObject( hPen );DeleteObject( hBrush );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) ); SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(255, 100, 100) );SelectObject(hdcMem, hBrush);for( y = 1; y < ROW - 1; y++ ) //画出地图中每个被占据的方格{for( x = 1; x < COL - 1; x++ ){if( Map[y][x] ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX +LEN * (x + 1), StartY + LEN * (y + 1) );}}}for( y = 0; y < 4; y++ ) //画当前方块{for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] ){if( y + CurrentY > 0 ){Rectangle( hdcMem, (x + CurrentX) * LEN + StartX,(y + CurrentY) * LEN +StartY,(x + CurrentX + 1) * LEN + StartX,(y + CurrentY + 1) * LEN + StartY );}}}}for( y = 0; y < 4; y++ )//在窗口右边区域画下一个方块{for( x = 0; x < 4; x++ ){if( NextBox[y][x] ){Rectangle( hdcMem, (x + COL) * LEN + StartX,(y + 2) * LEN + StartY,(x+ COL + 1) * LEN + StartX, (y + 3) * LEN + StartY );}}}DeleteObject( hPen );DeleteObject( hBrush );DeleteObject( hBitMap );BitBlt( hdc, 0, 0, cxClient, cyClient, hdcMem, 0, 0, SRCCOPY );DeleteDC( hdcMem );EndPaint( hwnd, &ps );return 0;case WM_DESTROY:KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );PostQuitMessage( 0 );return 0;}//end of switch( message )return DefWindowProc( hwnd, message, wParam, lParam );}。