mercredi 1 juillet 2020

Repeat if statement depending on random number R

I am trying to place a vector within a matrix depending on the values within the matrix for a Battleship game. So if there is already a ship placed I assign a vector of '1' for the length of the ship. I want that the newly placed ship (vector) does not touch or overlap previous ships. I therefore thought to check if the area where i want to set my new ship has not been assigned a '1' to. To randomly place the ship I choose random numbers for x and y. How can I built a loop that repeats the process of trying to place the ship until it is possible? That is, it should repeat choosing random numbers until the vector is not placed on a cell in the matrix with the value '1'. That is the start so far, but I do not know how to continue. 'area' is the matrix, 'xbegin' and 'ybegin' are the first randomly chosen x and y values from where the vector (here n4 for the length of 4 of the ship) starts.

  if(direction=="vertical"){
  xbegin<- sample(1:10, 1)
  ybegin<-sample(1:7,1)
  if(area[ybegin:(ybegin+3),xbegin]!=1){
    area[ybegin:(ybegin+3),xbegin]=n4}else{....repeat if n4 overlaps...
    }
  }

Aucun commentaire:

Enregistrer un commentaire