声振论坛

 找回密码
 我要加入

QQ登录

只需一步,快速开始

查看: 2221|回复: 12

[共享资源] 用matlab编写的一个贪食蛇游戏

[复制链接]
发表于 2006-11-13 10:39 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?我要加入

x
该文件需要存为engine.m

  1. %=====This script is used with "snake.m" as a part of the program
  2. %=====By Valery Garmider=========================================
  3. %=====Updated 27/03/03===========================================
  4.                 %===Evaluates next values of snake's head coordinates==
  5.                 ih=ih+xdrn;
  6.                 jh=jh+ydrn;
  7.                 %===The snake catches a prey==============
  8.                 if [ih==ir jh==jr]
  9.                         %===Evaluates next prey coordinates==
  10.                         SNK=sparse(i,j,1,m,m);
  11.                         [nsi,nsj]=find(~SNK);
  12.                         pr=floor((m^2-k)*rand)+1;
  13.                         ir=nsi(pr);
  14.                         jr=nsj(pr);
  15.                         set(Prey,'xdata',ir,'ydata',jr,'Color','y');
  16.                         %===Updates comment window===========
  17.          if timer>9
  18.             set(uic(4),'String',' Catched it! Go! ');
  19.          else
  20.             set(uic(4),'String','At last! Come on! Move your ass!');
  21.          end;
  22.                         %===Updates play variables=========       
  23.                         score=score+floor(timer/10);
  24.                         level=level+1;
  25.                         timer=109;
  26.          incrmnt=incrmnt-6;
  27.          %===Define colors=======================
  28.          SnakColor=[(cos(level*pi/100))^2  (sin(level*pi/130))^2  (cos(level*pi/60))^2];   
  29.          HeadColor=1-SnakColor;   
  30.          %===Updates score and level indicators==
  31.                         set(ScoreHndl,'String',int2str(score));
  32.          set(LevelHndl,'String',int2str(level));
  33.                 end;
  34.                 %===Updates snake image=====================
  35.                 if incrmnt<6
  36.                         incrmnt=incrmnt+1;
  37.                         k=k+1;
  38.                         i=[ih i];
  39.                         j=[jh j];
  40.                 else
  41.                         i=[ih i(1:k-1)];
  42.                         j=[jh j(1:k-1)];
  43.                         set(PlotHndl,'xdata',itl,'ydata',jtl,'color',[0.4 0.8 0.4]);
  44.       end;
  45.                 set(HeadHndl,'xdata',ih,'ydata',jh,'color',HeadColor);
  46.                 set(HeadHndl,'xdata',i(3),'ydata',j(3),'color',SnakColor);
  47.       set(PlotHndl,'xdata',i(3),'ydata',j(3),'color',SnakColor);
  48.       PreyColor=[0.5+timer/218 timer/109 0];
  49.       set(Prey,'Color',PreyColor);
  50.                 %==="A stupid snake catches his own tail" indicator=====
  51.       CMP=(i==ih)&(j==jh);
  52.       %===Pause the game======================================
  53.       PausGm=strcmp(get(ValNumber,'SelectionType'),'alt');
  54.                 %===Decreasing the score timer===============
  55.                 if timer>9
  56.                         timer=timer-1;
  57.                 end;
  58.                 drawnow;
  59.                 %===Some comments============================
  60.                 %if xPt<0|xPt>m+1|yPt<0|yPt>m+1
  61.                 %         InsdprStr= ...
  62.                 %        [' Press inside the play area!                       '];
  63.                 %        set(uic(4),'String',InsdprStr);
  64.                 if [timer<50 timer>9]
  65.                         set(uic(4),'String',' Hurry!');
  66.                 elseif timer==9
  67.                         LateStr= ...
  68.                         [' Too late!                                         '
  69.                          ' Next time move your ass quicker!                  '];
  70.                         set(uic(4),'String',LateStr);
  71.                 end;
复制代码

[ 本帖最后由 suffer 于 2006-11-15 15:28 编辑 ]
回复
分享到:

使用道具 举报

 楼主| 发表于 2006-11-13 10:40 | 显示全部楼层
  1. function snake(action)
  2. %=======THE GREATEST GAME OF SNAKE==================
  3. %  Well known game from cellular telephones
  4. %  now also available on MATLAB.
  5. %
  6. %  Pretty nice interface,
  7. %  mouse control,
  8. %  funny coments are displayed during the play.
  9. %
  10. %  *ROOLS*
  11. %  All rules are familiar besides one :
  12. %  more time you waste to catch the "prey" - less points you get.
  13. %  Wasted too much time ? You don't get points at all.
  14. %  The comment window will notify you whenever you should hurry
  15. %  and whenever the maximal time is expired.
  16. %  In addition, the "prey" will change color - from yellow(you get 10 pts)
  17. %  to dark brown(you get 0 pts).
  18. %
  19. %  *START A NEW GAME*
  20. %  Choose "New game" in the menubar.
  21. %  Then type your name (or anything else) in desired place.
  22. %
  23. %  *MOUSE CONTROL*
  24. %  Just start to play - you`ll quickly get the point :
  25. %      leftclicking turns the snake towards the pointer,
  26. %      rightclicking pouses the game.
  27. %  Tip : rightclick whenever you miss the "prey",
  28. %        or if you want to "roll up" enormously long snake.
  29. %
  30. %  *SAVE AND LOAD THE GAME*
  31. %  You can save the current game :  
  32. %      just rightclick to pause the game and
  33. %      choose "Save game" in the menubar.
  34. %  Later you`ll be able to continue any saved game :
  35. %      choose "Continue game" in the menubar
  36. %      and type a name of the saved game in desired.
  37. %  Tip : before saving, be sure the snake "looks nice".
  38. %
  39. %  *BEST RESULTS*
  40. %  If the player exceeds the highscore, his result and his name
  41. %  are stored in memory.
  42. %
  43. %  *RUNNING TEXT*
  44. %  Under the "play area" you`ll see the text tray running.
  45. %  It displays the following : player`s name, best player`s
  46. %  (SnakeMaster`s) name and best result.
  47. %
  48. %  *COMMENTS*
  49. %  On the bottom of the window you`ll see an area displaying
  50. %  comments guiding you in using the interface
  51. %  and some announcements during the play, for instance :
  52. %  when the time, desired to get any  points for catching the "prey",
  53. %  is running out, the word "Hurry" appears.
  54. %
  55. %  *DEMO*
  56. %  Choose "Demonstration" in the menubar to see a demoplay.
  57. %  
  58. %  *CREDITS*
  59. %  The "snake" game - version 1.03
  60. %        Created by Valery Garmider
  61. %  Updated 27/03/03
  62. %        Copyright (c) by Valery Garmider, Inc.
  63. %
  64. %===================================================


  65. if nargin<1
  66.    action='initialize';
  67. end;

  68. %=================Initialize=======================
  69. if strcmp(action,'initialize')
  70.    %=============================
  71.    Rsltn=get(0,'ScreenSize');
  72.    Ratio=1.65;
  73.    width=max(Rsltn)/4;
  74.    height=Ratio*width;
  75.    Pstn=[(Rsltn(3)-width)/2 (Rsltn(4)-height)/2 width height];
  76.         ValNumber=figure( ...
  77.                 'name','The greatest game of Snake', ...
  78.                 'NumberTitle','off', ...
  79.                 'Visible','off', ...
  80.       'BackingStore','off', ...
  81.       'menubar','none', ...
  82.       'Color','k', ...
  83.       'Position',Pstn);
  84.    FrmHeight=0.25;
  85.    AssHeight=1.00/Ratio;
  86.    AssPstn=[0.00 FrmHeight 1.00 AssHeight];
  87.         AssHndl=axes( ...
  88.                 'Units','normalized', ...
  89.                 'Position',AssPstn, ...
  90.                 'Visible','off', ...
  91.                 'DrawMode','fast', ...
  92.       'NextPlot','add', ...
  93.       'Color',[0.4 0.8 0.4], ...
  94.       'UserData',1);
  95.         %==Introduction comment======================
  96.         text(0,0.85,' Want to play? ', ...
  97.                 'HorizontalAlignment','center','color','w');
  98.         text(0,0.70,'  Let`s play!   ', ...
  99.                 'HorizontalAlignment','center','color','w');
  100.    axis([-1 1 -1 1]);
  101.    
  102.    %Create the menu
  103.    label = str2mat(...
  104.       '&Snake Tools', ...
  105.       '>&New game', ...
  106.       '>&Continue game', ...
  107.       '>&Save game', ...
  108.       '>&Demonstration', ...
  109.       '>&About Snake', ...
  110.       '>>---------', ...
  111.       '>&Quit Snake');
  112.    call = str2mat(...
  113.       '', ...
  114.       'snake(''start'');', ...
  115.       'set(gca,''UserData'',1);snake(''load'');', ...
  116.       'snake(''save'');', ...
  117.       'snake(''Demo'');', ...
  118.       'snake(''info'');', ...
  119.       '', ...
  120.       'snake(''close'')');
  121.    Menu=makemenu(ValNumber,label,call);
  122.    set(Menu(4),'Enable','off');
  123.         %===The comment window======================
  124.    FrmPstn=[0.00 FrmHeight+AssHeight 1.00, ...
  125.          1.00-FrmHeight-AssHeight];
  126.         uicontrol( ...
  127.                 'Style','frame', ...
  128.                 'Units','normalized', ...
  129.                 'Position',FrmPstn, ...
  130.                 'BackgroundColor',[0.5 0.5 0.5]);
  131.         uicontrol( ...
  132.                 'Style','frame', ...
  133.                 'Units','normalized', ...
  134.                 'Position',[0.00 0.00 1.00 FrmHeight], ...
  135.                 'BackgroundColor',[0.5 0.5 0.5]);
  136.          PromptStr= ...
  137.    ['Press the "NEW" button to begin a new game,'
  138.          'the "LOAD" button to continue a saved game,'
  139.          'the "INFO" button for information,         '
  140.          'the "EXIT" button to shut this folly down. '];
  141.         PromptHndl=uicontrol( ...
  142.                 'Style','edit', ...
  143.                 'Units','normalized', ...
  144.                 'Max',10, ...
  145.       'BackgroundColor',[0.2 0.2 0.2], ...
  146.       'ForeGroundColor',[1.0 0.5 1.0], ...
  147.                 'Position',[0.01 0.01 0.98 0.14], ...
  148.                 'String',PromptStr);
  149.    %==="SCORE" and "LEVEL" indicators===========
  150.    ScrPstn=[0.06 FrmHeight+AssHeight+0.01 0.14 0.04];
  151.         ScoreHndl=uicontrol( ...
  152.                 'Style','edit', ...
  153.                 'Units','normalized', ...
  154.                 'Max',10, ...
  155.       'BackgroundColor',[0.3 0.2 0.2], ...
  156.       'ForeGroundColor',[0.9 0.9 0.9], ...
  157.                 'Position',ScrPstn, ...
  158.                 'Visible','off');                               
  159.         LevelHndl=uicontrol( ...
  160.                 'Style','edit', ...
  161.                 'Units','normalized', ...
  162.                 'Max',10, ...
  163.       'BackgroundColor',[0.3 0.2 0.2], ...
  164.       'ForeGroundColor',[0.9 0.9 0.9], ...
  165.                 'Position',[0.94-ScrPstn(3) ScrPstn(2:4)], ...
  166.                 'Visible','off');
  167.         %===Name typing area========================
  168.         FrmHndl=uicontrol( ...
  169.                 'Style','frame', ...
  170.                 'Units','normalized', ...
  171.                 'Position',[0.30 0.36 0.40 0.40], ...
  172.                 'BackgroundColor',[0.5 0.5 0.5], ...
  173.                 'Visible','off');
  174.         IntrdcHndl=uicontrol( ...
  175.                 'Style','text', ...
  176.                 'Units','normalized', ...
  177.                 'Max',10, ...
  178.                 'BackgroundColor',[0.5 0.5 0.5], ...
  179.                 'ForegroundColor',[0.8 0.8 0.8], ...
  180.                 'Position',[0.31 0.65 0.38 0.05], ...
  181.       'Visible','off');                       
  182.         NameHndl=uicontrol( ...
  183.                 'Style','edit', ...
  184.                 'Units','normalized', ...
  185.                 'Max',10, ...
  186.                 'BackgroundColor',[1 1 1], ...
  187.                 'Position',[0.32 0.55 0.36 0.04], ...
  188.                 'Visible','off');                                               
  189.         %===The OK button===========================
  190.         OKHndl=uicontrol( ...
  191.                 'Style','pushbutton', ...
  192.                 'Units','normalized', ...
  193.                 'Position',[0.43 0.40 0.14 0.08], ...
  194.                 'Interruptible','on', ...
  195.                 'String','OK', ...
  196.                 'Callback','snake(''play'');', ...
  197.                 'Visible','off');                                                               
  198.    %===The Speed slider========================
  199.    IndPstn=[0.01 FrmHeight+AssHeight+0.06 0.98 0.04];
  200.         IndString=['score                      speed                        level'];
  201.         IndHndl=uicontrol( ...
  202.                 'Style','text', ...
  203.                 'Units','normalized', ...
  204.                 'Max',10, ...
  205.                 'BackgroundColor',[0.5 0.5 0.5], ...
  206.                 'ForegroundColor',[0.8 0.8 0.8], ...
  207.                 'Position',IndPstn, ...
  208.       'String',IndString, ...
  209.       'Visible','off');       
  210.    SpdLngth=0.2;
  211.    SpdPstn=[0.5-SpdLngth FrmHeight+AssHeight+0.01 SpdLngth*2 0.04];
  212.         SpeedHndl=uicontrol( ...
  213.                 'Style','slider', ...
  214.                 'Units','normalized', ...
  215.                 'Position',SpdPstn, ...
  216.       'Interruptible','on', ...
  217.       'Visible','off', ...
  218.       'value',0.5);       
  219.    %===Buttons information=====================
  220.    BtnWidth=0.23;
  221.    BtnHeight=0.06;
  222.    BtnSize=[BtnWidth BtnHeight];
  223.    BtnSpace=(1.00-BtnWidth)/2;
  224.    Dstnc=BtnHeight+0.03;
  225.         %===The START button========================
  226.         StartHndl=uicontrol( ...
  227.                 'Style','pushbutton', ...
  228.                 'Units','normalized', ...
  229.                 'Position',[BtnSpace FrmHeight+Dstnc*4 BtnSize], ...
  230.                 'Interruptible','on', ...
  231.                 'String','new', ...
  232.                 'Callback','snake(''start'');');
  233.         %===The INFO button========================
  234.         InfoHndl=uicontrol( ...
  235.                 'Style','pushbutton', ...
  236.                 'Units','normalized', ...
  237.                 'Position',[BtnSpace FrmHeight+Dstnc*2 BtnSize], ...
  238.                 'Interruptible','on', ...
  239.                 'String','info', ...
  240.                 'Callback','snake(''info'');');
  241.         %===The CLOSE button========================
  242.         CloseHndl=uicontrol( ...
  243.                 'Style','pushbutton', ...
  244.                 'Units','normalized', ...
  245.                 'Position',[BtnSpace FrmHeight+Dstnc BtnSize], ...
  246.                 'Interruptible','on', ...
  247.                 'String','exit', ...
  248.                 'Callback','snake(''close'');');
  249.         %===The LOAD button========================
  250.         LOADHndl=uicontrol( ...
  251.                 'Style','pushbutton', ...
  252.                 'Units','normalized', ...
  253.                 'Position',[BtnSpace FrmHeight+Dstnc*3 BtnSize], ...
  254.                 'Interruptible','on', ...
  255.                 'String','load', ...
  256.                 'Value',1, ...
  257.       'Callback','set(gca,''UserData'',1);snake(''load'');');
  258.    %===Player`s name===========================
  259.         PlrHndl=uicontrol( ...
  260.                 'Style','text', ...
  261.                 'Units','normalized', ...
  262.                 'Max',10, ...
  263.                 'BackgroundColor',[0.5 0.5 0.5], ...
  264.                 'ForegroundColor',[0.8 0.8 0.0], ...
  265.       'Position',[0.01 0.19 0.98 0.04], ...
  266.       'String','...check...', ...
  267.       'Visible','off');       
  268.         %===Saves interface data====================
  269.         uic=[StartHndl;InfoHndl;CloseHndl;PromptHndl;IndHndl;ScoreHndl; ...
  270.          LevelHndl;NameHndl;OKHndl;FrmHndl;IntrdcHndl;PlrHndl;LOADHndl;SpeedHndl;0;Menu];
  271. set(ValNumber,'Visible','on','UserData',uic);


  272. %===Start a new game screen=========================
  273. elseif strcmp(action,'start')
  274.    cla;
  275.         AssHndl=gca;
  276.         ValNumber=gcf;
  277.         %===Loads interface data============================
  278.    uic=get(ValNumber,'UserData');
  279.    cla;
  280.         set(uic([5:7 12 14]),'Visible','off');
  281.         set(AssHndl,'Visible','off');
  282.    set(uic(19),'Enable','off');%"save property"
  283.         set(uic([1:3 13]),'Visible','off');       
  284.    set(uic(9),'Callback','snake(''play'');');
  285.    set(uic(11),'string','Type your name:');
  286.         %===Player introducing===============================
  287.    set(uic(8:11),'Visible','on');
  288.    set(uic(4),'string','Introduce yourself please.');
  289.    %===Game Data Initialize=====
  290.       m=50;
  291.            k=4;
  292.                 ih=m/2;jh=m/2;
  293.                 i=[ih ih-1 ih-2 ih-3];j=[jh jh jh jh];
  294.                 score=0;
  295.                 level=0;
  296.                 ir=floor(m*rand)+1;
  297.                 jr=floor(m*rand)+1;
  298.                 xdrn=1;
  299.                 ydrn=0;
  300.                 timer=109;       
  301.                 incrmnt=6;

  302.     GmData={i j ih jh k timer incrmnt score level  ir jr xdrn ydrn 1};
  303.     set(AssHndl,'UserData',GmData);

  304. %===Load a saved game screen=========================
  305. elseif strcmp(action,'load')
  306.         cla;
  307.         AssHndl=gca;
  308.         ValNumber=gcf;
  309.         %===Loads interface data============================
  310.    uic=get(ValNumber,'UserData');
  311.         cla;
  312.         set(uic([5:7 12 14]),'Visible','off');
  313.         set(AssHndl,'Visible','off');
  314.    set(uic(19),'Enable','off');%"save property"
  315.         set(uic([1:3 13]),'Visible','off');       
  316.    set(uic(9),'Callback','snake(''load'');');
  317.    set(uic(11),'string','Load a saved game:');
  318.         %===Player introducing===============================
  319.    set(uic(8:11),'Visible','on');
  320.    Name=get(uic(8),'string');
  321.    if get(AssHndl,'UserData')
  322.       set(uic(4),'string','Type a name of a saved game');
  323.       set(AssHndl,'UserData',0);
  324.    %Check`s if saved game exists=======================
  325.    elseif ~exist([Name '.txt'])
  326.       WrngStr= ...
  327.          ['Can`t find such a saved game    '
  328.           'Type a correct name!            '];
  329.       set(uic(4),'String',WrngStr);
  330.    else
  331.       %===Loades game data==================
  332.                 fid=fopen([Name '.txt'],'r');
  333.                 SnkInf=fscanf(fid,'%3d %3d\n',[2,inf]);
  334.                 i=SnkInf(1,:);
  335.                 j=SnkInf(2,:);
  336.                 i(1:4)=[];j(1:4)=[];
  337.                 ih=i(1);jh=j(1);
  338.                 k=length(i);
  339.                 timer=SnkInf(1,1);       
  340.                 incrmnt=SnkInf(2,1);
  341.                 score=SnkInf(1,2);
  342.                 level=SnkInf(2,2);
  343.                 ir=SnkInf(1,3);
  344.                 jr=SnkInf(2,3);
  345.                 xdrn=SnkInf(1,4);
  346.                 ydrn=SnkInf(2,4);
  347.       set(uic(13),'value',1);
  348.       
  349.       GmData={i j ih jh k timer incrmnt score level  ir jr xdrn ydrn 1};
  350.       set(AssHndl,'UserData',GmData);
  351.       
  352.       snake('play');
  353.    end;
  354.    
  355. %===============Start===============================
  356. elseif strcmp(action,'play')
  357.         cla;
  358.         AssHndl=gca;
  359.         ValNumber=gcf;
  360.         %===Loads interface data============================
  361.    uic=get(ValNumber,'UserData');
  362.    %score and level indicators=========================
  363.         ScoreHndl=uic(6);
  364.         LevelHndl=uic(7);
  365.         %===Player introducing removing======================
  366.    set(uic(8:11),'Visible','off');
  367.    set(uic(19),'Enable','on');%"save property"
  368.    %===Extracts value of highscore and best player`s name
  369.    if [exist('highscor.txt') exist('bestplyr.txt')]
  370.       fid=fopen('highscor.txt','r');
  371.       highscr=fscanf(fid,'%6d');
  372.       fid=fopen('bestplyr.txt','r');
  373.       bestplyr=fscanf(fid,'%s');
  374.    else
  375.       highscr=0;
  376.       bestplyr='Nobody';
  377.    end;
  378.    %Player`s name==================
  379.    Name=get(uic(8),'string');
  380.    %Running text=======================================
  381.    RunStr=[' **** Player: ' Name ' **** Best result: ', ...
  382.          int2str(highscr) ' **** SnakeMaster: ' bestplyr];
  383.    set(uic(12),'Visible','on', ...
  384.       'String',RunStr(1:min([50 length(RunStr)])));
  385.         %===Uncover the figure===============================                     
  386.         set(AssHndl, ...
  387.                 'DrawMode','fast', ...
  388.                 'Visible','on', ...
  389.                 'Box','on', ...
  390.                 'Xtick',[],'Ytick',[], ...
  391.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  392.         figure(gcf);
  393.         m=50;
  394.         %===Exceeding highscore movie variables==========
  395.         a(1:m+2)=zeros(1,m+2);b(1:m+2)=(m+1)*ones(1,m+2);
  396.         c(1:m+2)=0:m+1;d(1:m+2)=m+2-[1:m+2];
  397.    %===Snake game initial variables===================
  398.    GmData=get(AssHndl,'UserData');
  399.    i=GmData{1};
  400.    j=GmData{2};
  401.    ih=GmData{3};
  402.    jh=GmData{4};
  403.    k=GmData{5};
  404.    timer=GmData{6};
  405.    incrmnt=GmData{7};
  406.    score=GmData{8};
  407.    level=GmData{9};
  408.    ir=GmData{10};
  409.    jr=GmData{11};
  410.    xdrn=GmData{12};
  411.    ydrn=GmData{13};
  412.    PausGm=2*GmData{14}+strcmp(get(ValNumber,'SelectionType'),'alt');
  413.    %===for debugging purposes============================
  414.    ChitStr=get(uic(4),'string');
  415.    if length(ChitStr)>11
  416.       if strcmp(ChitStr(1:8),'teleport')&str2num(ChitStr(9:12))
  417.       ih=str2num(ChitStr(9:10));
  418.       jh=str2num(ChitStr(11:12));end;end;
  419.    if strcmp(ChitStr,'flipflop')
  420.       i=fliplr(i);
  421.       j=fliplr(j);
  422.       ih=i(1);
  423.       jh=j(1);end;
  424.    if length(ChitStr)>3
  425.       if strcmp(ChitStr(1:4),'tree')&str2num(ChitStr(5:end))
  426.       vetka=min(length(i),str2num(ChitStr(5:end)));
  427.       ih=i(vetka);
  428.       jh=j(vetka);end;end;
  429.    if length(ChitStr)>3
  430.       if strcmp(ChitStr(1:4),'jump')&str2num(ChitStr(5:6))
  431.       jmpdst=str2num(ChitStr(5:6));
  432.       ih=ih+jmpdst*xdrn;
  433.       jh=jh+jmpdst*ydrn;end;end;
  434.    %Play area clicking toggle
  435.    set(AssHndl,'UserData',1);
  436.         %==Helper variables============
  437.    ibdy=i(3:end);jbdy=j(3:end);
  438. %===Colors====================================
  439. SnakColor=[(cos(level*pi/100))^2  (sin(level*pi/130))^2  (cos(level*pi/60))^2];   
  440. HeadColor=1-SnakColor;   
  441. PreyColor=[0.5+timer/218 timer/109 0];
  442. %===Drawing initial snake`s body===========================
  443.         PlotHndl=plot(ibdy,jbdy,'.', ...
  444.                 'EraseMode','none', ...
  445.                 'color',SnakColor, ...
  446.                 'MarkerSize',15, ...
  447.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  448. %===Drawing initial snake`s head==========================
  449.         HeadHndl=plot(i(1:2),j(1:2),'.', ...
  450.                 'EraseMode','none', ...
  451.                 'color',HeadColor, ...
  452.                 'MarkerSize',15, ...
  453.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  454. %===Drawing initial "Prey" ================================
  455.         Prey=plot(ir,jr,'.', ...
  456.                 'EraseMode','xor', ...
  457.                 'color',PreyColor, ...
  458.                 'MarkerSize',15, ...
  459.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  460.         axis([0 m+1 0 m+1]);
  461. %===Initial values of play variables=============
  462.         CMP=1;
  463. %==="Player","Snakemaster","SCORE","HIGHSCORE" and "LEVEL" indicators===============
  464.         set(ScoreHndl, ...
  465.       'Visible','on', ...
  466.                 'String',int2str(score));
  467.         set(LevelHndl, ...
  468.                 'Visible','on', ...
  469.       'String',int2str(level));
  470.    %===Slider, and indicators label======
  471.    set(uic([5 14]),'Visible','on');
  472.    %Comment window===========================================
  473.          GoStr= ...
  474.         [' Go!                                               '];
  475.      set(uic(4),'String',GoStr);
  476.      drawnow;
  477.    %===THE MAIN LOOP=================================       
  478.    while [ih>0 ih<=m jh>0 jh<=m nnz(CMP)==1 ~PausGm]   
  479.                 %===Tail erasing variables================
  480.       itl=i(end);jtl=j(end);
  481.                 %===Make sure the button pressed inside the "Play area"==
  482.                      currPt=get(AssHndl,'CurrentPoint');
  483.                     xPt=currPt(1,1);yPt=currPt(1,2);
  484.                 btndn=get(AssHndl,'UserData');
  485.                 if [xPt>=0 xPt<=m+1 yPt>=0 yPt<=m+1 btndn]
  486.                         %===Evaluating variables of snake direction==
  487.                         dx=sign(xPt-ih);dy=sign(yPt-jh);
  488.                         xdrn=(~xdrn)*dx+(~dy)*xdrn;
  489.                         ydrn=(~ydrn)*dy+(~dx)*ydrn;
  490.                         set(AssHndl,'UserData',0);  
  491.       end;
  492.       %=====Next step routine==========================
  493.       engine;
  494.       %=====Running text tray==========================
  495.       RunStr=[RunStr(2:end) RunStr(1)];
  496.       set(uic(12),'Visible','on', ...
  497.          'String',RunStr(1:min([50 length(RunStr)])));                 
  498.                 %===Snake's speed loop=======================
  499.       ratio=get(uic(14),'value');
  500.       pause(0.20-ratio*0.18);
  501. %                for count=1:(15000-ratio*10000)
  502. %                        r=rand;
  503. %                end;
  504.         end;
  505.    %===END OF MAIN LOOP=================================
  506.    %================Pause Game===========================
  507.    if PausGm
  508.       GmData={i j ih jh k timer incrmnt score level  ir jr xdrn ydrn 0};
  509.       set(AssHndl, ...
  510.          'UserData',GmData, ...
  511.          'ButtonDownFcn','snake(''play'');');
  512.       set([PlotHndl HeadHndl Prey],'ButtonDownFcn','snake(''play'');');
  513.                         ResumStr= ...
  514.                         [' The game paused.                     '
  515.                          ' Press inside the play area to resume.'
  516.                          ' You can save this game for a while.  '];
  517.        set(uic(4),'String',ResumStr);
  518.        %===If the game only begins====================================
  519.        if PausGm>1
  520.           InsdprStr= ...
  521.              [' Press inside the play area when ready             '];
  522.           set(uic(4),'String',InsdprStr);
  523.        end;
  524.    %======================================================   
  525.    else   
  526.         if score>highscr
  527.                 %===Highscore exceeding movie================
  528.                 while m>1
  529.                         m=m-1;
  530.                         a=a(2:m+2)+1;
  531.                         b=b(2:m+2)-1;
  532.                         c=c(2:m+2);
  533.                         d=d(2:m+2);
  534.                         plot([a c b d],[c b d a],'.', ...
  535.                         'markersize',25,'color',[0.02*m  0  1-0.02*m]);
  536.                 end;
  537.                 text(25,35,[Name '!'],'color','g', ...
  538.                         'HorizontalAlignment','center', ...
  539.                         'FontSize',20,'FontWeight','bold');
  540.                 text(25,28,'You have exceeded the highscore!', ...
  541.                         'HorizontalAlignment','center');
  542.                 text(25,24,['A new highscore is ' int2str(score)], ...
  543.                         'HorizontalAlignment','center');
  544.                 text(25,20,'Press a button to play again', ...
  545.                         'HorizontalAlignment','center');
  546.                 %===Message in comment window=========================
  547.                  ExcStr= ...
  548.                 [' Congradulations!.                                 '
  549.                  ' You have made the best result.                    '
  550.                  ' Now you are the snakemaster!                      '
  551.                  ' Press a button                                    '];
  552.                 set(uic(4),'String',ExcStr);
  553.                 %===Saves a new highscore and a new snakemaster========
  554.                 fid=fopen('highscor.txt','w');
  555.                 fprintf(fid,'%6d',score);
  556.                 fid=fopen('bestplyr.txt','w');
  557.                 fprintf(fid,'%s',Name);
  558.         else
  559.                 %==="Game Over"========================================
  560.                 set(PlotHndl,'xdata',i,'ydata',j);
  561.                 text(25,28,'      G A M E  O V E R       ', ...
  562.                         'HorizontalAlignment','center', ...
  563.                         'FontWeight','bold','FontSize',20,'color','b');
  564.                 %===Message in comment window==========================
  565.                  SheetStr= ...
  566.                         [' You loose like a piece of shit!          '
  567.                          ' Press a button to try again, Ass hole!   '];
  568.                  set(uic(4),'String',SheetStr);
  569.         end;
  570.         %===prepares to start a new game=======================
  571.    pause(0.5);
  572.    set(AssHndl,'ButtonDownFcn','snake(''NewGame'');');
  573. end;

  574. %===Demonstration session===============================================
  575. elseif strcmp(action,'Demo')
  576.         cla;
  577.         AssHndl=gca;
  578.         ValNumber=gcf;
  579.    %===Prepares screen=================================
  580.    set(AssHndl,'color','b');
  581.    set(AssHndl,'color',[0.4 0.8 0.4]);
  582.         uic=get(ValNumber,'UserData');
  583.         PromptHndl=uic(4);
  584.         ScoreHndl=uic(6);
  585.    LevelHndl=uic(7);
  586.    
  587.         %===Player introducing removing======================
  588.    set(uic([1:3 8:11 13 14]),'Visible','off');
  589.    set(uic([17:19 21 22]),'Enable','off');%"save property"
  590.    set(uic(5),'Visible','on');

  591.    %===Running text=============================================
  592.         RunStr=['**** Demonstration ******** Demonstration ****'];
  593.    set(uic(12),'Visible','on', ...
  594.       'String',RunStr);
  595.         %===Uncover the figure===============================                     
  596.         set(AssHndl, ...
  597.                 'DrawMode','fast', ...
  598.                 'Visible','on', ...
  599.                 'Box','on', ...
  600.       'Xtick',[],'Ytick',[], ...
  601.       'UserData',0, ...
  602.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  603.         figure(gcf);
  604.         m=50;
  605.         %===Snake game initial variables===================       
  606.                 k=4;
  607.                 ih=m/2;jh=m/2;
  608.                 i=[ih ih-1 ih-2 ih-3];j=[jh jh jh jh];
  609.                 score=0;
  610.                 level=0;
  611.                 ir=floor(m*rand)+1;
  612.                 jr=floor(m*rand)+1;
  613.                 xdrn=1;
  614.                 ydrn=0;
  615.                 timer=109;       
  616.                 incrmnt=6;
  617.         %===helper variables=
  618.         ibdy=i;jbdy=j;
  619.    ibdy(1:2)=[];jbdy(1:2)=[];
  620. %===Colors====================================
  621. SnakColor=[(cos(level*pi/100))^2  (sin(level*pi/130))^2  (cos(level*pi/60))^2];   
  622. HeadColor=1-SnakColor;   
  623. PreyColor=[0.5+timer/218 timer/109 0];
  624. %===Drawing initial snake`s body===========================
  625.         PlotHndl=plot(ibdy,jbdy,'.', ...
  626.                 'EraseMode','none', ...
  627.                 'color','m', ...
  628.                 'MarkerSize',15, ...
  629.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  630. %===Drawing initial snake`s head==========================
  631.         HeadHndl=plot(i(1:2),j(1:2),'.', ...
  632.                 'EraseMode','none', ...
  633.                 'color','r', ...
  634.                 'MarkerSize',15, ...
  635.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  636. %===Drawing initial "Prey" ================================
  637.         Prey=plot(ir,jr,'.', ...
  638.                 'EraseMode','xor', ...
  639.                 'color','y', ...
  640.                 'MarkerSize',15, ...
  641.                 'ButtonDownFcn','set(gca,''UserData'',1)');
  642.         axis([0 m+1 0 m+1]);
  643. %===Initial values of play variables=============
  644.         CMP=1;
  645. %==="Player","Snakemaster","SCORE","HIGHSCORE" and "LEVEL" indicators===============
  646.         set(ScoreHndl, ...
  647.                 'Visible','on', ...
  648.                 'String',int2str(score));
  649.         set(LevelHndl, ...
  650.                 'Visible','on', ...
  651.                 'String',int2str(level));

  652.          GoStr= ...
  653.         [' Go!                                               '];
  654.      set(PromptHndl,'String',GoStr);

  655. %===THE MAIN LOOP=================================       
  656.         while [ih>0 ih<=m jh>0 jh<=m nnz(CMP)==1 ~get(AssHndl,'UserData')]
  657.                 %===Tail erasing variables================
  658.                 itl=i(k);jtl=j(k);
  659.                 %===snake demo engine========================
  660.                 dx=sign(ir-ih);dy=sign(jr-jh);
  661.                 if dx*xdrn+dy*ydrn<=0
  662.                         xdrn=(~xdrn)*dx+(~dy)*xdrn;
  663.                         ydrn=(~ydrn)*dy+(~dx)*ydrn;
  664.       end;
  665.       WUS=sparse(i,j,[1:k],m,m);
  666.                    WUS=[ones(2,m);WUS;ones(2,m)];
  667.          WUS=[ones(m+4,2) WUS ones(m+4,2)];
  668.          isrnd=[1 -1 0 0];jsrnd=[0 0 1 -1];
  669.       srnd=[WUS(ih+3,jh+2) WUS(ih+1,jh+2) WUS(ih+2,jh+3) WUS(ih+2,jh+1)];
  670.       iwu=ih+2+xdrn;jwu=jh+2+ydrn;
  671.       if WUS(iwu,jwu)
  672.          if [nnz(srnd)==2 xdrn==(ih-i(2)) ydrn==(jh-j(2))]
  673.             pwus=WUS(iwu+(~xdrn),jwu+(~ydrn));
  674.             mwus=WUS(iwu-(~xdrn),jwu-(~ydrn));
  675.             drn=pwus*(pwus-WUS(iwu,jwu))+mwus*(WUS(iwu,jwu)-mwus);
  676.             xdrn=(~xdrn)*sign(drn);
  677.             ydrn=(~ydrn)*sign(drn);
  678.          elseif nnz(srnd)==3
  679.             srnd=find(~srnd);
  680.             xdrn=isrnd(srnd);
  681.             ydrn=jsrnd(srnd);
  682.          else
  683.             xdrn=ih-i(2);
  684.             ydrn=jh-j(2);
  685.          end;
  686.       end;
  687.       %===Next step routine=========
  688.       engine;
  689.       %====Running text=======================
  690.       RunStr=[RunStr(2:end) RunStr(1)];
  691.       set(uic(12),'String',RunStr);
  692.       %===Snake`s speed============
  693.       pause(0.025);
  694.    end;
  695.    %===END OF MAIN LOOP=============
  696.    snake('NewGame');
  697. %===Starts a new game===================================================
  698. elseif strcmp(action,'NewGame')
  699.         AssHndl=gca;
  700.         ValNumber=gcf;
  701.         %===Loads interface data============================
  702.    uic=get(ValNumber,'UserData');
  703.    %===Clears/Defaults interface=======================
  704.         cla;
  705.         set(uic([5:7 12 14]),'Visible','off');
  706.    set(AssHndl,'Visible','off');
  707.    set(uic(17:22),'Enable','on');
  708.    set(uic(19),'Enable','off');%"save property"
  709.         %==Introduction comment======================
  710.         text(25,46,' Wan`t you play ', ...
  711.                 'HorizontalAlignment','center','color','w');
  712.         text(25,42,'  one more time?   ', ...
  713.                 'HorizontalAlignment','center','color','w');       
  714.         set(uic([1:3 13]),'Visible','on');
  715.          PromptStr= ...
  716.    ['Press the "NEW" button to begin a new game,'
  717.          'the "LOAD" button to continue a saved game,'
  718.          'the "INFO" button for information,         '
  719.          'the "EXIT" button to shut this folly down. '];
  720.     set(uic(4),'String',PromptStr);
  721.     %===Changes the poster=========================
  722.     FgRs=get(0,'children');
  723.     if any(FgRs==uic(15))
  724.        delete(uic(15));
  725.     end;
  726.    
  727. %=====Save the game===================================
  728. elseif strcmp(action,'save')
  729.         AssHndl=gca;
  730.         ValNumber=gcf;
  731.         %===Loads interface data============================
  732.    uic=get(ValNumber,'UserData');
  733.    GmData=get(AssHndl,'UserData');
  734.    i=GmData{1};
  735.    j=GmData{2};
  736.    ih=GmData{3};
  737.    jh=GmData{4};
  738.    k=GmData{5};
  739.    timer=GmData{6};
  740.    incrmnt=GmData{7};
  741.    score=GmData{8};
  742.    level=GmData{9};
  743.    ir=GmData{10};
  744.    jr=GmData{11};
  745.    xdrn=GmData{12};
  746.    ydrn=GmData{13};
  747.    %Player`s name==================
  748.    Name=get(uic(8),'string');
  749. %Opens data file and saves=======================
  750. SavInfo=[timer   score ir xdrn i
  751.                         incrmnt level jr ydrn j];  
  752.                         fid=fopen([Name '.txt'],'w');
  753.                         fprintf(fid,'%3d %3d\n',SavInfo);
  754.                         set(uic(4),'String',' The game saved. ');
  755.       set(AssHndl, ...
  756.          'UserData',GmData, ...
  757.          'ButtonDownFcn','snake(''play'');');
  758.        
  759. %===Opens the information window========================================
  760. elseif strcmp(action,'info'),
  761.    helpwin(mfilename);
  762. %===Quits the game===========================      
  763. elseif strcmp(action,'close')
  764.         AssHndl=gca;
  765.         ValNumber=gcf;
  766.         %===Loads interface data============================
  767.    uic=get(ValNumber,'UserData');
  768.    FimHndl=uic(15);
  769.    FgRs=get(0,'children');
  770.    if any(FgRs==FimHndl)
  771.       delete(FimHndl);
  772.    end;
  773.    close(gcf);
  774. end;

  775. %=========================================================================
  776. %========================END OF THE PROGRAM===============================
  777. %=========================================================================
复制代码
发表于 2006-11-13 12:52 | 显示全部楼层
是不是很战内存啊?
发表于 2006-11-14 10:28 | 显示全部楼层
这么强吗!顶一下
发表于 2006-11-14 15:11 | 显示全部楼层
强人啊,佩服!
 楼主| 发表于 2006-11-14 18:09 | 显示全部楼层
原帖由 lxq 于 2006-11-13 12:52 发表
是不是很战内存啊?


还可以了
发表于 2006-11-15 10:23 | 显示全部楼层
没话说 学习中
发表于 2006-11-15 12:59 | 显示全部楼层

好像还存在一些问题

 楼主| 发表于 2006-11-15 15:29 | 显示全部楼层
原帖由 xjtu211 于 2006-11-15 12:59 发表



程序没有什么问题,不过发布的时候少申明了一点

第一个文件必须存engine.m
发表于 2006-11-25 12:34 | 显示全部楼层
第二个代码存成snake.m行吗?
然后运行snake.m
是这样的吗?
能具体解释一下吗?
我很菜
发表于 2006-11-28 00:04 | 显示全部楼层
9楼的说法,好象不好用啊.
因为游戏过程中score不见变化啊
请问lz,能解释一下么?
 楼主| 发表于 2006-11-29 09:22 | 显示全部楼层
原帖由 fenyunwd 于 2006-11-28 00:04 发表
9楼的说法,好象不好用啊.
因为游戏过程中score不见变化啊
请问lz,能解释一下么?


没有出现你所说的问题
没吃掉一个,score就会增加
 楼主| 发表于 2006-11-29 09:22 | 显示全部楼层
原帖由 HolySaint 于 2006-11-25 12:34 发表
第二个代码存成snake.m行吗?
然后运行snake.m
是这样的吗?
能具体解释一下吗?
我很菜


是这样的
您需要登录后才可以回帖 登录 | 我要加入

本版积分规则

QQ|小黑屋|Archiver|手机版|联系我们|声振论坛

GMT+8, 2024-6-17 21:39 , Processed in 0.067722 second(s), 19 queries , Gzip On.

Powered by Discuz! X3.4

Copyright © 2001-2021, Tencent Cloud.

快速回复 返回顶部 返回列表