Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 11 additions & 1 deletion components/Board.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -34,17 +34,27 @@ const Board = ({ cells }: BoardProps) => {
(acc, { coord }) => (acc = Math.min(acc, -(coord.y - coord.z))),
+Infinity
)
const maxYZCoordinate = cells.reduce(
(acc, { coord }) => (acc = Math.max(acc, -(coord.y - coord.z))),
-Infinity
)
const maxXCoordinate = cells.reduce(
(acc, { coord }) => (acc = Math.max(acc, coord.x)),
-Infinity
)
const totalCols = maxXCoordinate - minXCoordinate + 1
const totalRows = maxYZCoordinate - minYZCoordinate + 1

const screenWidth = window.innerWidth
const screenHeight = window.innerHeight

const yUnit = screenWidth < screenHeight ? totalCols : totalRows
const unit = Math.min(screenWidth, screenHeight) / ((yUnit + 24) * 3)
return (
<div
className="board"
style={{
gridTemplateColumns: `repeat(${totalCols}, 1fr 2fr) 1fr`,
gridTemplateColumns: `repeat(${totalCols}, ${unit}px ${2 * unit}px) ${unit}px`,
}}
>
{cells.map((cell) => {
Expand Down
135 changes: 72 additions & 63 deletions components/Menu.tsx
Original file line number Diff line number Diff line change
@@ -1,63 +1,72 @@
import React, { useEffect, useState } from 'react'
import { useRouter } from 'next/router'

import { generateRoomId } from '../lib/p2p'

const Menu = () => {
const router = useRouter()
const [code, setCode] = useState('')
const [generated, setGenerated] = useState('')

const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!code) {
return
}
router.push({
pathname: 'rooms/' + code,
query: {},
})
}

useEffect(() => {
// useEffect so the generated roomId is the same on client and server
setGenerated(generateRoomId())
}, [])

return (
<div className="flex flex-col justify-center ">
<a
href={'/rooms/' + generated + '?create=1'}
className="btn text-center hover:bg-gray-400"
>
Create game
</a>

<div className="text-center my-8">OR</div>

<form
onSubmit={() => handleSubmit}
className="flex flex-col justify-center"
>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mb-2"
type="text"
placeholder="Room code"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
<a
href={'/rooms/' + code}
className={
'btn text-center' + (!code ? ' btn-disabled' : ' hover:bg-gray-400')
}
>
Join game
</a>
<button onClick={handleSubmit} className="hidden" type="submit" />
</form>
</div>
)
}

export default Menu
import React, { useContext, useEffect, useState } from 'react'
import { useRouter } from 'next/router'

import { generateRoomId } from '../lib/connection'
import { gameContext } from '../context/machines'

const Menu = () => {
const router = useRouter()
const [code, setCode] = useState('')
const [generated, setGenerated] = useState('')
const [, sendToGame] = useContext(gameContext)

const handleSubmit = (e: React.FormEvent) => {
e.preventDefault()
if (!code) {
return
}
router.push({
pathname: 'rooms/' + code,
query: {},
})
}

useEffect(() => {
// useEffect so the generated roomId is the same on client and server
setGenerated(generateRoomId())
}, [])

return (
<div className="flex flex-col justify-center ">
<button
onClick={() => sendToGame('GAME.SEARCH')}
className="btn my-1 text-center hover:bg-gray-400"
>
Search game
</button>

<a
href={'/rooms/' + generated + '?create=1'}
className="btn my-1 text-center hover:bg-gray-400"
>
Create game
</a>

<div className="text-center my-8">OR</div>

<form
onSubmit={() => handleSubmit}
className="flex flex-col justify-center"
>
<input
className="shadow appearance-none border rounded w-full py-2 px-3 text-gray-700 leading-tight focus:outline-none focus:shadow-outline mb-2"
type="text"
placeholder="Room code"
value={code}
onChange={(e) => setCode(e.target.value)}
/>
<a
href={'/rooms/' + code}
className={
'btn text-center' + (!code ? ' btn-disabled' : ' hover:bg-gray-400')
}
>
Join game
</a>
<button onClick={handleSubmit} className="hidden" type="submit" />
</form>
</div>
)
}

export default Menu
17 changes: 0 additions & 17 deletions config/webrtc_ICE_servers.json

This file was deleted.

105 changes: 105 additions & 0 deletions lib/connection.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
import { io } from 'socket.io-client'
// import { getSession } from 'next-auth/client'
// const WebSocket = require('ws')

import { Context } from '../machines/types'

const socket = io('http://localhost:3001')

function initMatchmakingSocket() {
if (!process.browser) {
return
}

const matchmakingSocket = new WebSocket(
'ws://localhost:8888/api/matchmaking/queue'
)

matchmakingSocket.onopen = (x) => {
console.log('matchmakingsocket connection', x)
matchmakingSocket.send('Hello!')
}

matchmakingSocket.onmessage = (data) => {
console.log('matchmakingSocket message', data)
}

matchmakingSocket.onerror = (error) => {
console.log('matchmakingSocket ERROR', JSON.stringify(error))
}
}

socket.on('connected', (socketId: string) => {
console.log('connected', socketId)

socket.on('ROOM.CREATED', (roomId: string) => {
console.log(`Created room ${roomId}`)
})

socket.on('ROOM.JOINED', (roomId: string) => {
console.log(`Joined room ${roomId}`)
})

socket.on('disconnect', (/* reason: string */) => {
console.log('disconnected!', socket)
socket.emit('PLAYER.DISCONNECT', socket.id)
})
})

export async function createRoom(
roomId: string,
callback: Function,
context: Context
) {
console.log('creating game', roomId, context)
socket.emit('ROOM.CREATE', roomId)

callback({ type: 'SYNC', state: { ...context, roomId } })

socket.on('SYNC', (context: Context) => {
console.log('callbacking')
callback({ type: 'SYNC', state: context })
})
}

export async function joinRoom(
roomId: string,
callback: Function,
context: Context
) {
console.log('joingin', roomId)
socket.emit('ROOM.JOIN', roomId)

if (!window.location.href.includes('rooms/')) {
window.location.href = 'http://localhost:3000/rooms/' + roomId
}

callback({ type: 'SYNC', state: { ...context, roomId } })

socket.on('SYNC', (context: Context) => {
console.log('callbacking')
callback({ type: 'SYNC', state: { ...context, roomId } })
})
}

export async function searchGame(callback: Function) {
// const session = await getSession()
// const { userId } = session
// TODO: create socket connection with matchmaking backend
// TODO: send gamesearch event to matchmaking-socket
// TODO: on answer, joinRoom(roomId) (passed as callback)
initMatchmakingSocket()
const roomId = 'test1'
setTimeout(() => {
callback({ type: 'GAME.JOIN', roomId })
}, 2000)
}

export async function sync(context: Context, roomId: string) {
console.log('syncing', context, roomId)
socket.emit('SYNC', { ...context, roomId })
}

export const generateRoomId = () => {
return Math.random().toString(26).substring(5, 10)
}
Loading