俄罗斯方块游戏代码
俄罗斯方块c代码
/********************************************** 游戏名称:俄罗斯方块**********************************************/#ifndef BLOCK_H_H#define BLOCK_H_H#include<windows.h>#include<time.h>#include<iostream>using namespace std;#define WIDTH 10 //游戏区宽度#define HEIGHT 22 //游戏区高度#define SIZE 10 //方块大小#define KIND 8 //方块种类#define ID_LEFT 0#define ID_RIGHT 1#define ID_DOWN 2#define ID_UP 3#define ID_TIMER 4//八种方块struct BLOCK{WORD dir[4];COLORREF color;};//当前方块、下一方块struct BLOCKINFO{byte id:3;char x,y;byte dir:2;};enum DRAW{SHOW,//显示方块HIDE//隐藏方块};///////////定义函数////////////////void Init(HDC hdc); //初始化void NewGame(HDC hdc); //新游戏void GameOver(); //游戏结束void NewBlock(HDC hdc); //产生新方块bool CheckBlock(BLOCKINFO block); //检查是否可放下方块void DrawBlock(HDC hdc,BLOCKINFO block,DRAW draw); //画方块void OnRotate(HDC hdc); //旋转方块void Transform(HDC hdc); //变形方块void OnLeft(HDC hdc); //左移方块void OnRight(HDC hdc); //右移方块void OnDown(HDC hdc); //下移方块void OnSink(HDC hdc); //下沉方块#endif#include"BLOCK.h"//窗口句柄HWND Hwnd;bool start=true;int grade=0; //分数int level=1; //等级//文本TCHAR buf1[10],buf2[10];int len1=sprintf(buf1,"等级:%d",level);int len2=sprintf(buf2,"分数:%d",grade);//颜色COLORREFBLACK=RGB(0,0,0),RED=RGB(255,0,0),GREEN=RGB(0,255,0),BLUE=RGB(0,0,255),YELL OW=RGB(255,255,0),ORANGE=RGB(255,165,0),LA VENDER=RGB(230,230,250),GRAY=RG B(128,128,128),WHITE=RGB(255,255,255);//当前方块、下一方块BLOCKINFO g_curblock,g_nextblock;//八种方块BLOCK g_blocks[KIND]={{0x0F00,0x4444,0x0F00,0x4444,RED},{0x0660,0x0660,0x0660,0x0660,BLUE},{0x4460,0x02E0,0x0622,0x0740,GREEN},{0x2260,0x0E20,0x0644,0x0470,YELLOW},{0x0C60,0x2640,0x0C60,0x2640,ORANGE},{0x0360,0x4620,0x0360,0x4620,LA VENDER},{0x4E00,0x4C40,0xE40,0x4640,GRAY},{0x4E20,0x06C4,0x0472,0x2360,ORANGE}};//游戏区byte g_world[WIDTH][HEIGHT]={0};//游戏区颜色COLORREF color[WIDTH][HEIGHT]={0};//初始化游戏void Init(HDC hdc){grade=0; //分数level=1; //等级RECT rect;SetBkColor(hdc,BLACK);SetTextColor(hdc,WHITE);TextOut(hdc,(WIDTH+4)*SIZE,(HEIGHT-6)*SIZE,buf1,len1);TextOut(hdc,(WIDTH+4)*SIZE,(HEIGHT-8)*SIZE,buf2,len2);SetRect(&rect,-8.5*SIZE,(HEIGHT-2)*SIZE,-SIZE,(HEIGHT-3)*SIZE);SelectObject(hdc,GetStockObject(NULL_BRUSH));SelectObject(hdc,GetStockObject(WHITE_PEN));DrawText(hdc,TEXT("操作介绍"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("左移:左键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("右移:右键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("下移:下键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("下沉:空格键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("旋转:上键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("变形:Shift+上键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("暂停:回车键"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);OffsetRect(&rect,0,-2*SIZE);DrawText(hdc,TEXT("退出:Esc"),-1,&rect,DT_SINGLELINE|DT_VCENTER|DT_LEFT);Rectangle(hdc,0,0,WIDTH*SIZE,HEIGHT*SIZE);Rectangle(hdc,(WIDTH+4)*SIZE,HEIGHT*SIZE,(WIDTH+8)*SIZE,(HEIGHT-4)*SIZE);srand((unsigned)time(NULL));NewGame(hdc);}//游戏结束void GameOver(){KillTimer(Hwnd,ID_TIMER);if(IDYES==MessageBox(Hwnd,"是否重新开始","提示",MB_YESNO)){start=true;for(int i=0;i<WIDTH;i++){for(int j=0;j<HEIGHT;j++){color[i][j]=0;}}SetTimer(Hwnd,ID_TIMER,500,NULL);InvalidateRect(Hwnd,NULL,TRUE);}elseSendMessage(Hwnd,WM_DESTROY,0,0);}//新游戏void NewGame(HDC hdc){if(start){//清空游戏区ZeroMemory(g_world, WIDTH * HEIGHT);//生成下一方块g_nextblock.id=rand()%8;g_nextblock.dir=rand()%4;g_nextblock.x=WIDTH+4;g_nextblock.y=HEIGHT-1;}for(int i=0;i<WIDTH;i++){for(int j=0;j<HEIGHT;j++){if(color[i][j]){SelectObject(hdc,GetStockObject(WHITE_PEN));SelectObject(hdc,CreateSolidBrush(color[i][j]));}else{SelectObject(hdc,GetStockObject(BLACK_BRUSH));SelectObject(hdc,GetStockObject(BLACK_PEN));}RoundRect(hdc,i*SIZE,j*SIZE,(i+1)*SIZE,(j+1)*SIZE,0.25*SIZE,0.25*SIZE);}}NewBlock(hdc);}//产生新方块void NewBlock(HDC hdc){if(start){start=false;DrawBlock(hdc,g_nextblock,HIDE);g_curblock=g_nextblock;g_curblock.x=WIDTH/2-2;g_curblock.y=HEIGHT+2;g_nextblock.id=rand()%8;g_nextblock.dir=rand()%4;WORD c=g_blocks[g_curblock.id].dir[g_curblock.dir];while((c&0xF)==0){g_curblock.y--;c>>=4;}}DrawBlock(hdc,g_curblock,SHOW);DrawBlock(hdc,g_nextblock,SHOW);}//画方块void DrawBlock(HDC hdc,BLOCKINFO block,DRAW draw){WORD b=g_blocks[block.id].dir[block.dir];int x,y;COLORREF color;SelectObject(hdc,GetStockObject(NULL_BRUSH));SelectObject(hdc,GetStockObject(WHITE_PEN));Rectangle(hdc,0,0,WIDTH*SIZE,HEIGHT*SIZE);Rectangle(hdc,(WIDTH+4)*SIZE,HEIGHT*SIZE,(WIDTH+8)*SIZE,(HEIGHT-4)*SIZE); switch(draw){case SHOW:color=g_blocks[block.id].color;SelectObject(hdc,GetStockObject(WHITE_PEN));break;case HIDE:color=BLACK;SelectObject(hdc,GetStockObject(BLACK_PEN));break;}SelectObject(hdc,CreateSolidBrush(color));for(int i=0;i<16;i++){if(b&0x8000){x=block.x+i%4;y=block.y-i/4;if(y<HEIGHT){RoundRect(hdc,x*SIZE,y*SIZE,(x+1)*SIZE,(y+1)*SIZE,0.25*SIZE,0.25*SIZE); }}b<<=1;}SelectObject(hdc,GetStockObject(BLACK_BRUSH));SelectObject(hdc,GetStockObject(BLACK_PEN));}//检查是否可放下方块bool CheckBlock(BLOCKINFO block){WORD b=g_blocks[block.id].dir[block.dir];int x,y;for(int i=0;i<16;i++){if(b&0x8000){x=block.x+i%4;y=block.y-i/4;if((x<0)||(x>=WIDTH)||(y<0))return false;if((y<HEIGHT)&&(g_world[x][y]))return false;}b<<=1;}return true;}//左移方块void OnLeft(HDC hdc){BLOCKINFO tmp;tmp=g_curblock;tmp.x--;if(CheckBlock(tmp)){DrawBlock(hdc,g_curblock,HIDE);g_curblock.x--;DrawBlock(hdc,g_curblock,SHOW);}}//右移方块void OnRight(HDC hdc){BLOCKINFO tmp;tmp=g_curblock;tmp.x++;if(CheckBlock(tmp)){DrawBlock(hdc,g_curblock,HIDE);g_curblock.x++;DrawBlock(hdc,g_curblock,SHOW);}}//旋转方块void OnRotate(HDC hdc){int dx;BLOCKINFO tmp;tmp=g_curblock;tmp.dir++;if(CheckBlock(tmp)){dx=0;goto rotate;}tmp.x=g_curblock.x-1;if(CheckBlock(tmp)){dx=-1;goto rotate;}tmp.x=g_curblock.x+1;if(CheckBlock(tmp)){dx=1;goto rotate;}tmp.x=g_curblock.x-2;if(CheckBlock(tmp)){dx=-2;goto rotate;}tmp.x=g_curblock.x+2;if(CheckBlock(tmp)){dx=2;goto rotate;}return;rotate:DrawBlock(hdc,g_curblock,HIDE);g_curblock.dir++;g_curblock.x+=dx;DrawBlock(hdc,g_curblock,SHOW);}//变形方块void Transform(HDC hdc){int dx;BLOCKINFO tmp;tmp=g_curblock;tmp.id++;if(CheckBlock(tmp)){dx=0;goto transform;}tmp.x=g_curblock.x-1;if(CheckBlock(tmp)){dx=-1;goto transform;}tmp.x=g_curblock.x+1;if(CheckBlock(tmp)){dx=1;goto transform;}tmp.x=g_curblock.x-2;if(CheckBlock(tmp)){dx=-2;goto transform;}tmp.x=g_curblock.x+2;if(CheckBlock(tmp)){dx=2;goto transform;}return;transform:DrawBlock(hdc,g_curblock,HIDE);g_curblock.id++;g_curblock.x+=dx;DrawBlock(hdc,g_curblock,SHOW);}//下沉方块void OnSink(HDC hdc){int i,x,y;DrawBlock(hdc,g_curblock,HIDE);BLOCKINFO tmp=g_curblock;tmp.y--;while(CheckBlock(tmp)){g_curblock.y--;tmp.y--;}DrawBlock(hdc,g_curblock,SHOW);//判断是否结束游戏WORD b=g_blocks[g_curblock.id].dir[g_curblock.dir];for(i=0;i<16;i++){if(b&0x8000){if(g_curblock.y-i/4>=HEIGHT){GameOver();return;}else{g_world[g_curblock.x+i%4][g_curblock.y-i/4]=1;color[g_curblock.x+i%4][g_curblock.y-i/4]=g_blocks[g_curblock.id].color;}}b<<=1;}//判断是否消行int row[4]={0};bool brow=false;for(y=g_curblock.y;y>=(g_curblock.y>3?g_curblock.y-3:0);y--){i=0;for(x=0;x<WIDTH;x++){if(g_world[x][y]==1)i++;}if(i==WIDTH){brow=true;row[g_curblock.y-y]=1;grade+=10;}}//延时200毫秒Sleep(200);//消行if(brow){for(i=0;i<4;i++)if(row[i]){for(y=g_curblock.y-i+1;y<HEIGHT;y++)for(x=0;x<WIDTH;x++){g_world[x][y-1]=g_world[x][y];g_world[x][y]=0;color[x][y-1]=color[x][y];color[x][y]=0;}BitBlt(hdc,0,(g_curblock.y-i)*SIZE,WIDTH*SIZE,(HEIGHT-g_curblock.y+i-1)*SIZE-1,hdc ,0,(g_curblock.y-i+1)*SIZE,SRCCOPY);len2=sprintf(buf2,"分数:%d",grade);SetBkColor(hdc,BLACK);SetTextColor(hdc,WHITE);TextOut(hdc,(WIDTH+4)*SIZE,(HEIGHT-8)*SIZE,buf2,len2);}}if(grade/100&&(!(grade%100))){level+=1;len1=sprintf(buf1,"等级:%d",level);SetBkColor(hdc,BLACK);SetTextColor(hdc,WHITE);TextOut(hdc,(WIDTH+4)*SIZE,(HEIGHT-6)*SIZE,buf1,len1);KillTimer(Hwnd,ID_TIMER);SetTimer(Hwnd,ID_TIMER,500-30*level,NULL);}start=true;NewBlock(hdc);}//下移方块void OnDown(HDC hdc){BLOCKINFO tmp;tmp=g_curblock;tmp.y--;if(CheckBlock(tmp)){DrawBlock(hdc,g_curblock,HIDE);g_curblock.y--;DrawBlock(hdc,g_curblock,SHOW);}elseOnSink(hdc);}#include"BLOCK.h"HINSTANCE hinst;//窗口句柄extern HWND Hwnd;bool s=true;//窗口过程函数LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam);/////////////////////////int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hpreInstance,LPSTR lpCmdLine,int nCmdShow){hinst=hInstance;WNDCLASS wndclass;wndclass.style=CS_HREDRAW|CS_VREDRAW;//类型wndclass.lpfnWndProc=WindowProc;//窗口过程函数wndclass.cbClsExtra=0;//存储附加信息wndclass.cbWndExtra=0;//wndclass.hInstance=hInstance;//程序的实例句柄wndclass.hIcon=LoadIcon(NULL,IDI_APPLICATION);//图标(IDI_APPLICATION)wndclass.hCursor=LoadCursor(NULL,IDC_ARROW);//光标wndclass.hbrBackground=(HBRUSH)GetStockObject(BLACK_BRUSH);//获取系统画刷wndclass.lpszMenuName=NULL;//菜单名wndclass.lpszClassName="tetris";//窗口类名RegisterClass(&wndclass);//注册窗口//创建窗口HWND hwnd;hwnd=CreateWindow("tetris","俄罗斯方块",WS_OVERLAPPED|WS_SYSMENU|WS_MINIMIZEBOX,280,50,70*SIZE,60*SIZE,NULL,NULL,hInstance,NULL);//WS_OVERLAPPEDWINDOWHwnd=hwnd;//显示窗口ShowWindow(hwnd,nCmdShow);//更新窗口UpdateWindow(hwnd);MSG msg;BOOL bRet;while(bRet=GetMessage(&msg,NULL,0,0))//获取消息{if(bRet==-1)return -1;TranslateMessage(&msg);DispatchMessage(&msg);}return msg.wParam;}//////////////////////////////////LRESULT CALLBACK WindowProc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam){int wmId, wmEvent;PAINTSTRUCT ps;LPDRAWITEMSTRUCT pdis;HDC hdc;static int cxClient,cyClient;static HWND hleft,hright,hup,hdown;POINT pt[3];switch (uMsg){case WM_SIZE:cxClient=LOWORD(lParam);cyClient=HIWORD(lParam);MoveWindow(hleft,53*SIZE,40*SIZE,3*SIZE,3*SIZE,TRUE);MoveWindow(hright,59*SIZE,40*SIZE,3*SIZE,3*SIZE,TRUE);MoveWindow(hup,56*SIZE,37*SIZE,3*SIZE,3*SIZE,TRUE);MoveWindow(hdown,56*SIZE,43*SIZE,3*SIZE,3*SIZE,TRUE);break;case WM_CREATE:SetTimer(hwnd,ID_TIMER,500,NULL);hleft=CreateWindow(TEXT("button"),TEXT(""),WS_CHILD|WS_VISIBLE|BS_OWNERD RAW,0,0,3*SIZE,3*SIZE,hwnd,(HMENU)ID_LEFT,hinst,NULL);hright=CreateWindow(TEXT("button"),TEXT(""),WS_CHILD|WS_VISIBLE|BS_OWNER DRAW,0,0,3*SIZE,3*SIZE,hwnd,(HMENU)ID_RIGHT,hinst,NULL);hdown=CreateWindow(TEXT("button"),TEXT(""),WS_CHILD|WS_VISIBLE|BS_OWNER DRAW,0,0,3*SIZE,3*SIZE,hwnd,(HMENU)ID_DOWN,hinst,NULL);hup=CreateWindow(TEXT("button"),TEXT(""),WS_CHILD|WS_VISIBLE|BS_OWNERD RAW,0,0,3*SIZE,3*SIZE,hwnd,(HMENU)ID_UP,hinst,NULL);break;case WM_PAINT:hdc=BeginPaint(hwnd,&ps);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);Init(hdc);EndPaint(hwnd,&ps);break;case WM_COMMAND:wmId = LOWORD(wParam);wmEvent = HIWORD(wParam);switch (wmId){case 106:DestroyWindow(hwnd);break;default:return DefWindowProc(hwnd, uMsg, wParam, lParam);}break;case WM_TIMER:if(s){hdc=GetDC(hwnd);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);OnDown(hdc);ReleaseDC(hwnd,hdc);}break;case WM_KEYDOWN:switch(wParam){case VK_LEFT:if(s){hdc=GetDC(hwnd);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);OnLeft(hdc);ReleaseDC(hwnd,hdc);}SendMessage(hleft,BM_SETSTATE,1,0);break;case VK_RIGHT:if(s){hdc=GetDC(hwnd);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);OnRight(hdc);ReleaseDC(hwnd,hdc);}SendMessage(hright,BM_SETSTATE,1,0);break;case VK_UP:if(s){hdc=GetDC(hwnd);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);if(GetKeyState(VK_SHIFT)<0)Transform(hdc);elseOnRotate(hdc);ReleaseDC(hwnd,hdc);}SendMessage(hup,BM_SETSTATE,1,0);break;case VK_DOWN:if(s){hdc=GetDC(hwnd);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);OnDown(hdc);ReleaseDC(hwnd,hdc);}SendMessage(hdown,BM_SETSTA TE,1,0);break;case VK_SPACE:if(s){hdc=GetDC(hwnd);SetMapMode(hdc,MM_ISOTROPIC);SetWindowExtEx(hdc,250,250,NULL);SetViewportExtEx(hdc,cxClient,-cyClient,NULL);SetViewportOrgEx(hdc,20*SIZE,55*SIZE,NULL);OnSink(hdc);ReleaseDC(hwnd,hdc);}break;case VK_RETURN:if(s)s=false;elses=true;break;}break;case WM_KEYUP:switch(wParam){case VK_LEFT:SendMessage(hleft,BM_SETSTATE,0,0);break;case VK_RIGHT:SendMessage(hright,BM_SETSTATE,0,0);break;case VK_UP:SendMessage(hup,BM_SETSTA TE,0,0);break;case VK_DOWN:SendMessage(hdown,BM_SETSTA TE,0,0);break;}break;case WM_DRAWITEM:pdis=(LPDRAWITEMSTRUCT)lParam;FillRect(pdis->hDC,&pdis->rcItem,(HBRUSH)GetStockObject(BLACK_BRUSH));if(pdis->itemState&ODS_SELECTED)SelectObject(pdis->hDC,(HBRUSH)CreateSolidBrush(RGB(255,0,0)));elseSelectObject(pdis->hDC,(HBRUSH)CreateSolidBrush(RGB(255,255,255)));switch(pdis->CtlID){case ID_LEFT:pt[0].x=0;pt[0].y=1.5*SIZE;pt[1].x=3*SIZE;pt[1].y=0;pt[2].x=3*SIZE;pt[2].y=3*SIZE;break;case ID_RIGHT:pt[0].x=0;pt[0].y=0;pt[1].x=0;pt[1].y=3*SIZE;pt[2].x=3*SIZE;pt[2].y=1.5*SIZE;break;case ID_DOWN:pt[0].x=0;pt[0].y=0;pt[1].x=3*SIZE;pt[1].y=0;pt[2].x=1.5*SIZE;pt[2].y=3*SIZE;break;case ID_UP:pt[0].x=1.5*SIZE;pt[0].y=0;pt[1].x=0;pt[1].y=3*SIZE;pt[2].x=3*SIZE;pt[2].y=3*SIZE;break;}Polygon(pdis->hDC,pt,3);break;case WM_CLOSE:DestroyWindow(hwnd);break;case WM_DESTROY:KillTimer(hwnd,ID_TIMER);PostQuitMessage(0);break;default:return DefWindowProc(hwnd, uMsg, wParam, lParam);}return 0;}。
简单俄罗斯方块程序代码
简单俄罗斯方块程序代码俄罗斯方块是一款非常经典的游戏,它需要玩家通过操作方块来消除行,随着游戏的深入,难度越来越大。
我们可以用Python语言来编写俄罗斯方块程序,它可以让我们体验到这个经典游戏的乐趣。
首先,我们需要导入相关的模块:```pythonimport pygameimport random```其中,pygame模块可以让我们创建图形化界面,random模块可以用于生成随机数,方便我们随机生成方块。
接下来,我们需要定义一些常量和变量:```python# 定义常量WIDTH = 480HEIGHT = 640CELL_SIZE = 30# 定义变量board = [[0] * 10 for i in range(20)]score = 0ticks = 0fall_speed = 60next_block = random.randint(0, 6)block_pos = (0, 3)current_block = None```这里定义了几个常量:游戏窗口的宽度和高度,单元格的大小。
同时,我们还需要一个二维数组board来表示游戏画面上的格子状态,score来表示当前得分,ticks表示已经落下的方块数量,fall_speed表示方块下落的速度,next_block表示下一个方块的类型,block_pos表示当前方块的位置,current_block则表示当前正在下落的方块。
接下来,我们需要定义一些函数来实现游戏的各种功能。
首先是绘制游戏画面的函数:```pythondef draw_game():screen.fill((0, 0, 0))# 绘制已经落下的方块for i in range(20):for j in range(10):if board[i][j] != 0:pygame.draw.rect(screen, (255, 255, 255),(j * CELL_SIZE, i * CELL_SIZE, CELL_SIZE, CELL_SIZE))# 绘制正在下落的方块if current_block:for i in range(4):for j in range(4):if current_block[i][j] != 0:pygame.draw.rect(screen, (255, 255, 255),((block_pos[1] + j) * CELL_SIZE, (block_pos[0] + i) * CELL_SIZE, CELL_SIZE, CELL_SIZE))# 绘制下一个方块draw_next_block()# 绘制得分font = pygame.font.SysFont('SimHei', 20)text = font.render('得分:%d' % score, True, (255, 255, 255))screen.blit(text, (10, 10))pygame.display.flip()```这个函数会首先清空画面,然后遍历board数组,绘制已经落下的方块。
俄罗斯方块游戏VB代码
Private n(3), m(3) As Integer'n(3)记录游戏区的四个活动方块的编号'm(3)记录预览区的四个活动方块的编号Private situation, situation2, linenum, t As Integer'situation记录游戏区的方块样式'situation2记录预览区的方块样式,linenum记录一次消除的行数Private Declare Function sndPlaySound Lib "Winmm.dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Long) As LongPrivate Sub hidefang(a As Integer) '定义使方块不可见的过程Select Case aCase 0 'a=0使游戏区方块不可见Command6(n(0)).Visible = FalseCommand6(n(1)).Visible = FalseCommand6(n(2)).Visible = FalseCommand6(n(3)).Visible = FalseCase 1 'a=1使预览区方块不可见Command3(m(0)).Visible = FalseCommand3(m(1)).Visible = FalseCommand3(m(2)).Visible = FalseCommand3(m(3)).Visible = FalseEnd SelectEnd SubPrivate Sub showfang(a As Integer) '定义使方块可见的过程Select Case aCase 0 'a=0使游戏区方块可见Command6(n(0)).Visible = TrueCommand6(n(1)).Visible = TrueCommand6(n(2)).Visible = TrueCommand6(n(3)).Visible = TrueCase 1 'a=1使预览区方块不可见Command3(m(0)).Visible = TrueCommand3(m(1)).Visible = TrueCommand3(m(2)).Visible = TrueCommand3(m(3)).Visible = TrueEnd SelectEnd SubPrivate Sub clearline() '定义消除整行的过程For i = 190 To 10 Step -10If Command6(i).Visible = True And _Command6(i + 1).Visible = True And _Command6(i + 2).Visible = True And _Command6(i + 3).Visible = True And _Command6(i + 4).Visible = True And _Command6(i + 5).Visible = True And _Command6(i + 8).Visible = True And _Command6(i + 9).Visible = True ThenFor j = i + 4 To i Step -1t = 1Command6(j).Visible = FalseCommand6(2 * i + 9 - j).Visible = FalseFor k = 1 To 4000DoEventsNextt = 0Nextlinenum = linenum + 1For j = i - 1 To 0 Step -1If Command6(j).Visible = True ThenCommand6(j).Visible = FalseCommand6(j + 10).Visible = TrueEnd IfNextclearline '为了实现连消数行,这里使用递归调用End IfNextEnd SubPrivate Function downable() As Boolean'自定义函数,确定方块是否能下降If n(0) < 190 And n(1) < 190 And n(2) < 190 And n(3) < 190 ThenIf Command6(n(0) + 10).Visible = False And _Command6(n(1) + 10).Visible = False And _Command6(n(2) + 10).Visible = False And _Command6(n(3) + 10).Visible = False Thendownable = TrueElsedownable = FalseEnd IfElsedownable = FalseEnd IfEnd FunctionPrivate Function leftable() As Boolean'自定义函数,确定方块是否能左移If n(0) Mod 10 <> 0 And n(1) Mod 10 <> 0 And n(2) Mod 10 <> 0 And n(3) Mod 10 <> 0 Then If Command6(n(0) - 1).Visible = False And _Command6(n(1) - 1).Visible = False And _Command6(n(2) - 1).Visible = False And _Command6(n(3) - 1).Visible = False Thenleftable = TrueEnd IfElseleftable = FalseEnd IfEnd FunctionPrivate Function rightable() As Boolean'自定义函数,确定方块是否能右移If n(0) Mod 10 <> 9 And n(1) Mod 10 <> 9 And n(2) Mod 10 <> 9 And n(3) Mod 10 <> 9 Then If Command6(n(0) + 1).Visible = False And _Command6(n(1) + 1).Visible = False And _Command6(n(2) + 1).Visible = False And _Command6(n(3) + 1).Visible = False Thenrightable = TrueElserightable = FalseEnd IfElserightable = FalseEnd IfEnd FunctionPrivate Sub loadfangkuai() '定义随机产生一种方块的过程Select Case Int(Rnd * 6)'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case 0 '长条形Select Case Int(Rnd * 2)Case 0m(0) = 3m(1) = 4m(2) = 5m(3) = 6situation2 = 0Case 1m(0) = 5m(1) = 15m(2) = 25m(3) = 35situation2 = 1End Select'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case 1 '正方形m(0) = 4m(1) = 5m(2) = 14m(3) = 15situation2 = 2Select Case Int(Rnd * 2)Case 0m(0) = 6m(1) = 5m(2) = 15m(3) = 14situation2 = 3Case 1m(0) = 4m(1) = 14m(2) = 15m(3) = 25situation2 = 4End Select''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 3 '反S形Select Case Int(Rnd * 2)Case 0m(0) = 4m(1) = 5m(2) = 15m(3) = 16situation2 = 5Case 1m(0) = 5m(1) = 15m(2) = 14m(3) = 24situation2 = 6End Select''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 4 'T字形Select Case Int(Rnd * 4)Case 0m(0) = 4m(1) = 5m(2) = 6m(3) = 15situation2 = 7Case 1m(0) = 5m(1) = 15m(2) = 25m(3) = 14situation2 = 8Case 2m(0) = 16situation2 = 9Case 3m(0) = 24m(1) = 14m(2) = 4m(3) = 15situation2 = 10End Select''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 5 '正7字形Select Case Int(Rnd * 4)Case 0m(0) = 4m(1) = 5m(2) = 15m(3) = 25situation2 = 11Case 1m(0) = 5m(1) = 15m(2) = 14m(3) = 13situation2 = 12Case 2m(0) = 25m(1) = 24m(2) = 14m(3) = 4situation2 = 13Case 3m(0) = 14m(1) = 4m(2) = 5m(3) = 6situation2 = 14End Select''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 6 '反7字形Select Case Int(Rnd * 4)Case 0m(0) = 5m(1) = 4m(2) = 14m(3) = 24situation2 = 15Case 1m(3) = 3situation2 = 16Case 2m(0) = 24m(1) = 25m(2) = 15m(3) = 5situation2 = 17Case 3m(0) = 4m(1) = 14m(2) = 15m(3) = 16situation2 = 18End SelectEnd SelectEnd SubPrivate Sub zhuan() '定义使方块旋转的过程Select Case situation''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case 0 '长条形If n(0) - 18 >= 2 And n(3) + 9 <= 198 ThenIf Command6(n(0) - 18).Visible = False And _Command6(n(1) - 9).Visible = False And _Command6(n(3) + 9).Visible = False Thenhidefang 0n(0) = n(0) - 18n(1) = n(1) - 9n(3) = n(3) + 9showfang 0situation = 1End IfEnd IfCase 1If (n(0) + 18) Mod 10 < 8 And (n(3) - 9) Mod 10 > 0 Then If Command6(n(0) + 18).Visible = False And _Command6(n(1) + 9).Visible = False And _Command6(n(3) - 9).Visible = False Thenhidefang 0n(0) = n(0) + 18n(1) = n(1) + 9n(3) = n(3) - 9showfang 0situation = 0End IfCase 2 '正方形,无变化形态'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 3 '正S形If n(0) - 11 > 1 ThenIf Command6(n(0) - 11).Visible = False And _Command6(n(3) + 2).Visible = False Thenhidefang 0n(0) = n(0) - 11n(2) = n(2) - 9n(3) = n(3) + 2showfang 0situation = 4End IfEnd IfCase 4If (n(3) - 2) Mod 10 < 9 ThenIf Command6(n(2) + 9).Visible = False And _Command6(n(3) - 2).Visible = False Thenhidefang 0n(0) = n(0) + 11n(2) = n(2) + 9n(3) = n(3) - 2showfang 0situation = 3End IfEnd If'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 5 '反S形If n(0) - 9 > 1 ThenIf Command6(n(0) - 9).Visible = False And _Command6(n(3) - 2).Visible = False Thenhidefang 0n(0) = n(0) - 9n(2) = n(2) - 11n(3) = n(3) - 2showfang 0situation = 6End IfEnd IfCase 6If (n(3) + 2) Mod 10 > 0 ThenIf Command6(n(2) + 11).Visible = False And _ Command6(n(3) + 2).Visible = False Thenhidefang 0n(0) = n(0) + 9n(2) = n(2) + 11n(3) = n(3) + 2End IfEnd If'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''' Case 7 'T字形If n(0) - 9 > 0 ThenIf Command6(n(0) - 9).Visible = False Thenhidefang 0n(0) = n(0) - 9n(2) = n(2) + 9n(3) = n(3) - 11showfang 0situation = 8End IfEnd IfCase 8If (n(0) + 11) Mod 10 > 0 ThenIf Command6(n(0) + 11).Visible = False Thenhidefang 0n(0) = n(0) + 11n(2) = n(2) - 11n(3) = n(3) - 9showfang 0situation = 9End IfEnd IfCase 9If n(0) + 9 < 199 ThenIf Command6(n(0) + 9).Visible = False Thenhidefang 0n(0) = n(0) + 9n(2) = n(2) - 9n(3) = n(3) + 11showfang 0situation = 10End IfEnd IfCase 10If (n(0) - 11) Mod 10 < 9 ThenIf Command6(n(0) - 11).Visible = False Thenhidefang 0n(0) = n(0) - 11n(2) = n(2) + 11n(3) = n(3) + 9showfang 0situation = 7End IfEnd IfIf n(0) - 9 > 1 And (n(3) - 22) Mod 10 < 9 ThenIf Command6(n(0) - 9).Visible = False And _Command6(n(3) - 22).Visible = False Thenhidefang 0n(0) = n(0) - 9n(2) = n(2) - 11n(3) = n(3) - 22showfang 0situation = 12End IfEnd IfCase 12If (n(0) + 11) Mod 10 > 0 And n(3) - 18 > 1 Then If Command6(n(0) + 11).Visible = False And _Command6(n(3) - 18).Visible = False Thenhidefang 0n(0) = n(0) + 11n(2) = n(2) - 9n(3) = n(3) - 18showfang 0situation = 13End IfEnd IfCase 13If n(0) + 9 < 198 And (n(3) + 22) Mod 10 > 0 Then If Command6(n(0) + 9).Visible = False And _Command6(n(3) + 22).Visible = False Thenhidefang 0n(0) = n(0) + 9n(2) = n(2) + 11n(3) = n(3) + 22showfang 0situation = 14End IfEnd IfCase 14If (n(0) - 11) Mod 10 < 9 And n(3) + 18 < 198 Then If Command6(n(0) - 11).Visible = False And _Command6(n(3) + 18).Visible = False Thenhidefang 0n(0) = n(0) - 11n(2) = n(2) + 9n(3) = n(3) + 18showfang 0situation = 11End IfEnd IfIf (n(3) - 22) Mod 10 < 8 ThenIf Command6(n(2) - 11).Visible = False And _Command6(n(3) - 22).Visible = False Thenhidefang 0n(0) = n(0) + 9n(2) = n(2) - 11n(3) = n(3) - 22showfang 0situation = 16End IfEnd IfCase 16If n(3) - 18 > 1 ThenIf Command6(n(2) - 9).Visible = False And _Command6(n(3) - 18).Visible = False Thenhidefang 0n(0) = n(0) - 11n(2) = n(2) - 9n(3) = n(3) - 18showfang 0situation = 17End IfEnd IfCase 17If (n(3) + 22) Mod 10 > 1 ThenIf Command6(n(2) + 11).Visible = False And _Command6(n(3) + 22).Visible = False Thenhidefang 0n(0) = n(0) - 9n(2) = n(2) + 11n(3) = n(3) + 22showfang 0situation = 18End IfEnd IfCase 18If n(3) + 18 < 198 ThenIf Command6(n(2) + 9).Visible = False And _Command6(n(3) + 18).Visible = False Thenhidefang 0n(0) = n(0) + 11n(2) = n(2) + 9n(3) = n(3) + 18showfang 0situation = 15End IfEnd IfEnd SubPrivate Sub Command1_Click()Form1.ShowForm2.ShowEnd SubPrivate Sub Command2_Click()Picture1.SetFocusIf Command2.Caption = "开始" ThenPicture1.SetFocus''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Timer1.Interval = 1000 / Val(Text1.Text)'根据关卡系数设置方块下降速度''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''For i = 19 To 20 - Val(Text3.Text) Step -1'根据难度系数产生不同难度的地基For j = i * 10 To i * 10 + 9If Rnd >= 0.5 Then Command6(j).Visible = True NextNext''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''For i = 0 To 3 '引用预览区已经产生的方块n(i) = m(i)Nextshowfang 0situation = situation2''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Timer1.Enabled = True '设置一些控件的可用性Command4.Enabled = TrueCommand1.Enabled = FalseCommand5.Enabled = False''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''hidefang 1 '清空预览区loadfangkuai '继续在预览区产生方块showfang 1''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Command2.Caption = "结束"Else''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Timer1.Enabled = False '设置一些控件的可用性Command4.Enabled = FalseCommand1.Enabled = TrueCommand5.Enabled = True''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''For i = 1 To 199Command6(i).Visible = FalseNextCommand2.Caption = "开始"Text2.Text = "0"linenum = 0End IfEnd SubPrivate Sub Command4_Click()Select Case Command4.CaptionCase "暂停"Command4.Caption = "继续"Timer1.Enabled = FalseCommand1.Enabled = TrueCommand5.Enabled = TrueCase "继续"Command4.Caption = "暂停"Timer1.Enabled = TrueCommand1.Enabled = FalseCommand5.Enabled = FalsePicture1.SetFocusEnd SelectEnd SubPrivate Sub Command5_Click()Form1.ShowForm3.ShowEnd SubPrivate Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) If t = 0 Thenhidefang 0Select Case KeyCode''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case vbKeyLeft '点击向左键If leftable() = True ThenFor j = 0 To 3Command6(n(j) - 1).Visible = Truen(j) = n(j) - 1Next jEnd Ifshowfang 0''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case vbKeyDown '点击向下键If downable() = True ThenFor j = 0 To 3Command6(n(j) + 10).Visible = Truen(j) = n(j) + 10Next jEnd Ifshowfang 0''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case vbKeyRight '点击向右键If rightable() = True ThenFor j = 0 To 3Command6(n(j) + 1).Visible = Truen(j) = n(j) + 1Next jEnd Ifshowfang 0''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case vbKeySpace '点击旋转键(空格键)showfang 0zhuan''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Case Elseshowfang 0End SelectEnd IfEnd SubPrivate Sub Form_Load()WMP1.URL = App.Path & "\1.MP3"Dim SoundFile As String, Result As LongSoundFile = "C:\Users\Administrator\Desktop\新建文件夹\夜的钢琴曲(五).mp3" '此处为路径Result = sndPlaySound(SoundFile, 1)Form2.HideForm3.HideRandomize '非正序的随机数For i = 1 To 199 '创建游戏区的方块Load Command6(i)Next iFor i = 0 To 199 '在游戏区以10×20排列方块Command6(i).Left = (i Mod 10)Command6(i).Top = i \ 10Command6(i).Visible = FalseNext iFor i = 1 To 39 '创建预览区的方块Load Command3(i)Next iFor i = 0 To 39 '在预览区排列方块Command3(i).Left = (i Mod 10) - 3Command3(i).Top = i \ 10Command3(i).Visible = FalseNext iloadfangkuai '在预览区产生第一个方块showfang 1End SubPrivate Sub Timer1_Timer()hidefang 0If downable() = True Then '能够下降For j = 0 To 3n(j) = n(j) + 10Next jshowfang 0Else '不能继续下降了showfang 0'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''clearline '引用自定义方法,判断是否消除满行'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''For i = 0 To 9 '如果方块叠至最上层,游戏结束If Command6(i).Visible = True Then Exit ForNextIf i < 10 Then Command2_Click: Exit Sub'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''For i = 0 To 3 '引用预览区已经产生的方块n(i) = m(i)Nextshowfang 0situation = situation2''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''Text2.Text = Str(Val(Text2.Text) + 100 * (2 ^ linenum - 1))'这段代码控制加分'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''这段代码控制过关升级If Val(Right(Text2.Text, 4)) < Val(Right(Str(Val(Text2.Text) - 100 * (2 ^ linenum - 1)), 4)) Then Text1.Text = Str(Val(Text1.Text) + 1)Timer1.Interval = 1000 / Val(Text1.Text)End If''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''linenum = 0hidefang 1 '清空预览区loadfangkuai '继续在预览区产生方块showfang 1End IfEnd SubPrivate Sub WMP1_PlayStateChange(ByVal NewState As Long)'当播放器的播放状态变为"停止"时,再次播放If NewState = 1 Then '1为停止(一曲播完)WMP1.Controls.play '再播放End IfEnd Sub。
JS版《俄罗斯方块》游戏原创代码
window.BORDER_COLOR = "#000000"; // 单元格边框颜色
window.GAME = null; // 游戏对象
// 方块组合产生的矩阵(共7种组合)
window.TYPE = [
[[0, 0], [0, 1], [0, 2], [0, 3]], // ━
window.CELL = 20; // 每个单元格像素大小
window.BORDER = 1; // 单元格边框大小
window.ROWS = 20; // 最多有几行单元格
window.COLS = 12; // 最多有几列单元格
window.INTERVAL = 500; // 间隔时间
[[0, 0], [0, 1], [1, 1], [1, 2]], // ┏┛
[[1, 0], [1, 1], [0, 1], [0, 2]] // ┗┓
];
// 获取浏览器类型
window.getBrowser = function (){
var browserName = erAgent.toLowerCase();
var right_width = this.span * 4 + 60;
var top = (document.documentElement.clientHeight - height) / 2;
var divs = this.getChildByTag(this.container, "div");
this.container.style.marginTop = top + "px";
俄罗斯方块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); }。
俄罗斯方块程序代码
//包含头文件#include<stdio.h>#include<Windows.h>#include<conio.h>#include<graphics.h>#include<time.h>#include "Tetris.h"//int score=0;//int lever=1;//char scores[10];//char levers[10];/*enum cmd{round, //旋转方块left, //左移方块right, //右移方块down, //下一方块bottom, //方块沉底quit //离开游戏};//定义绘制方块的状态的枚举类型enum draw{show, //显示方块hide //抹掉方块};//定义俄罗斯方块的结构体struct block{int dir[4]; //方块的四个旋转的状态int color; //方块的颜色}*/static T_TrsBlockStyle gz_tBlockStyleTab[7] ={/* 口口口口口口口口口口口口口口口口*/{0x0F00, 0x4444, 0x0F00, 0x4444, RED},/*口口口口口口口口口口口口口口口口*/{0x0660, 0x0660, 0x0660, 0x0660, BLUE},/* 口口口口口口口口口口口口口口口口*/{0x4460, 0x02E0, 0x0622, 0x0740, MAGENTA},/* 口口口口口口口口口口口口口口口口*/{0x2260, 0x0E20, 0x0644, 0x0470, YELLOW},/* 口口口口口口口口口口口口口口口口*/{0x0C60, 0x2640, 0x0C60, 0x2640, CYAN},/* 口口口口口口口口口口口口口口口口*/{0x0360, 0x4620, 0x0360, 0x4620, GREEN},/* 口口口口口口口口口口口口口口口口*/{0x4E00, 0x4C40, 0x0E40, 0x4640, BROWN}};/*//定义俄罗斯方块的信息的结构体struct blockinfo{int id; //7中方块中的哪一种byte dir:2; //1种方块中四个方向中的哪个char x,y; //方块的坐标(不是屏幕中的而是自己设置的游戏区域中的)}curblock,nextblock;*/// 定义游戏区//unsigned char area[width][high] = {0};//函数声明bool TRS_AppCreate(void ** ppUser,void * pFunc);static void TRS_Init(void *pUser);static void TRS_DrawBackground(void *pUser);static void TRS_GameOver(void *pUser);static void TRS_Quit(void *pUser);static void TRS_ScoreShow(void *pUser);static void TRS_NewGame(void *pUser);static AEEEvent TRS_GetMsg(PCTetrisApp pMe);static bool TRS_TetrisHandle(void *pUser, DWORD evt, WORD w,DWORD dw);static void TRS_Newblock(void *pUser);static void TRS_DrawBlock(void *pUser,T_TrsBlockInfo tCurBlck,EDrawStyle eStyle);static bool TRS_Checkblock(void *pUser, T_TrsBlockInfo tCurBlck);static void TRS_HRound(void *pUser);static void TRS_HLeft(void *pUser);static void TRS_HRight(void *pUser);static void TRS_HDown(void *pUser);static void TRS_HBottom(void *pUser);/*------------------------------------------------------------------------------函数名称:main功能说明:主函数参数说明:作者:时间:-------------------------------------------------------------------------------*/void main(){PCTetrisApp pMe;AEEEvent eMsg;//init();TRS_AppCreate((void **)&pMe,NULL);/*while(true){scoreshow();c=getcmd();discmd(c);if (c == quit){HWND wnd = GetHWnd();if (MessageBox(wnd, _T("您要退出游戏吗?"), _T("提醒"), MB_OKCANCEL | MB_ICONQUESTION) == IDOK)Quit();}}*/}bool TRS_AppCreate(void ** ppUser,void * pFunc);{PCTetrisApp pMe;new(pMe);*ppUser = pMe;pMe->m_iScore=0;pMe->m_iLever=0;memset(pMe->m_iScores,0,sizeof(int)*10);memset(pMe->m_iLevers,0,sizeof(int)*10);for(iLoop = 0;iLoop <GSCRN_WIDTH_CL;iLoop++){for(jLoop=0;jLoop <GSCRN_HIGHT_CL;jLoop++){pMe->m_uiArea[iLoop][jLoop]=0;}}pMe->m_dwOldTime = 0;pMe->m_dwNewTime = 0;return true;}static bool TRS_TetrisHandle(void *pUser, DWORD evt, WORD w,DWORD dw) {switch(evt){case EVT_ROUND :TRS_HRound(pUser);break;case EVT_LEFT :TRS_HLeft(pUser);break;case EVT_RIGHT :TRS_HRight(pUser);break;case EVT_DOWN :TRS_HDown(pUser);break;case EVT_BOTTOM:TRS_HBottom(pUser);break;case EVT_QUIT :{HWND wnd = GetHWnd();if (MessageBox(wnd, _T("您要退出游戏吗?"), _T("提醒"), MB_OKCANCEL | MB_ICONQUESTION) == IDOK)TRS_Quit(pUser);}break;default:return false;}return true;}//初始化函数static void TRS_Init(void *pUser){PCTetrisApp pMe =(PCTetrisApp)pUser;initgraph(SCREEN_HIGHT,SCREEN_WIDTH); //初始化屏幕大小srand((unsigned)time(NULL)); //以当前时间作为随机种子TRS_NewGame();}static void TRS_DrawBackground(void *pUser);{PCTetrisApp pMe =(PCTetrisApp)pUser;setfont(TRS_GUIDE_FONT_SIZE,0,TRS_GUIDE_FONT_TYPE); //定义字体宋体,字高16,字宽比例自动适应outtextxy(TRS_OPERATION_TITLE_X,TRS_OPERATION_TITLE_Y,"操作提示:");outtextxy(TRS_MLEFT_X,TRS_MLEFT_Y,"a:左移");outtextxy(TRS_MRIGHT_X,TRS_MRIGHT_Y,"d:右移");outtextxy(TRS_MDOWN_X,TRS_MDOWN_Y,"s:下移");outtextxy(TRS_ROTATION_X,TRS_ROTATION_Y,"w:变形");outtextxy(TRS_MBOTTOM_X,TRS_MBOTTOM_Y,"空格:沉底");outtextxy(TRS_EXIT_X,TRS_EXIT_Y,"ESC:退出");setfont(50,0,"黑体");outtextxy(460,160,"Tetris");setfont(22,0,"宋体");outtextxy(20,20,"得分:");outtextxy(20,80,"等级:");setorigin(220,20); //设置坐标原点setfillstyle(WHITE); //设置填充颜色为白色//画游戏的边框bar3d(-21,-1,-6,GSCRN_HIGHT_CL * CELL_WIDTH,5,1);bar(-21,GSCRN_HIGHT_CL * CELL_WIDTH,GSCRN_WIDTH_CL * CELL_WIDTH,GSCRN_HIGHT_CL * CELL_WIDTH+20);bar3d(GSCRN_WIDTH_CL * CELL_WIDTH,-1,GSCRN_WIDTH_CL * CELL_WIDTH+15,GSCRN_HIGHT_CL * CELL_WIDTH+20,5,1);//画预览方块区域的边框rectangle((GSCRN_WIDTH_CL + 2) * CELL_WIDTH - 1, -1, (GSCRN_WIDTH_CL + 6) * CELL_WIDTH, 4 * CELL_WIDTH);}// 退出游戏static void TRS_Quit(void *pUser){PCTetrisApp pMe =(PCTetrisApp)pUser;closegraph();//释放应用空间free(pMe);exit(0);}// 结束游戏static void TRS_GameOver(void *pUser){HWND wnd = GetHWnd();if (MessageBox(wnd, _T("游戏结束。
python俄罗斯方块小游戏代码
import pygameimport random# 游戏参数WIDTH = 800HEIGHT = 600FPS = 60# 颜色常量BLACK = (0, 0, 0)WHITE = (255, 255, 255)RED = (255, 0, 0)GREEN = (0, 255, 0)BLUE = (0, 0, 255)# 方块大小和行列数BLOCK_SIZE = 30ROWS = HEIGHT // BLOCK_SIZECOLS = WIDTH // BLOCK_SIZE# 初始化Pygamepygame.init()screen = pygame.display.set_mode((WIDTH, HEIGHT))clock = pygame.time.Clock()# 定义方块类class Block(pygame.sprite.Sprite):def __init__(self, color):super().__init__()self.image = pygame.Surface((BLOCK_SIZE, BLOCK_SIZE))self.image.fill(color)self.rect = self.image.get_rect()# 定义俄罗斯方块类class Tetris:def __init__(self):self.grid = [[None] * COLS for _ in range(ROWS)]self.current_block = Noneself.next_block = Noneself.score = 0def create_block(self):shapes = [[[1, 1, 1, 1]], # I[[1, 1], [1, 1]], # O[[1, 1, 0], [0, 1, 1]], # Z[[0, 1, 1], [1, 1, 0]], # S[[1, 1, 1], [0, 0, 1]], # J[[1, 1, 1], [1, 0, 0]], # L[[1, 1, 1], [0, 1, 0]] # T]shape = random.choice(shapes)color = random.choice([RED, GREEN, BLUE])block = pygame.sprite.Group()for r in range(len(shape)):for c in range(len(shape[r])):if shape[r][c] == 1:b = Block(color)b.rect.x = c * BLOCK_SIZEb.rect.y = r * BLOCK_SIZEblock.add(b)return blockdef check_collision(self):for block in self.current_block:if block.rect.bottom >= HEIGHT or \self.grid[block.rect.bottom // BLOCK_SIZE][block.rect.x // BLOCK_SIZE] is not None:return Truereturn Falsedef update_grid(self):for block in self.current_block:self.grid[block.rect.y // BLOCK_SIZE][block.rect.x // BLOCK_SIZE] = blockdef remove_completed_rows(self):completed_rows = []for r in range(ROWS):if None not in self.grid[r]:completed_rows.append(r)for row in completed_rows:for c in range(COLS):self.grid[row][c] = Nonefor r in range(row, 0, -1):for c in range(COLS):self.grid[r][c] = self.grid[r - 1][c]if self.grid[r][c] is not None:self.grid[r][c].rect.y += BLOCK_SIZEself.score += 10def draw_grid(self):for r in range(ROWS):for c in range(COLS):block = self.grid[r][c]if block is not None:screen.blit(block.image, block.rect)def draw_score(self):font = pygame.font.SysFont(None, 30)text = font.render(f"Score: {self.score}", True, WHITE)screen.blit(text, (10, 10))def game_over(self):font = pygame.font.SysFont(None, 60)text = font.render("Game Over", True, RED)screen.blit(text, (WIDTH/2 - text.get_width()/2, HEIGHT/2 - text.get_height()/2))pygame.display.flip()pygame.time.wait(3000)def run(self):self.current_block = self.create_block()self.next_block = self.create_block()running = Truewhile running:clock.tick(FPS)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:这是一个简单的俄罗斯方块小游戏的Python代码示例。
俄罗斯方块C语言代码
#include <stdio.h>#include <dos.h>#include <conio.h>#include <graphics.h>#include <stdlib.h>#ifdef__cplusplus#define __CPPARGS ...#else#define __CPPARGS#endif#define MINBOXSIZE 15 /* 最小方块的尺寸*/#define BGCOLOR 7 /* 背景着色*/#define GX 200#define GY 10#define SJNUM 10000 /* 每当玩家打到一万分等级加一级*/ /* 按键码*/#define VK_LEFT 0x4b00#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_HOME 0x4700#define VK_END 0x4f00#define VK_SPACE 0x3920#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 /* 要出的下一个方块的纵坐标*/#define NEXTROW 12 /* 要出的下一个方块的横从标*/#define MAXROW 14 /* 游戏屏幕大小*/#define MAXCOL 20#define SCCOL 100 /*游戏屏幕大显示器上的相对位置*/#define SCROW 60int gril[22][16]; /* 游戏屏幕坐标*/int col=1,row=7; /* 当前方块的横纵坐标*/int boxfx=0,boxgs=0; /* 当前寺块的形壮和方向*/int nextboxfx=0,nextboxgs=0,maxcol=22;/*下一个方块的形壮和方向*/ int minboxcolor=6,nextminboxcolor=6;int num=0; /*游戏分*/int dj=0,gamedj[10]={18,16,14,12,10,8,6,4,2,1};/* 游戏等级*//* 以下我用了一个3维数组来纪录方块的最初形状和方向*/int boxstr[7][4][16]={{{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},{0,1,0,0,1,1,0,0,1,0,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},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}},{{1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0},{1,1,1,0,1,0,0,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},{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,0,0,0,0}},{{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0},{0,0,0,0,1,1,1,1,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,0,0,0,1,1,1,1,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}},{{0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{0,1,0,0,1,1,1,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}}};/* 随机得到当前方块和下一个方块的形状和方向*/void boxrad(){minboxcolor=nextminboxcolor;boxgs=nextboxgs;boxfx=nextboxfx;nextminboxcolor=random(14)+1;if(nextminboxcolor==4||nextminboxcolor==7||nextminboxcolor==8) nextminboxcolor=9;nextboxfx=F_DONG;nextboxgs=random(7);}/*初始化图形模试*/void init(int gdrive,int gmode){int errorcode;initgraph(&gdrive,&gmode,"e:\\tc");errorcode=graphresult();if(errorcode!=grOk){printf("error of: %s",grapherrormsg(errorcode));exit(1);}}/* 在图形模式下的清屏*/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){setfillstyle(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;b=SCROW+bsc;clscr(a+1,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE,color);if(color!=BGCOLOR){setcolor(bdcolor);line(a+1,b+1,a-1+MINBOXSIZE,b+1);line(a+1,b+1,a+1,b-1+MINBOXSIZE);line(a-1+MINBOXSIZE,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE); line(a+1,b-1+MINBOXSIZE,a-1+MINBOXSIZE,b-1+MINBOXSIZE); }}/*游戏中出现的文字*/void txt(int a,int b,char *txt,int font,int color){setcolor(color);settextstyle(0,0,font);outtextxy(a,b,txt);}/*windows 绘制*/void win(int a,int b,int c,int d,int bgcolor,int bordercolor){clscr(a,b,c,d,bgcolor);setcolor(bordercolor);line(a,b,c,b);line(a,b,a,d);line(a,d,c,d);line(c,b,c,d);}/* 当前方块的绘制*/void funbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+row+a)*MINBOXSIZE,(i+col+b)*MINBOXSIZE,color,bdcolor); }/*下一个方块的绘制*/void nextfunbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[nextboxgs][nextboxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+a)*MINBOXSIZE,(i+b)*MINBOXSIZE,color,bdcolor);}/*时间中断定义*/#define TIMER 0x1cint TimerCounter=0;void interrupt ( *oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)){oldhandler=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*由于游戏的规则,消掉都有最小方块的一行*/void delcol(int a){int i,j;for(i=a;i>1;i--)for(j=1;j<15;j++){minbox(j*MINBOXSIZE,i*MINBOXSIZE,BGCOLOR,BGCOLOR);gril[i][j]=gril[i-1][j];if(gril[i][j]==1)minbox(j*MINBOXSIZE,i*MINBOXSIZE,minboxcolor,0);}/*消掉所有都有最小方块的行*/ void delete(){int i,j,zero,delgx=0;char *nm="00000";for(i=1;i<21;i++){zero=0;for(j=1;j<15;j++)if(gril[j]==0)zero=1;if(zero==0){delcol(i);delgx++;}}num=num+delgx*delgx*10;dj=num/10000;sprintf(nm,"%d",num);clscr(456,173,500,200,4);txt(456,173,"Number:",1,15);txt(456,193,nm,1,15);}/*时间中断结束*/void KillTimer(){disable();setvect(TIMER,oldhandler); enable();}/* 测试当前方块是否可以向下落*/ int downok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i]; for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i+1][row+j])k=0;return(k);/* 测试当前方块是否可以向左行*/int leftok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j-1])k=0;return(k);}/* 测试当前方块是否可以向右行*/int rightok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j+1])k=0;return(k);}/* 测试当前方块是否可以变形*/int upok(){int i,j,k=1,a[4][4];for(i=0;i<4;i++)for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx+1][i];for(i=3;i>=0;i--)for(j=3;j>=0;j--)if(a[j] && gril[col+i][row+j])k=0;return(k);}/*当前方块落下之后,给屏幕坐标作标记*/ void setgril(){int i,j,a[4][4];funbox(0,0,minboxcolor,0);for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j])gril[col+i][row+j]=1;col=1;row=7;}/*游戏结束*/void gameover(){int i,j;for(i=20;i>0;i--)for(j=1;j<15;j++)minbox(j*MINBOXSIZE,i*MINBOXSIZE,2,0);txt(103,203,"Game Over",3,10);}/*按键的设置*/void call_key(int keyx){switch(keyx){case VK_DOWN: { /*下方向键,横坐标加一。
俄罗斯方块-C语言-完整代码
int y; SetConsoleTextAttribute(Output,0xf0);
for(y=4;y<26;y++) {
//两条纵线 gotoxyWithFullwidth(10,y-3);//鼠标定位
gotoxyWithFullwidth(10,y-3);//鼠标定位 printf("%2s"," "); gotoxyWithFullwidth(23,y-3);//鼠标定位 printf("%2s"," "); }
bool dead;//挂 }Manager;//结构体别名
//构造存储游戏控制相关数据的结构体 typedef struct TetrisControl {
bool pause;//暂停 bool clockwise;//旋转方向;顺时针方向为ture int direction;//移动方向:0向左移动 1向右移动 //游戏池内每格的颜色 //此版本是彩色的,仅用游戏池数据无法存储颜色 int color[28][16]; }Control;//Control是结构体别名
//初始状态的游戏池 //每个元素表示游戏池的一行 //两端各置两个1,底部两行全部为1,便于进行碰撞 //这样一来游戏池的宽度为12列 共16列 //当某个元素为OXFFFF时,说明该行已经填满 //顶部4行用于给方块,不显示 //底部2行不显示,显示出来的游戏池高度为22行 static const unsigned int gs_uInitialTetrisPool[28]= {
效果图如下
俄罗斯方块-C语言-完整代码
#ifndef _DAY7_H #define _DAY7_H #include<windows.h> #include<time.h> #include<stdbool.h> #include<conio.h>//控制台输入输出函数getch通过键盘进行的操作 //游戏区域位置设计 #define COL_BEGIN 2 #define COL_END 14 #define ROW_BEGIN 4 #define ROW_END 26
俄罗斯方块python代码
俄罗斯方块python代码俄罗斯方块Python代码俄罗斯方块是一款经典的电子游戏,由前苏联科学家阿列克谢·帕基特诺夫于1984年创造。
这个游戏的目标是通过移动、旋转和摆放不同形状的方块,使它们在屏幕上形成完整的水平行,当一行被填满时,会消除并得到积分。
下面是一个使用Python编写的俄罗斯方块代码示例:```pythonimport pygameimport random# 方块的形状SHAPES = [[[1, 1, 1, 1]], # I形状[[1, 1], [1, 1]], # O形状[[1, 1, 0], [0, 1, 1]], # Z形状[[0, 1, 1], [1, 1, 0]], # S形状[[1, 1, 1], [0, 1, 0]], # T形状[[1, 1, 1], [0, 0, 1]], # L形状[[1, 1, 1], [1, 0, 0]] # J形状]# 初始化游戏界面def init_game():pygame.init()screen = pygame.display.set_mode((300, 600))pygame.display.set_caption("俄罗斯方块")return screen# 创建方块def create_block():shape = random.choice(SHAPES)return shape# 绘制方块def draw_block(screen, block, x, y):for i in range(len(block)):for j in range(len(block[i])):if block[i][j] == 1:pygame.draw.rect(screen, (255, 0, 0), (x + j * 30, y + i * 30, 30, 30))# 游戏主循环def main():screen = init_game()clock = pygame.time.Clock()x, y = 100, 0 # 方块的初始位置block = create_block() # 创建一个方块while True:for event in pygame.event.get():if event.type == pygame.QUIT:pygame.quit()returnkeys = pygame.key.get_pressed()if keys[pygame.K_LEFT]:x -= 30if keys[pygame.K_RIGHT]:x += 30if keys[pygame.K_DOWN]:y += 30screen.fill((0, 0, 0)) # 清空屏幕draw_block(screen, block, x, y) # 绘制方块pygame.display.update()clock.tick(5) # 控制游戏帧率if __name__ == "__main__":main()```以上是一个简单的俄罗斯方块游戏的Python代码示例。
俄罗斯方块代码
俄罗斯方块代码清单:#define MAXCOM 7 //部件数#define WIDE 13 //游戏区域宽#define HIGH 26 //高#define SIZE 12 //组成游戏区域的方格大小#define TOP 50 //游戏左上角坐标#define LEFT 50#define EASY 500 //游戏难度#define NORMAL 300#define HARD 200typedef struct tagComponet{int intComID; //部件的ID号int intDimension; //存储该部件所需的数组维数int* pintArray; //指向存储该部件的数组}Componet;class CRusBlockView : public CView{……private:int m_intComID; // 当前下落的部件int m_intState[HIGH][WIDE]; //当前状态Componet m_Componets[MAXCOM]; //所有部件的内部表示int m_intScore; //分数int m_intLevel;Componet m_CurrentCom; //当前的部件POINT ptIndex; //部件数组在全局数组中的索引// 产生一个新的部件void NewComponet(void);// 是否还可以下落bool CanDown(void);// 刷新函数void MyInvalidateRect(POINT ptStart, int intDimension);// 消去行void Disappear(void);// 判断游戏是否结束bool CheckFail(void);// 是否还可以旋转bool CanRotate(void);// 是否还可以左移bool CanLeft(void);// 是否还可以右移bool CanRight(void);//检查是否有足够的空位显示新的部件,否则游戏结束bool CanNew();};CRusBlockView::CRusBlockView(){// TODO: add construction code herefor (int i=0;i<HIGH;i++)for(int j=0;j<WIDE;j++)m_intState[i][j]=0;m_intLevel=NORMAL; //初始化难度srand((unsigned) time(NULL)); //初始化随机数m_intScore=0;m_CurrentCom.intComID=-1;m_CurrentCom.intDimension=0;m_CurrentCom.pintArray=NULL;//初始化7个部件//0:方块m_Componets[0].intComID=0;m_Componets[0].intDimension=2;m_Componets[0].pintArray=new int[4];for (i=0;i<4;i++)m_Componets[0].pintArray[i]=1; // 1 1// 1 1//1:-|m_Componets[1].intComID=1;m_Componets[1].intDimension=3;m_Componets[1].pintArray=new int[9];m_Componets[1].pintArray[0]=0;m_Componets[1].pintArray[1]=1;m_Componets[1].pintArray[2]=0; // 0 1 0m_Componets[1].pintArray[3]=1; // 1 1 1m_Componets[1].pintArray[4]=1; // 0 0 0m_Componets[1].pintArray[5]=1;m_Componets[1].pintArray[6]=0;m_Componets[1].pintArray[7]=0;m_Componets[1].pintArray[8]=0;//2m_Componets[2].intComID=2;m_Componets[2].intDimension=3;m_Componets[2].pintArray=new int[9];m_Componets[2].pintArray[0]=1;m_Componets[2].pintArray[1]=0;m_Componets[2].pintArray[2]=0; // 1 0 0 m_Componets[2].pintArray[3]=1; // 1 1 0 m_Componets[2].pintArray[4]=1; // 0 1 0 m_Componets[2].pintArray[5]=0;m_Componets[2].pintArray[6]=0;m_Componets[2].pintArray[7]=1;m_Componets[2].pintArray[8]=0;//3m_Componets[3].intComID=3;m_Componets[3].intDimension=3;m_Componets[3].pintArray=new int[9];m_Componets[3].pintArray[0]=0;m_Componets[3].pintArray[1]=0;m_Componets[3].pintArray[2]=1; // 0 0 1 m_Componets[3].pintArray[3]=0; // 0 1 1 m_Componets[3].pintArray[4]=1; // 0 1 0 m_Componets[3].pintArray[5]=1;m_Componets[3].pintArray[6]=0;m_Componets[3].pintArray[7]=1;m_Componets[3].pintArray[8]=0;//4m_Componets[4].intComID=4;m_Componets[4].intDimension=3;m_Componets[4].pintArray=new int[9];m_Componets[4].pintArray[0]=1;m_Componets[4].pintArray[1]=0;m_Componets[4].pintArray[2]=0; // 1 0 0 m_Componets[4].pintArray[3]=1; // 1 1 1 m_Componets[4].pintArray[4]=1; // 0 0 0 m_Componets[4].pintArray[5]=1;m_Componets[4].pintArray[6]=0;m_Componets[4].pintArray[7]=0;m_Componets[4].pintArray[8]=0;//5m_Componets[5].intComID=5;m_Componets[5].intDimension=3;m_Componets[5].pintArray=new int[9];m_Componets[5].pintArray[0]=0;m_Componets[5].pintArray[1]=0;m_Componets[5].pintArray[2]=1; // 0 0 1m_Componets[5].pintArray[3]=1; // 1 1 1m_Componets[5].pintArray[4]=1; // 0 0 0m_Componets[5].pintArray[5]=1;m_Componets[5].pintArray[6]=0;m_Componets[5].pintArray[7]=0;m_Componets[5].pintArray[8]=0;//6m_Componets[6].intComID=6;m_Componets[6].intDimension=4;m_Componets[6].pintArray=new int[16];m_Componets[6].pintArray[0]=0;m_Componets[6].pintArray[1]=1;m_Componets[6].pintArray[2]=0; // 0 1 0 0m_Componets[6].pintArray[3]=0; // 0 1 0 0m_Componets[6].pintArray[4]=0; // 0 1 0 0m_Componets[6].pintArray[5]=1; // 0 1 0 0 m_Componets[6].pintArray[6]=0;m_Componets[6].pintArray[7]=0;m_Componets[6].pintArray[8]=0;m_Componets[6].pintArray[9]=1;m_Componets[6].pintArray[10]=0;m_Componets[6].pintArray[11]=0;m_Componets[6].pintArray[12]=0;m_Componets[6].pintArray[13]=1;m_Componets[6].pintArray[14]=0;m_Componets[6].pintArray[15]=0;}CRusBlockView::~CRusBlockView(){//释放内存for(int i=0;i<MAXCOM;i++)delete [] m_Componets[i].pintArray;delete [] m_CurrentCom.pintArray;}void CRusBlockView::OnDraw(CDC* pDC){CRusBlockDoc* pDoc = GetDocument();ASSERT_V ALID(pDoc);// TODO: add draw code for native data here//画游戏区域CBrush brushBK(RGB(135,197,255));CBrush* pbrushOld=pDC->SelectObject(&brushBK);pDC->Rectangle(LEFT-1,TOP-1,LEFT+WIDE*SIZE+1,TOP+HIGH*SIZE+1);//画不能移动的方块CBrush brushStick(RGB(127,127,127));pDC->SelectObject(&brushStick);for (int i=0;i<HIGH;i++)for(int j=0;j<WIDE;j++)if(m_intState[i][j]==1)pDC->Rectangle(LEFT+SIZE*j,TOP+SIZE*i,LEFT+SIZE*(j+1),TOP+SIZE*(i+1));//画下落的部件if(m_CurrentCom.intComID>=0){CBrush brushCom(RGB(0,255,0));pDC->SelectObject(&brushCom);int intDimension=m_CurrentCom.intDimension;for(int i=0;i<intDimension*intDimension;i++){if(m_CurrentCom.pintArray[i]==1){int m=ptIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=ptIndex.y+(i%intDimension);pDC->Rectangle(LEFT+SIZE*n,TOP+SIZE*m,LEFT+SIZE*(n+1),TOP+SIZE*(m+1));}}}//显示得分CString strOut;strOut.Format("得分%d",m_intScore);pDC->TextOut(LEFT+WIDE*SIZE+50,TOP+100,strOut);pDC->SelectObject(&pbrushOld);}void CRusBlockView::OnTimer(UINT nIDEvent){// TODO: Add your message handler code here and/or call defaultint intDimension=m_CurrentCom.intDimension;if(CanDown()) //可以下落{//擦除MyInvalidateRect(ptIndex,intDimension);//下落ptIndex.x++;//显示新位置上的部件MyInvalidateRect(ptIndex,intDimension);}else{for(int i=0;i<intDimension*intDimension;i++){if(m_CurrentCom.pintArray[i]==1){int m=ptIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=ptIndex.y+(i%intDimension);m_intState[m][n]=1;}}MyInvalidateRect(ptIndex,intDimension);Disappear(); //消去行if(CheckFail()) //游戏结束{m_CurrentCom.intComID=-1;KillTimer(1);MessageBox("Game Over!");}elseNewComponet(); //新部件}CView::OnTimer(nIDEvent);}void CRusBlockView::OnKeyDown(UINT nChar, UINT nRepCnt, UINT nFlags){// TODO: Add your message handler code here and/or call defaultint intDimension=m_CurrentCom.intDimension;switch(nChar) //left 37, right 39, up 38{case 37:if(CanLeft()){//擦除MyInvalidateRect(ptIndex,intDimension);//左移ptIndex.y--;//显示新位置上的部件MyInvalidateRect(ptIndex,intDimension);}break;case 39:if(CanRight()){//擦除MyInvalidateRect(ptIndex,intDimension);//右移ptIndex.y++;//显示新位置上的部件MyInvalidateRect(ptIndex,intDimension);}break;case 38:if(CanRotate()){//擦除MyInvalidateRect(ptIndex,intDimension);//转动int* pintNewCom=new int[intDimension*intDimension];for(int i=0;i<intDimension*intDimension;i++){intintR=intDimension*(intDimension-(i%intDimension)-1)+(i/intDimension);pintNewCom[i]=m_CurrentCom.pintArray[intR];}for(i=0;i<intDimension*intDimension;i++){m_CurrentCom.pintArray[i]=pintNewCom[i];}delete [] pintNewCom;//显示新位置上的部件MyInvalidateRect(ptIndex,intDimension);}break;}CView::OnKeyDown(nChar, nRepCnt, nFlags);}void CRusBlockView::NewComponet(void){int intComID=rand()%7; //产生随机数m_CurrentCom.intComID=intComID;int intDimension=m_Componets[intComID].intDimension;m_CurrentCom.intDimension=intDimension;delete [] m_CurrentCom.pintArray; //删除上一个部件的内存分配m_CurrentCom.pintArray=new int[intDimension*intDimension];//拷贝部件for(int i=0;i<intDimension*intDimension;i++)m_CurrentCom.pintArray[i]=m_Componets[intComID].pintArray[i];ptIndex.x=0;//行ptIndex.y=5;//列//检查是否有足够的空位显示新的部件,否则游戏结束if(CanNew()){//显示该部件MyInvalidateRect(ptIndex,intDimension);}else{m_CurrentCom.intComID=-1;KillTimer(1);MessageBox("Game Over!");}}bool CRusBlockView::CanDown(void){bool boolDown=true;POINT intNewIndex=ptIndex; //假设可以下落intNewIndex.x++;int intDimension=m_CurrentCom.intDimension;for(int i=0;i<intDimension*intDimension;i++){if(m_CurrentCom.pintArray[i]==1){int m=intNewIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=intNewIndex.y+(i%intDimension);if(m>=HIGH || m_intState[m][n]==1) //被挡住或出游戏区域boolDown=false;}}return boolDown;}// 可以左移bool CRusBlockView::CanLeft(void){bool boolLeft=true;int intDimension=m_CurrentCom.intDimension;POINT ptNewIndex=ptIndex; //假设可以左移ptNewIndex.y--;for(int i=0;i<intDimension*intDimension;i++){if(m_CurrentCom.pintArray[i]==1){int m=ptNewIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=ptNewIndex.y+(i%intDimension);if(n<0 || m_intState[m][n]==1) //被挡住或出游戏区域boolLeft=false;}}return boolLeft;}// 可以右移bool CRusBlockView::CanRight(void){bool boolRight=true;int intDimension=m_CurrentCom.intDimension;POINT ptNewIndex=ptIndex; //假设可以右移ptNewIndex.y++;for(int i=0;i<intDimension*intDimension;i++){if(m_CurrentCom.pintArray[i]==1){int m=ptNewIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=ptNewIndex.y+(i%intDimension);if(n>=WIDE || m_intState[m][n]==1) //被挡住或出游戏区域boolRight=false;}}return boolRight;}// 可以旋转bool CRusBlockView::CanRotate(void){bool boolRotate=true;int intDimension=m_CurrentCom.intDimension;POINT ptNewIndex=ptIndex;//假设可以转动//新的矩阵存储转动后的部件int* pintNewCom=new int[intDimension*intDimension];//顺时针转动并判断for(int i=0;i<intDimension*intDimension;i++){int intR=intDimension*(intDimension-(i%intDimension)-1)+(i/intDimension);pintNewCom[i]=m_CurrentCom.pintArray[intR];if(pintNewCom[i]==1){int m=ptNewIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=ptNewIndex.y+(i%intDimension);if(n<0 || m_intState[m][n]==1 || n>=WIDE || m>=HIGH) //被挡住或出游戏区域boolRotate=false;}}delete [] pintNewCom;return boolRotate;}// 可以产生新的部件bool CRusBlockView::CanNew(void){bool boolNew=true;int intDimension=m_CurrentCom.intDimension;POINT ptNewIndex=ptIndex; //假设可以for(int i=0;i<intDimension*intDimension;i++){if(m_CurrentCom.pintArray[i]==1){int m=ptNewIndex.x+i/intDimension; //找出部件对应整体数组中的位置int n=ptNewIndex.y+(i%intDimension);if(m_intState[m][n]==1) //被挡住boolNew=false;}}return boolNew;}//判断游戏是否结束bool CRusBlockView::CheckFail(void){bool boolEnd=false;for(int j=0;j<WIDE;j++)if(m_intState[0][j]==1)boolEnd=true;return boolEnd;}//消去行void CRusBlockView::Disappear(void){int intLine=0; //一次消去的行数for(int i=HIGH-1;i>=0;i--){bool boolLine=true;for(int j=0;j<WIDE;j++)if(m_intState[i][j]==0)boolLine=false;if(boolLine) //行可以消去{intLine++;//向下移动for(int m=i;m>0;m--)for(int n=0;n<WIDE;n++)m_intState[m][n]=m_intState[m-1][n];for(int n=0;n<WIDE;n++)m_intState[0][n]=0; //最顶层清除i++;}}if(intLine>0){m_intScore+=(intLine-1)*200+100;InvalidateRect(CRect(LEFT+WIDE*SIZE+50,TOP+100,LEFT+WIDE*SIZE+200,TOP+200));}InvalidateRect(CRect(LEFT,TOP,LEFT+WIDE*SIZE,TOP+HIGH*SIZE));}void CRusBlockView::OnGameStart(){// TODO: Add your command handler code herefor (int i=0;i<HIGH;i++)for(int j=0;j<WIDE;j++)m_intState[i][j]=0;m_intScore=0;Invalidate();NewComponet();SetTimer(1,m_intLevel,NULL);}void CRusBlockView::OnGameEnd(){// TODO: Add your command handler code hereKillTimer(1);}void CRusBlockView::OnLevelNormal(){// TODO: Add your command handler code herem_intLevel=NORMAL;}void CRusBlockView::OnLevelHard(){// TODO: Add your command handler code herem_intLevel=HARD;}void CRusBlockView::OnLevelEasy(){// TODO: Add your command handler code herem_intLevel=EASY;}//刷新函数void CRusBlockView::MyInvalidateRect(POINT ptStart, int intDimension) {//刷新了一个以ptStart为左上角,长度为intDimension的正方形区域,//同时注意判断了不要越出游戏区域int x1=LEFT+ptStart.y*SIZE;x1=x1>LEFT?x1:LEFT;int y1=TOP+ptStart.x*SIZE;y1=y1>TOP?y1:TOP;int x2=LEFT+(ptStart.y+intDimension)*SIZE;x2=x2>LEFT+WIDE*SIZE?LEFT+WIDE*SIZE:x2;int y2=TOP+(ptStart.x+intDimension)*SIZE;y2=y2>TOP+HIGH*SIZE?TOP+HIGH*SIZE:y2;InvalidateRect(CRect(x1,y1,x2,y2));// InvalidateRect(CRect(50,50,50+13*12,50+26*12));}。
俄罗斯方块游戏代码
#include <stdio.h>#include <dos.h>#include <conio.h>#include <graphics.h>#include <stdlib.h>#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endif#define MINBOXSIZE 15 /* 最小方块的尺寸*/#define BGCOLOR 7 /* 背景着色*/#define GX 200#define GY 10#define SJNUM 10000 /* 每当玩家打到一万分等级加一级*/ /* 按键码*/#define VK_LEFT 0x4b00#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_HOME 0x4700#define VK_END 0x4f00#define VK_SPACE 0x3920#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 /* 要出的下一个方块的纵坐标*/#define NEXTROW 12 /* 要出的下一个方块的横从标*/#define MAXROW 14 /* 游戏屏幕大小*/#define MAXCOL 20#define SCCOL 100 /*游戏屏幕大显示器上的相对位置*/#define SCROW 60int gril[22][16]; /* 游戏屏幕坐标*/int col=1,row=7; /* 当前方块的横纵坐标*/int boxfx=0,boxgs=0; /* 当前寺块的形壮和方向*/int nextboxfx=0,nextboxgs=0,maxcol=22;/*下一个方块的形壮和方向*/ int minboxcolor=6,nextminboxcolor=6;int num=0; /*游戏分*/int dj=0,gamedj[10]={18,16,14,12,10,8,6,4,2,1};/* 游戏等级*//* 以下我用了一个3维数组来纪录方块的最初形状和方向*/int boxstr[7][4][16]={{{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},{0,1,0,0,1,1,0,0,1,0,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},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}},{{1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0},{1,1,1,0,1,0,0,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},{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,0,0,0,0}},{{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0},{0,0,0,0,1,1,1,1,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,0,0,0,1,1,1,1,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}},{{0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{0,1,0,0,1,1,1,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}}};/* 随机得到当前方块和下一个方块的形状和方向*/void boxrad(){minboxcolor=nextminboxcolor;boxgs=nextboxgs;boxfx=nextboxfx;nextminboxcolor=random(14)+1;if(nextminboxcolor==4||nextminboxcolor==7||nextminboxcolor==8) nextminboxcolor=9;nextboxfx=F_DONG;nextboxgs=random(7);}/*初始化图形模试*/void init(int gdrive,int gmode){int errorcode;initgraph(&gdrive,&gmode,"e:\\tc");errorcode=graphresult();if(errorcode!=grOk){printf("error of: %s",grapherrormsg(errorcode));exit(1);}}/* 在图形模式下的清屏*/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){setfillstyle(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;b=SCROW+bsc;clscr(a+1,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE,color);if(color!=BGCOLOR){setcolor(bdcolor);line(a+1,b+1,a-1+MINBOXSIZE,b+1);line(a+1,b+1,a+1,b-1+MINBOXSIZE);line(a-1+MINBOXSIZE,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE); line(a+1,b-1+MINBOXSIZE,a-1+MINBOXSIZE,b-1+MINBOXSIZE); }}/*游戏中出现的文字*/void txt(int a,int b,char *txt,int font,int color){setcolor(color);settextstyle(0,0,font);outtextxy(a,b,txt);}/*windows 绘制*/void win(int a,int b,int c,int d,int bgcolor,int bordercolor){clscr(a,b,c,d,bgcolor);setcolor(bordercolor);line(a,b,c,b);line(a,b,a,d);line(a,d,c,d);line(c,b,c,d);}/* 当前方块的绘制*/void funbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+row+a)*MINBOXSIZE,(i+col+b)*MINBOXSIZE,color,bdcolor); }/*下一个方块的绘制*/void nextfunbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[nextboxgs][nextboxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+a)*MINBOXSIZE,(i+b)*MINBOXSIZE,color,bdcolor);}/*时间中断定义*/#define TIMER 0x1cint TimerCounter=0;void interrupt ( *oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)){oldhandler=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*由于游戏的规则,消掉都有最小方块的一行*/void delcol(int a){int i,j;for(i=a;i>1;i--)for(j=1;j<15;j++){minbox(j*MINBOXSIZE,i*MINBOXSIZE,BGCOLOR,BGCOLOR);gril[i][j]=gril[i-1][j];if(gril[i][j]==1)minbox(j*MINBOXSIZE,i*MINBOXSIZE,minboxcolor,0);}/*消掉所有都有最小方块的行*/ void delete(){int i,j,zero,delgx=0;char *nm="00000";for(i=1;i<21;i++){zero=0;for(j=1;j<15;j++)if(gril[j]==0)zero=1;if(zero==0){delcol(i);delgx++;}}num=num+delgx*delgx*10;dj=num/10000;sprintf(nm,"%d",num);clscr(456,173,500,200,4);txt(456,173,"Number:",1,15);txt(456,193,nm,1,15);}/*时间中断结束*/void KillTimer(){disable();setvect(TIMER,oldhandler); enable();}/* 测试当前方块是否可以向下落*/ int downok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i]; for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i+1][row+j])k=0;return(k);/* 测试当前方块是否可以向左行*/int leftok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j-1])k=0;return(k);}/* 测试当前方块是否可以向右行*/int rightok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j+1])k=0;return(k);}/* 测试当前方块是否可以变形*/int upok(){int i,j,k=1,a[4][4];for(i=0;i<4;i++)for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx+1][i];for(i=3;i>=0;i--)for(j=3;j>=0;j--)if(a[j] && gril[col+i][row+j])k=0;return(k);}/*当前方块落下之后,给屏幕坐标作标记*/ void setgril(){int i,j,a[4][4];funbox(0,0,minboxcolor,0);for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j])gril[col+i][row+j]=1;col=1;row=7;}/*游戏结束*/void gameover(){int i,j;for(i=20;i>0;i--)for(j=1;j<15;j++)minbox(j*MINBOXSIZE,i*MINBOXSIZE,2,0);txt(103,203,"Game Over",3,10);}/*按键的设置*/void call_key(int keyx){switch(keyx){case VK_DOWN: { /*下方向键,横坐标加一。
C语言俄罗斯方块游戏源代码
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<Heng && Touch(ActH,ActS,1,0)==CAN) { ActH++;} 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 SOUNபைடு நூலகம்S : case SOUNDs :if (Sounds==CAN) Sounds=CANNOT; else Sounds=CAN;break; case UP :if(Act==7) { while(acts<Shu-1&&Position[ActH][acts]!=1) acts++; Position[ActH][acts]=0; DrawBox(ActH,acts,0); acts=ActS; break; } else { Display(0);
俄罗斯方块游戏原代码
#include<stdio.h>#include<stdlib.h>#include<dos.h>#include<graphics.h> /*系统提供的头文件*/#define TIMER 0x1c /*定义时钟中断的中断号*/#define VK_LEFT 0x4b00/*左移键*/#define VK_RIGHT 0x4d00/*右移键*/#define VK_DOWN 0x5000 /*加速键*/#define VK_UP 0x4800 /*变形键*/#define VK_SPACE 0x3920 /*变形键*/#define VK_END 0x4f00 /*暂停键*/#define VK_ESC 0x011b#define VK_ENTER 0x1c0d#define BSIZE 16 /*方块的边长是16个象素*/#define MAX_SHAPE 19 /*总共有19种各形态的方块*/#define BOARD_WIDTH 10 /*游戏面板的宽度,以方块的宽度为单位*/#define BOARD_HEIGHT 20/*游戏面板的高度,以方块的宽度为单位*/#define BGCOLOR BLACK /*背景色*/#define FORECOLOR WHITE /*前景色*/#define FALSE 0#define TRUE 1#define EMPTY 0#define FILLED 1#define BOARD_LEFT_X 10 /*游戏面板左上角的横坐标*/#define BOARD_LEFT_Y 5 /*游戏面板左上角的纵坐标*//*定义全局变量*/extern int Gameboard[BOARD_WIDTH+2][BOARD_HEIGHT+2];extern int nCurrent_block_index ; /*当前下落的方块的索引号*/ extern int nNext_block_index ; /*下一个方块的索引号*/extern int nSpeed, nScore; /*速度和得分*/extern int nSpeedUpScore; /*第一次要加速需达到的分数*/extern int bAccel, bOver;extern int nOriginX, nOriginY;/*某一形状的原点的绝对坐标*/ extern unsigned int TimerCounter; /* 计时变量,每秒钟增加18 */struct block{int arrXY[8];int nColor;int nNext;}; /*保存某一形状信息的结构体*/typedef struct block BLOCK;extern BLOCK arrayBlock[19];void interrupt newtimer(void);void SetTimer(void interrupt(*IntProc)(void));void KillTimer();void InitializeGraph();void InitializeGameboard() ;void DrawSquare(int x, int y);void DrawBlock(int BlockIndex, int sx, int sy,int color); int IsConflict(int BlockIndex, int x, int y);void HandleLeft(int BlockIndex,int *x, int *y);void HandleRight(int BlockIndex,int *x, int *y);void HandleUp(int *BlockIndex,int *x, int *y);int HandleDown(int BlockIndex,int *x, int *y);int IsLineFull(int y);void KillLine(int y);int KillLines(int y);int IsGameOver();int GameOver();void StartGame();void ProcessInGame();void game();void win();void help();void design();void show_win();void main(){win();menu();}void help(){clrscr();help();textcolor(WHITE);gotoxy(20,4);cprintf("\xDB\xDB\xDB\xDB\xB2 HELP ABOUT THE Game \xB2\xDB\xDB\xDB\xDB"); gotoxy(4,6);cprintf(" [ 1 ] - Metamorphose : Press the left key square moves left "); gotoxy(30,8);cprintf("Press the left key square move to the right");gotoxy(30,10);cprintf("Press down key square accelerate whereabouts");gotoxy(4,12);cprintf(" [ 2 ] - Speed up : Press the button oblong rotating ");gotoxy(4,14);cprintf(" [ 3 ] - Game Start : Press Enter to button to start the game"); gotoxy(4,16);cprintf(" [ 4 ] - Game Over : Press the ESC key to quit the game");gotoxy(30,18);cprintf("YOU WANT TO BE HELPFUL");gotoxy(6,23);printf("Press any key to go to the MAIN MENU ........");getche();}menu(){int x;do{{clrscr();design();textcolor(WHITE);cprintf("\xDB\xDB\xDB\xDB\xB2 Tetris Game \xB2\xDB\xDB\xDB\xDB");gotoxy(3,4);cprintf("--------------------------------------------------------------------------");gotoxy(35,5);cprintf("MAIN MENU");gotoxy(26,8);cprintf(" 1 - New Game ");gotoxy(26,9);cprintf(" 2 - Rank ");gotoxy(26,10);cprintf(" 3 - HELP ");gotoxy(26,11);cprintf(" 4 - The Game Explain ");gotoxy(26,12);cprintf(" 5 - EXIT ");x=toupper(getch());switch(x){case '1':game();break;case '2':cprintf("At present there is no ranking");break;case '3':help();break;case '4':cprintf("This game by LuWenJun,ChenLong,QiWei jointly compiled,Deficiencies still please forgive me");break;case '5':exit(0);break;default:clrscr();design();gotoxy(17,12);printf("\a\xDB\xB2 WRONG ENTRY : PRESS ANY KEY AND TRY AGAIN"); getche();}}}while(x!='5');return x;}void win(){int i,graphdriver,graphmode,size,page;char s1[30],s2[30];graphdriver=DETECT;initgraph(&graphdriver,&graphmode,"c:\\turboc2");cleardevice();setbkcolor(BLUE);setviewport(40,40,600,440,1);setfillstyle(1,2);setcolor(YELLOW);rectangle(0,0,560,400);floodfill(50,50,14);rectangle(20,20,540,380);setfillstyle(1,13);floodfill(21,300,14);setcolor(BLACK);settextstyle(1,0,6);outtextxy(100,60,"Welcom You");setviewport(100,200,540,380,0);setcolor(14);setfillstyle(1,12);rectangle(20,20,420,120);settextstyle(2,0,9);floodfill(21,100,14);sprintf(s1,"Let's our play Tetris Game!");setcolor(YELLOW);outtextxy(60,40,s1);sprintf(s2,"Press any key to play....");setcolor(1);settextstyle(4,0,3);outtextxy(110,80,s2);getch();closegraph();}void design(){int i;clrscr();textcolor(14);gotoxy(2,2);cprintf("\xC9");gotoxy(3,2);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,2);cprintf("\xBB");gotoxy(2,3);cprintf("\xBA");gotoxy(2,4);cprintf("\xBA");gotoxy(2,5);cprintf("\xBA");gotoxy(2,6);cprintf("\xBA");gotoxy(2,7);cprintf("\xBA");gotoxy(2,8);cprintf("\xB A");gotoxy(2,9);cprintf("\xBA");gotoxy(2,10);cprintf("\xBA");gotoxy(2,11);cprintf("\ xBA");gotoxy(2,12);cprintf("\xBA");gotoxy(2,13);cprintf("\xBA");gotoxy(2,14);cprintf("\xBA");gotoxy(2,15);cprintf(" \xBA");gotoxy(2,16);cprintf("\xBA");gotoxy(2,17);cprintf("\xBA");gotoxy(2,18);cprintf("\xBA");gotoxy(2,22);cprintf(" \xCC");gotoxy(2,19);cprintf("\xBA");gotoxy(2,20);cprintf("\xBA");gotoxy(2,21);cprintf(" \xBA");gotoxy(2,24);cprintf("\xC8");gotoxy(2,23);cprintf("\xBA");gotoxy(3,24);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,18);cprintf("\xBA");gotoxy(77,19);cprintf("\xBA");gotoxy(77,20);cprint f("\xBA");gotoxy(77,21);cprintf("\xBA");gotoxy(77,24);cprintf("\xBC");gotoxy(77,23);cprintf("\xBA");gotoxy(3,22);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,22);cprintf("\xB9");gotoxy(77,3);cprintf("\xBA");gotoxy(77,4);cprintf("\xBA");gotoxy(77,5);cprintf("\xBA");gotoxy(77,6);cprintf("\xBA");gotoxy(77,7);cprintf("\xBA");gotoxy(77,8);cprintf(" \xBA");gotoxy(77,9);cprintf("\xBA");gotoxy(77,10);cprintf("\xBA");gotoxy(77,11);cprintf ("\xBA");gotoxy(77,12);cprintf("\xBA");gotoxy(77,13);cprintf("\xBA");gotoxy(77,14);cprintf("\xBA");gotoxy(77,15);cprint f("\xBA");gotoxy(77,16);cprintf("\xBA");gotoxy(77,17);cprintf("\xBA");textcolor(RED);}void show_win(void){union REGS in, out;in.x.ax = 0x1;int86(0x33, &in, &out);}/*********************************************************** 函数原型:void InitializeGraph() * * 传入参数:无 ** 返回值:无 ** 函数功能:初始化进入图形模式***********************************************************/void InitializeGraph(){int gdriver = VGA, gmode=VGAHI, errorcode;/* 初始化图形模式*/initgraph(&gdriver, &gmode, "c:\\turboc2");/* 读取初始化结果 */errorcode = graphresult();if (errorcode != grOk) /* 错误发生 */{printf("Graphics error: %s\n", grapherrormsg(errorcode));printf("Press any key to halt:");getch();exit(1); /* 返回错误码 */}}/*********************************************************** 函数原型:void InitializeGameboard() ** 传入参数:无** 返回值:无** 函数功能:初始化游戏面板以及下一形状提示框、计分框和难度框 ***********************************************************/void InitializeGameboard(){/* 绘制游戏面板(即游戏区域)*/setfillstyle(SOLID_FILL,BGCOLOR);bar(BSIZE*BOARD_LEFT_X,BSIZE*BOARD_LEFT_Y,BSIZE*(BOARD_LEFT_X+BOARD_WIDTH),BSIZE*(BOARD_LEFT_Y+BOARD_HEIGHT));setcolor(WHITE);rectangle(BSIZE*BOARD_LEFT_X,BSIZE*BOARD_LEFT_Y,BSIZE*(BOARD_LEFT_X+BOARD_WIDTH),BSIZE*(BOARD_LEFT_Y+BOARD_HEIGHT));/*绘制下一形状提示框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(5+1), "next");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*(24.5+2), BSIZE*6, BSIZE*(24.5+2+5), BSIZE*(6+5));setcolor(YELLOW);rectangle(BSIZE*(24.5+2), BSIZE*6, BSIZE*(24.5+2+5), BSIZE*(6+5));/*绘制速度框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(12+1), "level");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1)); setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(13+1), "0");/*绘制计分框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(19+1), "score");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1)); setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(20+1), "0");}int Gameboard[BOARD_WIDTH+2][BOARD_HEIGHT+2];int nCurrent_block_index;/* 当前下落的方块的索引号*/int nNext_block_index ; /*下一个方块的索引号*/int nSpeed, nScore; /*速度和得分*/int nSpeedUpScore = 1000; /*第一次要加速需达到的分数*/int bAccel, bOver;int nOriginX=5, nOriginY=1;/*某一形状的原点的绝对坐标*/ BLOCK arrayBlock[19]={/*x1,y1,x2,y2,x3,y3,x4,y4, color, next*/{ 0,-2, 0,-1, 0, 0, 1, 0, CYAN, 1}, /* */{-1, 0, 0, 0, 1,-1, 1, 0, CYAN, 2}, /* # */{ 0,-2, 1,-2, 1,-1, 1, 0, CYAN, 3}, /* # */{-1,-1,-1, 0, 0,-1, 1,-1, CYAN, 0}, /* ## */{ 0,-2, 0,-1, 0, 0, 1,-2,MAGENTA, 5}, /* */{-1,-1,-1, 0, 0, 0, 1, 0,MAGENTA, 6}, /* ## */{ 0, 0, 1,-2, 1,-1, 1, 0,MAGENTA, 7}, /* # */{-1,-1, 0,-1, 1,-1, 1, 0,MAGENTA, 4}, /* # */{-1, 0, 0,-1, 0, 0, 1, 0,YELLOW, 9}, /* */{-1,-1, 0,-2, 0,-1, 0, 0,YELLOW, 10}, /* */{-1,-1, 0,-1, 0, 0, 1,-1,YELLOW, 11}, /* # */{ 0,-2, 0,-1, 0, 0, 1,-1,YELLOW, 8}, /* ### */{-1, 0, 0,-1, 0, 0, 1,-1, BROWN, 13}, /* ## */{ 0,-2, 0,-1, 1,-1, 1, 0, BROWN, 12}, /* ## */{-1,-1, 0,-1, 0, 0, 1, 0, WHITE, 15}, /* ## */{ 0,-1, 0, 0, 1,-2, 1,-1, WHITE, 14}, /* ## */{ 0,-3, 0,-2, 0,-1, 0, 0, RED, 17},/* # */{-1, 0, 0, 0, 1, 0, 2, 0, RED, 16},/* # *//* # *//* # */{ 0,-1, 0, 0, 1,-1, 1, 0, BLUE, 18},/* ## *//* ## */};/*********************************************************** 函数原型:void StartGame () ** 传入参数:无** 返回值:无 ** 函数功能:游戏开始时调用的函数,其中绘制界面需调用函数 ** InitializeGameboard(), 接下来需初始化游戏面板的 ** 各个方块和一些全局变量的初值 ***********************************************************/void StartGame(){int i,j;/*设置游戏面板中每个方块的初始值*/for(j=0;j<=BOARD_HEIGHT;j++)for(i=0;i<BOARD_WIDTH+2;i++){if(i==0 || i==BOARD_WIDTH+1)Gameboard[i][j] = FILLED;elseGameboard[i][j] = EMPTY;}for(i=0;i<BOARD_WIDTH+2;i++)Gameboard[i][BOARD_HEIGHT+1] = FILLED;InitializeGameboard();/*设置游戏变量的初值*/nNext_block_index = -1; /*游戏初始,没有下一个形状的索引号*/nSpeed = 0;nScore = 0;}/*********************************************************** 函数原型:void ProcessInGame() ** 传入参数:无** 返回值:无** 函数功能:核心函数,主要用于处理在游戏中的各种事件(如按下各种按键) ***********************************************************/void ProcessInGame(){int key;bioskey(0);randomize();while(1){if(nNext_block_index==-1){nCurrent_block_index = rand()%19;nNext_block_index = rand()%19;/*绘制下一个提示形状*/DrawBlock(nNext_block_index,19,6,arrayBlock[nNext_block_index].nColor );}else{nCurrent_block_index = nNext_block_index;DrawBlock(nNext_block_index, 19,6,BGCOLOR ); /* 消除原来的提示形状 */nNext_block_index = rand()%19;DrawBlock(nNext_block_index,19,6,arrayBlock[nNext_block_index].nColor ); /*绘制下一个提示形状 */}nOriginX=5, nOriginY=1;TimerCounter = 0;DrawBlock(nCurrent_block_index, nOriginX,nOriginY, arrayBlock[nCurrent_block_index].nColor );/*在面板内绘制当前形状*/while(1){if (bioskey(1))key=bioskey(0);else key=0;bAccel = FALSE;switch(key){case VK_LEFT: /* 左移 */HandleLeft(nCurrent_block_index,&nOriginX,&nOriginY );break;case VK_RIGHT: /* 右移 */HandleRight(nCurrent_block_index,&nOriginX,&nOriginY );break;case VK_UP: /* 旋转 */case VK_SPACE:HandleUp(&nCurrent_block_index, &nOriginX,&nOriginY);break;case VK_DOWN: /* 下落加速键 */bAccel=TRUE;break;case VK_END: /* 暂停*/bioskey(0);break;case VK_ESC: /* 退出游戏 */bOver=TRUE;return;}if(bAccel || TimerCounter>(20-nSpeed*2))if(HandleDown(nCurrent_block_index,&nOriginX,&nOriginY))break;if(bOver)return;}}}/*********************************************************** 函数原型:void main() ** 传入参数:无 ** 返回值:无 ** 函数功能:入口函数,包含俄罗斯方块程序的主流程 ***********************************************************/void game(){InitializeGraph();SetTimer(newtimer); /*设置新的时钟中断*/while(1){StartGame();ProcessInGame();if(GameOver())break;bOver = FALSE;}KillTimer();closegraph();}unsigned int TimerCounter=0; /* 计时变量,每秒钟增加18 *//*********************************************************** 函数原型:void interrupt (*oldtimer)(void) ** 传入参数:无** 返回值:无** 函数功能:指向原来时钟中断处理过程入口的中断处理函数指针(句柄) ***********************************************************/void interrupt (*oldtimer)(void);/*********************************************************** 函数原型:void interrupt newtimer(void) ** 传入参数:无 ** 返回值:无 ** 函数功能:新的时钟中断处理函数 ***********************************************************/void interrupt newtimer(void){(*oldtimer)();TimerCounter++;}/*********************************************************** 函数原型:void SetTimer(void interrupt(*)(void)) ** 传入参数:无 ** 返回值:无 ** 函数功能:设置新的时钟中断处理函数 ***********************************************************/void SetTimer(void interrupt(*IntProc)(void)){oldtimer=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*********************************************************** 函数原型:void KillTimer() ** 传入参数:无 ** 返回值:无 ** 函数功能:恢复原先的时钟中断处理函数 ***********************************************************/void KillTimer(){disable();setvect(TIMER,oldtimer);enable();}/*********************************************************** 函数原型:void DrawSquare(int x, int y) ** 传入参数:游戏面板中的横坐标x,纵坐标y ** 返回值:无 ** 函数功能:在坐标(x, y)处绘制方块 ***********************************************************/void DrawSquare(int x, int y){if(y<1)return;bar(BSIZE*(x+9)+1,BSIZE*(y+4)+1,BSIZE*(x+10)-1,BSIZE*(y+5)-1);}/*********************************************************** 函数原型:void DrawBlock(int BlockIndex, int sx, int sy,int color) ** 传入参数:形状的索引BlockIndex,绝对横坐标x,绝对纵坐标y,颜色color ** 返回值:无** 函数功能:在坐标(sx, sy)处绘制颜色为color的形状***********************************************************/void DrawBlock(int BlockIndex, int sx, int sy,int color){int i,c;setfillstyle(SOLID_FILL, color);for(i=0;i<7;i+=2)DrawSquare(arrayBlock[BlockIndex].arrXY[i]+sx,arrayBlock[BlockIndex].arrXY[i+1]+sy);}/*********************************************************** 函数原型:int IsConflict(int BlockIndex, int x, int y) ** 传入参数:形状的索引BlockIndex,绝对横坐标x,绝对纵坐标y ** 返回值:无冲突返回0,有冲突返回1 ** 函数功能:判断形状是否能存在于坐标(x, y)处 * **********************************************************/int IsConflict(int BlockIndex, int x, int y){int i;for (i=0;i<=7;i++,i++){if (arrayBlock[BlockIndex].arrXY[i]+x<1 || arrayBlock[BlockIndex].arrXY[i]+x>10)return TRUE;if (arrayBlock[BlockIndex].arrXY[i+1]+y<1)continue;if(Gameboard[arrayBlock[BlockIndex].arrXY[i]+x][arrayBlock[BlockIndex].arrXY[i+1]+ y])return TRUE;}return FALSE;}/*********************************************************** 函数原型:int HandleLeft(int BlockIndex,int *x, int *y) * * 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下左方向键时的处理函数***********************************************************/void HandleLeft(int BlockIndex,int *x, int *y) /*按下左方向键时的处理函数*/{if(!IsConflict(BlockIndex,*x-1,*y)){DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*x)--;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleRight(int BlockIndex,int *x, int *y) ** 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下右方向键时的处理函数***********************************************************/void HandleRight(int BlockIndex,int *x, int *y)/*按下右方向键时的处理函数*/{if(!IsConflict(BlockIndex,*x+1,*y)){DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*x)++;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleUp(int BlockIndex,int *x, int *y) ** 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下上方向键(旋转键)时的处理函数***********************************************************/void HandleUp(int *BlockIndex,int *x, int *y) /*按下旋转键时的处理函数*/{int NextBlockIndex, i;static int arrayOffset[5]={0,-1,1,-2,2};NextBlockIndex = arrayBlock[*BlockIndex].nNext;for(i=0;i<5;i++)if(!IsConflict(NextBlockIndex, *x+arrayOffset[i],*y)){DrawBlock(*BlockIndex, *x, *y, BGCOLOR); /*擦除原先的形状*/*BlockIndex = arrayBlock[*BlockIndex].nNext;(*x) += arrayOffset[i];DrawBlock(*BlockIndex, *x, *y, arrayBlock[*BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleDown(int BlockIndex,int *x, int *y) * * 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:仍在自由下落返回0,无法下落了返回1 ** 函数功能:按下向下方向键或自由下落时的处理函数***********************************************************/int HandleDown(int BlockIndex,int *x, int *y)/*按下下方向键或自由下落时的处理函数*/{char ScoreBuffer[10]={0},SpeedBuffer[10]={0};int i;int NumLinesKilled=0;/*if(TimerCounter>(20-nSpeed*2))*/{TimerCounter = 0; /*重置时钟中断*/if(!IsConflict(BlockIndex,*x,*y+1)) /*仍在下落*/{DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*y)++;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/return FALSE;/*仍在下落返回FALSE*/}else /*无法再下落了*/{DrawBlock(BlockIndex,*x,*y,FORECOLOR);for (i=0;i<=7;i++,i++){if ((*y)+arrayBlock[BlockIndex].arrXY[i+1]<1)continue;Gameboard[(*x)+arrayBlock[BlockIndex].arrXY[i]][(*y)+arrayBlock[BlockIndex].arrX Y[i+1]]=1;}NumLinesKilled = KillLines(*y);if(NumLinesKilled>0){switch(NumLinesKilled){case 1:nScore+=100;case 2:nScore+=300;case 3:nScore+=500;case 4:nScore+=800;}/*重绘计分框*/setfillstyle(SOLID_FILL,BLACK);bar(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));itoa(nScore,ScoreBuffer, 10);setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(20+1), ScoreBuffer);if(nScore > nSpeedUpScore){nSpeed++;nSpeedUpScore+= nSpeed*1000;/*重绘速度框*/setfillstyle(SOLID_FILL,BLACK);bar(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1)); itoa(nSpeed,SpeedBuffer,10);setcolor(YELLOW);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(13+1), SpeedBuffer);}if(IsGameOver())bOver = TRUE;return TRUE; /*下落到底返回TRUE*/}}}/*********************************************************** 函数原型:int IsLineFull(int y) ** 传入参数:纵坐标y ** 返回值:填满返回1,否则返回0 ** 函数功能:判断第y行是否已被填满***********************************************************/int IsLineFull(int y){int i;for(i=1;i<=10;i++)if(!Gameboard[i][y])return FALSE;return TRUE;}/*********************************************************** void KillLine(int y) ** 传入参数:纵坐标y ** 返回值:无 ** 函数功能:消去第y行***********************************************************/void KillLine(int y){int i,j;for(j=y;j>=2;j--)for(i=1;i<=10;i++){if(Gameboard[i][j]==Gameboard[i][j-1])continue;if(Gameboard[i][j-1]==FILLED){Gameboard[i][j]=FILLED;setfillstyle(SOLID_FILL,FORECOLOR);}else /*Gameboard[i][j-1]==EMPTY*/Gameboard[i][j] = EMPTY;setfillstyle(SOLID_FILL,BGCOLOR);}DrawSquare(i,j);}}/*********************************************************** 函数原型:int KillLines(int y) ** 传入参数:纵坐标y ** 返回值:消去的行数 ** 函数功能:消去第y行以及与第y行连续的上面被填满的行 ***********************************************************/int KillLines(int y){int i, j, LinesKilled=0;for(i=0;i<4;i++){while(IsLineFull(y)){KillLine(y);LinesKilled++;i++;}y--;if(y<1)break;}return LinesKilled;}/*********************************************************** 函数原型:int IsGameOver() ** 传入参数:无 ** 返回值:游戏结束返回1,否则返回0 ** 函数功能:判断游戏是否结束***********************************************************/int IsGameOver(){int i;for(i=1;i<=10;i++)if(Gameboard[i][1])return TRUE;return FALSE;}/*********************************************************** 函数原型:int GameOver() ** 传入参数:无** 返回值:退出游戏返回1,否则返回0 ** 函数功能:在界面上输出游戏结束信息,并根据用户按键选择决定是否退出游戏***********************************************************/int GameOver(){int key;settextjustify(CENTER_TEXT,TOP_TEXT);/* 输出游戏结束信息 */setcolor(RED);outtextxy(BSIZE*15,BSIZE*12,"Game Over");setcolor(GREEN);outtextxy(BSIZE*15,BSIZE*14,"Enter : New Game");outtextxy(BSIZE*15,BSIZE*15,"Esc : Exit");for(;;){while(!bioskey(1));key=bioskey(0);if (key==VK_ENTER)return FALSE; /* 按下回车键,重新开始游戏 */if (key==VK_ESC)return TRUE; /* 按下ESC键,退出游戏 */}}。
C语言俄罗斯方块游戏源代码
/*学无止境*/ #include <stdlib.h>#include <stdio.h>#include <graphics.h>#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,"Tetris");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++)for (j=0;j<MAX;j++){Position[i][j]=1;middle[i][j]=-1;}for (i=0;i<Heng;i++)for (j=0;j<Shu;j++)Position[i][j]=0;for (i=0;i<Heng;i++)for (j=0;j<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++)for (j=0;j<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<Heng && Touch(ActH,ActS,1,0)==CAN) { ActH++;}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)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",&TopScore);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){for (i=0;i<4;i++)for (j=0;j<4;j++)if (a[NextAct][0][i][j]==1) DrawBox(Heng+4+i,1+j,Color); }void DetectFill(){int Number,Fall,FallTime=0;for (i=Shu-1;i>=0;i--){Number=0;for (j=0;j<Heng;j++)if (Position[j][i]==1) Number++;if (Number==Heng){FallTime++;if (Sounds==CAN){sound(500);delay(500);nosound();}for (Fall=i;Fall>0;Fall--)for (j=0;j<Heng;j++){Position[j][Fall]=Position[j][Fall-1]; middle[j][Fall]=middle[j][Fall-1];if (Position[j][Fall]==0) DrawBox(j,Fall,0); else DrawBox(j,Fall,middle[j][Fall]+1);}i++;}}switch(FallTime){case 0:break;case 1:Scores+=1;break;case 2:Scores+=3;break;case 3:Scores+=6;break;case 4:Scores+=10;break;}if (FallTime!=0){GetScores();if (Scores%100==0) Delays-=100;}}void Fail(){if (Sounds==CAN){for (k=0;k<3;k++){sound(300);delay(200);nosound();}}setcolor(1);OutTextXY(440,200,"Game over!"); Quit();closegraph();exit(0);}。
俄罗斯方块游戏代码
俄罗斯方块游戏代码include#include d[j] = src->d[j][3 - i];}int MapCheck(int x, int y) /* 检测地图中某坐标是否有砖块 ..............*/ {if (x =10 || y = 26) return -1;return map[y][x];}int BlockCheck(int x, int y, const Block* src) /* 检测砖块位置合法性 ..*/ {int i, j;for (j = 0; j d[j] = BlockList[k][j];for (i = rand() % 4; i > 0; i--, *src = t) Rotate(src, }long TimePass = 0, TimeExit = -1, GameTime = -1, w;void GameMain(void);/*--------------------------------------------------------------------- // 程序入口函数//--------------------------------------------------------------------- */void main(void){clrscr(); /* 初始化:清屏 ...........*/randomize(); /* 初始化:随机数种子 .....*/for (w = 0; w = 0; i--) if (!BlockCheck(x, i - 1,y = i; v = 0;}if (key == 27) GameMode = 1; /* ESC: 退出游戏 ......*/ if (key == 72) { /* UP: 转动砖块 .......*/Rotate(if (BlockCheck(x, y,}if (--v = 20) GameMode = -1; /* 判断死亡 ...........*/ else y = 20, x = 3;GameDriver(); /* 消除完成的行 .......*/} else y--; /* 否则:下降 .........*/}GameView(); /* 显示: 更新屏幕 .....*/}while (kbhit()) getch(); /* 按任意键结束 .......*/ while (!kbhit()); nosound(); /* 关闭扬声器 .........*/}void GameDriver(void)/* 处理消除行 ..............................*/{int inc[5]={10,100,300,600,1000}, count = 0, x, y, k, i, j;for (y = 0; y =0for (i = 0; i < 10; i++) for (j = 0; j < 20; j++) { /* 显示地图 ...*/ m = TextBck[19 - j], n = i * 2;SCREEN(n+1,j+1) = (m)? '[':'.', SCOLOR(n+1,j+1) = (m)? cmap[m] : 8; SCREEN(n+2,j+1) = (m)? ']':'.', SCOLOR(n+2,j+1) = (m)? cmap[m] : 8; }for (j = 0; j < 4; j++) for (i = 0; i < 4; i++) { /* 显示下个砖块*/ m = C.d[j], n = 160 * (j + 8) + 4 * i + 58;TextBuf[n+0] = (m)? '[':'.', TextBuf[n+1] = (m)? cmap[m] : 8;[/post] TextBuf[n+2] = (m)? ']':'.', TextBuf[n+3] = (m)? cmap[m] : 8;}if (TimePasstextcolor(0xa-8);gotoxy(30,1); printf("POSITION: [%2d,%2d]", x, y); /* 显示分数等 .*/gotoxy(30,2); printf("SPEED: %d", GameSpeed);gotoxy(30,6); printf("SCORE: "); cprintf("%ld", GameScore);gotoxy(30,5); printf("TIME: "); /* 显示时间 ...*/m = (int)(TimePass / 18.2) / 60, n = (int)(TimePass / 18.2) % 60;cprintf("%d%d:%d%d", (m/10), (m%10), (n/10), (n%10));gotoxy(1, 23);}。
小游戏代码编程
小游戏代码编程1. 俄罗斯方块```javascript// 俄罗斯方块// 定义一个游戏类class TetrisGame {constructor() {// 初始化游戏参数this.width = 10;this.height = 20;this.score = 0;this.level = 1;this.lines = 0;this.gameOver = false;this.gameBoard = [];this.currentBlock = null;this.nextBlock = null;this.init();}// 初始化游戏init() {// 初始化游戏板for (let i = 0; i < this.height; i++) {this.gameBoard[i] = new Array(this.width).fill(0); }// 生成下一个方块this.nextBlock = this.generateBlock();// 生成当前方块this.currentBlock = this.generateBlock();}// 生成方块generateBlock() {// 生成随机数,用来表示方块的类型let type = Math.floor(Math.random() * 7); let block = null;switch (type) {case 0:block = new IBlock();break;case 1:block = new JBlock();break;case 2:block = new LBlock();break;case 3:block = new OBlock();break;case 4:block = new SBlock();break;case 5:block = new TBlock();break;case 6:block = new ZBlock();break;}return block;}// 更新游戏update() {// 更新游戏板this.updateGameBoard();// 检测游戏是否结束this.checkGameOver();// 更新分数this.updateScore();// 更新关卡this.updateLevel();}// 更新游戏板updateGameBoard() {// 清除游戏板this.gameBoard.forEach(row => row.fill(0));// 将当前方块的位置更新到游戏板this.currentBlock.block.forEach((row, y) => {row.forEach((value, x) => {if (value !== 0) {this.gameBoard[y + this.currentBlock.y][x + this.currentBlock.x] = value;}});});}// 检测游戏是否结束checkGameOver() {// 如果当前方块的位置已经超出游戏板,则游戏结束if (this.currentBlock.y < 0) {this.gameOver = true;}}// 更新分数updateScore() {// 根据消除的行数更新分数this.score += this.lines * 10;}// 更新关卡updateLevel() {// 根据消除的行数更新关。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
#include <stdio.h>#include <dos.h>#include <conio.h>#include <graphics.h>#include <stdlib.h>#ifdef __cplusplus#define __CPPARGS ...#else#define __CPPARGS#endif#define MINBOXSIZE 15 /* 最小方块的尺寸*/#define BGCOLOR 7 /* 背景着色*/#define GX 200#define GY 10#define SJNUM 10000 /* 每当玩家打到一万分等级加一级*/ /* 按键码*/#define VK_LEFT 0x4b00#define VK_RIGHT 0x4d00#define VK_DOWN 0x5000#define VK_UP 0x4800#define VK_HOME 0x4700#define VK_END 0x4f00#define VK_SPACE 0x3920#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 /* 要出的下一个方块的纵坐标*/#define NEXTROW 12 /* 要出的下一个方块的横从标*/#define MAXROW 14 /* 游戏屏幕大小*/#define MAXCOL 20#define SCCOL 100 /*游戏屏幕大显示器上的相对位置*/#define SCROW 60int gril[22][16]; /* 游戏屏幕坐标*/int col=1,row=7; /* 当前方块的横纵坐标*/int boxfx=0,boxgs=0; /* 当前寺块的形壮和方向*/int nextboxfx=0,nextboxgs=0,maxcol=22;/*下一个方块的形壮和方向*/ int minboxcolor=6,nextminboxcolor=6;int num=0; /*游戏分*/int dj=0,gamedj[10]={18,16,14,12,10,8,6,4,2,1};/* 游戏等级*//* 以下我用了一个3维数组来纪录方块的最初形状和方向*/int boxstr[7][4][16]={{{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},{0,1,0,0,1,1,0,0,1,0,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},{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}},{{1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0},{1,1,1,0,1,0,0,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},{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,0,0,0,0}},{{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0},{0,0,0,0,1,1,1,1,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,0,0,0,1,1,1,1,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}},{{0,0,0,0,1,1,1,0,0,1,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0},{0,1,0,0,1,1,1,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}}};/* 随机得到当前方块和下一个方块的形状和方向*/void boxrad(){minboxcolor=nextminboxcolor;boxgs=nextboxgs;boxfx=nextboxfx;nextminboxcolor=random(14)+1;if(nextminboxcolor==4||nextminboxcolor==7||nextminboxcolor==8) nextminboxcolor=9;nextboxfx=F_DONG;nextboxgs=random(7);}/*初始化图形模试*/void init(int gdrive,int gmode){int errorcode;initgraph(&gdrive,&gmode,"e:\\tc");errorcode=graphresult();if(errorcode!=grOk){printf("error of: %s",grapherrormsg(errorcode));exit(1);}}/* 在图形模式下的清屏*/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){setfillstyle(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;b=SCROW+bsc;clscr(a+1,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE,color);if(color!=BGCOLOR){setcolor(bdcolor);line(a+1,b+1,a-1+MINBOXSIZE,b+1);line(a+1,b+1,a+1,b-1+MINBOXSIZE);line(a-1+MINBOXSIZE,b+1,a-1+MINBOXSIZE,b-1+MINBOXSIZE); line(a+1,b-1+MINBOXSIZE,a-1+MINBOXSIZE,b-1+MINBOXSIZE); }}/*游戏中出现的文字*/void txt(int a,int b,char *txt,int font,int color){setcolor(color);settextstyle(0,0,font);outtextxy(a,b,txt);}/*windows 绘制*/void win(int a,int b,int c,int d,int bgcolor,int bordercolor){clscr(a,b,c,d,bgcolor);setcolor(bordercolor);line(a,b,c,b);line(a,b,a,d);line(a,d,c,d);line(c,b,c,d);}/* 当前方块的绘制*/void funbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+row+a)*MINBOXSIZE,(i+col+b)*MINBOXSIZE,color,bdcolor); }/*下一个方块的绘制*/void nextfunbox(int a,int b,int color,int bdcolor){int i,j;int boxz[4][4];for(i=0;i<16;i++)boxz[i/4][i%4]=boxstr[nextboxgs][nextboxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(boxz[i][j]==1)minbox((j+a)*MINBOXSIZE,(i+b)*MINBOXSIZE,color,bdcolor);}/*时间中断定义*/#define TIMER 0x1cint TimerCounter=0;void interrupt ( *oldhandler)(__CPPARGS);void interrupt newhandler(__CPPARGS){TimerCounter++;oldhandler();}void SetTimer(void interrupt (*IntProc)(__CPPARGS)){oldhandler=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*由于游戏的规则,消掉都有最小方块的一行*/void delcol(int a){int i,j;for(i=a;i>1;i--)for(j=1;j<15;j++){minbox(j*MINBOXSIZE,i*MINBOXSIZE,BGCOLOR,BGCOLOR);gril[i][j]=gril[i-1][j];if(gril[i][j]==1)minbox(j*MINBOXSIZE,i*MINBOXSIZE,minboxcolor,0);}/*消掉所有都有最小方块的行*/ void delete(){int i,j,zero,delgx=0;char *nm="00000";for(i=1;i<21;i++){zero=0;for(j=1;j<15;j++)if(gril[j]==0)zero=1;if(zero==0){delcol(i);delgx++;}}num=num+delgx*delgx*10;dj=num/10000;sprintf(nm,"%d",num);clscr(456,173,500,200,4);txt(456,173,"Number:",1,15);txt(456,193,nm,1,15);}/*时间中断结束*/void KillTimer(){disable();setvect(TIMER,oldhandler); enable();}/* 测试当前方块是否可以向下落*/ int downok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i]; for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i+1][row+j])k=0;return(k);/* 测试当前方块是否可以向左行*/int leftok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j-1])k=0;return(k);}/* 测试当前方块是否可以向右行*/int rightok(){int i,j,k=1,a[4][4];for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j] && gril[col+i][row+j+1])k=0;return(k);}/* 测试当前方块是否可以变形*/int upok(){int i,j,k=1,a[4][4];for(i=0;i<4;i++)for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx+1][i];for(i=3;i>=0;i--)for(j=3;j>=0;j--)if(a[j] && gril[col+i][row+j])k=0;return(k);}/*当前方块落下之后,给屏幕坐标作标记*/ void setgril(){int i,j,a[4][4];funbox(0,0,minboxcolor,0);for(i=0;i<16;i++)a[i/4][i%4]=boxstr[boxgs][boxfx][i];for(i=0;i<4;i++)for(j=0;j<4;j++)if(a[j])gril[col+i][row+j]=1;col=1;row=7;}/*游戏结束*/void gameover(){int i,j;for(i=20;i>0;i--)for(j=1;j<15;j++)minbox(j*MINBOXSIZE,i*MINBOXSIZE,2,0);txt(103,203,"Game Over",3,10);}/*按键的设置*/void call_key(int keyx){switch(keyx){case VK_DOWN: { /*下方向键,横坐标加一。