Info

Diese Frage ist geschlossen. Öffnen Sie sie erneut, um sie zu bearbeiten oder zu beantworten.

While loop repeating only 1 segment multiple times before moving on

1 Ansicht (letzte 30 Tage)
Joseph Kain
Joseph Kain am 5 Mär. 2016
Geschlossen: MATLAB Answer Bot am 20 Aug. 2021
So I am writing a code to simulate a battle between a player and a random monster. my code is as follows:
function battle
Ab=msgbox('You have encountered a');
waitfor (Ab)
MH=10;
MA=0;
PH=100;
PA=0;
Run=0
while 0< PH && MH>0
PH = PH - MA
MA= randi([1 20],1,1) -5 %use dice roll sim to determine monsters attack%
if MA > 0
Bb=msgbox(sprintf('The monster hit you for %d health points!', MA));
waitfor (Bb)
continue
else
MA=0
Bb=msgbox('____ missed!');
waitfor (Bb)
playc= questdlg('What do you do?',...
'Menu',...
'Attack the monster','Cry','Run away!', 'Attack the monster')
switch playc
case 'Attack the monster'
PA= randi([1 20],1,1)-2
if PA>0
Cb=msgbox(sprintf('You hit the monster for %d health points!', PA));
waitfor (Cb)
else
Cb=msgbox('you missed!')
end
case 'Cry'
Cb=msgbox('You feel a little better after you cry');
waitfor (Cb)
PH=PH+10
Db=msgbox('You regain 10 hit points')
waitfor (Db)
case 'Run Away!'
Eb=msgbox('Just like real life, you cannot run from your problems!')
break
end
end
MH=MH-PA
end
end
So my problem is that the monster attacks the player multiple times in a row, and only moves on when the monster misses. Then the player gets to make his choice, but then when it comes back to the monsters turn, once again he gets to attack until he misses. Any ideas?

Antworten (1)

Anup Kayande
Anup Kayande am 14 Mär. 2016
Because you programmed your monster to be so! :-P You put the player's instance of attack into monster's ELSE statement.
Why don't you try and get a random number based on which you can let either monster or the player attack. If the number is 1 player attacks and if it is 2 monster attacks.

Diese Frage ist geschlossen.

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by