make a code snake game
- User
make a code snake game
- Assistant
- User
in react
- Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
make a code snake game
in react
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Creating a simple Snake game can be a fun way to practice your programming skills. Below, I'll provide a basic implementation of the Snake game using Python and the pygame library. Before you run the code, make sure you have pygame installed. You can install it using pip:
pip install pygame
Here's the code for a simple Snake game:
import pygame
import time
import random
pygame.init()
# Define colors
white = (255, 255, 255)
yellow = (255, 255, 102)
black = (0, 0, 0)
red = (213, 50, 80)
green = (0, 255, 0)
blue = (50, 153, 213)
# Window size
dis_width = 800
dis_height = 600
# Create the game window
dis = pygame.display.set_mode((dis_width, dis_height))
pygame.display.set_caption('Snake Game by OpenAI')
# Game settings
clock = pygame.time.Clock()
snake_block = 10
snake_speed = 15
# Fonts
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)
def our_snake(snake_block, snake_list):
for x in snake_list:
pygame.draw.rect(dis, black, [x[0], x[1], snake_block, snake_block])
def message(msg, color):
mesg = font_style.render(msg, True, color)
dis.blit(mesg, [dis_width / 6, dis_height / 3])
def gameLoop():
game_over = False
game_close = False
x1 = dis_width / 2
y1 = dis_height / 2
x1_change = 0
y1_change = 0
snake_List = []
Length_of_snake = 1
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
while not game_over:
while game_close == True:
dis.fill(blue)
message("You Lost! Press Q-Quit or C-Play Again", red)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
game_over = True
game_close = False
if event.key == pygame.K_c:
gameLoop()
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x1_change = -snake_block
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = snake_block
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -snake_block
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = snake_block
x1_change = 0
if x1 >= dis_width or x1 < 0 or y1 >= dis_height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
dis.fill(blue)
pygame.draw.rect(dis, green, [foodx, foody, snake_block, snake_block])
snake_Head = []
snake_Head.append(x1)
snake_Head.append(y1)
snake_List.append(snake_Head)
if len(snake_List) > Length_of_snake:
del snake_List[0]
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
our_snake(snake_block, snake_List)
pygame.display.update()
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, dis_width - snake_block) / 10.0) * 10.0
foody = round(random.randrange(0, dis_height - snake_block) / 10.0) * 10.0
Length_of_snake += 1
clock.tick(snake_speed)
pygame.quit()
quit()
gameLoop()
Here are a few things the code does:
pygame where the game will run.Feel free to modify the code, improve it, or add new features such as score tracking or different levels. Enjoy playing and coding!
Creating a Snake game using React involves setting up a React application and managing the game's state and rendering logic. Here’s a simple version of the Snake game implemented with React:
First, ensure you have Node.js and npm installed, then create a new React app if you haven't already:
npx create-react-app snake-game
cd snake-game
Once the project is set up, you can replace the contents of src/App.js with the following code:
import React, { useState, useEffect, useRef } from 'react';
import './App.css';
const CANVAS_SIZE = [800, 600];
const SNAKE_START = [
[8, 7],
[8, 8],
];
const APPLE_START = [8, 3];
const SCALE = 20;
const SPEED = 100;
const DIRECTIONS = {
ArrowUp: [0, -1],
ArrowDown: [0, 1],
ArrowLeft: [-1, 0],
ArrowRight: [1, 0],
};
function App() {
const canvasRef = useRef();
const [snake, setSnake] = useState(SNAKE_START);
const [apple, setApple] = useState(APPLE_START);
const [direction, setDirection] = useState([0, -1]);
const [speed, setSpeed] = useState(null);
const [gameOver, setGameOver] = useState(false);
useEffect(() => {
const handleKeyDown = (e) => {
if (DIRECTIONS[e.key]) {
setDirection(DIRECTIONS[e.key]);
}
};
window.addEventListener('keydown', handleKeyDown);
return () => window.removeEventListener('keydown', handleKeyDown);
}, []);
useEffect(() => {
if (speed && !gameOver) {
const gameLoop = setInterval(() => {
moveSnake();
}, speed);
return () => clearInterval(gameLoop);
}
}, [snake, speed, gameOver]);
const startGame = () => {
setSnake(SNAKE_START);
setApple(APPLE_START);
setDirection([1, 0]);
setSpeed(SPEED);
setGameOver(false);
};
const moveSnake = () => {
const newSnake = JSON.parse(JSON.stringify(snake));
const newHead = [
newSnake[0][0] + direction[0],
newSnake[0][1] + direction[1],
];
newSnake.unshift(newHead);
if (checkCollision(newHead)) {
setSpeed(null);
setGameOver(true);
return;
}
if (!checkAppleCollision(newSnake)) {
newSnake.pop();
}
setSnake(newSnake);
};
const checkCollision = (piece, newSnake = snake) => {
if (
piece[0] * SCALE >= CANVAS_SIZE[0] ||
piece[0] < 0 ||
piece[1] * SCALE >= CANVAS_SIZE[1] ||
piece[1] < 0
) {
return true;
}
for (const segment of newSnake) {
if (piece[0] === segment[0] && piece[1] === segment[1]) {
return true;
}
}
return false;
};
const checkAppleCollision = (newSnake) => {
if (newSnake[0][0] === apple[0] && newSnake[0][1] === apple[1]) {
let newApple = apple;
while (newSnake.some((segment) => segment[0] === newApple[0] && segment[1] === newApple[1])) {
newApple = [
Math.floor((Math.random() * CANVAS_SIZE[0]) / SCALE),
Math.floor((Math.random() * CANVAS_SIZE[1]) / SCALE),
];
}
setApple(newApple);
return true;
}
return false;
};
return (
<div className="App">
<button onClick={startGame}>Start</button>
{gameOver && <div>GAME OVER!</div>}
<canvas
ref={canvasRef}
style={{ border: '1px solid black' }}
width={`${CANVAS_SIZE[0]}px`}
height={`${CANVAS_SIZE[1]}px`}
/>
<div>
<p>Use the arrow keys to move the snake.</p>
</div>
</div>
);
}
export default App;
Next, replace the contents of src/App.css to give your game some basic styles:
.App {
display: flex;
justify-content: center;
align-items: center;
flex-direction: column;
height: 100vh;
background-color: #282c34;
color: white;
}
button {
margin-bottom: 20px;
padding: 10px 20px;
font-size: 16px;
}
direction state, which is updated via keyboard events.SCALE to fit the canvas.Navigate to your project directory and start the development server:
npm start
This will open a new browser window with your React Snake game. You can control the snake using the arrow keys. Enjoy customizing and enhancing your game!