用matlab编写的俄罗斯方块小游戏
用matlab编写的俄罗斯方块小游戏
用matlab编写的俄罗斯方块小游戏fun ctio n RussiaBlock( varargin )if nargin == 0OldHandle = findobj( 'Type', 'figure', 'Tag', 'RussiaBlock');if ishandle( OldHandle )delete( OldHa ndle );endFigureHandle = figure( 'Name',' 俄罗斯方块MATLAB 版','Tag', 'RussiaBlock', 'NumberTitle', 'off,...'Menubar', 'none', 'DoubleBuffer', 'on', 'Resize', 'off, 'visible', 'on',...'KeyPressFcn', 'RussiaBlock( "KeyPress_Callback", gcbo )',...'HelpFcn', 'helpdlg(''帮不了你--!","不好意思'')',...'CloseRequestFcn', 'RussiaBlock( ''CloseFigure_Callback'', gcbo )');gen erate_FigureC ontent( FigureHa ndle );ini t_FigureC ontent( FigureHa ndle );set( FigureHandle, 'Visible', 'on');elseif ischar( varargi n{1})feval( vararg in {:});end% ------------------------------------------------------------------------fun ctio n gen erate_FigureC ontent( FigureHa ndle )TabSpace = 30 ;BlockWidth = 20 ;BlockHeight = 20 ;FigureWidth = BlockWidth * (12 + 1) + TabSpace * 7;FigureHeight = 500 ;set( FigureHa ndle, 'Positio n', [0 0 FigureWidth FigureHeight]);movegui( FigureHa ndle, 'cen ter');%创建菜单BeginMenu = uimenu( FigureHandle, 'Label',' 开始');StartMenu = uimenu( BeginMenu, 'Label',' 开始新游戏','Accelerator', 'N',...'Callback','RussiaBlock( "StartNewGame_Callback", gcbo )');SaveMe nu = uime nu( Beg inMenu, 'Label', 'Separator', 'on', 'Cal','RussiaBlock( "SaveGame_Callback", gcbo )'); LoadMe nu = uime nu( Begi nMenu, 'Label','Cal', 'RussiaBlock( ''LoadGame_Callback'',gcbo )');QuitMenu = uimenu( BeginMenu, 'Label', 'close(gcf)');Operati onMenu = uime nu( FigureHa ndle, 'Label',' BoardConfigMenu = uimenu( OperationMenu, 'label',' 'Cal', 'RussiaBlock( ''BoardConfig_Callback'', gcbo )');FigureConfigMenu = uimenu( OperationMenu, 'label',''Cal', 'RussiaBlock( ''FigureCo nfig_Callback", gcbo )'); HighScoreMe nu = uime nu( Operati onMenu, 'label',''Cal', 'RussiaBlock( ''HighScore_Callback'',gcbo )', 'Enable', 'off ); GameLevelMe nu = uimenu( Operati onMenu, 'Label',' 'Cal','RussiaBlock( ''GameLevel_Callback'',gcbo )'); HelpMe nu = uime nu( FigureHa ndle, 'Label', AboutMenu = uimenu( HelpMenu, 'Label','MATLAB 版'',''关于此软件 ............ '')'); HelpDlgMenu = uimenu( HelpMenu, 'Label',不了你--!'',''不好意思”)');%创建工具条,图标可以用imread 从图片读取,但图片不要太大BeginTool = uipushtool( 'ToolTipString',' 开始','CData', rand(16,16,3), 'Tag', 'BeginTool',... 'ClickedCallback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )');PauseTool = uitoggletool( 'ToolTipString',' 暂停','Tag', 'PauseTool', 'Tag', 'PauseTool',... 'CData', reshape( repmat( [1 1 0], 16, 16), [16,16,3] ),...'ClickedCallback', 'RussiaBlock( ''PauseGame_Callback'', gcbo )');%创建游戏窗口Mai nWin dowXPos = TabSpace;Mai nWin dowYPos = TabSpace;Mai nWin dowWidth = BlockWidth * 12 ;Mai nWin dowHeight = BlockHeight * 22 ;Mai nWin dowPositio n = [Mai nWin dowXPos Mai nWin dowYPos Mai nWin dowWidthMai nWin dowHeight];%定义游戏窗口的右键菜单AxesContextMenu = uicontextmenu( 'Tag', 'uicontextmenu');保存','Accelerator', 'S', 'Enable', 'off,...读取','Accelerator', 'L', 'Enable', 'off,...退出','Accelerator', Q, 'Separator', 'on: 'Cal', 功能');键盘设置','Enable', 'off,...界面设置','Enable', 'off,...最高记录','Separator', 'on',...游戏难度',...帮助');关于此软件','Cal', 'helpdlg(''俄罗斯方块游戏帮助','Separator', 'on', 'Cal', 'helpdig (” 帮uimenu( AxesContextMenu, 'Label',' 设置窗口颜色','Cal','RussiaBlock( ''Wi ndowColor_Callback", gcbo )')uimenu( AxesContextMenu, 'Label',' 设置背景图片','Cal','RussiaBlock( ''Wi ndowPicture_Callback", gcbo )') uimenu( AxesContextMenu, 'Label',' 设置方块颜色','Cal','RussiaBlock( ''BlockColor_Callback'', gcbo )')uimenu( AxesContextMenu, 'Label',' 恢复默认','Cal', 'RussiaBlock( ''Default_Callback'', gcbo )') MainAxes = axes( 'Uniits', 'pixels', 'Pos', MainWindowPosition, 'XTick', [], 'YTick'』, 'XTickLabel', [],... 'YTickLabel', [], 'Box', 'on', 'Tag', 'MainAxes', 'UicontextMenu', AxesContextMenu,...'XLim', [0 MainWindowWidth], 'YLim', [0 MainWindowHeight]);hold on;%创建一个窗口用于显示下一个方块的图形NextBlockWndXPos = Mai nWin dowXPos + Mai nWin dowWidth + TabSpace ; NextBlockWndHeight = 4 * TabSpace + BlockHeight ;NextBlockWndYPos = Mai nWin dowYPos + Mai nWin dowHeight - NextBlockWndHeight ; NextBlockWndWidth = TabSpace * 4 + BlockWidth ;NextBlockWndPosition = [NextBlockWndXPos NextBlockWndYPos NextBlockWndWidth NextBlockWndHeight];NextBlockAxes = axes( 'Units', 'pixels', 'Pos', NextBlockWndPosition, 'XTick', [], 'YTick',[],...'XTickLabel', [], 'YTickLabel', [], 'XLim', [0 NextBlockWndWidth],...'YLim', [0 NextBlockWndHeight], ...'Box', 'on', 'Tag', 'NextBlockAxes', 'Color', [0.85 0.85 0.85]);%创建一组控件,包括(两个文本框用于显示当前方块数和成绩,两个按钮用于暂停和退出)Butt on Tag = { 'QuitButto n', 'PauseButto n', 'BlockNumText', 'ScoreText' };Butt on Style = { 'pushbutto n', 'togglebutto n', 'text', 'text' };Fon tColor = { [0 0 0], [1 0 0], [0 0 1], [1 0 1] };Butt on Color = { [0.7 0.8 0.9], [0.3 1 0.3], [0.5 1 1], [0.5 1 1] };ButtonString = {'退出','暂停','方块数','积分'};Butto nCallback = { 'close(gcf)', 'RussiaBlock( ''Butto nPauseGame_Callback", gcbo )', '', '' };Butt onNu mber = len gth( Butt on Tag );Butto nWidth = NextBlockWndWidth ;Butto nH eight = 50 ;Butto nXPos = NextBlockWndXPos ;Butto nYPos = Mai nWin dowYPos + TabSpace ;Butto nPositi on = [Butto nXPos Butt on YPos Butto nWidth Butto nH eight];Butto nTabSpace = (NextBlockWndYPos - 2 * TabSpace - Butto nH eight * Butto nNu mber) / Butt onNu mber ;for num = 1: Butt onNu mberTempButt on Positi on = Butt on Positi on ;TempButto nPositio n(2) = Butto nPositio n(2) + (num - 1) * (Butto nTabSpace +Butto nH eight);if findstr( ButtonStyle{num}, 'button')TempButto nPositio n(1) = TempButto nPositi on (1) + 10 ;TempButto nPositio n(2) = TempButto nPositio n(2) + 5 ;TempButtonPosition(3) = TempButtonPosition(3) - 10 * 2 ;TempButto nPositio n(4) = TempButto nPositio n(4) - 5 * 2 ;elseTempButtonPosition(1) = TempButtonPosition(1) - 10 ;TempButto nPositio n(2) = TempButto nPositio n(2) - 5 ;TempButto nPositio n(3) = TempButto nPositio n(3) + 10 * 2;TempButto nPositio n(4) = TempButto nPositio n(4) + 5 * 2 ;endButto nHan dle = uico ntrol( 'Tag', Butto nTag{ nu m}, 'Style', Butt on Style{ num}, 'Pos', TempButt on Positi on,…'Foregro un dcolor', Fon tCol or{nu m}, 'Backgro un dcolor', Butt on Col or{nu m},...'Fo ntsize', 16, 'Stri ng', Butto nStri ng{ nu m}, 'Cal', Butt on Callback{ num});if findstr( ButtonStyle{num}, 'text')set( Butt onHan dle, 'Max', 2 );endif fin dstr( Butto nTag{ num}, 'PauseButto n')set( ButtonHandle, 'Enable', 'inactive', 'ButtonDownFcn', ButtonCallback{num}, 'Cal',''); endendMainBlockAxes = axes( 'Units', 'pixels', 'Pos', MainWindowPosition, 'XTick', [], 'YTick'』,'XTickLabel', [],...'YTickLabel', [], 'Box', 'on', 'Tag', 'MainBlockAxes', 'Hittest', 'off,...'XLim', [0 MainWindowWidth], 'YLim', [0 MainWindowHeight], 'Color', 'none');line( 'Visible', 'on', 'Tag', 'BlockHandle', 'Markersize', 18, 'Parent', MainBlockAxes, 'HitTest', 'off,...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', nan, 'YData', nan, 'LineStyle', 'none');line( 'Visible', 'off, 'Tag', 'TempBlock', 'Markersize', 18, 'Parent', MainBlockAxes, 'HitTest', 'off,...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', 130, 'YData', 30, 'LineStyle', 'none');line( 'Visible', 'off, 'Tag', 'NextBlock', 'Markersize', 18, 'Parent', NextBlockAxes, 'HitTest', 'off,...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', 30, 'YData', 30, 'LineStyle', 'none');setappdata( FigureHa ndle, 'XLim', [0 Mai nWin dowWidth]) setappdata( FigureHa ndle, 'YLim', [0 Mai nWin dowHeight]) han dles = guiha ndles( FigureHa ndle );guidata( FigureHa ndle, han dles );% ------------------------------------------------fun ctio n in it_FigureC on te nt( FigureHa ndle )han dles = guidata( FigureHa ndle );Colorl nfo =[];tryColorl nfo = load('ColorI nfo.mat');catchendif isempty( Colorl nfo )Colorl nfo.BlockColor = GetDefaultBlockColor ;Colorl nfo.Mai nAxesColor = GetDefaultMai nAxesColor ;ColorI nfo.Ma in AxesImage .Im ageData =[];endset( han dles.Mai nAxes, 'Color', ColorI nfo.Mai nAxesColor );if ~isempty( ColorI nfo.Ma in AxesImage .Im ageData )ImageHa ndle = image( ColorI nfo.Ma in AxesImage .Im ageData, 'Pare nt', han dles.Ma in Axes ); set( ImageHa ndle, ColorI nfo.Ma in AxesImage.Property );setappdata( FigureHa ndle, 'ImageData', ColorI nfo.Ma in AxesImage .Im ageData ); endset( han dles.BlockHa ndle, 'MarkerFaceColor', ColorI nfo.BlockColor );set( ha ndles.TempBlock, 'MarkerFaceColor', ColorI nfo.BlockColor );set( ha ndles.NextBlock, 'MarkerFaceColor', ColorI nfo.BlockColor ); setappdata( FigureHandle,'BlockColor', ColorInfo.BlockColor );% -----------------------------------------------------------fun ctio n StartNewGame_Callback( h, StartType )han dles = guidata( h );global PauseTimeif nargin == 1StartType = 'NewStart';setappdata( han dles.RussiaBlock, 'BlockNumber', 0 );set( handles.BlockNumText, 'String', {' 方块数','0'});setappdata( han dles.RussiaBlock, 'Curre ntScore', 0 );set( handles.ScoreText, 'String', {' 积分','0'});set( handles.BlockHandle, 'XData', nan, 'YData', nan );set( handles.TempBlock, 'XData', nan, 'YData', nan );TextHandle = findobj( 'Parent', handles.MainBlockAxes, 'Type', 'text');delete( TextHandle );elseendset( ha ndles.NextBlock, 'Visible', 'on');set( han dles.TempBlock, 'Visible', 'on');set( handles.PauseTool, 'State', 'off );set( han dles.PauseButt on, 'Value', 0 );YLim = get( handles.MainAxes, 'YLim');while( isha ndle( h ))TotalYData = get( handles.BlockHandle, 'YData');if any( TotalYData >= YLim(2))% Game overtext( 20, 200, 'GameOver', 'Parent', handles.MainBlockAxes,...'Fo ntSize', 30, 'Color', 'r', 'Fo ntAn gle', 'italic');break;endif len gth( TotalYData ) >= 4TotalXData = get( handles.BlockHandle, 'XData');LastBlockYData = TotalYData( end - 3: end );LastBlockYData = uni que( LastBlockYData );CompleteL ine =[];Usefull ndex =[];for num = 1: len gth( LastBlockYData )[YData, I ndex] = find( TotalYData == LastBlockYData (n um));if len gth( YData ) == 12CompleteL ine = [CompleteL ine, LastBlockYData (nu m)];Usefull ndex = [Usefull ndex, In dex];endendif ~isempty( CompleteL ine )TotalXData( Usefull ndex)=[];TotalYData( Usefull ndex)=[];Lin eNumber = len gth( CompleteL ine );ScoreArray = [100 300 600 1000];NewScore = ScoreArray(L in eNumber);Curren tScore = getappdata( han dles.RussiaBlock, 'Curre ntScore'); TextString = get( handles.ScoreText, 'String');TextStri ng{2} = Curre ntScore + NewScore ;set( handles.ScoreText, 'String', TextString );setappdata( han dles.RussiaBlock, 'Curre ntScore', Curren tScore + NewScore );UpdateGameLevel( han dles.RussiaBlock, Curren tScore + NewScore );%处理需要下移的方块for num = Lin eNumber : -1 : 1[YData, Index] = find( TotalYData > LastBlockYData(num));TotalYData(I ndex) = TotalYData(I ndex) - 20 ;endendset( ha ndles.BlockHa ndle, 'XData', TotalXData, 'YData', TotalYData );endBlockNumber = getappdata( han dles.RussiaBlock, 'BlockNumber');TextStri ng = get( ha ndles.BlockNumText, 'Stri ng');TextStri ng{2} = BlockNumber + 1 ;set( ha ndles.BlockNumText, 'Stri ng', TextStri ng );setappdata( handles.RussiaBlock, 'BlockNumber', BlockNumber + 1 ); GameLevel = getappdata( han dles.RussiaBlock, 'GameLevel');if isempty( GameLevel )PauseTime = 0.3 ;elsePauseTime = ceil( 20 / GameLevel ) / 100 ;endTempBlockPos. LeftStep = 0 ;TempBlockPos.Dow nStep = 0 ;setappdata( han dles.RussiaBlock, 'TempBlockPos', TempBlockPos );Status = 1;[BlockXArray,BlockYArray] = Com_GetBlock( h );set( ha ndles.TempBlock, 'XData', BlockXArray, 'YData', BlockYArray ); while( Status & ishandle( h ))if(PauseTime) ~= 0pause( PauseTime )endStatus = test_MoveBlock( h, 'Dow n');endend% ------------------------------------------------------------------------fun ctio n KeyPress_Callback( h )han dles = guidata( h );PauseState = get( han dles.PauseTool, 'State');if strcmp( PauseState, 'on')returnendBoardC onfig = getappdata( han dles.RussiaBlock, 'BoardC on fig');if isempty( BoardConfig )Left = 'leftarrow';Right = 'rightarrow';Down = 'dow narrow';Change = 'uparrow';Drop = 'space';elseLeft = BoardCo nfig.Left ;Right = BoardConfig.Right;Dow n = BoardC on fig.Dow n ;Change = BoardC on fig.Cha nge ;Drop = BoardC on fig.Drop ;endCurren tKey = get( han dles.RussiaBlock, 'Curre ntKey');switch Curre ntKeycase Lefttest_MoveBlock( h, 'Left');case Righttest_MoveBlock( h, 'Right');case Downtest_MoveBlock( h, 'Dow n');case Changetest_MoveBlock( h, 'Cha nge');case Droptest_MoveBlock( h, 'Drop');otherwisereturn ;end% ------------------------------------------------------------------------fun ctio n Win dowColor_Callback( h )han dles = guidata( h );CurrentColor = get( handles.MainAxes, 'Color');NewColor = uisetcolor( CurrentColor,' 请选择窗口颜色');if len gth( NewColor ) == 0return;elseset( han dles.Mai nAxes, 'Color', NewColor );end% -------------------------------------------------------fun ctio n Win dowPicture_Callback( h ) han dles = guidata( h ); [PictureFile, Path] = uigetfile( {'*.jpg; *.bmp'},' if isnumeric( PictureFile )return ;请选择图片’);else% if len gth( PictureFile ) > 31% errordlg('文件名过长,读取失败’);% endtryPicture = imread( [Path, PictureFile]);for num = 1: size( Picture, 3 )ValidPicture(:, :, num) = flipud( Picture(:,:,num));endAxesXLim = get( handles.MainAxes, 'XLim');AxesYLim = get( handles.MainAxes, 'YLim');BlockHandle = findobj( handles.MainAxes, 'Style', 'line'); cla( BlockHandle );ImageXLimit = size(Picture, 2);ImageYLimit = size(Picture, 1);if diff( AxesXLim ) < size(Picture, 2) | diff( AxesYLim ) < size(Picture, 1) %超出坐标轴范围,压缩显示XScale = diff( AxesXLim ) / size(Picture, 2);YScale = diff( AxesYLim ) / size(Picture, 1);%取较小比例压缩Scale = min( XScale, YScale );ImageXLimit = size(Picture, 2) * Scale ;ImageYLimit = size(Picture, 1) * Scale ; end lmageXData(1) = AxesXLim(1) + (diff( AxesXLim ) - ImageXLimit) / 2 + 1; lmageXData(2) = ImageXData(1) + ImageXLimit - 1;ImageYData(1) = AxesYLim(1) + (diff( AxesYLim ) - ImageYLimit) / 2 + 1;ImageYData(2) = ImageYData(1) + ImageYLimit - 1;image( ValidPicture, 'Parent', handles.MainAxes, 'Hittest', 'off, ...'XData',ImageXData,'YData',ImageYData, 'Tag', 'MainImage'); setappdata( han dles.RussiaBlock, 'ImageData', ValidPicture ); catchErrorStri ng = spri ntf([' 读取图片失败,错误信息为:\n ',lasterr]);errordlg( ErrorStri ng );endend% ------------------------------------------------------------------------fun ctio n BlockColor_Callback( h )han dles = guidata( h );Curren tColor = getappdata( han dles.RussiaBlock, 'BlockColor'); if isempty( Curren tColor )Curre ntColor = GetDefaultBlockColor ;setappdata( han dles.RussiaBlock, 'BlockColor', Curren tColor ); endNewColor = uisetcolor( CurrentColor,' 请选择方块颜色');if len gth( NewColor ) == 0return;elsesetappdata( han dles.RussiaBlock, 'BlockColor', NewColor ); set( ha ndles.BlockHa ndle,'MarkerFaceColor', NewColor );set( han dles.TempBlock, 'MarkerFaceColor', NewColor );set( ha ndles.NextBlock, 'MarkerFaceColor', NewColor );end% ------------------------------------------------------------------------fun ctio n Default_Callback( h )han dles = guidata( h );BlockColor = GetDefaultBlockColor ;AxesColor = GetDefaultMai nAxesColor ;set( handles.MainAxes, 'Color', AxesColor );set( handles.BlockHandle, 'MarkerFaceColor', BlockColor );set( ha ndles.TempBlock, 'MarkerFaceColor', BlockColor );set( han dles.NextBlock, 'MarkerFaceColor', BlockColor );% ------------------------------------------------------------------------fun ctio n PauseGame_Callback( h )han dles = guidata( h );ToolStart = get( ha ndles .P auseTool, 'State');if strcmp( ToolStart, 'on')set( handles.PauseButton, 'Value', 1 );waitfor( ha ndles.PauseTool, 'State', 'off );elseset( ha ndles .P auseButt on, 'Value', 0 );end% ------------------------------------------------------------------------fun ctio n Butt on PauseGame_Callback( h )han dles = guidata( h );ToggleButto nValue = get( h, 'Value');if ToggleButt onV alue == 0set( h, 'Value', 1 );set( h, 'String','继续');set( handles.PauseTool, 'State', 'on');waitfor( ha ndles.PauseTool, 'State', 'off );elseset( h, 'Value', 0 );set( h, 'String','暂停');set( handles.PauseTool, 'State', 'off );set( han dles.RussiaBlock, 'Curre ntObject', han dles.Ma in Axes ); end% ------------------------------------------------------------------------fun ctio n CloseFigure_Callback( h )han dies = guidata( h );BlockColor = getappdata( han dles.RussiaBlock, 'BlockColor');MainAxesColor = get( handles.MainAxes, 'Color');Main AxesImageHa ndle = fin dobj( han dles.Ma in Axes, 'Type', 'image');if ~isempty( Main AxesImageHa ndle )Main AxesImage.Property.Tag = get( Main AxesImageHa ndle, 'Tag');Mai nAxesImage.Property.Hittest = get( Main AxesImageHa ndle, 'Hittest');Mai nAxesImage.Property.XData = get( Mai nAxesImageHa ndle, 'XData');Mai nAxesImage.Property.YData = get( Mai nAxesImageHa ndle, 'YData');Main AxesImage .Im ageData = getappdata( han dles.RussiaBlock, 'ImageData'); else Main AxesImage .Im ageData =[]; end save ColorI nfo.mat BlockColor Main AxesColor Main AxesImage delete( han dles.RussiaBlock );% ------------------------------------------------------------------------fun ctio n Color = GetDefaultBlockColorColor = [0 0 1];% ------------------------------------------------------------------------fun ctio n Color = GetDefaultMai nAxesColorColor = [1 1 1];% ---------------------------------------------------------------fun ctio n [ BlockXArray, BlockYArray] = Com_GetBlock( varargin ) global Block In dex ; BlockXArray =[];BlockYArray =[];han dles = guidata( vararg in {1});if nargin == 1BlockArray = getappdata( han dles.RussiaBlock, 'BlockArray');BlockIndex = ceil( rand(1) * 24 );else % nargin == 2Block In dex = vararg in {2};end switch(BlockI ndex)case {1,2,3,4} % 方块BlockXArray = [0;0;1;1] * 20 -10 ;BlockYArray = [0;1;1;0] * 20 -10 ; case {5,6} % 竖长条BlockXArray = [0;0;0;0] * 20 - 10 ;BlockYArray =卜1;0;1;2] * 20 - 10 ; case {7,8} % 横长条BlockXArray =卜1;0;1;2] * 20 - 10 ;BlockYArray = [1;1;1;1] * 20 - 10 ; case {9} % 4 类T T1BlockXArray =卜1;0;1;0] * 20 - 10 ;BlockYArray = [1;1;1;0] * 20 - 10 ; case {10} % T2BlockXArray = [0;0;1;0] * 20 - 10 ;BlockYArray = [2;1;1;0] * 20 - 10 ; case {11} % T3BlockXArray = [0;0;1;-1] * 20 - 10 ;BlockYArray = [2;1;1;1] * 20 - 10 ; case {12} % T4BlockXArray = [0;0;0;-1] * 20 - 10 ;BlockYArray = [2;1;0;1] * 20 - 10 ; case {13} % 8 类L L1BlockXArray = [0;0;0;1] * 20 - 10 ;BlockYArray = [1;0;-1;-1] * 20 - 10 ; case {14} % L2BlockXArray = [-1;0;1;1] * 20 - 10 ;BlockYArray = [0;0;0;1] * 20 - 10 ; case {15} % L3BlockXArray = [-1;0;0;0] * 20 - 10 ;BlockYArray = [1;1;0;-1] * 20 - 10 ; case {16} % L4BlockXArray = [-1;-1;0;1] * 20 - 10 ;BlockYArray = [-1;0;0;0] * 20 - 10 ; case {17} % L5BlockXArray = [-1;0;0;0] * 20 - 10 ;BlockYArray = [-1;-1;0;1] * 20 - 10 ; case {18} % L6BlockXArray = [-1;-1;0;1] * 20 - 10 ;BlockYArray = [1;0;0;0] * 20 - 10 ; case {19} % L7BlockXArray = [0;0;0;1] * 20 - 10 ;BlockYArray = [-1;0;1;1] * 20 - 10 ; case {20} % L8BlockXArray = [-1;0;1;1] * 20 - 10 ;BlockYArray = [0;0;0;-1] * 20 - 10 ; case {21 22} % 4 类Z Z1BlockXArray = [-1;0;0;1] * 20 - 10 ;BlockYArray = [1;1;0;0] * 20 - 10 ; case {23 24} % Z2BlockXArray = [0;0;1;1] * 20 -10 ;BlockYArray = [-1;0;0;1] * 20 - 10 ; case {25 26} % Z3BlockXArray = [-1;0;0;1] * 20 - 10 ;BlockYArray = [0;0;1;1] * 20 - 10 ; case {27 28} % Z4BlockXArray = [0;0;1;1] * 20 - 10 ;BlockYArray = [1;0;0;-1] * 20 - 10 ;end if nargin == 1NewBlockArray.BlockXArray = BlockXArray ;NewBlockArray.BlockYArray = BlockYArray ;NewBlockArray.Blockl ndex = BlockI ndex ;NextAxesXLim = get( han dles.NextBlockAxes, 'XLim');NextAxesYLim = get( han dles.NextBlockAxes, 'YLim');set( han dles.NextBlock, 'XData', [BlockXArray + 0.5 * diff( NextAxesXLim )-ceil( sum( BlockXArray )/4 )],...'YData', [BlockYArray + 0.5 * diff( NextAxesYLim )] - ceil( sum( BlockYArray ) / 4 )); setappdata( han dles.RussiaBlock, 'BlockArray', NewBlockArray );if isempty( BlockArray )Com_GetBlock( varargin{1});elseBlockXArray = BlockArray.BlockXArray ; BlockYArray = BlockArray.BlockYArray ; BlockI ndex = BlockArray.Blockl ndex ; endendAxesXLim = getappdata( han dles.RussiaBlock, 'XLim'); AxesYLim = getappdata( handles.RussiaBlock, 'YLim'); BlockXArray = BlockXArray + 0.5 * diff( AxesXLim ); BlockYArray = BlockYArray + diff( AxesYLim );% ------------------------------------------------ fun ctio n Status = test_MoveBlock( h, MoveMode )Status = 1;if ~isha ndle( h ) returnend han dles = guidata( h );TempXData = get( han dles.TempBlock, 'XData');TempYData = get( ha ndles.TempBlock, 'YData');TempXData = TempXData';TempYData = TempYData';TotaIXData = get( handles.BlockHandle, 'XData');TotalYData = get( handles.BlockHandle, 'YData');TotaIXData = TotalXData';TotalYData = TotalYData';TempBlockPos = getappdata( han dles.RussiaBlock, 'TempBlockPos');if isempty( TempBlockPos )returnendAxesXLim = getappdata( han dles.RussiaBlock, 'XLim');AxesYLim = getappdata( han dles.RussiaBlock, 'YLim');switch MoveModecase 'Left'if any( TempXData - 20 < AxesXLim(l))returnendTestArray = ismember( [TempXData - 20, TempYData], [TotalXData, TotalYData], 'rows'); if any( TestArray )return;elseset( han dles.TempBlock, 'XData', TempXData - 20 );TempBlockPos. LeftStep = TempBlockPos .L eftStep + 1 ;setappdata( han dles.RussiaBlock, 'TempBlockPos', TempBlockPos );endcase 'Right'if any( TempXData + 20 > AxesXLim(2))returnendTestArray = ismember( [TempXData + 20, TempYData], [TotalXData, TotalYData], 'rows'); if any( TestArray )return;elseset( han dles.TempBlock, 'XData', TempXData + 20 );TempBlockPos. LeftStep = TempBlockPos .L eftStep - 1 ;setappdata( han dles.RussiaBlock, 'TempBlockPos', TempBlockPos );endcase 'Dow n'if any( TempYData - 20 < AxesYLim(1))set( handles.BlockHandle, 'XData', [TotalXData; TempXData],...'YData', [TotalYData; TempYData]);Status = 0 ;returnendTestArray = ismember( [TempXData, TempYData - 20], [TotaIXData, TotalYData],'rows');if any( TestArray )set( handles.BlockHandle, 'XData', [TotalXData; TempXData],...'YData', [TotalYData; TempYData]);Status = 0 ;elseset( han dles.TempBlock, 'YData', TempYData - 20 );TempBlockPos.Dow nStep = TempBlockPos.Dow nStep + 1 ;setappdata( han dles.RussiaBlock, 'TempBlockPos', TempBlockPos );endcase 'Drop'global PauseTimePauseTime = 0 ;case 'Cha nge'global Block In dexOldBlockI ndex = BlockI ndex ;switch Block In dexcase {1,2,3,4}return;case {5,6}Newln dex = 7 ;case {7,8}Newln dex = 5 ;case {9,10,11,12}New In dex = mod( OldBlockI ndex, 4 ) + 9;case {13,14,15,16}New In dex = mod( OldBlockI ndex, 4 ) + 13;case {17,18,19,20}New In dex = mod( OldBlockI ndex, 4 ) + 17;case {21,22}NewI ndex = 23;case {23,24}NewI ndex = 21;case {25,26}New In dex = 27 ;case {27,28}New In dex = 25 ;end[BlockXArray, BlockYArray] = Com_GetBlock( h, NewI ndex );NewTempXData = BlockXArray - TempBlockPos .L eftStep * 20 ;NewTempYData = BlockYArray - TempBlockPos.Dow nStep * 20 ;if any( NewTempXData < AxesXLim(1) ) | any( NewTempXData > AxesXLim(2) ) |...any( NewTempYData < AxesYLim(1))Blockl ndex = OldBlockl ndex ;return;endTestArray = ismember( [NewTempXData, NewTempYData], [TotalXData, TotalYData], 'rows'); if any( TestArray )。
俄罗斯方块小游戏(HTML游戏使用JavaScript开发)
俄罗斯方块小游戏(HTML游戏使用JavaScript开发)俄罗斯方块是一款风靡全球的经典游戏,现在我们将使用JavaScript语言开发一个基于HTML的俄罗斯方块小游戏。
在这篇文章中,我将介绍游戏的设计思路、实现过程以及一些技术细节。
一、游戏设计思路打开游戏页面后,玩家将看到一个空白的游戏区域,该区域由10列和20行方格构成。
方块将从游戏区域的顶部下落,玩家需要控制方块的方向和位置,使其在下落过程中填满一行或多行。
当一行被完全填满时,该行将被消除,并且玩家得到相应的分数。
游戏的难度会逐渐增加,方块下落的速度会逐渐加快,挑战玩家的反应和操作能力。
当方块堆积到游戏区域的顶部时,游戏结束。
玩家可以选择重新开始游戏或退出游戏。
二、游戏实现过程1. 创建HTML结构首先,我们需要创建一个HTML结构,包含游戏区域以及一些控制按钮。
游戏区域可以使用一个div元素进行表示,每个方格可以使用一个span元素表示。
同时,添加开始按钮和重新开始按钮,用于控制游戏的开始和重新开始。
2. CSS样式设计为了使游戏界面美观,我们需要设计一些CSS样式。
通过设置游戏区域的背景颜色、方格的颜色及边框效果,可以使游戏界面更加具有吸引力。
3. 实现游戏逻辑使用JavaScript语言实现游戏的逻辑部分。
我们需要为方块设计一个类,定义方块的形状、位置以及移动的方法。
在游戏的运行过程中,我们需要检测按键事件,根据玩家的操作移动方块的位置。
同时,需要实现方块的下落、旋转和消除行等功能。
4. 添加事件监听为了使玩家能够操作游戏,我们需要为游戏界面添加键盘事件监听。
通过监听键盘的上、下、左、右方向键,可以控制方块的移动和旋转。
5. 计分和游戏结束在游戏进行过程中,我们需要实时更新玩家的分数,并判断游戏是否结束。
当方块堆积到游戏区域的顶部时,游戏结束,弹出游戏结束的提示框,并显示玩家的最终得分。
三、技术细节在实现俄罗斯方块小游戏的过程中,我们使用了以下技术:1. HTML:用于创建游戏界面的结构,包括游戏区域和按钮等元素。
俄罗斯方块MATLAB
俄罗斯方块MATLAB1. 简介俄罗斯方块是一款经典的益智游戏,由俄罗斯人阿列克谢·帕基特诺夫于1984年发明。
该游戏的目标是通过旋转和移动不同形状的方块,使它们在底部形成完整的水平线,以便消除。
本文档将介绍如何使用MATLAB编写俄罗斯方块游戏,并提供相应的代码示例和说明。
2. 游戏规则俄罗斯方块游戏中使用7种由4个小方块组成的不同形状的方块,这些方块可以通过旋转和平移来移动和变换。
方块在游戏区域的顶部出现,并向下移动。
玩家可以通过按下相应的键来旋转和平移方块,以使其落入一个合适的位置。
游戏中的主要目标是通过放置和消除方块,尽可能地清空游戏区域。
当一个水平行被完全填满时,它将被消除,并得分。
如果方块堆积到达游戏区域的顶部,游戏结束。
3. 游戏实现要在MATLAB中实现俄罗斯方块游戏,需要考虑以下几个方面:3.1 游戏区域表示游戏区域可以用一个二维矩阵来表示,其中的元素代表方块的状态,空闲位置为0,有方块的位置为1。
游戏区域的大小可以在代码中进行定义,并且可以在游戏进行过程中动态调整。
3.2 方块表示方块可以用一个二维矩阵来表示,其中的元素代表方块的状态,空闲位置为0,有方块的位置为1。
方块的形状可以通过旋转和变换来改变,可以通过一系列的操作来实现。
3.3 方块移动和变换玩家可以通过按下键盘上的方向键来移动和旋转方块。
移动方块时,需要检查方块是否与游戏区域的边界或已有的方块冲突,避免方块无法继续移动。
旋转方块时,需要根据方块的当前状态和旋转后的状态来判断是否可以旋转。
3.4 方块堆积和消除当方块到达底部或无法继续移动时,需要将方块固定在游戏区域中,并检查是否有水平行被完全填满。
如果有水平行被完全填满,需要将其消除并计分。
3.5 游戏结束判断当方块堆积到达游戏区域的顶部时,游戏结束,玩家可以选择重新开始或退出游戏。
4. 示例代码function tetrisGame()% 游戏初始化gameArea = zeros(20, 10); % 初始化游戏区域currentBlock = generateBlock(); % 随机生成一个方块gameover = false; % 游戏结束标志score = 0; % 初始得分while ~gameover% 显示游戏区域和当前方块drawGameArea(gameArea);drawBlock(currentBlock);% 获取玩家输入keyPressed = getKeyPress();switch keyPressedcase 'leftarrow'% 向左移动方块if canMoveLeft(currentBlock, game Area)currentBlock = moveLeft(curre ntBlock);endcase 'rightarrow'% 向右移动方块if canMoveRight(currentBlock, gam eArea)currentBlock = moveRight(curr entBlock);endcase 'downarrow'% 加速方块下落if canMoveDown(currentBlock, game Area)currentBlock = moveDown(curre ntBlock);endcase 'uparrow'% 旋转方块if canRotate(currentBlock, gameAr ea)currentBlock = rotate(current Block);endcase 'q'% 退出游戏gameover = true;otherwise% 无效输入,继续游戏end% 更新游戏区域和当前方块gameArea = updateGameArea(currentBlock, g ameArea);[gameArea, score] = clearLines(gameArea, score);% 判断游戏是否结束if isGameOver(gameArea)gameover = true;endend% 游戏结束,显示得分fprintf('游戏结束,总得分:%d\', score);end5. 总结通过使用MATLAB编写代码,我们成功实现了俄罗斯方块游戏。
俄罗斯方块小游戏编程实现
俄罗斯方块小游戏编程实现俄罗斯方块(Tetris)是一款经典的游戏,它的设计简单,玩法有趣,备受玩家喜爱。
在本文中,我们将探讨如何使用编程语言来实现俄罗斯方块小游戏。
1. 游戏介绍俄罗斯方块是一款由七种不同形状的方块组成的拼图游戏。
这些方块会从屏幕顶部逐渐下落,玩家需要通过调整方块的位置和旋转来使其完全填满一行。
当一行被填满时,该行会消除,并玩家会获得相应的分数。
游戏的目标是尽可能多地消除行并获得高分。
2. 游戏设计在编程实现俄罗斯方块游戏时,我们需要考虑以下几个关键因素:- 方块的形状:俄罗斯方块由七种不同形状的方块组成,每个方块由四个小方块组成。
- 方块的移动:玩家可以通过按下不同的按键来移动方块的位置,包括向左、向右和向下。
- 方块的旋转:方块可以按照一定的规则进行旋转,玩家可以通过按下相应的按键来实现旋转。
- 方块的下落:方块会以一定的速度从屏幕顶部下落,玩家需要控制方块的下落速度以适应游戏进程。
- 行的消除:当一行被填满时,该行会被消除,并玩家会获得相应的分数。
消除行后,上方的方块会下落填补空缺。
3. 编程实现为了编程实现俄罗斯方块游戏,我们可以选择使用一种合适的编程语言,例如Java、C++或Python。
这些语言都具备强大的图形库和用户交互功能,能够很好地支持游戏的图形界面和用户操作。
在编程实现过程中,我们可以使用面向对象的思想来设计游戏的各个组件,例如方块、游戏区域和玩家。
我们可以将方块抽象成一个类,其中包含方块的属性和操作方法。
游戏区域可以设计成一个矩形框,其中保存了方块的位置和状态。
玩家可以通过键盘输入来移动和旋转方块。
通过合理的设计和编程,我们可以实现一个功能完善的俄罗斯方块小游戏。
在游戏中,玩家可以使用键盘进行操作,控制方块的移动、旋转和下落,以达到消除行的目的并获得高分。
4. 总结俄罗斯方块小游戏是一款简单而有趣的游戏,通过编程实现它可以锻炼我们的逻辑思维和编程能力。
在本文中,我们探讨了俄罗斯方块游戏的设计要点,并提到了一些实现该游戏的编程思路。
小游戏俄罗斯方块代码(JAVA)
东西绝对不多说,直接看!看了拷贝就懂了!!,直接可以拷贝下面的东西,然后记得把那个BLOCK 的名字改成你自己的类名,这个很关键哦,不然是错的可别怪我,呵呵~~import java.awt.*;importimport javax.swing.*;import java.applet.* ;import .*;import ng.*;import java.io.*;publicclass Block extends JPanel implementsActionListener,KeyListener //应该是继承JPanel{static Button but []= newButton[6];static Button noStop =newButton( "取消暂停");static Label scoreLab =newLabel( "分数:" );static Label infoLab =newLabel( "提示:" );static Label speedLab=newLabel( "级数:" );static Label scoreTex =newLabel( "0" );static Label infoTex =newLabel( "");static Label speedTex=newLabel( "1" );static JFramejf =newJFrame();static MyTimer timer ;static ImageIcon icon=newImageIcon( "resource/Block.jpg" );static JMenuBarmb=newJMenuBar();static JMenumenu0=newJMenu("游戏");static JMenumenu1=newJMenu("帮助");static JMenuItem mi0=newJMenuItem( "新游戏");static JMenuItem mi1=newJMenuItem( "退出");static JMenuItem mi1_0=newJMenuItem("关于");static JDialog dlg_1 ;static JTextArea dlg_1_text =newJTextArea();精心整理staticint startSign =0; // 游戏开始标志0未开始1开始2暂停static StringbutLab []={ "开始游戏","重新开始","降低级数","提高级数","游戏暂停","退出游戏"};staticint game_body [][]= newint[19][10];staticint game_sign_x[]= newint[4]; //用于记录4个方格的水平位置staticint game_sign_y[]= newint[4]; //用于记录4个方格的垂直位置staticboolean downSign =false;// 是否落下staticint blockNumber=1; //砖块的编号staticint gameScore =0; // 游戏分数staticint speedMark =1;publicstaticvoid main(Stringargs[]){BlockmyBlock= newBlock();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 =newMyTimer(myBlock); //启动线程timer .setDaemon(true);timer .start();timer .suspend();}publicvoid init(){setLayout( null );for (int i=0;i<6;i++)精心整理{but [i]= newButton(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();}publicvoid actionPerformed(ActionEvente){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=newJDialog( jf ,"关于");try{FileInputStreamio= newFileInputStream( "resource/guanyu.txt" );//得到路径byte a[]= newbyte [io.available()];io.read(a);io.close();Stringstr= newString(a);dlg_1_text .setText(str );}catch (Exceptiong){}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();}精心整理}publicvoid rand_block() //随机产生砖块{int num;num=(int)(Math. random()*6)+1; //产生0~6之间的随机数blockNumber=num;switch(blockNumber){case1:block1(); blockNumber =1;break ;case2:block2(); blockNumber =2;break ;case3:block3(); blockNumber =3;break ;case4:block4(); blockNumber =4;break ;case5:block5(); blockNumber =5;break ;case6:block6(); blockNumber =6;break ;case7:block7(); blockNumber =7;break ;}}publicvoid 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_si gn_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_si gn_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]&&gam e_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;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 [1]==game_sign_y [2]&&game_sign_y[2]== game_sign_y[3]&&gam e_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; game_body[game_sign_y [3]-1][ game_sign_x [3]-1]=1; 精心整理infoTex .setText( "游戏进行中!");repaint();}}if(game_sign_x [1]==game_sign_x [2]&&game_sign_x[1]== game_sign_x[3]&&gam e_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]&&gam e_sign_x[0]== game_sign_x [3]){if(game_body [game_sign_y [0]+1][ game_sign_x[0]+1]!=2&& game_body[game_si gn_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();}}}i f (blockNumber==4&& downSign ==false )//变换转弯2有4种情况{if (game_sign_x [0]== game_sign_x [1]&& game_sign_x [0]== game_sign_x [3]&& gam e_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]&&gam e_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]&&gam e_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]&&gam e_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]&&gam e_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]&&gam e_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]&&gam e_sign_y [2]== game_sign_y [3]){if(game_body [game_sign_y [0]+1][ game_sign_x[0]-1]!=2&& game_body[game_si gn_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]&&gam e_sign_x[2]== game_sign_x [3]){if(game_body [game_sign_y [0]+1][ game_sign_x[0]+1]!=2&& game_body[game_si gn_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_si gn_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();}}}}publicvoid 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; }}}}精心整理publicvoid num_csh_restart() //重新开始时数组清零{for (int i=0;i<19;i++){for (int j=0;j<10;j++){game_body[i][j]=0;}}}publicvoid keyTyped(KeyEvente){}publicvoid keyPressed(KeyEvente){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( "游戏未开始或已结束!");}}publicvoid keyReleased(KeyEvente){}publicvoid paint(Graphicsg){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, }if (game_body[i][j]==2){g.setColor(Color. magenta);g.fill3DRect(30*j,30*(i-4),30,30, }} truetrue););}}publicvoid 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();}}publicvoid right() //向右移动{int sign=0;dingwei();for (int k=0;k<4;k++)精心整理{if (game_sign_x[k]==9||{sign=1;}}if (sign==0&& downSign {num_csh_game();for (int k=0;k<4;k++) {game_body[game_sign_y}game_body[game_sign_y[k]][==false )[k]][ game_sign_x [k]+1]=1;game_sign_x [k]+1]==2)infoTex .setText("向右移动!"); repaint();}}publicvoid down() //下落{int sign=0;dingwei();for (int k=0;k<4;k++){if (game_sign_y[k]==18||{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_ygame_body[game_sign_y)[k]+1][ game_sign_x [k]]=1;[k]+1][game_sign_x [k]]==2)精心整理infoTex .setText( "游戏进行中!");repaint();}}publicboolean 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();returntrue ;}elsereturnfalse ;}publicvoid 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];}}}}}publicvoid changeColor() // 给已经落下的块换色{downSign =false ;for (int k=0;k<4;k++){game_body[game_sign_y [k]][ game_sign_x[k]]=2; }}publicvoid 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++;}}}}publicvoid cancelDW() //将定位数组初始化{for (int k=0;k<4;k++){game_sign_x [k]=0;game_sign_y [k]=0;精心整理}}publicvoid block1() //长条{game_body[0][4]=1;game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;}publicvoid block2() //正方形{game_body[3][4]=1;game_body[2][4]=1;game_body[3][5]=1;game_body[2][5]=1;}publicvoid block3() //3 加1(下) {game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;game_body[3][5]=1;}publicvoid block4() //3 加1(中){game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;game_body[2][5]=1;}publicvoid block5() //3 加1(上){game_body[1][4]=1;game_body[2][4]=1;game_body[3][4]=1;game_body[1][5]=1;}publicvoid block6() //转折1{game_body[1][5]=1;game_body[2][5]=1;game_body[2][4]=1;game_body[3][4]=1;}publicvoid block7() //转折2{game_body[1][4]=1;game_body[2][4]=1;game_body[2][5]=1;game_body[3][5]=1;}}//定时线程class MyTimer extendsThread{Block myBlock ;public MyTimer(BlockmyBlock){this.myBlock =myBlock;}publicvoid run(){while (myBlock.startSign ==1){try {sleep ((10- myBlock.speedMark +1)*100); myBlock .down();}catch (InterruptedExceptione){}}}}。
matlab课程设计报告模板俄罗斯方块
matlab课程设计报告模板俄罗斯方块
一.需求分析
在个人电脑日益普及的今天,一些有趣的桌面游戏已经成为人们在使用计算机进行工作或学习之余休闲娱乐的
首选,而俄罗斯方块游戏是人们最熟悉的小游戏之一,它以其趣味性强,易上手等诸多特点得到了大众的认
可,因此开发此游戏软件可满足人们的一些娱乐的需求。
此俄罗斯方块游戏可以为用户提供一个可在普通个人电脑上运行的,界面美观的,易于控制的俄罗斯方块游
戏。
二,系统运行环境
操作系统选择Windows XP版本,运行环境选择MyEclipse
三.系统功能需求描述
俄罗斯方块游戏是-款适合大众的游戏软件,它适合不同年龄的人玩。
本软件要实现的功能如下:
1.游戏区:玩家可以在游戏区中堆积方块,并能够在游戏过程中随时了解得分情况。
2.游戏控制:玩家可以通过游戏控制功能来选择开始新的一局游戏,暂停或退出游戏。
3.级别设置:玩家可以根据自己的需要自行设定游戏的开始级别,级别越高,游戏速度越快,难度越大。
四,总体设计
游戏中玩家可以做的操作有:
1.以90度为单位旋转方每一格块。
2.以格子为单位左右移动方块,让方块加速落下。
3.方块移到区域最下方或是着地到其他方块上无法移动时,就会固定在该处,而新的随机图形会出现在区域上方开始落下。
4.当区域中某一列横向格子全部由方块填满,则该列会自动消除并成为玩家的得分。
同时删除的列数越多,得分指数上升。
5.当固定的方块堆到区域最上方,则游戏结束。
五.系统结构图
六.程序模块设计。
俄罗斯方块MATLAB
俄罗斯方块MATLAB俄罗斯方块是一款经典的游戏,能够锻炼逻辑思维和反应能力。
在此文档中,我们将介绍如何使用MATLAB编写俄罗斯方块游戏。
游戏规则俄罗斯方块的游戏规则非常简单。
游戏开始时,玩家面前是一个空白的矩形网格,游戏通过不断下落的方块来进行。
每个下落的方块都由四个小方块组成,它们以不同的形状和颜色出现。
玩家可以使用键盘上的方向键来控制方块的移动和旋转,目标是将方块堆叠在一起,填满一行或多行,并且不留下任何缝隙。
一旦一行被填满,这一行将被清除,并且玩家将获得得分。
游戏会逐渐加速,难度越来越大。
当方块堆叠得太高,超过屏幕的上边界时,游戏结束。
开始编写游戏首先,我们需要创建一个MATLAB函数来运行俄罗斯方块游戏。
以下是一个基础的游戏函数的框架:function tetris_game()% 初始化游戏init_game();% 游戏主循环while game_over() == false% 渲染游戏界面render();% 获取玩家输入get_player_input();% 更新游戏状态update_game_state();% 控制游戏速度control_game_speed();end% 游戏结束game_over_screen();end游戏初始化在游戏开始前,我们需要对游戏进行初始化,包括设置窗口大小、创建游戏界面、生成第一个方块等。
以下是初始化函数的一个示例:function init_game()% 设置窗口大小figure('Position', [100, 100, 400, 600]);% 创建游戏界面game_grid = zeros(20, 10);% 生成第一个方块current_block = generate_block();end游戏渲染游戏渲染是指将游戏状态以图形方式显示出来,让玩家可以看到当前的游戏界面。
下面是一个简单的渲染函数的示例:function render()% 绘制游戏界面draw_game_grid();% 绘制当前方块draw_block(current_block);% 显示得分等信息show_game_info();end玩家输入玩家输入是通过键盘来控制方块的移动和旋转。
俄罗斯方块游戏(HTML游戏使用JavaScript开发)
俄罗斯方块游戏(HTML游戏使用JavaScript开发)俄罗斯方块是一款经典的益智类游戏,深受广大玩家的喜爱。
本文将介绍一种使用JavaScript开发的网页版俄罗斯方块游戏。
1. 游戏概述俄罗斯方块游戏是由若干个不同形状的方块组成,玩家通过操控下落方块的移动和旋转来使它们在游戏界面中完整地拼接成一行或多行。
每当完成一行,该行将被消除并得分。
当方块堆积到达游戏界面的顶部时,游戏结束。
2. 开发环境为了实现网页版俄罗斯方块游戏,我们将使用HTML、CSS和JavaScript这三种基本的Web开发技术。
2.1 HTMLHTML(超文本标记语言)用于构建网页的结构和内容。
对于俄罗斯方块游戏,我们需要使用HTML来创建游戏界面、显示得分等。
2.2 CSSCSS(层叠样式表)用于设置网页的样式和布局。
我们可以使用CSS来美化游戏界面,使其更具吸引力和易读性。
2.3 JavaScriptJavaScript是一种用于开发动态网页和交互式元素的编程语言。
在开发俄罗斯方块游戏中,我们将使用JavaScript来实现游戏的逻辑和交互效果。
3. 游戏开发步骤3.1 创建游戏界面首先,我们需要在HTML中创建游戏界面的容器,用于显示下落方块和游戏得分等信息。
我们可以使用HTML的div元素来实现这一目标,并使用CSS来美化游戏界面。
3.2 定义方块的形状我们需要定义不同形状的方块。
通过使用JavaScript的数组和对象,我们可以将每个方块表示为一个包含一系列坐标的集合。
这些坐标定义了方块的位置和形状。
3.3 控制方块的移动和旋转在游戏中,玩家需要能够控制方块的移动和旋转。
我们可以使用JavaScript编写函数来实现这些操作。
通过监听键盘事件,我们可以实现方块的左右移动和快速下落,同时通过旋转方块的形状来适应不同的游戏情况。
3.4 检测碰撞和消行在游戏中,我们需要检测方块与其他方块或游戏界面边界的碰撞,以及当一行满格时进行消行操作并更新得分。
俄罗斯方块游戏原代码
#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键,退出游戏 */}}。
有趣的MATLAB1.游戏程序
有趣的MATLAB1.游戏程序MATLAB游戏程序目录1.空格游戏 (2)2.华容道 (3)3.凑五子棋 (14)4.2048 (19)5.俄罗斯方块 (24)1.空格游戏function pintu1()A = gen();G = [1 2 3;4 5 6;7 8 0];drawmap(A);while 1[xpos,ypos] = ginput(1);col = ceil(xpos);row = 3-ceil(ypos)+1;num = A(row,col);if row>1&A(row-1,col)==0A(row-1,col) = num;A(row,col) = 0;endif row<3&A(row+1,col)==0A(row+1,col) = num;A(row,col) = 0;endif col>1&A(row,col-1)==0A(row,col-1) = num;A(row,col) = 0;endif col<3&A(row,col+1)==0A(row,col+1) = num;A(row,col) = 0;enddrawmap(A)zt = abs(A-G);if sum(zt(:))==0msgbox('恭喜您成功完成!')breakendendfunction drawmap(A)clf;hold online([0 3],[0 0],'linewidth',4);line([3 3],[0 3],'linewidth',4);line([0 3],[3 3],'linewidth',4);line([0 0],[0 3],'linewidth',4);for i = 1:3for j = 1:3drawrect([j-1 3-i],[j 3-i],[j 3-i+1],[j-1 3-i+1],'y',A(i,j)); endendaxis equalaxis offfunction drawrect(x1,x2,x3,x4,color,num)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)if num==0text(0.5*(x1(1)+x2(1)),0.5*(x1(2)+x4(2)),' ','fontsize',24)elsetext(0.5*(x1(1)+x2(1))-0.05,0.5*(x1(2)+x4(2)),num2str(num),'fontsize',24) endfunction y = gen()y = inf*ones(1,9);for i = 1:9while 1a = randint(1,1,9);if isempty(find(y==a))y(i) = a;breakendendendy = reshape(y,3,3);2.华容道function huarongdao()A = [2 1 1 3;2 1 1 3;4 6 6 5;4 7 7 5;7 0 0 7];drawmap(A)while 1if A(5,2)==1&A(5,3)==1ch = menu('曹操成功逃出华容道!如果要继续玩,按“是”,否则按“否”','是','否');switch chcase 1huarongdao();case 2returnendend[xpos,ypos] = ginput(1);col = ceil(xpos);row = 5-ceil(ypos)+1;juese = A(row,col);switch juesecase 1%点击了曹操[I,J] = find(A==1);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0]) A([rn,rm],ln-1)=[1;1];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0]) A([rn,rm],lm+1)=[1;1];A([rn,rm],ln)=[0;0];drawmap(A)end%判断是否能向下移if rn>1&isequalm(A(rn-1,[ln,lm]),[0,0]) A(rn-1,[ln,lm])=[1,1];A(rn+1,[ln,lm])=[0,0];drawmap(A)end%判断是否能向上移if rm<5&isequalm(A(rm+1,[ln,lm]),[0,0]) A(rm+1,[ln,lm])=[1,1];A(rm-1,[ln,lm])=[0,0];drawmap(A)endcase 2% 点击了黄忠[I,J] = find(A==2);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0]) A([rn,rm],ln-1)=[2;2];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0]) A([rn,rm],lm+1)=[2;2];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 2;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 2;A(rm-1,ln) = 0;drawmap(A)endelse%只能上移A(rn-1,ln) = 2;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 2;A(rm-1,ln) = 0;drawmap(A)endcase 3%张飞[I,J] = find(A==3);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[3;3];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[3;3];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 3;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 3;A(rm-1,ln) = 0;endelse%只能上移A(rn-1,ln) = 3;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 3;A(rm-1,ln) = 0;endcase 4%马超[I,J] = find(A==4);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0])A([rn,rm],ln-1)=[4;4];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0])A([rn,rm],lm+1)=[4;4];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 4;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm+1,ln) = 4;endelse%只能上移A(rn-1,ln) = 4;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 4;A(rm-1,ln) = 0;drawmap(A)endcase 5%赵云[I,J] = find(A==5);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向左移if ln>1&isequalm(A([rn,rm],ln-1),[0;0]) A([rn,rm],ln-1)=[5;5];A([rn,rm],lm)=[0;0];drawmap(A)end%判断是否能向右移if lm<4&isequalm(A([rn,rm],lm+1),[0;0]) A([rn,rm],lm+1)=[5;5];A([rn,rm],ln)=[0;0];drawmap(A)endif rn>1&A(rn-1,ln)==0if rm<5&A(rm+1,ln)==0%如果又能上移又能下移,则要点击的部位ch = menu('请选择移到的方向:','上','下')switch chcase 1%上移A(rn-1,ln) = 5;A(rn+1,ln) = 0;drawmap(A)case 2%下移A(rm-1,ln) = 0;drawmap(A)endelse%只能上移A(rn-1,ln) = 5;A(rn+1,ln) = 0;drawmap(A)endelseif rm<5&A(rm+1,ln)==0A(rm+1,ln) = 5;A(rm-1,ln) = 0;drawmap(A)endcase 6%关羽[I,J] = find(A==6);rm = max(I);rn = min(I);lm = max(J);ln = min(J);%判断是否能向上移if rn>1 & isequalm(A(rn-1,[ln,lm]),[0,0])A(rn-1,[ln,lm])=[6,6];A(rn,[ln,lm])=[0,0];drawmap(A)end%判断是否能向下移if rm<5&isequalm(A(rm+1,[ln,lm]),[0,0])A(rm+1,[ln,lm])=[6,6];A(rm,[ln,lm])=[0,0];drawmap(A)endif ln>1&A(rn,ln-1)==0if lm<4&A(rm,lm+1)==0%如果又能左移又能右移,则要点击的部位ch = menu('请选择移到的方向:','左','右')switch chcase 1%左移A(rm,ln-1) = 6;A(rm,ln+1) = 0;drawmap(A)case 2%右移A(rm,lm+1) = 6;A(rm,lm-1) = 0;drawmap(A)endelse%只能左移A(rm,ln-1) = 6;A(rm,ln+1) = 0;drawmap(A)endelseif lm<4&A(rm,lm+1)==0A(rm,lm+1) = 6;A(rm,lm-1) = 0;drawmap(A)endcase 7 %小卒if row>1&A(row-1,col)==0 % 上if col>1&A(row,col-1)==0 % 左ch = menu('请选择移到的方向:','上','左') switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col-1) = 7;A(row,col) = 0;drawmap(A)endelseif row<5&A(row+1,col)==0% 下ch = menu('请选择移到的方向:','上','下') switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0 %右switch chcase 1A(row-1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse %只能向上A(row-1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col>1&A(row,col-1)==0%左if row<5&A(row+1,col)==0%下ch = menu('请选择移到的方向:','左','下') switch chcase 1A(row,col-1) = 7;A(row,col) = 0;drawmap(A)case 2A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0%右switch chcase 1A(row,col-1) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse%只能向左A(row,col-1) = 7;A(row,col) = 0;drawmap(A)endelseif row<5&A(row+1,col)==0%下if col<4&A(row,col+1)==0%右ch = menu('请选择移到的方向:','下','右') switch chcase 1A(row+1,col) = 7;A(row,col) = 0;drawmap(A)case 2A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endelse%只能向下A(row+1,col) = 7;A(row,col) = 0;drawmap(A)endelseif col<4&A(row,col+1)==0%只能向右A(row,col+1) = 7;A(row,col) = 0;drawmap(A)endendendfunction drawmap(A)clfhold on%曹操[I J] = find(A==1);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'r')text(0.5*(x1+x2)-0.5,0.5*(y1+y2),'曹操','fontsize',28)% 黄忠[I,J] = find(A==2);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'黄','fontsize',28)text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'忠','fontsize',28) % 张飞[I,J] = find(A==3);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'张','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'飞','fontsize',28) % 马超[I,J] = find(A==4);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'马','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'超','fontsize',28) % 赵云[I,J] = find(A==5);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y1),'赵','fontsize',28) text(0.5*(x1+x2)-0.26,0.5*(0.5*(y1+y2)+y2),'云','fontsize',28) % 关羽[I,J] = find(A==6);x1 = min(J)-1;x2 = max(J);y1 = 5-(min(I)-1);y2 = 5-max(I);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'y')text(0.5*(x1+0.5*(x1+x2))-0.26,0.5*(y1+y2),'关','fontsize',28) text(0.5*(0.5*(x1+x2)+x2)-0.26,0.5*(y1+y2),'羽','fontsize',28) %小卒[I,J] = find(A==7);for i = 1:length(I)x1 = J(i)-1;x2 = J(i);y1 = 5-(I(i)-1);y2 = 5-I(i);drawrect([x1,y1],[x2,y1],[x2,y2],[x1,y2],'g')text(0.5*(x1+x2)-0.26,0.5*(y1+y2),'卒','fontsize',28)end% 画背景line([0 4],[0 0],'color','b','linewidth',4)line([0 4],[5 5],'color','b','linewidth',4)line([0 0],[0 5],'color','b','linewidth',4)line([4 4],[0 5],'color','b','linewidth',4)for i = 1:4line([0 4],[i i],'color','b','linestyle','--')endfor i = 1:3line([i i],[0 5],'color','b','linestyle','--')endaxis equalaxis([0 4 0 5])axis offfunction drawrect(x1,x2,x3,x4,color)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)3.凑五子棋function [ ] = five()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha sshf=figure('resize','off','name','five',...'position',[360 280 560 420],'numbertitle','off');set(gcf,'menubar','none','color',[0.3 0.3 0.3])set(gca,'position',[0.2300 0.1100 0.7750 0.8150]) set(gca,'xlim',[0,9],'ylim',[0,9])set(ha,'xtick',[],'ytick',[],'box','on')set(ha,'color',[0.7 0.6,0.6])set(ha,'DataAspectRatio',[1 1 1],'PlotBoxAspectRatio',[1 1 1]) x=repmat([0;9],1,9);y=[1:9;1:9];line(x,y,'color','k')line(y,x,'color','k')hst=uicontrol('style','text','string','Score','fontsize',30,...'units','normal','position',[0.02,0.55,0.26,0.14],'parent',hf,...'ForegroundColor','w','backgroundcolor',[0.3 0.3 0.3],...'fontweight','bold');hsc=uicontrol('style','text','string','0','fontsize',24,...'units','normal','position',[0.02,0.4,0.26,0.14],'parent',hf,...'ForegroundColor','w','backgroundcolor',[0.3 0.3 0.3],...'fontweight','bold');hbt=uicontrol('style','pushbutton','string','Restart','fontsize',1 8,...'units','normal','position',[0.02,0.16,0.26,0.14],'parent',hf,... 'fontweight','bold','callback',@restart);color=[...1 1 0;1 0 1;0 1 1;1 0 0;0 1 0;0 0 1;0.7 0.3 0;];h1=annotation('ellipse',[0.04,0.84,0.06,0.08],'facecolor','k'); h2=annotation('ellipse',[0.12,0.84,0.06,0.08],'facecolor','k'); h3=annotation('ellipse',[0.2,0.84,0.06,0.08],'facecolor','k'); set(ha,'buttondownfcn',@select2)initializefunction initialize()global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ssa=zeros(9);h=zeros(9)*NaN;m1=[];n1=[];m2=[];n2=[];ss=0;k=rs(1:81,5);t=ceil(rand(1,5)*7);a(k)=t;[m,n] = ind2sub([9,9],k);y=9.5-m;x=n-0.5;for p=1:5h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',... 'buttondownfcn',@select1);endt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function [k]=rs(s,n);for m=1:nt=ceil(rand*length(s));k(m)=s(t);s(t)=[];endfunction select1(src,eventdata)global a h m1 n1n1=ceil(get(src,'xdata'));m1=ceil(9-get(src,'ydata'));set(h(~isnan(h)),'markeredgecolor','none')set(src,'markeredgecolor','w')function select2(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ss if isempty(m1) || isempty(n1)returnendcp=get(src,'currentpoint');n2=ceil(cp(1,1));m2=ceil(9-cp(1,2));if a(m2,n2)returnendb=~a;b(m1,n1)=1;b=bwlabel(b,4);if b(m1,n1)~=b(m2,n2)enda(m2,n2)=a(m1,n1);a(m1,n1)=0;h(m2,n2)=h(m1,n1);h(m1,n1)=NaN;set(h(m2,n2),'xdata',n2-0.5,'ydata',9.5-m2,'markeredgecolor','none') m1=[];n1=[];judgement;if sum(sum(~a))<3hgo=text(1,4.5,'Game Over','fontsize',36,'fontweight',...'bold','parent',src);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendif ~ssnew;endfunction judgementglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssb=logical(zeros(9,9));ss=0;left=0;right=0;up=0;down=0;lu=0;rd=0;ld=0;ru=0;while n2-left-1>0 && a(m2,n2-left-1)==a(m2,n2)left=left+1;endwhile n2+right+1<10 && a(m2,n2+right+1)==a(m2,n2)right=right+1;endwhile m2-up-1>0 && a(m2-up-1,n2)==a(m2,n2)up=up+1;endwhile m2+down+1<10 && a(m2+down+1,n2)==a(m2,n2) down=down+1;endwhile n2-lu-1>0 && m2-lu-1>0 && a(m2-lu-1,n2-lu-1)==a(m2,n2) lu=lu+1;endwhile n2+rd+1<10 && m2+rd+1<10 && a(m2+rd+1,n2+rd+1)==a(m2,n2) rd=rd+1;endwhile n2-ld-1>0 && m2+ld+1<10 && a(m2+ld+1,n2-ld-1)==a(m2,n2) ld=ld+1;endwhile n2+ru+1<10 && m2-ru-1>0 && a(m2-ru-1,n2+ru+1)==a(m2,n2) ru=ru+1;endif left+right+1>=5b(m2,n2-left:n2+right)=1;endif up+down+1>=5b(m2-up:m2+down,n2)=1;endif lu+rd+1>=5ind=sub2ind([9,9],m2-lu:m2+rd,n2-lu:n2+rd);b(ind)=1;endif ld+ru+1>=5ind=sub2ind([9,9],m2+ld:-1:m2-ru,n2-ld:n2+ru);b(ind)=1;endif sum(sum(b))a(b)=0;delete(h(b));h(b)=NaN;score=score+sum(sum(b));set(hsc,'string',num2str(score))ss=1;endfunction newglobal a h m1 n1 m2 n2 t h1 h2 h3 color score hsc hak=rs(find(~a),3);a(k)=t;[mt,nt] = ind2sub([9,9],k);y=9.5-mt;x=nt-0.5;for p=1:3h(k(p))=line(x(p),y(p),'marker','o','markersize',24,...'markerfacecolor',color(t(p),:),'markeredgecolor','none',... 'buttondownfcn',@select1);endfor p=1:3m2=mt(p);n2=nt(p);judgement;endif sum(sum(~a))==0hgo=text(1,4.5,'Game Over','fontsize',36,'fontweight',... 'bold','parent',ha);pause(3)delete(hgo);delete(h(~isnan(h)))set(hsc,'string','0')initialize;returnendt=ceil(rand(1,3)*7);set(h1,'facecolor',color(t(1),:))set(h2,'facecolor',color(t(2),:))set(h3,'facecolor',color(t(3),:))function restart(src,eventdata)global a h m1 n1 m2 n2 t h1 h2 h3 color score hsc ha ssdelete(h(~isnan(h)))set(hsc,'string','0')initialize;4.2048function g2048(action)global totalscore flag score_board if nargin<1figure_h=figure;set(figure_h,'Units','points')set(figure_h,'UserData',figure_h); totalscore=0;flag=0;score_board=zeros(1,16);action='initialize';endswitch action。
MATLAB游戏编程实例(拼图)
MATLAB游戏编程实例(拼图)这是一个简单的游戏,只要把数字按顺序排好就可以了。
游戏方法是用鼠标点中数字,如果该数字相邻的格子为空,则自动移到到该空格。
本程序是由realghost编写,如果有问题可以与联系。
附图如下:function pintu1()A = gen()G = [1 2 3;4 5 6;7 8 0];drawmap(A);while 1[xpos,ypos] = ginput(1);col = ceil(xpos);row = 3-ceil(ypos)+1;num = A(row,col);if row>1&A(row-1,col)==0A(row-1,col) = num;A(row,col) = 0;endif row<3&A(row+1,col)==0A(row+1,col) = num;A(row,col) = 0;endif col>1&A(row,col-1)==0A(row,col-1) = num;A(row,col) = 0;endif col<3&A(row,col+1)==0A(row,col+1) = num;A(row,col) = 0;enddrawmap(A)zt = abs(A-G);if sum(zt(:))==0msgbox('??ò??-3é1|?′o?í?£?')breakendendfunction drawmap(A)clf;hold online([0 3],[0 0],'linewidth',4);line([3 3],[0 3],'linewidth',4);line([0 3],[3 3],'linewidth',4);line([0 0],[0 3],'linewidth',4);for i = 1:3for j = 1:3drawrect([j-1 3-i],[j 3-i],[j 3-i+1],[j-1 3-i+1],'y',A(i,j));endendaxis equalaxis offfunction drawrect(x1,x2,x3,x4,color,num)x = [x1(1) x2(1) x3(1) x4(1)];y = [x1(2) x2(2) x3(2) x4(2)];fill(x,y,color)if num==0text*(x1(1)+x2(1)),*(x1(2)+x4(2)),' ','fontsize',24)elsetext*(x1(1)+x2(1)),*(x1(2)+x4(2)),num2str(num),'fontsize',24)endfunction y = gen()y = inf*ones(1,9);for i = 1:9while 1a = randint(1,1,9);if isempty(find(y==a)) y(i) = a;breakendendendy = reshape(y,3,3);。
88行代码实现俄罗斯方块游戏(含讲解)
88行代码实现俄罗斯方块游戏(含讲解)在正式阅读本文之前,请你记得你应该用娱乐的心态来看,本代码所使用到的技巧,在工作了的人眼里会觉得很纠结,很蛋疼,很不可理喻,很丑,注意,是你蛋疼,不关我的事通常,写一个俄罗斯方块,往往动不动就几百行,甚至上千行,而这里只有88行正所谓头脑风暴,打破常规。
这里将使用很多不平常的手段来减少代码但为了能更通用,一份控制台版本的代码,同样是88行,直接复制到VC即可编译:#include<windows.h>#include<stdio.h>#include<time.h>#include<conio.h>#include<stdlib.h>char gcText[] = " 1LJTSZ#";struct tetris {int _pool[16][32], (*pool)[32], tmap[8][4][16];int x, y, s, st, t;}gt;void trsInit() {int sp[8][4] = {{15,4369},{23,785,116,547},{71,275,113,802},{39,305,114,562},{54,561},{99,306},{51,51},{-1}};int *p, i, j, b;for (p = sp[0]; *p >= 0; ++p) if ( *p == 0 ) *p = p[-2];gt.pool = >._pool[4];for (j = 0; j < 7; ++j)for (i = 0; i < 4; ++i)for (b = 0; b < 16; ++b)gt.tmap[j+1][i][b] = (sp[j][i] & 1) * (j + 1),sp[j][i] >>= 1;memset(gt._pool, -1, sizeof(gt._pool));for (i = 0; i < 10; ++i)memset(>.pool[i], 0, sizeof(int[21]));return ;}int trsCopy(int sp[], int x, int y, int c) {int i, cx, cy;for (i = 0; i < 16; ++i) if (sp[i]) {cx = x + (i & 3), cy = y + (i >> 2);if (gt.pool[cx][cy])if (c == 2) gt.pool[cx][cy] = 0; else return0;if (c==1) gt.pool[cx][cy] = sp[i];}return1;}int trsScene() {int x, y = 0;COORD pos = {0};gt.s = rand() % 7 + 1, gt.st = gt.t = 0;gt.x = 3, gt.y = 0;for (--gt.t; ; Sleep(1), --gt.t) {int k = 0;while (kbhit()) {k = getch();if (k == 27) return0;if (k == 'A' || k == 'a') {if (trsCopy(gt.tmap[gt.s][gt.st], gt.x-1, gt.y, 0)) --gt.x;} else if (k == 'D' || k == 'd') {if (trsCopy(gt.tmap[gt.s][gt.st], gt.x+1, gt.y, 0)) ++gt.x;} else if (k == 'W' || k == 'w') {if (trsCopy(gt.tmap[gt.s][(gt.st+1) % 4], gt.x, gt.y, 0))gt.st = (gt.st+1) % 4;}}if (k == 'S' || k == 's' || gt.t < 0) {if (trsCopy(gt.tmap[gt.s][gt.st], gt.x, gt.y+1, 0))++gt.y,gt.t=50;else {trsCopy(gt.tmap[gt.s][gt.st], gt.x, gt.y, 1);for (--y; y > 0; --y) {for (x = 0; gt.pool[x][y] > 0; ++x);if (gt.pool[x][y] < 0)for (k = y++; k > 0; --k)for (x = 0; gt.pool[x][0] >= 0; ++x)gt.pool[x][k] = gt.pool[x][k-1];}return1;}}trsCopy(gt.tmap[gt.s][gt.st], gt.x, gt.y, 1);SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), pos);for (y = 1; gt.pool[0][y] >= 0; ++y,putchar(10)) {for (x = 0; gt.pool[x][0] >= 0; ++x) {putchar(gcText[gt.pool[x][y]]);}}trsCopy(gt.tmap[gt.s][gt.st], gt.x, gt.y, 2);}}int main() {srand((unsigned)time(NULL));for (trsInit(); trsScene(); );return0;}以下是对代码的压缩方法进行分析首先,通常我们需要准备7种方块,4个方向的形状表,相当多的俄罗斯方块程序就是在开头写了这样一个很长的数组定义,有的光这个定义就直接超100行了,这个程序是怎么实现的呢?其实这个程序,同样是使用一个7*4*16的数组来保存这个形状表,但是,它没有直接初始化,见这个数组的定义:int sp[8][4] = {{15,4369},{23,785,116,547},{71,275,113,802},{39,305,114,562},{54,561},{99,306},{51,51},{-1}};这个莫名其妙的数组的值是什么意思呢?其实很好猜的,我们尝试把这些数化为二进制:15 = 11114369 = 1000100010001合理地四位四位拆开,从低位到高位,从左到右,从上到下排列一下:11110000000000001000100010001000你终于发现,这就是长条方块的两个形状后面类似然后你会发现,这个数组并不完整,有的只定义了两个形状,有的是四个形状,没定义的数会默认置0的,这个怎么解释?看这个数组定义的下面第二行:for (p = sp[0]; *p >= 0; ++p) if ( *p == 0 ) *p = p[-2];意思是找出这个数组为0的元素,用它前面的元素值填上即*p = p[-2]而数组中最后一个元素值-1起监督头的作用,用于让这个循环跳出虽然可以把这些常数全直接写在数组里,但常数太多显得不太好,就这样写了之后你看到这行代码:gt.pool = >._pool[4];为什么定义两个pool呢?因为我们需要在原来的pool的界外用-1值填充,以便后面做碰撞检测减少不必要的代码但如果直接用原来的_pool,那每次访问都要加上一个偏移常数,不美观且显得代码长,就用另一个指针直接指向开始的位置然后,后面的三重循环就是解开那个位压缩数组以初始化gt.tmap数组,这个数组就是记录7*4种形状的数组再下面三行,就是初始化pool,游戏区为0,界外为-1而其中,i < 10决定了游戏池的宽度为10,sizeof(int[21])决定了游戏池的高度是20 (0我们不使用,这一行有特殊作用,后文会讲)用memset也是为了免写二重循环而已。
俄罗斯方块游戏程序设计
俄罗斯方块游戏程序设计报告学号:姓名:难度:****知识点:(1)绘图(2)键盘事件处理(3)定时器控件(4)多模块程序设计(5)文本文件的读写1.功能要求:(1)启动程序,单击“开始”或“回车”键开始游戏。
不同形状以随机颜色出现,出现时的方向是随机的;(2)使用“选项”菜单画框提供按键方案;(3)游戏过程中可以单击窗口右下角的“暂停”和“继续”,也可使用“回车”键控制,打开“选项”对话框时,程序自动进入暂停状态;(4)计分遵循一次消去一行加一百,两行三百,三行七百,四行一千五,程序自动记录并显示历史的最高分;(5)得分每增加2000分,程序自动将方块下落速度提高一档。
2.需要解决的疑难问题和方法:(1)本程序在模块中定义变量:Private blnGrid(0 To 19, 0 To 9) As Boolean '网格Private lngColor(0 To 19, 0 To 9) As Long '网格绘制颜色Private blnBlock(0 To 4, 0 To 3, 0 To 3, 0 To 3) As Boolean '五种方块的四种不同方位Private blnStarted As Boolean '是否已开始玩Dim intTypeCur As Integer '当前方块的类型Dim lngColorCur As Long '当前方块的颜色Dim intOrieCur As Integer '当前方块的方位Dim intOrieNext As Integer '当前方块的下一个方位Dim intXCur As Integer '当前方块的当前位置Dim intYCur As IntegerDim intXNext As Integer '当前方块的下一个位置Dim intYNext As IntegerPublic intDownDistance As Integer '快速下降时的下降距离Public blnClockWise As Boolean '方块旋转方向Public blnShowNext As Boolean '是否显示下一个方块Public blnScheme As Boolean '按键方案Dim lngScore As Long '得分Dim intTypeNew As Integer '下一个方块的类型Dim lngColorNew As Long '下一个方块的颜色Dim intOrieNew As Integer '下一个方块的方位Dim lngHighScore As LongDim blnRedraw As Boolean(2)画10×20的网格:Dim i As Integer, j As Integer'去掉旧图象For i = 0 To 3If i + intYCur >= 0 And i + intYCur <= 19 Then '如果在大方框外,则不绘制For j = 0 To 3If j + intXCur >= 0 And j + intXCur <= 9 ThenIf (j + intXCur >= 0) And (j + intXCur <= 9) And (blnBlock(intTypeCur, intOrieCur, i, j)) And Not blnGrid(i + intYCur, j + intXCur) ThenpicGrid.Line ((j + intXCur) * 20 + 2, (i + intYCur) * 20 + 2)-((j + intXCur) * 20 + 19, (i + intYCur) * 20 + 19), vbBlack, BpicGrid.Line ((j + intXCur) * 20 + 4, (i + intYCur) * 20 + 4)-((j + intXCur) * 20 + 17, (i + intYCur) * 20 + 17), vbWhite, BFEnd IfEnd IfNextEnd IfNext'画新图象For i = 0 To 3If i + intYNext >= 0 And i + intYNext <= 19 Then '如果在大方框外,则不绘制For j = 0 To 3If (j + intXNext >= 0) And (j + intXNext <= 9) And (blnBlock(intTypeCur, intOrieNext, i, j)) Then picGrid.Line ((j + intXNext) * 20 + 2, (i + intYNext) * 20 + 2)-((j + intXNext) * 20 + 19, (i + intYNext) * 20 + 19), lngColorCur, BpicGrid.Line ((j + intXNext) * 20 + 4, (i + intYNext) * 20 + 4)-((j + intXNext) * 20 + 17, (i + intYNext) * 20 + 17), lngColorCur, BFEnd IfNextEnd If(3)五种方块形状:'I 型方块数据blnBlock(0, 0, 0, 0) = False: blnBlock(0, 0, 0, 1) = False: blnBlock(0, 0, 0, 2) = True: blnBlock(0, 0, 0, 3) = False blnBlock(0, 0, 1, 0) = False: blnBlock(0, 0, 1, 1) = False: blnBlock(0, 0, 1, 2) = True: blnBlock(0, 0, 1, 3) = False blnBlock(0, 0, 2, 0) = False: blnBlock(0, 0, 2, 1) = False: blnBlock(0, 0, 2, 2) = True: blnBlock(0, 0, 2, 3) = False blnBlock(0, 0, 3, 0) = False: blnBlock(0, 0, 3, 1) = False: blnBlock(0, 0, 3, 2) = True: blnBlock(0, 0, 3, 3) = FalseblnBlock(0, 1, 0, 0) = False: blnBlock(0, 1, 0, 1) = False: blnBlock(0, 1, 0, 2) = False: blnBlock(0, 1, 0, 3) = False blnBlock(0, 1, 1, 0) = True: blnBlock(0, 1, 1, 1) = True: blnBlock(0, 1, 1, 2) = True: blnBlock(0, 1, 1, 3) = TrueblnBlock(0, 1, 3, 0) = False: blnBlock(0, 1, 3, 1) = False: blnBlock(0, 1, 3, 2) = False: blnBlock(0, 1, 3, 3) = FalseblnBlock(0, 2, 0, 0) = False: blnBlock(0, 2, 0, 1) = False: blnBlock(0, 2, 0, 2) = True: blnBlock(0, 2, 0, 3) = False blnBlock(0, 2, 1, 0) = False: blnBlock(0, 2, 1, 1) = False: blnBlock(0, 2, 1, 2) = True: blnBlock(0, 2, 1, 3) = False blnBlock(0, 2, 2, 0) = False: blnBlock(0, 2, 2, 1) = False: blnBlock(0, 2, 2, 2) = True: blnBlock(0, 2, 2, 3) = False blnBlock(0, 2, 3, 0) = False: blnBlock(0, 2, 3, 1) = False: blnBlock(0, 2, 3, 2) = True: blnBlock(0, 2, 3, 3) = FalseblnBlock(0, 3, 0, 0) = False: blnBlock(0, 3, 0, 1) = False: blnBlock(0, 3, 0, 2) = False: blnBlock(0, 3, 0, 3) = False blnBlock(0, 3, 1, 0) = False: blnBlock(0, 3, 1, 1) = False: blnBlock(0, 3, 1, 2) = False: blnBlock(0, 3, 1, 3) = FalseblnBlock(0, 3, 2, 0) = True: blnBlock(0, 3, 2, 1) = True: blnBlock(0, 3, 2, 2) = True: blnBlock(0, 3, 2, 3) = True blnBlock(0, 3, 3, 0) = False: blnBlock(0, 3, 3, 1) = False: blnBlock(0, 3, 3, 2) = False: blnBlock(0, 3, 3, 3) = False'反L 型方块数据blnBlock(1, 0, 0, 0) = False: blnBlock(1, 0, 0, 1) = True: blnBlock(1, 0, 0, 2) = True: blnBlock(1, 0, 0, 3) = TrueblnBlock(1, 0, 1, 0) = False: blnBlock(1, 0, 1, 1) = False: blnBlock(1, 0, 1, 2) = False: blnBlock(1, 0, 1, 3) = True blnBlock(1, 0, 2, 0) = False: blnBlock(1, 0, 2, 1) = False: blnBlock(1, 0, 2, 2) = False: blnBlock(1, 0, 2, 3) = FalseblnBlock(1, 0, 3, 0) = False: blnBlock(1, 0, 3, 1) = False: blnBlock(1, 0, 3, 2) = False: blnBlock(1, 0, 3, 3) = FalseblnBlock(1, 1, 0, 0) = False: blnBlock(1, 1, 0, 1) = False: blnBlock(1, 1, 0, 2) = True: blnBlock(1, 1, 0, 3) = True blnBlock(1, 1, 1, 0) = False: blnBlock(1, 1, 1, 1) = False: blnBlock(1, 1, 1, 2) = True: blnBlock(1, 1, 1, 3) = False blnBlock(1, 1, 2, 0) = False: blnBlock(1, 1, 2, 1) = False: blnBlock(1, 1, 2, 2) = True: blnBlock(1, 1, 2, 3) = False blnBlock(1, 1, 3, 0) = False: blnBlock(1, 1, 3, 1) = False: blnBlock(1, 1, 3, 2) = False: blnBlock(1, 1, 3, 3) = FalseblnBlock(1, 2, 0, 0) = False: blnBlock(1, 2, 0, 1) = True: blnBlock(1, 2, 0, 2) = False: blnBlock(1, 2, 0, 3) = FalseblnBlock(1, 2, 1, 0) = False: blnBlock(1, 2, 1, 1) = True: blnBlock(1, 2, 1, 2) = True: blnBlock(1, 2, 1, 3) = TrueblnBlock(1, 2, 2, 0) = False: blnBlock(1, 2, 2, 1) = False: blnBlock(1, 2, 2, 2) = False: blnBlock(1, 2, 2, 3) = FalseblnBlock(1, 2, 3, 0) = False: blnBlock(1, 2, 3, 1) = False: blnBlock(1, 2, 3, 2) = False: blnBlock(1, 2, 3, 3) = FalseblnBlock(1, 3, 0, 0) = False: blnBlock(1, 3, 0, 1) = False: blnBlock(1, 3, 0, 2) = False: blnBlock(1, 3, 0, 3) = True blnBlock(1, 3, 1, 0) = False: blnBlock(1, 3, 1, 1) = False: blnBlock(1, 3, 1, 2) = False: blnBlock(1, 3, 1, 3) = True blnBlock(1, 3, 2, 0) = False: blnBlock(1, 3, 2, 1) = False: blnBlock(1, 3, 2, 2) = True: blnBlock(1, 3, 2, 3) = True blnBlock(1, 3, 3, 0) = False: blnBlock(1, 3, 3, 1) = False: blnBlock(1, 3, 3, 2) = False: blnBlock(1, 3, 3, 3) = False'正L型方块数据blnBlock(2, 0, 0, 0) = False: blnBlock(2, 0, 0, 1) = True: blnBlock(2, 0, 0, 2) = True: blnBlock(2, 0, 0, 3) = TrueblnBlock(2, 0, 2, 0) = False: blnBlock(2, 0, 2, 1) = False: blnBlock(2, 0, 2, 2) = False: blnBlock(2, 0, 2, 3) = False blnBlock(2, 0, 3, 0) = False: blnBlock(2, 0, 3, 1) = False: blnBlock(2, 0, 3, 2) = False: blnBlock(2, 0, 3, 3) = FalseblnBlock(2, 1, 0, 0) = False: blnBlock(2, 1, 0, 1) = False: blnBlock(2, 1, 0, 2) = True: blnBlock(2, 1, 0, 3) = False blnBlock(2, 1, 1, 0) = False: blnBlock(2, 1, 1, 1) = False: blnBlock(2, 1, 1, 2) = True: blnBlock(2, 1, 1, 3) = False blnBlock(2, 1, 2, 0) = False: blnBlock(2, 1, 2, 1) = False: blnBlock(2, 1, 2, 2) = True: blnBlock(2, 1, 2, 3) = True blnBlock(2, 1, 3, 0) = False: blnBlock(2, 1, 3, 1) = False: blnBlock(2, 1, 3, 2) = False: blnBlock(2, 1, 3, 3) = FalseblnBlock(2, 2, 0, 0) = False: blnBlock(2, 2, 0, 1) = False: blnBlock(2, 2, 0, 2) = False: blnBlock(2, 2, 0, 3) = True blnBlock(2, 2, 1, 0) = False: blnBlock(2, 2, 1, 1) = True: blnBlock(2, 2, 1, 2) = True: blnBlock(2, 2, 1, 3) = True blnBlock(2, 2, 2, 0) = False: blnBlock(2, 2, 2, 1) = False: blnBlock(2, 2, 2, 2) = False: blnBlock(2, 2, 2, 3) = False blnBlock(2, 2, 3, 0) = False: blnBlock(2, 2, 3, 1) = False: blnBlock(2, 2, 3, 2) = False: blnBlock(2, 2, 3, 3) = FalseblnBlock(2, 3, 0, 0) = False: blnBlock(2, 3, 0, 1) = False: blnBlock(2, 3, 0, 2) = True: blnBlock(2, 3, 0, 3) = True blnBlock(2, 3, 1, 0) = False: blnBlock(2, 3, 1, 1) = False: blnBlock(2, 3, 1, 2) = False: blnBlock(2, 3, 1, 3) = True blnBlock(2, 3, 2, 0) = False: blnBlock(2, 3, 2, 1) = False: blnBlock(2, 3, 2, 2) = False: blnBlock(2, 3, 2, 3) = True blnBlock(2, 3, 3, 0) = False: blnBlock(2, 3, 3, 1) = False: blnBlock(2, 3, 3, 2) = False: blnBlock(2, 3, 3, 3) = False'T型方块数据blnBlock(3, 0, 0, 0) = False: blnBlock(3, 0, 0, 1) = True: blnBlock(3, 0, 0, 2) = True: blnBlock(3, 0, 0, 3) = True blnBlock(3, 0, 1, 0) = False: blnBlock(3, 0, 1, 1) = False: blnBlock(3, 0, 1, 2) = True: blnBlock(3, 0, 1, 3) = False blnBlock(3, 0, 2, 0) = False: blnBlock(3, 0, 2, 1) = False: blnBlock(3, 0, 2, 2) = False: blnBlock(3, 0, 2, 3) = False blnBlock(3, 0, 3, 0) = False: blnBlock(3, 0, 3, 1) = False: blnBlock(3, 0, 3, 2) = False: blnBlock(3, 0, 3, 3) = FalseblnBlock(3, 1, 0, 0) = False: blnBlock(3, 1, 0, 1) = False: blnBlock(3, 1, 0, 2) = True: blnBlock(3, 1, 0, 3) = False blnBlock(3, 1, 1, 0) = False: blnBlock(3, 1, 1, 1) = False: blnBlock(3, 1, 1, 2) = True: blnBlock(3, 1, 1, 3) = True blnBlock(3, 1, 2, 0) = False: blnBlock(3, 1, 2, 1) = False: blnBlock(3, 1, 2, 2) = True: blnBlock(3, 1, 2, 3) = False blnBlock(3, 1, 3, 0) = False: blnBlock(3, 1, 3, 1) = False: blnBlock(3, 1, 3, 2) = False: blnBlock(3, 1, 3, 3) = FalseblnBlock(3, 2, 0, 0) = False: blnBlock(3, 2, 0, 1) = False: blnBlock(3, 2, 0, 2) = True: blnBlock(3, 2, 0, 3) = False blnBlock(3, 2, 1, 0) = False: blnBlock(3, 2, 1, 1) = True: blnBlock(3, 2, 1, 2) = True: blnBlock(3, 2, 1, 3) = True blnBlock(3, 2, 2, 0) = False: blnBlock(3, 2, 2, 1) = False: blnBlock(3, 2, 2, 2) = False: blnBlock(3, 2, 2, 3) = False blnBlock(3, 2, 3, 0) = False: blnBlock(3, 2, 3, 1) = False: blnBlock(3, 2, 3, 2) = False: blnBlock(3, 2, 3, 3) = FalseblnBlock(3, 3, 0, 0) = False: blnBlock(3, 3, 0, 1) = False: blnBlock(3, 3, 0, 2) = True: blnBlock(3, 3, 0, 3) = False blnBlock(3, 3, 1, 0) = False: blnBlock(3, 3, 1, 1) = True: blnBlock(3, 3, 1, 2) = True: blnBlock(3, 3, 1, 3) = False blnBlock(3, 3, 2, 0) = False: blnBlock(3, 3, 2, 1) = False: blnBlock(3, 3, 2, 2) = True: blnBlock(3, 3, 2, 3) = False blnBlock(3, 3, 3, 0) = False: blnBlock(3, 3, 3, 1) = False: blnBlock(3, 3, 3, 2) = False: blnBlock(3, 3, 3, 3) = False'正方形型方块数据blnBlock(4, 0, 0, 0) = False: blnBlock(4, 0, 0, 1) = True: blnBlock(4, 0, 0, 2) = True: blnBlock(4, 0, 0, 3) = False blnBlock(4, 0, 1, 0) = False: blnBlock(4, 0, 1, 1) = True: blnBlock(4, 0, 1, 2) = True: blnBlock(4, 0, 1, 3) = False blnBlock(4, 0, 2, 0) = False: blnBlock(4, 0, 2, 1) = False: blnBlock(4, 0, 2, 2) = False: blnBlock(4, 0, 2, 3) = FalseblnBlock(4, 1, 0, 0) = False: blnBlock(4, 1, 0, 1) = True: blnBlock(4, 1, 0, 2) = True: blnBlock(4, 1, 0, 3) = False blnBlock(4, 1, 1, 0) = False: blnBlock(4, 1, 1, 1) = True: blnBlock(4, 1, 1, 2) = True: blnBlock(4, 1, 1, 3) = False blnBlock(4, 1, 2, 0) = False: blnBlock(4, 1, 2, 1) = False: blnBlock(4, 1, 2, 2) = False: blnBlock(4, 1, 2, 3) = False blnBlock(4, 1, 3, 0) = False: blnBlock(4, 1, 3, 1) = False: blnBlock(4, 1, 3, 2) = False: blnBlock(4, 1, 3, 3) = FalseblnBlock(4, 2, 0, 0) = False: blnBlock(4, 2, 0, 1) = True: blnBlock(4, 2, 0, 2) = True: blnBlock(4, 2, 0, 3) = False blnBlock(4, 2, 1, 0) = False: blnBlock(4, 2, 1, 1) = True: blnBlock(4, 2, 1, 2) = True: blnBlock(4, 2, 1, 3) = False blnBlock(4, 2, 2, 0) = False: blnBlock(4, 2, 2, 1) = False: blnBlock(4, 2, 2, 2) = False: blnBlock(4, 2, 2, 3) = False blnBlock(4, 2, 3, 0) = False: blnBlock(4, 2, 3, 1) = False: blnBlock(4, 2, 3, 2) = False: blnBlock(4, 2, 3, 3) = FalseblnBlock(4, 3, 0, 0) = False: blnBlock(4, 3, 0, 1) = True: blnBlock(4, 3, 0, 2) = True: blnBlock(4, 3, 0, 3) = False blnBlock(4, 3, 1, 0) = False: blnBlock(4, 3, 1, 1) = True: blnBlock(4, 3, 1, 2) = True: blnBlock(4, 3, 1, 3) = False blnBlock(4, 3, 2, 0) = False: blnBlock(4, 3, 2, 1) = False: blnBlock(4, 3, 2, 2) = False: blnBlock(4, 3, 2, 3) = False blnBlock(4, 3, 3, 0) = False: blnBlock(4, 3, 3, 1) = False: blnBlock(4, 3, 3, 2) = False: blnBlock(4, 3, 3, 3) = False 3.窗体和模块说明:本程序有两个窗体,为frmMain和frmOption,两个PictureBox,是picGrid和picNext,四个TextBox,十四个Label,两个CommandButton,四个OptionButton,一个CheckBox,六个Frame,三个Line,一个Timer。
Matlab实现贪吃蛇小游戏的示例代码
Matlab实现贪吃蛇⼩游戏的⽰例代码由于⽼师说如果拿MATLAB制作出游戏或者有趣的动画的话。
平时成绩可以拿满分于是。
开始尝试制作各种matlab⼩游戏最初通过Alex的贪吃蛇学到了⼀些东西,然后制作了⼀个类似的俄罗斯⽅块在课堂上展⽰的(都是动的⽅块嗯哒)。
后来⾃⼰也尝试写着玩了⼀些其他版本的贪吃蛇,并做出了⼀些改进。
补动图:没错这就有点类似贪吃蛇⼤作战⾥的蛇啦然后做出的改进包括:在关闭窗⼝时不报错的设置,因为⽤了timer这个函数,在关闭图像时他会报错,我们就可以加⼊⼀个回调函数:set(gcf,'tag','co','CloseRequestFcn',@clo);function clo(~,~)stop(game)delete(findobj('tag','co'));clfcloseend意思是每次有关闭请求时就调⽤clo这个函数然后为了防⽌他提⽰你⽤递归的⽅式调⽤close,再加上delete(findobj(‘tag’,‘co’));删除之前的设定。
完整代码function snake%axis set..............................................................axis equallen=40;axis(0.5+[0,len,0,len])set(gca,'xtick',[],'ytick',[],'xcolor','w','ycolor','w')set(gca,'color','k')hold on%snake and food begining set...........................................snaketop=[5,5;4.5,5];body=[5,5;4.5,5;4,5;3.5,5;3,5;2.5,5];food=[10,10];direction=[1,0];long=6;plotsnake=scatter(gca,body(:,1),body(:,2),120,'w','filled');plotfood=scatter(gca,food(1),food(2),120,'w','filled');%timer set.............................................................set(gcf,'WindowButtonMotionFcn',@snakefcn)fps = 8;game = timer('ExecutionMode', 'FixedRate', 'Period',1/fps, 'TimerFcn', @snakegame);start(game) %..................................................................................set(gcf,'tag','co','CloseRequestFcn',@clo);function clo(~,~)stop(game)delete(findobj('tag','co'));clfcloseendfunction snakegame(~,~)snaketop=[body(1,:)+direction;body(1,:)+1/2*direction];snaketop(snaketop>len)=snaketop(snaketop>len)-len;snaketop(snaketop<1)=snaketop(snaketop<1)+len;body=[snaketop;body];body(long+1:end,:)=[];if (snaketop(1,1)-food(1))^2+(snaketop(1,2)-food(2))^2<1long = long + 2;food = randi(len, [1, 2]);endset(plotfood,'XData',food(1),'YData',food(2))set(plotsnake,'XData',body(:,1),'YData',body(:,2))endfunction snakefcn(~,~)xy=get(gca,'CurrentPoint');x=xy(1,1);y=xy(1,2);dir=[x-body(1,1),y-body(1,2)];dis=sqrt((x-body(1,1))^2+(y-body(1,2))^2);direction=dir/dis;endend以上就是Matlab实现贪吃蛇⼩游戏的⽰例代码的详细内容,更多关于Matlab贪吃蛇游戏的资料请关注其它相关⽂章!。
俄罗斯方块
自动化专业综合设计报告设计题目:俄罗斯方块的设计所在实验室:自动化系统仿真实验室指导教师:学生姓名班级学号成绩评定:一、设计目的1、首先应该熟练掌握学会MA TLAB的GUI图形界面化模块。
2、其次熟练运用Matlab中的编程语言,使用编程语言实现俄罗斯方块小游戏中的基本要求,即能够实现不同方块图形之间的转换,能够实现移动和翻转功能。
3、最后,能够实现停止,退出等功能,理解Matlab设计的基本方法。
二、设计要求1.实现图形界面化。
2.能够随机产生不同形状的方块,且旋转按钮实现图形的旋转,完成不同方块图形之间的转换。
3.能够实现判断方块落地时下方是否存在障碍,若填满一行,进行消除,并且能够计分,在成绩按钮中现实所的成绩。
三、设计内容(可加附页):1、首先,使用GUI建立一个图形界面如图所示用callback其生成.m文件。
2、在.m文件中添加程序,实现题目要求。
主程序如下:function RussiaBlock(action)%定义全局变量global CENTER_X CENTER_Y POS STUCK USED_SPACE H;global WIDTH HEIGHT LEVEL TIME_DELAY SQ_X SQ_Y;global H_SLIDER_WIDTH H_SLIDER_HEIGHT;global H_TEXT_WIDTH H_TEXT_HEIGHT H_TEXT_SCORE;global START_HANDLE STOP_HANDLE STOP_GAME EXIT_HANDLE;global H_A H_B BOX H_LINE ;if nargin < 1, action = 'initialize'; end;if strcmp(action,'initialize'),WIDTH = 10; % 默认游戏窗口的宽度HEIGHT = 25; % 默认游戏窗口的高度BOX = 1; % 默认显示游戏边框TIME_DELAY =1*exp((5/9)*log(0.1));%时间延时设置fig=figure( ...'Name','RussiaBlock for Matlab', 'NumberTitle','off', ...'Visible','off', 'BackingStore','off');SQ_X = [0 -1 -1 0]'; % 方块单元的X轴顶点坐标SQ_Y = [0 0 -1 -1]'; % 方块单元的Y轴顶点坐标%游戏窗口为axes表格figure(fig);H_A = axes( ...'Units','normalized', 'Position', [.1 .18 .4 .8], ...'Visible','off', 'DrawMode','fast', ...'NextPlot','replace', 'XLim',[1 WIDTH+1],'YLim',[0 HEIGHT]); H_B = axes( ...'Units','normalized', 'Position', [.1 .18 .4 .8],...'Visible','off', 'DrawMode','fast', ...'NextPlot','replace', 'XLim',[1 WIDTH+1],'YLim',[0 HEIGHT]); % 游戏界面初始边框if BOX == 1,BOX = ~BOX;RussiaBlock('box');end%各按键信息设置STOP_HANDLE = uicontrol('units','normalized',...'position', [.848 .876 .1 .05],'string','停止', ... 'callback','RussiaBlock(''stop'')', ...'interruptible','on','visible','off');EXIT_HANDLE = uicontrol('units','normalized',...'position', [.85 .757 .1 .05],'string','退出', ...'callback','delete(gcf)', ...'interruptible','off');START_HANDLE = uicontrol('units','normalized',...'position', [.848 .876 .1 .05],'string','开始', ... 'callback','RussiaBlock(''start'')', ...'interruptible','on','visible','on');left_handle = uicontrol('units','normalized',...'position', [.534 .521 .1 .05 ],'string','左移', ... 'callback','RussiaBlock(''left'')', ...'interruptible','on');right_handle = uicontrol('units','normalized',...'position', [.673 .521 .1 .05 ],'string','右移', ... 'callback','RussiaBlock(''right'')', ...'interruptible','on');drop_handle = uicontrol('units','normalized',...'position',[.604 .462 .1 .05 ],'string','下落', ... 'callback','RussiaBlock(''drop'')');rotate_handle = uicontrol('units','normalized',...'position',[.593 .59 .1 .05],'string','旋转', ...'callback','RussiaBlock(''rotate'')');H_TEXT_SCORE = uicontrol(...'ForegroundColor',[ 0 1 1 ],...'Position',[ 0.552 0.876 0.2 0.07],...'String','分数: xxxxx',...'Units','normalized');end; % 结束时初始化程序%切换表格边框if strcmp(action,'box'),BOX = ~BOX;if BOX == 1,H_LINE = line ([1 WIDTH+1 WIDTH+1 1 1], [1 1 HEIGHT HEIGHT 1]);else, delete(H_LINE);endend;% 左移动作if strcmp(action,'left'),stopped = 0;for i=1:4, if USED_SPACE(POS(i,1)-1,POS(i,2)) == 1, stopped=1; end; end; if stopped == 0,POS(:,1) = POS(:,1) - 1;CENTER_X = CENTER_X - 1;for i=1:4, set(H(i),'XData',SQ_X+POS(i,1),'YData',SQ_Y+POS(i,2)); end;drawnow;end;end;%右移动作if strcmp(action,'right'),stopped = 0;for i=1:4, if USED_SPACE(POS(i,1)+1,POS(i,2)) == 1, stopped=1; end; end;if stopped == 0,POS(:,1) = POS(:,1) + 1;CENTER_X = CENTER_X + 1;for i=1:4, set(H(i),'XData',SQ_X+POS(i,1),'YData',SQ_Y+POS(i,2)); end;drawnow;end;end;%整体下降if strcmp(action,'drop'),while STUCK==0,for i=1:4, if USED_SPACE(POS(i,1),POS(i,2)-1) == 1, STUCK=1; end; end;if STUCK == 0, POS(:,2) = POS(:,2) -1; end;end;for i=1:4, set(H(i),'XData',SQ_X+POS(i,1),'YData',SQ_Y+POS(i,2)); end; drawnow;end;%旋转if strcmp(action,'rotate'),new_x = -(POS(:,2) - CENTER_Y) + CENTER_X;new_y = (POS(:,1) - CENTER_X) + CENTER_Y;stopped = 0;for i=1:4,if ((new_x>1) & (new_x<(WIDTH+2)) & (new_y>1)),if USED_SPACE(new_x(i), new_y(i)) == 1, stopped=1; end;else, stopped=1;end;end;if stopped == 0, % 空格没有被占据POS = [new_x new_y];for i=1:4, set(H(i),'XData',SQ_X+POS(i,1),'YData',SQ_Y+POS(i,2)); end;drawnow;end;end;%暂停if strcmp(action,'stop'),STOP_GAME = 1;end;% 开始俄罗斯方块if strcmp(action,'start'),STOP_GAME = 0;score = 0;set(START_HANDLE, 'visible', 'off');set(STOP_HANDLE, 'visible', 'on');set(EXIT_HANDLE, 'visible', 'off');set(H_TEXT_SCORE, 'string', ['分数: ' num2str(score)]);h_matb = zeros(WIDTH+2,HEIGHT);USED_SPACE = zeros(WIDTH+2,HEIGHT);USED_SPACE(:,1) = ones(WIDTH+2,1);USED_SPACE ([1 WIDTH+2],:) = ones(2,HEIGHT);drawnow;axes(H_A);% 各类方块图案形状定义a_shape = [-1 0 1 2; 0 0 0 0]'; % 长方形b_shape = [-1 0 0 1; 0 0 1 0]'; % Z mirrorc_shape = [-1 0 0 1; 0 0 1 1]'; % Z normald_shape = [-1 0 0 1; 1 1 0 0]'; % truncated Te_shape = [0 0 1 1; 0 1 0 1]'; % 正方形f_shape = [-1 0 1 1; 0 0 0 1]'; % L normalg_shape = [-1 -1 0 1; 1 0 0 0]'; % L mirrorshape_matrix = [a_shape b_shape c_shape d_shape e_shape f_shape g_shape]; s = size(shape_matrix);num_shapes = s(2) / 2;color_matrix = [ 0 0 1; 0 1 0; 0 1 1; 1 0 0; 1 0 1; 1 1 0; 1 1 1];home_pos = ones(4,1) * [(WIDTH/2) (HEIGHT-2)];POS = a_shape + home_pos;for i=1:4, H(i) = patch(SQ_X+POS(i,1),SQ_Y+POS(i,2),'r');end;while ((sum(USED_SPACE(2:WIDTH+1,HEIGHT-4)) == 0) & (STOP_GAME == 0)),shape_index = ceil(num_shapes*rand(1)); %选择随机形状current_color = color_matrix(shape_index,:); % 颜色POS = shape_matrix(:,(2*shape_index - 1):(2*shape_index)) + home_pos; % 设置图形起始位置CENTER_X = home_pos(1,1); % 设置旋转原点CENTER_Y = home_pos(1,2);for i = 1:4,set(H(i),'XData',SQ_X+POS(i,1), 'YData',SQ_Y+POS(i,2), ...'FaceColor', current_color, 'Visible', 'on');end;drawnow;STUCK = 0;t0 = clock;while ((STUCK == 0) & (STOP_GAME == 0)),drawnow;if etime(clock,t0) > TIME_DELAY, % 下一个单元块for i=1:4,if USED_SPACE(POS(i,1),POS(i,2)-1) == 1, STUCK=1; end;end;if STUCK == 0,t0 = clock;POS(:,2) = POS(:,2) - 1;CENTER_Y = CENTER_Y - 1;for i = 1:4,set(H(i),'YData',SQ_Y+POS(i,2));end;drawnow;endend;drawnow;endfor i=1:4, USED_SPACE(POS(i,1),POS(i,2)) = 1; end; % 退格for i = 1:4, set(H(i),'Visible', 'off'); end; %隐藏活动区域axes(H_B);for i=1:4,h_matb(POS(i,1),POS(i,2)) = patch(SQ_X+POS(i,1),SQ_Y+POS(i,2),current_color);end;i=2;while i < HEIGHT, % 检查各行是否是完整的if sum(USED_SPACE(2:WIDTH+1,i)) == WIDTH,score = score + 10; % 添加完成一行的分数set(H_TEXT_SCORE, 'string', ['Score: ' num2str(score)]);for k1=2:WIDTH+1, delete(h_matb(k1,i)); end;for k2=(i+1):HEIGHT,for k1=2:WIDTH+1,if h_matb(k1,k2) ~= 0,set(h_matb(k1,k2),'YData',k2-1+SQ_Y);end;end;end;h_matb(2:WIDTH+1,i:(HEIGHT-1)) = h_matb(2:WIDTH+1,(i+1):HEIGHT); h_matb(2:WIDTH+1,HEIGHT) = zeros(WIDTH,1);USED_SPACE(2:WIDTH+1,i:(HEIGHT-1)) = USED_SPACE(2:WIDTH+1,(i+1):HEIGHT);USED_SPACE(2:WIDTH+1,HEIGHT) = zeros(WIDTH,1);else i = i+1;endendaxes(H_A);end % 结束循环%删除对象,清空游戏窗口for k2=2:HEIGHT,for k1=2:WIDTH+1,if h_matb(k1,k2) ~= 0,delete(h_matb(k1,k2));end;end;end;set(START_HANDLE, 'visible', 'on');set(STOP_HANDLE, 'visible', 'off');set(EXIT_HANDLE, 'visible', 'on');set(H_TEXT_SCORE, 'string', '成绩:0' );end % 结束游戏3、一开始运行时显示的画面:4、点击start游戏开始。
自娱自乐之俄罗斯方块的matlab实现
⾃娱⾃乐之俄罗斯⽅块的matlab实现function mtetris(cmd)%MTETRIS Matlab Tetris (v1.1)%% To play this game, type: MTETRIS%% Controls (use numpad):% [4] Left [5] Spin [6] Right% [2] Drop%% alternatively,% [Q] Left [W] Spin [E] Right% [S] Drop%% [Ctrl+P] Pause/Unpause%% During the game, use the game menu to set difficulty and to% enable/disable sound effects. Only one game can run at a time.% mtetris was written and tested on Matlab 5.3 (R11), but may% work with as early as Matlab 4.0 without changes.% Author: Pascal Getreuer, June 2004global MODE TIMESTEP MAP POS GEO BOXOFF BOXY SNDFLAG SNDS SNDD SNDROW SHAPEIND; global SCORE CLKSND HFIG HMODE HSCORE HCUR HMAP HPAUSE HSTOP HDIF HSND;if nargin ~= 1 | cmd == 'U' | cmd == 'C', %%% mtetris main routine %%%BoxX = 10 + 2; % playing field width + 2 border cellsBOXY = 18 + 1; % playing field height + 1 border cellBOXOFF = [BOXY,1];MODE = 0; % set game mode to playRowScore = [100,250,400,600] - 5; % points for filling rows% shapes dataShapes = reshape([-1 0 0 0 0 1 1 0 -1 0 0 0 1 0 2 0 -1 0 0 0 0 1 1 0 -1 ...0 0 0 0 1 1 1 0 0 0 1 1 0 1 1 -1 0 0 0 1 0 1 1 -1 1 -1 0 0 0 1 0],2,4,7);ShapeColors = [1 0 0;1 1 0;0 0.8 0;0 0 1];PatX = [0;-1;-1;0]; % coordinates for drawing patchesPatY = [0;0;-1;-1];ClkV=[0;0;86400;3600;60;1];if nargin ~= 1 | cmd == 'C'if nargin ~= 1 % initialize GUICLKSND = clock;% initialize figure windowHFIG = figure('Name','MTetris','Numbertitle','off','Menubar','none',...'Color',[0.831373 0.815686 0.784314],'Resize','off','DoubleBuffer','on',...'Position',[150,150,220,400],'CloseRequestFcn',[mfilename,'(''X'')'],...'KeyPressFcn',[mfilename,'(''K'')']);axes('Units','normalized','Position', [.05 .06 .9 .93],'Visible','off',...'DrawMode','fast','NextPlot','replace','XLim',[1,BoxX-1],'YLim',[1,BOXY]);set(line([1,BoxX-1,BoxX-1,1,1],[1,1,BOXY,BOXY,1]),'Color',[0,0,0]);% make button and handlesHSCORE = uicontrol('Units','normalized','Position',[0.05,0.01,.5,.05],...'Style','text','HorizontalAlignment','Left','FontWeight','bold');HMODE = uicontrol('Units','normalized','Position',[0.1,0.7,.8,.1],...'Style','text','FontSize',14);% make menutmp = uimenu('Label','&Game');HPAUSE = uimenu(tmp,'Label','&Pause','Callback',[mfilename,'(''P'')']);HSTOP = uimenu(tmp,'Label','&Stop','Callback',[mfilename,'(''N'')']);HDIF(1) = uimenu(tmp,'Label','&Beginner','Callback',[mfilename,'(''1'')'], ...'Separator','on','Checked','on');HDIF(2) = uimenu(tmp,'Label','&Intermediate','Callback',[mfilename,'(''2'')']);HDIF(3) = uimenu(tmp,'Label','&Expert','Callback',[mfilename,'(''3'')']);HDIF(4) = uimenu(tmp,'Label','&Custom...','Callback',[mfilename,'(''4'')']);HSND = uimenu(tmp,'Label','S&ound','Callback',[mfilename,'(''O'')'],'Separator','on'); uimenu(tmp,'Label','E&xit','Callback',[mfilename,'(''X'')'],'Separator','on');tmp = uimenu('Label','&Help');uimenu(tmp,'Label','Help &Notes','Callback',['global MODE;if ~MODE,',...mfilename,'(''P'');end;msgbox({''Controls (use numpad):'',',...''' [4] Left [5] Spin [6] Right'','' [2] Drop'','''',',...''' alternatively,'','' [Q] Left [W] Spin [E] Right'','...''' [S] Drop'','''',',...''' [Ctrl+P] Pause/Unpause ''},''Help Notes'')']);uimenu(tmp,'Label','&M-File Info','Callback','help MTetris');uimenu(tmp,'Label','&About MTetris','Separator','on','Callback',['global MODE;',...'if ~MODE,',mfilename,'(''P'');end;msgbox({'''',''MTetris 1.1'',' ...'''by Pascal Getreuer 2004-2005''},''About MTetris'')']);set(HFIG,'Position',[150,150,220,400]);TIMESTEP = 0.8; % beginner difficulty modeSNDFLAG = 1; % sound effects initially enabled (0 for disabled)GameSounds;elsefigure(HFIG);endset(HPAUSE,'Label','&Pause','Accelerator','P');set(HMODE,'String','PAUSED','Visible','off');set(HSCORE,'String','Score: 0');MAP = ones(BOXY,BoxX);MAP(2:BOXY,2:BoxX-1) = 0;HMAP = zeros(BOXY,BoxX);SCORE = 0;% place first shapeSHAPEIND = ceil(rand(1)*size(Shapes,3));GEO = Shapes(:,:,SHAPEIND);POS = [ceil(BoxX/2);BOXY-2];Color = ShapeColors(ceil(rand(1)*size(ShapeColors,1)),:);for i = 1:4HCUR(i) = patch(PatX + POS(1) + GEO(1,i),...PatY + POS(2) + GEO(2,i),Color);endelsefigure(HFIG);endLastSound = clock;while ~MODE % main game loopFrameStart = clock*ClkV;if any(MAP(BOXOFF*POS + BOXOFF*GEO - BOXY - 1)) % check if shape is blocked % add current shape into arraysMAP(BOXOFF*POS + BOXOFF*GEO - BOXY) = 1;HMAP(BOXOFF*POS + BOXOFF*GEO - BOXY) = HCUR;% spawn a new shapeSHAPEIND = ceil(rand(1)*size(Shapes,3));GEO = Shapes(:,:,SHAPEIND);POS = [ceil(BoxX/2);BOXY-2];Color = ShapeColors(ceil(rand(1)*size(ShapeColors,1)),:);% check for filled rowstmp = flipud(find(sum(MAP(2:BOXY,:),2) == BoxX)) + 1;if ~isempty(tmp)SCORE = SCORE + RowScore(length(tmp)); % add points for row (or rows)% clear rows and drop above rowsfor i = 1:length(tmp)delete(HMAP(tmp(i),2:BoxX-1));HMAP = [HMAP([1:tmp(i)-1,tmp(i)+1:BOXY],:);zeros(1,BoxX)];MAP = [MAP([1:tmp(i)-1,tmp(i)+1:BOXY],:);1,zeros(1,BoxX-2),1];endfor k1 = 2:BOXYfor k2 = 2:BoxX-1if HMAP(k1,k2) ~= 0set(HMAP(k1,k2),'YData',k1 + PatY);endendendtmp = clock;while etime(clock,tmp) < 0.2 & ~MODE, drawnow; endsound(SNDROW,22050);CLKSND = clock;endSCORE = SCORE + 5;set(HSCORE,'String',['Score: ',num2str(SCORE)]); % show updated scorefor i = 1:4HCUR(i) = patch(PatX + POS(1) + GEO(1,i),PatY + POS(2) + GEO(2,i),Color);endif any(MAP(BOXOFF*POS + BOXOFF*GEO - BOXY)) % game overfeval_r(mfilename,'N');break;endendif ~MODE % drop shape one cellif ~any(MAP(BOXOFF*POS + BOXOFF*GEO - BOXY - 1))POS = POS + [0;-1];for i = 1:4set(HCUR(i),'XData',PatX+POS(1) + GEO(1,i),'YData',PatY+POS(2) + GEO(2,i)); endendend% wait one timestepwhile (clock)*ClkV-FrameStart < TIMESTEP & ~MODEdrawnow;enddrawnow;endelse %%% GUI callback routines %%% if cmd == 'K' & ~MODEswitch get(HFIG,'CurrentCharacter')case {'4','q','Q'} % move shape leftif ~any(MAP(BOXOFF*POS + BOXOFF*GEO - BOXY*2))POS = POS + [-1;0];endcase {'6','e','E'} % move shape rightif ~any(MAP(BOXOFF*POS + BOXOFF*GEO))POS = POS + [1;0];endcase {'5','w','W'} % spin shapeif ~any(MAP(BOXOFF*POS + [-1,BOXY]*GEO - BOXY))if etime(clock,CLKSND) > 0.2sound(SNDS,22050);CLKSND = clock;endif SHAPEIND ~= 5GEO = [0,1;-1,0]*GEO;endendcase {'2','s','S'} % drop shapeNewInd = BOXOFF*POS + BOXOFF*GEO - BOXY - 1;if ~any(MAP(NewInd))if etime(clock,CLKSND) > 0.2sound(SNDD,22050);CLKSND = clock;endwhile ~any(MAP(NewInd))NewInd = NewInd - 1;POS = POS + [0;-1];endendendif all(ishandle(HCUR))for i = 1:4set(HCUR(i),'XData',[0;-1;-1;0] + POS(1) + GEO(1,i),...'YData',[0;0;-1;-1] + POS(2) + GEO(2,i));endendreturn;endswitch(cmd)case 'P'switch MODEcase 0 % pause the gameMODE = 1;set(HPAUSE,'Label','&Unpause');set(HMODE,'Visible','on');set(HCUR,'Visible','off');set(HMAP,'Visible','off');case 1 % unpause the gameMODE = 0;set(HPAUSE,'Label','&Pause');set(HMODE,'Visible','off');set(HCUR,'Visible','on');set(HMAP,'Visible','on');feval_r(mfilename,'U'); % unpause current gamecase 2 % new gamefeval_r(mfilename,'C'); % start a new game, but do not reinitialize the GUI endcase 'N'if MODE ~= 2 % stop gameMODE = 2;drawnow;set(HPAUSE,'Label','&New','Accelerator','N');set(HMODE,'String','GAME OVER','Visible','on');if all(ishandle(HCUR))delete(HCUR(:));endfor i = 1:prod(size(HMAP))if HMAP(i), delete(HMAP(i)); endendendcase '1' % beginner difficultyTIMESTEP = 0.8; % shapes fall one cell every 800 msset(HDIF(1),'Checked','on');set(HDIF(2:4),'Checked','off');case '2' % intermediate difficultyTIMESTEP = 0.48;set(HDIF(2),'Checked','on');set(HDIF([1,3,4]),'Checked','off');case '3' % expert difficultyTIMESTEP = 0.3;set(HDIF(3),'Checked','on');set(HDIF([1,2,4]),'Checked','off');case '4' % custom difficultytmp = inputdlg('Time Step (decrease for faster game)',...'Custom Difficulty',1,{num2str(TIMESTEP*1000)});if ~isempty(tmp)tmp = str2double(tmp)/1000;if ~isnan(tmp) & isreal(tmp) & tmp >= 0TIMESTEP = tmp;set(HDIF(4),'Checked','on');set(HDIF(1:3),'Checked','off');endendcase 'O' % enable/disable sound effectsSNDFLAG = ~SNDFLAG;GameSounds;case 'X' % exitMODE = 2;drawnow;closereq;endendreturn;function GameSounds %%% game sound effects %%%global SNDFLAG SNDLR SNDS SNDD SNDROW HSND;if SNDFLAGset(HSND,'Checked','on');SNDS = sin(([0:1500,1500:-1:0]).^1.2*2*pi*70/22050)*0.6; % spinSNDD = sin((3500:-1:1).^1.2*pi*200/22050).*linspace(0.6,0.1,3500); % drop SNDROW = conv(ones(1,15)/15,sin((1:5000)*pi.*interp1(... % row filled[500,600,400,600,300,200],linspace(1,6,5000),'nearest')/22050));elseset(HSND,'Checked','off');SNDS = 0; SNDD = 0; SNDROW = 0;endreturn;。
- 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
- 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
- 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。
用matlab编写的俄罗斯方块小游戏?function RussiaBlock( varargin )if nargin == 0OldHandle = findobj( 'Type', 'figure', 'Tag', 'RussiaBlock' ) ;if ishandle( OldHandle )delete( OldHandle ) ;endFigureHandle = figure( 'Name', '俄罗斯方块MATLAB版', 'Tag', 'RussiaBlock', 'NumberTitle', 'off',...'Menubar', 'none', 'DoubleBuffer', 'on', 'Resize', 'off', 'visible', 'on',...'KeyPressFcn', 'RussiaBlock( ''KeyPress_Callback'', gcbo )',...'HelpFcn', 'helpdlg(''帮不了你- -!'',''不好意思'')',...'CloseRequestFcn', 'RussiaBlock( ''CloseFigure_Callback'', gcbo )' ) ;generate_FigureContent( FigureHandle ) ;init_FigureContent( FigureHandle ) ;set( FigureHandle, 'Visible', 'on' ) ;elseif ischar( varargin{1} )feval( varargin{:} ) ;end% -------------------------------------------------------------------------function generate_FigureContent( FigureHandle )TabSpace = 30 ;BlockWidth = 20 ;BlockHeight = 20 ;FigureWidth = BlockWidth * (12 + 1) + TabSpace * 7;FigureHeight = 500 ;set( FigureHandle, 'Position', [0 0 FigureWidth FigureHeight] ) ;movegui( FigureHandle, 'center' ) ;% 创建菜单BeginMenu = uimenu( FigureHandle, 'Label', '开始' ) ;StartMenu = uimenu( BeginMenu, 'Label', '开始新游戏', 'Accelerator', 'N',...-'Callback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )');SaveMenu = uimenu( BeginMenu, 'Label', '保存', 'Accelerator', 'S', 'Enable', 'off',...'Separator', 'on', 'Cal', 'RussiaBlock( ''SaveGame_Callback'', gcbo )' );LoadMenu = uimenu( BeginMenu, 'Label', '读取', 'Accelerator', 'L', 'Enable', 'off',...'Cal', 'RussiaBlock( ''LoadGame_Callback'', gcbo )' );QuitMenu = uimenu( BeginMenu, 'Label', '退出', 'Accelerator', 'Q', 'Separator', 'on', 'Cal','close(gcf)');OperationMenu = uimenu( FigureHandle, 'Label', '功能' );BoardConfigMenu = uimenu( OperationMenu, 'label', '键盘设置', 'Enable', 'off',...'Cal', 'RussiaBlock( ''BoardConfig_Callback'', gcbo )' );FigureConfigMenu = uimenu( OperationMenu, 'label', '界面设置', 'Enable', 'off',...'Cal', 'RussiaBlock( ''FigureConfig_Callback'', gcbo )' );HighScoreMenu = uimenu( OperationMenu, 'label', '最高记录', 'Separator', 'on',...'Cal', 'RussiaBlock( ''HighScore_Callback'', gcbo )', 'Enable', 'off' );GameLevelMenu = uimenu( OperationMenu, 'Label', '游戏难度',...'Cal','RussiaBlock( ''GameLevel_Callback'', gcbo )' );HelpMenu = uimenu( FigureHandle, 'Label', '帮助' );AboutMenu = uimenu( HelpMenu, 'Label', '关于此软件', 'Cal', 'helpdlg(''俄罗斯方块MATLAB版'',''关于此软件…………'')');HelpDlgMenu = uimenu( HelpMenu, 'Label', '游戏帮助', 'Separator', 'on', 'Cal', 'helpdlg(''帮不了你- -!'',''不好意思'')' );% 创建工具条,图标可以用imread从图片读取,但图片不要太大BeginTool = uipushtool( 'ToolTipString', '开始', 'CData', rand(16,16,3), 'Tag', 'BeginTool',...'ClickedCallback', 'RussiaBlock( ''StartNewGame_Callback'', gcbo )' ) ;PauseTool = uitoggletool( 'ToolTipString', '暂停', 'Tag', 'PauseTool', 'Tag', 'PauseTool',...'CData', reshape( repmat( [1 1 0], 16, 16), [16,16,3] ),...'ClickedCallback', 'RussiaBlock( ''PauseGame_Callback'', gcbo )' ) ;% 创建游戏窗口MainWindowXPos = TabSpace;MainWindowYPos = TabSpace;MainWindowWidth = BlockWidth * 12 ;MainWindowHeight = BlockHeight * 22 ;MainWindowPosition = [MainWindowXPos MainWindowYPos MainWindowWidth MainWindowHeight] ;% 定义游戏窗口的右键菜单AxesContextMenu = uicontextmenu( 'Tag', 'uicontextmenu' ) ;uimenu( AxesContextMenu, 'Label', '设置窗口颜色', 'Cal','RussiaBlock( ''WindowColor_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '设置背景图片', 'Cal','RussiaBlock( ''WindowPicture_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '设置方块颜色', 'Cal','RussiaBlock( ''BlockColor_Callback'', gcbo )' )uimenu( AxesContextMenu, 'Label', '恢复默认', 'Cal', 'RussiaBlock( ''Default_Callback'',-gcbo )' )MainAxes = axes( 'Units', 'pixels', 'Pos', MainWindowPosition, 'XTick', [], 'YTick',[],'XTickLabel', [],...'YTickLabel', [], 'Box', 'on', 'Tag', 'MainAxes', 'UicontextMenu', AxesContextMenu,...'XLim', [0 MainWindowWidth], 'YLim', [0 MainWindowHeight] ) ;hold on;% 创建一个窗口用于显示下一个方块的图形NextBlockWndXPos = MainWindowXPos + MainWindowWidth + TabSpace ; NextBlockWndHeight = 4 * TabSpace + BlockHeight ;NextBlockWndYPos = MainWindowYPos + MainWindowHeight - NextBlockWndHeight ; NextBlockWndWidth = TabSpace * 4 + BlockWidth ;NextBlockWndPosition = [NextBlockWndXPos NextBlockWndYPos NextBlockWndWidth NextBlockWndHeight] ;NextBlockAxes = axes( 'Units', 'pixels', 'Pos', NextBlockWndPosition, 'XTick', [], 'YTick',[],...'XTickLabel', [], 'YTickLabel', [], 'XLim', [0 NextBlockWndWidth],...'YLim', [0 NextBlockWndHeight], ...'Box', 'on', 'Tag', 'NextBlockAxes', 'Color', [0.85 0.85 0.85] ) ;% 创建一组控件,包括(两个文本框用于显示当前方块数和成绩,两个按钮用于暂停和退出)ButtonTag = { 'QuitButton', 'PauseButton', 'BlockNumText', 'ScoreText' } ;ButtonStyle = { 'pushbutton', 'togglebutton', 'text', 'text' } ;FontColor = { [0 0 0], [1 0 0], [0 0 1], [1 0 1] } ;ButtonColor = { [0.7 0.8 0.9], [0.3 1 0.3], [0.5 1 1], [0.5 1 1] } ;ButtonString = { '退出', '暂停', '方块数', '积分' };ButtonCallback = { 'close(gcf)', 'RussiaBlock( ''ButtonPauseGame_Callback'', gcbo )', '', '' } ; ButtonNumber = length( ButtonTag ) ;ButtonWidth = NextBlockWndWidth ;ButtonHeight = 50 ;ButtonXPos = NextBlockWndXPos ;ButtonYPos = MainWindowYPos + TabSpace ;ButtonPosition = [ButtonXPos ButtonYPos ButtonWidth ButtonHeight] ;ButtonTabSpace = (NextBlockWndYPos - 2 * TabSpace - ButtonHeight * ButtonNumber) / ButtonNumber ;for num = 1: ButtonNumberTempButtonPosition = ButtonPosition ;TempButtonPosition(2) = ButtonPosition(2) + (num - 1) * (ButtonTabSpace +ButtonHeight);if findstr( ButtonStyle{num}, 'button' )TempButtonPosition(1) = TempButtonPosition(1) + 10 ;TempButtonPosition(2) = TempButtonPosition(2) + 5 ;TempButtonPosition(3) = TempButtonPosition(3) - 10 * 2 ;TempButtonPosition(4) = TempButtonPosition(4) - 5 * 2 ;else-TempButtonPosition(1) = TempButtonPosition(1) - 10 ;TempButtonPosition(2) = TempButtonPosition(2) - 5 ;TempButtonPosition(3) = TempButtonPosition(3) + 10 * 2;TempButtonPosition(4) = TempButtonPosition(4) + 5 * 2 ;endButtonHandle = uicontrol( 'Tag', ButtonTag{num}, 'Style', ButtonStyle{num}, 'Pos', TempButtonPosition,...'Foregroundcolor', FontColor{num}, 'Backgroundcolor', ButtonColor{num},...'Fontsize', 16, 'String', ButtonString{num}, 'Cal', ButtonCallback{num} ) ;if findstr( ButtonStyle{num}, 'text' )set( ButtonHandle, 'Max', 2 ) ;endif findstr( ButtonTag{num}, 'PauseButton' )set( ButtonHandle, 'Enable', 'inactive', 'ButtonDownFcn', ButtonCallback{num}, 'Cal', '' ) ;endendMainBlockAxes = axes( 'Units', 'pixels', 'Pos', MainWindowPosition, 'XTick', [], 'YTick',[],'XTickLabel', [],...'YTickLabel', [], 'Box', 'on', 'Tag', 'MainBlockAxes', 'Hittest', 'off',...'XLim', [0 MainWindowWidth], 'YLim', [0 MainWindowHeight], 'Color', 'none' ) ;line( 'Visible', 'on', 'Tag', 'BlockHandle', 'Markersize', 18, 'Parent', MainBlockAxes, 'HitTest','off',...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', nan, 'YData', nan, 'LineStyle', 'none' ) ;line( 'Visible', 'off', 'Tag', 'TempBlock', 'Markersize', 18, 'Parent', MainBlockAxes, 'HitTest','off',...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', 130, 'YData', 30, 'LineStyle', 'none' ) ;line( 'Visible', 'off', 'Tag', 'NextBlock', 'Markersize', 18, 'Parent', NextBlockAxes, 'HitTest','off',...'Marker', 's', 'MarkerEdgeColor', 'k', 'XData', 30, 'YData', 30, 'LineStyle', 'none' ) ;setappdata( FigureHandle, 'XLim', [0 MainWindowWidth] )setappdata( FigureHandle, 'YLim', [0 MainWindowHeight] )handles = guihandles( FigureHandle ) ;guidata( FigureHandle, handles ) ;% -------------------------------------------------------------------------function init_FigureContent( FigureHandle )handles = guidata( FigureHandle ) ;ColorInfo = [] ;tryColorInfo = load('ColorInfo.mat') ;catch-endif isempty( ColorInfo )ColorInfo.BlockColor = GetDefaultBlockColor ;ColorInfo.MainAxesColor = GetDefaultMainAxesColor ;ColorInfo.MainAxesImage.ImageData = [] ;endset( handles.MainAxes, 'Color', ColorInfo.MainAxesColor ) ;if ~isempty( ColorInfo.MainAxesImage.ImageData )ImageHandle = image( ColorInfo.MainAxesImage.ImageData, 'Parent',handles.MainAxes ) ;set( ImageHandle, ColorInfo.MainAxesImage.Property ) ;setappdata( FigureHandle, 'ImageData', ColorInfo.MainAxesImage.ImageData ) ;endset( handles.BlockHandle, 'MarkerFaceColor', ColorInfo.BlockColor ) ;set( handles.TempBlock, 'MarkerFaceColor', ColorInfo.BlockColor ) ;set( handles.NextBlock, 'MarkerFaceColor', ColorInfo.BlockColor ) ;setappdata( FigureHandle, 'BlockColor', ColorInfo.BlockColor ) ;% ------------------------------------------------------------function StartNewGame_Callback( h, StartType )handles = guidata( h ) ;global PauseTimeif nargin == 1StartType = 'NewStart' ;setappdata( handles.RussiaBlock, 'BlockNumber', 0 ) ;set( handles.BlockNumText, 'String', {'方块数','0'} ) ;setappdata( handles.RussiaBlock, 'CurrentScore', 0 ) ;set( handles.ScoreText, 'String', {'积分','0'} ) ;set( handles.BlockHandle, 'XData', nan, 'YData', nan ) ;set( handles.TempBlock, 'XData', nan, 'YData', nan ) ;TextHandle = findobj( 'Parent', handles.MainBlockAxes, 'Type', 'text' ) ;delete( TextHandle ) ;elseendset( handles.NextBlock, 'Visible', 'on' ) ;set( handles.TempBlock, 'Visible', 'on' ) ;set( handles.PauseTool, 'State', 'off' ) ;set( handles.PauseButton, 'Value', 0 ) ;YLim = get( handles.MainAxes, 'YLim' ) ;while( ishandle( h ) )-TotalYData = get( handles.BlockHandle, 'YData' ) ;if any( TotalYData >= YLim(2) )% Game overtext( 20, 200, 'GameOver', 'Parent', handles.MainBlockAxes,...'FontSize', 30, 'Color', 'r', 'FontAngle', 'italic' ) ;break;endif length( TotalYData ) >= 4TotalXData = get( handles.BlockHandle, 'XData' ) ;LastBlockYData = TotalYData( end - 3: end ) ;LastBlockYData = unique( LastBlockYData ) ;CompleteLine = [] ;UsefulIndex = [] ;for num = 1: length( LastBlockYData )[YData, Index] = find( TotalYData == LastBlockYData(num) ) ;if length( YData ) == 12CompleteLine = [CompleteLine, LastBlockYData(num)] ;UsefulIndex = [UsefulIndex, Index] ;endendif ~isempty( CompleteLine )TotalXData( UsefulIndex ) = [] ;TotalYData( UsefulIndex ) = [] ;LineNumber = length( CompleteLine ) ;ScoreArray = [100 300 600 1000] ;NewScore = ScoreArray(LineNumber) ;CurrentScore = getappdata( handles.RussiaBlock, 'CurrentScore' ) ;TextString = get( handles.ScoreText, 'String' ) ;TextString{2} = CurrentScore + NewScore ;set( handles.ScoreText, 'String', TextString ) ;setappdata( handles.RussiaBlock, 'CurrentScore', CurrentScore + NewScore ) ;UpdateGameLevel( handles.RussiaBlock, CurrentScore + NewScore ) ;% 处理需要下移的方块for num = LineNumber : -1 : 1[YData, Index] = find( TotalYData > LastBlockYData(num) ) ;TotalYData(Index) = TotalYData(Index) - 20 ;endendset( handles.BlockHandle, 'XData', TotalXData, 'YData', TotalYData ) ;end-BlockNumber = getappdata( handles.RussiaBlock, 'BlockNumber' ) ;TextString = get( handles.BlockNumText, 'String' ) ;TextString{2} = BlockNumber + 1 ;set( handles.BlockNumText, 'String', TextString ) ;setappdata( handles.RussiaBlock, 'BlockNumber', BlockNumber + 1 ) ;GameLevel = getappdata( handles.RussiaBlock, 'GameLevel' ) ;if isempty( GameLevel )PauseTime = 0.3 ;elsePauseTime = ceil( 20 / GameLevel ) / 100 ;endTempBlockPos.LeftStep = 0 ;TempBlockPos.DownStep = 0 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;Status = 1;[BlockXArray,BlockYArray] = Com_GetBlock( h ) ;set( handles.TempBlock, 'XData', BlockXArray, 'YData', BlockYArray ) ;while( Status & ishandle( h ) )if(PauseTime) ~= 0pause( PauseTime )endStatus = test_MoveBlock( h, 'Down' ) ;endend% -------------------------------------------------------------------------function KeyPress_Callback( h )handles = guidata( h ) ;PauseState = get( handles.PauseTool, 'State' ) ;if strcmp( PauseState, 'on' )returnendBoardConfig = getappdata( handles.RussiaBlock, 'BoardConfig' ) ;if isempty( BoardConfig )Left = 'leftarrow' ;Right = 'rightarrow' ;Down = 'downarrow' ;Change = 'uparrow' ;Drop = 'space' ;elseLeft = BoardConfig.Left ;Right = BoardConfig.Right ;Down = BoardConfig.Down ;-Change = BoardConfig.Change ;Drop = BoardConfig.Drop ;endCurrentKey = get( handles.RussiaBlock, 'CurrentKey' ) ;switch CurrentKeycase Lefttest_MoveBlock( h, 'Left' ) ;case Righttest_MoveBlock( h, 'Right' ) ;case Downtest_MoveBlock( h, 'Down' ) ;case Changetest_MoveBlock( h, 'Change' ) ;case Droptest_MoveBlock( h, 'Drop' ) ;otherwisereturn ;end% -------------------------------------------------------------------------function WindowColor_Callback( h )handles = guidata( h ) ;CurrentColor = get( handles.MainAxes, 'Color' ) ;NewColor = uisetcolor( CurrentColor, '请选择窗口颜色' ) ;if length( NewColor ) == 0return;elseset( handles.MainAxes, 'Color', NewColor ) ;end% -------------------------------------------------------------------------function WindowPicture_Callback( h )handles = guidata( h ) ;[PictureFile, Path] = uigetfile( {'*.jpg; *.bmp'},'请选择图片' );if isnumeric( PictureFile )return ;else% if length( PictureFile ) > 31% errordlg( '文件名过长,读取失败' ) ;% endtryPicture = imread( [Path, PictureFile] ) ;for num = 1: size( Picture, 3 )ValidPicture(:, :, num) = flipud( Picture(:,:,num) ) ;AxesXLim = get( handles.MainAxes, 'XLim' ) ;AxesYLim = get( handles.MainAxes, 'YLim' ) ;BlockHandle = findobj( handles.MainAxes, 'Style', 'line' ) ;cla( BlockHandle ) ;ImageXLimit = size(Picture, 2) ;ImageYLimit = size(Picture, 1) ;if diff( AxesXLim ) < size(Picture, 2) | diff( AxesYLim ) < size(Picture, 1) % 超出坐标轴范围,压缩显示XScale = diff( AxesXLim ) / size(Picture, 2) ;YScale = diff( AxesYLim ) / size(Picture, 1) ;% 取较小比例压缩Scale = min( XScale, YScale ) ;ImageXLimit = size(Picture, 2) * Scale ;ImageYLimit = size(Picture, 1) * Scale ;endImageXData(1) = AxesXLim(1) + (diff( AxesXLim ) - ImageXLimit) / 2 + 1; ImageXData(2) = ImageXData(1) + ImageXLimit - 1;ImageYData(1) = AxesYLim(1) + (diff( AxesYLim ) - ImageYLimit) / 2 + 1; ImageYData(2) = ImageYData(1) + ImageYLimit - 1;image( ValidPicture, 'Parent', handles.MainAxes, 'Hittest', 'off', ...'XData',ImageXData,'YData',ImageYData, 'Tag', 'MainImage' ); setappdata( handles.RussiaBlock, 'ImageData', ValidPicture ) ;catchErrorString = sprintf( ['读取图片失败,错误信息为:\n',lasterr] ) ; errordlg( ErrorString ) ;endend% -------------------------------------------------------------------------function BlockColor_Callback( h )handles = guidata( h ) ;CurrentColor = getappdata( handles.RussiaBlock, 'BlockColor' ) ;if isempty( CurrentColor )CurrentColor = GetDefaultBlockColor ;setappdata( handles.RussiaBlock, 'BlockColor', CurrentColor ) ;endNewColor = uisetcolor( CurrentColor, '请选择方块颜色' ) ;if length( NewColor ) == 0return;setappdata( handles.RussiaBlock, 'BlockColor', NewColor ) ; set( handles.BlockHandle, 'MarkerFaceColor', NewColor ) ;set( handles.TempBlock, 'MarkerFaceColor', NewColor ) ;set( handles.NextBlock, 'MarkerFaceColor', NewColor ) ;end% ------------------------------------------------------------------------ function Default_Callback( h )handles = guidata( h ) ;BlockColor = GetDefaultBlockColor ;AxesColor = GetDefaultMainAxesColor ;set( handles.MainAxes, 'Color', AxesColor ) ;set( handles.BlockHandle, 'MarkerFaceColor', BlockColor ) ;set( handles.TempBlock, 'MarkerFaceColor', BlockColor ) ;set( handles.NextBlock, 'MarkerFaceColor', BlockColor ) ;% ------------------------------------------------------------------------- function PauseGame_Callback( h )handles = guidata( h ) ;ToolStart = get( handles.PauseTool, 'State' ) ;if strcmp( ToolStart, 'on' )set( handles.PauseButton, 'Value', 1 ) ;waitfor( handles.PauseTool, 'State', 'off' ) ;elseset( handles.PauseButton, 'Value', 0 ) ;end% ------------------------------------------------------------------------- function ButtonPauseGame_Callback( h )handles = guidata( h ) ;ToggleButtonValue = get( h, 'Value' ) ;if ToggleButtonValue == 0set( h, 'Value', 1 ) ;set( h, 'String', '继续' ) ;set( handles.PauseTool, 'State', 'on' ) ;waitfor( handles.PauseTool, 'State', 'off' ) ;elseset( h, 'Value', 0 ) ;set( h, 'String', '暂停' ) ;set( handles.PauseTool, 'State', 'off' ) ;set( handles.RussiaBlock, 'CurrentObject', handles.MainAxes ) ; end-% ------------------------------------------------------------------------function CloseFigure_Callback( h )handles = guidata( h ) ;BlockColor = getappdata( handles.RussiaBlock, 'BlockColor' ) ;MainAxesColor = get( handles.MainAxes, 'Color' ) ;MainAxesImageHandle = findobj( handles.MainAxes, 'Type', 'image' ) ;if ~isempty( MainAxesImageHandle )MainAxesImage.Property.Tag = get( MainAxesImageHandle, 'Tag' );MainAxesImage.Property.Hittest = get( MainAxesImageHandle, 'Hittest' );MainAxesImage.Property.XData = get( MainAxesImageHandle, 'XData' );MainAxesImage.Property.YData = get( MainAxesImageHandle, 'YData' );MainAxesImage.ImageData = getappdata( handles.RussiaBlock, 'ImageData' ) ;elseMainAxesImage.ImageData = [] ;endsave ColorInfo.mat BlockColor MainAxesColor MainAxesImagedelete( handles.RussiaBlock ) ;% -------------------------------------------------------------------------function Color = GetDefaultBlockColorColor = [0 0 1] ;% -------------------------------------------------------------------------function Color = GetDefaultMainAxesColorColor = [1 1 1] ;% ----------------------------------------------------------------function [BlockXArray, BlockYArray] = Com_GetBlock( varargin )global BlockIndex ;BlockXArray = [] ;BlockYArray = [] ;handles = guidata( varargin{1} ) ;if nargin == 1BlockArray = getappdata( handles.RussiaBlock, 'BlockArray' ) ;BlockIndex = ceil( rand(1) * 24 ) ;else % nargin == 2BlockIndex = varargin{2} ;endswitch(BlockIndex)case {1,2,3,4} % 方块BlockXArray = [0;0;1;1] * 20 - 10 ;BlockYArray = [0;1;1;0] * 20 - 10 ;case {5,6} % 竖长条BlockXArray = [0;0;0;0] * 20 - 10 ;case {7,8} % 横长条BlockXArray = [-1;0;1;2] * 20 - 10 ; BlockYArray = [1;1;1;1] * 20 - 10 ; case {9} % 4类T T1 BlockXArray = [-1;0;1;0] * 20 - 10 ; BlockYArray = [1;1;1;0] * 20 - 10 ; case {10} % T2BlockXArray = [0;0;1;0] * 20 - 10 ; BlockYArray = [2;1;1;0] * 20 - 10 ; case {11} % T3BlockXArray = [0;0;1;-1] * 20 - 10 ; BlockYArray = [2;1;1;1] * 20 - 10 ; case {12} % T4BlockXArray = [0;0;0;-1] * 20 - 10 ; BlockYArray = [2;1;0;1] * 20 - 10 ; case {13} % 8类L L1 BlockXArray = [0;0;0;1] * 20 - 10 ; BlockYArray = [1;0;-1;-1] * 20 - 10 ; case {14} % L2BlockXArray = [-1;0;1;1] * 20 - 10 ; BlockYArray = [0;0;0;1] * 20 - 10 ; case {15} % L3BlockXArray = [-1;0;0;0] * 20 - 10 ; BlockYArray = [1;1;0;-1] * 20 - 10 ; case {16} % L4BlockXArray = [-1;-1;0;1] * 20 - 10 ; BlockYArray = [-1;0;0;0] * 20 - 10 ; case {17} % L5BlockXArray = [-1;0;0;0] * 20 - 10 ; BlockYArray = [-1;-1;0;1] * 20 - 10 ; case {18} % L6BlockXArray = [-1;-1;0;1] * 20 - 10 ; BlockYArray = [1;0;0;0] * 20 - 10 ; case {19} % L7BlockXArray = [0;0;0;1] * 20 - 10 ; BlockYArray = [-1;0;1;1] * 20 - 10 ; case {20} % L8BlockXArray = [-1;0;1;1] * 20 - 10 ; BlockYArray = [0;0;0;-1] * 20 - 10 ; case {21 22} % 4类Z Z1 BlockXArray = [-1;0;0;1] * 20 - 10 ; BlockYArray = [1;1;0;0] * 20 - 10 ; case {23 24} % Z2BlockYArray = [-1;0;0;1] * 20 - 10 ;case {25 26} % Z3BlockXArray = [-1;0;0;1] * 20 - 10 ;BlockYArray = [0;0;1;1] * 20 - 10 ;case {27 28} % Z4BlockXArray = [0;0;1;1] * 20 - 10 ;BlockYArray = [1;0;0;-1] * 20 - 10 ;endif nargin == 1NewBlockArray.BlockXArray = BlockXArray ;NewBlockArray.BlockYArray = BlockYArray ;NewBlockArray.BlockIndex = BlockIndex ;NextAxesXLim = get( handles.NextBlockAxes, 'XLim' ) ;NextAxesYLim = get( handles.NextBlockAxes, 'YLim' ) ;set( handles.NextBlock, 'XData', [BlockXArray + 0.5 * diff( NextAxesXLim ) -ceil( sum( BlockXArray ) / 4 ) ],...'YData', [BlockYArray + 0.5 * diff( NextAxesYLim )] - ceil( sum( BlockYArray ) / 4 ) ) ; setappdata( handles.RussiaBlock, 'BlockArray', NewBlockArray ) ;if isempty( BlockArray )Com_GetBlock( varargin{1} ) ;elseBlockXArray = BlockArray.BlockXArray ;BlockYArray = BlockArray.BlockYArray ;BlockIndex = BlockArray.BlockIndex ;endendAxesXLim = getappdata( handles.RussiaBlock, 'XLim' ) ;AxesYLim = getappdata( handles.RussiaBlock, 'YLim' ) ;BlockXArray = BlockXArray + 0.5 * diff( AxesXLim ) ;BlockYArray = BlockYArray + diff( AxesYLim ) ;% -------------------------------------------------------------------------function Status = test_MoveBlock( h, MoveMode )Status = 1;if ~ishandle( h )returnendhandles = guidata( h ) ;TempXData = get( handles.TempBlock, 'XData' ) ;TempYData = get( handles.TempBlock, 'YData' ) ;TempXData = TempXData';TempYData = TempYData' ;-TotalXData = get( handles.BlockHandle, 'XData' ) ;TotalYData = get( handles.BlockHandle, 'YData' ) ;TotalXData = TotalXData' ;TotalYData = TotalYData' ;TempBlockPos = getappdata( handles.RussiaBlock, 'TempBlockPos' ) ;if isempty( TempBlockPos )returnendAxesXLim = getappdata( handles.RussiaBlock, 'XLim' ) ;AxesYLim = getappdata( handles.RussiaBlock, 'YLim' ) ;switch MoveModecase 'Left'if any( TempXData - 20 < AxesXLim(1) )returnendTestArray = ismember( [TempXData - 20, TempYData], [TotalXData, TotalYData],'rows' ) ;if any( TestArray )return;elseset( handles.TempBlock, 'XData', TempXData - 20 ) ;TempBlockPos.LeftStep = TempBlockPos.LeftStep + 1 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;endcase 'Right'if any( TempXData + 20 > AxesXLim(2) )returnendTestArray = ismember( [TempXData + 20, TempYData], [TotalXData, TotalYData],'rows' ) ;if any( TestArray )return;elseset( handles.TempBlock, 'XData', TempXData + 20 ) ;TempBlockPos.LeftStep = TempBlockPos.LeftStep - 1 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;endcase 'Down'if any( TempYData - 20 < AxesYLim(1) )set( handles.BlockHandle, 'XData', [TotalXData; TempXData],...'YData', [TotalYData; TempYData] ) ;Status = 0 ;return-endTestArray = ismember( [TempXData, TempYData - 20], [TotalXData, TotalYData],'rows' ) ;if any( TestArray )set( handles.BlockHandle, 'XData', [TotalXData; TempXData],...'YData', [TotalYData; TempYData] ) ;Status = 0 ;elseset( handles.TempBlock, 'YData', TempYData - 20 ) ;TempBlockPos.DownStep = TempBlockPos.DownStep + 1 ;setappdata( handles.RussiaBlock, 'TempBlockPos', TempBlockPos ) ;endcase 'Drop'global PauseTimePauseTime = 0 ;case 'Change'global BlockIndexOldBlockIndex = BlockIndex ;switch BlockIndexcase {1,2,3,4}return;case {5,6}NewIndex = 7 ;case {7,8}NewIndex = 5 ;case {9,10,11,12}NewIndex = mod( OldBlockIndex, 4 ) + 9;case {13,14,15,16}NewIndex = mod( OldBlockIndex, 4 ) + 13;case {17,18,19,20}NewIndex = mod( OldBlockIndex, 4 ) + 17;case {21,22}NewIndex = 23;case {23,24}NewIndex = 21;case {25,26}NewIndex = 27 ;case {27,28}NewIndex = 25 ;end[BlockXArray, BlockYArray] = Com_GetBlock( h, NewIndex ) ;NewTempXData = BlockXArray - TempBlockPos.LeftStep * 20 ;NewTempYData = BlockYArray - TempBlockPos.DownStep * 20 ;if any( NewTempXData < AxesXLim(1) ) | any( NewTempXData > AxesXLim(2) ) |...。