Turtle.sf 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/ruby
  2. require('Image::Magick')
  3. class Turtle(
  4. x = 500,
  5. y = 500,
  6. angle = 0,
  7. scale = 1,
  8. mirror = 1,
  9. xoff = 0,
  10. yoff = 0,
  11. color = 'black',
  12. ) {
  13. has im = %O<Image::Magick>.new(size => "#{x}x#{y}")
  14. method init {
  15. angle.deg2rad!
  16. im.ReadImage('canvas:white')
  17. }
  18. method forward(r) {
  19. var (newx, newy) = (x + r*sin(angle), y + r*-cos(angle))
  20. im.Draw(
  21. primitive => 'line',
  22. points => join(' ',
  23. round(x * scale + xoff),
  24. round(y * scale + yoff),
  25. round(newx * scale + xoff),
  26. round(newy * scale + yoff),
  27. ),
  28. stroke => color,
  29. strokewidth => 1,
  30. )
  31. (x, y) = (newx, newy)
  32. }
  33. method save_as(filename) {
  34. im.Write(filename)
  35. }
  36. method turn(theta) {
  37. angle += theta*mirror
  38. }
  39. method state {
  40. [x, y, angle, mirror]
  41. }
  42. method setstate(state) {
  43. (x, y, angle, mirror) = state...
  44. }
  45. method mirror {
  46. mirror.neg!
  47. }
  48. }