In this example I am given the task to change the color of the head. The head is said that the code ypos also seen beneath associates with snake's head that needs to be changed yellow. Does anyone have an idea how I can do that?
plotGrid <- function(N=30, border = "white", col = "light green") {
par(mar=c(1,1,1,1))
plot(0, 0, type="n", xlim = c(0, N), ylim = c(0, N), axes = FALSE,
xlab = "", ylab = "", asp = 1)
for (i in 1:N) {
ystart <- (i-1)
yend <- i
rect(0:(N-1), ystart, 1:N, yend, border = border, col= col)
}
}
plotSnake <- function(snake, border = "black", col = "red") {
for (i in 1:nrow(snake)) {
xstart <- snake$xpos[i]-1
xend <- snake$xpos[i]
ystart <- snake$ypos[i]-1
yend <- snake$ypos[i]
rect(xstart, ystart, xend, yend, border = border, col = col)
}
}
snake <- as.data.frame(matrix(0,10,2))
names(snake) <- c("xpos","ypos")
snake$xpos <- 11:20
snake$ypos <- rep(15,10)
plotGrid()
plotSnake(snake)
CodePudding user response:
How about this:
plotSnake <- function(snake, border = "black", col = "red") {
xstart <- snake$xpos[1]-1
xend <- snake$xpos[1]
ystart <- snake$ypos[1]-1
yend <- snake$ypos[1]
rect(xstart, ystart, xend, yend, border = border, col = "yellow")
if (nrow(snake) > 1)
{
for (i in 2:nrow(snake)) {
xstart <- snake$xpos[i]-1
xend <- snake$xpos[i]
ystart <- snake$ypos[i]-1
yend <- snake$ypos[i]
rect(xstart, ystart, xend, yend, border = border, col = col)
}
}
}