robot-update.lua 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. local function intFromPort(gate, port, len)
  2. local v = 0
  3. for i = 1, len do
  4. v = v + Gate.getportstate(gate, port+i-1)*math.pow(2, i-1)
  5. end
  6. return v
  7. end
  8. local function rotateVector(vec, rot)
  9. if rot==0 then return { vec[1], vec[2], vec[3]}
  10. elseif rot==1 then return { vec[2], -vec[1], vec[3]}
  11. elseif rot==2 then return {-vec[1], -vec[2], vec[3]}
  12. elseif rot==3 then return {-vec[2], vec[1], vec[3]}
  13. else error("invalid rot "..rot) end
  14. end
  15. return function(gate)
  16. if not gate.waiting then
  17. local action = ""
  18. if Gate.getportstate(gate, 7)~=0 then -- remove brick
  19. action = action.."R\t"
  20. end
  21. if Gate.getportstate(gate, 8)~=0 then -- plant brick
  22. local color = intFromPort(gate, 1, 6)
  23. local colorfx = 0
  24. local shapefx = 0
  25. local ray = 1
  26. local col = 1
  27. local ren = 1
  28. action = action.."P "..color.." "..colorfx.." "..shapefx.." "..ray.." "..col.." "..ren.."\t"
  29. end
  30. if Gate.getportstate(gate, 22)~=0 then -- detect brick
  31. action = action.."D\t"
  32. end
  33. local movePos = {0, 0, 0}
  34. if Gate.getportstate(gate, 9)~=0 then movePos[3] = movePos[3]-0.2 end -- down
  35. if Gate.getportstate(gate, 10)~=0 then movePos[3] = movePos[3]+0.2 end -- up
  36. if Gate.getportstate(gate, 11)~=0 then movePos[1] = movePos[1]+0.5 end -- right
  37. if Gate.getportstate(gate, 12)~=0 then movePos[1] = movePos[1]-0.5 end -- left
  38. if Gate.getportstate(gate, 13)~=0 then movePos[2] = movePos[2]-0.5 end -- back
  39. if Gate.getportstate(gate, 14)~=0 then movePos[2] = movePos[2]+0.5 end -- forward
  40. local moveRotation = 0
  41. --if Gate.getportstate(gate, 13)~=0 then moveRotation = moveRotation+1 end -- right
  42. --if Gate.getportstate(gate, 14)~=0 then moveRotation = moveRotation-1 end -- left
  43. gate.robotdir = (gate.robotdir + moveRotation)%4
  44. if movePos[1]~=0 or movePos[2]~=0 or movePos[3]~=0 or moveRotation~=0 then
  45. movePos = rotateVector(movePos, gate.robotdir)
  46. gate.robotpos = { gate.robotpos[1]+movePos[1], gate.robotpos[2]+movePos[2], gate.robotpos[3]+movePos[3] }
  47. action = action.."M "..gate.robotpos[1].." "..gate.robotpos[2].." "..gate.robotpos[3].." "..gate.robotdir.."\t"
  48. end
  49. if action~="" then
  50. Gate.cb(gate, action:sub(1, #action-1))
  51. gate.waiting = true
  52. end
  53. end
  54. end