Search code examples
rplotsamplingmarkov-chains

Moving players on chance on a soccer field in R plot


Background:

I'm trying to come up with a coding scheme such that any of my 14 players (separately; each player is shown as numbered circles below) on the center thick line of my soccer field independently moves to left by .1 (in x-axis value unit) if the result of outcome = sample(x = c(1, 2), size = 1) is 1 and if the result of outcome = sample(x = c(1, 2), size = 1) is 2, the player moves to right by .1 (in x-axis value unit).

Thus, the goal is that each player can independently move to the left or right based on the result of the outcome.

Coding Question (R code is provided below):

Do I need to write outcome[i] = sample(x = c(1, 2), size = 1) 16 times for each player and then construct something like:

outcome1 = sample(x = c(1, 2), size = 1)
outcome2 = sample(x = c(1, 2), size = 1)
#.
#.
#.

and then change the x of that player based on his outcome:

if(outcome1 == 1) {  points(x - .1, y, cex = 4.5, lwd = 3, pch = 21, bg = 0)  
  } else { points(x + .1, y, cex = 4.5, lwd = 3, pch = 21, bg = 0)  }

Or there is a better way?

enter image description here

enter image description here

Here is my R code:

plot(1, ty = "n", ann = F, cex = 3)

par = par('usr')
rect(par[1], par[3], par[2], par[4], col = 'darkseagreen1' )

points( 1, 1, cex = 5, pch =20, col = 0)
points( 1, 1, cex = 33, lwd = 5, col = 0)
abline(v = 1, lwd = 10, col = 0)

rect(.6, .6, 1.4, 1.4, lwd = 5, border = 0)
rect(0, .85, .65, 1.15, lwd = 5, col = 'darkseagreen1', border = 0)
rect(1.35, .85, 1.45, 1.15, lwd = 5, col = 'darkseagreen1', border = 0)
box()

x = rep(1, 14); y = seq(.6, 1.4, len = 14)
points(x, y, cex = 4.5, lwd = 3, pch = 21, bg = 0)
text(x, y, 1:14, font = 2)

Solution

  • You could first sample all the moves for each player and store that in a matrix (rows are the players, columns are the time steps):

    nSteps <- 16
    nPlayers <- 14
    
    ## Sample movement of players:
    xStepsMx <- matrix(sample(c(-1,1)*0.1, nPlayers*nSteps, replace = TRUE),
            nrow = nPlayers, ncol = nSteps)
    

    You can then evaluate the position of each player at each time step:

    ## Position of players:
    xPosMx <- t(sapply(1:nrow(xStepsMx), function(ii) cumsum(xStepsMx[ii,]))) + x 
    

    For each time step timeStep in 1,2,...,16 you can then e.g. plot your players' position using

    timeStep <- 5    
    points(xPosMx[,timeStep], y, cex = 4.5, lwd = 3, pch = 21, bg = "white")
    text(xPosMx[,timeStep], y, 1:14, font = 2)