packages feed

spade-0.1.0.3: samples/snake.spd

graphicswindow(900, 900, true)
let headPos = { x : 100, y : 100}
let segmentCount = 5
let segments = makeSnake(headPos, segmentCount)
let snake =
 { segments: segments
 , direction : "right"
 }
let food = {x : random(0, 900), y : random(0, 900)}
loop
setcolor(0, 0, 0)
clearscreen()
setcolor(255, 0, 0)
drawSnake(snake)
drawfood(food)
let headpos = head(snake.segments)
if (haseaten(headpos, food))
  then let snake = growsnake(snake)
  let food = {x : random(0, 900), y: random(0, 900) }
endif
drawscreen()
let keys = getkeystate()
if inkeystate(keys, scancodes.q) then break endif
if inkeystate(keys, scancodes.down) then
 let snake.direction = "down"
endif
if inkeystate(keys, scancodes.up) then
 let snake.direction = "up"
endif
if inkeystate(keys, scancodes.left) then
 let snake.direction = "left"
endif
if inkeystate(keys, scancodes.right) then
 let snake.direction = "right"
endif
let snake = moveSnake(snake)
wait(0.02)
endloop

proc haseaten(headpos, food)
 let xdiff = headpos.x - food.x
 let ydiff = headpos.y - food.y
 return ((xdiff * xdiff) + (ydiff * ydiff)) < 100
endproc

proc moveSnake(snake)
  let nextHeadPos = snake.segments[1]
  let snakeLength = size(snake.segments)
  if snake.direction == "right" then
    let nextHeadPos.x = nextHeadPos.x + 8
  endif
  if snake.direction == "left" then
    let nextHeadPos.x = nextHeadPos.x - 8
  endif
  if snake.direction == "up" then
    let nextHeadPos.y = nextHeadPos.y - 8
  endif
  if snake.direction == "down" then
    let nextHeadPos.y = nextHeadPos.y + 8
  endif
  let snake.segments = [nextHeadPos] + take(snake.segments, snakeLength - 1)
  return snake
endproc

proc makeSnake(headPos, segmentCount)
 let segments = [headPos]
 for i = 1 to segmentCount
   let segments = segments + [{x : headPos.x - i*10, y: headPos.y}]
 endfor
 return segments
endproc

proc drawfood(food)
 setcolor(0, 200, 0)
 box(food.x, food.y, 8, 8)
endproc

proc growsnake(snake)
 let snake.segments = insertleft(head(moveSnake(snake).segments), snake.segments)
 return snake
endproc

proc drawSnake(snake)
 let segmentCount = size(snake.segments)
 for i = 1 to segmentCount
 box(snake.segments[i].x, snake.segments[i].y, 8, 8)
 endfor
endproc