C#实现俄罗斯方块
本文实例为大家分享了C#实现俄罗斯方块的具体代码,供大家参考,具体内容如下
1.调色板代码
namespaceTetris { classPalette { privateint_width=15;//画板宽度 privateint_height=25;//画板高度 privateColor[,]coorArr;//固定砖块数组 privateColordisapperColor;//背景色 privateGraphicsgpPalette;//砖块活动画板 privateGraphicsgpReady;//下一个砖块样式画板 privateBlockGroupbGroup;//砖块生产机制 privateBlockrunBlock;//正在活动的砖块 privateBlockreadyBlock;//下一个砖块 privateintrectPix;//单元格像 publicdelegatevoidIniCountHandle(int_count,intstate);//分数变量 publiceventIniCountHandleCountEvent; publicstaticint_Count=0; staticintmark=100;//静态变量衡量过关的标准 publicstaticintstate=1; privateSystem.Timers.TimertimerBlock;//定时器 privatestaticinttimeSpan=800;//定时器的时间间隔 publicPalette(intx,inty,intpix,ColordColor,Graphicsgp,Graphicsgr)//构造函数 { _width=x; _height=y; coorArr=newColor[_width,_height]; disapperColor=dColor; gpPalette=gp; gpReady=gr; rectPix=pix; } publicvoidStart()//游戏开始 { state=1; _Count=0; bGroup=newBlockGroup(); runBlock=bGroup.GetABlock(); runBlock.XPos=_width/2; inty=0; for(inti=0;iy) { y=runBlock[i].Y; } } runBlock.YPos=y; gpPalette.Clear(disapperColor);//清空画板 runBlock.Paint(gpPalette);//画运行砖块 Thread.Sleep(20); readyBlock=bGroup.GetABlock(); readyBlock.XPos=2; readyBlock.YPos=2; gpReady.Clear(disapperColor);//清空画板 readyBlock.Paint(gpReady); //初始化并启动定时器 timerBlock=newSystem.Timers.Timer(timeSpan); timerBlock.Elapsed+=newSystem.Timers.ElapsedEventHandler(OnTimedEvent); timerBlock.AutoReset=true; timerBlock.Start(); } publicvoidnextstate() { PaintBackground(gpPalette); timerBlock=newSystem.Timers.Timer(timeSpan); timerBlock.Elapsed+=newSystem.Timers.ElapsedEventHandler(OnTimedEvent); timerBlock.AutoReset=true; timerBlock.Start(); } privatevoidOnTimedEvent(objectsource,ElapsedEventArgse) { CheckAndOverBlock(); Down(); } publicboolDown()//砖块下移 { intxPos=runBlock.XPos; intyPos=runBlock.YPos+1; for(inti=0;i _height-1)//如果超出下边界则失败 returnfalse; if(!coorArr[xPos+runBlock[i].X,yPos-runBlock[i].Y].IsEmpty)//如果下边有东西挡则失败 returnfalse; } runBlock.erase(gpPalette);//擦除原来位置砖块 runBlock.YPos++; runBlock.Paint(gpPalette); returntrue; } publicvoidDrop()//丢下砖块 { timerBlock.Stop(); while(Down()); timerBlock.Start(); } publicvoidMoveLeft()//向左移动 { intxPos=runBlock.XPos-1; intyPos=runBlock.YPos; for(inti=0;i _width-1)//如果超出右边界则失败 return; if(!coorArr[xPos+runBlock[i].X,yPos-runBlock[i].Y].IsEmpty)//如果右边有东西挡则失败 return; } runBlock.erase(gpPalette); runBlock.XPos++; runBlock.Paint(gpPalette); } publicvoidDeasilRotate()//顺时针旋转 { for(inti=0;i _width-1) return; if(y<0||y>_height-1) return; if(!coorArr[x,y].IsEmpty) return; } runBlock.erase(gpPalette); runBlock.DeasilRotate(); runBlock.Paint(gpPalette); } publicvoidContraRotate()//逆时针旋转 { for(inti=0;i _width-1) return; if(y<0||y>_height-1) return; if(!coorArr[x,y].IsEmpty) return; } runBlock.erase(gpPalette); runBlock.ContraRotate(); runBlock.Paint(gpPalette); } privatevoidPaintBackground(Graphicsgp)//重画画板背景 { gp.Clear(Color.Black);//清空画板 for(inti=0;i<_height;i++) { for(intj=0;j<_width;j++) { if(!coorArr[j,i].IsEmpty) { SolidBrushsb=newSolidBrush(coorArr[j,i]); gp.FillRectangle(sb,j*rectPix+1, i*rectPix+1, rectPix-2, rectPix-2); } } } } publicvoidPaintPalette(Graphicsgp)//重画整个画板 { PaintBackground(gp);//先画背景 if(runBlock!=null)//再画活动的砖块 { runBlock.Paint(gp); } } publicvoidPaintReady(Graphicsgp)//重画下一个砖块 { if(readyBlock!=null) { readyBlock.Paint(gp); } } publicvoidCheckAndOverBlock()//检查砖块是否到底 { boolover=false; for(inti=0;i y) { y=runBlock[i].Y; } } runBlock.YPos=y; //检查新产生的砖块所占用的地方是否已经有砖块,如果有,则游戏结束 for(inti=0;i highRow) { highRow=y; } } intcount=0; boolrepaint=false;//判断是否重画 for(inti=lowRow;i<=highRow;i++)//检查是否满行 { boolrowFull=true; for(intj=0;j<_width;j++) { if(coorArr[j,i].IsEmpty)//如果有一个单元格为空,说明这一行不可能为满行 { rowFull=false; break; } } if(rowFull)//如果满行,则删除这一行 { count++; repaint=true;//如果删除,则需重画 for(intk=i;k>0;k--) { for(intj=0;j<_width;j++) { coorArr[j,k]=coorArr[j,k-1]; } } for(intj=0;j<_width;j++)//清空第0行 { coorArr[j,0]=Color.Empty; } } } //计算每满几行加的分值 if(count==1) { _Count+=10; CountEvent(_Count,state); } if(count==2) { _Count+=30; CountEvent(_Count,state); } if(count==3) { _Count+=60; CountEvent(_Count,state); } if(count>=4) { _Count+=80; CountEvent(_Count,state); } if(repaint)//重画 { PaintBackground(gpPalette); } if(_Count>=1000)//如果通关初始化为原来的值 { StringFormatdrawFormat=newStringFormat(); drawFormat.Alignment=StringAlignment.Center; gpPalette.DrawString("O(∩_∩)O"+"\r\n"+"***通关***"+"\r\n"+"按“开始”按钮\r\n王者归来", newFont("ArialBlack",20f), newSolidBrush(Color.Red), newRectangleF(0,_height*rectPix/2-100,_width*rectPix,120), drawFormat); timeSpan=800; state=1; _Count=0; timerBlock.Close(); } if(_Count>=mark) { mark+=100; timeSpan-=70; state++; CountEvent(_Count,state); StringFormatdrawFormat=newStringFormat(); drawFormat.Alignment=StringAlignment.Center; gpPalette.DrawString("\tO(∩_∩)O~\r\n***恭喜过关***\r\n按“下一关”按钮\r\n开始新的远征", newFont("ArialBlack",20f), newSolidBrush(Color.DodgerBlue), newRectangleF(0,_height*rectPix/2-80,_width*rectPix,120), drawFormat); timerBlock.Stop();//关闭计时器 } } publicvoidPause()//暂停 { if(timerBlock.Enabled==true) { timerBlock.Enabled=false; StringFormatdrawFormat=newStringFormat(); drawFormat.Alignment=StringAlignment.Center; gpPalette.DrawString("暂停"+"\r\n"+"得分:"+_Count.ToString(), newFont("ArialBlack",25f), newSolidBrush(Color.Aqua), newRectangleF(0,_height*rectPix/2-100,_width*rectPix,100), drawFormat); } } publicvoidEndPause()//结束暂停 { if(timerBlock.Enabled==false) { timerBlock.Enabled=true; PaintBackground(gpPalette); } } publicvoidClose()//关闭 { timerBlock.Close(); gpPalette.Dispose();//释放画布 gpReady.Dispose(); } } }
2.保存信息数组代码
namespaceTetris { classInfoArr { privateArrayListinfo=newArrayList();//存放多个BlockInfo累得的数组 privateint_length=0;//存放Arraylist的长度,以供访问 publicintLength { get { return_length; } } publicBlockInfothis[intindex]//索引器,根据下标,返回一个blockinfo的值 { get { return(BlockInfo)info[index]; } } publicstringthis[stringid]//索引器,根据一个字符串的id值下标,给相应id的颜色赋值 { set { if(value=="") { return; } for(inti=0;i3.方块信息代码
namespaceTetris { classBlockInfo { privateBitArray_id;//存放砖块样式 privateColor_bColor;//存放颜色信息 publicBlockInfo(BitArrayid,ColorbColor)//构造函数,给似有函数变量赋值 { _id=id; _bColor=bColor; } publicBitArrayID { get { return_id; } set { _id=value; } } publicColorBColor { get { return_bColor; } set { _bColor=value; } } publicstringGetIdStr() { StringBuilders=newStringBuilder(25); foreach(boolbin_id) { s.Append(b?"1":"0"); } returns.ToString(); } publicstringGetColorStr() { returnConvert.ToString(_bColor.ToArgb()); } } }4.方块组代码
namespaceTetris { classBlockGroup { privateInfoArrinfo;//存放所有砖块样式信息 privateColordisapperColor;//背景色 privateintrectPix;//单元格像素 publicBlockGroup()//构造函数 { Configconfig=newConfig(); config.LoadFromXmlFile(); info=newInfoArr(); info=config.Info; disapperColor=config.BackColor; rectPix=config.RectPix; } publicBlockGetABlock()//从砖块组中随机抽取一个砖块样式并返回 { Randomrd=newRandom();//声明一个产生随机数的类 intkeyOrder=rd.Next(0,info.Length);//产生一个随机数 BitArrayba=info[keyOrder].ID;//把抽取出的砖块样式赋给BitArray类对象ba intstruNum=0;//确定这个砖块样式中被填充方块的个数 foreach(boolbinba)//需要确定point数组的长度 { if(b) { struNum++; } } Point[]structArr=newPoint[struNum];//新建一个point数组,并确定其长度,以创建新的block intk=0; for(intj=0;j5.方块的基本属性代码
namespaceTetris { classBlock { protectedPoint[]structArr;//存放砖块组成信息的坐标数组 protectedint_xPos;//砖块中心点所在的X坐标 protectedint_yPos;//砖块中心点所在的y坐标 protectedColor_blockColor;//砖块颜色 protectedColordisapperColor;//擦除颜色 protectedintrectPix;//每单元格像素 publicBlock()//默认构造函数,声明此构造函数是为了子类能创建 { } publicBlock(Point[]sa,ColorbColor,ColordColor,intpix) { //重载构造函数,给成员变量赋值 _blockColor=bColor; disapperColor=dColor; rectPix=pix; structArr=sa; } publicPointthis[intindex]//索引器,根据索引访问砖块里的小方块坐标 { get { returnstructArr[index]; } } publicintLength//属性,表示structArr的长度 { get { returnstructArr.Length; } } #region成员变量相应的属性 publicintXPos { get { return_xPos; } set { _xPos=value; } } publicintYPos { get { return_yPos; } set { _yPos=value; } } publicColorBlockColor { get { return_blockColor; } } #endregion publicvoidDeasilRotate()//顺时针旋转 { inttemp; for(inti=0;i6.俄罗斯方块窗体代码
namespaceTetris { publicpartialclassFrmTetris:Form { publicFrmTetris() { InitializeComponent(); CheckForIllegalCrossThreadCalls=false; } privatePalettep; privateKeysdownKey; privateKeysdropKey; privateKeysmoveLeftKey; privateKeysmoveRightKey; privateKeysdeasilRotateKey; privateKeyscontraRotateKey; privateintpaletteWidth; privateintpaletteHeight; privateColorpaletteColor; privateintrectPix; privatevoidbtnStart_Click(objectsender,EventArgse) { lblState.Text="等级:1"; lblcount.Text="得分:0"; if(p!=null) { p.Close(); } p=newPalette(paletteWidth,paletteHeight,rectPix,paletteColor, Graphics.FromHwnd(pbRun.Handle), Graphics.FromHwnd(lblReady.Handle)); p.CountEvent+=newPalette.IniCountHandle(p_CountEvent); p.Start(); } voidp_CountEvent(int_count,intstate) { lblcount.Text="得分:"+_count.ToString(); lblState.Text="等级:"+state.ToString(); } privatevoidpbRun_Paint(objectsender,PaintEventArgse) { if(p!=null) { p.PaintPalette(e.Graphics); } } privatevoidlblReady_Paint(objectsender,PaintEventArgse) { if(p!=null) { p.PaintReady(e.Graphics); } } privatevoidFrmTetris_Load(objectsender,EventArgse) { //读取xml文件中的参数配置信息,并依次赋给似有成员变量 Configconfig=newConfig(); config.LoadFromXmlFile(); downKey=config.DownKey; dropKey=config.DropKey; moveLeftKey=config.MoveLeftKey; moveRightKey=config.MoveRightKey; deasilRotateKey=config.DeasilRotateKey; contraRotateKey=config.ContraRotateKey; paletteWidth=config.CoorWidth; paletteHeight=config.CoorHeight; paletteColor=config.BackColor; rectPix=config.RectPix; //根据画板的长度和宽度信息动态改变窗体及画板的规格 this.Width=paletteWidth*rectPix+215; this.Height=paletteHeight*rectPix+38; pbRun.Width=paletteWidth*rectPix; pbRun.Height=paletteHeight*rectPix; } privatevoidFrmTetris_KeyDown(objectsender,KeyEventArgse) { if(e.KeyValue==32)//屏蔽回车键 { e.Handled=true; } if(e.KeyCode==downKey)//下降 { p.Down(); } elseif(e.KeyCode==dropKey) { p.Drop(); } elseif(e.KeyCode==moveLeftKey) { p.MoveLeft(); } elseif(e.KeyCode==moveRightKey) { p.MoveRight(); } elseif(e.KeyCode==deasilRotateKey) { p.DeasilRotate(); } elseif(e.KeyCode==contraRotateKey) { p.ContraRotate(); } } privatevoidbtnPause_Click(objectsender,EventArgse) { if(p==null) { return; } if(btnPause.Text=="暂停") { p.Pause(); btnPause.Text="继续"; } else { p.EndPause(); btnPause.Text="暂停"; } } privatevoidbtnConfig_Click(objectsender,EventArgse) { if(btnPause.Text=="暂停") { btnPause.PerformClick(); } using(Frmconfigfrmconfig=newFrmconfig()) { frmconfig.ShowDialog(); } } privatevoidFrmTetris_FormClosing(objectsender,FormClosingEventArgse) { if(p!=null) { p.Close(); } } privatevoidbutton5_Click(objectsender,EventArgse) { p.Down(); } privatevoidbutton1_Click(objectsender,EventArgse) { p.MoveLeft(); } privatevoidbutton2_Click(objectsender,EventArgse) { p.MoveRight(); } privatevoidbutton3_Click(objectsender,EventArgse) { p.DeasilRotate(); } privatevoidbutton4_Click(objectsender,EventArgse) { p.ContraRotate(); } privatevoidbutton6_Click(objectsender,EventArgse) { p.Drop(); } privatevoidbutton7_Click(objectsender,EventArgse) { OpenFileDialogofDialog=newOpenFileDialog(); ofDialog.AddExtension=true; ofDialog.CheckFileExists=true; ofDialog.CheckPathExists=true; //thenextsentencemustbeinsingleline ofDialog.Filter="MP3文件(*.mp3)|*.mp3|Audio文件(*.avi)|*.avi|VCD文件(*.dat)|*.dat|WAV文件(*.wav)|*.wav|所有文件(*.*)|*.*"; ofDialog.DefaultExt="*.mp3"; if(ofDialog.ShowDialog()==DialogResult.OK) { this.axWindowsMediaPlayer1.URL=ofDialog.FileName; } } privatevoidtimer1_Tick(objectsender,EventArgse) { DateTimedt=DateTime.Now;//当前时间的实例; lbltime.Text=dt.ToString();//转为string类型把值交给lbltime的Text属性; } privatevoidbutton8_Click(objectsender,EventArgse) { p.CountEvent+=newPalette.IniCountHandle(p_CountEvent); p.nextstate(); } } }7.游戏设置窗体代码
namespaceTetris { publicpartialclassFrmconfig:Form { publicFrmconfig() { InitializeComponent(); } privatebool[,]struArr=newbool[5,5]; privateColorblockColor=Color.Red; privatevoidlblMode_Paint(objectsender,PaintEventArgse) { Graphicsgp=e.Graphics; gp.Clear(Color.Black); Penp=newPen(Color.White); for(inti=31;i<155;i=i+31) gp.DrawLine(p,1,i,155,i); for(inti=31;i<155;i=i+31) gp.DrawLine(p,i,1,i,155); //填充颜色 SolidBrushs=newSolidBrush(blockColor); for(intx=0;x<5;x++) { for(inty=0;y<5;y++) { if(struArr[x,y]) { gp.FillRectangle(s,31*x+1,31*y+1,30,30); } } } } privatevoidlblMode_MouseClick(objectsender,MouseEventArgse) { if(e.Button!=MouseButtons.Left) return; intxPos,yPos; xPos=e.X/31; yPos=e.Y/31; struArr[xPos,yPos]=!struArr[xPos,yPos]; boolb=struArr[xPos,yPos]; Graphicsgp=lblMode.CreateGraphics(); SolidBrushs=newSolidBrush(b?blockColor:Color.Black); gp.FillRectangle(s,31*xPos+1,31*yPos+1,30,30); gp.Dispose(); } } }更多有趣的经典小游戏实现专题,分享给大家:
C++经典小游戏汇总
python经典小游戏汇总
python俄罗斯方块游戏集合
JavaScript经典游戏玩不停
java经典小游戏汇总
javascript经典小游戏汇总
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。