working ish version one with rooms, thx to claude
This commit is contained in:
1
bun.lock
1
bun.lock
@@ -8,6 +8,7 @@
|
||||
"next": "16.1.6",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3",
|
||||
"zod": "^4.3.6",
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
||||
@@ -11,7 +11,8 @@
|
||||
"dependencies": {
|
||||
"next": "16.1.6",
|
||||
"react": "19.2.3",
|
||||
"react-dom": "19.2.3"
|
||||
"react-dom": "19.2.3",
|
||||
"zod": "^4.3.6"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@tailwindcss/postcss": "^4",
|
||||
|
||||
41
src/app/api/room/[code]/route.ts
Normal file
41
src/app/api/room/[code]/route.ts
Normal file
@@ -0,0 +1,41 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { getRoom, closeRoom, leaveRoom } from '@/lib/rooms';
|
||||
|
||||
export async function GET(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ code: string }> }
|
||||
) {
|
||||
const { code } = await params;
|
||||
const room = getRoom(code);
|
||||
|
||||
if (!room) {
|
||||
return NextResponse.json({ error: 'Room not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json({
|
||||
code: room.code,
|
||||
playerCount: room.players.size,
|
||||
players: Array.from(room.players.values()),
|
||||
isActive: room.isActive,
|
||||
});
|
||||
}
|
||||
|
||||
export async function POST(
|
||||
req: Request,
|
||||
{ params }: { params: Promise<{ code: string }> }
|
||||
) {
|
||||
const { code } = await params;
|
||||
const body = await req.json();
|
||||
|
||||
if (body.action === 'close') {
|
||||
const success = closeRoom(code, body.moderatorId);
|
||||
return NextResponse.json({ success });
|
||||
}
|
||||
|
||||
if (body.action === 'leave') {
|
||||
const success = leaveRoom(code, body.playerId);
|
||||
return NextResponse.json({ success });
|
||||
}
|
||||
|
||||
return NextResponse.json({ error: 'Invalid action' }, { status: 400 });
|
||||
}
|
||||
7
src/app/api/room/create/route.ts
Normal file
7
src/app/api/room/create/route.ts
Normal file
@@ -0,0 +1,7 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { createRoom } from '@/lib/rooms';
|
||||
|
||||
export async function POST() {
|
||||
const { code, moderatorId } = createRoom();
|
||||
return NextResponse.json({ code, moderatorId });
|
||||
}
|
||||
13
src/app/api/room/join/route.ts
Normal file
13
src/app/api/room/join/route.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { joinRoom } from '@/lib/rooms';
|
||||
|
||||
export async function POST(req: Request) {
|
||||
const { code, playerName } = await req.json();
|
||||
const result = joinRoom(code, playerName);
|
||||
|
||||
if (!result) {
|
||||
return NextResponse.json({ error: 'Room not found' }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(result);
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 25 KiB |
@@ -1,26 +1,3 @@
|
||||
@import "tailwindcss";
|
||||
|
||||
:root {
|
||||
--background: #ffffff;
|
||||
--foreground: #171717;
|
||||
}
|
||||
|
||||
@theme inline {
|
||||
--color-background: var(--background);
|
||||
--color-foreground: var(--foreground);
|
||||
--font-sans: var(--font-geist-sans);
|
||||
--font-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
:root {
|
||||
--background: #0a0a0a;
|
||||
--foreground: #ededed;
|
||||
}
|
||||
}
|
||||
|
||||
body {
|
||||
background: var(--background);
|
||||
color: var(--foreground);
|
||||
font-family: Arial, Helvetica, sans-serif;
|
||||
}
|
||||
@tailwind base;
|
||||
@tailwind components;
|
||||
@tailwind utilities;
|
||||
|
||||
80
src/app/host/page.tsx
Normal file
80
src/app/host/page.tsx
Normal file
@@ -0,0 +1,80 @@
|
||||
"use client";
|
||||
|
||||
import { useState, useEffect } from "react";
|
||||
|
||||
export default function HostPage() {
|
||||
const [roomCode, setRoomCode] = useState("");
|
||||
const [moderatorId, setModeratorId] = useState("");
|
||||
const [players, setPlayers] = useState<any[]>([]);
|
||||
|
||||
async function createRoom() {
|
||||
const res = await fetch("/api/room/create", { method: "POST" });
|
||||
const data = await res.json();
|
||||
setRoomCode(data.code);
|
||||
setModeratorId(data.moderatorId);
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
if (!roomCode) return;
|
||||
|
||||
const interval = setInterval(async () => {
|
||||
const res = await fetch(`/api/room/${roomCode}`);
|
||||
const data = await res.json();
|
||||
setPlayers(data.players || []);
|
||||
}, 2000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [roomCode]);
|
||||
|
||||
async function closeRoom() {
|
||||
await fetch(`/api/room/${roomCode}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "close", moderatorId }),
|
||||
});
|
||||
window.location.href = "/";
|
||||
}
|
||||
|
||||
if (!roomCode) {
|
||||
return (
|
||||
<main className="min-h-screen flex items-center justify-center">
|
||||
<button
|
||||
onClick={createRoom}
|
||||
className="px-12 py-6 bg-green-600 text-white rounded-lg text-2xl hover:bg-green-700"
|
||||
>
|
||||
Create Room
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen p-8">
|
||||
<div className="max-w-2xl mx-auto">
|
||||
<h1 className="text-4xl font-bold mb-8">Room Code</h1>
|
||||
<div className="text-8xl font-bold text-blue-600 tracking-widest mb-12">
|
||||
{roomCode}
|
||||
</div>
|
||||
|
||||
<div className="bg-gray-100 p-6 rounded-lg">
|
||||
<h2 className="text-2xl font-bold mb-4">
|
||||
Players ({players.length})
|
||||
</h2>
|
||||
|
||||
{players.map((p) => (
|
||||
<div key={p.id} className="py-3 border-b border-gray-300">
|
||||
{p.name}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
<button
|
||||
onClick={closeRoom}
|
||||
className="mt-8 px-8 py-3 bg-red-600 text-white rounded-lg hover:bg-red-700"
|
||||
>
|
||||
Close Room
|
||||
</button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
@@ -1,34 +1,19 @@
|
||||
import type { Metadata } from "next";
|
||||
import { Geist, Geist_Mono } from "next/font/google";
|
||||
import "./globals.css";
|
||||
|
||||
const geistSans = Geist({
|
||||
variable: "--font-geist-sans",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
const geistMono = Geist_Mono({
|
||||
variable: "--font-geist-mono",
|
||||
subsets: ["latin"],
|
||||
});
|
||||
|
||||
export const metadata: Metadata = {
|
||||
title: "Create Next App",
|
||||
description: "Generated by create next app",
|
||||
title: "SciBowl Quiz",
|
||||
description: "Science Bowl quiz game",
|
||||
};
|
||||
|
||||
export default function RootLayout({
|
||||
children,
|
||||
}: Readonly<{
|
||||
}: {
|
||||
children: React.ReactNode;
|
||||
}>) {
|
||||
}) {
|
||||
return (
|
||||
<html lang="en">
|
||||
<body
|
||||
className={`${geistSans.variable} ${geistMono.variable} antialiased`}
|
||||
>
|
||||
{children}
|
||||
</body>
|
||||
<body>{children}</body>
|
||||
</html>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -1,65 +1,25 @@
|
||||
import Image from "next/image";
|
||||
import Link from "next/link";
|
||||
|
||||
export default function Home() {
|
||||
return (
|
||||
<div className="flex min-h-screen items-center justify-center bg-zinc-50 font-sans dark:bg-black">
|
||||
<main className="flex min-h-screen w-full max-w-3xl flex-col items-center justify-between py-32 px-16 bg-white dark:bg-black sm:items-start">
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/next.svg"
|
||||
alt="Next.js logo"
|
||||
width={100}
|
||||
height={20}
|
||||
priority
|
||||
/>
|
||||
<div className="flex flex-col items-center gap-6 text-center sm:items-start sm:text-left">
|
||||
<h1 className="max-w-xs text-3xl font-semibold leading-10 tracking-tight text-black dark:text-zinc-50">
|
||||
To get started, edit the page.tsx file.
|
||||
</h1>
|
||||
<p className="max-w-md text-lg leading-8 text-zinc-600 dark:text-zinc-400">
|
||||
Looking for a starting point or more instructions? Head over to{" "}
|
||||
<a
|
||||
href="https://vercel.com/templates?framework=next.js&utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
<main className="min-h-screen flex flex-col items-center justify-center p-8">
|
||||
<h1 className="text-6xl font-bold mb-12">🧪 SciBowl Quiz</h1>
|
||||
|
||||
<div className="flex gap-6">
|
||||
<Link
|
||||
href="/host"
|
||||
className="px-8 py-4 bg-blue-600 text-white rounded-lg text-xl hover:bg-blue-700 transition"
|
||||
>
|
||||
Templates
|
||||
</a>{" "}
|
||||
or the{" "}
|
||||
<a
|
||||
href="https://nextjs.org/learn?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
className="font-medium text-zinc-950 dark:text-zinc-50"
|
||||
Host a Game
|
||||
</Link>
|
||||
|
||||
<Link
|
||||
href="/play"
|
||||
className="px-8 py-4 bg-green-600 text-white rounded-lg text-xl hover:bg-green-700 transition"
|
||||
>
|
||||
Learning
|
||||
</a>{" "}
|
||||
center.
|
||||
</p>
|
||||
</div>
|
||||
<div className="flex flex-col gap-4 text-base font-medium sm:flex-row">
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center gap-2 rounded-full bg-foreground px-5 text-background transition-colors hover:bg-[#383838] dark:hover:bg-[#ccc] md:w-[158px]"
|
||||
href="https://vercel.com/new?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
<Image
|
||||
className="dark:invert"
|
||||
src="/vercel.svg"
|
||||
alt="Vercel logomark"
|
||||
width={16}
|
||||
height={16}
|
||||
/>
|
||||
Deploy Now
|
||||
</a>
|
||||
<a
|
||||
className="flex h-12 w-full items-center justify-center rounded-full border border-solid border-black/[.08] px-5 transition-colors hover:border-transparent hover:bg-black/[.04] dark:border-white/[.145] dark:hover:bg-[#1a1a1a] md:w-[158px]"
|
||||
href="https://nextjs.org/docs?utm_source=create-next-app&utm_medium=appdir-template-tw&utm_campaign=create-next-app"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
>
|
||||
Documentation
|
||||
</a>
|
||||
Join a Game
|
||||
</Link>
|
||||
</div>
|
||||
</main>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
88
src/app/play/page.tsx
Normal file
88
src/app/play/page.tsx
Normal file
@@ -0,0 +1,88 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
|
||||
export default function PlayPage() {
|
||||
const [name, setName] = useState("");
|
||||
const [code, setCode] = useState("");
|
||||
const [joined, setJoined] = useState(false);
|
||||
const [playerId, setPlayerId] = useState("");
|
||||
|
||||
async function join() {
|
||||
const res = await fetch("/api/room/join", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ code: code.toUpperCase(), playerName: name }),
|
||||
});
|
||||
|
||||
const data = await res.json();
|
||||
|
||||
if (data.error) {
|
||||
alert(data.error);
|
||||
return;
|
||||
}
|
||||
|
||||
setPlayerId(data.playerId);
|
||||
setJoined(true);
|
||||
}
|
||||
|
||||
async function leave() {
|
||||
await fetch(`/api/room/${code}`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ action: "leave", playerId }),
|
||||
});
|
||||
window.location.href = "/";
|
||||
}
|
||||
|
||||
if (joined) {
|
||||
return (
|
||||
<main className="min-h-screen flex flex-col items-center justify-center p-8">
|
||||
<h1 className="text-4xl font-bold mb-4">✓ You're in!</h1>
|
||||
<p className="text-xl mb-8">
|
||||
Room: <strong>{code}</strong>
|
||||
</p>
|
||||
<p className="text-gray-600 mb-8">Waiting for host to start...</p>
|
||||
<button
|
||||
onClick={leave}
|
||||
className="px-8 py-3 bg-gray-600 text-white rounded-lg hover:bg-gray-700"
|
||||
>
|
||||
Leave Room
|
||||
</button>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="min-h-screen flex items-center justify-center p-8">
|
||||
<div className="w-full max-w-md">
|
||||
<h1 className="text-4xl font-bold mb-8 text-center">Join a Room</h1>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Your Name"
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className="w-full p-4 text-lg border-2 border-gray-300 rounded-lg mb-4"
|
||||
maxLength={20}
|
||||
/>
|
||||
|
||||
<input
|
||||
type="text"
|
||||
placeholder="Room Code"
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value.toUpperCase())}
|
||||
className="w-full p-4 text-lg border-2 border-gray-300 rounded-lg mb-6 uppercase"
|
||||
maxLength={6}
|
||||
/>
|
||||
|
||||
<button
|
||||
onClick={join}
|
||||
className="w-full px-8 py-4 bg-blue-600 text-white rounded-lg text-xl hover:bg-blue-700"
|
||||
>
|
||||
Join
|
||||
</button>
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
78
src/lib/rooms.ts
Normal file
78
src/lib/rooms.ts
Normal file
@@ -0,0 +1,78 @@
|
||||
import { Room } from '@/types';
|
||||
|
||||
// Use global to persist across Next.js hot reloads
|
||||
declare global {
|
||||
var roomStorage: Map<string, Room> | undefined;
|
||||
}
|
||||
|
||||
// Initialize global storage if it doesn't exist
|
||||
if (!global.roomStorage) {
|
||||
global.roomStorage = new Map();
|
||||
}
|
||||
|
||||
export const rooms = global.roomStorage;
|
||||
|
||||
function generateCode(): string {
|
||||
const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
|
||||
return Array.from({ length: 6 }, () =>
|
||||
chars[Math.floor(Math.random() * chars.length)]
|
||||
).join('');
|
||||
}
|
||||
|
||||
function generateId(): string {
|
||||
return Math.random().toString(36).substring(2, 15);
|
||||
}
|
||||
|
||||
export function createRoom() {
|
||||
const code = generateCode();
|
||||
const moderatorId = generateId();
|
||||
|
||||
rooms.set(code, {
|
||||
code,
|
||||
moderatorId,
|
||||
players: new Map(),
|
||||
isActive: true,
|
||||
createdAt: new Date(),
|
||||
});
|
||||
|
||||
console.log('✅ Created room:', code, 'Total rooms:', rooms.size);
|
||||
return { code, moderatorId };
|
||||
}
|
||||
|
||||
export function joinRoom(code: string, name: string) {
|
||||
const room = rooms.get(code);
|
||||
console.log('👤 Join attempt for room:', code, 'Room exists:', !!room, 'Total rooms:', rooms.size);
|
||||
|
||||
if (!room?.isActive) return null;
|
||||
|
||||
const playerId = generateId();
|
||||
room.players.set(playerId, { id: playerId, name, score: 0 });
|
||||
|
||||
console.log('✅ Player joined:', name, 'Total players:', room.players.size);
|
||||
return { playerId };
|
||||
}
|
||||
|
||||
export function getRoom(code: string) {
|
||||
const room = rooms.get(code);
|
||||
console.log('🔍 Get room:', code, 'Exists:', !!room, 'Total rooms:', rooms.size);
|
||||
return room;
|
||||
}
|
||||
|
||||
export function closeRoom(code: string, moderatorId: string) {
|
||||
const room = rooms.get(code);
|
||||
if (room?.moderatorId === moderatorId) {
|
||||
room.isActive = false;
|
||||
console.log('🔒 Room closed:', code);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function leaveRoom(code: string, playerId: string) {
|
||||
const room = rooms.get(code);
|
||||
const result = room?.players.delete(playerId) ?? false;
|
||||
if (result) {
|
||||
console.log('👋 Player left room:', code, 'Remaining players:', room?.players.size);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
18
src/lib/scibowl-api.ts
Normal file
18
src/lib/scibowl-api.ts
Normal file
@@ -0,0 +1,18 @@
|
||||
const BASE_URL = 'https://scibowldb.com/api';
|
||||
|
||||
interface RandomQuestionResponse {
|
||||
question: any;
|
||||
}
|
||||
|
||||
export async function getRandomQuestion() {
|
||||
const res = await fetch(`${BASE_URL}/questions/random`);
|
||||
if (!res.ok) throw new Error('Failed to fetch question');
|
||||
const data: RandomQuestionResponse = await res.json();
|
||||
return data.question;
|
||||
}
|
||||
|
||||
export async function getAllQuestions() {
|
||||
const res = await fetch(`${BASE_URL}/questions`);
|
||||
if (!res.ok) throw new Error('Failed to fetch questions');
|
||||
return await res.json();
|
||||
}
|
||||
27
src/types/index.ts
Normal file
27
src/types/index.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
export interface Question {
|
||||
api_url: string;
|
||||
bonus_answer: string;
|
||||
bonus_format: string;
|
||||
bonus_question: string;
|
||||
category: string;
|
||||
id: number;
|
||||
source: string;
|
||||
tossup_answer: string;
|
||||
tossup_format: string;
|
||||
tossup_question: string;
|
||||
uri: string;
|
||||
}
|
||||
|
||||
export interface Player {
|
||||
id: string;
|
||||
name: string;
|
||||
score: number;
|
||||
}
|
||||
|
||||
export interface Room {
|
||||
code: string;
|
||||
moderatorId: string;
|
||||
players: Map<string, Player>;
|
||||
isActive: boolean;
|
||||
createdAt: Date;
|
||||
}
|
||||
Reference in New Issue
Block a user