npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

react-battleships-engine

v0.1.2

Published

A TypeScript-based Battleship game engine for React, featuring ship placement, attack handling, and game logic management.

Downloads

21

Readme

React Battleship Engine

This package provides a TypeScript engine for the classic Battleship game, adapted for React using a custom hook, useGameBoard. The hook manages the game logic, including ship placement, tracking hits, and checking for victory conditions.

Based on the original battleships-engine.

Installation

Install the package with npm or yarn:

npm install react-battleships-engine

or

pnpm add react-battleships-engine

or

yarn add react-battleships-engine

Usage

Importing the Hook

You can import the useGameBoard hook and necessary types from the package:

import { useGameBoard, TCoords, ShipType, Direction  } from "react-battleships-engine";

Example

Using the Hook in a React Component

You can use the useGameBoard hook to initialize a game board, place ships, and handle player actions.

import React, { useEffect } from "react";
import { useGameBoard } from "react-battleships-engine";

const BattleshipGame: React.FC = () => {
    const {
        ships,
        placeShip,
        randomlyPlaceShips,
        receiveAttack,
        hasLost,
        missed,
    } = useGameBoard();

    // Example: Place ships randomly when the game starts
    useEffect(() => {
        randomlyPlaceShips();
    }, []);

    // Example: Handle a player attack
    const handleAttack = (coords: { x: number, y: number }) => {
        try {
            receiveAttack(coords);
        } catch (error) {
            console.error(error.message);
        }
    };

    return (
        <div>
            <h1>Battleship Game</h1>
            <button onClick={() => randomlyPlaceShips()}>
                Randomly Place Ships
            </button>
            <button onClick={() => handleAttack({ x: 3, y: 5 })}>
                Attack (3, 5)
            </button>
            {hasLost() && <p>You lost!</p>}
        </div>
    );
};

export default BattleshipGame;

Available Hook Methods

useGameBoard(initialShips?: Ship[])

The useGameBoard hook manages the game board state and logic. It returns a set of methods and state for interacting with the board.

  • placeShip(params: { type: ShipType; coords: TCoords; direction: Direction }): Manually place a ship on the board at specific coordinates.
  • randomlyPlaceShips(): Randomly place all ships on the game board.
  • receiveAttack(coords: TCoords): Process an attack at the specified coordinates.
  • hasLost(): Returns true if all ships are sunk.
  • resetGameBoard(): Resets the board and state for a new game.

Ship Placement Example

Manually Placing a Ship

You can manually place a ship on the board by specifying its type, coordinates, and direction:

placeShip({
    type: "battleship",
    coords: { x: 3, y: 5 },
    direction: "hor", // horizontal
});

Randomly Placing Ships

To randomly place all ships on the board:

randomlyPlaceShips();

Attack Example

Handling an Attack

You can register an attack on the board by specifying the coordinates:

receiveAttack({ x: 4, y: 7 });

If the attack misses, the missed coordinates will be updated.

Checking for Game Over

To check if a player has lost (i.e., all ships have been sunk):

if (hasLost()) {
    console.log("Game over, all ships have been sunk!");
}

API Reference

useGameBoard

This hook manages the game board's state and interactions.

  • ships: A map containing all placed ships on the board.
  • takenCells: A map of cells that are occupied by ships.
  • missed: A map of missed attacks on the board.
  • randomlyPlaceShips(): Randomly places all ships on the board.
  • placeShip(params: { type: ShipType; coords: TCoords; direction: Direction }): Places a specific ship on the board.
  • receiveAttack(coords: TCoords): Processes an attack at the given coordinates.
  • hasLost(): Returns true if all ships have been sunk.
  • resetGameBoard(): Resets the game board to its initial state.

Ship

The Ship class defines the behavior of a ship, including its position, hit detection, and sinking status.

  • type: The type of the ship.
  • length: The length of the ship.
  • hit(): Marks the ship as hit.
  • isSunk(): Checks if the ship is completely sunk.

Coords

The Coords class represents the coordinates of a cell on the game board.

  • x: The x-coordinate.
  • y: The y-coordinate.
  • toString(): Returns the coordinates in string format (x,y).

License

MIT