Skip to content

Commit

Permalink
migrating to typescript (still needs refactoring)
Browse files Browse the repository at this point in the history
  • Loading branch information
igorcafe committed Jun 27, 2022
1 parent ee406bc commit 51238cb
Show file tree
Hide file tree
Showing 9 changed files with 116 additions and 54 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
node_modules
2 changes: 1 addition & 1 deletion index.html
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@
}
</style>

<script type="module" src="/src/index.js">
<script type="module" src="/src/index.ts">
</script>
</body>
</html>
29 changes: 26 additions & 3 deletions src/config.js → src/config.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,8 @@
const canvas = document.getElementById('canvas')
import { Player } from "./player"
import { Point } from "./utils"
import { Wall } from "./wall"

const canvas = document.getElementById('canvas') as HTMLCanvasElement

const width = 26
const height = 15
Expand All @@ -8,7 +12,7 @@ canvas.height = height

const ctx = canvas.getContext('2d')

const colors = {
const colors: Record<string, string> = {
S: '#fc0',
s: '#ff0',
E: '#ccc',
Expand All @@ -21,7 +25,7 @@ const colors = {
',': '#303050',
}

const keymaps = {
const keymaps: Record<string, string> = {
a: '0.left',
d: '0.right',
w: '0.up',
Expand All @@ -43,13 +47,32 @@ const keymaps = {
i: '1.up',
k: '1.down',
u: '1.reverse',
// ' ': '1.start',
// r: '1.restart',
}

const board: string[][] = []
const fruit: Point = {
x: 17,
y: 7,
}

const players: Player[] = []
const walls: Wall[] = []
const intervalId: number | undefined = 0

export const game = {
paused: true,
width,
height,
ctx,
colors,
keymaps,
fruit,
board,
players,
walls,
intervalId,
newMatch() {},
endMatch() {}
}
44 changes: 32 additions & 12 deletions src/index.js → src/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { Wall } from './wall.js'
// import { Wall } from './wall'
import { Player } from './player.js'
import { createMatrix, randomPosition } from './utils.js'
import { game } from './config.js'
// import { $ } from './utils'
// import { $, createMatrix, randomPosition } from './utils'
import { $, createMatrix } from './utils'
import { game } from './config'

// const { game.width, game.height, game.colors, game.keymaps } = game
// const emptyBoard = copy(game.board)
Expand All @@ -10,28 +12,34 @@ import { game } from './config.js'
// return JSON.parse(JSON.stringify(obj))
// }

const canvas = $('#canvas') as HTMLCanvasElement
const fullscreen = $('#fullscreen') as HTMLButtonElement

fullscreen.onclick = () => {
const requestFullScreen = canvas.requestFullScreen || canvas.webkitRequestFullScreen
const requestFullScreen = canvas.requestFullscreen //|| canvas.webkitRequestFullScreen
requestFullScreen.call(canvas)
}

game.endMatch = function () {
this.paused = true
clearInterval(this.intervalId)
game.paused = true
clearInterval(game.intervalId)
}

game.newMatch = function () {
// debugger
this.paused = true
clearInterval(this.intervalId)
this.intervalId = setup()
game.paused = true
clearInterval(game.intervalId)
game.intervalId = setup()
}

window.onkeydown = (e) => {
const command = game.keymaps[e.key]
if (command) {
const [i, fn] = command.split('.')
game.players[i][fn]()

// @ts-ignore
// TODO: solution for this
game.players[parseInt(i)][fn]()
}
}

Expand Down Expand Up @@ -71,7 +79,7 @@ window.addEventListener('gamepadconnected', () => {
gamepadEnabled = true
})

function setup() {
function setup(): number {
// clearBoard()
game.board = createMatrix(game.height, game.width, '.')
// window.game.board = game.board
Expand Down Expand Up @@ -115,10 +123,12 @@ function setup() {
}

loop()
return setInterval(loop, 100)
return setInterval(loop, 100) ?? 0
}

function loop() {
if (!game.ctx) return

if (gamepadEnabled) {
gamepads = navigator.getGamepads()
gamepads.forEach((gamepad, i) => {
Expand All @@ -145,9 +155,17 @@ function loop() {

let command = game.keymaps[map]

// @ts-ignore
// TODO: solution for this
if (command && command !== gamepad.previousCommand) {
const [i, fn] = command.split('.')

// @ts-ignore
// TODO: solution for this
game.players[i][fn]()

// @ts-ignore
// TODO: solution for this
gamepad.previousCommand = command
}
})
Expand All @@ -157,12 +175,14 @@ function loop() {
p.erase()
})


game.ctx.fillStyle = '#335'
game.ctx.fillRect(0, 0, game.width, game.height)

game.ctx.fillStyle = '#f00'
game.ctx.fillRect(0, 0, 1, 1)

// if (game.board[game.fruit.y])
game.board[game.fruit.y][game.fruit.x] = 'o'

game.players.forEach((p) => {
Expand Down
28 changes: 18 additions & 10 deletions src/player.js → src/player.ts
Original file line number Diff line number Diff line change
@@ -1,34 +1,41 @@
import { randomPosition, pointsIntersect } from './utils.js'
import { randomPosition, pointsIntersect, Point } from './utils.js'
import { game } from './config.js'

// const { game.width, game.height } = game
// import { game } from './index.js'

// import { ctx, game.width, game.height, colors, keymaps } from './config.js'

type PlayerConstructorParams = { x: number, y: number, maxX: number, maxY: number, isPlayer1?: boolean }
type Direction = 'right' | 'down' | 'left' | 'up'

export class Player {
directions = {
oppositeDirections: Record<Direction, Direction> = {
left: 'right',
up: 'down',
right: 'left',
down: 'up',
}
facing = 'right'
facing: Direction = 'right'
moveSpeed = 1
moved = true
speed = { x: 0, y: 0 }
body = []
body: Point[] = []
charHead = 'E'
charBody = 'e'
enemyHead = 'S'
enemyBody = 's'
score = 0
isPlayer1 = false
maxX: number
maxY: number

constructor({ x, y, maxX, maxY, isPlayer1}) {
// TODO: change this to a cleaner solution
constructor({ x, y, maxX, maxY, isPlayer1}: PlayerConstructorParams) {
this.maxX = maxX
this.maxY = maxY
this.isPlayer1 = isPlayer1
this.isPlayer1 = isPlayer1 ?? false


if (isPlayer1) {
// this.moveSpeed = 2
Expand All @@ -55,7 +62,7 @@ export class Player {
this.body = this.body.reverse()
this.speed.x *= -1
this.speed.y *= -1
this.facing = this.directions[this.facing]
this.facing = this.oppositeDirections[this.facing]
}

draw() {
Expand All @@ -69,18 +76,19 @@ export class Player {
erase() {
for (const part of this.body) {
// debugger
// if (game.board[part.y])
game.board[part.y][part.x] = '.'
}
}

eat() {
this.score++
this.body.push({ ...this.body.at(-1) })
this.body.push({ ...this.body.at(-1)! })
// cleanTile(this.head.x, this.head.y)
game.board[this.head.y][this.head.x] = '.'
game.fruit = randomPosition(game.width - 1, game.height - 1, [
(x, y) => !game.players.some((p) => p.body.some((b) => b.x === x && b.y === y)),
(x, y) => !game.walls.some((w) => w.x === x && w.y === y),
(x: number, y: number) => !game.players.some((p) => p.body.some((b) => b.x === x && b.y === y)),
(x: number, y: number) => !game.walls.some((w) => w.x === x && w.y === y),
])
}

Expand Down
26 changes: 0 additions & 26 deletions src/utils.js

This file was deleted.

32 changes: 32 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
export type Point = { x: number, y: number }

export function randomPosition(maxX: number, maxY: number, validations: Function[] = []) {
let x: number
let y: number
do {
x = Math.floor(Math.random() * maxX)
y = Math.floor(Math.random() * maxY)
// debugger
} while (!validations.every((v) => !v || v(x, y)))
return { x, y }
}

export function pointsIntersect(...points: Point[]) {
// const points = [...arguments]
const ref = points[0]
return points.every((point) => ref.x === point.x && ref.y === point.y)
}

export function createMatrix(lines: number, cols: number, string: string) {
const res: string[][] = []
for (let l = 0; l < lines; l++) {
res.push([])
for (let c = 0; c < cols; c++) {
res[l].push(string)
}
}
return res
}

export const $ = document.querySelector.bind(document)
// export const $$ = (q: string) => [...document.querySelectorAll(q)]
1 change: 1 addition & 0 deletions src/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
/// <reference types="vite/client" />
7 changes: 5 additions & 2 deletions src/wall.js → src/wall.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import { game } from './config.js'
import { game } from './config'

export class Wall {
constructor(x, y) {
x: number
y: number

constructor(x: number, y: number) {
this.x = x
this.y = y
}
Expand Down

1 comment on commit 51238cb

@vercel
Copy link

@vercel vercel bot commented on 51238cb Jun 27, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Successfully deployed to the following URLs:

becomb – ./

becomb.vercel.app
becomb-git-master-igoracmelo.vercel.app
becomb-igoracmelo.vercel.app

Please sign in to comment.