Browse Source

implement viewport

Harry de Boer 10 năm trước cách đây
mục cha
commit
a397dcd7d5
1 tập tin đã thay đổi với 17 bổ sung19 xóa
  1. 17 19
      board/board.go

+ 17 - 19
board/board.go

@@ -5,7 +5,6 @@ import (
 	"encoding/json"
 	"fmt"
 	"io"
-	"log"
 	"math/rand"
 )
 
@@ -61,8 +60,21 @@ type jsonTile struct {
 }
 
 func (b Board) WriteJSON(w io.Writer, startCol, startRow, cols, rows int) {
-	fmt.Fprintf(w, "{x=\"%v\",y=\"%v\",rows=\"%v\",columns=\"%v\",tiles={", startCol, startRow, cols, rows)
+	sc, sr, cols, rows := sanitizeViewPort(b, startCol, startRow, cols, rows)
 
+	for y := startRow; y < sr+rows; y++ {
+		for x := startCol; x < sc+cols; x++ {
+			t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
+			bs, _ := json.Marshal(t)
+			w.Write(bs)
+			w.Write([]byte{','})
+		}
+	}
+
+	fmt.Fprintf(w, "}}")
+}
+
+func sanitizeViewPort(b Board, startCol, startRow, cols, rows int) (int, int, int, int) {
 	if startCol > b.Cols {
 		startCol = b.Cols
 	}
@@ -77,13 +89,11 @@ func (b Board) WriteJSON(w io.Writer, startCol, startRow, cols, rows int) {
 		rows += startRow
 		startRow = 0
 	}
-	log.Printf("startCol: %v", startCol)
 	if startCol+cols > b.Cols {
 		cols = b.Cols - startCol
 	}
-	log.Printf("startRow: %v", startRow)
-	if startRow+rows > b.Cols {
-		rows = b.Cols - startRow
+	if startRow+rows > b.Rows {
+		rows = b.Rows - startRow
 	}
 	if cols < 0 {
 		cols = 0
@@ -91,19 +101,7 @@ func (b Board) WriteJSON(w io.Writer, startCol, startRow, cols, rows int) {
 	if rows < 0 {
 		rows = 0
 	}
-
-	log.Printf("x=%v, y=%v, cols=%v, rows=%v \n", startCol, startRow, cols, rows)
-
-	for y := startRow; y < startRow+rows; y++ {
-		for x := startCol; x < startCol+cols; x++ {
-			t := &jsonTile{x, y, b.Get(x, y).Name(), ""}
-			bs, _ := json.Marshal(t)
-			w.Write(bs)
-			w.Write([]byte{','})
-		}
-	}
-
-	fmt.Fprintf(w, "}}")
+	return startCol, startRow, cols, rows
 }
 
 func (b Board) randomizeTile(x, y int) {