fix(engine): add JSON marshaling to Direction for string/int interop

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 <noreply@anthropic.com>
This commit is contained in:
jedarden 2026-05-02 16:23:55 -04:00
parent 9b16b32aef
commit de4bc9eedd

View file

@ -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 {