rowboz/robots/robots.go

154 lines
2.6 KiB
Go
Raw Permalink Normal View History

package robots
func (game *Game) initRobots() {
var fabricate int = game.level * 16
for i := 0; i < fabricate; i++ {
2024-01-08 11:12:13 +01:00
var robot Robot
robot.id = i
robot.comms = make(chan Position)
var found bool
var rndPos Position
for !found {
rndPos = game.randPos()
if !game.onPlayer(rndPos) {
found = true
}
}
2024-01-08 11:12:13 +01:00
robot.position = rndPos
game.robots = append(game.robots, robot)
go game.Robot(robot)
}
}
func (game *Game) drawRobots() {
for _, r := range game.robots {
game.screen.SetContent(r.position.x, r.position.y, '+', nil, game.style)
}
}
func (game *Game) moveRobots() {
2024-01-08 11:12:13 +01:00
var robotPos Position
2024-01-08 11:12:13 +01:00
// Iterate through the robots
for i, _ := range game.robots {
game.robots[i].comms <- game.player.position
robotPos = <-game.robots[i].comms
game.robots[i].position = robotPos
}
// After all the moves, lets check if any of the rowboz collided with anything
for _, r := range game.robots {
// Hit a player? Game over!
if game.onPlayer(r.position) {
game.gameover = 1
return
}
// Robots mingling? Trash!
if game.onRobot(r) {
// Delete robot
game.deleteRobot(r)
// Create trash
game.addTrash(r)
}
// Hugging Trash? More trash!
if game.onTrash(r.position) {
// Delete robot
game.deleteRobot(r)
}
}
}
func (game *Game) onRobot(robot Robot) bool {
var found bool = false
for _, r := range game.robots {
if robot.id != r.id && robot.position == r.position {
found = true
}
}
return found
}
func (game *Game) deleteRobot(robot Robot) {
var rowboz []Robot
2024-01-08 11:12:13 +01:00
// Delete from Array
for _, r := range game.robots {
2024-01-08 11:12:13 +01:00
if robot.id != r.id {
rowboz = append(rowboz, r)
}
}
game.robots = nil
game.robots = rowboz
2024-01-08 11:12:13 +01:00
// Close the channel
close(robot.comms)
game.player.score++
}
2024-01-08 11:12:13 +01:00
func (game *Game) Robot(robot Robot) {
var player Position
var robotPos Position = robot.position
var emptyPos Position
for {
// Wait for input from the channel
player = <-robot.comms
if player == emptyPos {
close(robot.comms)
return
}
//fmt.Println(player, robotPos)
// Determine direction to move in
robotPos = game.moveRobot(player, robot.position)
robot.position = robotPos
// Return new position of robot
robot.comms <- robotPos
}
}
func (game *Game) moveRobot(player Position, robot Position) Position {
var newPosition Position
// Determine in which direction to go
if player.x < robot.x {
newPosition.x = robot.x - 1
} else if player.x > robot.x {
newPosition.x = robot.x + 1
}
if player.y < robot.y {
newPosition.y = robot.y - 1
} else if player.y > robot.y {
newPosition.y = robot.y + 1
}
//fmt.Println(player, robot, newPosition)
return newPosition
}