-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.jsx
More file actions
114 lines (102 loc) · 2.97 KB
/
App.jsx
File metadata and controls
114 lines (102 loc) · 2.97 KB
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
101
102
103
104
105
106
107
108
109
110
111
112
113
114
// import Board from "./board.jsx"
import { useEffect, useRef, useState } from 'react';
import './App.css';
function App() {
const [direction, setdirection] = useState({ x: 0, y: 1 })
const [snakeArr, setSnakeArr] = useState([{ x: 6, y: 7 }]);
const [food, setfood] = useState({ x: 5, y: 4 })
const directionRef = useRef(direction)
const [gameOver, setgameOver] = useState(false)
function generateFood() {
let x = Math.floor(Math.random() * 20)
let y = Math.floor(Math.random() * 20)
setfood({ x, y })
}
useEffect(() => {
directionRef.current = direction
}, [direction])
useEffect(() => {
function keypress(e) {
if (e.key === 'ArrowUp') setdirection({ x: -1, y: 0 })
if (e.key === 'ArrowDown') setdirection({ x: 1, y: 0 })
if (e.key === 'ArrowRight') setdirection({ x: 0, y: 1 })
if (e.key === 'ArrowLeft') setdirection({ x: 0, y: -1 })
}
window.addEventListener('keydown', keypress);
return () => window.removeEventListener('keydown', keypress)
}, [])
useEffect(() => {
if (gameOver) return;
const interval = setInterval(() => {
setSnakeArr(prev => {
const head = prev[0];
const newHead = {
x: head.x + directionRef.current.x,
y: head.y + directionRef.current.y,
};
checkCollision(newHead, prev
)
const iseating = newHead.x === food.x && newHead.y === food.y;
if (iseating) {
generateFood()
return [newHead, ...prev];
}
else {
return [newHead, ...prev.slice(0, -1)];
}
});
}, 170);
return () => clearInterval(interval);
}, [direction, food]);
function checkCollision(head, snake) {
//wall collision
if (head.x < 0 || head.x >= 20 || head.y < 0 || head.y >= 20) {
setgameOver(true)
}
//snake collison
for (let i = 0; i < snake.length; i++) {
if (head.x == snake[i].x && head.y == snake[i].y) {
setgameOver(true)
}
}
}
return (
<div style={{position:"relative"}}>
<h1>Snake Game</h1>
<div className="controls">
<p>Score: {snakeArr.length}</p>
<button onClick={() => {
setSnakeArr([{ x: 6, y: 7 }]);
setfood({ x: 5, y: 4 });
setdirection({ x: 0, y: 1 });
setgameOver(false);
}}>Start New Game</button>
</div>
<div className="board">
{gameOver && (
<div className="game-over">
<h2>Game Over!</h2>
</div>
)}
{snakeArr.map((segment, index) => (
<div
key={index}
className="snake"
style={{
gridColumn: segment.y + 1, // grid is 1-indexed
gridRow: segment.x + 1,
}}
></div>
))}
<div
className="snake-food"
style={{
gridColumn: food.y + 1,
gridRow: food.x + 1,
}}
></div>
</div>
</div>
)
}
export default App;