area.zig 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. const std = @import("std");
  2. const shapeModule = @import("shape.zig");
  3. const Shape = shapeModule.Shape;
  4. const kShapeSize = shapeModule.kShapeSize;
  5. pub const Area = struct {
  6. rows: u8 = 0,
  7. cols: u8 = 0,
  8. data: []u8 = undefined,
  9. dataAllocator: std.mem.Allocator,
  10. pub fn init(allocator: std.mem.Allocator, rows: u8, cols: u8) !Area {
  11. var area: Area = .{
  12. .rows = rows,
  13. .cols = cols,
  14. .data = try allocator.alloc(u8, rows*cols),
  15. .dataAllocator = allocator,
  16. };
  17. for (0 .. area.data.len) |i| {
  18. area.data[i] = '.';
  19. }
  20. return area;
  21. }
  22. pub fn deinit(self: *const Area) void {
  23. self.dataAllocator.free(self.data);
  24. }
  25. pub fn copy(self: *const Area, allocator: std.mem.Allocator) !Area {
  26. const area: Area = .{
  27. .rows = self.rows,
  28. .cols = self.cols,
  29. .data = try allocator.alloc(u8, self.rows*self.cols),
  30. .dataAllocator = allocator,
  31. };
  32. std.mem.copyForwards(u8, area.data, self.data);
  33. return area;
  34. }
  35. pub fn totalFreeSize(self: *const Area) usize {
  36. var freeSize:usize = 0;
  37. for (self.data) |d| {
  38. if (d == '.') {
  39. freeSize += 1;
  40. }
  41. }
  42. return freeSize;
  43. }
  44. pub fn getCell(self: *const Area, row: u8, col: u8) u8 {
  45. return self.data[row*self.cols + col];
  46. }
  47. pub fn setCell(self: *Area, row: u8, col: u8, cell: u8) void {
  48. self.data[row*self.cols + col] = cell;
  49. }
  50. pub fn print(self: *const Area, allocator: std.mem.Allocator) !void {
  51. for (0..self.rows) |row| {
  52. for (0..self.cols) |col| {
  53. const cell = self.getCell(@intCast(row), @intCast(col));
  54. try std.fs.File.stdout().writeAll(
  55. try std.fmt.allocPrint(allocator, "{c}", .{cell}));
  56. }
  57. try std.fs.File.stdout().writeAll("\n");
  58. }
  59. }
  60. pub fn appendShape(self: * const Area, allocator: std.mem.Allocator,
  61. shape: *const Shape, row: u8, col: u8, shapeSymbol: u8) !?Area {
  62. var area = try self.copy(allocator);
  63. for (0..kShapeSize) |shapeRow| {
  64. for (0..kShapeSize) |shapeCol| {
  65. if (shape.getCell(@intCast(shapeRow), @intCast(shapeCol)) == '.') {
  66. continue;
  67. }
  68. const areaRow:u8 = @intCast(shapeRow + row);
  69. if (areaRow >= area.rows) {
  70. area.deinit();
  71. return null;
  72. }
  73. const areaCol:u8 = @intCast(shapeCol + col);
  74. if (areaCol >= area.cols) {
  75. area.deinit();
  76. return null;
  77. }
  78. if (area.getCell(areaRow, areaCol) != '.') {
  79. area.deinit();
  80. return null;
  81. }
  82. area.setCell(areaRow, areaCol, shapeSymbol);
  83. }
  84. }
  85. return area;
  86. }
  87. };