1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
/** @jsxImportSource https://esm.sh/react */
import React, { useState, useEffect, useRef } from "https://esm.sh/react";
import { createRoot } from "https://esm.sh/react-dom/client";
const CANVAS_SIZE = 400;
const GRID_SIZE = 20;
const CELL_SIZE = CANVAS_SIZE / GRID_SIZE;
function ChatRoom() {
const [messages, setMessages] = useState([]);
const [inputMessage, setInputMessage] = useState('');
const [username, setUsername] = useState('');
const sendMessage = () => {
if (inputMessage && username) {
setMessages([...messages, { username, message: inputMessage }]);
setInputMessage('');
}
};
return (
<div>
<h2>Chat Room</h2>
<div style={{ height: '200px', overflowY: 'scroll', border: '1px solid black', padding: '10px', marginBottom: '10px' }}>
{messages.map((msg, index) => (
<p key={index}><strong>{msg.username}:</strong> {msg.message}</p>
))}
</div>
<input
type="text"
placeholder="Your username"
value={username}
onChange={(e) => setUsername(e.target.value)}
style={{ marginRight: '10px' }}
/>
<input
type="text"
placeholder="Type a message"
value={inputMessage}
onChange={(e) => setInputMessage(e.target.value)}
style={{ marginRight: '10px' }}
/>
<button onClick={sendMessage}>Send</button>
</div>
);
}
function SnakeGame() {
const [snake, setSnake] = useState([{ x: 10, y: 10 }]);
const [food, setFood] = useState({ x: 15, y: 15 });
const [direction, setDirection] = useState({ x: 1, y: 0 });
const [gameOver, setGameOver] = useState(false);
const canvasRef = useRef(null);
useEffect(() => {
const handleKeyPress = (e) => {
switch (e.key) {
case 'w': setDirection({ x: 0, y: -1 }); break;
case 's': setDirection({ x: 0, y: 1 }); break;
case 'a': setDirection({ x: -1, y: 0 }); break;
case 'd': setDirection({ x: 1, y: 0 }); break;
}
};
window.addEventListener('keydown', handleKeyPress);
return () => window.removeEventListener('keydown', handleKeyPress);
}, []);
useEffect(() => {
if (gameOver) return;
const moveSnake = () => {
setSnake(prevSnake => {
const newSnake = [...prevSnake];
const head = { ...newSnake[0] };
head.x += direction.x;
head.y += direction.y;
if (head.x < 0 || head.x >= GRID_SIZE || head.y < 0 || head.y >= GRID_SIZE) {
setGameOver(true);
return prevSnake;
}
newSnake.unshift(head);
if (head.x === food.x && head.y === food.y) {
setFood({
x: Math.floor(Math.random() * GRID_SIZE),
y: Math.floor(Math.random() * GRID_SIZE)
});
} else {
newSnake.pop();
}
return newSnake;
});
};
const gameLoop = setInterval(moveSnake, 100);
return () => clearInterval(gameLoop);
}, [direction, food, gameOver]);