俄罗斯方块源代码

合集下载

俄罗斯方块源代码

俄罗斯方块源代码

001第一个Cpp002#include <conio.h>003#include <stdlib.h>004#include<stdio.h>005#include <windows.h>006#include <mmsystem.h>007#pragma comment(lib,"winmm.lib") //播放背景音乐的头文件008#include "colorConsole.h"009#include<time.h>010#define SQUARE_COLOR BACKGROUD_BLUE|BACKGROUD_RED| BACKGROUD_INTENSITY //背景颜色011#define SQUARE_COLOR FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY //方块的颜色012#define up 72013#define down 80014#define left 75015#define right 77016#define esc 27017#define MAPW 15 //地图的宽度018#define MAPH 25 //地图的高度019020void initiate1();021int* build(); //创建方块 //初始化工作022BOOL isavailable(int a[],int x,int y,int w,int h); //判定是否能放下023void drawblocks(int a[],int w,int h,int x,int y,WORD wColors[],int nColors); 024void delete_cache(); //清除键盘缓冲区025void revolve(int a[][4],int w,int h,int*x,int y); //转动方块026void pro();027void end();028void delete_blocks(int*a,int w,int h,int x,int y);029void gameover();030void deletefull_line(int m[][MAPW],int row,int w,int h); //消除一行031032int dx=30,dy=5; //屏幕上的偏移量033int score=0,level=0;034int map[MAPH][MAPW];035int a1[4][4]={{1},{1,1,1}};036int a2[4][4]={{0,1},{1,1,1}};037int a3[4][4]={{1,1},{0,1,1}};038int a4[4][4]={{0,0,1},{1,1,1}};039int a5[4][4]={{0,1,1},{1,1}};040int a6[4][4]={{1,1,1,1}};041int a7[4][4]={{1,1},{1,1}};042int a[4][4];043044int main()045{046 HANDLE handle;047 handle=initiate();048 WORD wColors[1]={FOREGROUND_BLUE| FOREGROUND_GREEN|FOREGROUND_INTENSITY }; 049 while(1)050 {051 sndPlaySound("Resource\\Just Dance.wav",SND_LOOP|SND_ASYNC);//用异步方式播放音乐,PlaySound函数在开始播放后立即返回052 system("CLS");053 int n=0;054 printf("目录\n1.开始游戏\n2.退出游戏\n\n\n");055 scanf("%d",&n);056 switch(n)057 {058 case1:059 system("CLS");060 textout(handle,22,6,wColors+2,1,"请选择游戏等级:");061 textout(handle,32,8,wColors+2,1,"1.初级");062 textout(handle,32,10,wColors+2,1,"2.中级");063 textout(handle,32,12,wColors+2,1,"3.高级");064 while(1)065 {066 char choice;067 choice=_getch();068 if(choice=='1')069 {070 textout(handle,22,6,wColors+2,1,"开始游戏,初级");071 textout(handle,32,8,wColors+2,1," "); 072 textout(handle,32,10,wColors+2,1," "); 073 textout(handle,32,12,wColors+2,1," "); 074 level=0,score=0;075 Sleep(2000);076 textout(handle,22,6,wColors+2,1," "); 077 break;078 }079 else if(choice=='2')080 {081 textout(handle,22,6,wColors+2,1,"开始游戏,中级"); 082 textout(handle,32,8,wColors+2,1," "); 083 textout(handle,32,10,wColors+2,1," "); 084 textout(handle,32,12,wColors+2,1," "); 085 level=2,score=20;086 Sleep(2000);087 textout(handle,22,6,wColors+2,1," "); 088 break;089 }090 else if(choice=='3')091 {092 textout(handle,22,6,wColors+2,1,"开始游戏,高级"); 093 textout(handle,32,8,wColors+2,1," "); 094 textout(handle,32,10,wColors+2,1," "); 095 textout(handle,32,12,wColors+2,1," "); 096 level=4,score=40;097 Sleep(2000);098 textout(handle,22,6,wColors+2,1," "); 099 break;100 }101 else if(choice!='1'&&choice!='2'&&choice!='3')102 continue;103 }104 pro();105 break;106 case2:107 return0;108 default:109 printf("错误,按键继续");110 while(!_kbhit());111 }112 }}113114115116void pro() //游戏主题117{118 initiate1();119 int*b=NULL;120 b=build(); //创建方块121 int sign,blank,x,y;122 while(1)123 {124 for(int i=0;i<4;i++) //复制方块125 for(int j=0;j<4;j++)126 if(a[i][j]=*(b+i*4+j)) blank=i;127 y=1-blank;x=4;128 delete_blocks(&a[0][0],4,4,16,10);129130 b=build();131 HANDLE handle;132 handle=initiate();133 WORD wColors[1]={FOREGROUND_BLUE| FOREGROUND_GREEN|FOREGROUND_INTENSITY }; 134 drawblocks(b,4,4,16,10,wColors,1);135136 wColors[0]=SQUARE_COLOR;137 drawblocks(&a[0][0],4,4,x,y,wColors,1);138139 delete_cache();140141 char string[5];142 wColors[0]=FOREGROUND_RED| FOREGROUND_GREEN|FOREGROUND_INTENSITY; 143 textout(handle,dx-10,8+dy,wColors,1,itoa(score,string,10));144 textout(handle,dx-10,14+dy,wColors,1,itoa(level,string,10));145146 sign=1;147 while(sign)148 {149 int delay=0,max_delay=100-10*level; //延迟量150 while(delay<max_delay)151 {152 if(_kbhit()) //用if避免按住键使方块卡住153 {154 int draw=0;155 int key=_getch();156 switch(key)157 {158 case up:159 delete_blocks(&a[0][0],4,4,x,y);160 revolve(a,4,4,&x,y);161 draw=1;162 break;163 case down:164 delay=max_delay;165 break;166 case left:167 if(isavailable(&a[0][0],x-1,y,4,4))168 {169 delete_blocks(&a[0][0],4,4,x,y);170 x--;171 draw=1;172 }173 break ;174 case right:175 if(isavailable(&a[0][0],x+1,y,4,4)) 176 {177 delete_blocks(&a[0][0],4,4,x,y);178 x++;179 draw=1;180 }181 break;182 case32://32 是空格键的ASCII码,按空格键暂停183 while(1)184 {185 textout(handle,dx,-2+dy,wColors,1,"Press any key to continue"); 186 Sleep(200);18 7 textout(handle,dx,-2+dy,wColors,1," ");188 Sleep(200);189 if(_kbhit())190 {191 draw=1;192 break;193 }194 }195 break;196 case esc://按键退出游戏197 exit(EXIT_SUCCESS);198 }199 if(draw)200 {201 HANDLE handle;202 handle=initiate();203 WORD wColors[1]={SQUARE_COLOR};204 drawblocks(&a[0][0],4,4,x,y,wColors,1); 205 draw=0;206 }207 }208 _sleep(5);delay++;209 }210 if(isavailable(&a[0][0],x,y+1,4,4)) //是否能下移211 {212 delete_blocks(&a[0][0],4,4,x,y);213 y++;214 HANDLE handle;215 handle=initiate();216 WORD wColors[1]={SQUARE_COLOR};217 drawblocks(&a[0][0],4,4,x,y,wColors,1);218 }219 else220 {221 sign=0; //标记,使跳出 while(sign) 循环,产生新方块222 if(y<=1)223 {224 system("CLS");225 HANDLE handle;226 handle=initiate();227 WORD wColors[1]={FOREGROUND_RED| FOREGROUND_GREEN};228 textout(handle,4+dx,6+dy,wColors,1,"GAME OVER!!!");229 textout(handle,4+dx,8+dy,wColors,1,"分数:");230 textout(handle,10+dx,8+dy,wColors,1,itoa(score,string,10)); 231 textout(handle,4+dx,10+dy,wColors,1,"制作者:***");232 delete_cache();233 exit(EXIT_SUCCESS);234 } //是否结束235 for(int i=0;i<4;i++) //放下方块236 for(int j=0;j<4;j++)237 if(a[i][j]&&((i+y)<MAPH-1)&&((j+x)<MAPW-1))238 map[i+y][j+x]=a[i][j];239 int full,k=0;240 for( i=y;i<min(y+4,MAPH-1);i++)241 {242 full=1;243 for(int j=1;j<14;j++)244 if(!map[i][j]) full=0;245 if(full) //消掉一行246 {247 deletefull_line(map,i,MAPW,MAPH);248 k++;249 score=score+k;250 level=min(score/10,9);251 }252 }253 }254 }255256 }257}258void initiate1() //初始化259{260 int i;261 for(i=0;i<25;i++)262 {263 map[i][0]=-2;264 map[i][14]=-2;265 }266 for(i=0;i<15;i++)267 {268 map[0][i]=-1;269 map[24][i]=-1;270 }271 map[0][0]=-3;272 map[0][14]=-3;273 map[24][0]=-3;274 map[24][14]=-3;275276 HANDLE handle;277 handle=initiate();278 WORD wColors[1]={FOREGROUND_GREEN| FOREGROUND_BLUE|FOREGROUND_INTENSITY}; 279 textout(handle,dx-10,6+dy,wColors,1,"SCORE");280 textout(handle,dx-10,12+dy,wColors,1,"LEVEL");281 textout(handle,32+dx,8+dy,wColors,1,"NEXT");282 wColors[0]=FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_INTENSITY;283 drawblocks(&map[0][0],15,25,0,0,wColors,1);284textout(handle,dx,dy,wColors,1,"◎═════════════◎"); 285 wColors[0]=FOREGROUND_BLUE| FOREGROUND_GREEN|FOREGROUND_INTENSITY; 286 textout(handle,dx+8,dy+5,wColors,1,"按任意键开始");287 wColors[0]=FOREGROUND_BLUE|FOREGROUND_RED|FOREGROUND_INTENSITY ; 288 textout(handle,dx+7,dy-3,wColors,1,"制作者:***");289290 int x=_getch();291 srand(time(NULL));292 textout(handle,dx+8,dy+5,wColors,1," ");}293294295int* build() //创建方块296{297 int* a=NULL;298 int c=rand()%7;299 switch(c)300 {301 case0:302 a=&a1[0][0];break;303 case1:304 a=&a2[0][0];break;305 case2:306 a=&a3[0][0];break;307 case3:308 a=&a4[0][0];break;309 case4:310 a=&a5[0][0];break;311 case5:312 a=&a6[0][0];break;313 case6:314 a=&a7[0][0];break;315 }316 return a;317}318319void drawblocks(int a[],int w,int h,int x,int y,WORD wColors[],int nColors) //画出方块320{321 HANDLE handle;322 handle = initiate();323 int temp;324325 for(int i=0;i<h;i++)326 for(int j=0;j<w;j++)327 if((temp=a[i*w+j])&&y+i>0)328 {329 if(temp==-3)330 {331textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"◎");332 _sleep(30);333 }334 else if(temp==-2)335 {336textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"║");337 _sleep(30);338 }339340 else if(temp==1)341 textout(handle,2*(x+j)+dx,y+i+dy,wCol ors,nColors,"◎");342 else if(temp==-1)343 {344textout(handle,2*(x+j)+dx,y+i+dy,wColors,nColors,"═");345 _sleep(30);346 }347 }348}349350void delete_cache() //清除缓冲区351{352 while(_kbhit())353 {354 _getch();355 }356}357358void delete_blocks(int*a,int w,int h,int x,int y) //覆盖方块359{360 HANDLE handle;361 handle=initiate();362 WORD wColors[1]={SQUARE_COLOR};363 for(int i=0;i<h;i++)364 for(int j=0;j<w;j++)365 if(a[i*w+j]&&i+y>0)366 textout(handle,2*(x+j)+dx,y+i+dy,wColors,1," ");}367368369370void revolve(int a[][4],int w,int h,int*x,int y) //转动方块371{372 int b[4][4]={{0,0,0,0},{0,0,0,0},{0,0,0,0},{0,0,0,0}};373 int sign=0,line=0;374 for(int i=h-1;i>=0;i--)375 {376 for(int j=0;j<w;j++)377 if(a[i][j])378 {379 b[j][line]=a[i][j];380 sign=1;381 }382 if(sign)383 {384 line++;385 sign=0;386 }387 }388 for(i=0;i<4;i++)389 if(isavailable(&b[0][0],*x-i,y,w,h))390 {391 *x-=i;392 for(int k=0;k<h;k++)393 for(int j=0;j<w;j++)394 a[k][j]=b[k][j];395 break;396 }}397398399void deletefull_line(int m[][MAPW],int row,int w,int h) //消除满行的方块400{401 HANDLE handle;402 handle=initiate();403 WORD wColors[1]={SQUARE_COLOR};404 textout(handle,2+dx,row+dy,wColors,1,"﹌﹌﹌﹌﹌﹌﹌﹌﹌﹌");405 _sleep(100);406407 int i;408 for(i=row;i>1;i--)409 {410 delete_blocks(&m[i][1],MAPW-2,1,1,i);411 for(int j=1;j<MAPW-1;j++)412 m[i][j]=m[i-1][j];413 drawblocks(&m[i][1],MAPW-2,1,1,i,wColors,1);414 }415 for(i=1;i<MAPW-1;i++)416 m[1][i]=0;}417418419BOOL isavailable(int a[],int x,int y,int w,int h)420{421 for(int i=max(y,1);i<y+h;i++)422 for(int j=x;j<x+w;j++)423 if(map[i][j]&&a[w*(i-y)+j-x])424 return0;425 return1;426}427428第二个cpp:429#include "colorConsole.h"430431432HANDLE initiate()433{434 HANDLE hOutput;435 hOutput = GetStdHandle(STD_OUTPUT_HANDLE);436 return hOutput;437}438BOOL textout(HANDLE hOutput,int x,int y,WORD wColors[],int nColors,LPTSTR lpszString) 439{440 DWORD cWritten;441 BOOL fSuccess;442 COORD coord;443444 coord.X = x; // start at first cell445 coord.Y = y; // of first row446 fSuccess = WriteConsoleOutputCharacter(447 hOutput, // screen buffer handle448 lpszString, // pointer to source string449 lstrlen(lpszString), // length of string450 coord, // first cell to write to451 &cWritten); // actual number written452 if(! fSuccess)453 cout<<"error:WriteConsoleOutputCharacter"<<endl;454455456 for(;fSuccess && coord.X < lstrlen(lpszString)+x; coord.X += nColors)457 {458 fSuccess = WriteConsoleOutputAttribute(459 hOutput, // screen buffer handle460 wColors, // pointer to source string 461 nColors, // length of string 462 coord, // first cell to write to 463 &cWritten); // actual number written 464 }465 if(! fSuccess)466 cout<<"error:WriteConsoleOutputAttribute"<<endl; 467468 return0;469}。

俄罗斯方块源代码

俄罗斯方块源代码

package Game;import java.awt.BorderLayout;import java.awt.Color;import ponent;import java.awt.Graphics;import java.awt.Insets;import youtManager;import java.awt.event.ActionEvent;import java.awt.event.ActionListener;import java.awt.event.KeyEvent;import java.awt.event.KeyListener;import java.awt.event.MouseEvent;import java.awt.event.MouseListener;import java.util.Random;import javax.swing.JFrame;import javax.swing.JLabel;import javax.swing.JMenu;import javax.swing.JMenuBar;import javax.swing.JMenuItem;import javax.swing.JPanel;import javax.swing.JTextField;import javax.swing.Timer;import javax.swing.border.Border;public class QuareGame extends JFrame implements ActionListener { private GamePanel gamePanel ;//菜单工具组件JMenuBar menuBar = new JMenuBar();//menuBar.setSize(20, 20);JMenu menuFile = new JMenu("游戏");JMenuItem newGame = new JMenuItem("新游戏");JMenuItem pauseGame = new JMenuItem("暂停");JMenuItem overGame = new JMenuItem("结束");JMenu menuHelp=new JMenu("帮助");//JLabel labLevel=new JLabel("选择关卡:");JTextField txtLevel=new JTextField();public QuareGame(GamePanel gp) {setBounds(500, 100, 400, 480);setTitle("my small game");setLayout(new BorderLayout());JFrame.setDefaultLookAndFeelDecorated(true);//添加菜单条setJMenuBar(createMenuBar());this.gamePanel = gp;if(gamePanel!=null){add(gamePanel);addKeyListener(gamePanel);}labLevel.setBounds(260, 140, 50, 30);txtLevel.setBounds(260, 180, 50, 30);// add(labLevel);// add(txtLevel);setVisible(true);// setResizable(false);}// 菜单条public JMenuBar createMenuBar() {menuFile.add(newGame);menuFile.add(pauseGame);menuFile.add(overGame);menuBar.add(menuFile);menuBar.add(menuHelp);menuHelp.add(new JMenuItem("版本号"));//添加事件newGame.addActionListener(this);pauseGame.addActionListener(this);overGame.addActionListener(this);return menuBar;}public static void main(String[] args) {JFrame.setDefaultLookAndFeelDecorated(true);QuareGame game = new QuareGame(new GamePanel(new int[22][12] ,new int[2][2]));}@Overridepublic void actionPerformed(ActionEvent e) {//System.out.println(e.getActionCommand());if(e.getActionCommand(). equals("新游戏")){System.out.println("newgame");if(gamePanel!=null){remove(gamePanel);removeKeyListener(gamePanel);}this.gamePanel = new GamePanel(new int[22][12] ,new int[2][2]);add(gamePanel);addKeyListener(gamePanel);}else if(e.getActionCommand().equals("暂停")){pauseGame.setText("继续");gamePanel.timer.stop();}else if(e.getActionCommand().equals("继续")){pauseGame.setText("暂停");gamePanel.timer.start();}else if(e.getActionCommand().equals("结束")){if(gamePanel!=null)this.remove(gamePanel);gamePanel=null;}}}class GamePanel extends JPanel implements KeyListener {/****/private static final long serialVersionUID = 1L;Random random=new Random();JLabel labLevel=new JLabel("选择关卡:");JTextField txtLevel=new JTextField();int size = 20;// 显示大小// 座标int x = 4, y;int i = 0, j = 0;Timer timer=null;int level=1;int score =0;int steep=1000;//方块下降的速度TimerAction timerAction;//绘图颜色Color mapColor;Color moveShapColor;int colors[][]={{255, 222, 173},{47 ,79, 79},{255, 228 ,225},{0 ,255 ,0},{0, 0 ,255},{255, 193, 37},{156 ,156 ,156 },{202 ,225, 255},{171, 130, 255},{224 ,102 ,255},{255 ,62 ,150},{255, 0 ,0}};// squareType类型和squareState状态int squareType, squareState;int nextState=0;//每次产生一个新的会自加1并取2的余数赋给自己int map[][];// = new int;int nextTypeAndState [][];// 方块的几种形状态和状态(每个方块由一个4*4的矩阵构成)// I O T Z S L Jint shape[][][];//构造函数public GamePanel(int map[][],int nextTypeAndState[][]) {this.nextTypeAndState=nextTypeAndState;this.map=map;this.shape=this.initShap();setBackground(new Color(250, 250, 250));initMap();initWall();createdSquare();timerAction=new TimerAction();timer = new Timer(steep, timerAction);timer.start();score = 0;initTypeAndState();this.mapColor=createColor();this.moveShapColor=createColor();// setLayout();//// labLevel.setBounds(260, 140, 80, 30);// txtLevel.setBounds(50, 80, 50, 80);// txtLevel.setText("111");// txtLevel.setSize(10, 10);// add(labLevel,BorderLayout.EAST);// add(txtLevel,BorderLayout.EAST);setSize(400, 480);}public int[][][] initShap(){return new int[][][]{{ { 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 },{ 0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0 } },// s{ { 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },{ 0, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 0, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 } }, // z{ { 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 } }, // j{ { 0, 1, 0, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },{ 1, 0, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // o{ { 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // l{ { 1, 0, 0, 0, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0 },{ 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 1, 1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },{ 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 } }, // t{ { 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 1, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0 },{ 1, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 },{ 0, 1, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0 } } };}// 初始化地图public void initMap() {for (i = 0; i < map.length; i++) {for (j = 0; j < map[0].length; j++) {map[i][j] = 0;}}}// 初始化围墙public void initWall() {for (i = 0; i < map.length; i++) {map[i][0] = 2; // 两边为2 (1.表示普通2 表示围墙)map[i][11] = 2;}// 底部for (j = 0; j < 12; j++) {map[map.length - 1][j] = 2;}}// 产生新方块方法public void createdSquare() {x = 4;y = 0;nextState=(nextState+1)%2;getTypeAndState(nextState);}//获取当前方块数据,并计算下一个方块数据public void getTypeAndState(int index){squareType= nextTypeAndState[0][index];nextTypeAndState[0][index]=(int) (Math.random() * 100) % 7;squareState=nextTypeAndState[1][index];nextTypeAndState[1][index]=(int) (Math.random() * 100) % 4;}//初始化当前方块和下一个方块public void initTypeAndState(){for (int i = 0; i < nextTypeAndState[0].length; i++) {nextTypeAndState[0][i]=(int) (Math.random() * 100) % 7;}for (int i = 0; i < nextTypeAndState[1].length; i++) {nextTypeAndState[1][i]=(int) (Math.random() * 100) % 4;}}//随机产生颜色方法public Color createColor(){int temp[]=colors[random.nextInt(colors.length)];//此处不用减1return new Color(temp[0],temp[1],temp[2]);}// 是否超出边界public int isOverstep(int x, int y, int squareType, int squareState) {for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {if (shape[squareType][squareState][i * 4 + j] == 1) {if (map[y + i][j + x] > 0) {return 0;}}}}// 0 1 0 0 0 1 0 0// 1 1 1 0 0 1 0 0// 0 0 0 0 0 1 0 0// 0 0 0 0 0 1 0 0return 1;}// 四个移动方法public void leftMove() {// 合法没有超出边界if (isOverstep(x - 1, y, squareType, squareState) == 1) {x -= 1;}// System.out.println(x);repaint();}public void rightMove() {if (isOverstep(x + 1, y, squareType, squareState) == 1) {x += 1;}repaint();}public void dowmMove() {if (isOverstep(x, y + 1, squareType, squareState) == 1) {y += 1;}// destroyLine();// 销行得分repaint();}public void trunMove() {if (isOverstep(x, y, squareType, (squareState + 1) % 4) == 1) { squareState = (squareState + 1) % 4;}repaint();}// 按键临听@Overridepublic void keyPressed(KeyEvent e) {// System.out.println(e.getKeyCode());switch (e.getKeyCode()) {case 65:case 37:leftMove();break;case 68:case 39:rightMove();break;case 83:case 40:dowmMove();break;case 87:case 38:trunMove();break;}}@Overridepublic void keyReleased(KeyEvent e) {}@Overridepublic void keyTyped(KeyEvent e) {}// 添加到map中public void addSqu(int x, int y, int squareType, int squareState) { for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {if (shape[squareType][squareState][i * 4 + j] == 1) {map[i + y][x + j] = 1;}}}// 重绘调用的方法@Overridepublic void paintComponent(Graphics g) {super.paintComponent(g);//正在下落的方块for (j = 0; j < 16; j++) {if (shape[squareType][squareState][j] == 1) {g.setColor(new Color(40, 40, 80));g.drawRect((j % 4 + x) * size, (j / 4 + y) * size, size, size);g.setColor(moveShapColor);g.fillRect((j % 4 + x) * size+2, (j / 4 + y) * size+2, size-4, size-4);// System.out.println("移动中的方块");}}// 已经放在map中的方块2固定的围墙1是随机产生后下落的for (i = 0; i < map.length; i++) {for (j = 0; j < map[0].length; j++) {if (map[i][j] == 1) {g.setColor(new Color(40,100,220));g.drawRect(j * size, i * size, size, size);g.setColor(mapColor);g.fillRect(j * size + 2, i * size + 2, size - 4, size - 4);} else if (map[i][j] == 2) {g.setColor(createColor());g.fillRect(j * size, i * size, size, size);}}}g.drawString("分数:" + score, 260, 100);g.drawString("下一个方块:" , 260, 120);g.drawString("当前等级:"+level, 260 , 140);//显示下一个图象int type=nextTypeAndState[0][(nextState+1)%2];int state=nextTypeAndState[1][(nextState+1)%2];for (int i = 0; i < 4; i++) {for (int j = 0; j < 4; j++) {if(shape[type][state][i*4+j]==1){g.setColor(mapColor);g.drawRect(j*20+260, i*20+170, size, size);}}}// 销行得分方法public void destroyLine() {int destroyCount = 0;for (int i = map.length - 2; i > 0; i--) {int count = 0;// for循环除掉两边的围墙for (int j = 1; j < map[0].length - 1; j++) {count += map[i][j];}if (count == map[0].length - 2) {destroyCount += 1;for (int x = i; x > 0; x--) {for (int j = 1; j < map[0].length - 1; j++) {map[x][j] = map[x - 1][j];}}i = i + 1;}}//是否结束游戏if(isOver()){this.size = 20;// 显示大小// 座标this.x = 4;this.score=0;this.steep=1000;//方块下降的速度// this.map[][] = new int[22][12];this.nextState=0;//每次产生一个新的会自加1并取2的余数赋给自己this.nextTypeAndState=new int[2][2];this.map=new int[22][12];this.shape=initShap();setBackground(new Color(250, 250, 250));initMap();initWall();createdSquare();timer.removeActionListener(timerAction);this.timerAction=new TimerAction();timer=new Timer(steep, timerAction);timer.start();score = 0;level=0;initTypeAndState();setSize(400, 480);return;}countScore(destroyCount);//计算分数}//统计得分计算下一关public void countScore(int destroyCount){switch (destroyCount) {case 0:return;case 1:score += 1;break;case 2:score += 3;break;case 3:score += 5;break;case 4:score += 10;break;}if(score>=level*20){System.out.println("下一关");level+=1;mapColor=createColor();//设置一下关的颜色moveShapColor=createColor();JLabel labNextLevel=new JLabel("wellcome to "+score/100+"level good lock");labNextLevel.setBounds(50, 100, 200, 30);this.add(labNextLevel);// timer.stop();// labNextLevel=null;this.remove(labNextLevel);steep=steep*80/100;timer.setDelay(steep);// timer.start();}}// //根据分数判断是否进入下一关// public void nextLevel(int score){// if()// }//判断游戏结束public boolean isOver(){//map的第一行是否为1for(int i=1;i<map[0].length-1;i++){if(map[0][i]==1)return true;}return false;}// timer 刷新调用的动作侦听器class TimerAction implements ActionListener {public void actionPerformed(ActionEvent e) {if (isOverstep(x, y + 1, squareType, squareState) == 1) {y = y + 1;repaint();}else if (isOverstep(x, y + 1, squareType, squareState) == 0) {y=y+1;repaint();try {Thread.sleep(steep*50/100);} catch (Exception e2) {e2.printStackTrace();}addSqu(x, y-1, squareType, squareState);createdSquare();repaint();destroyLine();// 销行得分}}}}public class app1_1 {}。

俄罗斯方块c语言源代码

俄罗斯方块c语言源代码

俄罗斯方块c语言源代码俄罗斯方块游戏是一款非常受欢迎的游戏,使用C语言编写源代码实现其功能。

下面是俄罗斯方块游戏的C语言源代码:1. 创建窗口函数: // 创建窗口函数 void CreateWindow(int width, int height) { // 使用SDL库创建窗口 SDL_Init(SDL_INIT_EVERYTHING); SDL_Window *window = SDL_CreateWindow("Tetris",SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED,width, height, 0); // 设置刷新时间SDL_SetHint(SDL_HINT_RENDER_VSYNC, "1"); }2. 创建游戏函数: // 创建游戏函数 void CreateGame() { // 设置随机数种子srand((unsigned int)time(NULL)); // 加载游戏资源 LoadResources(); // 初始化游戏数据InitGameData(); // 初始化游戏界面InitGameUI(); // 开始游戏循环 GameLoop(); // 清理游戏资源 CleanupGame(); }3. 绘图函数: // 绘图函数 void Draw(int x, inty, Color color) { // 使用SDL库在指定位置绘制指定颜色的矩形 SDL_Rect rect; rect.x = x;rect.y = y; rect.w = BLOCK_SIZE; rect.h = BLOCK_SIZE; SDL_SetRenderDrawColor(renderer, color.r, color.g, color.b, color.a);SDL_RenderFillRect(renderer, &rect); }。

俄罗斯方块完整源代码

俄罗斯方块完整源代码

//不多说,直接可以拷贝下面的东西,就可以运行。

package day04;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class ERSBlock extends JPanel implements ActionListener,KeyListener//应该是继承JPanel{static Button but[] = new Button[6];static Button noStop = new Button("取消暂停"); static Label scoreLab = new Label("分数:");static Label infoLab = new Label("提示:");static Label speedLab = new Label("级数:");static Label scoreTex = new Label("0");static Label infoTex = new Label(" ");static Label speedTex = new Label("1");static JFrame jf = new JFrame();static MyTimer timer;static ImageIcon icon=new ImageIcon("resource/Block.jpg");static JMenuBar mb = new JMenuBar();static JMenu menu0 = new JMenu("游戏 ");static JMenu menu1 = new JMenu("帮助 ");static JMenuItem mi0 = new JMenuItem("新游戏"); static JMenuItem mi1 = new JMenuItem("退出");static JMenuItem mi1_0 = new JMenuItem("关于"); static JDialog dlg_1;static JTextArea dlg_1_text = new JTextArea(); static int startSign= 0;//游戏开始标志 0 未开始 1 开始 2 暂停static String butLab[] = {"开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"};static int game_body[][] = new int[19][10];static int game_sign_x[] = new int[4];//用于记录4个方格的水平位置static int game_sign_y[] = new int[4];//用于记录4个方格的垂直位置static boolean downSign = false;//是否落下static int blockNumber = 1;//砖块的编号static int gameScore = 0;//游戏分数static int speedMark = 1;public static void main(String args[]) {ERSBlock myBlock = new ERSBlock();mb.add(menu0);mb.add(menu1);menu0.add(mi0);menu0.add(mi1);menu1.add(mi1_0);jf.setJMenuBar(mb);myBlock.init();jf.add(myBlock);jf.setSize(565,501);jf.setResizable(false);jf.setTitle("俄罗斯方块");jf.setIconImage(icon.getImage());jf.setLocation(200,100);jf.show();timer = new MyTimer(myBlock); //启动线程timer.setDaemon(true);timer.start();timer.suspend();}public void init(){setLayout(null);for(int i = 0;i < 6;i++){but[i] = new Button(butLab[i]);add(but[i]);but[i].addActionListener(this);but[i].addKeyListener(this);but[i].setBounds(360,(240 + 30 * i),160,25); }add(scoreLab);add(scoreTex);add(speedLab);add(speedTex);add(infoLab);add(infoTex);add(scoreLab);scoreLab.setBounds(320,15,30,20); scoreTex.setBounds(360,15,160,20); scoreTex.setBackground(Color.white); speedLab.setBounds(320,45,30,20); speedTex.setBounds(360,45,160,20); speedTex.setBackground(Color.white);but[1].setEnabled(false);but[4].setEnabled(false);infoLab.setBounds(320,75,30,20); infoTex.setBounds(360,75,160,20); infoTex.setBackground(Color.white); noStop.setBounds(360,360,160,25); noStop.addActionListener(this); noStop.addKeyListener(this);mi0.addActionListener(this);mi1.addActionListener(this);mi1_0.addActionListener(this);num_csh_game();rand_block();}public void actionPerformed(ActionEvent e){if(e.getSource() == but[0])//开始游戏{startSign = 1;infoTex.setText("游戏已经开始!");but[0].setEnabled(false);but[1].setEnabled(true);but[4].setEnabled(true);timer.resume();}if(e.getSource() == but[1]||e.getSource() == mi0)//重新开始游戏{startSign = 0;gameScore = 0;timer.suspend();num_csh_restart();repaint();rand_block();scoreTex.setText("0");infoTex.setText("新游戏!");but[0].setEnabled(true);but[1].setEnabled(false);but[4].setEnabled(false);}if(e.getSource() == but[2])//降低级数 {infoTex.setText("降低级数!"); speedMark--;if(speedMark <= 1){speedMark = 1;infoTex.setText("已经是最低级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[3])//提高级数 {infoTex.setText("提高级数!");speedMark++;if(speedMark >= 9){speedMark = 9;infoTex.setText("已经是最高级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[4])//游戏暂停 {this.add(noStop);this.remove(but[4]);infoTex.setText("游戏暂停!"); timer.suspend();}if(e.getSource() == noStop)//取消暂停 {this.remove(noStop);this.add(but[4]);infoTex.setText("继续游戏!"); timer.resume();}if(e.getSource() == but[5]||e.getSource() == mi1)//退出游戏{jf.dispose();}if(e.getSource() == mi1_0)//退出游戏{dlg_1 = new JDialog(jf,"关于");try{FileInputStream io = new FileInputStream("resource/guanyu.txt");//得到路径byte a[] = new byte[io.available()];io.read(a);io.close();String str = new String(a);dlg_1_text.setText(str);}catch(Exception g){}dlg_1_text.setEditable(false);dlg_1.add(dlg_1_text);dlg_1.pack();dlg_1.setResizable(false);dlg_1.setSize(200, 120);dlg_1.setLocation(400, 240);dlg_1.show();}}public void rand_block()//随机产生砖块{int num;num = (int)(Math.random() * 6) + 1;//产生0~6之间的随机数blockNumber = num;switch(blockNumber){case 1: block1(); blockNumber = 1; break;case 2: block2(); blockNumber = 2; break;case 3: block3(); blockNumber = 3; break;case 4: block4(); blockNumber = 4; break;case 5: block5(); blockNumber = 5; break;case 6: block6(); blockNumber = 6; break;case 7: block7(); blockNumber = 7; break;}}public void change_body(int blockNumber)//改变砖块状态{dingwei();if(blockNumber == 1&&downSign == false)//变换长条2种情况{if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 16)//说明长条是横着的{if(game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] != 2){num_csh_game();game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] >= 1&&game_sign_x[3] <= 7)//说明长条是竖着的{if(game_body[game_sign_y[0] +1][game_sign_x[0]-1] != 2&&game_body[game_sign_y[3] -2][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]]=1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 3&&downSign == false)//变换转弯1有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] >= 1){if(game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;= 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[1] == game_sign_x[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[3] <= 8){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1]= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] == game_sign_x[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 4&&downSign == false)//变换转弯2有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[3] <= 7){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[1] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[2]) {if(game_body[game_sign_y[1]][game_sign_x[1] + 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0]] = 1;game_body[game_sign_y[1]][game_sign_x[1] + 2] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[0] == game_sign_y[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] - 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2] - 2] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 5&&downSign == false)//变换转弯3有4种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[2] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[1] >= 2){if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[1]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[2] == game_sign_y[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] +2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2]][game_sign_x[2] + 2] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[2] == game_sign_x[3]){if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 6&&downSign == false)//变换两层砖块1的2种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] -1 ] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 7&&downSign == false)//变换两层砖块2的2种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] <= 16){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[2] <= 17)if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}}public void num_csh_game()//数组清零for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){game_body[i][j] = 2;}else{game_body[i][j] = 0;}}}}public void num_csh_restart()//重新开始时数组清零 {for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++)game_body[i][j] = 0;}}}public void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e){if(e.getKeyCode() == KeyEvent.VK_DOWN&&startSign == 1)//处理下键{this.down();}if(e.getKeyCode() == KeyEvent.VK_LEFT&&startSign == 1)//处理左键{this.left();}if(e.getKeyCode() == KeyEvent.VK_RIGHT&&startSign== 1)//处理右键{this.right();}if(e.getKeyCode() == KeyEvent.VK_UP&&startSign== 1)//处理上键转换{this.change_body(blockNumber);}if(startSign == 0){infoTex.setText("游戏未开始或已结束!");}}public void keyReleased(KeyEvent e){}public void paint(Graphics g){g.setColor(Color.black);g.fill3DRect(0,0,300,450,true);for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){g.setColor(Color.blue);g.fill3DRect(30*j,30*(i-4),30,30,true); }if(game_body[i][j] == 2){g.setColor(Color.magenta);g.fill3DRect(30*j,30*(i-4),30,30,true); }}}}public void left()//向左移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 0||game_body[game_sign_y[k]][game_sign_x[k] - 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] - 1] = 1; }infoTex.setText("向左移动!");repaint();}}public void right()//向右移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 9||game_body[game_sign_y[k]][game_sign_x[k] + 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] + 1] = 1; }infoTex.setText("向右移动!");repaint();}}public void down()//下落{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_y[k] == 18||game_body[game_sign_y[k] + 1][game_sign_x[k]] == 2){sign = 1;downSign = true;changeColor();cancelDW();getScore();if(game_over() == false){rand_block();repaint();}}}if(sign == 0){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k] + 1][game_sign_x[k]] = 1;}infoTex.setText("游戏进行中!");repaint();}}public boolean game_over()//判断游戏是否结束{int sign=0;for(int i = 0;i < 10;i++){if(game_body[4][i] == 2){sign = 1;}}if(sign == 1){infoTex.setText("游戏结束!");changeColor();repaint();startSign = 0;timer.suspend();return true;}elsereturn false;}public void getScore()//满行消除方法{for(int i = 0;i < 19;i++){int sign = 0;for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){sign++;}}if(sign == 10){gameScore += 100;scoreTex.setText(gameScore+"");infoTex.setText("恭喜得分!");for(int j = i;j >= 1;j--){for(int k = 0;k < 10;k++){game_body[j][k] = game_body[j - 1][k];}}}}}public void changeColor()//给已经落下的块换色{downSign = false;for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k]] = 2; }}public void dingwei()//确定其位置{int k = 0;cancelDW();for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){game_sign_x[k] = j;game_sign_y[k] = i;k++;}}}}public void cancelDW()//将定位数组初始化{for(int k = 0;k < 4;k++){game_sign_x[k] = 0;game_sign_y[k] = 0;}}public void block1()//长条{game_body[0][4] = 1;game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block2()//正方形{game_body[3][4] = 1;game_body[3][5] = 1;game_body[2][5] = 1;}public void block3()//3加1(下) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[3][5] = 1;}public void block4()//3加1(中) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[2][5] = 1;}public void block5()//3加1(上) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[1][5] = 1;}public void block6()//转折1 {game_body[1][5] = 1;game_body[2][5] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block7()//转折2 {game_body[1][4] = 1;game_body[2][4] = 1;game_body[2][5] = 1;game_body[3][5] = 1;}}//定时线程class MyTimer extends Thread {ERSBlock myBlock;public MyTimer(ERSBlock myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){}}}}。

俄罗斯方块源代码

俄罗斯方块源代码

import java.awt.*;//包含用于创建用户界面和绘制图形图像的所有类。

import java.awt.event.*;//提供处理由 AWT 组件所激发的各类事件的接口和类。

//俄罗斯方块类public class ERS_Block extends Frame{ //Class 类的实例表示正在运行的 Java 应用程序中的类和接口。

//类 Frame,Frame 是带有标题和边界的顶层窗口.public static boolean isPlay=false;public static int level=1,score=0;public static TextField scoreField,levelField;public static MyTimer timer;GameCanvas gameScr;public static void main(String[] argus){ERS_Block ers = new ERS_Block("俄罗斯方块游戏");WindowListener win_listener = new WinListener();//接口 WindowListener,用于接收窗口事件的侦听器接口。

ers.addWindowListener(win_listener);}//俄罗斯方块类的构造方法ERS_Block(String title){super(title);setSize(600,480);setLayout(new GridLayout(1,2));gameScr = new GameCanvas();gameScr.addKeyListener(gameScr);timer = new MyTimer(gameScr);//类 Timer,一种线程设施,用于安排以后在后台线程中执行的任务。

可安排任务执行一次,或者定期重复执行。

俄罗斯方块源代码

俄罗斯方块源代码

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

C语言编程俄罗斯方块的算法及源代码

C语言编程俄罗斯方块的算法及源代码

//俄罗斯方块#include "stdio.h"#include "conio.h"#include "stdlib.h"#include "windows.h"#include "time.h"#define N 17#define M 13#define K 19int s[N][M]={{0,0,0},{0,0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0},{0}, {1},{1,0,0,1},{1,1,1,1,1,1,0,1,1,0,0,1,1}};/*当前状态*/inta[K][3][3]={{0,2,0,2,2,2},{0,2,0,2,2,0,0,2},{0,2,0,0,2,2,0,2},{2,2,2,0,2},{2,2,2,0,0,2 ,0},{2,0,0,2,2,2},{2,0,0,2,0,0,2,2},{0,0,2,0,0,2,0,2,2},{0,0,2,2,2,2},{2,2,2,2,0,0}, {2,2,0,0,2,0,0,2,0},{0,2,2,0,2,0,0,2,0},{{2},{2},{2}},{2,2,2},{2,2,0,2,2,0},{2,0,0,2,2,0,0,2},{0,0,2,0,2,2,0,2},{2,2,0,0,2,2},{0,2,2,2,2,0}};void Disp(){int i,j;for(i=0;i<N;i++){for(j=0;j<M;j++)printf("%c",s[i][j]?48+s[i][j]:' ');printf("┃\n");}printf("━━━━━━━━");printf("\n\n操作说明:A-->左移,D-->右移,W-->变形,ESC-->退出\n");}void Down(){int i,j,k;for(j=0;j<M;j++)if(s[N-1][j]==2)break;/*判断是否在下边界*/if(j<M)/*若方块在下边界则将方块由2变1;因为用两种不同的符号,容易判断方块是否“着陆”及左右移动时,是否碰壁*/{for(i=0;i<N;i++)for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=1;for(i=N-1;i>=0;i--){for(j=0;j<M;j++)//判断第i行是否有空格if(s[i][j]==0)break;if(j==M)/*若第i行没空格消去第i行*/for(k=i++-1;k>=0;k--)//?for(j=0;j<M;j++)s[k+1][j]=s[k][j];}return;}for(i=0;i<N-1;i++){for(j=0;j<M;j++)if(s[i][j]==2)if(s[i+1][j]!=0&&s[i+1][j]!=2)break;/*方块下方不空说明触到1了退出内循环*/ if(j<M)break;/*方块下方不空退出外循环*/}if(i<N-1||j<M){for(i=0;i<N;i++)//若已触到1则将方块由 2变1*/for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=1;for(i=N-1;i>=0;i--){for(j=0;j<M;j++)if(s[i][j]==0)break;//判断第i行是否有空格if(j==M)/*若第i行没空格消去第i行*/for(k=i++-1;k>=0;k--)for(j=0;j<M;j++)s[k+1][j]=s[k][j];}return;}for(i=N-1;i>=0;i--)for(j=0;j<M;j++)if(s[i][j]==2)s[i+1][j]=s[i][j],s[i][j]=0;/*方块下移*/}void Right(){int i,j;for(i=0;i<N;i++)if(s[i][M-1]==2)return;/* 已经在右边界退出 */for(i=0;i<N;i++)for(j=0;j<M-1;j++)if(s[i][j]==2)if(s[i][j+1]!=0&&s[i][j+1]!=2)return;/* 方块右方不空,即方块右边有1 退出 */ for(j=M-2;j>=0;j--)for(i=0;i<N;i++)if(s[i][j]==2)s[i][j+1]=s[i][j],s[i][j]=0;/* 方块右移 */}void Left(){int i,j;for(i=0;i<N;i++)if(s[i][0]==2)return;/* 已经在左边界退出 */for(i=0;i<N;i++)for(j=1;j<M;j++)if(s[i][j]==2)if(s[i][j-1]!=0&&s[i][j-1]!=2)return;/* 方块左方不空退出 */ for(j=1;j<M;j++)for(i=0;i<N;i++)if(s[i][j]==2)s[i][j-1]=s[i][j],s[i][j]=0;/* 方块左移 */}int Have()/*判断是否有可移动方块,没有返回1,否则返回0*/{int i,j;for(i=0;i<N;i++)for(j=1;j<M;j++)if(s[i][j]==2)return 0;return 1;}int Add()/*随机生成方块*/{int t,x;/*生成两随机数t和x分别作为第t种方块和第x位置出现*/int i,j;srand((unsigned int)time(NULL));t=rand()%K;x=rand()%(M-3);if(x<0) x=-x%(M-3);//?for(i=0;i<3;i++)for(j=x;j<x+3;j++)//把生成的方块存到初状态中s[i][j]=a[t][i][j-x];}void bianxing(int t,int n){int i,j,k,m,x,y;for(i=0;i<N;i++)//首先扫描是否有移动方块;及方块变形前的位置“行、列”{m=-1;for(j=0;j<M;j++)if(s[i][j]==2){m=i,x=j,y=i;break;//y,x记录所在行、列;并退出内循环}if(m!=-1)//m!=-1证明有移动方块break;//退出外循环}if(m!=-1)//m!=-1证明有移动方块{if(x+3>M||y+3>N) return;//判断是否有可变形空间,没有就返回for(i=y;i<y+3;i++)//判断是否有3*3的变形空间,没有就返回for(j=x;j<x+3;j++)if(s[i][j]==1) return;/*擦除当前移动方块;因为上面判断3*3的移动空间,是从上面开始扫描,遇到第一个小格子时,依他为基点向右下方扫描是否有3*3的空间;显然只进行下面的变形--存储是不行的;如:002002022-->2220020时,显然前面的方格倒数第二个2,留在了3*3变形空间的外面,输出图形将多一个格子,所以要在变形-->存储操作前进行擦除操作*/for(i=y;i<y+3;i++)for(j=0;j<M;j++)if(s[i][j]==2)s[i][j]=0;//变形并把它存储到当前状态中if(t<=3&&t>=0){static int h1;if(h1>n)h1=0;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h1][i-y][j-x];h1++;}else if(t<=11&&t>=4){static int h2=4;if(h2>n)h2=4;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h2][i-y][j-x];h2++;}else if(t<=13&&t>=12){static int h3=12;if(h3>n)h3=12;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h3][i-y][j-x];h3++;}else if(t<=18&&t>=15){static int h4=15;if(h4>n)h4=0;for(i=y;i<y+3;i++)//把方块存储到当前状态中for(j=x;j<x+3;j++)s[i][j]=a[h4][i-y][j-x];h4++;}}void main(){char c;int i=0,t;char str[][50]={" ((`'-\"``\"\"-'`))"," ) - - ( "," / (o _ o) \ "," \ ( 0 ) /"," _'-.._'='_..-'_ "," /`;#'#'#.-.#'#'#;`\ "," \_)) '#' ((_/ "," #. ☆ Game ☆ # "," '#. Over! .#' "," / '#. .#' \ "," _\ \'#. .#'/ /_"," (((___) '#' (___) ",""};system("color 0a");while(1)/*判断是否有按键,没有循环输出i,否则停,conio.h*/{if(!kbhit())/*kbhit用来判断是否有按键输入,若有按键返回非零值,否则返回零;没有按键时c被赋予一个“非操作键值”,它将一直下移;有按键是调用getch函数,读取键值*/c='2';elsec=getch();if(c=='p')//停止键;按任意键可解除停止getch();system("CLS");/*清屏,TC用clrscr();,VC用system("CLS");*/if(Have())//Have()判断是否有可移动方块,没有返回1,否则返回0t=Add();switch(c){case 'a':Left();break; /*左移*/case 'd':Right();break; /*右移*/case 27: system("pause");return; /*按Esc(=27)另存后退出*/default:;}//变形if(c=='w')if(t>=0&&t<=3) bianxing(t,3);else if(t>=4&&t<=11) bianxing(t,11);else if(t==12||t==13) bianxing(t,13);else if(t>=15&&t<=18) bianxing(t,18);c='2';Down();//判断方块的停、走和消除//判断顶层是否有1 有:游戏结束for(i=0;i<M;i++)if(s[0][i]==1){system("CLS");i=0;while(1){if(strlen(str[i])==0)break;printf("%s\n",str[i++]);}system("pause");exit(0);}Disp();//刷屏Sleep(500);/*睡眠ms,windows.h*/}}***********************************************************。

俄罗斯方块源代码

俄罗斯方块源代码

2**************************************************************************** ***/3/* Define to prevent recursive inclusion-------------------------------------*/4#ifndef _HEAD_H_5#define _HEAD_H_67/* Includes------------------------------------------------------------------*/8#include <graphics.h>9#include <stdio.h>10#include <conio.h>11#include <stdlib.h>12#include <time.h>1314/* Macro---------------------------------------------------------------------*/15#define TRUE 116#define FALSE 01718//GUI游戏界面相关的参数19#define GUI_WALL_SQUARE_WIDTH 10 //外围围墙小方格的宽度(单位:像素)20#define GUI_xWALL_SQUARE_NUM 30 //横向(x轴方向)围墙小方格的数量(必须是偶数)21#define GUI_yWALL_SQUARE_NUM 46 //纵向(y轴方向)围墙小方格的数量(必须是偶数)22#define GUI_WALL_WIDTH_PIX (GUI_WALL_SQUARE_WIDTH*GUI_xWALL_SQUARE_NUM) 23#define GUI_WALL_HIGH_PIX (GUI_WALL_SQUARE_WIDTH*GUI_yWALL_SQUARE_NUM) 2425#define WINDOW_WIDTH 480 //窗口的宽度26#define WINDOW_HIGH GUI_WALL_HIGH_PIX //窗口高度2728//俄罗斯方块相关的参数29//移动的方向30#define DIRECT_UP 331#define DIRECT_DOWN 232#define DIRECT_LEFT -133#define DIRECT_RIGHT 13435//每一个小方块的大小(是围墙小方格宽度的2倍)36#define ROCK_SQUARE_WIDTH (2*GUI_WALL_SQUARE_WIDTH)37//横向能容纳小方格的数量38#define X_ROCK_SQUARE_NUM ((GUI_xWALL_SQUARE_NUM-2)/2)39//纵向能容纳小方格的数量40#define Y_ROCK_SQUARE_NUM ((GUI_yWALL_SQUARE_NUM-2)/2)42/* Exported types------------------------------------------------------------*/43typedef int BOOL ; //布尔值类型4445/*数据结构-线性表(结构体数组)*/46typedef struct ROCK47{48//用来表示方块的形状(每一个字节是8位,用每4位表示方块中的一行)49 unsigned int rockShapeBits ;50int nextRockIndex ; //下一个方块,在数组中的下标51} RockType ;5253//方块在图形窗口中的位置(即定位4*4大块的左上角坐标)54typedef struct LOCATE55{56int left ;57int top ;58} RockLocation_t ;5960/* Function prototypes-------------------------------------------------------*/61//源文件play.c中62void PlayGame(void) ;6364//源文件init.c中65int InitProcParameters(void) ;6667//源文件GUI.c中68void DrawRock(int, const struct LOCATE *, BOOL) ;69void DrawGameGUI(void) ;70void UpdataScore(void) ;71void UpdataGrade(int) ;7273#endif /* _HEAD_H_ */7475/*********************** (C) COPYRIGHT 2013 yang_yulei *********END OF FILE****/下面是源文件main.cpp[cpp]view plain copyprint?76/************************ (C) COPYRIGHT 2013 yang_yulei************************77* File Name : main.cpp78* Author : yang_yulei79* Date First Issued : 1/16/201280* Description : 开发环境 VC++ 6.0 含EasyX图形库() 81* 俄罗斯方块82*83*84**************************************************************************** ****85* History:86* 1/16/2012 : V0.187* 12/18/2013 : V0.288**************************************************************************** ****89*90**************************************************************************** ***/91/* Includes------------------------------------------------------------------*/92#include "head.h"93#include <windows.h>94#include <dos.h>9596/* Typedef-------------------------------------------------------------------*/97/* Variables-----------------------------------------------------------------*/98//全局变量-游戏板的状态描述(即表示当前界面哪些位置有方块)99//0表示没有,1表示有(多加了两行和两列,形成一个围墙,便于判断方块是否能够移动)100char g_gameBoard[Y_ROCK_SQUARE_NUM+2][X_ROCK_SQUARE_NUM+2] = {0} ;101//统计分数102int g_score = 0 ;103//等级104int g_grade = 0 ;105106int g_rockTypeNum = 0 ; //共有多少种俄罗斯方块107RockType rockArray[50] = {(0,0)} ;108109/*************************************************************************** ****110* Function Name : main111* Description : Main program112* Input : None113* Output : None114* Return : None115**************************************************************************** ***/116int117main(void)118{119//画出游戏界面120 initgraph(WINDOW_WIDTH, WINDOW_HIGH) ; //初始化图形窗口121 cleardevice() ;122 DrawGameGUI() ;123124//使用 API 函数修改窗口名称125HWND hWnd = GetHWnd();126 SetWindowText(hWnd, "俄罗斯方块");127128//初始化参数129 InitProcParameters() ;130131//游戏过程132 PlayGame() ;133134 closegraph() ;135return 0 ;136}下面是源文件init.cpp---游戏运行前初始化的一些方法[cpp]view plain copyprint?137/************************ (C) COPYRIGHT 2013 yang_yulei************************138* File Name : init.cpp139* Author : yang_yulei140* Date First Issued : 12/18/2013141* Description :142*143**************************************************************************** ****144*145****************************************************************************146/* Includes------------------------------------------------------------------*/147#include "head.h"148149/* Variables-----------------------------------------------------------------*/150extern char g_gameBoard[][X_ROCK_SQUARE_NUM+2] ;151extern int g_rockTypeNum ;152extern RockType rockArray[] ;153154/* Function prototypes-------------------------------------------------------*/155static int ReadRockShape(void) ;156static unsigned int ShapeStr2uInt(char* const);157158/*************************************************************************** ****159* Function Name : InitProcParameters160* Description : 在正式开始运行游戏前,初始化一些参数:g_gameBoard161从配置文件中读取系统中俄罗斯方块的形状162* Be called : main163* Input : None164* Output : g_gameBoard rockArray165* Return : None166**************************************************************************** ***/167//初始化程序参数168int169InitProcParameters(void)170{171int i ;172173//初始化游戏板(把这个二维数组的四周置1,当作围墙,用于判断边界)174for (i = 0; i < X_ROCK_SQUARE_NUM+2; i++)175 {176 g_gameBoard[0][i] = 1 ;177 g_gameBoard[Y_ROCK_SQUARE_NUM+1][i]= 1 ;178 }179for (i = 0; i < Y_ROCK_SQUARE_NUM+2; i++)180 {181 g_gameBoard[i][0] = 1 ;182 g_gameBoard[i][X_ROCK_SQUARE_NUM+1]= 1 ;183 }185//从配置文件中读取游戏中所有方块的形状点阵186 ReadRockShape() ;187188return 0 ;189}190191/*************************************************************************** ****192* Function Name : ReadRockShape193* Description : 从配置文件中读取系统中俄罗斯方块的形状把它记录在rockArray中194* Be called : InitProcParameters195* Input : rockshape.ini196* Output : rockArray197* Return : 成功返回0 失败返回1198**************************************************************************** ***/199int200ReadRockShape(void)201{202FILE* fp ;203int i = 0 ;204int len = 0 ;205int rockArrayIdx = 0 ;206int shapeNumPerRock = 0 ; //一种方块的形态数目(用于计算方块的nextRockIndex) 207208char rdBuf[128] ;209char rockShapeBitsStr[128] = {0};210211 unsigned int shapeBits = 0 ;212213 g_rockTypeNum = 0 ;214215//打开配置文件从中读取方块的形状216 fp = fopen(".\\rockshape.ini", "r") ;217if (fp == NULL)218 {219 perror("open file error!\n") ;220return 1 ;221 }222223while (fgets(rdBuf, 128, fp) != NULL)224 {225 len = strlen(rdBuf) ;226 rdBuf[len-1] = '\0' ;227228switch (rdBuf[0])229 {230case'@': case'#':231 strcat(rockShapeBitsStr, rdBuf) ;232break ;233234case 0 : //一个方块读取结束235 shapeBits = ShapeStr2uInt(rockShapeBitsStr) ;236 rockShapeBitsStr[0] = 0 ;237 shapeNumPerRock++ ;238 rockArray[rockArrayIdx].rockShapeBits = shapeBits ;239 rockArray[rockArrayIdx].nextRockIndex = rockArrayIdx + 1 ;240 rockArrayIdx++ ;241 g_rockTypeNum++ ; //记录方块数量的全局变量+1242break ;243244case'-'://一种方块读取结束(更新其nextRockIndex值)245 rockArray[rockArrayIdx-1].nextRockIndex = rockArrayIdx - shapeNumPerRock ;246 shapeNumPerRock = 0 ;247break ;248249default :250break ;251 }252 }//while()253254return 0 ;255}256257/*************************************************************************** ****258* Function Name : ShapeStr2uInt259* Description : 把配置文件中的描述方块形状的字符串转化为 unsigned int型260* Be called :261* Input : shapeStr 描述方块形状的字符串(从文件中读取的)262* Output : None263* Return : unsigned int型的方块形状点阵(用其低16位表示)264**************************************************************************** ***/265unsigned int266ShapeStr2uInt(char* const shapeStr)268 unsigned int shapeBitsRet = 0 ;269char* p = shapeStr ;270271for (p += 15; p >= shapeStr; p--)272 {273if (*p == '@')274 {275 shapeBitsRet |= ((unsigned int)1 << (&shapeStr[15]-p)) ;276 }277 }278279return shapeBitsRet ;280}下面是源文件GUI.cpp---一些关于在界面上画出界面的一些方法[cpp]view plain copyprint?281/************************ (C) COPYRIGHT 2013 yang_yulei************************282* File Name : GUI.cpp283* Author : yang_yulei284* Date First Issued : 12/18/2013285* Description :286*287**************************************************************************** ****288*289**************************************************************************** ***/290/* Includes------------------------------------------------------------------*/291#include "head.h"292293/* Variables-----------------------------------------------------------------*/294//预览区位置295RockLocation_t previewLocation ={GUI_WALL_SQUARE_WIDTH*GUI_xWALL_SQUARE_NUM+70, 50} ;296297extern RockType rockArray[] ;299/*******************************************************************************300* Function Name : DrawRock301* Description : 在游戏区画出编号为rockIndex的方块302* Be called : PlayGame()303* Input : rockIndex :304 currentLocatePtr: 此方块的位置305 displayed : 此方块是否显示306* Output : None307* Return : None308*******************************************************************************/309void310DrawRock(int rockIndex, const struct LOCATE * currentLocatePtr, BOOL displayed) 311{312int i ;313int mask ;314int rockX ; //俄罗斯方块的4*4模型的左上角点x轴的坐标315int rockY ; //俄罗斯方块的4*4模型的左上角点y轴的坐标316int spaceFlag ; //占位标记(用于g_gameBoard,1表示某处有方块 0表示此处无方块) 317int color ; //画出的方块的颜色318319//若此方块是用于显示的,则设置其颜色为白色,其占位标记设为1320//否则设置其颜色为黑色(背景色),占位标记设为0321 displayed ? (color = WHITE,spaceFlag = 1)322 : (color = BLACK,spaceFlag = 0) ;323324 setcolor(color) ; //设置画笔颜色325 setlinestyle(PS_SOLID, NULL, 2) ; //设置线形为1像素的实线326 rockX = currentLocatePtr->left ;327 rockY = currentLocatePtr->top ;328329//逐位扫描由unsigned int的低2字节330//16个位组成的俄罗斯方块形状点阵(其代表4*4的方块形状)331 mask = (unsigned int)1 << 15 ;332for (i=1; i<=16; i++)333 {334//与掩码相与为1的即为方块上的点335if ((rockArray[rockIndex].rockShapeBits & mask) != 0)336 {337//在屏幕上画出此方块338 rectangle(rockX+2,339 rockY+2,340 rockX+ROCK_SQUARE_WIDTH-2,341 rockY+ROCK_SQUARE_WIDTH-2) ;342 }343344//每4次换行转到下一行继续画345 i%4 == 0 ? (rockY += ROCK_SQUARE_WIDTH, rockX = currentLocatePtr->left) 346 : rockX += ROCK_SQUARE_WIDTH ;347348 mask >>= 1 ;349 }350}351352/*******************************************************************************353* Function Name : DrawGameGUI354* Description : 画出游戏界面355* Be called : main()356* Input : None357* Output : None358* Return : None359*******************************************************************************/360void361DrawGameGUI(void)362{363int i = 0 ;364int wallHigh = GUI_yWALL_SQUARE_NUM * GUI_WALL_SQUARE_WIDTH ;//围墙的高度(像素)365366 setcolor(RED) ; //设置围墙的颜色367 setlinestyle(PS_SOLID, NULL, 0) ; //设置围墙方格的线形(1像素的实线)368369//画出围墙(画矩形是先确定左上顶点的坐标,再确定右下顶点坐标)370//先画出上下墙371for (i = GUI_WALL_SQUARE_WIDTH;372 i <= GUI_WALL_WIDTH_PIX;373 i += GUI_WALL_SQUARE_WIDTH)374 {375 rectangle(i-GUI_WALL_SQUARE_WIDTH,376 0,377 i,378 GUI_WALL_SQUARE_WIDTH) ; //上墙379380 rectangle(i-GUI_WALL_SQUARE_WIDTH,381 wallHigh-GUI_WALL_SQUARE_WIDTH,382 i,383 wallHigh) ; //下墙384 }385386//再画出左右墙387for (i = 2*GUI_WALL_SQUARE_WIDTH;388 i <= wallHigh-GUI_WALL_SQUARE_WIDTH;389 i += GUI_WALL_SQUARE_WIDTH)390 {391 rectangle(0,392 i-GUI_WALL_SQUARE_WIDTH,393 GUI_WALL_SQUARE_WIDTH,394 i) ; //左墙395396 rectangle(GUI_WALL_WIDTH_PIX-GUI_WALL_SQUARE_WIDTH,397 i-GUI_WALL_SQUARE_WIDTH,398 GUI_WALL_WIDTH_PIX,399 i) ; //右墙400 }401402//画分隔线403 setcolor(WHITE) ; //设置画笔颜色404 setlinestyle(PS_DASH, NULL, 2) ; //设置线形为2像素的虚线405 line(GUI_WALL_WIDTH_PIX+20,0,GUI_WALL_WIDTH_PIX+20,wallHigh) ; //在偏移右围墙的20处画线406407//画右边统计分数及版权信息栏408//先设置字体409 LOGFONT f ; //定义字体属性结构体410 getfont(&f) ; //获得当前字体411 f.lfHeight = 18 ; //设置字体高度为 38(包含行距)412 strcpy(f.lfFaceName, "黑体") ; //设置字体为“黑体”413 f.lfQuality = ANTIALIASED_QUALITY ; //设置输出效果为抗锯齿414 setfont(&f) ; //设置字体样式415416//1,显示预览417 outtextxy(GUI_WALL_WIDTH_PIX+80 , 20 , "预览") ;418//2,显示等级栏419 outtextxy(GUI_WALL_WIDTH_PIX+80 , 140 , "等级") ;420//3,显示得分栏421 outtextxy(GUI_WALL_WIDTH_PIX+80 , 190 , "得分") ;422423//4,显示操作说明424 outtextxy(GUI_WALL_WIDTH_PIX+65 , 255 , "操作说明") ;425 getfont(&f) ;426 strcpy(f.lfFaceName, "宋体") ;427 f.lfHeight = 15 ;428 setfont(&f) ;429 outtextxy(GUI_WALL_WIDTH_PIX+45 , 290 , "w.a.s.d控制方向") ;430 outtextxy(GUI_WALL_WIDTH_PIX+45 , 313 , "回车键暂停") ;431 outtextxy(GUI_WALL_WIDTH_PIX+45 , 336 , "空格键快速下落") ;432433//5.版权信息434 line(GUI_WALL_WIDTH_PIX+20 , wallHigh-65 , WINDOW_WIDTH , wallHigh-65) ; 435 outtextxy(GUI_WALL_WIDTH_PIX+40 , wallHigh-50 , " 杨溢之作品") ;436 outtextxy(GUI_WALL_WIDTH_PIX+40 , wallHigh-30 , " QQ:702080167") ;437438//显示等级,得分信息439 setcolor(RED) ;440 outtextxy(GUI_WALL_WIDTH_PIX+90 , 163 , "1") ;441 outtextxy(GUI_WALL_WIDTH_PIX+90 , 223 , "0") ;442}443444/*************************************************************************** ****445* Function Name : UpdataScore446* Description : 增加一次得分,并把游戏界面的得分区显示更新447* Be called : ProcessFullRow()448* Input : None449* Output : None450* Return : None451**************************************************************************** ***/452void453UpdataScore(void)454{455char scoreStr[5] ; //用字符串的形式存储得分456extern int g_score ;457extern int g_grade ;458459//分数的增长的单位是10460 g_score += 10 ;461//得分是100的倍数,则等级加1 (等级在5级以上的就保持不变)462if (g_score == (g_score/100)*100 && g_grade < 5)463 UpdataGrade(++g_grade) ;464465//删除原先信息466 setfillstyle(BLACK) ;467 bar(GUI_WALL_WIDTH_PIX+90,220,GUI_WALL_WIDTH_PIX+99,229) ;468469//显示信息470 setcolor(RED) ;471 sprintf(scoreStr , "%d" , g_score) ;472 outtextxy(GUI_WALL_WIDTH_PIX+90 , 223 , scoreStr) ;473}474475/*************************************************************************** ****476* Function Name : UpdataGrade477* Description : 增加一次等级,并把游戏界面的等级区显示更新478* Be called :479* Input : grade :新的等级值480* Output : None481* Return : None482**************************************************************************** ***/483void484UpdataGrade(int grade)485{486char gradeStr[5] ;487488//删除原先信息489 setfillstyle(BLACK) ;490 bar(GUI_WALL_WIDTH_PIX+90,160,GUI_WALL_WIDTH_PIX+99,169) ;491492//显示信息493 setcolor(RED) ;494 sprintf(gradeStr , "%d" , grade) ;495 outtextxy(GUI_WALL_WIDTH_PIX+90 , 163 , gradeStr) ;496}下面是源文件play.cpp---控制游戏的重要方法[cpp]view plain copyprint?497/************************ (C) COPYRIGHT 2013 yang_yulei************************498* File Name : play.cpp499* Author : yang_yulei500* Date First Issued : 12/18/2013501* Description :502*503**************************************************************************** ****504*505**************************************************************************** ***/506/* Includes------------------------------------------------------------------*/507#include "head.h"508509/* Variables-----------------------------------------------------------------*/510extern char g_gameBoard[][X_ROCK_SQUARE_NUM+2] ;511extern int g_rockTypeNum ;512extern RockType rockArray[] ;513514/* Function prototypes-------------------------------------------------------*/515static BOOL MoveAble(int, const struct LOCATE *, int) ;516static void SetOccupyFlag(int, const struct LOCATE *) ;517static void ProcessFullRow(void) ;518static BOOL isGameOver() ;519static void ProccessUserHit(int, int*, struct LOCATE*) ;520static void FastFall(int, struct LOCATE *, struct LOCATE *) ;521static void DelFullRow(int f_row) ;522523/*************************************************************************** ****524* Function Name : PlayGame525* Description : 此程序的主要设计逻辑526* Be called : main527* Input : None528* Output : None529* Return : None530**************************************************************************** ***/531void532PlayGame(void)533{534int userHitChar ; //用户敲击键盘的字符535int currentRockIndex ; //当前方块在rockArray数组中下标536int nextRockIndex ; //准备的下个方块的下标537BOOL moveAbled = FALSE ;//记录方块能否落下538DWORD oldtime = 0;539extern int g_grade ;540541//当前方块位置542 RockLocation_t currentRockLocation ;543//初始方块位置(由当中开始下落)544 RockLocation_t initRockLocation ={(GUI_xWALL_SQUARE_NUM/2-4)*GUI_WALL_SQUARE_WIDTH,545 GUI_WALL_SQUARE_WIDTH};546//预览区位置547extern RockLocation_t previewLocation ;548549//为第一次下落,初始化参数550//随机选择当前的俄罗斯方块形状和下一个俄罗斯方块形状551 srand(time(NULL)) ;552 currentRockIndex = rand()%g_rockTypeNum ;553 nextRockIndex = rand()%g_rockTypeNum ;554 currentRockLocation.left = initRockLocation.left ;555 currentRockLocation.top = initRockLocation.top ;556557while(1)558 {559 DrawRock(currentRockIndex, ¤tRockLocation, TRUE) ;560 FlushBatchDraw(); //用批绘图功能,可以消除闪烁561562//判断能否下落563 moveAbled = MoveAble(currentRockIndex, ¤tRockLocation, DIRECT_DOWN) ; 564565//如果不能下落则生成新的方块566if (!moveAbled)567 {568//设置占位符(此时方块已落定)569 SetOccupyFlag(currentRockIndex, ¤tRockLocation) ;570//擦除预览571 DrawRock( nextRockIndex, &previewLocation, FALSE) ;572//生成新的方块573 currentRockIndex = nextRockIndex ;574 nextRockIndex = rand()%g_rockTypeNum ;575 currentRockLocation.left = initRockLocation.left ;576 currentRockLocation.top = initRockLocation.top ;577 }578579//显示预览580 DrawRock(nextRockIndex, &previewLocation, TRUE) ;581582//如果超时(且能下落),自动下落一格583// 这个超时时间400-80*g_grade 是本人根据实验自己得出的584// 一个速度比较适中的一个公式(g_grade不会大于等于5)585DWORD newtime = GetTickCount();586if (newtime - oldtime >= (unsigned int)(400-80*g_grade) && moveAbled == TRUE)587 {588 oldtime = newtime ;589 DrawRock(currentRockIndex, ¤tRockLocation, FALSE) ; //擦除原先位置590 currentRockLocation.top += ROCK_SQUARE_WIDTH ; //下落一格591 }592593//根据当前游戏板的状况判断是否满行,并进行满行处理594 ProcessFullRow() ;595596//判断是否游戏结束597if (isGameOver())598 {599 MessageBox( NULL,"游戏结束", "GAME OVER", MB_OK ) ;600 exit(0) ;601 }602603//测试键盘是否被敲击604if (kbhit())605 {606 userHitChar = getch() ;607 ProccessUserHit(userHitChar, ¤tRockIndex, ¤tRockLocation) ;608 }609610 Sleep(20) ; //降低CPU使用率611 }//结束外层while(1)612613}614615/*************************************************************************** ****616* Function Name : ProccessUserHit617* Description : 处理用户敲击键盘618* Be called : PlayGame()619* Input : userHitChar 用户敲击键盘的ASCII码620 rockIndexPtr 当前俄罗斯方块在rockArray中的下标621 rockLocationPtr 当前方块在游戏界面中的位置622623* Output : rockIndexPtr 响应用户敲击后新方块的下标624 rockLocationPtr 响应用户敲击后新方块的位置625* Return : None626**************************************************************************** ***/627void628ProccessUserHit(int userHitChar, int* rockIndexPtr, struct LOCATE* rockLocationPtr)629{630switch (userHitChar)631 {632case'w' : case'W' : //“上”键633//检查是否能改变方块形状634if (MoveAble(rockArray[*rockIndexPtr].nextRockIndex, rockLocationPtr, DIRECT_UP))635 {636 DrawRock(*rockIndexPtr, rockLocationPtr, FALSE) ;637 *rockIndexPtr = rockArray[*rockIndexPtr].nextRockIndex ;638 }639break ;640641case's' : case'S' : //“下”键642 DrawRock(*rockIndexPtr, rockLocationPtr, FALSE) ; //擦除原先位置643 rockLocationPtr->top += ROCK_SQUARE_WIDTH ;644break ;645646case'a' : case'A' : //“左”键647if (MoveAble(*rockIndexPtr, rockLocationPtr, DIRECT_LEFT))648 {649 DrawRock(*rockIndexPtr, rockLocationPtr, FALSE) ;650 rockLocationPtr->left -= ROCK_SQUARE_WIDTH ;651 }652break ;653654case'd' : case'D' : //“右”键655if (MoveAble(*rockIndexPtr, rockLocationPtr, DIRECT_RIGHT))656 {657 DrawRock(*rockIndexPtr, rockLocationPtr, FALSE) ;658 rockLocationPtr->left += ROCK_SQUARE_WIDTH ;659 }660break ;661662case' ' : //空格(快速下落)663 DrawRock(*rockIndexPtr, rockLocationPtr, FALSE) ;664 FastFall(*rockIndexPtr, rockLocationPtr, rockLocationPtr) ;665break ;666667case 13 : //回车键(暂停)668while(1)669 { userHitChar = getch() ;670if (userHitChar==13)671break ;672 }673break ;674675default :676break ;677 }678679}680681/*******************************************************************************682* Function Name : MoveAble683* Description : 判断编号为rockIndex 在位置currentLocatePtr的方块684能否向direction移动685* Be called :686* Input : None687* Output : None688* Return : TRUE 可以移动689 FALSE 不可以移动690*******************************************************************************/691BOOL692MoveAble(int rockIndex, const struct LOCATE* currentLocatePtr, int f_direction) 693{694int i ;695int mask ;696int rockX ;697int rockY ;698699 rockX = currentLocatePtr->left ;700 rockY = currentLocatePtr->top ;701702 mask = (unsigned int)1 << 15 ;703for (i=1; i<=16; i++)704 {705//与掩码相与为1的即为方块上的点706if ((rockArray[rockIndex].rockShapeBits & mask) != 0)707 {708//判断能否移动(即扫描即将移动的位置是否与设置的围墙有重叠)709//若是向上(即翻滚变形)710if( f_direction == DIRECT_UP )711 {712//因为此情况下传入的是下一个方块的形状,故我们直接判断此方块的位置是否已经被占713if(g_gameBoard[(rockY-GUI_WALL_SQUARE_WIDTH)/ROCK_SQUARE_WIDTH+1]714[(rockX-GUI_WALL_SQUARE_WIDTH)/ROCK_SQUARE_WIDTH+1] == 1)715return FALSE ;716 }717//如果是向下方向移动718else if( f_direction == DIRECT_DOWN )719 {720if(g_gameBoard[(rockY-GUI_WALL_SQUARE_WIDTH)/ROCK_SQUARE_WIDTH+2]721[(rockX-GUI_WALL_SQUARE_WIDTH)/ROCK_SQUARE_WIDTH+1] ==1)722return FALSE ;723 }724else//如果是左右方向移动725 { //f_direction的DIRECT_LEFT为-1,DIRECT_RIGHT为1,故直接加f_direction即可判断。

俄罗斯方块完整源代码

俄罗斯方块完整源代码

//不多说,直接可以拷贝下面的东西,就可以运行。

package day04;import java.awt.*;import java.awt.event.*;import javax.swing.*;import java.applet.*;import ng.String.*;import ng.*;import java.io.*;public class ERSBlock extends JPanel implements ActionListener,KeyListener//应该是继承JPanel{static Button but[] = new Button[6];static Button noStop = new Button("取消暂停"); static Label scoreLab = new Label("分数:");static Label infoLab = new Label("提示:");static Label speedLab = new Label("级数:");static Label scoreTex = new Label("0");static Label infoTex = new Label(" ");static Label speedTex = new Label("1");static JFrame jf = new JFrame();static MyTimer timer;static ImageIcon icon=new ImageIcon("resource/Block.jpg");static JMenuBar mb = new JMenuBar();static JMenu menu0 = new JMenu("游戏 ");static JMenu menu1 = new JMenu("帮助 ");static JMenuItem mi0 = new JMenuItem("新游戏"); static JMenuItem mi1 = new JMenuItem("退出");static JMenuItem mi1_0 = new JMenuItem("关于"); static JDialog dlg_1;static JTextArea dlg_1_text = new JTextArea(); static int startSign= 0;//游戏开始标志 0 未开始 1 开始 2 暂停static String butLab[] = {"开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"};static int game_body[][] = new int[19][10];static int game_sign_x[] = new int[4];//用于记录4个方格的水平位置static int game_sign_y[] = new int[4];//用于记录4个方格的垂直位置static boolean downSign = false;//是否落下static int blockNumber = 1;//砖块的编号static int gameScore = 0;//游戏分数static int speedMark = 1;public static void main(String args[]) {ERSBlock myBlock = new ERSBlock();mb.add(menu0);mb.add(menu1);menu0.add(mi0);menu0.add(mi1);menu1.add(mi1_0);jf.setJMenuBar(mb);myBlock.init();jf.add(myBlock);jf.setSize(565,501);jf.setResizable(false);jf.setTitle("俄罗斯方块");jf.setIconImage(icon.getImage());jf.setLocation(200,100);jf.show();timer = new MyTimer(myBlock); //启动线程timer.setDaemon(true);timer.start();timer.suspend();}public void init(){setLayout(null);for(int i = 0;i < 6;i++){but[i] = new Button(butLab[i]);add(but[i]);but[i].addActionListener(this);but[i].addKeyListener(this);but[i].setBounds(360,(240 + 30 * i),160,25); }add(scoreLab);add(scoreTex);add(speedLab);add(speedTex);add(infoLab);add(infoTex);add(scoreLab);scoreLab.setBounds(320,15,30,20); scoreTex.setBounds(360,15,160,20); scoreTex.setBackground(Color.white); speedLab.setBounds(320,45,30,20); speedTex.setBounds(360,45,160,20); speedTex.setBackground(Color.white);but[1].setEnabled(false);but[4].setEnabled(false);infoLab.setBounds(320,75,30,20); infoTex.setBounds(360,75,160,20); infoTex.setBackground(Color.white); noStop.setBounds(360,360,160,25); noStop.addActionListener(this); noStop.addKeyListener(this);mi0.addActionListener(this);mi1.addActionListener(this);mi1_0.addActionListener(this);num_csh_game();rand_block();}public void actionPerformed(ActionEvent e){if(e.getSource() == but[0])//开始游戏{startSign = 1;infoTex.setText("游戏已经开始!");but[0].setEnabled(false);but[1].setEnabled(true);but[4].setEnabled(true);timer.resume();}if(e.getSource() == but[1]||e.getSource() == mi0)//重新开始游戏{startSign = 0;gameScore = 0;timer.suspend();num_csh_restart();repaint();rand_block();scoreTex.setText("0");infoTex.setText("新游戏!");but[0].setEnabled(true);but[1].setEnabled(false);but[4].setEnabled(false);}if(e.getSource() == but[2])//降低级数 {infoTex.setText("降低级数!"); speedMark--;if(speedMark <= 1){speedMark = 1;infoTex.setText("已经是最低级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[3])//提高级数 {infoTex.setText("提高级数!");speedMark++;if(speedMark >= 9){speedMark = 9;infoTex.setText("已经是最高级数!"); }speedTex.setText(speedMark + ""); }if(e.getSource() == but[4])//游戏暂停 {this.add(noStop);this.remove(but[4]);infoTex.setText("游戏暂停!"); timer.suspend();}if(e.getSource() == noStop)//取消暂停 {this.remove(noStop);this.add(but[4]);infoTex.setText("继续游戏!"); timer.resume();}if(e.getSource() == but[5]||e.getSource() == mi1)//退出游戏{jf.dispose();}if(e.getSource() == mi1_0)//退出游戏{dlg_1 = new JDialog(jf,"关于");try{FileInputStream io = new FileInputStream("resource/guanyu.txt");//得到路径byte a[] = new byte[io.available()];io.read(a);io.close();String str = new String(a);dlg_1_text.setText(str);}catch(Exception g){}dlg_1_text.setEditable(false);dlg_1.add(dlg_1_text);dlg_1.pack();dlg_1.setResizable(false);dlg_1.setSize(200, 120);dlg_1.setLocation(400, 240);dlg_1.show();}}public void rand_block()//随机产生砖块{int num;num = (int)(Math.random() * 6) + 1;//产生0~6之间的随机数blockNumber = num;switch(blockNumber){case 1: block1(); blockNumber = 1; break;case 2: block2(); blockNumber = 2; break;case 3: block3(); blockNumber = 3; break;case 4: block4(); blockNumber = 4; break;case 5: block5(); blockNumber = 5; break;case 6: block6(); blockNumber = 6; break;case 7: block7(); blockNumber = 7; break;}}public void change_body(int blockNumber)//改变砖块状态{dingwei();if(blockNumber == 1&&downSign == false)//变换长条2种情况{if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 16)//说明长条是横着的{if(game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] != 2){num_csh_game();game_body[game_sign_y[0] - 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] + 2][game_sign_x[3] - 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] >= 1&&game_sign_x[3] <= 7)//说明长条是竖着的{if(game_body[game_sign_y[0] +1][game_sign_x[0]-1] != 2&&game_body[game_sign_y[3] -2][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]]=1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 3&&downSign == false)//变换转弯1有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] >= 1){if(game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;= 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[1] == game_sign_x[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[3] <= 8){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1]= 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] == game_sign_x[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 4&&downSign == false)//变换转弯2有4种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[3] <= 7){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3]][game_sign_x[3] + 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3]][game_sign_x[3] + 2] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[1] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[2]) {if(game_body[game_sign_y[1]][game_sign_x[1] + 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0]] = 1;game_body[game_sign_y[1]][game_sign_x[1] + 2] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] == game_sign_x[3]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[0] == game_sign_y[2]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] - 2] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] - 1] = 1;game_body[game_sign_y[2]][game_sign_x[2] - 2] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 5&&downSign == false)//变换转弯3有4种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[2] == game_sign_x[3]&&game_sign_y[0] == game_sign_y[1]&&game_sign_x[1] >= 2){if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[1] == game_sign_y[2]&&game_sign_y[2] == game_sign_y[3]&&game_sign_x[0] == game_sign_x[1]&&game_sign_y[0] <= 16){if(game_body[game_sign_y[0] + 2][game_sign_x[0]] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0] + 2][game_sign_x[0]] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[1] == game_sign_x[3]&&game_sign_y[2] == game_sign_y[3]) {if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[2]][game_sign_x[2] +2] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2]][game_sign_x[2] + 2] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[1] == game_sign_y[2]&&game_sign_x[2] == game_sign_x[3]){if(game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] != 2&&game_body[game_sign_y[3] - 2][game_sign_x[3]] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] + 1] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 2][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 6&&downSign == false)//变换两层砖块1的2种情况{if(game_sign_x[0] == game_sign_x[2]&&game_sign_x[0] >= 2){if(game_body[game_sign_y[0]][game_sign_x[0] - 2] != 2&&game_body[game_sign_y[2] - 1][game_sign_x[2] -1 ] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] - 2] = 1;game_body[game_sign_y[1]][game_sign_x[1]] = 1;game_body[game_sign_y[2] - 1][game_sign_x[2] - 1] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] + 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[3] <= 17){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] + 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] + 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}}if(blockNumber == 7&&downSign == false)//变换两层砖块2的2种情况{if(game_sign_x[0] == game_sign_x[1]&&game_sign_x[0] <= 16){if(game_body[game_sign_y[0]][game_sign_x[0] + 2] != 2&&game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] != 2&&game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] != 2){num_csh_game();game_body[game_sign_y[0]][game_sign_x[0] + 2] = 1;game_body[game_sign_y[1] - 1][game_sign_x[1] + 1] = 1;game_body[game_sign_y[2]][game_sign_x[2]] = 1;game_body[game_sign_y[3] - 1][game_sign_x[3] - 1] = 1;infoTex.setText("游戏进行中!");repaint();}}if(game_sign_y[0] == game_sign_y[1]&&game_sign_y[2] <= 17)if(game_body[game_sign_y[0] + 1][game_sign_x[0] -1] != 2&&game_body[game_sign_y[1]][game_sign_x[1] -2] != 2&&game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] != 2){num_csh_game();game_body[game_sign_y[0] + 1][game_sign_x[0] - 1] = 1;game_body[game_sign_y[1]][game_sign_x[1] - 2] = 1;game_body[game_sign_y[2] + 1][game_sign_x[2] + 1] = 1;game_body[game_sign_y[3]][game_sign_x[3]] = 1;infoTex.setText("游戏进行中!");repaint();}}}}public void num_csh_game()//数组清零for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){game_body[i][j] = 2;}else{game_body[i][j] = 0;}}}}public void num_csh_restart()//重新开始时数组清零 {for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++)game_body[i][j] = 0;}}}public void keyTyped(KeyEvent e){}public void keyPressed(KeyEvent e){if(e.getKeyCode() == KeyEvent.VK_DOWN&&startSign == 1)//处理下键{this.down();}if(e.getKeyCode() == KeyEvent.VK_LEFT&&startSign == 1)//处理左键{this.left();}if(e.getKeyCode() == KeyEvent.VK_RIGHT&&startSign== 1)//处理右键{this.right();}if(e.getKeyCode() == KeyEvent.VK_UP&&startSign== 1)//处理上键转换{this.change_body(blockNumber);}if(startSign == 0){infoTex.setText("游戏未开始或已结束!");}}public void keyReleased(KeyEvent e){}public void paint(Graphics g){g.setColor(Color.black);g.fill3DRect(0,0,300,450,true);for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){g.setColor(Color.blue);g.fill3DRect(30*j,30*(i-4),30,30,true); }if(game_body[i][j] == 2){g.setColor(Color.magenta);g.fill3DRect(30*j,30*(i-4),30,30,true); }}}}public void left()//向左移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 0||game_body[game_sign_y[k]][game_sign_x[k] - 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] - 1] = 1; }infoTex.setText("向左移动!");repaint();}}public void right()//向右移动{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_x[k] == 9||game_body[game_sign_y[k]][game_sign_x[k] + 1] == 2){sign = 1;}}if(sign == 0&&downSign == false){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k] + 1] = 1; }infoTex.setText("向右移动!");repaint();}}public void down()//下落{int sign = 0;dingwei();for(int k = 0;k < 4;k++){if(game_sign_y[k] == 18||game_body[game_sign_y[k] + 1][game_sign_x[k]] == 2){sign = 1;downSign = true;changeColor();cancelDW();getScore();if(game_over() == false){rand_block();repaint();}}}if(sign == 0){num_csh_game();for(int k = 0;k < 4;k++){game_body[game_sign_y[k] + 1][game_sign_x[k]] = 1;}infoTex.setText("游戏进行中!");repaint();}}public boolean game_over()//判断游戏是否结束{int sign=0;for(int i = 0;i < 10;i++){if(game_body[4][i] == 2){sign = 1;}}if(sign == 1){infoTex.setText("游戏结束!");changeColor();repaint();startSign = 0;timer.suspend();return true;}elsereturn false;}public void getScore()//满行消除方法{for(int i = 0;i < 19;i++){int sign = 0;for(int j = 0;j < 10;j++){if(game_body[i][j] == 2){sign++;}}if(sign == 10){gameScore += 100;scoreTex.setText(gameScore+"");infoTex.setText("恭喜得分!");for(int j = i;j >= 1;j--){for(int k = 0;k < 10;k++){game_body[j][k] = game_body[j - 1][k];}}}}}public void changeColor()//给已经落下的块换色{downSign = false;for(int k = 0;k < 4;k++){game_body[game_sign_y[k]][game_sign_x[k]] = 2; }}public void dingwei()//确定其位置{int k = 0;cancelDW();for(int i = 0;i < 19;i++){for(int j = 0;j < 10;j++){if(game_body[i][j] == 1){game_sign_x[k] = j;game_sign_y[k] = i;k++;}}}}public void cancelDW()//将定位数组初始化{for(int k = 0;k < 4;k++){game_sign_x[k] = 0;game_sign_y[k] = 0;}}public void block1()//长条{game_body[0][4] = 1;game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block2()//正方形{game_body[3][4] = 1;game_body[3][5] = 1;game_body[2][5] = 1;}public void block3()//3加1(下) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[3][5] = 1;}public void block4()//3加1(中) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[3][4] = 1;game_body[2][5] = 1;}public void block5()//3加1(上) {game_body[1][4] = 1;game_body[2][4] = 1;game_body[1][5] = 1;}public void block6()//转折1 {game_body[1][5] = 1;game_body[2][5] = 1;game_body[2][4] = 1;game_body[3][4] = 1;}public void block7()//转折2 {game_body[1][4] = 1;game_body[2][4] = 1;game_body[2][5] = 1;game_body[3][5] = 1;}}//定时线程class MyTimer extends Thread {ERSBlock myBlock;public MyTimer(ERSBlock myBlock){this.myBlock = myBlock;}public void run(){while(myBlock.startSign == 1){try{sleep((10-myBlock.speedMark + 1)*100);myBlock.down();}catch(InterruptedException e){}}}}。

C语言俄罗斯方块游戏源代码

C语言俄罗斯方块游戏源代码

C语言俄罗斯方块游戏源代码/*学无止境*/ #include#include#include#define ESC 27#define UP 328#define DOWN 336#define LEFT 331#define RIGHT 333#define BLANK 32#define BOTTOM 2#define CANNOT 1#define CAN 0#define MAX 30#define F1 315#define ADD 43#define EQUAL 61#define DEC 45#define SOUNDs 115#define SOUNDS 83#define PAUSEP 80#define PAUSEp 112void Init();void Down();void GoOn();void ksdown();void Display(int color);void Give();int Touch(int x,int y,int dx,int dy);int GeyKey();void Select();void DetectFill();void GetScores();void Fail();void Help();void Quit();void DrawBox(int x,int y,int Color);void OutTextXY(int x,int y,char *String); void DispScore(int x,int y,char Ch);void DrawNext(int Color);int Heng=12,Shu=20; /*横竖*/int Position[MAX][MAX];int middle[MAX][MAX];int ActH,ActS;int Act,Staus;int i,j,k;int Wid=10;int NoPass=CAN;float Delays=15000;int BeginH=250,BeginS=7;float Seconds=0;int Scores=0;int flag=1;int Sounds=CAN;int PreAct,NextAct;int a[8][4][4][4]={{{1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0}, {1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,0,0,0,1,0,0,0,1,0,0,0},{1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0}},{{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0},{1,1,0,0,1,1,0,0,0,0,0,0,0,0,0,0}},{{1,1,1,0,0,1,0,0,0,0,0,0,0,0,0,0},{0,1,0,0,1,1,0,0,0,1,0,0,0,0,0,0},{0,1,0,0,1,1,1,0,0,0,0,0,0,0,0,0},{1,0,0,0,1,1,0,0,1,0,0,0,0,0,0,0}}, {{1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}, {0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0}, {1,0,0,0,1,1,0,0,0,1,0,0,0,0,0,0}, {0,1,1,0,1,1,0,0,0,0,0,0,0,0,0,0}}, {{0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0}, {1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0}, {0,1,0,0,1,1,0,0,1,0,0,0,0,0,0,0}, {1,1,0,0,0,1,1,0,0,0,0,0,0,0,0,0}}, {{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0}, {1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0}, {1,1,1,0,0,0,1,0,0,0,0,0,0,0,0,0}, {0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0}}, {{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}, {1,0,0,0,1,0,0,0,1,1,0,0,0,0,0,0}, {1,1,1,0,1,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0}}, {{1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0}}}; int b[4][4];main(int argc,char *argv[]){if (argc!=1){if (argv[1]!="")Heng=atoi(argv[1]);if (argv[2]!="")Shu=atoi(argv[2]);}Init(); /*初始化界面*/PreAct=random(8); /*取得当前的方块*/for(;;) /*以下是游戏流程*/{NextAct=random(8); /*取得下一个方块*/ DrawNext(1); /*画出下一个方块*/Act=PreAct;if (Heng%2==0) ActH=Heng/2;else ActH=(Heng-1)/2;ActS=0; /*方块开始从游戏空间的中间下落*/ Staus=0; /*取开始的状态*/NoPass=CAN; /*物体可以下落*/Give(); /*取得当前的方块*/Display(Act+1); /*显示当前的方块,每种方块的颜色不同*/ GoOn(); /*游戏的算法精髓所在*/PreAct=NextAct; /*方块下落完毕,取得下一个方块*/ DrawNext(0);}}void Init(){int GraphDriver=DETECT,GraphMode;registerbgidriver(EGAVGA_driver);initgraph(&GraphDriver,&GraphMode,"");if (kbhit()) Sounds=CANNOT;setcolor(1);OutTextXY(10,10,"T etris");OutTextXY(30,30,"Version 2.0");OutTextXY(10,120,"Help:");OutTextXY(20,140,"+ :Faster");OutTextXY(20,160,"- :Slower");OutTextXY(20,180,"Esc :Quit");OutTextXY(20,200,"F1 :Help");OutTextXY(10,310,"Copyright(c) 1998.2.22"); OutTextXY(10,320,"By Mr. Unique");outtextxy(10,250,"Score: 00000");rectangle(BeginH-3,BeginS-3,BeginH+Heng*(Wid+2)+2,BeginS+Sh u*(Wid+2)+2);rectangle(BeginH-5,BeginS-5,BeginH+Heng*(Wid+2)+4,BeginS+Sh u*(Wid+2)+4);rectangle(BeginH+(Heng+4)*(Wid+2)-2,BeginS+10,BeginH+(Heng+8)*(Wid+2)+2,BeginS+12+4*(Wid+2));for (i=0;i<max;i++)< bdsfid="173" p=""></max;i++)<>for (j=0;j<max;j++)< bdsfid="175" p=""></max;j++)<>{Position[i][j]=1;middle[i][j]=-1;}for (i=0;i<heng;i++)< bdsfid="180" p=""></heng;i++)<> for (j=0;j<shu;j++)< bdsfid="182" p=""></shu;j++)<>Position[i][j]=0;for (i=0;i<heng;i++)< bdsfid="185" p=""></heng;i++)<> for (j=0;j<shu;j++)< bdsfid="187" p=""></shu;j++)<>DrawBox(i,j,0);randomize();}void GoOn(){for(;;){Seconds+=0.2; /*控制方块的下落速度*/ if (Seconds>=Delays) {Down();Seconds=0;if (NoPass==BOTTOM){DetectFill();middle[ActH][ActS]=Act;if (ActS==0)Fail();return;}}if (kbhit())Select();}}void Down() /*方块下降*/{Display(0);if (Touch(ActH,ActS,0,1)==CAN)ActS++;elsemiddle[ActH][ActS]=Act;Display(Staus+1);}int Touch(int x,int y,int dx,int dy) {NoPass=CAN;for (i=0;i<4;i++)for (j=0;j<4;j++)Position[x+dx+i][y+dy+j]+=b[i][j]; for (i=0;i<max;i++)< bdsfid="226" p=""></max;i++)<>for (j=0;j<max;j++)< bdsfid="228" p=""></max;j++)<>if (Position[i][j]>1)NoPass=CANNOT;for (i=0;i<4;i++)for (j=0;j<4;j++){Position[x+dx+i][y+dy+j]-=b[i][j];middle[x+dx+i][y+dy+j]=Act;if (NoPass==CANNOT && dx==0 && dy==1) { for (i=0;i<4;i++)for (j=0;j<4;j++)Position[x+i][y+j]+=b[i][j];NoPass=BOTTOM;}return NoPass;}int GetKey(void){int Ch,Low,Hig;Ch=bioskey(0);Low=Ch&0x00ff;Hig=(Ch&0xff00)>>8;return(Low==0?Hig+256:Low);}void Select(){int OldStaus,acts=ActS;switch(GetKey())case ESC :Quit();break;case DOWN :Seconds+=14500;break;case LEFT :Display(0);if (ActH>0 && Touch(ActH,ActS,-1,0)==CAN) { ActH--;}Display(Act+1);break;case RIGHT :Display(0);if (ActH<="" bdsfid="262" p="" touch(acth,acts,1,0)="=CAN)" {="">Display(Act+1);break;case BLANK : Display(0);ksdown();Display(Act+1);break;case F1 :Help();break;case EQUAL :case ADD :if (Delays>300) Delays-=100;break; case DEC :if (Delays<3000) Delays+=100;break; case PAUSEP :case PAUSEp :getch();break;case SOUNDS :case SOUNDs :if (Sounds==CAN)Sounds=CANNOT;elseSounds=CAN;break;case UP :if(Act==7){while(acts<shu-1&&position[acth][acts]!=1)< bdsfid="280" p=""></shu-1&&position[acth][acts]!=1)<>acts++;Position[ActH][acts]=0;DrawBox(ActH,acts,0);acts=ActS;break;}else{Display(0);OldStaus=Staus;switch(Act){case 0:case 3:case 4:if (Staus==1) Staus=0;else Staus=1;break; case 1:break;case 2:case 5:case 6:if (Staus==3) Staus=0;else Staus++;break; } Give();if (Touch(ActH,ActS,0,0)==CANNOT){Staus=OldStaus;Give();}Display(Act+1);break;}}}void ksdown(){while(flag){if(Touch(ActH,ActS,0,0)==CAN){ActS++;}else {ActS--;flag=0;}}flag=1;}void Quit(){int ch,TopScore;FILE *fp;if ((fp=fopen("Russian.scr","r+"))!=NULL) {fscanf(fp,"%d",&T opScore);if (Scores>TopScore){setcolor(1);outtextxy(470,80,"Hello !");outtextxy(470,100,"In all the players,"); outtextxy(470,120,"You are the First !"); outtextxy(470,140,"And your score will"); outtextxy(470,160,"be the NEW RECORD !"); fseek(fp,0L,0);fprintf(fp,"%d",Scores);fclose(fp);}setcolor(1);OutTextXY(470,220,"Are You Sure (Yes/no)?"); ch=getch();if (ch=='y'||ch=='Y'){closegraph();delay(20);exit(0);}setcolor(0);outtextxy(470,220,"Are You Sure (Yes/no)?"); }void OutTextXY(int x,int y,char *String) {int i=0;char a[2];moveto(x,y);a[1]='\0';while (*(String+i)!='\0')a[0]=*(String+i);outtext(a);if (Sounds==CAN && a[0]!=' ') {sound(3000);delay(50);nosound();}i++;}}void Help(){unsigned Save;void *Buf;Save=imagesize(160,120,500,360); Buf=malloc(Save);getimage(160,120,500,360,Buf); setfillstyle(1,1);bar(160,120,500,280);setcolor(0);OutTextXY(170,130," About & Help");OutTextXY(170,150," # # # ########## # # # "); OutTextXY(170,160," # ## # # # # # # ###### ### "); OutTextXY(170,170," ########## ########## ## # # ");OutTextXY(170,180," # # # # # # # ## #### "); OutTextXY(170,190," # ## # #### ## # # # "); OutTextXY(170,200," # ## # # # # # ## # # # "); OutTextXY(170,210," # # # ## ## # ###### # # # "); OutTextXY(170,220," ## # ## # ## # # # # "); OutTextXY(170,230," # ## # #### # ## # "); OutTextXY(170,260," Good Luckly to You ");getch();putimage(160,120,Buf,0);free(Buf);}void GetScores(){int Sec10000,Sec1000,Sec100,Sec10,Sec1;setfillstyle(0,1);bar(60,250,109,260);Sec1=Scores%10;Sec10=(Scores%100-Scores%10)/10;Sec100=(Scores%1000-Scores%100)/100;Sec1000=(Scores%10000-Scores%1000)/1000;Sec10000=(Scores%100000-Scores%10000)/10000; DispScore(60,250,'0'+Sec10000);DispScore(70,250,'0'+Sec1000);DispScore(80,250,'0'+Sec100);DispScore(90,250,'0'+Sec10);DispScore(100,250,'0'+Sec1);DispScore(110,250,'0');DispScore(120,250,'0');}void DispScore(int x,int y,char Ch)char a[2];a[1]='\0';a[0]=Ch;outtextxy(x,y,a);}void Give(){for (i=0;i<4;i++)for (j=0;j<4;j++)b[i][j]=a[Act][Staus][i][j];}void Display(int color){for (i=0;i<4;i++)for (j=0;j<4;j++)if (b[i][j]==1) DrawBox(ActH+i,ActS+j,color); } void DrawBox(int x,int y,int Color){x=BeginH+x*(Wid+2);y=BeginS+y*(Wid+2);setfillstyle(1,Color);bar(x+2,y+2,x+Wid-1,y+Wid-1);if (Color==0)setcolor(9);elsesetcolor(Act+1);rectangle(x+4,y+4,x+Wid-4,y+Wid-4);}void DrawNext(int Color)。

基于python语言编写的俄罗斯方块源代码

基于python语言编写的俄罗斯方块源代码

基于python语言编写的俄罗斯方块源代码(以下代码均经过测试,可以直接运行)import pygameimport random# 定义方块的颜色和大小BLOCK_COLORS = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]BLOCK_SIZE = [10, 10]# 初始化Pygamepygame.init()# 设置游戏窗口的尺寸和标题screen_width = 800screen_height = 600screen = pygame.display.set_mode((screen_width, screen_height))pygame.display.set_caption("Russian Blocks")# 定义方块的类class Block:def __init__(self, x, y):self.x = xself.y = yself.color = BLOCK_COLORS[random.randint(0, len(BLOCK_COLORS)-1)]self.size = BLOCK_SIZE[random.randint(0, len(BLOCK_SIZE)-1)] def draw(self, screen):pygame.draw.rect(screen, self.color, (self.x, self.y, self.size, self.size)) def update(self):self.y += 1self.x = self.y * self.size + BLOCK_SIZE[random.randint(0, len(BLOCK_SIZE)-1)] # 创建一个新的方块new_block = Block(200, 0)# 主循环running = Truewhile running:# 处理事件for event in pygame.event.get():if event.type == pygame.QUIT:running = False# 移动方块new_block.update()new_block.draw(screen)# 检查是否有新方块放置在顶部if new_block.x < new_block.size:# 把新方块放置在顶部new_block.y = random.randint(请注意,此代码只是一个简单的示例,可能需要更多的工作和技能才能实现完整的游戏。

俄罗斯方块源代码自用可运行

俄罗斯方块源代码自用可运行

#include<easyx.h>#include<conio.h>#include<time.h>/////////////////////////////////////////////// 定义常量、枚举量、结构体、全局变量/////////////////////////////////////////////#define WIDTH 10// 游戏区宽度#define HEIGHT 22// 游戏区高度#define UNIT 20// 每个游戏区单位的实际像素// 定义操作类型enum CMD{CMD_ROTATE,// 方块旋转CMD_LEFT, CMD_RIGHT, CMD_DOWN,// 方块左、右、下移动CMD_SINK,// 方块沉底CMD_QUIT // 退出游戏};// 定义绘制方块的方法enum DRAW{SHOW,// 显示方块CLEAR,// 擦除方块FIX // 固定方块};// 定义七种俄罗斯方块struct BLOCK{WORD dir[4];// 方块的四个旋转状态COLORREF color;// 方块的颜色} g_Blocks[7]={{0x0F00,0x4444,0x0F00,0x4444, RED },// I {0x0660,0x0660,0x0660,0x0660, BLUE },// 口{0x4460,0x02E0,0x0622,0x0740, MAGENTA },// L{0x2260,0x0E20,0x0644,0x0470, YELLOW },// 反L{0x0C60,0x2640,0x0C60,0x2640, CYAN },// Z{0x0360,0x4620,0x0360,0x4620, GREEN },// 反Z{0x4E00,0x4C40,0x0E40,0x4640, BROWN }};// T// 定义当前方块、下一个方块的信息struct BLOCKINFO{byte id;// 方块 IDchar x, y;// 方块在游戏区中的坐标byte dir :2;// 方向} g_CurBlock, g_NextBlock;// 定义游戏区BYTE g_World[WIDTH][HEIGHT]={0};/////////////////////////////////////////////// 函数声明/////////////////////////////////////////////void Init();// 初始化游戏void Quit();// 退出游戏void NewGame();// 开始新游戏void GameOver();// 结束游戏CMD GetCmd();// 获取控制命令void DispatchCmd(CMD _cmd);// 分发控制命令void NewBlock();// 生成新的方块bool CheckBlock(BLOCKINFO _block);// 检测指定方块是否可以放下void DrawUnit(int x,int y, COLORREF c, DRAW _draw);// 画单元方块void DrawBlock(BLOCKINFO _block, DRAW _draw = SHOW);// 画方块void OnRotate();// 旋转方块void OnLeft();// 左移方块void OnRight();// 右移方块void OnDown();// 下移方块void OnSink();// 沉底方块/////////////////////////////////////////////// 函数定义/////////////////////////////////////////////// 主函数void main(){Init();CMD c;while(true){c = GetCmd();DispatchCmd(c);// 按退出时,显示对话框咨询用户是否退出if(c == CMD_QUIT){HWND wnd = GetHWnd();if(MessageBox(wnd, _T("您要退出游戏吗?"), _T("提醒"), MB_OKCANCEL | MB_ICONQUESTION)== IDOK)Quit();}}}// 初始化游戏void Init(){initgraph(640,480);srand((unsigned)time(NULL));setbkmode(TRANSPARENT);// 设置图案填充的背景色为透明// 显示操作说明settextstyle(14,0, _T("宋体"));outtextxy(20,330, _T("操作说明"));outtextxy(20,350, _T("上:旋转"));outtextxy(20,370, _T("左:左移"));outtextxy(20,390, _T("右:右移"));outtextxy(20,410, _T("下:下移"));outtextxy(20,430, _T("空格:沉底"));outtextxy(20,450, _T("ESC:退出"));// 设置坐标原点setorigin(220,20);// 绘制游戏区边界rectangle(-1,-1, WIDTH * UNIT, HEIGHT * UNIT);rectangle((WIDTH +1)* UNIT -1,-1,(WIDTH +5)* UNIT,4* UNIT);// 开始新游戏NewGame();}// 退出游戏void Quit(){closegraph();exit(0);}// 开始新游戏void NewGame(){// 清空游戏区setfillcolor(BLACK);solidrectangle(0,0, WIDTH * UNIT -1, HEIGHT * UNIT -1);ZeroMemory(g_World, WIDTH * HEIGHT);// 生成下一个方块g_NextBlock.id = rand()%7;g_NextBlock.dir = rand()%4;g_NextBlock.x = WIDTH +1;g_NextBlock.y = HEIGHT -1;// 获取新方块NewBlock();}// 结束游戏void GameOver(){HWND wnd = GetHWnd();if(MessageBox(wnd, _T("游戏结束。

俄罗斯方块源代码全注释超精简版(完整程序+游戏截图)

俄罗斯方块源代码全注释超精简版(完整程序+游戏截图)

俄罗斯方块全注释超精简版(流程清晰,适于初学者,欢迎各位交流:****************,作者:XSH)游戏截图:主程序:Main.cpp#include<windows.h>#include <mmsystem.h>#include<stdio.h>#include<time.h>#include<stdlib.h>#include<conio.h>#include<string.h>#include "colorConsole.h"#define LEFT 75#define RIGHT 77#define DOWN 80#define SPACE 32//全局变量//屏幕#define m_W 12#define m_H 22 //屏幕高和宽bool map[100][100]; //界面数组//结构struct Cube //方块结构为4*4矩阵{bool c[4][4];};//得分int level; //关卡数int score; //分数//难度bool newGame; //检测是否需要重新开始游戏int dif; //速度//颜色HANDLE handle; //当前窗口句柄WORD wColors[8];//颜色WORD newColor; //绘制方块的颜色WORD nextColor; //下一方块颜色//位置int posx, posy; //当前方块(相对map)左上角坐标//方块Cube myCube; //游戏者所控制的方块Cube NextCube; //显示下一个方块Cube trCube; //旋转后的方块//样式int style; //方块样式int nextStyle;//下一个方块的样式Cube baseCube[15]={ //基本方块{0,0,0,0,0,0,1,0,0,1,1,0,0,0,1,0},//凸形{0,0,0,0,0,1,1,0,0,1,1,0,0,0,0,0},//方形{0,0,1,0,0,1,1,0,0,1,0,0,0,0,0,0},//Z1形{0,0,0,0,0,1,1,0,1,1,0,0,0,0,0,0},//Z2形{0,1,0,0,0,1,0,0,0,1,0,0,0,1,0,0},//条形{0,0,0,0,0,0,1,0,0,0,1,0,0,1,1,0},//L1形{0,0,0,0,1,1,1,0,1,0,0,0,0,0,0,0}//L2形};//功能函数//打印绘制图形void InitFrame();//边框初始化void draw_frame(); //打印边框void draw_map(WORD color); //以颜色color扫描打印界面//记录void Get(Cube cube); //获取当前方块的记录void redraw(); //擦去当前方块的记录//检测功能bool meet;bool check_meet(int x, int y, Cube cube);//检测在map中以x,y为左上角的cube是否遇到map 中对应方块bool gameOver;bool check_gameOver();//检测游戏是否结束void remove();//扫描检测并消去当前界面中满行//显示void showScore();//显示得分void showNext();//显示下一个方块//按键信息处理void goDown();void goLeft();void goRight();void transfer(int style); //按space键使方块顺时针旋转90度的算法void kh_Space();//主函数void main(){while(1){PlaySound("俄罗斯方块.wav",NULL,SND_LOOP|SND_ASYNC);handle = initiate(); //绘图初始化wColors[0]=FOREGROUND_RED|FOREGROUND_INTENSITY;//红色wColors[1]=FOREGROUND_BLUE|FOREGROUND_INTENSITY;//蓝色wColors[2]=FOREGROUND_GREEN|FOREGROUND_INTENSITY;//绿色wColors[3]=FOREGROUND_RED|FOREGROUND_GREEN|FOREGROUND_INTENSITY;//黄色wColors[4]=FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUND_INTENSITY;//青色wColors[5]=FOREGROUND_BLUE|FOREGROUND_RED|FOREGROUND_INTENSITY;//紫色wColors[6]=FOREGROUND_RED|FOREGROUND_BLUE|FOREGROUND_GREEN|FOREGROUN D_INTENSITY;//白色wColors[7]=FOREGROUND_RED&FOREGROUND_BLUE&FOREGROUND_GREEN;//黑色newGame=false;memset(map,0,sizeof(map));//界面初始化if(gameOver) return;system("cls");//游戏变量初始化level=1; //关卡数初始化score=0; //分数初始化showScore();//显示分数,关卡数srand((unsigned)time(NULL)); //随机化种子InitFrame(); //界面边框初始化draw_frame(); //绘制边框nextColor=wColors[rand()%7];nextStyle=rand()%7;NextCube=baseCube[nextStyle];//游戏开始while(!newGame){posx=m_W/2-2; //初始坐标posy=1;meet=false;style=nextStyle;//获取样式newColor=nextColor;//获取颜色myCube=NextCube;//获取方块信息Get(myCube);draw_map(newColor);//绘制界面showScore();//获取下一个方块的信息并显示nextStyle=rand()%7;NextCube=baseCube[nextStyle]; nextColor=wColors[rand()%6]; showNext();//处理按键信息char key;while(1){//若没有按键且没到底,则一直下落while(!_kbhit()&&!meet){goDown();Sleep(500);}//若发生按键且没到底if (!meet){key=_getch();//接收按键switch(key){case DOWN: //下键goDown();break;case LEFT: //左键goLeft();break;case RIGHT: //右键goRight();break;case SPACE: //空格键kh_Space();break;case 'p': //暂停键_getch();break;case 'n': //新局键newGame=true;break;case '0' : //结束游戏return;default: break;}//switchif(newGame) break;}//若已经到底else{remove(); //扫描界面,消除满行showScore(); //显示得分if(check_gameOver()) return; //检查游戏是否结束break;}}//while(1)}//while(!newGame)}}//end of main()//各函数定义void InitFrame(){for(int i=0; i<m_W; i++){map[i][0]=1;map[i][m_H-1]=1;}for(int j=0; j<m_H; j++){map[0][j]=1;map[m_W-1][j]=1;}}//边框赋值初始化void Get(Cube cube){for(int i=0; i<4; i++)for(int j=0; j<4; j++)if(cube.c[i][j]==1&&map[posx+i][posy+j]==0)map[posx+i][posy+j]=1;}//获取当前方块void draw_map(WORD color){WORD c[1];c[0]=color;draw_frame();for(int j=1; j<m_H-1; j++)for(int i=1; i<m_W-1; i++)if(map[i][j]==1)textout(handle,20+i*2,j,c,1,"■");elsetextout(handle,20+i*2,j,c,1," ");}//以颜色color扫描打印界面中的方块void draw_frame(){WORD c[1],d[1];c[0]=wColors[rand()%7];d[0]=wColors[3];for(int i=0; i<m_W; i++){if(i%2==0){textout(handle,20+i*2,0,wColors+i%6,1,"◆");}else{textout(handle,20+i*2,0,wColors+i%6,1,"◇");}textout(handle,20+i*2,m_H-1,wColors+i%6,1,"□");}for(int j=1; j<m_H-1; j++){if(j%2==0){textout(handle,20,j,wColors+j%6,1,"★");textout(handle,20+(m_W-1)*2,j,wColors+i%6,1,"☆");}else{textout(handle,20,j,wColors+j%6,1,"☆");textout(handle,20+(m_W-1)*2,j,wColors+j%6,1,"★");}}textout(handle,1,2,c,1,"按键提示:");textout(handle,1,4,d,1,"n--开始新局");textout(handle,1,6,d,1,"p--暂停游戏");textout(handle,1,8,d,1,"方向键-控制方向");textout(handle,1,10,d,1,"空格键-旋转");textout(handle,1,12,d,1,"0--退出游戏");textout(handle,1,14,c,1,"作者:XSH ");}//打印边框void redraw(){for(int j=0; j<4; j++)for(int i=0; i<4; i++)if(myCube.c[i][j]==1)map[posx+i][posy+j]=0;}//擦去当前方块在map中的记录void remove(){int i,j,x,y;WORD c[1];c[0]=wColors[3];for(j=1; j<=m_H-2; j++){for(i=1; i<=m_W-2; i++)if(!map[i][j]) break;if(i>m_W-2){c[0]=wColors[rand()%7];for(int k1=1; k1<=m_W-2; k1++)textout(handle,20+k1*2,j,c,1,"■");Sleep(200);for(int k2=1; k2<m_W-1; k2++){textout(handle,20+k2*2,j,c,1," ");}Sleep(200);score=score+10;for(x=j-1; x>=1; x--){for(y=1; y<=m_W-2; y++){map[y][x+1]=map[y][x];}}draw_map(wColors[1]);}}}//扫描并消去当前界面中满行bool check_meet(int x, int y, Cube cube){for(int i=0; i<4; i++){for(int j=0; j<4; j++){if((cube.c[i][j]==1)&&(map[x+i][y+j]==1)){return true;}}}return false;}//检测在当前方块(map中以x,y为左上角的cube)是否遇到其他方块或墙壁(map中对应方块)bool check_gameOver(){char key;for(int i=1; i<=m_W-2; i++){if(map[i][1]==1){while(1){textout(handle,28,8,wColors+rand()%6,1,"GAME OVER!");textout(handle,15,9,wColors+rand()%6,1,"开始新局请按“n”结束游戏请按“0”");if(_kbhit()){key=_getch();if(key=='n') {newGame=true; return false;}if(key=='0') return true;}}}}return false;}//检测游戏是否结束void showScore(){char string[10];WORD c[1],d[1];c[0]=wColors[rand()%7];d[0]=wColors[rand()%7];for(int i=0; i<=1000; i++){if(score>=i*200&&score<(i+1)*200)break;}if(i!=level-1){level++;if(dif>=0){dif-=10;//每关加速}}textout(handle,20+m_W*2,10,c,1,"Your Score:");textout(handle,20+m_W*2,11,d,1,itoa(score,string,10));textout(handle,20+m_W*2+7,11,d,1,"分");textout(handle,20+m_W*2,0,c,1,"Level:");textout(handle,20+m_W*2,1,d,1,itoa(level,string,10));textout(handle,20+m_W*2+7,1,c,1,"关");}//显示当前分数,关卡数void showNext(){WORD d[1];d[0]=nextColor;textout(handle,20+m_W*2,3,d,1,"Next:");for(int i=0; i<4; i++){for(int j=0; j<4; j++){if(NextCube.c[i][j]==1)textout(handle,20+m_W*2+i*2,5+j,d,1,"■");elsetextout(handle,20+m_W*2+i*2,5+j,d,1," ");}}}//显示下一个方块void goDown(){redraw();if(!check_meet(posx,posy+1,myCube)){posy++;Get(myCube);draw_map(newColor);}else{Get(myCube);draw_map(newColor);meet=true;}}//下键void goLeft(){redraw();if(!check_meet(posx-1,posy,myCube)){posx--;Get(myCube);draw_map(newColor);}else goDown();}//左键void goRight(){redraw();if(!check_meet(posx+1,posy,myCube)){posx++;Get(myCube);draw_map(newColor);}else goDown();}//右键void transfer(int style){for(int i=0; i<4; i++)for(int j=0; j<4; j++)trCube.c[i][j]=myCube.c[j][3-i];} //按space键使方块顺时针旋转90度void kh_Space(){redraw();transfer(style);if(!check_meet(posx, posy, trCube)){myCube=trCube;Get(myCube);draw_map(newColor);}else goDown();}//空格键附件(可以用于任何游戏绘图):(注:附带声音文件俄罗斯方块.wav请自行下载,或发我邮箱~)ColorConsole.h#include <windows.h>#include <iostream.h>HANDLE initiate();BOOL textout(HANDLE hOutput,int x,int y,WORD wColors[],int nColors,LPTSTR lpszString);ColorConsole.cpp#include "colorConsole.h"HANDLE initiate(){HANDLE hOutput;hOutput = GetStdHandle(STD_OUTPUT_HANDLE);return hOutput;}BOOL textout(HANDLE hOutput,int x,int y,WORD wColors[],int nColors,LPTSTR lpszString) {DWORD cWritten;BOOL fSuccess;COORD coord;coord.X = x; // start at first cellcoord.Y = y; // of first rowfSuccess = WriteConsoleOutputCharacter(hOutput, // screen buffer handlelpszString, // pointer to source stringlstrlen(lpszString), // length of stringcoord, // first cell to write to&cWritten); // actual number writtenif (! fSuccess)cout<<"error:WriteConsoleOutputCharacter"<<endl;for (;fSuccess && coord.X < lstrlen(lpszString)+x; coord.X += nColors){fSuccess = WriteConsoleOutputAttribute(hOutput, // screen buffer handlewColors, // pointer to source stringnColors, // length of stringcoord, // first cell to write to&cWritten); // actual number written}if (! fSuccess)cout<<"error:WriteConsoleOutputAttribute"<<endl;return 0;}。

俄罗斯方块python源代码

俄罗斯方块python源代码

俄罗斯方块python源代码以下是一个简单的俄罗斯方块游戏的 Python 源代码。

该代码实现了以下功能:1. 游戏开始时随机生成一个俄罗斯方块方块。

2. 方块可以通过键盘上的箭头键进行移动,向下箭头键可以加速方块的下降速度。

3. 方块到达底部或者与其他方块重叠时,会固定在底部或其他方块上。

4. 当一行被填满时,该行会被删除,并增加玩家的得分。

5. 游戏在方块超过底部边界时结束。

以下是源代码:```import pygameimport random# 初始化 Pygamepygame.init()# 游戏窗口的宽度和高度WIDTH = 640HEIGHT = 480# 方块的大小BLOCK_SIZE = 20# 定义颜色BLACK = (0, 0, 0)WHITE = (255, 255, 255)BLUE = (0, 0, 255)RED = (255, 0, 0)GREEN = (0, 255, 0)# 创建游戏窗口screen = pygame.display.set_mode((WIDTH, HEIGHT)) pygame.display.set_caption("俄罗斯方块")# 创建字体对象font = pygame.font.SysFont(None, 30)# 定义方块的形状SHAPES = [[[1, 1],[1, 1]],[[1, 0],[1, 0],[1, 1]],[[0, 1],[0, 1],[1, 1]],[[1, 1, 0],[0, 1, 1]],[[0, 1, 1],[1, 1, 0]],[[1, 1, 1, 1]]]# 定义方块的颜色COLORS = [BLUE,RED,GREEN,WHITE,BLACK,BLUE]class Block:def __init__(self, x, y):self.x = xself.y = yself.shape = random.choice(SHAPES)self.color = random.choice(COLORS)def draw(self):for i in range(len(self.shape)):for j in range(len(self.shape[i])):if self.shape[i][j] != 0:pygame.draw.rect(screen, self.color, (self.x + j * BLOCK_SIZE, self.y + i * BLOCK_SIZE, BLOCK_SIZE, BLOCK_SIZE))def move_down(self):self.y += BLOCK_SIZEdef move_left(self):self.x -= BLOCK_SIZEdef move_right(self):self.x += BLOCK_SIZEdef rotate(self):self.shape = [[self.shape[j][i] for j in range(len(self.shape))] for i in range(len(self.shape[0])-1, -1, -1)]def is_colliding(self, blocks):for i in range(len(self.shape)):for j in range(len(self.shape[i])):if self.shape[i][j] != 0:x = self.x + j * BLOCK_SIZEy = self.y + i * BLOCK_SIZEif y >= HEIGHT or x < 0 or x >= WIDTH:return Truefor block in blocks:if block != self and block.x == x and block.y == y: return Truereturn Falseclass Game:def __init__(self):self.score = 0self.blocks = []def new_block(self):self.blocks.append(Block(WIDTH // 2 - BLOCK_SIZE, 0))def remove_full_lines(self):y_values = [block.y for block in self.blocks]full_y_values = []for i in range(HEIGHT, 0, -BLOCK_SIZE):if y_values.count(i) == WIDTH // BLOCK_SIZE:full_y_values.append(i)if len(full_y_values) > 0:full_y_values.sort()for y in full_y_values:self.blocks = [block for block in self.blocks if block.y != y] for block in self.blocks:if block.y < y:block.move_down()self.score += 10def game_over(self):if any([block.y <= BLOCK_SIZE for block in self.blocks]):return Truereturn Falsedef draw(self):screen.fill(WHITE)for block in self.blocks:block.draw()pygame.draw.rect(screen, BLACK, (0, 0, WIDTH, HEIGHT), 4) score_text = font.render("Score: " + str(self.score), True, BLACK) screen.blit(score_text, (10, 10))pygame.display.update()def run(self):clock = pygame.time.Clock()running = Trueself.new_block()while running:clock.tick(10)for event in pygame.event.get():if event.type == pygame.QUIT:running = Falseelif event.type == pygame.KEYDOWN:if event.key == pygame.K_LEFT:self.blocks[-1].move_left()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_right()elif event.key == pygame.K_RIGHT:self.blocks[-1].move_right()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_left()elif event.key == pygame.K_DOWN:self.blocks[-1].move_down()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_up()elif event.key == pygame.K_UP:self.blocks[-1].rotate()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].y -= BLOCK_SIZEself.blocks.append(Block(WIDTH // 2 - BLOCK_SIZE, 0)) self.remove_full_lines()if self.game_over():running = Falseself.blocks[-1].move_down()if self.blocks[-1].is_colliding(self.blocks[:-1]):self.blocks[-1].move_up()self.blocks.append(Block(WIDTH // 2 - BLOCK_SIZE, 0)) self.remove_full_lines()if self.game_over():running = Falseself.draw()pygame.quit()if __name__ == "__main__":game = Game()game.run()```代码列表:1. 初始化 Pygame 和定义游戏窗口的宽度和高度。

俄罗斯方块源代码

俄罗斯方块源代码

#include<stdio.h>#include<stdlib.h>#include<graphics.h>#define LEFT 0x4b00#define RIGHT 0x4d00#define DOWN 0x5000#define UP 0x4800#define ESC 0x011b#define ENTER 0x1c0d#define N 20 /*行数*/#define M 10 /*列数*/int wuzhiwenkey; /*用来接收你所按的键*/int zhongkai; /*用来接收当前的物体状态信息*/int warcraft3=4; /*用来接收第一层状态信息*/struct point{int x;int y;int flag; /*画黑格还是有色格子*/int gezi_control; /*判断是否处于结构体gezi的控制下*/};struct point wu[N][M];struct gezi{int x;int y;int flag; /*判断这点是否要画色格*/};struct gezi zhiwen[4][4];struct array /*用来装物体的形状*/{int a[4][4];};struct bossarray /*搞这么多层,其实是为了随机出物体和改变物体的方向有顺序*/{struct array b[4];}shape[7];/*要控制的物体的形状*/int a1[4][4]={ {0,0,0,0},{0,1,0,0},{1,1,1,0},{0,0,0,0} };int a2[4][4]={ {0,1,0,0},{0,1,1,0},{0,1,0,0},{0,0,0,0} };int a3[4][4]={ {0,0,0,0},{1,1,1,0},{0,1,0,0},{0,0,0,0} };int a4[4][4]={ {0,1,0,0},{1,1,0,0},{0,1,0,0},{0,0,0,0} };int b1[4][4]={ {1,1,0,0},{0,1,1,0},{0,0,0,0},{0,0,0,0} };int b2[4][4]={ {0,1,0,0},{1,1,0,0},{1,0,0,0},{0,0,0,0} };int b3[4][4]={ {0,0,0,0},{0,1,1,0},{1,1,0,0},{0,0,0,0} };int b4[4][4]={ {0,1,0,0},{1,1,0,0},{1,0,0,0},{0,0,0,0} };int c1[4][4]={ {0,1,1,0},{1,1,0,0},{0,0,0,0},{0,0,0,0} };int c2[4][4]={ {1,0,0,0},{1,1,0,0},{0,1,0,0},{0,0,0,0} };int c3[4][4]={ {0,0,0,0},{1,1,0,0},{0,1,1,0},{0,0,0,0} };int c4[4][4]={ {0,1,0,0},{1,1,0,0},{1,0,0,0},{0,0,0,0} };int d1[4][4]={ {0,1,1,0},{0,0,1,0},{0,0,1,0},{0,0,0,0} };int d2[4][4]={ {0,0,0,0},{0,0,1,0},{1,1,1,0},{0,0,0,0} };int d3[4][4]={ {1,0,0,0},{1,0,0,0},{1,1,0,0},{0,0,0,0} };int d4[4][4]={ {1,1,1,0},{1,0,0,0},{0,0,0,0},{0,0,0,0} };int e1[4][4]={ {1,1,0,0},{1,0,0,0},{1,0,0,0},{0,0,0,0} };int e2[4][4]={ {1,1,1,0},{0,0,1,0},{0,0,0,0},{0,0,0,0} };int e3[4][4]={ {0,0,1,0},{0,0,1,0},{0,1,1,0},{0,0,0,0} };int e4[4][4]={ {0,0,0,0},{1,0,0,0},{1,1,1,0},{0,0,0,0} };int f1[4][4]={ {0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0} };int f2[4][4]={ {0,1,0,0},{0,1,0,0},{0,1,0,0},{0,1,0,0} };int f3[4][4]={ {0,0,0,0},{1,1,1,1},{0,0,0,0},{0,0,0,0} };int f4[4][4]={ {0,1,0,0},{0,1,0,0},{0,1,0,0},{0,1,0,0} };int g1[4][4]={ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} };int g2[4][4]={ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} };int g3[4][4]={ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} };int g4[4][4]={ {0,0,0,0},{0,1,1,0},{0,1,1,0},{0,0,0,0} };void setshape(int a[4][4],int temp[4][4]) /*把上面的数组的形状装到shape 里*/{int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++)a[i][j]=temp[i][j];}void setshape2() /*给shape给他形状*/{setshape(shape[0].b[0].a,a1);setshape(shape[0].b[1].a,a2);setshape(shape[0].b[2].a,a3);setshape(shape[0].b[3].a,a4);setshape(shape[1].b[0].a,b1);setshape(shape[1].b[1].a,b2);setshape(shape[1].b[2].a,b3);setshape(shape[1].b[3].a,b4);setshape(shape[2].b[0].a,c1);setshape(shape[2].b[1].a,c2);setshape(shape[2].b[2].a,c3);setshape(shape[2].b[3].a,c4);setshape(shape[3].b[0].a,d1);setshape(shape[3].b[1].a,d2);setshape(shape[3].b[2].a,d3);setshape(shape[3].b[3].a,d4);setshape(shape[4].b[0].a,e1);setshape(shape[4].b[1].a,e2);setshape(shape[4].b[2].a,e3);setshape(shape[4].b[3].a,e4);setshape(shape[5].b[0].a,f1);setshape(shape[5].b[1].a,f2);setshape(shape[5].b[2].a,f3);setshape(shape[5].b[3].a,f1);setshape(shape[6].b[0].a,g1);setshape(shape[6].b[1].a,g2);setshape(shape[6].b[2].a,g3);setshape(shape[6].b[3].a,g4);}/*改变格子数组flag的值,使之能显示物体的形状*/void zhiwen_flag(){void temp1(int a[4][4]); /*函数声明*/int estimate_error();void end();int k;randomize();k=random(6);zhongkai=k; /*保存当前的要下落的物体的形状信息*/ warcraft3=4; /*还原状态的初值*/switch(k){case 0: temp1(shape[0].b[0].a);break;case 1: temp1(shape[1].b[0].a);break;case 2: temp1(shape[2].b[0].a);break;case 3: temp1(shape[3].b[0].a);break;case 4: temp1(shape[4].b[0].a);break;case 5: temp1(shape[5].b[0].a);break;case 6: temp1(shape[6].b[0].a);break;}if(estimate_error()){end();}}void temp1(int a[4][4]) /*跟着zhiwen_flag函数,是他的小弟*/ {int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++){if(a[i][j]==1)zhiwen[i][j].flag=1;elsezhiwen[i][j].flag=0;}}void zhiwenflag_enter(){warcraft3++;temp1(shape[zhongkai].b[warcraft3%4].a);}/*这函数用来改变方框的gezi_control的值,为画方框做准备*/ void change(){int i,j,k,p;for(k=0;k<4;k++)for(p=0;p<4;p++)if(zhiwen[k][p].flag==1)for(i=0;i<N;i++)for(j=0;j<M;j++)if( (zhiwen[k][p].x==wu[i][j].x) && (zhiwen[k][p].y==wu[i][j].y) )wu[i][j].gezi_control=1;}void draw() /*画出图形*/{int i,j;for(i=0;i<N;i++)for(j=0;j<M;j++)if(wu[i][j].flag==0){setfillstyle(0,BLACK);bar(wu[i][j].x,wu[i][j].y,wu[i][j].x+20,wu[i][j].y+20);setcolor(BLACK);rectangle(wu[i][j].x,wu[i][j].y,wu[i][j].x+20,wu[i][j].y+20);}for(i=0;i<N;i++)for(j=0;j<M;j++){if(wu[i][j].gezi_control==1){setfillstyle(11,YELLOW);bar(wu[i][j].x,wu[i][j].y,wu[i][j].x+20,wu[i][j].y+20);setcolor(RED);rectangle(wu[i][j].x,wu[i][j].y,wu[i][j].x+20,wu[i][j].y+20);}if(wu[i][j].flag){setfillstyle(11,YELLOW);bar(wu[i][j].x,wu[i][j].y,wu[i][j].x+20,wu[i][j].y+20);setcolor(RED);rectangle(wu[i][j].x,wu[i][j].y,wu[i][j].x+20,wu[i][j].y+20);}}}void wuzhiwen200910214117() /*给zhiwen数组给初值,位置是最上面的格子*/ {int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++){zhiwen[i][j].x=wu[i][j+2].x;zhiwen[i][j].y=wu[i][j+2].y;zhiwen[i][j].flag=0;}}void cleargezi_control() /*物体下落后,把wu的gezi_control恢复原来的值*/ {int i,j;for(i=0;i<N;i++)for(j=0;j<M;j++)wu[i][j].gezi_control=0;}void setflag() /*下落的物本固定住*/{int i,j;for(i=0;i<N;i++)for(j=0;j<M;j++)if(wu[i][j].gezi_control==1)wu[i][j].flag=1;}int tmd() /*看格子的flag与方框的flag是否重复*/{int i,j,k,p;for(k=0;k<4;k++)for(p=0;p<4;p++)if(zhiwen[k][p].flag==1)for(i=0;i<N;i++)for(j=0;j<M;j++)if(wu[i][j].flag==1)if( (wu[i][j].x==zhiwen[k][p].x) && (wu[i][j].y==zhiwen[k][p].y) )return(1);return(0);}int estimate_error() /*判断zhiwen数组下移后是否与方框的格子重复*/{int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++)if(tmd())return(1);return(0);}int isunder() /*判断是否到了低了*/{int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++)if( (zhiwen[i][j].flag==1) && (zhiwen[i][j].y==wu[N-1][1].y) )return(1);return(0);}int turnleft_error() /*功能是判断向左时合不合理*/{int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++)if(zhiwen[i][j].flag==1)if(zhiwen[i][j].x==wu[1][0].x-20)return(1);return(0);}int turnright_error() /*功能是判断向右时合不合理*/{int i,j;for(i=0;i<4;i++)for(j=0;j<4;j++)if(zhiwen[i][j].flag==1)if(zhiwen[i][j].x==wu[1][M-1].x+20)return(1);return(0);}void deleteline() /*删除一行!妈呀终于到了最后一个函数了!!*/ {void deleteline2(int wuzhiwen);int i,j,sum=0;for(i=0;i<N;i++){for(j=0,sum=0;j<M;j++)sum+=wu[i][j].flag;if(sum==M){deleteline2(i);draw();sleep(1);}}}void deleteline2(int wuzhiwen) /*wuzhiwen是所在行,此函数专为deleteline()服务*/{int i,j;for(j=0;j<M;j++)wu[wuzhiwen][j].flag=0;for(i=wuzhiwen-1;i>=0;i--)for(j=0;j<M;j++)if(wu[i][j].flag==1){wu[i][j].flag=0;wu[i+1][j].flag=1;}}void end(){clrscr();outtextxy(200,200,"press any key to exit!");getch();exit(1);}void main(){int i,j; /*中间数据*/int graphdriver=DETECT,graphmode; void playgame();/*给point结构体数组给初值;*/for(i=1,wu[0][0].x=200;i<M;i++)wu[0][i].x=wu[0][i-1].x+20;for(i=1;i<N;i++)for(j=0;j<M;j++)wu[i][j].x=wu[0][j].x;for(i=1,wu[0][0].y=20;i<N;i++)wu[i][0].y=wu[i-1][0].y+20;for(j=1;j<M;j++)for(i=0;i<N;i++)wu[i][j].y=wu[i][0].y;for(i=0;i<N;i++)for(j=0;j<M;j++){wu[i][j].flag=0;wu[i][j].gezi_control=0;}setshape2(); /*给每一个形状初值*/wuzhiwen200910214117(); /*给zhiwen数组给初值*/zhiwen_flag(); /* 给格子数组初值 *//*图形驱动*/initgraph(&graphdriver,&graphmode,"");setcolor(YELLOW);outtextxy(10,40,"writer: wuzhiwen");outtextxy(10,60,"number: 200910214117");outtextxy(10,80,"finish in 2010-6-29");outtextxy(10,100,"from: zhongkai_school");outtextxy(10,120,"class: jiji 091.");setcolor(WHITE);outtextxy(10,200,"how to play:");outtextxy(10,220," press ENTER to change");outtextxy(10,240," press RIGHT or LEFT ");outtextxy(10,260," press ESC to exit");sleep(3);setcolor(WHITE);rectangle(wu[0][0].x-5 , wu[0][0].y-5 ,wu[N-1][M-1].x+25 , wu[N-1][M-1].y+25);playgame();}void playgame(){int i,j,k,p,i1,j1; /*中间数据*/while(1){cleargezi_control();change();draw(); /*画图*/sleep(1);/*格子数组的y值增加20。

俄罗斯方块游戏原代码

俄罗斯方块游戏原代码

#include<stdio.h>#include<stdlib.h>#include<dos.h>#include<graphics.h> /*系统提供的头文件*/#define TIMER 0x1c /*定义时钟中断的中断号*/#define VK_LEFT 0x4b00/*左移键*/#define VK_RIGHT 0x4d00/*右移键*/#define VK_DOWN 0x5000 /*加速键*/#define VK_UP 0x4800 /*变形键*/#define VK_SPACE 0x3920 /*变形键*/#define VK_END 0x4f00 /*暂停键*/#define VK_ESC 0x011b#define VK_ENTER 0x1c0d#define BSIZE 16 /*方块的边长是16个象素*/#define MAX_SHAPE 19 /*总共有19种各形态的方块*/#define BOARD_WIDTH 10 /*游戏面板的宽度,以方块的宽度为单位*/#define BOARD_HEIGHT 20/*游戏面板的高度,以方块的宽度为单位*/#define BGCOLOR BLACK /*背景色*/#define FORECOLOR WHITE /*前景色*/#define FALSE 0#define TRUE 1#define EMPTY 0#define FILLED 1#define BOARD_LEFT_X 10 /*游戏面板左上角的横坐标*/#define BOARD_LEFT_Y 5 /*游戏面板左上角的纵坐标*//*定义全局变量*/extern int Gameboard[BOARD_WIDTH+2][BOARD_HEIGHT+2];extern int nCurrent_block_index ; /*当前下落的方块的索引号*/ extern int nNext_block_index ; /*下一个方块的索引号*/extern int nSpeed, nScore; /*速度和得分*/extern int nSpeedUpScore; /*第一次要加速需达到的分数*/extern int bAccel, bOver;extern int nOriginX, nOriginY;/*某一形状的原点的绝对坐标*/ extern unsigned int TimerCounter; /* 计时变量,每秒钟增加18 */struct block{int arrXY[8];int nColor;int nNext;}; /*保存某一形状信息的结构体*/typedef struct block BLOCK;extern BLOCK arrayBlock[19];void interrupt newtimer(void);void SetTimer(void interrupt(*IntProc)(void));void KillTimer();void InitializeGraph();void InitializeGameboard() ;void DrawSquare(int x, int y);void DrawBlock(int BlockIndex, int sx, int sy,int color); int IsConflict(int BlockIndex, int x, int y);void HandleLeft(int BlockIndex,int *x, int *y);void HandleRight(int BlockIndex,int *x, int *y);void HandleUp(int *BlockIndex,int *x, int *y);int HandleDown(int BlockIndex,int *x, int *y);int IsLineFull(int y);void KillLine(int y);int KillLines(int y);int IsGameOver();int GameOver();void StartGame();void ProcessInGame();void game();void win();void help();void design();void show_win();void main(){win();menu();}void help(){clrscr();help();textcolor(WHITE);gotoxy(20,4);cprintf("\xDB\xDB\xDB\xDB\xB2 HELP ABOUT THE Game \xB2\xDB\xDB\xDB\xDB"); gotoxy(4,6);cprintf(" [ 1 ] - Metamorphose : Press the left key square moves left "); gotoxy(30,8);cprintf("Press the left key square move to the right");gotoxy(30,10);cprintf("Press down key square accelerate whereabouts");gotoxy(4,12);cprintf(" [ 2 ] - Speed up : Press the button oblong rotating ");gotoxy(4,14);cprintf(" [ 3 ] - Game Start : Press Enter to button to start the game"); gotoxy(4,16);cprintf(" [ 4 ] - Game Over : Press the ESC key to quit the game");gotoxy(30,18);cprintf("YOU WANT TO BE HELPFUL");gotoxy(6,23);printf("Press any key to go to the MAIN MENU ........");getche();}menu(){int x;do{{clrscr();design();textcolor(WHITE);cprintf("\xDB\xDB\xDB\xDB\xB2 Tetris Game \xB2\xDB\xDB\xDB\xDB");gotoxy(3,4);cprintf("--------------------------------------------------------------------------");gotoxy(35,5);cprintf("MAIN MENU");gotoxy(26,8);cprintf(" 1 - New Game ");gotoxy(26,9);cprintf(" 2 - Rank ");gotoxy(26,10);cprintf(" 3 - HELP ");gotoxy(26,11);cprintf(" 4 - The Game Explain ");gotoxy(26,12);cprintf(" 5 - EXIT ");x=toupper(getch());switch(x){case '1':game();break;case '2':cprintf("At present there is no ranking");break;case '3':help();break;case '4':cprintf("This game by LuWenJun,ChenLong,QiWei jointly compiled,Deficiencies still please forgive me");break;case '5':exit(0);break;default:clrscr();design();gotoxy(17,12);printf("\a\xDB\xB2 WRONG ENTRY : PRESS ANY KEY AND TRY AGAIN"); getche();}}}while(x!='5');return x;}void win(){int i,graphdriver,graphmode,size,page;char s1[30],s2[30];graphdriver=DETECT;initgraph(&graphdriver,&graphmode,"c:\\turboc2");cleardevice();setbkcolor(BLUE);setviewport(40,40,600,440,1);setfillstyle(1,2);setcolor(YELLOW);rectangle(0,0,560,400);floodfill(50,50,14);rectangle(20,20,540,380);setfillstyle(1,13);floodfill(21,300,14);setcolor(BLACK);settextstyle(1,0,6);outtextxy(100,60,"Welcom You");setviewport(100,200,540,380,0);setcolor(14);setfillstyle(1,12);rectangle(20,20,420,120);settextstyle(2,0,9);floodfill(21,100,14);sprintf(s1,"Let's our play Tetris Game!");setcolor(YELLOW);outtextxy(60,40,s1);sprintf(s2,"Press any key to play....");setcolor(1);settextstyle(4,0,3);outtextxy(110,80,s2);getch();closegraph();}void design(){int i;clrscr();textcolor(14);gotoxy(2,2);cprintf("\xC9");gotoxy(3,2);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,2);cprintf("\xBB");gotoxy(2,3);cprintf("\xBA");gotoxy(2,4);cprintf("\xBA");gotoxy(2,5);cprintf("\xBA");gotoxy(2,6);cprintf("\xBA");gotoxy(2,7);cprintf("\xBA");gotoxy(2,8);cprintf("\xB A");gotoxy(2,9);cprintf("\xBA");gotoxy(2,10);cprintf("\xBA");gotoxy(2,11);cprintf("\ xBA");gotoxy(2,12);cprintf("\xBA");gotoxy(2,13);cprintf("\xBA");gotoxy(2,14);cprintf("\xBA");gotoxy(2,15);cprintf(" \xBA");gotoxy(2,16);cprintf("\xBA");gotoxy(2,17);cprintf("\xBA");gotoxy(2,18);cprintf("\xBA");gotoxy(2,22);cprintf(" \xCC");gotoxy(2,19);cprintf("\xBA");gotoxy(2,20);cprintf("\xBA");gotoxy(2,21);cprintf(" \xBA");gotoxy(2,24);cprintf("\xC8");gotoxy(2,23);cprintf("\xBA");gotoxy(3,24);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,18);cprintf("\xBA");gotoxy(77,19);cprintf("\xBA");gotoxy(77,20);cprint f("\xBA");gotoxy(77,21);cprintf("\xBA");gotoxy(77,24);cprintf("\xBC");gotoxy(77,23);cprintf("\xBA");gotoxy(3,22);for(i=1;i<=74;i++)cprintf("\xCD");gotoxy(77,22);cprintf("\xB9");gotoxy(77,3);cprintf("\xBA");gotoxy(77,4);cprintf("\xBA");gotoxy(77,5);cprintf("\xBA");gotoxy(77,6);cprintf("\xBA");gotoxy(77,7);cprintf("\xBA");gotoxy(77,8);cprintf(" \xBA");gotoxy(77,9);cprintf("\xBA");gotoxy(77,10);cprintf("\xBA");gotoxy(77,11);cprintf ("\xBA");gotoxy(77,12);cprintf("\xBA");gotoxy(77,13);cprintf("\xBA");gotoxy(77,14);cprintf("\xBA");gotoxy(77,15);cprint f("\xBA");gotoxy(77,16);cprintf("\xBA");gotoxy(77,17);cprintf("\xBA");textcolor(RED);}void show_win(void){union REGS in, out;in.x.ax = 0x1;int86(0x33, &in, &out);}/*********************************************************** 函数原型:void InitializeGraph() * * 传入参数:无 ** 返回值:无 ** 函数功能:初始化进入图形模式***********************************************************/void InitializeGraph(){int gdriver = VGA, gmode=VGAHI, errorcode;/* 初始化图形模式*/initgraph(&gdriver, &gmode, "c:\\turboc2");/* 读取初始化结果 */errorcode = graphresult();if (errorcode != grOk) /* 错误发生 */{printf("Graphics error: %s\n", grapherrormsg(errorcode));printf("Press any key to halt:");getch();exit(1); /* 返回错误码 */}}/*********************************************************** 函数原型:void InitializeGameboard() ** 传入参数:无** 返回值:无** 函数功能:初始化游戏面板以及下一形状提示框、计分框和难度框 ***********************************************************/void InitializeGameboard(){/* 绘制游戏面板(即游戏区域)*/setfillstyle(SOLID_FILL,BGCOLOR);bar(BSIZE*BOARD_LEFT_X,BSIZE*BOARD_LEFT_Y,BSIZE*(BOARD_LEFT_X+BOARD_WIDTH),BSIZE*(BOARD_LEFT_Y+BOARD_HEIGHT));setcolor(WHITE);rectangle(BSIZE*BOARD_LEFT_X,BSIZE*BOARD_LEFT_Y,BSIZE*(BOARD_LEFT_X+BOARD_WIDTH),BSIZE*(BOARD_LEFT_Y+BOARD_HEIGHT));/*绘制下一形状提示框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(5+1), "next");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*(24.5+2), BSIZE*6, BSIZE*(24.5+2+5), BSIZE*(6+5));setcolor(YELLOW);rectangle(BSIZE*(24.5+2), BSIZE*6, BSIZE*(24.5+2+5), BSIZE*(6+5));/*绘制速度框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(12+1), "level");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1)); setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(13+1), "0");/*绘制计分框*/setcolor(BLUE);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(19+1), "score");setfillstyle(SOLID_FILL, BGCOLOR);bar(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1)); setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(20+1), "0");}int Gameboard[BOARD_WIDTH+2][BOARD_HEIGHT+2];int nCurrent_block_index;/* 当前下落的方块的索引号*/int nNext_block_index ; /*下一个方块的索引号*/int nSpeed, nScore; /*速度和得分*/int nSpeedUpScore = 1000; /*第一次要加速需达到的分数*/int bAccel, bOver;int nOriginX=5, nOriginY=1;/*某一形状的原点的绝对坐标*/ BLOCK arrayBlock[19]={/*x1,y1,x2,y2,x3,y3,x4,y4, color, next*/{ 0,-2, 0,-1, 0, 0, 1, 0, CYAN, 1}, /* */{-1, 0, 0, 0, 1,-1, 1, 0, CYAN, 2}, /* # */{ 0,-2, 1,-2, 1,-1, 1, 0, CYAN, 3}, /* # */{-1,-1,-1, 0, 0,-1, 1,-1, CYAN, 0}, /* ## */{ 0,-2, 0,-1, 0, 0, 1,-2,MAGENTA, 5}, /* */{-1,-1,-1, 0, 0, 0, 1, 0,MAGENTA, 6}, /* ## */{ 0, 0, 1,-2, 1,-1, 1, 0,MAGENTA, 7}, /* # */{-1,-1, 0,-1, 1,-1, 1, 0,MAGENTA, 4}, /* # */{-1, 0, 0,-1, 0, 0, 1, 0,YELLOW, 9}, /* */{-1,-1, 0,-2, 0,-1, 0, 0,YELLOW, 10}, /* */{-1,-1, 0,-1, 0, 0, 1,-1,YELLOW, 11}, /* # */{ 0,-2, 0,-1, 0, 0, 1,-1,YELLOW, 8}, /* ### */{-1, 0, 0,-1, 0, 0, 1,-1, BROWN, 13}, /* ## */{ 0,-2, 0,-1, 1,-1, 1, 0, BROWN, 12}, /* ## */{-1,-1, 0,-1, 0, 0, 1, 0, WHITE, 15}, /* ## */{ 0,-1, 0, 0, 1,-2, 1,-1, WHITE, 14}, /* ## */{ 0,-3, 0,-2, 0,-1, 0, 0, RED, 17},/* # */{-1, 0, 0, 0, 1, 0, 2, 0, RED, 16},/* # *//* # *//* # */{ 0,-1, 0, 0, 1,-1, 1, 0, BLUE, 18},/* ## *//* ## */};/*********************************************************** 函数原型:void StartGame () ** 传入参数:无** 返回值:无 ** 函数功能:游戏开始时调用的函数,其中绘制界面需调用函数 ** InitializeGameboard(), 接下来需初始化游戏面板的 ** 各个方块和一些全局变量的初值 ***********************************************************/void StartGame(){int i,j;/*设置游戏面板中每个方块的初始值*/for(j=0;j<=BOARD_HEIGHT;j++)for(i=0;i<BOARD_WIDTH+2;i++){if(i==0 || i==BOARD_WIDTH+1)Gameboard[i][j] = FILLED;elseGameboard[i][j] = EMPTY;}for(i=0;i<BOARD_WIDTH+2;i++)Gameboard[i][BOARD_HEIGHT+1] = FILLED;InitializeGameboard();/*设置游戏变量的初值*/nNext_block_index = -1; /*游戏初始,没有下一个形状的索引号*/nSpeed = 0;nScore = 0;}/*********************************************************** 函数原型:void ProcessInGame() ** 传入参数:无** 返回值:无** 函数功能:核心函数,主要用于处理在游戏中的各种事件(如按下各种按键) ***********************************************************/void ProcessInGame(){int key;bioskey(0);randomize();while(1){if(nNext_block_index==-1){nCurrent_block_index = rand()%19;nNext_block_index = rand()%19;/*绘制下一个提示形状*/DrawBlock(nNext_block_index,19,6,arrayBlock[nNext_block_index].nColor );}else{nCurrent_block_index = nNext_block_index;DrawBlock(nNext_block_index, 19,6,BGCOLOR ); /* 消除原来的提示形状 */nNext_block_index = rand()%19;DrawBlock(nNext_block_index,19,6,arrayBlock[nNext_block_index].nColor ); /*绘制下一个提示形状 */}nOriginX=5, nOriginY=1;TimerCounter = 0;DrawBlock(nCurrent_block_index, nOriginX,nOriginY, arrayBlock[nCurrent_block_index].nColor );/*在面板内绘制当前形状*/while(1){if (bioskey(1))key=bioskey(0);else key=0;bAccel = FALSE;switch(key){case VK_LEFT: /* 左移 */HandleLeft(nCurrent_block_index,&nOriginX,&nOriginY );break;case VK_RIGHT: /* 右移 */HandleRight(nCurrent_block_index,&nOriginX,&nOriginY );break;case VK_UP: /* 旋转 */case VK_SPACE:HandleUp(&nCurrent_block_index, &nOriginX,&nOriginY);break;case VK_DOWN: /* 下落加速键 */bAccel=TRUE;break;case VK_END: /* 暂停*/bioskey(0);break;case VK_ESC: /* 退出游戏 */bOver=TRUE;return;}if(bAccel || TimerCounter>(20-nSpeed*2))if(HandleDown(nCurrent_block_index,&nOriginX,&nOriginY))break;if(bOver)return;}}}/*********************************************************** 函数原型:void main() ** 传入参数:无 ** 返回值:无 ** 函数功能:入口函数,包含俄罗斯方块程序的主流程 ***********************************************************/void game(){InitializeGraph();SetTimer(newtimer); /*设置新的时钟中断*/while(1){StartGame();ProcessInGame();if(GameOver())break;bOver = FALSE;}KillTimer();closegraph();}unsigned int TimerCounter=0; /* 计时变量,每秒钟增加18 *//*********************************************************** 函数原型:void interrupt (*oldtimer)(void) ** 传入参数:无** 返回值:无** 函数功能:指向原来时钟中断处理过程入口的中断处理函数指针(句柄) ***********************************************************/void interrupt (*oldtimer)(void);/*********************************************************** 函数原型:void interrupt newtimer(void) ** 传入参数:无 ** 返回值:无 ** 函数功能:新的时钟中断处理函数 ***********************************************************/void interrupt newtimer(void){(*oldtimer)();TimerCounter++;}/*********************************************************** 函数原型:void SetTimer(void interrupt(*)(void)) ** 传入参数:无 ** 返回值:无 ** 函数功能:设置新的时钟中断处理函数 ***********************************************************/void SetTimer(void interrupt(*IntProc)(void)){oldtimer=getvect(TIMER);disable();setvect(TIMER,IntProc);enable();}/*********************************************************** 函数原型:void KillTimer() ** 传入参数:无 ** 返回值:无 ** 函数功能:恢复原先的时钟中断处理函数 ***********************************************************/void KillTimer(){disable();setvect(TIMER,oldtimer);enable();}/*********************************************************** 函数原型:void DrawSquare(int x, int y) ** 传入参数:游戏面板中的横坐标x,纵坐标y ** 返回值:无 ** 函数功能:在坐标(x, y)处绘制方块 ***********************************************************/void DrawSquare(int x, int y){if(y<1)return;bar(BSIZE*(x+9)+1,BSIZE*(y+4)+1,BSIZE*(x+10)-1,BSIZE*(y+5)-1);}/*********************************************************** 函数原型:void DrawBlock(int BlockIndex, int sx, int sy,int color) ** 传入参数:形状的索引BlockIndex,绝对横坐标x,绝对纵坐标y,颜色color ** 返回值:无** 函数功能:在坐标(sx, sy)处绘制颜色为color的形状***********************************************************/void DrawBlock(int BlockIndex, int sx, int sy,int color){int i,c;setfillstyle(SOLID_FILL, color);for(i=0;i<7;i+=2)DrawSquare(arrayBlock[BlockIndex].arrXY[i]+sx,arrayBlock[BlockIndex].arrXY[i+1]+sy);}/*********************************************************** 函数原型:int IsConflict(int BlockIndex, int x, int y) ** 传入参数:形状的索引BlockIndex,绝对横坐标x,绝对纵坐标y ** 返回值:无冲突返回0,有冲突返回1 ** 函数功能:判断形状是否能存在于坐标(x, y)处 * **********************************************************/int IsConflict(int BlockIndex, int x, int y){int i;for (i=0;i<=7;i++,i++){if (arrayBlock[BlockIndex].arrXY[i]+x<1 || arrayBlock[BlockIndex].arrXY[i]+x>10)return TRUE;if (arrayBlock[BlockIndex].arrXY[i+1]+y<1)continue;if(Gameboard[arrayBlock[BlockIndex].arrXY[i]+x][arrayBlock[BlockIndex].arrXY[i+1]+ y])return TRUE;}return FALSE;}/*********************************************************** 函数原型:int HandleLeft(int BlockIndex,int *x, int *y) * * 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下左方向键时的处理函数***********************************************************/void HandleLeft(int BlockIndex,int *x, int *y) /*按下左方向键时的处理函数*/{if(!IsConflict(BlockIndex,*x-1,*y)){DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*x)--;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleRight(int BlockIndex,int *x, int *y) ** 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下右方向键时的处理函数***********************************************************/void HandleRight(int BlockIndex,int *x, int *y)/*按下右方向键时的处理函数*/{if(!IsConflict(BlockIndex,*x+1,*y)){DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*x)++;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleUp(int BlockIndex,int *x, int *y) ** 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:无** 函数功能:按下上方向键(旋转键)时的处理函数***********************************************************/void HandleUp(int *BlockIndex,int *x, int *y) /*按下旋转键时的处理函数*/{int NextBlockIndex, i;static int arrayOffset[5]={0,-1,1,-2,2};NextBlockIndex = arrayBlock[*BlockIndex].nNext;for(i=0;i<5;i++)if(!IsConflict(NextBlockIndex, *x+arrayOffset[i],*y)){DrawBlock(*BlockIndex, *x, *y, BGCOLOR); /*擦除原先的形状*/*BlockIndex = arrayBlock[*BlockIndex].nNext;(*x) += arrayOffset[i];DrawBlock(*BlockIndex, *x, *y, arrayBlock[*BlockIndex].nColor); /*绘制当前形状*/}}/*********************************************************** 函数原型:int HandleDown(int BlockIndex,int *x, int *y) * * 传入参数:形状的索引BlockIndex,绝对横坐标的指针*x,绝对纵坐标的 ** 指针*y ** 返回值:仍在自由下落返回0,无法下落了返回1 ** 函数功能:按下向下方向键或自由下落时的处理函数***********************************************************/int HandleDown(int BlockIndex,int *x, int *y)/*按下下方向键或自由下落时的处理函数*/{char ScoreBuffer[10]={0},SpeedBuffer[10]={0};int i;int NumLinesKilled=0;/*if(TimerCounter>(20-nSpeed*2))*/{TimerCounter = 0; /*重置时钟中断*/if(!IsConflict(BlockIndex,*x,*y+1)) /*仍在下落*/{DrawBlock(BlockIndex,*x,*y,BGCOLOR); /*擦除原先的形状*/(*y)++;DrawBlock(BlockIndex, *x, *y, arrayBlock[BlockIndex].nColor); /*绘制当前形状*/return FALSE;/*仍在下落返回FALSE*/}else /*无法再下落了*/{DrawBlock(BlockIndex,*x,*y,FORECOLOR);for (i=0;i<=7;i++,i++){if ((*y)+arrayBlock[BlockIndex].arrXY[i+1]<1)continue;Gameboard[(*x)+arrayBlock[BlockIndex].arrXY[i]][(*y)+arrayBlock[BlockIndex].arrX Y[i+1]]=1;}NumLinesKilled = KillLines(*y);if(NumLinesKilled>0){switch(NumLinesKilled){case 1:nScore+=100;case 2:nScore+=300;case 3:nScore+=500;case 4:nScore+=800;}/*重绘计分框*/setfillstyle(SOLID_FILL,BLACK);bar(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*20, BSIZE*(25+8), BSIZE*(20+1));itoa(nScore,ScoreBuffer, 10);setcolor(RED);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(20+1), ScoreBuffer);if(nScore > nSpeedUpScore){nSpeed++;nSpeedUpScore+= nSpeed*1000;/*重绘速度框*/setfillstyle(SOLID_FILL,BLACK);bar(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1));setcolor(YELLOW);rectangle(BSIZE*25,BSIZE*13, BSIZE*(25+8), BSIZE*(13+1)); itoa(nSpeed,SpeedBuffer,10);setcolor(YELLOW);settextjustify(CENTER_TEXT, BOTTOM_TEXT);outtextxy(BSIZE*(25+4), BSIZE*(13+1), SpeedBuffer);}if(IsGameOver())bOver = TRUE;return TRUE; /*下落到底返回TRUE*/}}}/*********************************************************** 函数原型:int IsLineFull(int y) ** 传入参数:纵坐标y ** 返回值:填满返回1,否则返回0 ** 函数功能:判断第y行是否已被填满***********************************************************/int IsLineFull(int y){int i;for(i=1;i<=10;i++)if(!Gameboard[i][y])return FALSE;return TRUE;}/*********************************************************** void KillLine(int y) ** 传入参数:纵坐标y ** 返回值:无 ** 函数功能:消去第y行***********************************************************/void KillLine(int y){int i,j;for(j=y;j>=2;j--)for(i=1;i<=10;i++){if(Gameboard[i][j]==Gameboard[i][j-1])continue;if(Gameboard[i][j-1]==FILLED){Gameboard[i][j]=FILLED;setfillstyle(SOLID_FILL,FORECOLOR);}else /*Gameboard[i][j-1]==EMPTY*/Gameboard[i][j] = EMPTY;setfillstyle(SOLID_FILL,BGCOLOR);}DrawSquare(i,j);}}/*********************************************************** 函数原型:int KillLines(int y) ** 传入参数:纵坐标y ** 返回值:消去的行数 ** 函数功能:消去第y行以及与第y行连续的上面被填满的行 ***********************************************************/int KillLines(int y){int i, j, LinesKilled=0;for(i=0;i<4;i++){while(IsLineFull(y)){KillLine(y);LinesKilled++;i++;}y--;if(y<1)break;}return LinesKilled;}/*********************************************************** 函数原型:int IsGameOver() ** 传入参数:无 ** 返回值:游戏结束返回1,否则返回0 ** 函数功能:判断游戏是否结束***********************************************************/int IsGameOver(){int i;for(i=1;i<=10;i++)if(Gameboard[i][1])return TRUE;return FALSE;}/*********************************************************** 函数原型:int GameOver() ** 传入参数:无** 返回值:退出游戏返回1,否则返回0 ** 函数功能:在界面上输出游戏结束信息,并根据用户按键选择决定是否退出游戏***********************************************************/int GameOver(){int key;settextjustify(CENTER_TEXT,TOP_TEXT);/* 输出游戏结束信息 */setcolor(RED);outtextxy(BSIZE*15,BSIZE*12,"Game Over");setcolor(GREEN);outtextxy(BSIZE*15,BSIZE*14,"Enter : New Game");outtextxy(BSIZE*15,BSIZE*15,"Esc : Exit");for(;;){while(!bioskey(1));key=bioskey(0);if (key==VK_ENTER)return FALSE; /* 按下回车键,重新开始游戏 */if (key==VK_ESC)return TRUE; /* 按下ESC键,退出游戏 */}}。

C俄罗斯方块源码(完整功能版)

C俄罗斯方块源码(完整功能版)
//控制台
HANDLE hout;//控制台句柄
COORD curpos={0,0};//光标坐标
//主函数
intmain()
{
start1:
try
{
hout=GetStdHandle(STD_OUTPUT_HANDLE);//获取控制台句柄,以便移动光标
srand(time(0));//用当前时间初始化随机数生成器
{
system("cls");
printf("o(>﹏<)o出错啦!\n程序收到了一条错误信息,错误码是:%d(%s)\n您可以联系我们解决这个问题。\n",errnum,errword[errnum]);
printf("\n你可以选择以下操作:\n1.重启程序\n2.以默认设置重启程序\n3.向设置和数据文件写入默认设置然后重启\n4.退出\n");
#pragmacomment( lib,"winmm.lib" )
//定义
//方块
#defineNO 0
#defineSQR 1
//碰撞检测
#defineOK 0
#defineCANTMOVE 1
//方向
#defineUP 0
#defineDOWN 1
#defineLEFT 2
#defineRIGHT 3
},\
{\
0,0,1,0,\
0,1,1,0,\
0,1,0,0,\
0,0,0,0,\
}\
};
constcharerrword[4][50]={"程序没能取得足够的内存","无法打开或找不到设置文件set.ini","无法打开或找不到排行榜数据highscore.dat","您设置的参数太大或者太小"};

俄罗斯方块C语言源代码

俄罗斯方块C语言源代码
exit(1);
}
}
/* 在图形模式下的清屏 */
void cls()
{
setfillstyle(SOLID_FILL,0);
setcolor(0);
bar(0,0,640,480);
}
/*在图形模式下的高级清屏*/
void clscr(int a,int b,int c,int d,int color){
{0,0,1,0,1,1,1,0,0,0,0,0,0,0,0,0}},
{
{1,1,0,0,1,0,0,0,1,0,0,0,0,0,0,0},
{1,0,0,0,1,1,1,0,0,0,0,0,0,0,0,0},
{0,1,0,0,0,1,0,0,1,1,0,0,0,0,0,0},
{1,1,1,0,0,0,1,0,0,0,0,0,(SOLID_FILL,color);
setcolor(color);
bar(a,b,c,d);
}
/*最小方块的绘制*/
void minbox(int asc,int bsc,int color,int bdcolor){
int a=0,b=0;
a=SCCOL+asc;
#define VK_ESC 0x011b
#define VK_ENTER 0x1c0d
/* 定义俄罗斯方块的方向(我定义他为4种)*/
#define F_DONG 0
#define F_NAN 1
#define F_XI 2
#define F_BEI 3
#define NEXTCOL 20 /* 要出的下一个方块的纵坐标*/
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1.using System;using System.Collections.Generic;using System.Text;using System.Drawing;//addnamespace俄罗斯方块{public class Block{private short width;private short height;private short top;private short left;private int ID; //方块部件的IDpublic int[,] shape;//存储方块部件的形状,0为空白,1为有砖块public Block()//构造函数{Random randomGenerator = new Random();int randomBlock = randomGenerator.Next(1, 6);//产生1—4的数this.ID = randomBlock;switch (this.ID){case 1: //横条形this.Width = 4;this.Height = 1;this.Top = 0;this.Left = 3;shape = new int[this.Width, this.Height];shape[0, 0] = 1; shape[1, 0] = 1;shape[2, 0] = 1; shape[3, 0] = 1;break;case 2://正方形this.Width = 2;this.Height = 2;this.Top = 0;this.Left = 4;// Creates the new shape for this block.shape = new int[this.Width, this.Height];shape[0, 0] = 1; shape[0, 1] = 1;shape[1, 0] = 1;shape[1, 1] = 1;break;case 3://T形this.Width = 3;this.Height = 3;this.Top = 0;this.Left = 4;// Creates the new shape for this block.shape = new int[this.Width, this.Height];shape[0, 0] = 1; shape[1, 0] = 1;shape[2, 0] = 1; shape[1, 1] = 1;shape[1, 2] = 1;break;case 4://L形this.Width = 2;this.Height = 3;this.Top = 0;this.Left = 4;// Creates the new shape for this block.shape = new int[this.Width, this.Height];shape[0, 0] = 1; shape[0, 1] = 1;shape[0, 2] = 1; shape[1, 2] = 1;break;case 5: //Z形this.Width = 4;this.Height = 2;this.Top = 0;this.Left = 4;shape =new int[this.Width ,this.Height ];shape[0,0] = 1;shape [1,0]=1;shape [2,0]=0;shape [3,0]=0;shape[0,1] = 0;shape[1,1]=0;shape[2,1]=1;shape [3,1]=1;break;}}public short Width//Width属性{get{return width;}set{width = value;}}public short Height//Height属性{get{return height;}set{height = value;}}public short Top//Top属性{get{return top;}set{top = value;}}public short Left//Left属性{get{return left;}set{left = value;}}public void Draw(Graphics g){Image brickImage = Image.FromFile("image/block0.gif");for (int i = 0; i < this.Width; i++){for (int j = 0; j < this.Height; j++){if (this.shape[i, j] == 1)//黑色格子{//得到绘制这个格子的在游戏面板中的矩形区域Rectangle rect = new Rectangle((this.Left + i) * Game.BlockImageWidth, (this.Top + j) * Game.BlockImageHeight, Game.BlockImageWidth, Game.BlockImageHeight);g.DrawImage(brickImage, rect);}}}}}//class Block}2. using System;using System.Collections.Generic;using ponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;namespace俄罗斯方块{public partial class Form1 : Form{public Form1(){InitializeComponent();}Game game=null;private void button1_Click(object sender, EventArgs e){game= new Game();pictureBox1.Height = Game.BlockImageHeight * Game.PlayingFieldHeight + 3;pictureBox1.Width = Game.BlockImageWidth * Game.PlayingFieldWidth+3;pictureBox1.Invalidate();//重画游戏面板区域timer1.Enabled = true;button1.Enabled = false;Music.PlaySong(@"E:\sound\molihua.mid");}private void button2_Click(object sender, EventArgs e){if (button2.Text == "暂停游戏"){timer1.Enabled = false; button2.Text = "继续游戏";}else{timer1.Enabled = true; button2.Text = "暂停游戏";}}private void button3_Click(object sender, EventArgs e){this.Close();}private void pictureBox1_Paint(object sender, PaintEventArgs e){//重画游戏面板if (game != null){game.DrawPile(e.Graphics);game.DrawCurrentBlock(e.Graphics);}}private void pictureBox2_Paint(object sender, PaintEventArgs e){////重画下一个方块if (game != null) game.DrawNextBlock(e.Graphics);}private void timer1_Tick(object sender, EventArgs e){if (!game.DownCurrentBlock()){pictureBox1.Invalidate();//重画游戏面板区域pictureBox2.Invalidate();//重画下一个方块}lblScore.Text = game.score.ToString();if (game.over == true){timer1.Enabled = false;MessageBox.Show("游戏结束,", "提示");button1.Enabled = true;}}protected override bool ProcessCmdKey(ref Message msg, Keys e)//重写ProcessCmdKey方法{if (button2.Text == "继续游戏") return true;//暂停时不响应键盘if (e == Keys.Up || e == Keys.Down || e == Keys.Space ||e==Keys.Enter ||e == Keys.Left || e == Keys.Right){MyKeyPress(this, new KeyPressEventArgs((char)e));}return true;}//然后在MyKeyPress方法中处理private void MyKeyPress(object sender, KeyPressEventArgs e){switch (e.KeyChar){case (char)Keys.Up:game.RotateCurrentBlock();break;case (char)Keys.Down:if (!game.DownCurrentBlock())pictureBox1.Invalidate();//重画游戏面板区域break;case (char)Keys.Right:game.MoveCurrentBlockSide(false);break;case (char)Keys.Left:game.MoveCurrentBlockSide(true);break;case (char)Keys.Space:button2.PerformClick();break;case(char)Keys.Enter :button1.PerformClick();break;}pictureBox1.Invalidate();pictureBox2.Invalidate();}private void comboBox1_SelectedIndexChanged(object sender, EventArgs e){timer1.Interval = 550 - Convert.ToInt16(comboBox1.Text) * 50;}private void pictureBox2_Click(object sender, EventArgs e){}}}3. using System;using System.Collections.Generic;using System.Text;using System.Drawing;//addnamespace俄罗斯方块{class Game{public const int BlockImageWidth = 21;//方砖中每个小方格的大小public const int BlockImageHeight = 21;public const int PlayingFieldWidth = 10;//游戏面板大小public const int PlayingFieldHeight = 20;private int[,] pile; //存储在游戏面板中的所有方砖;private Block currentBlock ;//当前的俄罗斯方块private Block nextBlock ;//下一个的俄罗斯方块public int score = 0, lines=0;public bool over=false;//游戏是否结束public Game()//Game类构造函数{pile = new int[PlayingFieldWidth , PlayingFieldHeight];ClearPile();CreateNewBlock();//产生新的俄罗斯方块}private void ClearPile()//清空游戏面板中的所有方砖for (int i = 0; i < PlayingFieldWidth ; i++){for (int j = 0; j < PlayingFieldHeight ; j++){pile[i, j]= 0;}}}private void CreateNewBlock()//产生新的俄罗斯方块{if (this.nextBlock != null){currentBlock = nextBlock;}else{currentBlock = new Block();}nextBlock = new Block();}public void DrawPile(Graphics g){Image brickImage = Image.FromFile("image/block1.gif");//方砖的图形for (int i = 0; i < PlayingFieldWidth ; i++){for (int j = 0; j < PlayingFieldHeight ; j++){if (pile[i, j] == 1){Rectangle rect = new Rectangle(i * BlockImageWidth, j * BlockImageHeight, BlockImageWidth, BlockImageHeight);//(j - 1)g.DrawImage(brickImage, rect);}}}}public void DrawCurrentBlock(Graphics g){if (currentBlock != null)//检查当前块是否为空{currentBlock.Draw(g);}}public void DrawNextBlock(Graphics drawingSurface){if (nextBlock != null){short currentLeft = nextBlock.Left;short currentTop = nextBlock.Top;nextBlock.Left = (short)((6 - nextBlock.Width) / 2);nextBlock.Top = (short)((6 - nextBlock.Height) / 2);nextBlock.Draw(drawingSurface);nextBlock.Left = currentLeft;nextBlock.Top = currentTop;}}private void MoveBlockToPile()//固定到游戏面板上for (int i = 0; i < currentBlock.Width; i++){for (int j = 0; j < currentBlock.Height; j++){int fx, fy;fx = currentBlock.Left + i;fy = currentBlock.Top + j;if (currentBlock.shape[i, j] ==1){pile[fx, fy] = 1;}}}CheckForLines();if (CheckForGameOver())//检查游戏是否结束over = true;}public bool DownCurrentBlock(){bool hit = false;currentBlock.Top++;if ((currentBlock.Top + currentBlock.Height) > PlayingFieldHeight){hit = true;//当前块触游戏面板底}else//检查是否接触到下一行其他已落方块{for (int i = 0; i < currentBlock.Width; i++){for (int j = 0; j < currentBlock.Height; j++){int fx, fy;fx = currentBlock.Left + i;fy = currentBlock.Top + j;if ((currentBlock.shape[i, j] == 1) && (pile[fx, fy] == 1))//(fy + 1){hit = true;}}}}if (hit)//触到其他已落方块或游戏面板底{currentBlock.Top--;MoveBlockToPile();//固定到游戏面板上CreateNewBlock(); //产生新的俄罗斯方块}return hit;}public void RotateCurrentBlock()//旋转方块{bool canRotate = true;short newWidth = 0;short newHeight = 0;int[,] newShape;newWidth = currentBlock.Height;newHeight = currentBlock.Width;newShape = new int[newWidth, newHeight];int x,y;if (((currentBlock.Left + newWidth) <= Game.PlayingFieldWidth)&& ((currentBlock.Top + newHeight) < Game.PlayingFieldHeight)){for (int i = 0; i < currentBlock.Width; i++){for (int j = 0; j < currentBlock.Height; j++){x = ((currentBlock.Height - 1) - j);y = i;newShape[x, y] = currentBlock.shape[i, j];if (newShape[x, y] == 1 && pile[x + currentBlock.Left, y + currentBlock.Top] == 1){canRotate = false; return;//不能旋转}}}}if (canRotate){currentBlock.Width = newWidth;currentBlock.Height = newHeight;currentBlock.shape = newShape;}}}public void MoveCurrentBlockSide(bool left)//左右移动{bool canMove = true;if (left)//左移动{if (currentBlock.Left > 0){for (int i = 0; i < currentBlock.Width; i++){for (int j = 0; j < currentBlock.Height; j++){int fx, fy;fx = currentBlock.Left + i;fy = (currentBlock.Top + 1) + j;if ((currentBlock.shape[i, j] == 1) && (pile[(fx - 1), fy] ==1)){canMove = false;}}}if (canMove){currentBlock.Left--;}}}else//右移动{if ((currentBlock.Left + currentBlock.Width) < PlayingFieldWidth){for (int i = 0; i < currentBlock.Width; i++){for (int j = 0; j < currentBlock.Height; j++){int fx, fy;fx = currentBlock.Left + i;fy = (currentBlock.Top + 1) + j;if ((currentBlock.shape[i, j] == 1) && (pile[(fx + 1), fy]==1)){canMove = false;}}}if (canMove){currentBlock.Left++;}}}}private int CheckForLines()//检查是否满行并消去{int numLines = 0;int[] completeLines = new int[PlayingFieldHeight];for (int j = PlayingFieldHeight-1; j > 0; j--)//j = PlayingFieldHeight{bool fullLine = true;for (int i = 0; i < PlayingFieldWidth; i++){if (pile[i, j] == 0){fullLine = false;break;}}if (fullLine){numLines++;completeLines[numLines] = j;}}if (numLines > 0){for (int i = 1; i <= numLines; i++){ClearLine((completeLines[i] + (i - 1)));}score += 5 * (numLines * (numLines + 1));lines += numLines;}return numLines;}private void ClearLine(int lineNumber){for (int j = lineNumber; j > 0; j--){for (int i = 0; i < PlayingFieldWidth; i++){pile[i, j] = pile[i, (j - 1)];}}for (int i = 0; i < PlayingFieldWidth; i++){pile[i, 0] = 0;}}public bool CheckForGameOver()//检查游戏是否结束{if (currentBlock.Top == 0)return true;elsereturn false;}}}4. using System;using System.Collections.Generic;using System.Text;using System.Media;using System.Runtime.InteropServices;namespace俄罗斯方块{class Music{[DllImport("winmm.dll")]private static extern int mciSendString(string lpstrCommand,string lpstrReturnString,int uReturnLength,int hwndCallback);[DllImport("kernel32.dll", CharSet = CharSet.Auto)]public static extern int GetShortPathName([MarshalAs(UnmanagedType.LPTStr)] string path,[MarshalAs(UnmanagedType.LPTStr)] StringBuilder shortPath,int shortPathLength);///<summary>///背景音乐播放///</summary>///<param name="FileName"></param>public static void PlaySong(string FileName){StringBuilder shortPathTemp = new StringBuilder(255);int result = GetShortPathName(FileName, shortPathTemp, shortPathTemp.Capacity);string ShortPath = shortPathTemp.ToString();mciSendString("open " + ShortPath + " alias song", "", 0, 0);mciSendString("play song ", "", 0,0);mciSendString("play song repeat ", "", 0, 0);}private static SoundPlayer soundPlayer = new SoundPlayer();}}5. using System;using System.Collections.Generic;using System.Windows.Forms;namespace俄罗斯方块{static class Program{///<summary>///应用程序的主入口点。

相关文档
最新文档