Skip to content

Commit

Permalink
Fix ship collission when placing new ships
Browse files Browse the repository at this point in the history
  • Loading branch information
Scalaptia committed Mar 18, 2024
1 parent b2048f9 commit f0f5b2d
Showing 1 changed file with 12 additions and 0 deletions.
12 changes: 12 additions & 0 deletions src/components/board.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,29 +16,41 @@ export const createBoard = (width: number, height: number): Gameboard => {
this.ships.push(ship);

if (vertical) {
// Check wall collision
if (y + ship.length > this.boardGrid.length) {
this.ships.pop();
return false;
}

// Check ship collision
for (let i = 0; i < ship.length; i++) {
if (this.boardGrid[y + i][x].ship) {
this.ships.pop();
return false;
}
}

// Add ship to board
for (let i = 0; i < ship.length; i++) {
this.boardGrid[y + i][x].ship = ship;
}
} else {
// Check wall collision
if (x + ship.length > this.boardGrid[0].length) {
this.ships.pop();
return false;
}

// Check ship collision
for (let i = 0; i < ship.length; i++) {
if (this.boardGrid[y][x + i].ship) {
this.ships.pop();
return false;
}
}

// Add ship to board
for (let i = 0; i < ship.length; i++) {
this.boardGrid[y][x + i].ship = ship;
}
}
Expand Down

0 comments on commit f0f5b2d

Please sign in to comment.