eniallator

Snake

Sep 14th, 2015
317
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 2.05 KB | None | 0 0
  1. local totalX = 32
  2. local totalY = 27
  3. local grid = {}
  4. local snakeTail = {}
  5. local snakeSize = 0
  6. local snakeX = 1
  7. local snakeY = 1
  8. local output = ""
  9. local fruitIcon = "•"
  10. local snakeIcon = "@"
  11. local clock = os.clock
  12.  
  13. function makeGrid()
  14.    for x=1,totalY do
  15.       grid[x] = {}
  16.       for y=1,totalX do
  17.          grid[x][y] = " "
  18.       end
  19.    end
  20. end
  21.  
  22. function sleep(secs)
  23.    local timePoint = clock()
  24.    while clock() - timePoint <= secs do end
  25. end
  26.  
  27. while true do
  28.    fruitX = math.random(totalY)
  29.    fruitY = math.random(totalX)
  30.    snakeSize = snakeSize + 1
  31.  
  32.    while snakeX ~= fruitX or snakeY ~= fruitY do
  33.  
  34.       makeGrid()
  35.       table.insert(snakeTail,1,{snakeX,snakeY})
  36.  
  37.       while snakeSize < #snakeTail do
  38.          table.remove(snakeTail,#snakeTail)
  39.       end
  40.  
  41.       grid[snakeX][snakeY] = snakeIcon
  42.  
  43.       for k=1,#snakeTail do
  44.          grid[snakeTail[k][1]][snakeTail[k][2]] = snakeIcon
  45.       end
  46.  
  47.       if totalX < totalY then
  48.  
  49.          if snakeX > fruitX and snakeY == fruitY then
  50.             snakeX = snakeX - 1
  51.          end
  52.  
  53.          if snakeX < fruitX and snakeY == fruitY then
  54.             snakeX = snakeX + 1
  55.          end
  56.  
  57.          if snakeY > fruitY then
  58.             snakeY = snakeY - 1
  59.          end
  60.  
  61.          if snakeY < fruitY then
  62.             snakeY = snakeY + 1
  63.          end
  64.       else
  65.  
  66.          if snakeY > fruitY and snakeX == fruitX then
  67.             snakeY = snakeY - 1
  68.          end
  69.  
  70.          if snakeY < fruitY and snakeX == fruitX then
  71.             snakeY = snakeY + 1
  72.          end
  73.  
  74.          if snakeX > fruitX then
  75.             snakeX = snakeX - 1
  76.          end
  77.  
  78.          if snakeX < fruitX then
  79.             snakeX = snakeX + 1
  80.          end
  81.       end
  82.  
  83.       grid[fruitX][fruitY] = fruitIcon
  84.  
  85.       for l=1,#snakeTail do
  86.          if snakeTail[l][1] == snakeX and snakeTail[l][2] == snakeY then
  87.             snakeSize = 1
  88.          end
  89.       end
  90.  
  91.       output = ""
  92.       os.execute("cls")
  93.  
  94.       for i=1,totalY do
  95.          for j=1,totalX do
  96.             output = output .. grid[i][j]
  97.          end
  98.  
  99.          output = output .. "\n"
  100.       end
  101.       print(output)
  102.       sleep(0.3)
  103.    end
  104. end
Advertisement
Add Comment
Please, Sign In to add comment