如何将简单游戏减少到18行MATLab代码

时间:2016-03-28 02:55:16

标签: matlab

我最近的任务是将用MATLab代码编写的简单游戏减少到最多18行代码。这可以通过摆脱冗余来完成,但到目前为止我无法区分它们。我的代码目前运行到24行。

游戏要求如下:

“在本练习中,您需要实施一个简单的双人计数游戏。游戏首先将计数设置为0.两个玩家应该在数字1和2之间选择其他轮次。在每一轮中,数字为当前玩家选择被添加到计数中。达到10或更大值的玩家赢得游戏。程序应该检查输入的正确性。下面的图像有一个样本运行。

注意:您必须使程序最多包含18行代码,但不允许通过在同一行上放置多个语句/命令来实现此目标。“

还有一件事:我注意到这部分代码......

if count >= 10
    disp('Player x wins!');
end

...位置不正确,因为即使玩家1获胜并且游戏惊呼它,玩家2仍然会被要求输入一个数字。我不知道如何解决这个问题。抱歉! (我确信以某种方式更改此代码将有助于将总行数减少到18。)

请帮帮我!我已经把头发撕了3个小时了!

谢谢!

clear
clc
count = 0;
while count < 10;
    oneOrTwo = input('Player 1\nEnter 1 or 2: '); % Player 1 choose
    while oneOrTwo ~= 1 && oneOrTwo ~= 2
        oneOrTwo = input('Incorrect input. Try again: ');
    end
    count = count + oneOrTwo;
    if count >= 10
        disp('Player 1 wins!');
    end
    oneOrTwo = input('Player 2\nEnter 1 or 2: '); % Player 2 choose
    while oneOrTwo ~= 1 && oneOrTwo ~= 2
        oneOrTwo = input('Incorrect input. Try again: ');
    end
    count = count + oneOrTwo;
    if count >= 10
        disp('Player 2 wins!');
    end
end % This currently ends at line 24

1 个答案:

答案 0 :(得分:0)

我设法将其归结为12行代码。试试这个:

<uwsgi>
<fastrouter>:3660</fastrouter>
<master/>
<processes>5</processes>
<listen>8192</listen>
<fastrouter-subscription-server>10.12.1.26:7000</fastrouter-subscription-server>
<http-stats-server>10.*:5004</http-stats-server>
<stats>/tmp/stats_uwsgi_proxy.socket</stats>

<enable-threads/>
<logto>/home/chunyu/workspace/uwsgi_proxy/log/uwsgi.log</logto>
<daemonize>/home/chunyu/workspace/uwsgi_proxy/log/uwsgi.log</daemonize>

如您所见,输入过程使用clc count = 0; player = 1; % 0: player 1, 1: player 2 while count < 10; player = mod(player+1,2); oneOrTwo = input(['Count: ' num2str(count) '\nPlayer ' num2str(player+1) '\nEnter 1 or 2: ']); while oneOrTwo ~= 1 && oneOrTwo ~= 2 oneOrTwo = input('Incorrect input. Try again: '); end count = count + oneOrTwo; end disp(['Player ' num2str(player+1) ' wins!']); 变量压缩为一个。

胜利条件从内部被移除,因为一旦player超过10,循环结束。然后,显示获胜者消息。

删除了count指令,因为两个主要变量在开始时被初始化。

在询问输入时还添加了当前的clear信息。