main.wren 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. import "random" for Random
  2. class GrayscaleImage {
  3. construct new(width, height, depth) {
  4. _width = width
  5. _height = height
  6. _depth = depth
  7. _image = []
  8. for (y in 0...height) {
  9. _image.add(List.filled(width, 0))
  10. }
  11. }
  12. pixel(x, y, shade) {
  13. _image[y][x] = shade
  14. }
  15. // «rectangle»
  16. rectangle(x, y, width, height, shade) {
  17. // the two horizontal lines
  18. for (dx in 0..width) {
  19. pixel(x + dx, y, shade)
  20. pixel(x + dx, y + height, shade)
  21. }
  22. // the two vertical lines
  23. for (dy in 0..height) {
  24. pixel(x, y + dy, shade)
  25. pixel(x + width, y + dy, shade)
  26. }
  27. }
  28. // «end»
  29. showPGM() {
  30. System.print("P2") // the PGM header
  31. System.print("%(_width) %(_height)")
  32. System.print(_depth) // the maximum value which will appear
  33. for (y in 0..._height) {
  34. for (x in 0..._width) {
  35. System.write("%(_image[y][x]) ")
  36. }
  37. System.print()
  38. }
  39. }
  40. }
  41. var rand = Random.new()
  42. var width = 24
  43. var height = 24
  44. var depth = 8
  45. // «main»
  46. var image = GrayscaleImage.new(width, height, depth)
  47. // create up to 6 rectancles
  48. for (i in 0..rand.int(3, 6)) {
  49. // choose the color from the depth
  50. var color = rand.int(2, 8)
  51. // choose top-left point randomly
  52. var x = rand.int(0, width-3)
  53. var y = rand.int(0, height-3)
  54. // choose width and height from remaining
  55. var w = rand.int(x+2, width) - x
  56. var h = rand.int(y+2, height) - y
  57. // draw the rectangle
  58. image.rectangle(x, y, w, h, color)
  59. }
  60. image.showPGM()
  61. // «end»