From 40257e354d054c0a007adb7139a031ca7cb941fa Mon Sep 17 00:00:00 2001 From: Julien Dessaux Date: Fri, 1 Oct 2021 19:06:33 +0200 Subject: Continued implementing the funge space field --- src/field.nim | 140 +++++++++++++++++++++++++++++++++++++++++++++++++--------- 1 file changed, 119 insertions(+), 21 deletions(-) (limited to 'src') diff --git a/src/field.nim b/src/field.nim index a9d26fc..224e21d 100644 --- a/src/field.nim +++ b/src/field.nim @@ -1,37 +1,135 @@ type - Line = ref object + Line = object x, l: int columns: seq[int] - Field* = ref object + Field* = object x, y: int lx, ly: int lines: seq[Line] +proc blank*(f: var Field, x, y: int) = + if y < f.y or y >= f.y+f.ly: # outside the field + return + var l = addr f.lines[y-f.y] + if x < l.x or x >= l.x+l.l: # outside the field + return + if x > l.x and x < l.x+l.l-1: # just set the value + l.columns[x-l.x] = int(' ') + return + if l.l == 1: # this was the last character on the line + if y == f.y: # we need to trim the leading lines + var i = 1 + while f.lines[i].l == 0: + inc i + f.y += i + f.lines = f.lines[i.. f.lines[i].x: + f.x = f.lines[i].x + if x2 < f.lines[i].x + f.lines[i].l: + x2 = f.lines[i].x + f.lines[i].l + f.lx = x2-f.x + proc get*(f: Field, x, y: int): int = - if y >= f.y and y < f.y + f.ly: + if y >= f.y and y < f.y+f.ly: let l = f.lines[y-f.y] - if x >= l.x and x < l.x + l.l: + if x >= l.x and x < l.x+l.l: return l.columns[x-l.x] return int(' ') proc isIn*(f: Field, x, y: int): bool = return x >= f.x and y >= f.y and x < f.x+f.lx and y < f.y+f.ly -when defined(unitTesting): - let minimal = Field( - x: 0, - y: 0, - lx: 1, - ly: 1, - lines: @[ - Line(x: 0, l: 1, columns: @[int('@')]) - ] - ) - suite "Field": - test "Field.get": - check minimal.get(0,0) == int('@') - check minimal.get(1,0) == int(' ') - test "Field.isIn": - check minimal.isIn(0, 0) == true - check minimal.isIn(1, 0) == false +proc set*(f: var Field, x, y, v: int) = + if v == int(' '): + f.blank(x, y) + elif y >= f.y: + if y < f.y+f.ly: # the line exists + var l = addr f.lines[y-f.y] + if l.l == 0: # An empty line is a special case + l.x = x + l.l = 1 + l.columns = @[v] + if f.x > x: + f.lx = f.lx+f.x-x + f.x = x + if f.lx < x-f.x+1: + f.lx = x-f.x+1 + elif x >= l.x: + if x < l.x+l.l: # just set the value + l.columns[x-l.x] = v + else: # append columns + let newL = x-l.x+1 + l.columns.setlen(newL) + for i in l.l.. x: + f.lx = f.lx + f.x - x + f.x = x + else: # append lines + f.ly = y-f.y+1 + f.lines.setlen(f.ly) + f.lines[f.ly-1] = Line(x: x, l: 1, columns: @[v]) + if f.x > x: + f.lx = f.lx + f.x - x + f.x = x + if f.lx < x-f.x+1: + f.lx = x-f.x+1 + else: # prepend lines + let newLy = f.ly+f.y-y + var newlines = newSeq[Line](newLy) + newlines[0] = Line(x: x, l: 1, columns: @[v]) + for i in f.y-y.. x: + f.lx = f.lx+f.x-x + f.x = x + if f.lx < x-f.x+1: + f.lx = x-f.x+1 -- cgit v1.2.3