samedi 21 août 2021

R: Error: unexpected '}' in "}" when executing if statement nested inside while loop

Good morning,

I'm looking for help with the script below.

The output and error I get in R is:

> }
Error: unexpected '}' in "}"

The aim of the script is to simulate a game situation where worn armour has a 50% chance of blocking all damage. This is to figure out how many hits of 50 damage a player with 1000 hitpoints can take to reach 0 hitpoints.

I've nested an if-else loop inside a while loop.

I've attempted to simulate the 50% change of damage block with the sample() function.

I've included counters inside the loop that count how many times the player takes damage, how many times they don't take damage, and the total number of turns it takes for the player to reach 0 hitpoints.

Code below:

hp = 1000 # hitpoints
dmg = 50 # damage
i = 0 # turn counter
nd = 0 # no damage taken counter
d = 0 # damage taken counter

k <- sample(c(1:2), size = 1, replace = TRUE, prob=c(.50,.50))
# k is a random selected number between 1 and 2
# k = 1 means damage taken
# k = 2 means no damage taken

while (hp != 0){
  if (k = 1){
    hp = hp - dmg
    d = d + 1
  } else {
    nd = nd + 1
  }
  i = i + 1
  k <- sample(c(1:2), size = 1, replace = TRUE, prob=c(.50,.50))
}

Aucun commentaire:

Enregistrer un commentaire