From cf1fe76a4fc95b45f127b0f4759594eb5de24ed5 Mon Sep 17 00:00:00 2001 From: VedVid Date: Fri, 16 Nov 2018 01:09:58 +0100 Subject: [PATCH] removing element from slice of pointers is not trivial; now picking up works well, but game crashes while rendering --- controls.go | 6 ++++-- monsters.go | 15 ++++++++------- 2 files changed, 12 insertions(+), 9 deletions(-) diff --git a/controls.go b/controls.go index 0fc88c5..186a119 100644 --- a/controls.go +++ b/controls.go @@ -20,7 +20,9 @@ freely, subject to the following restrictions: package main -import blt "bearlibterminal" +import ( + blt "bearlibterminal" +) func Controls(k int, p *Creature, b Board, c Creatures, o Objects) bool { /* Function Controls is input handler. @@ -41,7 +43,7 @@ func Controls(k int, p *Creature, b Board, c Creatures, o Objects) bool { turnSpent = p.MoveOrAttack(-1, 0, b, c) case blt.TK_G: - turnSpent = p.PickUp(o) + turnSpent = p.PickUp(&o) } return turnSpent } diff --git a/monsters.go b/monsters.go index 9d64400..f6b8323 100644 --- a/monsters.go +++ b/monsters.go @@ -139,7 +139,7 @@ func (c *Creature) Move(tx, ty int, b Board) bool { return turnSpent } -func (c *Creature) PickUp(o Objects) bool { +func (c *Creature) PickUp(o *Objects) bool { /* PickUp is method that has *Creature as receiver and slice of *Object as argument. Creature tries to pick object up. @@ -149,12 +149,13 @@ func (c *Creature) PickUp(o Objects) bool { Picking objects up takes turn only if it's successful attempt. */ turnSpent := false - for i, v := range o { - if v.X == c.X && v.Y == c.Y && v.Pickable == true { - item := o[i] - c.Inventory = append(c.Inventory, item) - o[i] = o[len(o)-1] // Doesn't it leaks a memory? \/ - o = o[:len(o)-1] // It's slice of pointers to struct. + obj := *o + for i := 0; i <= len(obj); i++ { + if obj[i].X == c.X && obj[i].Y == c.Y && obj[i].Pickable == true { + c.Inventory = append(c.Inventory, obj[i]) + copy(obj[i:], obj[i+1:]) + obj[len(obj)-1] = nil + *o = obj[:len(obj)-1] turnSpent = true break }