Skip to content

Commit

Permalink
chore: add game instance and fix errors
Browse files Browse the repository at this point in the history
  • Loading branch information
luispied committed Apr 17, 2023
1 parent 0b445db commit 6dbea83
Show file tree
Hide file tree
Showing 10 changed files with 79 additions and 94 deletions.
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
</head>
<body>
<canvas id="canvas"></canvas>
<script type="module" src="./src/start.ts"></script>
<script type="module" src="./src/index.ts"></script>
<script type="module" src="./src/events.ts"></script>
</body>
</html>
41 changes: 24 additions & 17 deletions src/classes/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,15 @@ import { Ball } from "./ball";
import { Player } from "./player";

export class Game {
_players: number = 1;
players: number = 1;
winner: Player | null;
player1: Player;
player2: Player;
ball: Ball;
gameState: GameState;

private static instance: Game;

constructor() {
this.winner = null;
this.player1 = new Player(
Expand All @@ -34,14 +37,14 @@ export class Game {
DEFAULT_COLOR
);
this.player2 = new Player(
this._players > 1 ? "Player 2" : "Computer",
this.getPlayer2Name(),
canvas.width - PADDLE_WIDTH,
canvas.height / 2 - PADDLE_HEIGHT / 2,
PADDLE_HEIGHT,
PADDLE_WIDTH,
0,
DEFAULT_COLOR,
this._players > 1 ? false : true
this.getAI()
);
this.ball = new Ball(
canvas.width / 2,
Expand All @@ -54,14 +57,29 @@ export class Game {
this.gameState = GameState.menu;
}

static getInstance() {
if (!Game.instance) {
Game.instance = new Game();
}
return Game.instance;
}

setPlayers(players: number) {
this._players = players;
this.players = players;
this.player2.ai = this.getAI();
this.player2.name = this.getPlayer2Name();
}

getPlayer2Name(): string {
return this.players > 1 ? "Player 2" : "Computer";
}

getAI(): boolean {
return this.players > 1 ? false : true;
}

newGame() {
// getGameInstance();
if (
!this.gameState ||
this.gameState === GameState.menu ||
this.gameState === GameState.gameOver
) {
Expand Down Expand Up @@ -113,14 +131,3 @@ export class Game {
}
}
}

// create only one instance of the game and a method to access it
let game: Game;
export const getGameInstance = (): Game => {
if (!game) {
console.log("creating new game");
game = new Game();
}
console.log("returning game", game);
return game;
};
8 changes: 8 additions & 0 deletions src/classes/player.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,14 @@ export class Player {
this._ai = value;
}

get name() {
return this._name;
}

set name(value) {
this._name = value;
}

public toString() {
return `${this._name}`;
}
Expand Down
8 changes: 4 additions & 4 deletions src/constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@ export const ctx: CanvasRenderingContext2D = canvas.getContext(
) as CanvasRenderingContext2D;

// Define the ball speed constant
export const BALL_SPEED: number = 4; // You can set this value to whatever you want
export const BALL_SPEED: number = 5; // You can set this value to whatever you want

// Define the paddle height and width constants
export const PADDLE_HEIGHT: number = 100;
// Define the paddle height
export const PADDLE_HEIGHT: number = canvas.height * 1.5;
// Set the width of the paddles
export const PADDLE_WIDTH: number = 20;
export const PADDLE_WIDTH: number = canvas.width * 0.1;
// Set the speed of the paddles
export const PADDLE_SPEED: number = 5;

Expand Down
10 changes: 7 additions & 3 deletions src/drawing/draw.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,10 @@ import { ctx, canvas, GAME_FONT_FAMILY, DEFAULT_COLOR } from "../constants";
import { Ball } from "../classes/ball";
import { BallAndPlayers, Draw, Players } from "../types";

// Set the canvas width and height to the window width and height
canvas.width = window.innerWidth;
canvas.height = window.innerHeight;

const drawBorder = (): void => {
// Draw a border around the canvas
let borderThickness = 5;
Expand Down Expand Up @@ -35,6 +39,7 @@ const drawNet = (): void => {
const drawPaddles = (players: Players): void => {
// destructure the args
let { player1, player2 } = players;

// draw player1 paddle
if (player1) {
if (player1.width && player1.height && player1.color) {
Expand Down Expand Up @@ -141,7 +146,7 @@ const drawText = (draw: Draw): void => {
y,
color = DEFAULT_COLOR,
fontFamily = GAME_FONT_FAMILY,
fontSize = 16,
fontSize = 32,
textAlign = "center",
isBold = false,
hasShadow = false,
Expand All @@ -154,11 +159,10 @@ const drawText = (draw: Draw): void => {
if (typeof x !== "number" || typeof y !== "number") {
throw new Error("Coordinates are not numbers.");
}

// Set the fill color.
ctx.fillStyle = color;
// Set the font.
ctx.font = `${isBold && "bold"} ${fontSize}px ${fontFamily}`;
ctx.font = `${isBold ? "bold" : ""} ${fontSize}px ${fontFamily}`;
// Set the text alignment.
ctx.textAlign = textAlign;

Expand Down
30 changes: 6 additions & 24 deletions src/drawing/messages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,9 +18,6 @@ const showNewGameMessage = (): void => {
const showGameOverMessage = (winner: Player): void => {
clearCanvas();

const messageFontFamily = GAME_FONT_FAMILY;
const messageTextAlign = "center";
const messageColor = DEFAULT_COLOR;
const messageWidth = canvas.width / 2;
const messageHeight = canvas.height / 2;

Expand All @@ -29,21 +26,15 @@ const showGameOverMessage = (winner: Player): void => {
text: "Game Over",
x: messageWidth,
y: messageHeight - 100,
color: messageColor,
fontFamily: messageFontFamily,
fontSize: 48,
textAlign: messageTextAlign,
});

// draw winner message
drawText({
text: `${winner.toString()} wins`,
x: messageWidth,
y: messageHeight,
color: messageColor,
fontFamily: messageFontFamily,
fontSize: 32,
textAlign: messageTextAlign,
});

// draw new game message
Expand All @@ -52,34 +43,25 @@ const showGameOverMessage = (winner: Player): void => {

// Draw the score for both players
const showScore = (player1Score: number, player2Score: number): void => {
const scoreFontFamily = GAME_FONT_FAMILY;
const scoreTextSize = 60;
const scoreTextAlign = "center";
const scoreColor = DEFAULT_COLOR;
const leftPlayerScorePosition = canvas.width / 4;
const rightPlayerScorePosition = (canvas.width / 4) * 3;
const scoresCanvasHeight = canvas.height / 5;
const y = canvas.height / 5;
const fontSize = 120;

// Draw player 1's score
drawText({
text: player1Score.toString(),
x: leftPlayerScorePosition,
y: scoresCanvasHeight,
color: scoreColor,
fontFamily: scoreFontFamily,
fontSize: scoreTextSize,
textAlign: scoreTextAlign,
y,
fontSize,
});

// Draw player 2's score
drawText({
text: player2Score.toString(),
x: rightPlayerScorePosition,
y: scoresCanvasHeight,
color: scoreColor,
fontFamily: scoreFontFamily,
fontSize: scoreTextSize,
textAlign: scoreTextAlign,
y,
fontSize,
});
};

Expand Down
42 changes: 17 additions & 25 deletions src/events.ts
Original file line number Diff line number Diff line change
@@ -1,70 +1,62 @@
import { getGameInstance } from "./classes/game";
import { Game } from "./classes/game";
import { PADDLE_HEIGHT, PADDLE_SPEED } from "./constants";
import { GameState } from "./types";
import { drawMenu, menuActions, menuCursorDown, menuCursorUp } from "./ui/menu";

// destructuring the game instance
let { player1, player2, gameState, newGame, setPlayers } = getGameInstance();
const game = Game.getInstance();

document.addEventListener("mousemove", function (event: MouseEvent) {
// Move player1 paddle
player1.y = event.clientY - PADDLE_HEIGHT / 2;
game.player1.y = event.clientY - PADDLE_HEIGHT / 2;
});

document.addEventListener("touchmove", function (event: TouchEvent) {
// Move player1 paddle
player1.y = event.touches[0].clientY - PADDLE_HEIGHT / 2;
game.player1.y = event.touches[0].clientY - PADDLE_HEIGHT / 2;
});

document.addEventListener("touchstart", function (_event: TouchEvent) {
// Start a new game loop
newGame();
game.newGame();
});

document.addEventListener("click", function (_event: Event) {
// Start a new game loop
newGame();
game.newGame();
});

// Add event listeners for paddle movement
document.addEventListener("keydown", function (event: KeyboardEvent) {
if (event.code === "KeyW") {
// Move player1 up
player1.velocityY = -PADDLE_SPEED;
game.player1.velocityY = -PADDLE_SPEED;
} else if (event.code === "KeyS") {
// Move player1 down
player1.velocityY = PADDLE_SPEED;
game.player1.velocityY = PADDLE_SPEED;
} else if (event.code === "ArrowUp") {
if (gameState === GameState.menu) {
if (game.gameState === GameState.menu) {
event.preventDefault();
menuCursorUp();
}
// Move player2 up
player2.velocityY = -PADDLE_SPEED;
game.player2.velocityY = -PADDLE_SPEED;
} else if (event.code === "ArrowDown") {
if (gameState === GameState.menu) {
if (game.gameState === GameState.menu) {
event.preventDefault();
menuCursorDown();
}
// Move player2 down
player2.velocityY = PADDLE_SPEED;
} else if (event.code === "Space" && gameState === GameState.menu) {
game.player2.velocityY = PADDLE_SPEED;
} else if (event.code === "Space" && game.gameState === GameState.menu) {
// Start a new game loop
newGame();
game.newGame();
} else if (event.code === "Escape") {
// Draw the menu
drawMenu();
} else if (event.code === "Enter" && gameState === GameState.menu) {
} else if (event.code === "Enter" && game.gameState === GameState.menu) {
// If the Enter key is pressed in menu, do something based on the selected menu option
menuActions();
} else if (event.code === "Digit1") {
// Set the number of players to 1
console.log("Setting players to 1");
setPlayers(1);
} else if (event.code === "Digit2") {
// Set the number of players to 2
console.log("Setting players to 2");
setPlayers(2);
}
});

Expand All @@ -73,11 +65,11 @@ document.addEventListener("keyup", function (event: KeyboardEvent) {
// Player 1 controls
if (event.code === "KeyW" || event.code === "KeyS") {
// Stop player1 movement
player1.velocityY = 0;
game.player1.velocityY = 0;
}
// Player 2 controls
else if (event.code === "ArrowUp" || event.code === "ArrowDown") {
// Stop player2 movement
player2.velocityY = 0;
game.player2.velocityY = 0;
}
});
3 changes: 3 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { drawMenu } from "./ui/menu";

drawMenu();
8 changes: 0 additions & 8 deletions src/start.ts

This file was deleted.

Loading

0 comments on commit 6dbea83

Please sign in to comment.