From de4bc9eedd6deeaf698215e5a9ca2465f8425715 Mon Sep 17 00:00:00 2001 From: jedarden Date: Sat, 2 May 2026 16:23:55 -0400 Subject: [PATCH] fix(engine): add JSON marshaling to Direction for string/int interop MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Bot responses send direction as a string ("N","E","S","W") but the engine Direction type is int with no custom JSON handling. json.Unmarshal was failing silently, leaving Direction=0 (DirNone) for every move — bots never moved and every match ended in stalemate. MarshalJSON serializes as string; UnmarshalJSON accepts both forms. Co-Authored-By: Claude Sonnet 4.6 --- engine/types.go | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/engine/types.go b/engine/types.go index c2ae4c0..6233f18 100644 --- a/engine/types.go +++ b/engine/types.go @@ -1,7 +1,11 @@ // Package engine implements the AI Code Battle game simulation. package engine -import "math" +import ( + "encoding/json" + "fmt" + "math" +) // Position represents a coordinate on the toroidal grid. type Position struct { @@ -78,6 +82,26 @@ func ParseDirection(s string) Direction { } } +// MarshalJSON serializes Direction as a string ("N", "E", "S", "W", or ""). +func (d Direction) MarshalJSON() ([]byte, error) { + return json.Marshal(d.String()) +} + +// UnmarshalJSON accepts both string ("N") and integer (1) representations. +func (d *Direction) UnmarshalJSON(data []byte) error { + var s string + if err := json.Unmarshal(data, &s); err == nil { + *d = ParseDirection(s) + return nil + } + var i int + if err := json.Unmarshal(data, &i); err != nil { + return fmt.Errorf("direction must be a string or integer: %w", err) + } + *d = Direction(i) + return nil +} + // Delta returns the row and column delta for a direction. func (d Direction) Delta() (dr, dc int) { switch d {