vb6.0俄罗斯方块代码

合集下载

俄罗斯方块网上代码

俄罗斯方块网上代码

1/******************************************************************************2 **文件:Tetris.c3 **编写者:huangminqiang4 **编写日期:2010年12月8号5 **简要描述:俄罗斯方块游戏6 **修改者:7 **修改日期:2012年12月12号第3次修改8 **注:后期功能有些不太完善,主要因为时间原因。

VC6.0环境能正常的跑起来。

9*******************************************************************************/ 10#include <stdio.h>11#include <windows.h>12#include <conio.h>13#include <time.h>1415//游戏窗口16#define FrameX 4 //游戏窗口左上角的X轴坐标17#define FrameY 4 //游戏窗口左上角的Y轴坐标18#define Frame_height 20 //游戏窗口的高度19#define Frame_width 18 //游戏窗口的宽度2021//定义全局变量22int i,j,temp,temp1,temp2; //temp,temp1,temp2用于记住和转换方块变量的值23int a[80][80]={0}; //标记游戏屏幕的图案:2,1,0分别表示该位置为游戏边框、方块、无图案;初始化为无图案24int b[4]; //标记4个"口"方块:1表示有方块,0表示无方块2526//声明俄罗斯方块的结构体27struct Tetris28{29int x; //中心方块的x轴坐标30int y; //中心方块的y轴坐标31int flag; //标记方块类型的序号32int next; //下一个俄罗斯方块类型的序号33int speed; //俄罗斯方块移动的速度34int count; //产生俄罗斯方块的个数35int score; //游戏的分数36int level; //游戏的等级37};3839//函数原型声明40//光标移到指定位置41void gotoxy(HANDLE hOut, int x, int y);42//制作游戏窗口43void make_frame();44//随机产生方块类型的序号45void get_flag(struct Tetris *);46//制作俄罗斯方块47void make_tetris(struct Tetris *);48//打印俄罗斯方块49void print_tetris(HANDLE hOut,struct Tetris *);50//清除俄罗斯方块的痕迹51void clear_tetris(HANDLE hOut,struct Tetris *);52//判断是否能移动,返回值为1,能移动,否则,不动53int if_moveable(struct Tetris *);54//判断是否满行,并删除满行的俄罗斯方块55void del_full(HANDLE hOut,struct Tetris *);56//开始游戏57void start_game();585960void main()61{62 //制作游戏窗口63 make_frame();64 //开始游戏65 start_game();66}6768/******光标移到指定位置**************************************************************/69void gotoxy(HANDLE hOut, int x, int y)70{71 COORD pos;72 pos.X = x; //横坐标73 pos.Y = y; //纵坐标74 SetConsoleCursorPosition(hOut, pos);75}7677/******制作游戏窗口******************************************************************/ 78void make_frame()79{80HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //定义显示器句柄变量8182 gotoxy(hOut,FrameX+Frame_width-5,FrameY-2); //打印游戏名称83 printf("俄罗斯方块");84 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+7); //打印选择菜单85 printf("**********下一个方块:");86 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+13);87 printf("**********");88 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+17);89 printf("↑键:变体");90 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+19);91 printf("空格:暂停游戏");92 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+15);93 printf("Esc :退出游戏");9495 gotoxy(hOut,FrameX,FrameY); //打印框角并记住该处已有图案96 printf("╔");97 gotoxy(hOut,FrameX+2*Frame_width-2,FrameY);98 printf("╗");99 gotoxy(hOut,FrameX,FrameY+Frame_height);100 printf("╚");101 gotoxy(hOut,FrameX+2*Frame_width-2,FrameY+Frame_height); 102 printf("╝");103 a[FrameX][FrameY+Frame_height]=2;104 a[FrameX+2*Frame_width-2][FrameY+Frame_height]=2;105106for(i=2;i<2*Frame_width-2;i+=2)107 {108 gotoxy(hOut,FrameX+i,FrameY);109 printf("═"); //打印上横框110 }111for(i=2;i<2*Frame_width-2;i+=2)112 {113 gotoxy(hOut,FrameX+i,FrameY+Frame_height);114 printf("═"); //打印下横框115 a[FrameX+i][FrameY+Frame_height]=2; //记住下横框有图案116 }117for(i=1;i<Frame_height;i++)118 {119 gotoxy(hOut,FrameX,FrameY+i);120 printf("║"); //打印左竖框121 a[FrameX][FrameY+i]=2; //记住左竖框有图案122 }123for(i=1;i<Frame_height;i++)124 {125 gotoxy(hOut,FrameX+2*Frame_width-2,FrameY+i);126 printf("║"); //打印右竖框127 a[FrameX+2*Frame_width-2][FrameY+i]=2; //记住右竖框有图案129}130131/******制作俄罗斯方块********************************************************************/ 132void make_tetris(struct Tetris *tetris)133{134 a[tetris->x][tetris->y]=b[0]; //中心方块位置的图形状态:1-有,0-无135switch(tetris->flag) //共6大类,19种类型136 {137case 1: //田字方块138 {139 a[tetris->x][tetris->y-1]=b[1];140 a[tetris->x+2][tetris->y-1]=b[2];141 a[tetris->x+2][tetris->y]=b[3];142break;143 }144case 2: //直线方块:----145 {146 a[tetris->x-2][tetris->y]=b[1];147 a[tetris->x+2][tetris->y]=b[2];148 a[tetris->x+4][tetris->y]=b[3];149break;150 }151case 3: //直线方块: |152 {153 a[tetris->x][tetris->y-1]=b[1];154 a[tetris->x][tetris->y-2]=b[2];155 a[tetris->x][tetris->y+1]=b[3];156break;157 }158case 4: //T字方块159 {160 a[tetris->x-2][tetris->y]=b[1];161 a[tetris->x+2][tetris->y]=b[2];162 a[tetris->x][tetris->y+1]=b[3];163break;164 }165case 5: //T字顺时针转90度方块166 {167 a[tetris->x][tetris->y-1]=b[1];168 a[tetris->x][tetris->y+1]=b[2];169 a[tetris->x-2][tetris->y]=b[3];170break;172case 6: //T字顺时针转180度方块173 {174 a[tetris->x][tetris->y-1]=b[1]; 175 a[tetris->x-2][tetris->y]=b[2]; 176 a[tetris->x+2][tetris->y]=b[3]; 177break;178 }179case 7: //T字顺时针转270度方块180 {181 a[tetris->x][tetris->y-1]=b[1]; 182 a[tetris->x][tetris->y+1]=b[2]; 183 a[tetris->x+2][tetris->y]=b[3]; 184break;185 }186case 8: //Z字方块187 {188 a[tetris->x][tetris->y+1]=b[1]; 189 a[tetris->x-2][tetris->y]=b[2]; 190 a[tetris->x+2][tetris->y+1]=b[3]; 191break;192 }193case 9: //Z字顺时针转90度方块194 {195 a[tetris->x][tetris->y-1]=b[1]; 196 a[tetris->x-2][tetris->y]=b[2]; 197 a[tetris->x-2][tetris->y+1]=b[3]; 198break;199 }200case 10: //Z字顺时针转180度方块201 {202 a[tetris->x][tetris->y-1]=b[1]; 203 a[tetris->x-2][tetris->y-1]=b[2]; 204 a[tetris->x+2][tetris->y]=b[3]; 205break;206 }207case 11: //Z字顺时针转270度方块208 {209 a[tetris->x][tetris->y+1]=b[1]; 210 a[tetris->x+2][tetris->y-1]=b[2]; 211 a[tetris->x+2][tetris->y]=b[3]; 212break;213 }214case 12: //7字方块216 a[tetris->x][tetris->y-1]=b[1]; 217 a[tetris->x][tetris->y+1]=b[2]; 218 a[tetris->x-2][tetris->y-1]=b[3]; 219break;220 }221case 13: //7字顺时针转90度方块222 {223 a[tetris->x-2][tetris->y]=b[1]; 224 a[tetris->x-2][tetris->y+1]=b[2]; 225 a[tetris->x+2][tetris->y]=b[3]; 226break;227 }228case 14: //7字顺时针转180度方块229 {230 a[tetris->x][tetris->y-1]=b[1]; 231 a[tetris->x][tetris->y+1]=b[2]; 232 a[tetris->x+2][tetris->y+1]=b[3]; 233break;234 }235case 15: //7字顺时针转270度方块236 {237 a[tetris->x-2][tetris->y]=b[1]; 238 a[tetris->x+2][tetris->y-1]=b[2]; 239 a[tetris->x+2][tetris->y]=b[3]; 240break;241 }242case 16: //倒7字方块243 {244 a[tetris->x][tetris->y+1]=b[1]; 245 a[tetris->x][tetris->y-1]=b[2]; 246 a[tetris->x+2][tetris->y-1]=b[3]; 247break;248 }249case 17: //倒7字顺指针转90度方块250 {251 a[tetris->x-2][tetris->y]=b[1]; 252 a[tetris->x-2][tetris->y-1]=b[2]; 253 a[tetris->x+2][tetris->y]=b[3]; 254break;255 }256case 18: //倒7字顺时针转180度方块257 {258 a[tetris->x][tetris->y-1]=b[1];259 a[tetris->x][tetris->y+1]=b[2];260 a[tetris->x-2][tetris->y+1]=b[3];261break;262 }263case 19: //倒7字顺时针转270度方块264 {265 a[tetris->x-2][tetris->y]=b[1];266 a[tetris->x+2][tetris->y+1]=b[2];267 a[tetris->x+2][tetris->y]=b[3];268break;269 }270 }271}272273//******判断是否可动*************************************************************************/ 274int if_moveable(struct Tetris *tetris)275{276if(a[tetris->x][tetris->y]!=0)//当中心方块位置上有图案时,返回值为0,即不可移动277 {278return 0;279 }280else281 {282if( //当为田字方块且除中心方块位置外,其他"口"字方块位置上无图案时,返回值为1,即可移动283 ( tetris->flag==1 && ( a[tetris->x][tetris->y-1]==0 &&284 a[tetris->x+2][tetris->y-1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 285 //或为直线方块且除中心方块位置外,其他"口"字方块位置上无图案时,返回值为1,即可移动286 ( tetris->flag==2 && ( a[tetris->x-2][tetris->y]==0 &&287 a[tetris->x+2][tetris->y]==0 && a[tetris->x+4][tetris->y]==0 ) ) || 288289 ( tetris->flag==3 && ( a[tetris->x][tetris->y-1]==0 &&290 a[tetris->x][tetris->y-2]==0 && a[tetris->x][tetris->y+1]==0 ) ) || 291292 ( tetris->flag==4 && ( a[tetris->x-2][tetris->y]==0 &&293 a[tetris->x+2][tetris->y]==0 && a[tetris->x][tetris->y+1]==0 ) ) || 294295 ( tetris->flag==5 && ( a[tetris->x][tetris->y-1]==0 &&296 a[tetris->x][tetris->y+1]==0 && a[tetris->x-2][tetris->y]==0 ) ) || 297298 ( tetris->flag==6 && ( a[tetris->x][tetris->y-1]==0 &&299 a[tetris->x-2][tetris->y]==0 && a[tetris->x+2][tetris->y]==0 ) ) ||300301 ( tetris->flag==7 && ( a[tetris->x][tetris->y-1]==0 &&302 a[tetris->x][tetris->y+1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 303304 ( tetris->flag==8 && ( a[tetris->x][tetris->y+1]==0 &&305 a[tetris->x-2][tetris->y]==0 && a[tetris->x+2][tetris->y+1]==0 ) ) || 306307 ( tetris->flag==9 && ( a[tetris->x][tetris->y-1]==0 &&308 a[tetris->x-2][tetris->y]==0 && a[tetris->x-2][tetris->y+1]==0 ) ) || 309310 ( tetris->flag==10 && ( a[tetris->x][tetris->y-1]==0 &&311 a[tetris->x-2][tetris->y-1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 312313 ( tetris->flag==11 && ( a[tetris->x][tetris->y+1]==0 &&314 a[tetris->x+2][tetris->y-1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 315316 ( tetris->flag==12 && ( a[tetris->x][tetris->y-1]==0 &&317 a[tetris->x][tetris->y+1]==0 && a[tetris->x-2][tetris->y-1]==0 ) ) || 318319 ( tetris->flag==13 && ( a[tetris->x-2][tetris->y]==0 &&320 a[tetris->x-2][tetris->y+1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 321322 ( tetris->flag==14 && ( a[tetris->x][tetris->y-1]==0 &&323 a[tetris->x][tetris->y+1]==0 && a[tetris->x+2][tetris->y+1]==0 ) ) || 324325 ( tetris->flag==15 && ( a[tetris->x-2][tetris->y]==0 &&326 a[tetris->x+2][tetris->y-1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 327328 ( tetris->flag==16 && ( a[tetris->x][tetris->y+1]==0 &&329 a[tetris->x][tetris->y-1]==0 && a[tetris->x+2][tetris->y-1]==0 ) ) || 330331 ( tetris->flag==17 && ( a[tetris->x-2][tetris->y]==0 &&332 a[tetris->x-2][tetris->y-1]==0 && a[tetris->x+2][tetris->y]==0 ) ) || 333334 ( tetris->flag==18 && ( a[tetris->x][tetris->y-1]==0 &&335 a[tetris->x][tetris->y+1]==0 && a[tetris->x-2][tetris->y+1]==0 ) ) || 336337 ( tetris->flag==19 && ( a[tetris->x-2][tetris->y]==0 &&338 a[tetris->x+2][tetris->y+1]==0 && a[tetris->x+2][tetris->y]==0 ) ) ) 339340 {341return 1;342 }343 }344return 0;345}346347/******随机产生俄罗斯方块类型的序号**********************************************************/348void get_flag(struct Tetris *tetris)349{350 tetris->count++; //记住产生方块的个数351 srand((unsigned)time(NULL)); //初始化随机数352if(tetris->count==1)353 {354 tetris->flag = rand()%19+1; //记住第一个方块的序号355 }356 tetris->next = rand()%19+1; //记住下一个方块的序号357}358359/******打印俄罗斯方块**********************************************************************/ 360void print_tetris(HANDLE hOut,struct Tetris *tetris)361{362for(i=0;i<4;i++)363 {364 b[i]=1; //数组b[4]的每个元素的值都为1365 }366 make_tetris(tetris); //制作俄罗斯方块367for( i=tetris->x-2; i<=tetris->x+4; i+=2 )368 {369for(j=tetris->y-2;j<=tetris->y+1;j++)370 {371if( a[i][j]==1 && j>FrameY )372 {373 gotoxy(hOut,i,j);374 printf("□"); //打印边框内的方块375 }376 }377 }378 //打印菜单信息379 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+1);380 printf("level : %d",tetris->level);381 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+3);382 printf("score : %d",tetris->score);383 gotoxy(hOut,FrameX+2*Frame_width+3,FrameY+5);384 printf("speed : %dms",tetris->speed);385}386387/******清除俄罗斯方块的痕迹****************************************************************/ 388void clear_tetris(HANDLE hOut,struct Tetris *tetris)389{390for(i=0;i<4;i++)391 {392 b[i]=0; //数组b[4]的每个元素的值都为0393 }394 make_tetris(tetris); //制作俄罗斯方块395for( i=tetris->x-2; i<=tetris->x+4; i+=2 )396 {397for(j=tetris->y-2;j<=tetris->y+1;j++)398 {399if( a[i][j]==0 && j>FrameY )400 {401 gotoxy(hOut,i,j);402 printf(" "); //清除方块403 }404 }405 }406}407408/******判断是否满行并删除满行的俄罗斯方块****************************************************/409void del_full(HANDLE hOut,struct Tetris *tetris)410{ //当某行有Frame_width-2个方块时,则满行411int k,del_count=0; //分别用于记录某行方块的个数和删除方块的行数的变量412for(j=FrameY+Frame_height-1;j>=FrameY+1;j--)413 {414 k=0;415for(i=FrameX+2;i<FrameX+2*Frame_width-2;i+=2)416 {417if(a[i][j]==1) //竖坐标依次从下往上,横坐标依次由左至右判断是否满行418 {419 k++; //记录此行方块的个数420if(k==Frame_width-2)421 {422for(k=FrameX+2;k<FrameX+2*Frame_width-2;k+=2)423 { //删除满行的方块424 a[k][j]=0;425 gotoxy(hOut,k,j);426 printf(" ");427 Sleep(1);428 }429for(k=j-1;k>FrameY;k--)430 { //如果删除行以上的位置有方块,则先清除,再将方块下移一个位置431for(i=FrameX+2;i<FrameX+2*Frame_width-2;i+=2)432 {433if(a[i][k]==1)434 {435 a[i][k]=0;436 gotoxy(hOut,i,k);437 printf(" ");438 a[i][k+1]=1;439 gotoxy(hOut,i,k+1);440 printf("□");441 }442 }443 }444 j++; //方块下移后,重新判断删除行是否满行445 del_count++; //记录删除方块的行数446 }447 }448 }449 }450 tetris->score+=100*del_count; //每删除一行,得100分451if( del_count>0 && ( tetris->score%1000==0 ||tetris->score/1000>tetris->level-1 ) )452 { //如果得1000分即累计删除10行,速度加快20ms并升一级453 tetris->speed-=20;454 tetris->level++;455 }456}457458/******开始游戏******************************************************************************/ 459void start_game()460{461HANDLE hOut = GetStdHandle(STD_OUTPUT_HANDLE); //定义显示器句柄变量462struct Tetris t,*tetris=&t; //定义结构体的指针并指向结构体变量463 unsigned char ch; //定义接收键盘输入的变量464465 tetris->count=0; //初始化俄罗斯方块数为0个466 tetris->speed=300; //初始移动速度为300ms467 tetris->score=0; //初始游戏的分数为0分468 tetris->level=1; //初始游戏为第1关469470while(1)471 {//循环产生方块,直至游戏结束472 get_flag(tetris); //得到产生俄罗斯方块类型的序号473 temp=tetris->flag; //记住当前俄罗斯方块序号474475 //打印下一个俄罗斯方块的图形(右边窗口)476 tetris->x=FrameX+2*Frame_width+6;477 tetris->y=FrameY+10;478 tetris->flag = tetris->next;479 print_tetris(hOut,tetris);480481 tetris->x=FrameX+Frame_width; //初始中心方块x坐标482 tetris->y=FrameY-1; //初始中心方块y坐标483 tetris->flag=temp; //取出当前的俄罗斯方块序号484485while(1)486 {//控制方块方向,直至方块不再下移487 label:print_tetris(hOut,tetris);//打印俄罗斯方块488 Sleep(tetris->speed); //延缓时间489 clear_tetris(hOut,tetris); //清除痕迹490 temp1=tetris->x; //记住中心方块横坐标的值491 temp2=tetris->flag; //记住当前俄罗斯方块序号492if(kbhit())493 { //判断是否有键盘输入,有则用ch↓接收494 ch=getch();495if(ch==75) //按←键则向左动,中心横坐标减2 496 {497 tetris->x-=2;498 }499if(ch==77) //按→键则向右动,中心横坐标加2 500 {501 tetris->x+=2;502 }503if(ch==72) //按↑键则变体即当前方块顺时针转90度504 {505if( tetris->flag>=2 && tetris->flag<=3 )506 {507 tetris->flag++;508 tetris->flag%=2;509 tetris->flag+=2;510 }511if( tetris->flag>=4 && tetris->flag<=7 )512 {513 tetris->flag++;514 tetris->flag%=4;515 tetris->flag+=4;516 }517if( tetris->flag>=8 && tetris->flag<=11 )518 {519 tetris->flag++;520 tetris->flag%=4;521 tetris->flag+=8;522 }523if( tetris->flag>=12 && tetris->flag<=15 )524 {525 tetris->flag++;526 tetris->flag%=4;527 tetris->flag+=12;528 }529if( tetris->flag>=16 && tetris->flag<=19 )530 {531 tetris->flag++;532 tetris->flag%=4;533 tetris->flag+=16;534 }535 }536if(ch==32) //按空格键,暂停537 {538 print_tetris(hOut,tetris);539while(1)540 {541if(kbhit()) //再按空格键,继续游戏542 {543 ch=getch();544if(ch==32)545 {546goto label;547 }548 }549 }550 }551if(if_moveable(tetris)==0) //如果不可动,上面操作无效552 {553 tetris->x=temp1;554 tetris->flag=temp2;555 }556else //如果可动,执行操作557 {558goto label;559 }560 }561 tetris->y++; //如果没有操作指令,方块向下移动562if(if_moveable(tetris)==0) //如果向下移动且不可动,方块放在此处563 {564 tetris->y--;565 print_tetris(hOut,tetris);566 del_full(hOut,tetris);567break;568 }569 }570571for(i=tetris->y-2;i<tetris->y+2;i++)572 {//游戏结束条件:方块触到框顶位置573if(i==FrameY)574 {575 j=0; //如果游戏结束,j=0576 }577 }578if(j==0)579 {580 system("cls");581 getch();582break;583 }584 //清除下一个俄罗斯方块的图形(右边窗口)585 tetris->flag = tetris->next;586 tetris->x=FrameX+2*Frame_width+6;587 tetris->y=FrameY+10;588 clear_tetris(hOut,tetris);589 }590}591592。

俄罗斯方块代码

俄罗斯方块代码

1./*2.*虚拟的单个方格类,控制方格的颜色3.*/4.class RussiaBox implements Cloneable5.{6. private boolean isColor;7.8. public RussiaBox(boolean isColor)9. {10. this.isColor = isColor;11. }12. /*13. *设置颜色14. */15. public void setColor(boolean isColor)16. {17. this.isColor=isColor;18. }19. /*20. *返回颜色21. */22. public boolean isColorBox()23. {24. return isColor;25. }26. /*27. * @see ng.Object#clone()28. */29. public Object clone()30. {31. Object o = null;32. try33. {34. o=super.clone();35. }catch(CloneNotSupportedException e)36. {37. e.printStackTrace();38. }39. return o;40. }41.}42./*43. * 游戏中方块显示的画布类44. */45.import java.awt.*;46.import java.awt.event.*;47.import javax.swing.*;48.import javax.swing.border.*;49.50.class GameCanvas extends JPanel51.{52. private RussiaBox [][]boxes;53. private int rows = 20 , cols = 12;54. private static GameCanvas canvas=null;55. private int boxWidth, boxHeight;//默认为零需要调用fanning函数设置56. private Color blockColor = Color.RED, bgColor = new Color(0,204,204);57. private EtchedBorder border=new EtchedBorder(EtchedBorder.RAISED,Color.WHITE, new Color(148, 145, 140)) ;58.59. /*60. *采用单件模式,构造函数私有61. */62. private GameCanvas()63. {64. boxes = new RussiaBox[rows][cols];65.66. for(int i = 0; i < boxes.length; i ++)67. for(int j = 0; j<boxes[i].length; j ++)68. boxes[i][j] = new RussiaBox(false);69.70. setBorder(border);71. }72. /*73. *获得GameCanvas实例74. */75. public static GameCanvas getCanvasInstance()76. {77. if(canvas == null)78. canvas = new GameCanvas();79.80. return canvas;81. }82. /*83. *设置画布的背景色84. */85. public void setBgColor(Color bgColor)86. {87. this.bgColor = bgColor;88. }89. /*90. * 获得画布的背景色91. */92. public Color getBgColor()93. {94. return bgColor;95. }96. /*97. *设置方块的颜色98. */99. public void setBlockColor(Color blockColor) 100. {101. this.blockColor = blockColor; 102. }103. /*104. *方块的颜色105. */106. public Color getBlockColor()107. {108. return blockColor;109. }110. /*111. *设置画布中方块的行数112. */113. public void setRows(int rows)114. {115. this.rows = rows;116. }117. /*118. *得到画布中方块的行数119. */120. public int getRows()121. {122. return rows;123. }124. /*125. *设置画布中方块的列数126. */127. public void setCols(int cols)128. {129. this.cols = cols;130. }131. /*132. *得到画布中方块的列数133. */134. public int getCols()135. {136. return cols;137. }138. /*139. *得到row行,col列的方格140. */141. public RussiaBox getBox(int row, int col)142. {143. if(row >= 0 && row < rows && col >= 0 && col < cols) 144. return boxes[row][col];145.146. else147. return null;148. }149. /*150. *在画布中绘制方块151. */152. public void paintComponent(Graphics g)153. {154. super.paintComponent(g);155.156. fanning();157. for(int i = 0; i < boxes.length; i ++)158. for(int j = 0; j < boxes[i].length; j ++)159. {160. Color color = boxes[i][j].isColorBox() ? blockCo lor : bgColor;161. g.setColor(color);162. g.fill3DRect(j * boxWidth, i * boxHeight , boxWi dth , boxHeight , true);163. }164. }165. /*166. *清除第row行167. */168. public void removeLine(int row)169. {170. for(int i = row; i > 0; i --)171. for(int j = 0; j < cols; j ++)172. {173. boxes[i][j] = (RussiaBox)boxes[i-1][j].clone();174. }175. }176. /*177. *重置为初始时的状态178. */179. public void reset()180. {181. for(int i = 0; i < boxes.length; i++)182. for(int j = 0 ;j < boxes[i].length; j++)183. {184. boxes[i][j].setColor(false);185. }186. repaint();187. }188. /*189. * 根据窗体的大小自动调整方格的大小190. */191. public void fanning()192. {193. boxWidth = getSize().width / cols;194. boxHeight = getSize().height / rows;195. }196.197.}198./*199. * 方块类200. */201.class RussiaBlock extends Thread202.{203. private int style,y,x,level;204. private boolean moving,pausing;205. private RussiaBox boxes[][];206. private GameCanvas canvas;207.208. public final static int ROWS = 4;209. public final static int COLS = 4;210. public final static int BLOCK_KIND_NUMBER = 7;211. public final static int BLOCK_STATUS_NUMBER = 4; 212. public final static int BETWEEN_LEVELS_TIME = 50; 213. public final static int LEVEL_FLATNESS_GENE = 3; 214.216. *方块的所有风格及其不同的状态217. */218. public final static int[][] STYLES = {// 共28种状态219. {0x0f00, 0x4444, 0x0f00, 0x4444}, // 长条型的四种状态220. {0x04e0, 0x0464, 0x00e4, 0x04c4}, // 'T'型的四种状态221. {0x4620, 0x6c00, 0x4620, 0x6c00}, // 反'Z'型的四种状态222. {0x2640, 0xc600, 0x2640, 0xc600}, // 'Z'型的四种状态223. {0x6220, 0x1700, 0x2230, 0x0740}, // '7'型的四种状态224. {0x6440, 0x0e20, 0x44c0, 0x8e00}, // 反'7'型的四种状态225. {0x0660, 0x0660, 0x0660, 0x0660}, // 方块的四种状态226. };227. /*228. *构造函数229. */230. public RussiaBlock(int y,int x,int level,int style) 231. {232.233. this.y = y;234. this.x = x;235. this.level = level;236. moving = true;237. pausing = false;238. this.style = style;239.240. canvas = GameCanvas.getCanvasInstance();241.242. boxes = new RussiaBox[ROWS][COLS];243. int key = 0x8000;244. for(int i = 0; i < boxes.length; i++)245. for(int j = 0; j < boxes[i].length; j++)246. {247. boolean isColor = ( (style & key) != 0 ); 248. boxes[i][j] = new RussiaBox(isColor);249. key >>= 1;250. }251. display();252. }253. /*254. *线程的 run方法控制放块的下落及下落速度255. */256. public void run()258. while(moving)259. {260. try261. {262. sleep( BETWEEN_LEVELS_TIME * (RussiaBlocksGame.MAX_LEV EL - level + LEVEL_FLATNESS_GENE) );263. if(!pausing)264. moving = ( moveTo(y + 1,x) && moving ); 265. }catch(InterruptedException e)266. {267. e.printStackTrace();268. }269. }270. }271. /*272. *暂停移动273. */274. public void pauseMove()275. {276. pausing = true;277. }278. /*279. *从暂停状态恢复280. */281. public void resumeMove()282. {283. pausing = false;284. }285.286. /*287. *停止移动288. */289. public void stopMove()290. {291. moving = false;292. }293./*294. *向左移一格295. */296. public void moveLeft()297. {298. moveTo(y , x - 1);299. }301. *向右移一格302. */303. public void moveRight()304. {305. moveTo(y , x + 1);306. }307. /*308. *向下移一格,返回与其他几个不同,为了一键到底309. */310. public boolean moveDown()311. {312. if(moveTo(y + 1, x))313. return true;314. else315. return false;316. }317. /*318. *移到newRow,newCol位置319. */320. public synchronized boolean moveTo(int newRow, int newCol )321. {322. //erase();//必须在判断前进行擦除,否则isMoveable将产生错误行为323.324. if(!moving || !isMoveable(newRow,newCol))325. {326. display();327. return false;328. }329. y = newRow;330. x = newCol;331. display();332. canvas.repaint();333. return true;334. }335. /*336. *判断能否移到newRow,newCol位置337. */338. private boolean isMoveable(int newRow, int newCol) 339. {340. erase();341. for(int i = 0; i < boxes.length; i ++)342. for(int j = 0; j< boxes[i].length; j ++ )343. {344. if( boxes[i][j].isColorBox() )345. {346. RussiaBox box = canvas.getBox(newRow + i, newC ol + j);347. if(box == null || box.isColorBox())348. return false;349. }350. }351. return true;352. }353. /*354. *通过旋转变为下一种状态355. */356. public void turnNext()357. {358. int newStyle = 0;359. for(int i = 0; i < STYLES.length; i ++)360. for(int j = 0 ;j < STYLES[i].length; j++)361. {362. if(style == STYLES[i][j])363. {364. newStyle = STYLES[i][(j + 1)%BLOCK_STATUS_NUMB ER];365. break;366. }367. }368. turnTo(newStyle);369. }370. /*371. *通过旋转变能否变为newStyle状态372. */373. private synchronized boolean turnTo(int newStyle) 374. {375. //erase();//擦除之后在判断isTurnNextAble376. if(!moving || !isTurnable(newStyle))377. {378. display();379. return false;380. }381.382. style=newStyle;383. int key = 0x8000;384.385. for(int i = 0; i < boxes.length; i ++)386. for(int j = 0 ;j < boxes[i].length; j++)387. {388. boolean isColor = ((key & style) != 0 );389. boxes[i][j].setColor(isColor);390. key >>=1;391. }392. display();393. canvas.repaint();394. return true;395. }396. /*397. *判断通过旋转能否变为下一种状态398. */399. private boolean isTurnable(int newStyle)400. {401. erase();402. int key = 0x8000;403. for(int i = 0; i< boxes.length; i++)404. for(int j=0; j<boxes[i].length; j++)405. {406. if((key & newStyle) != 0)407. {408. RussiaBox box = canvas.getBox(y + i, x + j);409. if(box == null || box.isColorBox())410. return false;411. }412. key >>= 1;413. }414. return true;415. }416. /*417. *擦除当前方块(只是设置isColor属性,颜色并没有清除,为了判断能否移动之用)418. */419. private void erase()420. {421. for(int i = 0; i < boxes.length; i ++)422. for(int j = 0; j< boxes[i].length; j ++ )423. {424. if( boxes[i][j].isColorBox() )425. {426. RussiaBox box = canvas.getBox( y + i, x + j);427. if(box != null)428. box.setColor(false);429. }430. }431. }432. /*433. *显示当前方块(其实只是设置Color属性,在调用repaint方法时才真正显示)434. */435. private void display()436. {437. for(int i = 0; i < boxes.length; i ++)438. for(int j = 0;j< boxes[i].length ; j ++)439. {440. if(boxes[i][j].isColorBox())441. {442. RussiaBox box = canvas.getBox( y + i, x + j); 443. if(box != null)444. box.setColor( true );445. }446. }447. }448.}449./*450. * 控制面板类451. */452.import java.awt.*;453.import java.awt.event.*;454.import javax.swing.*;455.import javax.swing.border.*;456.457.class ControlPanel extends JPanel458.{459. private TipBlockPanel tipBlockPanel;460. private JPanel tipPanel,InfoPanel,buttonPanel;461. private final JTextField levelField,scoreField;462. private JButton playButton,pauseButton,stopButton, 463. turnHarderButton,turnEasilyButton; 464. private EtchedBorder border=new EtchedBorder(EtchedBorde r.RAISED,Color.WHITE, new Color(148, 145, 140)) ;465.466. private RussiaBlocksGame game;467. private Timer timer;468.469. public ControlPanel(final RussiaBlocksGame game) 470. {471. this.game = game;472. /*473. *图形界面部分474. */475. setLayout(new GridLayout(3,1,0,4));476.477. tipBlockPanel = new TipBlockPanel();478. tipPanel = new JPanel( new BorderLayout() );479. tipPanel.add( new JLabel("Next Block:") , BorderLayout.N ORTH );480. tipPanel.add( tipBlockPanel , BorderLayout.CENTER ); 481. tipPanel.setBorder(border);482.483. InfoPanel = new JPanel( new GridLayout(4,1,0,0) ); 484. levelField = new JTextField(""+RussiaBlocksGame.DEFAULT_ LEVEL);485. levelField.setEditable(false);486. scoreField = new JTextField("0");487. scoreField.setEditable(false);488. InfoPanel.add(new JLabel("Level:"));489. InfoPanel.add(levelField);490. InfoPanel.add(new JLabel("Score:"));491. InfoPanel.add(scoreField);492. InfoPanel.setBorder(border);493.494. buttonPanel = new JPanel(new GridLayout(5,1,0,0)); 495. playButton = new JButton("Play");496. pauseButton = new JButton("Pause");497. stopButton = new JButton("Stop");498. turnHarderButton = new JButton("Turn harder");499. turnEasilyButton = new JButton("Turn easily");500.501. buttonPanel.add(playButton);502. buttonPanel.add(pauseButton);503. buttonPanel.add(stopButton);504. buttonPanel.add(turnHarderButton);505. buttonPanel.add(turnEasilyButton);506. buttonPanel.setBorder(border);507.508. addKeyListener(new ControlKeyListener());//添加510. add(tipPanel);511. add(InfoPanel);512. add(buttonPanel);513. /*514. *添加事件监听器515. */516. playButton.addActionListener(517. new ActionListener()518. {519. public void actionPerformed(ActionEvent event) 520. {521. game.playGame();522. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件523. }524. });525.526. pauseButton.addActionListener(527. new ActionListener()528. {529. public void actionPerformed(ActionEvent event) 530. {531. if(pauseButton.getText().equals("Pause"))532. game.pauseGame();533. else534. game.resumeGame();535. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件536. }537. }538. );539. stopButton.addActionListener(540. new ActionListener()541. {542. public void actionPerformed(ActionEvent event) 543. {544. game.stopGame();545. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件546. }547. });548. turnHarderButton.addActionListener(549. new ActionListener()551. public void actionPerformed(ActionEvent event) 552. {553. int level = 0;554. try{555. level = Integer.parseInt(levelField.getText());556. setLevel(level + 1);557. }catch(NumberFormatException e)558. {559. e.printStackTrace();560. }561. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件562. }563. });564. turnEasilyButton.addActionListener(565. new ActionListener()566. {567. public void actionPerformed(ActionEvent event) 568. {569. int level = 0;570. try{571. level = Integer.parseInt(levelField.getText());572. setLevel(level - 1);573. }catch(NumberFormatException e)574. {575. e.printStackTrace();576. }577. requestFocus();//让ControlPanel重新获得焦点以响应键盘事件578. }579. });580. /*581. * 时间驱动程序,每格500毫秒对level,score值进行更新582. */583. timer = new Timer(500,584. new ActionListener()585. {586. public void actionPerformed(ActionEvent event) 587. {588. scoreField.setText(""+game.getScore());589. game.levelUpdate();591. }592. );593. timer.start();594. }595. /*596. * 设置预显方块的样式597. */598. public void setBlockStyle(int style)599. {600. tipBlockPanel.setStyle(style);601. tipBlockPanel.repaint();602. }603. /*604. * 重置,将所有数据恢复到最初值605. */606. public void reset()607. {608. levelField.setText(""+RussiaBlocksGame.DEFAULT_LEVEL);609. scoreField.setText("0");610. setPlayButtonEnabled(true);611. setPauseButtonLabel(true);612. tipBlockPanel.setStyle(0);613. }614.615. /*616. *设置playButton是否可用617. */618. public void setPlayButtonEnabled(boolean enable) 619. {620. playButton.setEnabled(enable);621. }622.623. /*624. *设置pauseButton的文本625. */626. public void setPauseButtonLabel(boolean pause)627. {628. pauseButton.setText( pause ? "Pause" : "Rusume" ); 629. }630.631. /*632. *设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸633. */634. public void fanning()635. {636. tipBlockPanel.fanning();637. }638. /*639. *根据level文本域的值返回当前的级别640. */641. public int getLevel()642. {643. int level = 0;644. try645. {646. level=Integer.parseInt(levelField.getText()); 647. }catch(NumberFormatException e)648. {649. e.printStackTrace();650. }651. return level;652. }653. /*654. * 设置level文本域的值655. */656. public void setLevel(int level)657. {658. if(level > 0 && level <= RussiaBlocksGame.MAX_LEVEL)659. levelField.setText("" + level);660. }661. /*662. * 内部类为预显方块的显示区域663. */664. private class TipBlockPanel extends JPanel665. {666. private Color bgColor = Color.darkGray,667. blockColor = Color.lightGray;668. private RussiaBox [][]boxes = new RussiaBox[RussiaBloc k.ROWS][RussiaBlock.COLS];669. private int boxWidth, boxHeight,style;670. private boolean isTiled = false;671.672. /*673. * 构造函数674. */675. public TipBlockPanel()676. {677. for(int i = 0; i < boxes.length; i ++)678. for(int j = 0; j < boxes[i].length; j ++)679. {680. boxes[i][j]=new RussiaBox(false);681. }682. style = 0x0000;683. }684. /*685. * 构造函数686. */687. public TipBlockPanel(Color bgColor, Color blockColor)688. {689. this();690. this.bgColor = bgColor;691. this.blockColor = blockColor;692. }693. /*694. * 设置方块的风格695. */696. public void setStyle(int style)697. {698. this.style = style;699. repaint();700. }701.702. /*703. * 绘制预显方块704. */705. public void paintComponent(Graphics g)706. {707. super.paintComponent(g);708.709. int key = 0x8000;710.711. if(!isTiled)712. fanning();713. for(int i = 0; i < boxes.length; i ++)714. for(int j = 0; j<boxes[i].length ;j ++)715. {716. Color color = (style & key) != 0 ? blockColor : bgColor;717. g.setColor(color);718. g.fill3DRect(j * boxWidth, i * boxHeight, boxWidt h, boxHeight, true);719. key >>=1;720. }721. }722. /*723. *设置方块的大小,改变窗体大小时调用可自动调整方块到合适的尺寸724. */725.726. public void fanning()727. {728. boxWidth = getSize().width / RussiaBlock.COLS; 729. boxHeight = getSize().height /RussiaBlock.ROWS; 730. isTiled=true;731. }732. }733. /*734. *内部类键盘键听器,响应键盘事件735. */736. class ControlKeyListener extends KeyAdapter {737. public void keyPressed(KeyEvent ke)738. {739. if (!game.isPlaying()) return;740.741. RussiaBlock block = game.getCurBlock();742. switch (ke.getKeyCode()) {743. case KeyEvent.VK_DOWN:744. block.moveDown();745. break;746. case KeyEvent.VK_LEFT:747. block.moveLeft();748. break;749. case KeyEvent.VK_RIGHT:750. block.moveRight();751. break;752. case KeyEvent.VK_UP:753. block.turnNext();754. break;755. case KeyEvent.VK_SPACE://一键到底756. while(block.moveDown())757. {758. }759. break;760. default:761. break;762. }763. }764. }765.}766./*767. * 主游戏类768. */769.import java.awt.*;770.import java.awt.event.*;771.import javax.swing.*;772.773.public class RussiaBlocksGame extends JFrame774.{775. public final static int PER_LINE_SCORE = 100;//消去一行得分776. public final static int PER_LEVEL_SCORE = PER_LINE_SCORE* 20;//升一级需要的分数777. public final static int DEFAULT_LEVEL = 5;//默认级别778. public final static int MAX_LEVEL = 10;//最高级别779. private int score=0,curLevelScore = 0;//总分和本级得分780.781. private GameCanvas canvas;782. private ControlPanel controlPanel;783. private RussiaBlock block;784.785. private int style = 0;786. boolean playing = false;787.788. private JMenuBar bar;789. private JMenu gameMenu,controlMenu,windowStyleMenu,inform ationMenu;790. private JMenuItem newGameItem,setBlockColorItem,setBgColo rItem,791. turnHardItem,turnEasyItem,exitItem;792. private JMenuItem playItem,pauseItem,resumeItem,stopIte m;793. private JRadioButtonMenuItem windowsRadioItem,motifRadi oItem,metalRadioItem;794. private JMenuItem authorItem,helpItem;795. private ButtonGroup buttonGroup;796. /*797. * 构造函数798. */799. public RussiaBlocksGame(String title)800. {801. super(title);802.803. setSize(300,400);804. Dimension scrSize=Toolkit.getDefaultToolkit().getScreen Size();805. setLocation((scrSize.width-getSize().width)/2,(scrSize.height-getSize().height)/2);806.807. createMenu();808. Container container=getContentPane();809. container.setLayout(new BorderLayout());810.811. canvas = GameCanvas.getCanvasInstance();812. controlPanel = new ControlPanel(this);813.814. container.add(canvas,BorderLayout.CENTER);815. container.add(controlPanel,BorderLayout.EAST); 816.817. addWindowListener(818. new WindowAdapter()819. {820. public void windowClosing(WindowEvent event)821. {822. stopGame();823. System.exit(0);824. }825. }826. );827.828. addComponentListener(829. new ComponentAdapter()830. {831. public void componentResized(ComponentEvent event) 832. {833. canvas.fanning();834. }835. }837. canvas.fanning();838. setVisible(true);839. }840. /*841. * 判断游戏是否正在进行842. */843. public boolean isPlaying()844. {845. return playing;846. }847. /*848. * 开始游戏并设置按钮和菜单项的可用性849. */850. public void playGame()851. {852. play();853. controlPanel.setPlayButtonEnabled(false); 854. playItem.setEnabled(false);855. }856. /*857. * 暂停游戏858. */859. public void pauseGame()860. {861. if(block != null) block.pauseMove(); 862. controlPanel.setPauseButtonLabel(false); 863. pauseItem.setEnabled(false);864. resumeItem.setEnabled(true);865. }866. /*867. * 从暂停中恢复游戏868. */869. public void resumeGame()870. {871. if(block != null) block.resumeMove(); 872. controlPanel.setPauseButtonLabel(true); 873. pauseItem.setEnabled(true);874. resumeItem.setEnabled(false);875. }876. /*877. * 停止游戏878. */879. public void stopGame()881. if(block != null) block.stopMove(); 882. playing = false;883. controlPanel.setPlayButtonEnabled(true); 884. controlPanel.setPauseButtonLabel(true); 885. playItem.setEnabled(true); 886. }887. /*888. * 得到当前级别889. */890. public int getLevel()891. {892. return controlPanel.getLevel();893. }894. /*895. * 设置当前级别,并更新控制面板的显示896. */897. public void setLevel(int level)898. {899. if(level>0&&level<11)900. controlPanel.setLevel(level);901. }902. /*903. * 得到当前总分数904. */905. public int getScore()906. {907. if(canvas != null)908. return score;909. return 0;910. }911. /*912. * 得到本级得分913. */914. public int getCurLevelScore()915. {916. if(canvas != null)917. return curLevelScore;918. return 0;919. }920. /*921. * 更新等级922. */923. public void levelUpdate()925. int curLevel = getLevel();926. if(curLevel < MAX_LEVEL && curLevelScore >= PER_LEVEL_ SCORE)927. {928. setLevel(curLevel + 1);929. curLevelScore -= PER_LEVEL_SCORE;930. }931. }932. /*933. * 获得当前得方块934. */935. public RussiaBlock getCurBlock() {936. return block;937. }938. /*939. * 开始游戏940. */941. private void play()942. {943. playing=true;944. Thread thread = new Thread(new Game());945. thread.start();946. reset();947. }948. /*949. * 重置950. */951. private void reset()952. {953. controlPanel.reset();954. canvas.reset();955. score = 0;956. curLevelScore = 0;957. }958. /*959. * 宣告游戏结束960. */961. private void reportGameOver()962. {963. JOptionPane.showMessageDialog(this,"Game over!"); 964. }965. /*966. * 创建菜单968. private void createMenu()969. {970. gameMenu = new JMenu("Game");971. newGameItem = new JMenuItem("New Game");972. setBlockColorItem = new JMenuItem("Set Block Color...") ;973. setBgColorItem = new JMenuItem("Set BackGround Color...");974. turnHardItem = new JMenuItem("Turn Harder");975. turnEasyItem = new JMenuItem("Turn Easily");976. exitItem = new JMenuItem("Exit");977. gameMenu.add(newGameItem);978. gameMenu.add(setBlockColorItem);979. gameMenu.add(setBgColorItem);980. gameMenu.add(turnHardItem);981. gameMenu.add(turnEasyItem);982. gameMenu.add(exitItem);983.984. controlMenu = new JMenu("Control");985. playItem = new JMenuItem("Play");986. pauseItem = new JMenuItem("Pause");987. resumeItem = new JMenuItem("Resume");988. stopItem = new JMenuItem("Stop");989. controlMenu.add(playItem);990. controlMenu.add(pauseItem);991. controlMenu.add(resumeItem);992. controlMenu.add(stopItem);993.994. windowStyleMenu = new JMenu("WindowStyle");995. buttonGroup = new ButtonGroup();996. windowsRadioItem = new JRadioButtonMenuItem("Windows") ;997. motifRadioItem = new JRadioButtonMenuItem("Motif"); 998. metalRadioItem = new JRadioButtonMenuItem("Mentel",true);999. windowStyleMenu.add(windowsRadioItem);1000. buttonGroup.add(windowsRadioItem);1001. windowStyleMenu.add(motifRadioItem);1002. buttonGroup.add(motifRadioItem);1003. windowStyleMenu.add(metalRadioItem);1004. buttonGroup.add(metalRadioItem);1005.1006. informationMenu = new JMenu("Information");1007. authorItem = new JMenuItem("Author:Fuliang"); 1008. helpItem = new JMenuItem("Help");1009. informationMenu.add(authorItem);1010. informationMenu.add(helpItem);1011.1012. bar = new JMenuBar();1013. bar.add(gameMenu);1014. bar.add(controlMenu);1015. bar.add(windowStyleMenu);1016. bar.add(informationMenu);1017.1018. addActionListenerToMenu();1019. setJMenuBar(bar);1020. }1021. /*1022. * 添加菜单响应1023. */1024. private void addActionListenerToMenu()1025. {1026. newGameItem.addActionListener(new ActionListener() { 1027. public void actionPerformed(ActionEvent ae) { 1028. stopGame();1029. reset();1030. setLevel(DEFAULT_LEVEL);1031. }1032. });1033.1034. setBlockColorItem.addActionListener(new ActionListener() {1035. public void actionPerformed(ActionEvent ae) { 1036. Color newBlockColor =1037. JColorChooser.showDialog(RussiaBlocksGame.this ,1038. "Set color for block", canvas.getBlock Color());1039. if (newBlockColor != null)1040. canvas.setBlockColor(newBlockColor);1041. }1042. });1043.1044. setBgColorItem.addActionListener(new ActionListener() {1045. public void actionPerformed(ActionEvent ae) { 1046. Color newBgColor =1047. JColorChooser.showDialog(RussiaBlocksGame.this ,"Set color for block",1048. canvas.getBgColor()); 1049. if (newBgColor != null)1050. canvas.setBgColor(newBgColor);1051. }1052. });1053.1054. turnHardItem.addActionListener(new ActionListener() { 1055. public void actionPerformed(ActionEvent ae) { 1056. int curLevel = getLevel();1057. if (curLevel < MAX_LEVEL) setLevel(curLevel + 1); 1058. }1059. });1060.1061. turnEasyItem.addActionListener(new ActionListener() { 1062. public void actionPerformed(ActionEvent ae) { 1063. int curLevel = getLevel();1064. if (curLevel > 1) setLevel(curLevel - 1);1065. }1066. });1067.1068. exitItem.addActionListener(new ActionListener() { 1069. public void actionPerformed(ActionEvent ae) { 1070. System.exit(0);1071. }1072. });1073. playItem.addActionListener(new ActionListener() { 1074. public void actionPerformed(ActionEvent ae) { 1075. playGame();1076. }1077. });1078.1079. pauseItem.addActionListener(new ActionListener() { 1080. public void actionPerformed(ActionEvent ae) { 1081. pauseGame();1082. }1083. });1084.1085. resumeItem.addActionListener(new ActionListener() { 1086. public void actionPerformed(ActionEvent ae) { 1087. resumeGame();1088. }1089. });。

俄罗斯方块游戏VB代码

俄罗斯方块游戏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。

俄罗斯方块源代码

俄罗斯方块源代码

C语言俄罗斯方块源代码Vc6.0编译通过#include<windows.h>#include<stdio.h>#include<time.h>#include<stdlib.h>#include<malloc.h>#include<conio.h>#define MAP_WIDTH10#define MAP_HEIGHT20#define BLOCKM"■"#define BKBLOCK"□"#define OUTSTD GetStdHandle(STD_OUTPUT_HANDLE)typedef int(*PFUN)(void *pData);void ShowMapArray(int map[MAP_HEIGHT][MAP_WIDTH]);//生成方块int xyIsInarrBlock(int arrBlock[4][2], int x, int y) //有返回1 没有返回0 {int i;for (i = 0;i<4;i++)if (arrBlock[i][0] == x && arrBlock[i][1] == y)return 1;return 0;}void GetTransBlocks(int arrBlock[4][2])//坐标模式4*4方块{int nTmp, x, y;int nCount = 1;int i;int nMinx = 0, nMiny = 0;memset(arrBlock, 0, 8 * sizeof(int));while (nCount < 4){nTmp = rand() % nCount;x = arrBlock[nTmp][0];y = arrBlock[nTmp][1];nTmp = rand() % 4;switch (nTmp){case 0:x--;break;case 1:y--;break;case 2:x++;break;case 3:y++;break;}if (xyIsInarrBlock(arrBlock, x, y))continue;arrBlock[nCount][0] = x;arrBlock[nCount][1] = y;if (nMinx > x)nMinx = x;if (nMiny > y)nMiny = y;nCount++;}for (i = 0;i<4;i++){if (nMinx < 0)arrBlock[i][0] -= nMinx;if (nMiny < 0)arrBlock[i][1] -= nMiny;}}//旋转void Ratat(int arrBlock[4][2], int Direct) // driect 1 顺时针方向旋转,-1 逆时针方向旋转{int i;int nMinx, nMiny;int nTmp;for (i = 0;i<4;i++){nTmp = arrBlock[i][0];arrBlock[i][0] = arrBlock[i][1] * (-1)*Direct;arrBlock[i][1] = nTmp*Direct;if (i == 0){nMinx = arrBlock[i][0];nMiny = arrBlock[i][1];}else{if (nMinx > arrBlock[i][0])nMinx = arrBlock[i][0];if (nMiny > arrBlock[i][1])nMiny = arrBlock[i][1];}}for (i = 0;i<4;i++){if (nMinx < 0)arrBlock[i][0] -= nMinx;if (nMiny < 0)arrBlock[i][1] -= nMiny;}}void gotoxy(int x, int y){COORD pos = { x,y };SetConsoleCursorPosition(OUTSTD, pos);}void showxy(int x, int y, int bShow){COORD pos = { x * 2 + 2,y + 2 };SetConsoleCursorPosition(OUTSTD, pos);if (bShow)printf(BLOCKM);elseprintf(BKBLOCK);}void DisShowCursor(){CONSOLE_CURSOR_INFO cci;GetConsoleCursorInfo(OUTSTD, &cci);cci.bVisible = FALSE;SetConsoleCursorInfo(OUTSTD, &cci);}int CheckBlockPlace(int map[MAP_HEIGHT][MAP_WIDTH], int x, int y, int block[4][2], int bShow) //判断位置是否可用{int i;if (x < 0 || y < 0 || x >= MAP_WIDTH || y >= MAP_HEIGHT)return 0;for (i = 0;i<4;i++){if (map[y + block[i][1]][x + block[i][0]] == 1 && bShow)return 0;if (y + block[i][1] >= MAP_HEIGHT || x + block[i][0] >= MAP_WIDTH)return 0;}return 1;}int ShowBlock(int x, int y, int block[4][2], int bShow){int i;for (i = 0;i<4;i++)showxy(block[i][0] + x, block[i][1] + y, bShow);return 1;}void LoadMap(int map[MAP_HEIGHT][MAP_WIDTH]){int i, j;DisShowCursor();system("cls");printf("----------------俄罗斯方块v0.1--------------");printf("\n\n");for (i = 0;i<MAP_HEIGHT;i++){printf(" ");for (j = 0;j<MAP_WIDTH;j++){if (map[i][j])printf(BLOCKM);elseprintf(BKBLOCK);}printf("\n");}gotoxy(MAP_WIDTH * 2 + 6, 4);printf("按s开始\n");gotoxy(MAP_WIDTH * 2 + 6, 5);printf("Next:");gotoxy(MAP_WIDTH * 2 + 6, 12);printf("分数:");}int gameDown(int map[MAP_HEIGHT][MAP_WIDTH], int blockxy[4][2], int nSec, PFUN OnFun, void *pOnData){int i, j, k;int nSelect;int x = 3, y = 0;static int maxy = 20;int missrow = 0;int xsum = 0;while (1){nSelect = OnFun(pOnData);if (nSelect){switch (nSelect){case 75:{if (CheckBlockPlace(map, x - 1, y, blockxy, 1))x--;}break;case 72:{Ratat(blockxy, 1);if (!CheckBlockPlace(map, x, y, blockxy, 1)){Ratat(blockxy, -1);}}break;case 77:{if (CheckBlockPlace(map, x + 1, y, blockxy, 1))x++;}break;}}else{if (CheckBlockPlace(map, x, y, blockxy, 1)){ShowBlock(x, y, blockxy, 1);Sleep(nSec);if (CheckBlockPlace(map, x, y + 1, blockxy, 1)){ShowBlock(x, y, blockxy, 0);y++;}else{for (i = 0;i<4;i++){map[y + blockxy[i][1]][x + blockxy[i][0]] = 1;}if (y < maxy)maxy = y;break;}}elsereturn -1;}}for (i = maxy;i<MAP_HEIGHT;i++){xsum = 0;for (j = 0;j<MAP_WIDTH;j++){xsum += map[i][j];}if (xsum == MAP_WIDTH){for (k = i;k >= maxy;k--)for (j = 0;j<MAP_WIDTH;j++)map[k][j] = map[k - 1][j];missrow++;LoadMap(map);}}return missrow;}// help functionvoid ShowMapArray(int map[MAP_HEIGHT][MAP_WIDTH]){int i, j;for (i = 0;i<MAP_HEIGHT;i++){COORD pos = { MAP_WIDTH * 2,i };SetConsoleCursorPosition(OUTSTD, pos);for (j = 0;j<MAP_WIDTH;j++){printf("%d", map[i][j]);}}}int GetInfo(void *pData){while (kbhit()){char ch1 = getch();if (ch1 < 0){ch1 = getch();}return ch1;}while (kbhit())getch();return 0;}int main(){int map[MAP_HEIGHT][MAP_WIDTH] = { 0 };int blockarrnow[4][2] = { 0 }, blockarrnext[4][2] = { 0 };int ch, nRe, i, j, nScro = 0, nSpeed = 300;BOOL bRun = TRUE;LoadMap(map);srand((unsigned)time(NULL));while (bRun){if (kbhit()){ch = getch();}if (ch == 's' || ch == 'S'){GetTransBlocks(blockarrnow);while (bRun){GetTransBlocks(blockarrnext);ShowBlock(MAP_WIDTH + 2, 5, blockarrnext, 1);nRe = gameDown(map, blockarrnow, nSpeed, GetInfo, NULL);for (i = 0;i<4;i++){blockarrnow[i][0] = blockarrnext[i][0];blockarrnow[i][1] = blockarrnext[i][1];}for (i = 0;i <= 4;i++)for (j = 0;j <= 4;j++){gotoxy(MAP_WIDTH * 2 + 4 + j * 2, 7 + i);printf(" ");}if (nRe < 0){bRun = FALSE;break;}else{nScro += (nRe * 100);gotoxy(MAP_WIDTH * 2 + 11, 12);printf("%d", nScro);}}}}return 0;}Vs2015 编译运行配图。

VB 俄罗斯方块

VB 俄罗斯方块

VB课程设计报告(附:源代码在后面)-------俄罗斯方块我的游戏初始界面如左一、功能介绍①启动程序,单击“开始”或“回车”键开始游戏②游戏开始后从网格顶部下落“T”字型、“L”字型、反“L”字型、“方块”和“长条”型的5种形状之一,不同的形状以随机颜色出现,出现的时的方向也是随机的。

同一个形状有4种不同的方向③使用“选项”菜单命令可以弹出“选项”对话框。

通过“选项”对话框为用户提供两套按键方案。

保证不同左右手习惯的用户或键盘上有坏键的用户可以方便的进行方块的移动和旋转。

默认情况下,使用“←”和“→”键左右移动方块。

使用“↑”键旋转,使用“↓”键加速下落。

通过“选项”对话框可以设置方块是顺时针还是逆时针方向④通过“选项”对话框还可以选择是否显示下一个形状的提示。

默认状态下,“下一个”区域会显示下一个即将出现的形状,如果关掉此功能,游戏时的难度会更大一些。

通过“选项”对话框可以指定加速下落时一次下落的格数。

若此设置值大于20,表示一次下落到底⑤游戏过程中,可以单击窗口右下方的“暂停”与“继续”,也可以使用“回车”键控制游戏的暂停和继续。

通过菜单命令打开“选项”对话框时,程序自动进入暂停的状态。

记分遵循以下规则,一次消去1行加100分、2行加300分、3行加700分、4行加1500分。

程序自动记录并显示最高分。

得分每增加2000分,程序自动将方块下落速度提高一档。

即分数越高,速度越大⑥程序能够保存用户通过“选项”对话框的设置,使之能在下一次运行时仍然有效亮点:①游戏界面增加了表情加载,不同情况下显示不同的表情,增加了游戏趣味性②玩家可以通过滚动条手动设置方块下落速度,可以直接挑战高难度③游戏增加了背景音乐,玩家在游戏的同时还可以享受轻音乐二﹑课程设计详细介绍程序主要由两个窗体构成:Form1(主窗口)、Form2(选项窗口)。

Form1:该窗体为程序主界面,难点在于运用绘图方法绘制网格。

在程序运行过程中,该窗体将展示出程序的大部分功能,包括方块下落、旋转、移动一系列动作,预览方块,调出设置界面等基本功能以及程序的亮点功能—调速、加载表情图片。

俄罗斯方块实例代码

俄罗斯方块实例代码

End Begin VB.Frame FraMax Caption = "最高分" Height = 795 Left = 3300 TabIndex = 3 Top = 2100 Width = 1800 Begin VB.TextBox TxtMax Alignment = 1 'Right Justify BackColor = &H8000000F& BeginProperty Font Name = "Fixedsys" Size = 12 Charset = 134 Weight = 400 Underline = 0 'False Italic = 0 'False Strikethrough = 0 'False EndProperty Height = 360 Left = 150 Locked = -1 'True TabIndex = 4 Text = "0" Top = 300 Width = 1500 End End Begin VB.Frame FraNext Caption = "下一个" Height = 1800 Left = 3300 TabIndex = 1 Top = 150 Width = 1800 Begin VB.PictureBox PicNext AutoRedraw = -1 'True BackColor = &H00FFFFFF& Height = 1260 Left = 240 ScaleHeight = 1200 ScaleWidth = 1200 TabIndex = 2
SetBlock Blocks(0, 0), "0100" "0100" "0100" "0100" SetBlock Blocks(1, 0), "0000" "1111" "0000" "0000" SetBlock Blocks(2, 0), "0100" "0100" "0100" "0100" SetBlock Blocks(3, 0), "0000" "1111" "0000" "0000" SetBlock Blocks(0, 1), "0100" "1110" "0000" "0000" SetBlock Blocks(1, 1), "0100" "0110" "0100" "0000" SetBlock Blocks(2, 1), "0000" "1110" "0100" "0000" SetBlock Blocks(3, 1), "0100" "1100" "0100" "0000" SetBlock Blocks(0, 2), "0000" "1110" "0010" "0000" SetBlock Blocks(1, 2), "0100" "0100" "1100" "0000" SetBlock Blocks(2, 2), "1000"

VC++ 6.0 MFC 俄罗斯方块 自动求解 代码 源程序

VC++ 6.0 MFC 俄罗斯方块 自动求解 代码 源程序

#include <windows.h>#include <time.h>#include <stdlib.h>#include <stdio.h>#define tDown 1 //方块下落定时器的标识(编号)#define tPaint 2 //重绘定时器的标识(编号)#define tDownTime 500 //方块下落一行位置的时间间隔#define tPaintTime 50 //窗口重绘的时间间隔#define ROW 24 //地图的行数目(第23行不用)#define COL 14 //地图的列数目(第0列和第13列不用)#define MAX_CLASS 7 //方块形状数目#define LEN 20 //每个方格大小为20×20像素#define StartY -1 * LEN + 5 //-15,绘制俄罗斯方块地图时的边界起始位置#define StartX -1 * LEN + 5 //-15int iDeleteRows = 0; //总共清除的行int iTotalNum = 0; //总得分char WindowTxt[100] = "俄罗斯方块游戏自动求解已关闭"; //窗口标题char s1[] = "关闭", s2[] = "启动"; //用于启动/关闭自动求解功能时显示不同的标题bool bAuto; //是否自动求解的标志bool Pause; //是否暂停的标志int Map[ROW][COL]; //俄罗斯方块的地图(被占据的方格为1,否则为0) int CurrentBox[4][4]; //当前落下的方块int CurrentY, CurrentX; //当前落下方块的当前位置(指左上角位置)int NextBox[4][4]; //下一个将落下的方块int Box[MAX_CLASS][4][4] = //7种方块形状{{{0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0}},{{0,0,0,0},{0,1,0,0},{1,1,1,0},{0,0,0,0}},{{0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0}},{{0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0}},{{0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0}},{{0,1,1,0},{0,1,0,0},{0,1,0,0},{0,0,0,0}{{0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0}}};void InitMap( ); //初始化地图int NewFall( ); //新的方块落下void BuildNextBox( ); //产生下一个随机的方块int Test( int y, int x, int box[4][4] ); //测试在(y,x)位置是否能放置方块box,能放置返回1,否则返回0int Drop( ); //定时时间到,当前方块下降一行位置void PutBox( ); //放置当前方块int Move( int Right ); //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动void Clear( ); //清除满足条件的行int Rotate( ); //测试旋转是否可行,如果可行则旋转当前方块int RotateTest( int Box1[4][4], int Box2[4][4] ); //旋转当前方块int count1( int y, int x, int box[4][4] ); //新增函数int BestStartX( ); //新增函数LRESULT CALLBACK WndProc( HWND, UINT, WPARAM, LPARAM ); //窗口处理函数声明int WINAPI WinMain( HINSTANCE hInstance, HINSTANCE hPrevInstance,PSTR szCmdLine, int iCmdShow ) //入口函数{static TCHAR szAppName[ ] = TEXT ("Russion");HWND hwnd;MSG msg;WNDCLASS wndclass;wndclass.style = CS_HREDRAW | CS_VREDRAW;wndclass.lpfnWndProc = WndProc;wndclass.cbClsExtra = 0;wndclass.cbWndExtra = 0;wndclass.hInstance = hInstance;wndclass.hIcon = LoadIcon( NULL, IDI_APPLICATION );wndclass.hCursor = LoadCursor( NULL, IDC_ARROW );wndclass.hbrBackground = (HBRUSH)GetStockObject( WHITE_BRUSH );wndclass.lpszMenuName = NULL;wndclass.lpszClassName = szAppName;if( !RegisterClass( &wndclass ) ){MessageBox( NULL, TEXT ("Program requires Windows NT!" ),szAppName, MB_ICONERROR );return 0;}hwnd = CreateWindow( szAppName, WindowTxt,WS_OVERLAPPED | WS_SYSMENU | WS_BORDER,CW_USEDEFAULT, CW_USEDEFAULT,(COL + 4) * LEN, //窗口宽度:(14+4)×20=360像素ROW * LEN, //窗口高度:24×20=480像素(包括标题栏部分)NULL, NULL, hInstance, NULL );ShowWindow( hwnd, iCmdShow );UpdateWindow( hwnd );while( GetMessage( &msg, NULL, 0, 0 ) ){TranslateMessage( &msg );DispatchMessage( &msg );}return msg.wParam;}//初始化地图(将第0列和第13列、第23行设置为1(被占据),其他位置设置为0) void InitMap( ){int y, x;for( y = 0; y < ROW; y++ ){for( x = 0; x < COL; x++ ){//第0列、第13列、第23行设置为1(被占据)if( x < 1 || x > COL - 2 || y > ROW - 2 )Map[y][x] = 1;else Map[y][x] = 0;}}}//计算在(y,x)位置(左上角位置)上放置方块box后空出的方格数int count1( int y, int x, int box[4][4] ){if( !Test(y,x,box) ) return 100; //不能在(y,x)位置放置box,返回∞if( Test(y+1,x,box) ) return 100; //如果box还能下降,也返回∞int tmpy, tmpx;int c = 0; //空出的方格数for( tmpx = 0; tmpx < 4; tmpx++ ) //考虑第0~3列{for( tmpy = 3; tmpy >= 0; tmpy-- ){if( box[tmpy][tmpx] ) break;}tmpy++;if( tmpy>0 ){for( ; tmpy<4; tmpy++ ){if( tmpy+y<0 || tmpy+y>=ROW || tmpx+x<0 || tmpx+x>=COL ) continue;if(!Map[tmpy+y][tmpx+x]) c++; //空出的方格}}}return c;}//当启动自动求解功能时,求下一个方块的最佳下降位置//策略1为:放置后,空出的方格数最少,为MinC1,此时能达到最高位置为MaxY1,该位置为BestX1;//策略2为:放置后,能下降的位置最高,为MaxY2,此时空出的方格数为MinC2,该位置为BestX2;//必有MaxY1<=MaxY2, MinC1>=MinC2//取二者的折衷,策略为:优先采取策略1,但如果MinC2==MinC1或MaxY2>=MaxY1+2,则取策略2int BestStartX( ){int X, Y, tmpx, tmpy; //循环变量int BestX = 0, MaxY = 0, MinC = 100;//最终所求的最佳下降位置int BestX1, MaxY1, MinC1; //策略1:MinC:最佳位置处放置方块时,空出的空格最少,BestX:最佳下降位置,MaxY:能下降到的位置int BestX2, MaxY2, MinC2; //策略2:最佳位置为能下降的位置最高int c; //以上策略求最值时用到的辅助变量int tBox1[4][4], tBox2[4][4]; //tBox2为实现旋转时用到的临时变量int Rotates = 0, Rotates1 = 0, Rotates2 = 0;//找到最佳位置后,当前方块需要旋转的次数int Last1, Last2; //Last1为下一个方块未旋转时最下一个方格所在的行,Last2为旋转后最下一个方格所在的行memcpy(tBox1, NextBox, sizeof(tBox1)); memcpy(tBox2, NextBox, sizeof(tBox1)); for( tmpy=3; tmpy>=0; tmpy-- ) //统计tBox1中最下一个方格所在的行{for( tmpx=0; tmpx<4; tmpx++ ) if(tBox1[tmpy][tmpx]) break;if(tmpx<4) break;}Last1 = tmpy;BestX1 = 0, MaxY1 = 0, MinC1 = 100; BestX2 = 0, MaxY2 = 0, MinC2 = 100;//枚举从第0~COL-4列下落for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last1>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last1;if( Y+Last1>MaxY2 || Y+Last1==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last1;}//第1次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 1;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 1;}//第2次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 2;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 2;}//第3次旋转,旋转后为tBox1Last2 = RotateTest(tBox1, tBox2); memcpy(tBox1, tBox2, sizeof(tBox1));for( X=0; X<=COL-4; X++ ){for( Y=0; Y<=ROW-1; Y++ )if( !Test( Y, X, tBox1 ) ) break;Y--;c = count1(Y,X,tBox1);if( c<MinC1 || c==MinC1 && Y+Last2>MaxY1 )MinC1 = c, BestX1 = X, MaxY1 = Y+Last2, Rotates1 = 3;if( Y+Last2>MaxY2 || Y+Last2==MaxY2 && c<MinC2 )MinC2 = c, BestX2 = X, MaxY2 = Y+Last2, Rotates2 = 3;}MinC = MinC1, BestX = BestX1, MaxY = MaxY1, Rotates = Rotates1;if( MinC2==MinC1 || MaxY2>=MaxY1+2 )MinC = MinC2, BestX = BestX2, MaxY = MaxY2, Rotates = Rotates2;if( Rotates>0 ){for( int i=0; i<Rotates; i++ ){RotateTest(NextBox, tBox1);memcpy(NextBox, tBox1, sizeof(tBox1));}}return BestX;}int NewFall( ) //新的方块落下(如果能落下返回1,否则不能落下返回0(程序就该结束了)) {int y, x;CurrentY = 0; //当前方块的当前位置是指该方块(4×4大小)的左上角所在位置if(bAuto) CurrentX = BestStartX( );else CurrentX = COL / 2 - 2; //初始为(0,5)for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = NextBox[y][x];}BuildNextBox( ); //产生下一个随机的方块return Test( CurrentY, CurrentX, CurrentBox );}int no[400] = {3,3,5,1};void BuildNextBox( ) //产生下一个随机的方块{static int j=0;int i, y, x;i = rand()%MAX_CLASS; //随机生成0~6的整数for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )NextBox[y][x] = Box[i][y][x];}}//测试在(y,x)位置(左上角位置)是否能放置方块box,能放置返回1,否则返回0int Test( int y, int x, int box[4][4] ){int tmpy, tmpx;for( tmpy = 0; tmpy < 4; tmpy++ ){for( tmpx = 0; tmpx < 4; tmpx++ ){if( Map[tmpy + y][tmpx + x] && box[tmpy][tmpx] )return 0;}}return 1;}int Drop( ) //定时时间到,当前方块下降一行位置(如果能下降返回1,否则返回0){int NewY;NewY = CurrentY + 1;if( Test( NewY, CurrentX, CurrentBox ) ){CurrentY = NewY;return 1;}return 0;}void PutBox( ) //在当前位置(CurrentY,CurrentX)放置当前方块(此时当前方块已经不能下降了){int y, x;for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] )Map[CurrentY + y][CurrentX + x] = CurrentBox[y][x];}}}int Move( int Right ) //(通过方向键)移动方块,参数right为1表示向右移动,为0表示向左移动{int x;if( Right ) x = CurrentX + 1; //向右移动一列位置else x = CurrentX - 1; //向左移动一列位置if( Test( CurrentY, x, CurrentBox ) ){CurrentX = x;return 1;}return 0;}void Clear( ) //清除满足条件的行{int y, x; //循环变量int DelY, DelX; //循环变量int Full; //一行是否满的标志for( y = 0; y < ROW - 1; y++ ) //检查第0~22行{Full = 1;for( x = 1; x < COL - 1; x++ ) //检查每行的第1~12列{if( !Map[y][x] ){Full = 0; break;}}if( Full ) //第y行满了,删除该行,该行以上的其他行下移一行{iDeleteRows++; iTotalNum = iDeleteRows*100; //更新得分for( DelY = y; DelY > 0; DelY-- ){for( DelX = 1; DelX < COL - 1; DelX++ )Map[DelY][DelX] = Map[DelY-1][DelX];}for( DelX = 1; DelX < COL - 1; DelX++ ) //第0行置为0Map[0][DelX] = 0;}}}int Rotate( ) //测试旋转是否可行,如果可行则旋转当前方块{int y, x;int TmpBox[4][4];RotateTest( CurrentBox, TmpBox );if( Test( CurrentY, CurrentX, TmpBox ) ){for( y = 0; y < 4; y++ ){for( x = 0; x < 4; x++ )CurrentBox[y][x] = TmpBox[y][x];}return 1;}else return 0;}/*0000 0000 0000 //旋转规律是:Box3[y][x] = Box1[y][3-x] -> 方块绕竖直方向对称变换0100-> 0010-> 0010 //Box2[x][y] = Box3[y][x] -> 沿着主对角线对称变换(相当于矩阵转置)1110 0111 01100000 0000 0010 */int RotateTest( int Box1[4][4], int Box2[4][4] ) //旋转当前方块{ //新增返回值为:旋转后的Box2中最下一个方格所在的行int y, x;for( y = 0; y < 4; y++ ){for( x = 3; x >=0; x-- )Box2[x][y] = Box1[y][3 - x];}for( y=3; y>=0; y-- ) //统计Box2中最下一个方格所在的行{for( x=0; x<4; x++ ){if(Box2[y][x]) break;}if(x<4) break;}return y;}LRESULT CALLBACK WndProc( HWND hwnd, UINT message, //窗口处理函数WPARAM wParam, LPARAM lParam ){HDC hdc, hdcMem;int y, x;PAINTSTRUCT ps;HBITMAP hBitMap;HPEN hPen;HBRUSH hBrush;static int cxClient, cyClient; //窗口客户区宽度和高度char str[20]; //用于显示得分的变量switch( message ){case WM_CREATE:SetTimer( hwnd, tDown, tDownTime, NULL ); //开启两个定时器SetTimer( hwnd, tPaint, tPaintTime, NULL );srand( (unsigned)time( NULL ) );bAuto = false;Pause = false;InitMap( );BuildNextBox( ); //先随机产生一个方块NewFall( ); //方块落下并随机产生下一个方块sprintf( str, " 得分:%d", iTotalNum ); strcat( WindowTxt, str );SetWindowText(hwnd,WindowTxt);return 0;case WM_SIZE:cxClient = LOWORD( lParam ); //取得窗口客户区宽度和高度cyClient = HIWORD( lParam );return 0;case WM_TIMER:switch( wParam ){case tDown: //下降定时器if( !Drop( ) ) //如果不能下降则放置当前方块{PutBox( );MessageBeep( -1 );Clear( ); //清除//刷新得分sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}}break;case tPaint: //重绘定时器InvalidateRect(hwnd, NULL, FALSE); //强制重绘窗口工作区break;}case WM_KEYDOWN:switch( wParam ){case VK_LEFT: //"向左"方向键if(bAuto) break;Move(0); break;case VK_RIGHT: //"向右"方向键if(bAuto) break;Move(1); break;case VK_UP: //"向上"方向键:旋转if(bAuto) break;Rotate( ); break;case VK_DOWN: //"向下"方向键:当前方块下移一行位置if(bAuto) break;MessageBeep( -1 ); Drop( ); break;case VK_RETURN: //回车键:暂停Pause = !Pause;if( Pause ) //暂停、自动求解时也可以暂停KillTimer( hwnd, tDown );else //启动{if(bAuto) SetTimer( hwnd, tDown, tDownTime/5, NULL );else SetTimer( hwnd, tDown, tDownTime, NULL );}break;case VK_SPACE:if(bAuto) break;while( 1 ) //使用永真循环,使得当前方块一直下降到不能下降为止{if( !Drop( ) ){PutBox( ); Clear( );sprintf( str, "%d", iTotalNum ); WindowTxt[36] = 0;strcat( WindowTxt, str ); SetWindowText(hwnd,WindowTxt);if( !NewFall( ) ) //如果新的方块不能落下,则程序结束{KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );//PostMessage( hwnd, WM_CLOSE, NULL, NULL );}break;}}break;case VK_F1:bAuto = !bAuto;if(bAuto) //自动求解{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime/5, NULL );memcpy( WindowTxt+25, s2, strlen(s2) ); //修改标题}else{KillTimer(hwnd, tDown );SetTimer( hwnd, tDown, tDownTime, NULL );memcpy( WindowTxt+25, s1, strlen(s1) ); //修改标题}SetWindowText(hwnd,WindowTxt);break;}case WM_PAINT: //重绘窗口工作区hdc = BeginPaint( hwnd, &ps );hdcMem = CreateCompatibleDC( hdc );hBitMap = CreateCompatibleBitmap( hdc, cxClient, cyClient );SelectObject( hdcMem, hBitMap );//画地图最外面的矩形(4, 4, 246, 446)Rectangle( hdcMem, StartX + LEN * 1 - 1,StartY + LEN * 1 - 1,StartX + LEN * (COL - 1) + 1, StartY + LEN * (ROW - 1) + 1 );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) );SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(250, 250, 250) );SelectObject( hdcMem, hBrush );for( y = 1; y < ROW - 1; y++ ) //画地图中的每一格{for( x = 1; x < COL - 1; x++ ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX + LEN * (x + 1), StartY + LEN * (y + 1) );}}DeleteObject( hPen );DeleteObject( hBrush );hPen = CreatePen( PS_SOLID, 1, RGB(180, 180, 180) ); SelectObject( hdcMem, hPen );hBrush = CreateSolidBrush( RGB(255, 100, 100) );SelectObject(hdcMem, hBrush);for( y = 1; y < ROW - 1; y++ ) //画出地图中每个被占据的方格{for( x = 1; x < COL - 1; x++ ){if( Map[y][x] ){Rectangle( hdcMem, StartX + LEN * x, StartY + LEN * y,StartX +LEN * (x + 1), StartY + LEN * (y + 1) );}}}for( y = 0; y < 4; y++ ) //画当前方块{for( x = 0; x < 4; x++ ){if( CurrentBox[y][x] ){if( y + CurrentY > 0 ){Rectangle( hdcMem, (x + CurrentX) * LEN + StartX,(y + CurrentY) * LEN +StartY,(x + CurrentX + 1) * LEN + StartX,(y + CurrentY + 1) * LEN + StartY );}}}}for( y = 0; y < 4; y++ )//在窗口右边区域画下一个方块{for( x = 0; x < 4; x++ ){if( NextBox[y][x] ){Rectangle( hdcMem, (x + COL) * LEN + StartX,(y + 2) * LEN + StartY,(x+ COL + 1) * LEN + StartX, (y + 3) * LEN + StartY );}}}DeleteObject( hPen );DeleteObject( hBrush );DeleteObject( hBitMap );BitBlt( hdc, 0, 0, cxClient, cyClient, hdcMem, 0, 0, SRCCOPY );DeleteDC( hdcMem );EndPaint( hwnd, &ps );return 0;case WM_DESTROY:KillTimer(hwnd, tDown );KillTimer(hwnd, tPaint );PostQuitMessage( 0 );return 0;}//end of switch( message )return DefWindowProc( hwnd, message, wParam, lParam );}。

俄罗斯方块代码

俄罗斯方块代码

class CTetrisDlg :public CDialog {public:void m_DrawImage(int ID, COLORREF clr, int x,int y, int shape);CTetrisDlg(CWnd* pParent = NULL); // standard constructor void m_DrawImage(int ID,CO LORREF clr,CPoint point,int shape);public:virtual BOOL PreTranslateMessage(MSG* pMsg);protected:virtual void DoDataExchange(CDataExchange* pDX);protected:virtual BOOL OnInitDialog();afx_msg void OnSysCommand(UINT nID, LPARAM lParam);afx_msg void OnPaint();afx_msg HCURSOR OnQueryDragIcon();afx_msg HBRUSH OnCtlColor(CDC* pDC, CWnd* pWnd, UINT nCtlColor);afx_msg void OnTimer(UINT nIDEvent);private:DWORD State;int Score;CPoint PointArray[4];bool Map[27][41];int Shape[19][8];int m_OldNextShape;int m_NextShape;int m_ioldshape;CPoint m_poldpos;int size;CPoint m_pcurpos;int m_CurShape;};BOOL CTetrisApp::InitInstance() {CTetrisDlg dlg;m_pMainWnd = &dlg;SetDialogBkColor(RGB(0,0,0),RGB(0,255,0));int nResponse = dlg.DoModal();}CTetrisDlg::CTetrisDlg(CWnd* pParent /*=NULL*/): CDialog(CTetrisDlg::IDD, pParent){srand(time(NULL));//设置随机种子m_CurShape=rand()%19;//初始化方块类型m_pcurpos.x=120;//方块当前位置m_pcurpos.y=0;m_NextShape=rand()%19;m_OldNextShape=m_NextShape;m_ioldshape=m_CurShape;m_poldpos=m_pcurpos; size=10;//方块大小Score=0;State=0;m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);}BOOL CTetrisDlg::OnInitDialog() {SetTimer(1,500,NULL);GetDlgItem(IDC_STA TIC_SCORE)->SetWindowText("0");GetDlgItem(IDC_STA TIC_LEVEL)->SetWindowText("Level 1"); int Shape1[19][8]={{0,0,0,0,0,0,0,0},{0,0,0,0,-1,2,-1,2},{0,0,-1,-1,0,0,1,-1},{0,0,0,0,0,2,0,0},{2,0,0,0,0,0,0,0},{0,2,0,0,0,0,0,0},{0,0,2,0,0,0,0,0},{0,0,0,0,-1,2,0,1},{0,0,0,0,0,0,1,-1},{0,0,1,1,0,0,0,0},{-1,1,0,0,0,0,0,0},{0,0,1,1,0,0,0,0},{-1,1,0,0,0,0,0,0},{0,0,0,0,-1,-1,0,0},{0,0,0,0,0,0,1,-1},{0,0,0,0,-1,2,0,0},{0,0,0,0,0,0,-2,-1},{0,0,1,-2,0,0,0,0},{0,0,0,0,-2,1,0,0}};memcpy(Shape,Shape1,sizeof(int)*19*8);for(int i=0;i<27;i++)for(int j=0;j<41;j++){Map[i][j]=0; }return TRUE; // return TRUE unless you set the focus to a control }void CTetrisDlg::OnPaint(){m_DrawImage(IDC_STA TIC_MAIN,RGB(0,0,0),m_poldpos,m_ioldshape);m_DrawImage(IDC_STA TIC_PRE,RGB(0,0,0),50,50,m_OldNextShape);m_poldpos=m_pcurpos;//记录当前形状和位置m_ioldshape=m_CurShape;m_OldNextShape=m_NextShape;m_DrawImage(IDC_STA TIC_MAIN,RGB(0,255,0),m_pcurpos,m_CurShape); m_DrawImage(IDC_STA TIC_PRE,RGB(0,255,0),50,50,m_NextShape);CDialog::OnPaint();}void CTetrisDlg::OnTimer(UINT nIDEvent) {int i;switch(nIDEvent){case 1://Timer1触底判断,并产生新的方块for(i=0;i<4;i++){if(PointArray[i].y==40*size ||Map[PointArray[i].x/size][PointArray[i].y/size+1]==1){for(int j=0;j<4;j++){Map[PointArray[j].x/size][PointArray[j].y/size]=1;}m_pcurpos.x=120;m_pcurpos.y=0;m_CurShape=m_NextShape; m_NextShape=rand()%19; break;}}if(i>=4){m_pcurpos.y+=size;}Invalidate();break;case 2://Timer2用来实现暂停功能,不过效果不太理想。

俄罗斯方块代码

俄罗斯方块代码

俄罗斯方块代码清单:#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));}。

俄罗斯方块代码

俄罗斯方块代码

VC6.0环境下的俄罗斯方块C语言源代码2011-5-15 12:31提问者:wobuzy1|浏览次数:2804次我来帮他解答2011-5-15 12:35满意回答#include <stdlib.h>#include <graphics.h>#include <bios.h>#define mDRAW 5#define mLINE 6#define mADOWN 7#define mGEN 8#define mLEFT 75#define mRIGHT 77#define mSPACE 57#define mDOWN 80#define mESC 1#define TIMEINT 2#define MAXX 9#define MAXY 30#define BACKCOLOR BLACK#define WINX 50#define WINY 470#define GAP 6#define AREAX (WINX+GAP)#define AREAY (WINY-GAP)#define BOXW 15int oldarea[MAXY+1][MAXX];int area[MAXY+1][MAXX];int actW,actH,actX,actY;int curX,curY,curColor,curW,curH;int newX,newY,newColor,newW,newH; int active;int box[4][4];int FORCOLOR;int MESSAGE;int BOX[7][4][4]={{{1,1,1,1},{0,0,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,1,0}, {1,0,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,1,0}, {0,0,1,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,1,0}, {0,1,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,0,0}, {0,1,1,0}, {0,0,0,0}, {0,0,0,0} },{{0,1,1,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0} },{{1,1,0,0}, {1,1,0,0}, {0,0,0,0}, {0,0,0,0}}};void init(); void draw(); int genBox(); int getKey(); void lineFull(); int moveLeft();int moveRight();int moveDown();int rotate();int getW();int getH();void clearOldBox();void putNewBox();int collisionRotate(int box[][4]); void getMessage();void dispatchMessage();int timeCome();void fallDown();int gameOver();main(){int i;init();do{getMessage(); dispatchMessage();}while(!gameOver());getch();closegraph();}void getMessage(){if(MESSAGE) return;if(timeCome()){MESSAGE=mADOWN; return;}if(bioskey(1)){MESSAGE=bioskey(0)>>8; return;}}void dispatchMessage(){switch(MESSAGE){case mLEFT: moveLeft();break; case mRIGHT: moveRight();break; case mADOWN: moveDown();break; case mSPACE: rotate();break;case mDOWN: fallDown(); break; case mDRAW: draw();break;case mLINE: lineFull();break;case mGEN: genBox();break; case mESC: closegraph(); exit(0); default: MESSAGE=0;}}void fallDown(){while(active){moveDown(); draw();}MESSAGE=mLINE;}int timeCome(){static long tm, old;tm=biostime(0,tm);if(tm-old<TIMEINT) return 0;else{old=tm; return 1;}}void init(){int i,j,x1,y1,x2,y2;int driver=DETECT, mode=0; randomize();registerbgidriver(EGAVGA_driver);initgraph(&driver,&mode,"");cleardevice();setfillstyle(SOLID_FILL,BLUE);bar(0,0,639,479);x1=AREAX;y1=AREAY-BOXW*MAXY;x2=AREAX+MAXX*BOXW;y2=AREAY;rectangle(--x1,--y1,++x2,++y2);setfillstyle(SOLID_FILL,BLACK);bar(++x1,++y1,--x2,--y2);y1=AREAY-MAXY*BOXW; y2=AREAY; setcolor(DARKGRAY);for(i=0;i<MAXX;i++){x1=AREAX+i*BOXW;line(x1,y1,x1,y2);}x1=AREAX; x2=x1+MAXX*BOXW;for(j=0;j<MAXY;j++){y1=AREAY-j*BOXW;line(x1,y1,x2,y1);}for(j=0;j<MAXY;j++)for(i=0;i<MAXX;i++)area[j][i]=oldarea[j][i]=0;actX=0; actY=0; actW=MAXX-1; actH=MAXY-1; draw();MESSAGE=mGEN;}int genBox(){int i,j,boxidx;boxidx=random(7); FORCOLOR=random(7)+1; for(j=0;j<4;j++)for(i=0;i<4;i++)box[j][i]=BOX[boxidx][j][i];curW=getW(); curH=getH();curX=(MAXX+curW)/2;if(curX+curW>=MAXX)curX=MAXX-1-curW;curY=MAXY-1-curH;newX=curX; newY=curY; actX=curX;actY=curY;actW=newW=curW; actH=newH=curH;active=1;if(collision(box)) return 0;putNewBox();draw(); MESSAGE=0;return 1;}void lineFull(){int row,col, rowEnd,full,i,j;rowEnd=newY+newH;if(rowEnd>=MAXY-1) rowEnd=MAXY-2;for(row=newY; row<=rowEnd;){full=1;for(col=0;col<MAXX;col++)if(!area[row][col]){full=0; break;}if(!full){++row; continue;}for(j=row; j<MAXY-1;j++)for(i=0;i<MAXX;i++)area[j][i]=area[j+1][i];actX=0;actY=row; actW=MAXX-1; actH=MAXY-1-row;draw(); rowEnd--;}MESSAGE=mGEN;}void draw(){int row,col,x1,y1,x2,y2;for(row=actY;row<=actY+actH;row++)for(col=actX;col<=actX+actW;col++)if(area[row][col]!=oldarea[row][col]){if(area[row][col]==0)setfillstyle(SOLID_FILL,BACKCOLOR);elsesetfillstyle(SOLID_FILL,FORCOLOR);x1=AREAX+col*BOXW; x2=x1+BOXW;y1=AREAY-(row+1)*BOXW; y2=y1+BOXW;bar(++x1,++y1,--x2,--y2);oldarea[row][col]=area[row][col];}MESSAGE=0;}int moveLeft(){newX=curX-1; clearOldBox();if(collision(box)){newX=curX;putNewBox();MESSAGE=0;return 0;}putNewBox();actW=curW+1; actX=curX=newX; MESSAGE=mDRAW;return 1;}int moveRight(){newX=curX+1; clearOldBox();if(collision(box)){newX=curX;putNewBox();MESSAGE=0;return 0;}putNewBox();actW=curW+1; actX=curX; curX=newX; MESSAGE=mDRAW;return 1;}int moveDown(){int i,j;newY=curY-1;clearOldBox();if(collision(box)){newY=curY;putNewBox();active=0;MESSAGE=mLINE;return 0;}putNewBox();actH=curH+1; actY=newY; curY=newY;MESSAGE=mDRAW;return 1;}int rotate(){int newBox[4][4];int i,j;clearOldBox();for(j=0;j<4;j++)for(i=0;i<4;i++)newBox[j][i]=0;for(j=0;j<4;j++)for(i=0;i<4;i++)newBox[curW-i][j]=box[j][i];newW=curH; newH=curW;if(collisionRotate(newBox)){newW=curW; newH=curH; newX=curX; newY=curY;putNewBox();MESSAGE=0;return 0;}for(j=0;j<4;j++)for(i=0;i<4;i++)box[j][i]=newBox[j][i];putNewBox();actH=newH>curH? newH:curH;actW=curX+actH-newX;actX=newX; actY=newY; curX=newX;curY=newY; curW=newW; curH=newH;MESSAGE=mDRAW;return 1;}int getW(){int i,j;for(i=3;i>0;i--)for(j=0;j<4;j++)if(box[j][i]) return i;return 0;}int getH(){int i,j;for(j=3;j>0;j--)for(i=0;i<4;i++)if(box[j][i]) return j;return 0;}void clearOldBox(){int i,j;for(j=0;j<=curH; j++)for(i=0;i<=curW; i++)if(box[j][i])area[curY+j][curX+i]=0;}void putNewBox(){int i,j;for(j=0;j<=newH;j++)for(i=0;i<=newW;i++)if(box[j][i])area[newY+j][newX+i]=FORCOLOR; }int collision(int cbox[][4]){int i,j;if(newX<0) return 1;if(newX+newW>=MAXX) return 1;if(newY<0) return 1;for(j=0;j<=newH;j++)for(i=0;i<=newW;i++)if(area[newY+j][newX+i]&&cbox[j][i]) return 1;return 0;}int collisionRotate(int cbox[][4]){int i,j;if(newX+newW>=MAXX) newX=MAXX-1-newW; if(newY+newH>=MAXY) newY=MAXY-1-newH; if(collision(cbox)) return 1;for(i=0;i<=newW;i++)for(j=0;j<=newH;j++)if(area[newY+j][newX+i]){newX-=newW-i+1; goto L;}L: return collision(cbox);}int gameOver(){if(!active &&(curY+curH>MAXY-3)) return 1; else return 0;}追问能有注释的不?。

vb 俄罗斯方块设计程序及分析

vb 俄罗斯方块设计程序及分析

************* 俄罗斯方块DIY ***************键盘控制方法:1.左右光标键控制方块左右移动;2.上光标键控制方块顺时针旋转90度;3.下光标键控制方块加速向下移动。

设计过程:(一) 在VB6.0中新建一个标准EXE工程(二) 建立一个窗体,窗体属性设置如下:名称= frmErsCaption = "俄罗斯方块1.12"(三) 在窗体上添加两个图片框,属性设置如下:(1)名称= picPlayAutoRedraw = TrueBackColor = &H00FF0000& '蓝色(2)名称= picNextAutoRedraw = TrueBackColor = &H00FF0000& '蓝色(四) 在窗体上再添加一个标签,属性设置如下:名称= lblFenShu(五) 用菜单编辑器制作如下菜单:(1)一级菜单项:标题= "文件(&F)"名称= mnuSet下属二级菜单项:标题= "退出"名称= mnuExit(2)一级菜单项:标题= "帮助(&H)"名称= mnuHelp下属二级菜单项:标题= "操作提示"名称= mnuTopic(六) 在窗体代码窗口输入如下代码:Option ExplicitPrivate Sub Form_KeyDown(KeyCode As Integer, Shift As Integer) '按键代码传入Main()主程序中gKeyRef = KeyCodeEnd SubPrivate Sub Form_Load()Me.Top=0Me.KeyPreview = TruepicPlay.ScaleMode = 3 'PixelpicNext.ScaleMode = 3 'PixelEnd SubPrivate Sub Form_Unload(Cancel As Integer)EndEnd SubPrivate Sub mnuExit_Click()'退出Unload MeEnd SubPrivate Sub mnuTopic_Click()Dim Msg As StringMsg = "键盘控制方法:" & vbCrLfMsg = Msg & "1.左右光标键控制方块左右移动;" & vbCrLfMsg = Msg & "2.上光标键控制方块顺时针旋转90度;" & vbCrLfMsg = Msg & "3.下光标键控制方块加速向下移动。

VB 俄罗斯方块的设计

VB 俄罗斯方块的设计

一、课程设计的目的与要求 (2)1.1、俄罗斯方块的要求 (2)1.2、俄罗斯方块设计的目的 (3)二、题目分析 (4)2.1、概要设计 (4)2.2、详细设计 (4)游戏区模块的设计 (5)控制区模块的设计 (5)三、设计思路 (6)3.1、系统流程的总设计 (6)3.2、游戏区模块的设计 (7)3.2.1、Bitblt函数参数的意义与用法 (7)3.2.2、俄罗斯方块的旋转 (8)3.2.3、如何实现方自动消除满行的方块 (9)3.2.4、随机从 7 个方块中选择一个 (10)3.2.5、设置每个模块的测试计 (11)3.3、整体游戏程序的结构设计 (11)3.4、程序设计 (13)四、调试过程 (14)4.1、设计游戏界面 (14)4.2、完善与改善游戏界面 (15)五、运行结果 (18)六、课程设计总结 (20)附录 (22)一、课程设计的目的与要求1.1、俄罗斯方块的要求俄罗斯方块的基本规则是移动、旋转和摆放游戏自动输出的各种方块,使之排列成完整的一行或多行并且消除得分,俄罗斯方块游戏是一款适合大众的游戏软件,它适合不同年龄的人玩。

本软件要实现的功能如下:(1)游戏区:玩家可以在游戏区中堆积方块,并能够在游戏过程中随时了解得分情况。

(2)游戏控制:玩家可以通过游戏控制功能来选择开始新的一局游戏,暂停或退出游戏。

(3)级别设置:玩家可以根据自己的需要自行设定游戏的开始级别,级别越高,游戏的速度越快,难度越大。

游戏规则如下:(1)电脑随机产生4个小方块组成的不同形状的游戏块,从上往下降落。

(2)游戏面板的宽度为12(以小方块的宽度为单位),高度为22,当一行被12个小方块填满时,此行便会被自动消除。

(3)利用键盘上的左右箭头键可以控制游戏块的左移与右移。

(4)利用键盘上的向上箭头键可以控制游戏块的旋转。

(5)利用键盘上的向下箭头键可以控制游戏块的快速下落。

(6)当游戏块无法下落时,游戏结束。

俄罗斯方块游戏原代码

俄罗斯方块游戏原代码

#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键,退出游戏 */}}。

vb俄罗斯方块程序代码

vb俄罗斯方块程序代码

Option ExplicitOption Base 0Private blnGrid(0 To 19, 0 To 9) As Boolean '网格Private lngColor(0 To 19, 0 To 9) As Long '网格绘制颜色Private blnBlock(0 To 4, 0 To 3, 0 To 3, 0 To 3) As Boolean '五种方块的四种不同方位Private blnStarted As Boolean '是否已开始玩Dim intTypeCur As Integer '当前方块的类型Dim lngColorCur As Long '当前方块的颜色Dim intOrieCur As Integer '当前方块的方位Dim intOrieNext As Integer '当前方块的下一个方位Dim intXCur As Integer '当前方块的当前位置Dim intYCur As IntegerDim intXNext As Integer '当前方块的下一个位置Dim intYNext As IntegerPublic intDownDistance As Integer '快速下降时的下降距离Public blnClockWise As Boolean '方块旋转方向Public blnShowNext As Boolean '是否显示下一个方块Public blnScheme As Boolean '按键方案Dim lngScore As Long '得分Dim intTypeNew As Integer '下一个方块的类型Dim lngColorNew As Long '下一个方块的颜色Dim intOrieNew As Integer '下一个方块的方位Dim lngHighScore As LongDim blnRedraw As BooleanPrivate Sub ShowBlock() '显示下落的方块Dim i As Integer, j As Integer'去掉旧图象For i = 0 To 3If i + intYCur >= 0 And i + intYCur <= 19 Then '如果在大方框外,则不绘制For j = 0 To 3If j + intXCur >= 0 And j + intXCur <= 9 ThenIf (j + intXCur >= 0) And (j + intXCur <= 9) And (blnBlock(intTypeCur, intOrieCur, i, j)) And Not blnGrid(i + intYCur, j + intXCur) ThenpicGrid.Line ((j + intXCur) * 20 + 2, (i + intYCur) * 20 + 2)-((j + intXCur) * 20 + 19, (i + intYCur) * 20 + 19), vbBlack, BpicGrid.Line ((j + intXCur) * 20 + 4, (i + intYCur) * 20 + 4)-((j +intXCur) * 20 + 17, (i + intYCur) * 20 + 17), vbWhite, BFEnd IfEnd IfNextEnd IfNext'画新图象For i = 0 To 3If i + intYNext >= 0 And i + intYNext <= 19 Then '如果在大方框外,则不绘制For j = 0 To 3If (j + intXNext >= 0) And (j + intXNext <= 9) And (blnBlock(intTypeCur, intOrieNext, i, j)) ThenpicGrid.Line ((j + intXNext) * 20 + 2, (i + intYNext) * 20 + 2)-((j + intXNext) * 20 + 19, (i + intYNext) * 20 + 19), lngColorCur, BpicGrid.Line ((j + intXNext) * 20 + 4, (i + intYNext) * 20 + 4)-((j + intXNext) * 20 + 17, (i + intYNext) * 20 + 17), lngColorCur, BFEnd IfNextEnd IfNextintYCur = intYNextintXCur = intXNextintOrieCur = intOrieNextEnd SubPrivate Sub Form_Activate()Dim i As Integer, j As Integer'绘制表格与已有的堆积方块For i = 0 To 19For j = 0 To 9If blnGrid(i, j) ThenpicGrid.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), lngColor(i, j), BpicGrid.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), lngColor(i, j), BFElsepicGrid.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), vbBlack, BpicGrid.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), vbWhite, BF End IfNextNext'绘制“下一个”网块For i = 0 To 3For j = 0 To 3picNext.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), vbBlack, B NextNext'初次启动时不显示下一个和移动方块If blnStarted ThenIf blnShowNext ThenFor i = 0 To 3For j = 0 To 3If blnBlock(intTypeNew, intOrieNew, i, j) ThenpicNext.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), lngColorNew, BpicNext.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), lngColorNew, BFElsepicNext.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), vbBlack, BpicNext.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), vbWhite, BFEnd IfNextNextElseFor i = 0 To 3For j = 0 To 3picNext.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), vbBlack, BpicNext.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), vbWhite, BFNextNextEnd IfCall ShowBlockEnd IfEnd SubPrivate Sub form_KeyDown(KeyCode As Integer, Shift As Integer)If KeyCode = 13 ThenIf Not blnStarted ThenCall lblStart_ClickExit SubEnd IfIf Timer1.Enabled ThenTimer1.Enabled = Falselblstart.Caption = "继续"Exit SubElseTimer1.Enabled = Truelblstart.Caption = "暂停"Exit SubEnd IfEnd IfIf Not Timer1.Enabled Then Exit SubIf blnScheme ThenSelect Case KeyCodeCase vbKeyLeftGoLeftCase vbKeyRightGoRightCase vbKeyUpRotateCase vbKeyDown '加速下降QuickDownEnd SelectElseSelect Case KeyCodeCase Asc("A")GoLeftCase Asc("S")GoRightCase Asc("W")RotateCase Asc("Z") '加速下降QuickDownEnd SelectEnd IfCall ShowBlockEnd SubPrivate Sub Form_Unload(Cancel As Integer)Open App.Path & "\block.dat" For Output As 1Write #1, intDownDistance, blnClockWise, blnShowNext, blnScheme, lngHighScoreClose 1End SubPrivate Sub lblStart_Click()If Not blnStarted ThenRandomizeblnStarted = TrueintTypeCur = Int(Rnd * 5) '随机出现方块与下一个方块lngColorCur = QBColor(Int(Rnd * 7))intOrieCur = Int(Rnd * 4) '随机决定方块方位intOrieNext = intOrieCurintYCur = -3: intXCur = 2 '方块出现时的位置intYNext = intYCur: intXNext = intXCurintTypeNew = Int(Rnd * 5) '随机产生下个方块的类型,方块与颜色intOrieNew = Int(Rnd * 4)lngColorNew = QBColor(Int(Rnd * 7))Call ShowBlockCall ShowNextEnd IfTimer1.Enabled = Not Timer1.EnabledIf Timer1.Enabled Thenlblstart.Caption = "暂停"Elselblstart.Caption = "继续"End IfEnd SubPrivate Sub mnuExit_Click()Unload MeEnd SubPrivate Sub mnuOption_Click()Timer1.Enabled = Falselblstart.Caption = "继续"frmOption.Show 1, MeEnd SubPrivate Sub Timer1_Timer()Dim i As Integer, j As IntegerFor i = 3 To 0 Step -1 '测试是否落到底For j = 0 To 3If blnBlock(intTypeCur, intOrieCur, i, j) And (i + intYCur >= 19) Then Exit For '超出下边界If Not (i + intYCur + 1 < 0 Or i + intYCur + 1 > 19 Or j + intXCur < 0 Or j + intXCur > 9) Then '如果下边遇到方块If blnBlock(intTypeCur, intOrieCur, i, j) And (blnGrid(i + intYCur + 1, j + intXCur)) ThenExit ForEnd IfEnd IfNextIf j <= 3 Then Exit ForNextIf i >= 0 Then '如果方块已落到底If intYCur <= -1 Then '本轮已结果Timer1.Enabled = FalseIf lngScore > lngHighScore ThenlngHighScore = lngScoretxtHigh.Text = lngHighScoreEnd IflngScore = 0txtScore.Text = 0RandomizeblnStarted = TrueintTypeCur = Int(Rnd * 5) '随机出现方块与下一个方块lngColorCur = QBColor(Int(Rnd * 14))intOrieCur = Int(Rnd * 4) '随机决定方块方位intOrieNext = intOrieCurintYCur = -3: intXCur = 2 '方块出现时的位置intYNext = intYCur: intXNext = intXCurintTypeNew = Int(Rnd * 5) '随机产生下个方块的类型,方块与颜色intOrieNew = Int(Rnd * 4)lngColorNew = QBColor(Int(Rnd * 14))Erase blnGrid, lngColorlblstart.Caption = "开始"Call Form_ActivateElseFor i = 0 To 3For j = 0 To 3If Not (i + intYCur < 0 Or i + intYCur > 19 Or j + intXCur < 0 Or j + intXCur > 9) Then '避免出现下标越界If blnBlock(intTypeCur, intOrieCur, i, j) ThenblnGrid(i + intYCur, j + intXCur) = TruelngColor(i + intYCur, j + intXCur) = lngColorCurEnd IfEnd IfNextNextRandomizeintTypeCur = intTypeNewintTypeNew = Int(Rnd * 5) '随机出现下一个方块lngColorCur = lngColorNewlngColorNew = QBColor(Int(Rnd * 7)) '随机出现下一个方块的颜色intOrieCur = intOrieNew '随机决定方块方位intOrieNext = intOrieNewintOrieNew = Int(Rnd * 4)intYCur = -3: intXCur = 2 '方块出现时的位置intYNext = intYCur: intXNext = intXCurintTypeNew = Int(Rnd * 5) '随机产生下个方块的类型,方块与颜色intOrieNew = Int(Rnd * 4)lngColorNew = QBColor(Int(Rnd * 7))Call ScoreCall ShowBlockCall ShowNext '显示下一个方块类型End IfElseintYNext = intYNext + 1Call ShowBlockEnd IfEnd SubPrivate Sub GoLeft()Dim i As Integer, j As IntegerFor i = 0 To 3For j = 0 To 3If blnBlock(intTypeCur, intOrieCur, j, i) And i + intXCur <= 0 Then Exit Sub '禁止超出左边界NextNextintXNext = intXNext - 1End SubPrivate Sub GoRight()Dim i As Integer, j As IntegerFor i = 3 To 0 Step -1For j = 0 To 3If blnBlock(intTypeCur, intOrieCur, j, i) And i + intXCur >= 9 Then Exit Sub '禁止超出右边界NextNextintXNext = intXNext + 1End SubPrivate Sub Rotate() '旋转Dim i As Integer, j As IntegerDim intTempNext As IntegerIf blnClockWise Then '临时产生下一个方位,检测是否超出范围,或重叠intTempNext = intOrieNext - 1If intTempNext = -1 Then intTempNext = 3ElseintTempNext = intOrieNext + 1If intTempNext = 4 Then intTempNext = 0End IfFor i = 3 To 0 Step -1For j = 0 To 3If blnBlock(intTypeCur, intTempNext, j, i) And i + intXCur > 9 Then Exit Sub '禁止超出右边界If blnBlock(intTypeCur, intTempNext, j, i) And i + intXCur < 0 Then Exit Sub '禁止超出左边界If blnBlock(intTypeCur, intTempNext, j, i) And j + intYCur > 19 Then Exit Sub '禁止超出下边界If blnBlock(intTypeCur, intTempNext, j, i) And j + intYCur < 0 Then Exit Sub '禁止超出上边界If j + intYCur >= 0 And j + intYCur <= 19 And i + intXCur >= 0 And i + intXCur <= 9 ThenIf blnBlock(intTypeCur, intTempNext, j, i) And blnGrid(j + intYCur, i + intXCur) Then Exit Sub '禁止重叠End IfNextNextintOrieCur = intOrieNextintOrieNext = intTempNext' intOrieNext = intOrieNext - 1' If intOrieNext = -1 Then intOrieNext = 3End SubPrivate Sub QuickDown()Dim i As Integer, j As Integer, k As IntegerDoFor i = 3 To 0 Step -1For j = 0 To 3If blnBlock(intTypeCur, intOrieCur, i, j) And (i + intYCur + k >= 19) Then Exit For '超出下边界If Not (i + intYCur + 1 + k < 0 Or i + intYCur + 1 + k > 19 Or j + intXCur < 0 Or j + intXCur > 9) Then '如果下边遇到方块If blnBlock(intTypeCur, intOrieCur, i, j) And (blnGrid(i + intYCur + 1 + k, j + intXCur)) ThenExit ForEnd IfEnd IfNextIf j <= 3 Then Exit ForNextIf i >= 0 Then Exit DoIf k = intDownDistance Then Exit Dok = k + 1LoopintYNext = intYNext + kCall ShowBlockEnd SubPrivate Sub Score()Dim i As Integer, j As Integer, k As Integer, num As IntegerFor i = 19 To 0 Step -1For j = 0 To 9If Not blnGrid(i, j) Then Exit ForNextIf j > 9 Thennum = num + 1For k = i To 1 Step -1For j = 0 To 9blnGrid(k, j) = blnGrid(k - 1, j)lngColor(k, j) = lngColor(k - 1, j)NextNextk = 0For j = 0 To 9blnGrid(k, j) = FalselngColor(k, j) = FalseNexti = i + 1End IfNextIf num > 0 ThenSelect Case numCase 1lngScore = lngScore + 100Case 2lngScore = lngScore + 300Case 3lngScore = lngScore + 700Case 4lngScore = lngScore + 1500End SelecttxtScore.Text = lngScoretxtSpeed = lngScore \ 2000 + 1Timer1.Interval = 300 - txtSpeed * 27Call Form_ActivateEnd IfEnd SubPrivate Sub ShowNext()Dim i As Integer, j As IntegerIf blnShowNext ThenFor i = 0 To 3For j = 0 To 3If blnBlock(intTypeNew, intOrieNew, i, j) ThenpicNext.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), lngColorNew, BpicNext.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), lngColorNew, BFElsepicNext.Line (j * 20 + 2, i * 20 + 2)-(j * 20 + 19, i * 20 + 19), vbBlack, BpicNext.Line (j * 20 + 4, i * 20 + 4)-(j * 20 + 17, i * 20 + 17), vbWhite, BFEnd IfNextNextEnd IfEnd SubPrivate Sub Form_Load()If Dir(App.Path & "\block.dat") <> "" ThenOpen App.Path & "\block.dat" For Input As 1Input #1, intDownDistance, blnClockWise, blnShowNext, blnScheme, lngHighScoreClose 1ElseintDownDistance = 20blnClockWise = TrueblnShowNext = TrueblnScheme = TruelngHighScore = 0End IftxtHigh.Text = lngHighScore'I 型方块数据blnBlock(0, 0, 0, 0) = False: blnBlock(0, 0, 0, 1) = False: blnBlock(0, 0, 0, 2) = True: blnBlock(0, 0, 0, 3) = FalseblnBlock(0, 0, 1, 0) = False: blnBlock(0, 0, 1, 1) = False: blnBlock(0, 0, 1, 2) = True: blnBlock(0, 0, 1, 3) = FalseblnBlock(0, 0, 2, 0) = False: blnBlock(0, 0, 2, 1) = False: blnBlock(0, 0, 2, 2) = True: blnBlock(0, 0, 2, 3) = FalseblnBlock(0, 0, 3, 0) = False: blnBlock(0, 0, 3, 1) = False: blnBlock(0, 0, 3, 2) = True: blnBlock(0, 0, 3, 3) = FalseblnBlock(0, 1, 0, 0) = False: blnBlock(0, 1, 0, 1) = False: blnBlock(0, 1, 0, 2) = False: blnBlock(0, 1, 0, 3) = FalseblnBlock(0, 1, 1, 0) = True: blnBlock(0, 1, 1, 1) = True: blnBlock(0, 1, 1, 2) = True: blnBlock(0, 1, 1, 3) = TrueblnBlock(0, 1, 2, 0) = False: blnBlock(0, 1, 2, 1) = False: blnBlock(0, 1, 2, 2) = False: blnBlock(0, 1, 2, 3) = FalseblnBlock(0, 1, 3, 3) = FalseblnBlock(0, 2, 0, 0) = False: blnBlock(0, 2, 0, 1) = False: blnBlock(0, 2, 0, 2) = True: blnBlock(0, 2, 0, 3) = FalseblnBlock(0, 2, 1, 0) = False: blnBlock(0, 2, 1, 1) = False: blnBlock(0, 2, 1, 2) = True: blnBlock(0, 2, 1, 3) = FalseblnBlock(0, 2, 2, 0) = False: blnBlock(0, 2, 2, 1) = False: blnBlock(0, 2, 2, 2) = True: blnBlock(0, 2, 2, 3) = FalseblnBlock(0, 2, 3, 0) = False: blnBlock(0, 2, 3, 1) = False: blnBlock(0, 2, 3, 2) = True: blnBlock(0, 2, 3, 3) = FalseblnBlock(0, 3, 0, 0) = False: blnBlock(0, 3, 0, 1) = False: blnBlock(0, 3, 0, 2) = False: blnBlock(0, 3, 0, 3) = FalseblnBlock(0, 3, 1, 0) = False: blnBlock(0, 3, 1, 1) = False: blnBlock(0, 3, 1, 2) = False: blnBlock(0, 3, 1, 3) = FalseblnBlock(0, 3, 2, 0) = True: blnBlock(0, 3, 2, 1) = True: blnBlock(0, 3, 2, 2) = True: blnBlock(0, 3, 2, 3) = TrueblnBlock(0, 3, 3, 0) = False: blnBlock(0, 3, 3, 1) = False: blnBlock(0, 3, 3, 2) = False: blnBlock(0, 3, 3, 3) = False'反L 型方块数据blnBlock(1, 0, 0, 0) = False: blnBlock(1, 0, 0, 1) = True: blnBlock(1, 0, 0, 2) = True: blnBlock(1, 0, 0, 3) = TrueblnBlock(1, 0, 1, 0) = False: blnBlock(1, 0, 1, 1) = False: blnBlock(1, 0, 1, 2) = False: blnBlock(1, 0, 1, 3) = TrueblnBlock(1, 0, 2, 0) = False: blnBlock(1, 0, 2, 1) = False: blnBlock(1, 0, 2, 2) = False: blnBlock(1, 0, 2, 3) = FalseblnBlock(1, 0, 3, 0) = False: blnBlock(1, 0, 3, 1) = False: blnBlock(1, 0, 3, 2) = False: blnBlock(1, 0, 3, 3) = FalseblnBlock(1, 1, 0, 0) = False: blnBlock(1, 1, 0, 1) = False: blnBlock(1, 1, 0, 2) = True: blnBlock(1, 1, 0, 3) = TrueblnBlock(1, 1, 1, 0) = False: blnBlock(1, 1, 1, 1) = False: blnBlock(1, 1, 1, 2) = True: blnBlock(1, 1, 1, 3) = FalseblnBlock(1, 1, 2, 0) = False: blnBlock(1, 1, 2, 1) = False: blnBlock(1, 1, 2, 2) = True: blnBlock(1, 1, 2, 3) = FalseblnBlock(1, 1, 3, 0) = False: blnBlock(1, 1, 3, 1) = False: blnBlock(1, 1, 3, 2) = False: blnBlock(1, 1, 3, 3) = FalseblnBlock(1, 2, 0, 0) = False: blnBlock(1, 2, 0, 1) = True: blnBlock(1, 2, 0, 2) = False: blnBlock(1, 2, 0, 3) = FalseblnBlock(1, 2, 1, 0) = False: blnBlock(1, 2, 1, 1) = True: blnBlock(1, 2, 1, 2) = True: blnBlock(1, 2, 1, 3) = TrueblnBlock(1, 2, 2, 3) = FalseblnBlock(1, 2, 3, 0) = False: blnBlock(1, 2, 3, 1) = False: blnBlock(1, 2, 3, 2) = False: blnBlock(1, 2, 3, 3) = FalseblnBlock(1, 3, 0, 0) = False: blnBlock(1, 3, 0, 1) = False: blnBlock(1, 3, 0, 2) = False: blnBlock(1, 3, 0, 3) = TrueblnBlock(1, 3, 1, 0) = False: blnBlock(1, 3, 1, 1) = False: blnBlock(1, 3, 1, 2) = False: blnBlock(1, 3, 1, 3) = TrueblnBlock(1, 3, 2, 0) = False: blnBlock(1, 3, 2, 1) = False: blnBlock(1, 3, 2, 2) = True: blnBlock(1, 3, 2, 3) = TrueblnBlock(1, 3, 3, 0) = False: blnBlock(1, 3, 3, 1) = False: blnBlock(1, 3, 3, 2) = False: blnBlock(1, 3, 3, 3) = False'正L型方块数据blnBlock(2, 0, 0, 0) = False: blnBlock(2, 0, 0, 1) = True: blnBlock(2, 0, 0, 2) = True: blnBlock(2, 0, 0, 3) = TrueblnBlock(2, 0, 1, 0) = False: blnBlock(2, 0, 1, 1) = True: blnBlock(2, 0, 1, 2) = False: blnBlock(2, 0, 1, 3) = FalseblnBlock(2, 0, 2, 0) = False: blnBlock(2, 0, 2, 1) = False: blnBlock(2, 0, 2, 2) = False: blnBlock(2, 0, 2, 3) = FalseblnBlock(2, 0, 3, 0) = False: blnBlock(2, 0, 3, 1) = False: blnBlock(2, 0, 3, 2) = False: blnBlock(2, 0, 3, 3) = FalseblnBlock(2, 1, 0, 0) = False: blnBlock(2, 1, 0, 1) = False: blnBlock(2, 1, 0, 2) = True: blnBlock(2, 1, 0, 3) = FalseblnBlock(2, 1, 1, 0) = False: blnBlock(2, 1, 1, 1) = False: blnBlock(2, 1, 1, 2) = True: blnBlock(2, 1, 1, 3) = FalseblnBlock(2, 1, 2, 0) = False: blnBlock(2, 1, 2, 1) = False: blnBlock(2, 1, 2, 2) = True: blnBlock(2, 1, 2, 3) = TrueblnBlock(2, 1, 3, 0) = False: blnBlock(2, 1, 3, 1) = False: blnBlock(2, 1, 3, 2) = False: blnBlock(2, 1, 3, 3) = FalseblnBlock(2, 2, 0, 0) = False: blnBlock(2, 2, 0, 1) = False: blnBlock(2, 2, 0, 2) = False: blnBlock(2, 2, 0, 3) = TrueblnBlock(2, 2, 1, 0) = False: blnBlock(2, 2, 1, 1) = True: blnBlock(2, 2, 1, 2) = True: blnBlock(2, 2, 1, 3) = TrueblnBlock(2, 2, 2, 0) = False: blnBlock(2, 2, 2, 1) = False: blnBlock(2, 2, 2, 2) = False: blnBlock(2, 2, 2, 3) = FalseblnBlock(2, 2, 3, 0) = False: blnBlock(2, 2, 3, 1) = False: blnBlock(2, 2, 3, 2) = False: blnBlock(2, 2, 3, 3) = FalseblnBlock(2, 3, 0, 0) = False: blnBlock(2, 3, 0, 1) = False: blnBlock(2, 3, 0, 2) = True: blnBlock(2, 3, 0, 3) = TrueblnBlock(2, 3, 1, 3) = TrueblnBlock(2, 3, 2, 0) = False: blnBlock(2, 3, 2, 1) = False: blnBlock(2, 3, 2, 2) = False: blnBlock(2, 3, 2, 3) = TrueblnBlock(2, 3, 3, 0) = False: blnBlock(2, 3, 3, 1) = False: blnBlock(2, 3, 3, 2) = False: blnBlock(2, 3, 3, 3) = False'T型方块数据blnBlock(3, 0, 0, 0) = False: blnBlock(3, 0, 0, 1) = True: blnBlock(3, 0, 0, 2) = True: blnBlock(3, 0, 0, 3) = TrueblnBlock(3, 0, 1, 0) = False: blnBlock(3, 0, 1, 1) = False: blnBlock(3, 0, 1, 2) = True: blnBlock(3, 0, 1, 3) = FalseblnBlock(3, 0, 2, 0) = False: blnBlock(3, 0, 2, 1) = False: blnBlock(3, 0, 2, 2) = False: blnBlock(3, 0, 2, 3) = FalseblnBlock(3, 0, 3, 0) = False: blnBlock(3, 0, 3, 1) = False: blnBlock(3, 0, 3, 2) = False: blnBlock(3, 0, 3, 3) = FalseblnBlock(3, 1, 0, 0) = False: blnBlock(3, 1, 0, 1) = False: blnBlock(3, 1, 0, 2) = True: blnBlock(3, 1, 0, 3) = FalseblnBlock(3, 1, 1, 0) = False: blnBlock(3, 1, 1, 1) = False: blnBlock(3, 1, 1, 2) = True: blnBlock(3, 1, 1, 3) = TrueblnBlock(3, 1, 2, 0) = False: blnBlock(3, 1, 2, 1) = False: blnBlock(3, 1, 2, 2) = True: blnBlock(3, 1, 2, 3) = FalseblnBlock(3, 1, 3, 0) = False: blnBlock(3, 1, 3, 1) = False: blnBlock(3, 1, 3, 2) = False: blnBlock(3, 1, 3, 3) = FalseblnBlock(3, 2, 0, 0) = False: blnBlock(3, 2, 0, 1) = False: blnBlock(3, 2, 0, 2) = True: blnBlock(3, 2, 0, 3) = FalseblnBlock(3, 2, 1, 0) = False: blnBlock(3, 2, 1, 1) = True: blnBlock(3, 2, 1, 2) = True: blnBlock(3, 2, 1, 3) = TrueblnBlock(3, 2, 2, 0) = False: blnBlock(3, 2, 2, 1) = False: blnBlock(3, 2, 2, 2) = False: blnBlock(3, 2, 2, 3) = FalseblnBlock(3, 2, 3, 0) = False: blnBlock(3, 2, 3, 1) = False: blnBlock(3, 2, 3, 2) = False: blnBlock(3, 2, 3, 3) = FalseblnBlock(3, 3, 0, 0) = False: blnBlock(3, 3, 0, 1) = False: blnBlock(3, 3, 0, 2) = True: blnBlock(3, 3, 0, 3) = FalseblnBlock(3, 3, 1, 0) = False: blnBlock(3, 3, 1, 1) = True: blnBlock(3, 3, 1, 2) = True: blnBlock(3, 3, 1, 3) = FalseblnBlock(3, 3, 2, 0) = False: blnBlock(3, 3, 2, 1) = False: blnBlock(3, 3, 2, 2) = True: blnBlock(3, 3, 2, 3) = FalseblnBlock(3, 3, 3, 0) = False: blnBlock(3, 3, 3, 1) = False: blnBlock(3, 3, 3, 2) = False: blnBlock(3, 3, 3, 3) = FalseblnBlock(4, 0, 0, 0) = False: blnBlock(4, 0, 0, 1) = True: blnBlock(4, 0, 0, 2) = True: blnBlock(4, 0, 0, 3) = FalseblnBlock(4, 0, 1, 0) = False: blnBlock(4, 0, 1, 1) = True: blnBlock(4, 0, 1, 2) = True: blnBlock(4, 0, 1, 3) = FalseblnBlock(4, 0, 2, 0) = False: blnBlock(4, 0, 2, 1) = False: blnBlock(4, 0, 2, 2) = False: blnBlock(4, 0, 2, 3) = FalseblnBlock(4, 0, 3, 0) = False: blnBlock(4, 0, 3, 1) = False: blnBlock(4, 0, 3, 2) = False: blnBlock(4, 0, 3, 3) = FalseblnBlock(4, 1, 0, 0) = False: blnBlock(4, 1, 0, 1) = True: blnBlock(4, 1, 0, 2) = True: blnBlock(4, 1, 0, 3) = FalseblnBlock(4, 1, 1, 0) = False: blnBlock(4, 1, 1, 1) = True: blnBlock(4, 1, 1, 2) = True: blnBlock(4, 1, 1, 3) = FalseblnBlock(4, 1, 2, 0) = False: blnBlock(4, 1, 2, 1) = False: blnBlock(4, 1, 2, 2) = False: blnBlock(4, 1, 2, 3) = FalseblnBlock(4, 1, 3, 0) = False: blnBlock(4, 1, 3, 1) = False: blnBlock(4, 1, 3, 2) = False: blnBlock(4, 1, 3, 3) = FalseblnBlock(4, 2, 0, 0) = False: blnBlock(4, 2, 0, 1) = True: blnBlock(4, 2, 0, 2) = True: blnBlock(4, 2, 0, 3) = FalseblnBlock(4, 2, 1, 0) = False: blnBlock(4, 2, 1, 1) = True: blnBlock(4, 2, 1, 2) = True: blnBlock(4, 2, 1, 3) = FalseblnBlock(4, 2, 2, 0) = False: blnBlock(4, 2, 2, 1) = False: blnBlock(4, 2, 2, 2) = False: blnBlock(4, 2, 2, 3) = FalseblnBlock(4, 2, 3, 0) = False: blnBlock(4, 2, 3, 1) = False: blnBlock(4, 2, 3, 2) = False: blnBlock(4, 2, 3, 3) = FalseblnBlock(4, 3, 0, 0) = False: blnBlock(4, 3, 0, 1) = True: blnBlock(4, 3, 0, 2) = True: blnBlock(4, 3, 0, 3) = FalseblnBlock(4, 3, 1, 0) = False: blnBlock(4, 3, 1, 1) = True: blnBlock(4, 3, 1, 2) = True: blnBlock(4, 3, 1, 3) = FalseblnBlock(4, 3, 2, 0) = False: blnBlock(4, 3, 2, 1) = False: blnBlock(4, 3, 2, 2) = False: blnBlock(4, 3, 2, 3) = FalseblnBlock(4, 3, 3, 0) = False: blnBlock(4, 3, 3, 1) = False: blnBlock(4, 3, 3, 2) = False: blnBlock(4, 3, 3, 3) = FalseEnd SubPrivate Sub Cmdcancel_Click()Unload MeEnd SubPrivate Sub Form_Load()If frmMain.blnClockWise ThenoptClockWise.V alue = TrueElseoptCounterClockWise.Value = True End IfIf frmMain.blnScheme ThenOption3.Value = TrueElseOption4.Value = TrueEnd IfIf frmMain.blnShowNext ThenchkShowNext.Value = 1ElsechkShowNext.Value = 0End IfText1.Text = frmMain.intDownDistanceEnd SubPrivate Sub CmdOk_Click()frmMain.blnClockWise = optClockWise.V alue frmMain.blnScheme = Option3.ValuefrmMain.blnShowNext = chkShowNext.ValuefrmMain.intDownDistance = Val(Text1)Unload MeEnd SubPrivate Sub Option1_Click()End Sub。

俄罗斯方块 代码

俄罗斯方块 代码
printf("any input of enter will be regarded as an unattached input!\n");
printf("So , when you are making choice ,you don't need to add enter from now on\n");
char up = 'w';
char down = 's'; /*暂停,快下,变形*/
char right = 'd';
char pause = ' ';
char change = 'j';
char fastdown = 'k';
int first = 0;
int setkey = 0 ; /*用户设置开关。 检测用户是否自己设置了游戏属性。1.表示有,0 没有*/
option = getch();
}
switch( option )
{
case '1': Game(1);break;
case '2': Game(2);break;
case '3': SetGame(2);break;
case '4': Aboat();break;
int autocolorkey = 1;
long score;
int nextblock;
int blockX[5],blockY[5]; /*location of the block*/
int nextx[5],nexty[5];

俄罗斯方块游戏代码

俄罗斯方块游戏代码

俄罗斯方块游戏代码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. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
工程概况 2.1 项目名称 俄罗斯方块游戏 2.2 设计平台 VB 全称Visual Basic,它是以Basic语言作为其基本语言的一种可视化编程工具。 Vb是microsoft公司于1991年退出的windows应用程序开发工具visual意思是“可视化的”。在它刚推出来时,自身还存在一些缺陷,功能也相对少一些。但是经过多年的开发研究。最近microsoft公司又推出了VB6.0版本 VB6.0运行环境:硬件,要求486以上的处理器、16MB以上内存,50MB 以上的硬盘,cd-rom驱动器,鼠标。软件:要求windows 95以上版本。 2.3程序设计思想 游戏是用来给大家娱乐的,所以要能在使用的过程中给大家带来快乐,消除大家的疲劳,所以我们在游戏中添加了漂亮的场景和动听的音乐,设置了过关升级的功能,激发大家的娱乐激情。 从游戏的基本玩法出发,主要就是俄罗斯方块的形状和旋转,我们在设计中在一个图片框中构造了一个4*4的网状小块,由这些小块组合成新的形状,每四个小块连接在一起就可以构造出一种造型,因此我们总共设计了7中造型,每种造型又可以通过旋转而变化出2到4种形状,利用随机函数在一个欲览窗体中提前展示形状供用户参考,然后将展示的形状复制到游戏窗体中进行摆放,在游戏窗体中用户就可以使用键盘的方向键来控制方块的运动,然后利用递归语句对每一行进行判断,如果有某行的方块是满的,则消除这行的方块,并且使上面的方块自由下落,其中,方块向下的速度是有时钟控件控制的,在游戏中,用户也可以使用向下键加快下落速度,定义一个变量,对消除的函数进行记录,最后就可以得出用户的分数,用if 语句对分数判断,达到一定的积分就可以升级到下一个档次。 俄罗斯方块游戏设计的主要步骤为以下10个方面: (1)游戏界面的设计。 (2)俄罗斯方块的造型。 (3)俄罗斯方块的旋转。 (4)俄罗斯方块的运动情况(包括向左,向右和向下)。 (5)俄罗斯方块的自动消行功能。 (6)游戏级别的自由选择。 (7)游戏速度的自由选择。 (8)游戏得分的计算。 (9)游戏菜单选项的设计及功能实现。 (10)游戏的背景音乐及特效。 2.4运用的控件和主要对象 我们在设计过程中主要用到的控件有:command控件,image控件,picture控件,label控件,timer控件,text控件,windows media player控件等等。 2.5主要实现的功能 我们开发的俄罗斯方块游戏,主要实现了以下几种功能: 1.可以灵活控制方块在图形框中运动。 2.游戏过程中方块可以自由旋转。 3.当某一行的方块排列满时,将自动将这一行方块消除,然后将上面所有方块向下移动,可以支持连续消行。 4.游戏前可以选择游戏的速度和游戏的等级,游戏速度既为方块下落速度,游戏等级为初始游戏时在基层随机生成一定行数的无规律方块,生成的行数由你来选择,每行至少产生5个以上的无规律方块,这样增加了游戏难度,对于游戏高手来说,无疑不是一个新的挑战。 5.游戏的得分支持积分,并且按照公式: 得分 = 原来分数+ 100 * (2 ^ 同时消除的行数-1) 这样,你同一时间消除的行数越多,你的得分也就越高,当游戏积分到了一定时可以自动升级,这个升级指速度升级。 6.游戏中提供了一个漂亮的场景和动听的音乐,给你带来无限激情。 2.6开发人员 由于这次课程设计所选的题目太复杂,而时间又比较紧张,指导老师建议和同学分工完成。我们小组成员包括组长孙磊周,副组长邹海星,此游戏由我们两个人共同开发而成。 正文 3.1游戏设计的具体实现 在我们两个人共同努力下,此次设计,终于能够圆满完成。由于时间的紧促,在设计中,也许会有一些考虑不周之处,但其功能已经能够满足大多用户的需求,相信假以时日,一定能做出一个更经典,更完美的俄罗斯方块游戏,下面我们将对每一步的具体如何实现展示给大家。 3.1.1游戏界面的设计和背景音乐及特效的实现 俄罗斯方块游戏主要由两个界面构成,登陆界面和开始游戏界面,在登陆界面中我们可以首先看到圣诞节的晚上飘梅花的场景,梅花从窗体顶部做函数曲线的下落运动,在窗体中定义一个Image控件组,在通用中定义梅花X坐标变量动态数组,Y坐标变量动态数组,步距X的变量动态数组,步距Y的变量动态数组,以及振幅变量动态数组。然后在窗体form_load中可以定义梅花的数量,利用随机函数产生随机的梅花坐标,步距和振幅,Image控件在运行时候就调用梅花图片,Image控件就可以由时钟控件控制下落速度,可以自由调节,梅花按snow(i).Left = xp(i) + am(i) * Sin(dx(i))函数在做纵向的正玄函数轨迹运动,竖直方向上为自由下落运动,,有am(i)来控制梅花的左右移动振幅。因此,我们就可以看到一个梅花在空中自由飘舞的画面了。 背景画面是用photoshop软件处理的漂亮图案,原本画面中的动画效果都是由Image控件制作的,还有点击进入游戏的按钮是由Label控件实现的,因为Image控件没有置前置后功能,不能将下雪的场景体现完整性,所以将这些图案全部放在背景上,不影响雪花飘落的效果,当点击画面的时候一样可以进入游戏界面。 游戏的背景音乐是由一段代码调用系统播放器Windows Player播放背景音乐,由于本次设计主要是针对游戏如何设计的,所以在这里就不对播放背景音乐的功能做介绍了。 3.1.2俄罗斯方块的造型 相信朋友们都玩过俄罗斯方块,对这个游戏的玩法和方块形状都比较熟悉。我们这个游戏只选择了最基本的7中造型,包括长条型,正方型,正S型,反S型,正7型,反7型,T型。如果需要我们可以添加更多的造型。将游戏界面的游戏区图片框分割成10*20的小块,每个小块放置一个command控件,预览区图片框按同样比例分割成4*4的小块,同样有command控件构成,我们可以把预览区图片框看作是从游戏区图片框中选取的一个部分,游戏区的小方块编号和欲览区编号如下图: 0 1 2 3 4 5 6 7 8 9 … … … … … … … … … … … … … … … … … … … … 90 91 92 93 94 95 96 97 98 99 3 4 5 6 13 14 15 16 23 24 25 26 33 34 35 36 游戏区编号 欲览区编号 利用Select将方块的7中造型列出,比如长条型的设计,在欲览区中分别有3.4.5.6和5.15.25.35四个方块构成两中形态,用数组为: m(0) = 3: m(1) = 4: m(2) = 5: m(3) = 6: situation2 = 0 m(0) = 5: m(1) = 15: m(2) = 25: m(3) = 35: situation2 = 1 将它的形状编号为0和1,在后面方便调用,其他的方块造型同样的方法。 3.1.3俄罗斯方块的旋转 俄罗斯方块的旋转主要将方块的位置加以变换得到的,例如上述范例,长条型有两中样式,根据小方块的编号变动来实现整个造型的旋转,比如: If n(0) - 18 >= 2 And n(3) + 9 <= 198 Then If cmdfang(n(0) - 18).Visible = False And _ cmdfang(n(1) - 9).Visible = False And _ cmdfang(n(3) + 9).Visible = False Then hidefang 0 n(0) = n(0) - 18 n(1) = n(1) - 9 n(3) = n(3) + 9 showfang 0 situation = 1 End If End If 方块的造型在旋转的时候存在一个公式,当然首先要判断是否满足旋转的要求,以上是一个长条型由横着变成竖立状态的旋转,我们以它的造型中的第三个小方块n(3)为中心旋转,这样,在开始运动的时候,长条形要发生旋转最少要运动到第三行,才能由横着变成竖立状态,游戏区图形框中第三行的第一个方块的编号为20,所以长条造型的第一个小方块的编号n(0)必须要大于20。同样,长条型方块在下落到底部的时候也有限制。如果长条下落到最后一行也将无法由横着变成竖立状态。 3.1.4如何实现方块的运动和自动消除满行的方块 我们的这个俄罗斯方块游戏主要是利用command控件的visible属性完成效果的,其实在游戏区图形框可以看成是由许多的command小方块组成,方块运动的过程就是造型里方块显示或者隐藏,就像现在的霓虹灯效果一样,由时钟控件控制visible属性改变的速度,上一层的消失,下一层的显示,这样,从视觉效果可以看到方块的下落运动效果。 方块在下落的过程中会自动判断每一行方块的visible属性,如果全部为true时,就会将这一行小方块的visible属性全部变成false,在将上面的小方块向下移动,利用for语句进行循环判断,将所有这样情况的行改变小方块visible属性。当有多行同时出现这样情况时使用递归调用,实现连续消行。具体程序代码如下: For i = 190 To 10 Step -10 If cmdfang(i).Visible = True And _ cmdfang(i + 1).Visible = True And _ cmdfang(i + 2).Visible = True And _ cmdfang(i + 3).Visible = True And _ cmdfang(i + 4).Visible = True And _ cmdfang(i + 5).Visible = True And _ cmdfang(i + 6).Visible = True And _ cmdfang(i + 7).Visible = True And _ cmdfang(i + 8).Visible = True And _ cmdfang(i + 9).Visible = True Then For j = i + 4 To i Step -1 t = 1 cmdfang(j).Visible = False cmdfang(2 * i + 9 - j).Visible = False For k = 1 To 4000 DoEvents Next t = 0 Next linenum = linenum + 1 For j = i - 1
相关文档
最新文档