我实际上是 matlab 的新手并尝试编写这个游戏......问题是当我输入 2 或 6 时,我的程序必须在 2 和 4 之间添加一个随机的新数字而不是零,但它没有......请帮助我找出问题出在哪里...我几乎可以肯定 for 循环是正确的,我猜问题出在 while 循环中...对不起我的语言...谢谢
for i=1:2
a1=rand;
if a1>0.666666
b1=4;
else
b1=2;
end
c1=round(3*rand + 1);
c2=round(3*rand + 1);
A(4,4)=0;
A(c1,c2)=b1;
end
disp(A)
while 2>1
S=input('direction')
if S==2
for i=1:4
if A(2,i)==0
A(2,i)=A(1,i);
A(1,i)=0;
end
if A(3,i)==0
A(3,i)=A(2,i);
A(2,i)=A(1,i);
A(1,i)=0;
end
if A(4,i)==0
A(4,i)=A(3,i);
A(3,i)=A(2,i);
A(2,i)=A(1,i);
A(1,i)=0;
end
end
for i=1:4
if A(4,i)==A(3,i);
A(4,i)=2*A(3,i);
A(3,i)=A(2,i);
A(2,i)=A(1,i);
A(1,i)=0;
end
if A(3,i)==A(2,i);
A(3,i)=2*A(2,i);
A(2,i)=A(1,i);
A(1,i)=0;
end
if A(2,i)==A(1,i)
A(2,i)=2*A(2,i);
A(1,i)=0;
end
end
a2=rand;
if a2>0.666666
b2=4;
else
b2=2;
end
while 3>1
x1=round(3*rand+1);
x2=round(3*rand+1);
if A(x1,x2)==0
break
end
if find(A)==16
break
end
end
if find(A)~=16
A(x1,x2)=b2;
end
end
if S==8
for i=1:4
if A(3,i)==0
A(3,i)=A(4,i);
A(4,i)=0;
end
if A(2,i)==0
A(2,i)=A(3,i);
A(3,i)=A(4,i);
A(4,i)=0;
end
if A(1,i)==0
A(1,i)=A(2,i);
A(2,i)=A(3,i);
A(3,i)=A(4,i);
A(4,i)=0;
end
end
for i=1:4
if A(1,i)==A(2,i)
A(1,i)=2*A(2,i);
A(2,i)=A(3,i);
A(3,i)=A(4,i);
A(4,i)=0;
end
if A(2,i)==A(3,i)
A(2,i)=2*A(3,i);
A(3,i)=A(4,i);
A(4,i)=0;
end
if A(3,i)==A(4,i)
A(3,i)=2*A(3,i);
A(4,i)=0;
end
end
a3=rand;
if a3>0.666666
b3=4;
else
b3=2;
end
while 1
x3=round(3*rand+1);
x4=round(3*rand+1);
if A(x3,x4)==0
break
end
if find(A)==16
break
end
end
if find(A)~=16
A(x3,x4)=b3;
end
end
if S==6
for j=1:4
if A(j,2)==0
A(j,2)=A(j,1);
A(j,1)=0;
end
if A(j,3)==0
A(j,3)=A(j,2);
A(j,2)=A(j,1);
A(j,1)=0;
end
if A(j,4)==0
A(j,4)=A(j,3);
A(j,3)=A(j,2);
A(j,2)=A(j,1);
A(j,1)=0;
end
end
for j=1:4
if A(j,4)==A(j,3);
A(j,4)=2*A(j,3);
A(j,3)=A(j,2);
A(j,2)=A(j,1);
A(j,1)=0;
end
if A(j,3)==A(j,2)
A(j,3)=2*A(j,2);
A(j,2)=A(j,1);
A(j,1)=0;
end
if A(j,2)==A(j,1)
A(j,2)=2*A(j,1);
A(j,1)=0;
end
end
a4=rand;
if a4>0.666666
b4=4;
else
b4=2;
end
while 2>1
x5=round(3*rand+1);
x6=round(3*rand+1);
if A(x5,x6)==0
break
end
if find(A)==16
break
end
end
if find(A)~=16
A(x5,x6)=b4;
end
end
if S==4
for j=1:4
if A(j,3)==0
A(j,3)=A(j,4);
A(j,4)=0;
end
if A(j,2)==0
A(j,2)=A(j,3);
A(j,3)=A(j,4);
A(j,4)=0;
end
if A(j,1)==0
A(j,1)=A(j,2);
A(j,2)=A(j,3);
A(j,3)=A(j,4);
A(j,4)=0;
end
end
for j=1:4
if A(j,1)==A(j,2)
A(j,1)=2*A(j,2);
A(j,2)=A(j,3);
A(j,3)=A(j,4);
A(j,4)=0;
end
if A(j,2)==A(j,3)
A(j,2)=2*A(j,3);
A(j,3)=A(j,4);
A(j,4)=0;
end
if A(j,3)==A(j,4)
A(j,3)=2*A(j,4);
A(j,4)=0;
end
end
a5=rand;
if a5>0.666666
b5=4;
else
b5=2;
end
while 2>1
x7=round(3*rand+1);
x8=round(3*rand+1);
if A(x7,x8)==0
break
end
if find(A)==16
break
end
end
if find(A)~=16
A(x7,x8)=b5;
end
end
disp(A)
end