| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105 |
- const std = @import("std");
- const shapeModule = @import("shape.zig");
- const Shape = shapeModule.Shape;
- const kShapeSize = shapeModule.kShapeSize;
- pub const Area = struct {
- rows: u8 = 0,
- cols: u8 = 0,
- data: []u8 = undefined,
- dataAllocator: std.mem.Allocator,
- pub fn init(allocator: std.mem.Allocator, rows: u8, cols: u8) !Area {
- var area: Area = .{
- .rows = rows,
- .cols = cols,
- .data = try allocator.alloc(u8, rows*cols),
- .dataAllocator = allocator,
- };
- for (0 .. area.data.len) |i| {
- area.data[i] = '.';
- }
- return area;
- }
- pub fn deinit(self: *const Area) void {
- self.dataAllocator.free(self.data);
- }
- pub fn copy(self: *const Area, allocator: std.mem.Allocator) !Area {
- const area: Area = .{
- .rows = self.rows,
- .cols = self.cols,
- .data = try allocator.alloc(u8, self.rows*self.cols),
- .dataAllocator = allocator,
- };
- std.mem.copyForwards(u8, area.data, self.data);
- return area;
- }
- pub fn totalFreeSize(self: *const Area) usize {
- var freeSize:usize = 0;
- for (self.data) |d| {
- if (d == '.') {
- freeSize += 1;
- }
- }
- return freeSize;
- }
- pub fn getCell(self: *const Area, row: u8, col: u8) u8 {
- return self.data[row*self.cols + col];
- }
- pub fn setCell(self: *Area, row: u8, col: u8, cell: u8) void {
- self.data[row*self.cols + col] = cell;
- }
- pub fn print(self: *const Area, allocator: std.mem.Allocator) !void {
- for (0..self.rows) |row| {
- for (0..self.cols) |col| {
- const cell = self.getCell(@intCast(row), @intCast(col));
- try std.fs.File.stdout().writeAll(
- try std.fmt.allocPrint(allocator, "{c}", .{cell}));
-
- }
- try std.fs.File.stdout().writeAll("\n");
- }
- }
- pub fn appendShape(self: * const Area, allocator: std.mem.Allocator,
- shape: *const Shape, row: u8, col: u8, shapeSymbol: u8) !?Area {
- var area = try self.copy(allocator);
- for (0..kShapeSize) |shapeRow| {
- for (0..kShapeSize) |shapeCol| {
- if (shape.getCell(@intCast(shapeRow), @intCast(shapeCol)) == '.') {
- continue;
- }
- const areaRow:u8 = @intCast(shapeRow + row);
- if (areaRow >= area.rows) {
- area.deinit();
- return null;
- }
- const areaCol:u8 = @intCast(shapeCol + col);
- if (areaCol >= area.cols) {
- area.deinit();
- return null;
- }
- if (area.getCell(areaRow, areaCol) != '.') {
- area.deinit();
- return null;
- }
- area.setCell(areaRow, areaCol, shapeSymbol);
- }
- }
- return area;
- }
- };
|