goship/ship.go
2024-06-17 22:34:04 +02:00

79 lines
1.3 KiB
Go

package main
type ship struct {
name string
shape uint64
board *board
owner *client
x uint8
y uint8
rotation uint8
}
func (ship *ship) nextSquare() bool {
var target uint8 = 8
if ship.rotation%2 == 0 {
target = 0
if ship.x == 0 && ship.y == 0 {
ship.x = 8
ship.y = 8
}
}
if ship.y == target {
return true //stop
}
if ship.x == target {
ship.x = 0
}
return false
}
func (ship *ship) placeShip() {
var row uint8 = 0
var col uint8 = 0
for {
// Calculate the bit position (0 to 63)
bitPos := (7-row)*8 + (7 - col)
// Extract the bit value
bit := (ship.shape>>bitPos)&1 == 1
if bit {
square := &ship.board.matrix[row][col]
square.ship = ship
square.status = 2
}
if ship.nextSquare() {
break
}
}
}
func (ship *ship) removeShip() {
var row uint8 = 0
var col uint8 = 0
for {
bitPos := (7-row)*8 + (7 - col)
bit := (ship.shape>>bitPos)&1 == 1
if bit {
square := &ship.board.matrix[row][col]
if square.status == 2 {
square.status = 0
square.ship = nil
}
}
if ship.nextSquare() {
break
}
}
}
func newShip(name string, shape uint64, rotation uint8, owner *client) *ship {
this := new(ship)
this.name = name
this.shape = shape
this.owner = owner
this.board = owner.board
this.rotation = rotation
this.placeShip()
return this
}