Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Change head color: Simple Snake Game

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?

enter image description here

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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)
        }
      }
    }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading