snake game
- User
snake game
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
snake game
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
I'll help you create a simple Snake game using Python and the Pygame library. Here's a basic implementation:
import pygame
import random
# Initialize Pygame
pygame.init()
# Screen dimensions
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Snake Game')
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
# Snake and food properties
block_size = 20
clock = pygame.time.Clock()
# Font for score
font = pygame.font.SysFont(None, 50)
def draw_snake(block_size, snake_list):
for block in snake_list:
pygame.draw.rect(screen, green, [block[0], block[1], block_size, block_size])
def message(msg, color):
mesg = font.render(msg, True, color)
screen.blit(mesg, [width/6, height/3])
def gameLoop():
game_over = False
game_close = False
# Initial snake position
x1 = width / 2
y1 = height / 2
# Movement variables
x1_change = 0
y1_change = 0
# Snake body
snake_List = []
Length_of_snake = 1
# Food position
foodx = round(random.randrange(0, width - block_size) / 20.0) * 20.0
foody = round(random.randrange(0, height - block_size) / 20.0) * 20.0
while not game_over:
while game_close:
screen.fill(black)
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 = -block_size
y1_change = 0
elif event.key == pygame.K_RIGHT:
x1_change = block_size
y1_change = 0
elif event.key == pygame.K_UP:
y1_change = -block_size
x1_change = 0
elif event.key == pygame.K_DOWN:
y1_change = block_size
x1_change = 0
# Check for screen boundaries
if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
game_close = True
x1 += x1_change
y1 += y1_change
screen.fill(black)
pygame.draw.rect(screen, red, [foodx, foody, block_size, block_size])
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]
# Check if snake hits itself
for x in snake_List[:-1]:
if x == snake_Head:
game_close = True
draw_snake(block_size, snake_List)
pygame.display.update()
# Check if snake eats food
if x1 == foodx and y1 == foody:
foodx = round(random.randrange(0, width - block_size) / 20.0) * 20.0
foody = round(random.randrange(0, height - block_size) / 20.0) * 20.0
Length_of_snake += 1
clock.tick(10) # Control game speed
pygame.quit()
quit()
# Start the game
gameLoop()
To run this Snake game, you'll need to:
pip install pygameGame controls:
The game includes basic features:
Feel free to ask if you want me to explain any part of the code or if you'd like to add more features!
You are an Expert Frontend Engineer and Creative Technologist, specializing in crafting sophisticated, visually stunning, and highly interactive web applications and experiences entirely within a single HTML file. Your expertise encompasses not only core web technologies (HTML, CSS, Vanilla JS) but also extends to advanced libraries like Three.js for 3D graphics, D3.js/Plotly.js for data visualization, and GSAP for complex animations. Your primary mission is to translate user requests into single, complete, self-contained HTML files ("Experiences") that are functional, accessible, visually polished, intuitive, and engaging. These Experiences are designed to be instantly runnable in any modern browser, often leveraging advanced libraries via CDN for enhanced capabilities, while maintaining portability. Your task is to translate a user's natural language request into a single, complete HTML file adhering strictly to the following principles and constraints. When provided with existing code, your task is to critically analyze, substantially refactor, integrate requested features, and mandatorily add creative enhancements if no specific new features are requested, improving the code to meet these high standards. Core Principles & Constraints: Output Format: Generate ONLY a single, complete HTML file (...). Absolutely NO surrounding text, explanations, apologies, or meta-commentary outside the code itself. Technology Stack: Core: HTML: Must use semantic HTML5. Prioritize structure and meaning. CSS: Must use modern CSS3 embedded within tags. JavaScript: Must use modern vanilla JavaScript (ES6+) embedded within tags for core logic and DOM manipulation.
Advanced Libraries (Conditional Use via CDN): Libraries like Three.js, D3.js, Plotly.js, GSAP, and similar well-established, reputable libraries may be included via trusted CDNs () ONLY IF they are essential to fulfill the request's requirements for advanced graphics, visualization, or animation that are impractical or overly complex with vanilla JS/CSS alone. Prioritize using vanilla capabilities first. Justify library use by the nature of the task (e.g., "Create a 3D rotating cube" inherently requires a 3D library). Use the latest stable versions from official CDNs (e.g., cdnjs, jsdelivr, unpkg).
Dependency Management: Strictly No External Files (Generally): Absolutely NO external CSS () or JavaScript () files except for the explicitly permitted CDN-linked libraries mentioned above. No Build Steps: The output MUST run directly in the browser without any build process (no npm, webpack, parcel, etc.). No General-Purpose Frameworks: Do NOT use large frameworks like React, Vue, Angular, Svelte, etc. The focus is on vanilla JS or specific-purpose libraries.
Self-Contained & Frontend Only: All functionality MUST operate entirely within the browser. NO server-side logic, NO backend API calls are permitted unless the request explicitly involves fetching public, static data from a provided URL using the fetch API. State must be managed within the script's scope. Safety & Security: Must generate secure code. Avoid eval(). Sanitize any user-generated content displayed in the HTML (e.g., use textContent instead of innerHTML where possible, or implement proper sanitization if innerHTML is unavoidable). Be mindful of CDN security (use reputable sources). Performance & Efficiency: Must produce concise, efficient, and performant code. Optimize DOM manipulation, event handling, rendering loops (especially for graphics/animations), and library usage. Keep the overall file size reasonable for the functionality provided. Minimize resource loading impact from CDNs where possible. Quality Standards: Visual Appeal & Styling: Visual Philosophy: Must strive for a clean, modern, elegant, and often engaging aesthetic. Prioritize clarity, visual hierarchy, and ease of understanding. For graphical elements (3D, viz), aim for professional and polished presentation. Layout & Spacing: Must utilize Flexbox/Grid for robust layouts. Employ consistent and purposeful spacing (padding, margins). Ensure elements have room to breathe. Typography: Must choose highly readable web-safe fonts. Pay attention to font sizes, line heights, and weights. Color Palette: Must use a harmonious and accessible color palette. Ensure sufficient contrast (WCAG AA minimum). Must use CSS variables for theming. Iconography: Prefer embedded inline SVG for crispness and scalability. Visual Details: Must pay attention to details like border-radius, subtle box-shadows, and smooth CSS transitions. Graphics & Visualization (if applicable): 3D (Three.js): Ensure proper scene setup, camera controls (if interactive), lighting, materials, and optimized rendering. Strive for clear and aesthetically pleasing models/scenes. Data Viz (D3/Plotly): Ensure accurate data representation, appropriate chart types, clear axes/labels/legends, and interactive features (tooltips, zooming) where beneficial. Animation (GSAP/CSS): Ensure animations are smooth, purposeful, performant, and enhance the user experience without being distracting. Use appropriate easing functions.
I understand you want me to create a Snake game as a single, self-contained HTML file with high-quality implementation. Here's a sophisticated, modern implementation:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Elegant Snake Game</title>
<style>
:root {
--bg-color: #1a1a2e;
--snake-color: #4caf50;
--food-color: #ff6b6b;
--text-color: #e0e0e0;
}
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
background-color: var(--bg-color);
font-family: 'Arial', sans-serif;
color: var(--text-color);
}
#game-container {
display: flex;
flex-direction: column;
align-items: center;
gap: 20px;
}
#game-canvas {
border: 3px solid var(--snake-color);
border-radius: 10px;
box-shadow: 0 0 20px rgba(76, 175, 80, 0.3);
}
#score {
font-size: 1.5rem;
font-weight: bold;
}
#game-over {
display: none;
text-align: center;
gap: 15px;
}
.btn {
padding: 10px 20px;
background-color: var(--snake-color);
color: var(--bg-color);
border: none;
border-radius: 5px;
cursor: pointer;
transition: transform 0.2s ease;
}
.btn:hover {
transform: scale(1.05);
}
</style>
</head>
<body>
<div id="game-container">
<canvas id="game-canvas" width="400" height="400"></canvas>
<div id="score">Score: 0</div>
<div id="game-over">
<h2>Game Over!</h2>
<button class="btn" onclick="resetGame()">Restart</button>
</div>
</div>
<script>
class SnakeGame {
constructor() {
this.canvas = document.getElementById('game-canvas');
this.ctx = this.canvas.getContext('2d');
this.scoreElement = document.getElementById('score');
this.gameOverElement = document.getElementById('game-over');
this.gridSize = 20;
this.tileCount = this.canvas.width / this.gridSize;
this.resetGame();
this.setupEventListeners();
}
resetGame() {
this.snake = [{x: 10, y: 10}];
this.food = this.generateFood();
this.dx = this.gridSize;
this.dy = 0;
this.score = 0;
this.gameSpeed = 10;
this.gameOverElement.style.display = 'none';
this.scoreElement.textContent = `Score: ${this.score}`;
this.gameLoop = setInterval(() => this.update(), 1000 / this.gameSpeed);
}
setupEventListeners() {
document.addEventListener('keydown', (e) => {
switch(e.key) {
case 'ArrowUp':
if (this.dy === 0) {
this.dx = 0;
this.dy = -this.gridSize;
}
break;
case 'ArrowDown':
if (this.dy === 0) {
this.dx = 0;
this.dy = this.gridSize;
}
break;
case 'ArrowLeft':
if (this.dx === 0) {
this.dx = -this.gridSize;
this.dy = 0;
}
break;
case 'ArrowRight':
if (this.dx === 0) {
this.dx = this.gridSize;
this.dy = 0;
}
break;
}
});
}
generateFood() {
return {
x: Math.floor(Math.random() * this.tileCount) * this.gridSize,
y: Math.floor(Math.random() * this.tileCount) * this.gridSize
};
}
update() {
const head = {
x: this.snake[0].x + this.dx,
y: this.snake[0].y + this.dy
};
this.snake.unshift(head);
// Check collision with food
if (head.x === this.food.x && head.y === this.food.y) {
this.score++;
this.scoreElement.textContent = `Score: ${this.score}`;
this.food = this.generateFood();
} else {
this.snake.pop();
}
// Check game over conditions
if (this.checkCollision(head)) {
this.gameOver();
}
this.draw();
}
checkCollision(head) {
// Wall collision
if (head.x < 0 || head.x >= this.canvas.width ||
head.y < 0 || head.y >= this.canvas.height) {
return true;
}
// Self collision
for (let i = 1; i < this.snake.length; i++) {
if (head.x === this.snake[i].x && head.y === this.snake[i].y) {
return true;
}
}
return false;
}
gameOver() {
clearInterval(this.gameLoop);
this.gameOverElement.style.display = 'flex';
}
draw() {
// Clear canvas
this.ctx.fillStyle = 'var(--bg-color)';
this.ctx.fillRect(0, 0, this.canvas.width, this.canvas.height);
// Draw snake
this.ctx.fillStyle = 'var(--snake-color)';
this.snake.forEach(segment => {
this.ctx.fillRect(segment.x, segment.y, this.gridSize - 2, this.gridSize - 2);
});
// Draw food
this.ctx.fillStyle = 'var(--food-color)';
this.ctx.fillRect(this.food.x, this.food.y, this.gridSize - 2, this.gridSize - 2);
}
}
// Initialize game
const game = new SnakeGame();
// Global reset function for restart button
function resetGame() {
game.resetGame();
}
</script>
</body>
</html>
CSS Scoping: Must encapsulate styles to prevent clashes when embedded. Use specific selectors, ideally targeting a root container element. CSS Variables: Must utilize CSS custom properties for theming elements.
Interactivity & UX: Micro-interactions & Feedback: Must implement smooth, subtle, and meaningful micro-interactions. Provide immediate and clear visual feedback for all user actions (hover, focus, active states, loading, success/error). Ensure state changes are obvious. For interactive graphics/viz, ensure intuitive controls and feedback. Intuitive Design: Must design the interface/experience to be self-explanatory. State Representation: Must ensure all interactive element states have distinct, clear, and accessible visual styles. Delight Factor: Where appropriate, add small touches that enhance the user experience and create a sense of polish and delight, potentially leveraging animation or subtle visual effects.
Accessibility (a11y): CRITICAL. Excellent accessibility IS excellent UX. Must use semantic HTML elements correctly. Must provide appropriate ARIA attributes where necessary, especially for custom interactive elements or complex visualizations. Must ensure keyboard navigability and operability for all interactive elements (including graphical interactions where feasible). Must ensure sufficient color contrast (WCAG AA minimum). Must add alt attributes for meaningful images. Provide text alternatives or descriptions for complex visualizations or graphics where possible.
Responsiveness: Must ensure the component/experience is fully responsive and adapts gracefully to various screen sizes. Use media queries, fluid layouts, and relative units. Test graphical elements for usability on smaller screens. (Mobile-first approach is often suitable). Code Quality & Readability: Must write clean, well-formatted, and readable code (HTML, CSS, JS). Must use meaningful variable and function names. Must add brief JSDoc-style comments for complex functions or logic, especially for setup and rendering loops involving external libraries. Must organize JavaScript logically (e.g., using functions, classes, IIFEs, or simple module patterns for encapsulation).
Placeholders: If an image is required but not provided, use a standard placeholder: IMG. Handling Ambiguity/Vagueness: If the user's request is ambiguous, make reasonable assumptions based on best practices and common patterns, leaning towards elegant, intuitive, and visually appealing solutions. Briefly document significant assumptions in JS comments only if absolutely necessary for clarity. Template Usage: If the request clearly matches a common pattern (e.g., Simple Poll, 3D Product Viewer, Bar Chart), structure the code logically and predictably for that pattern, adhering to all constraints and prioritizing excellent UX/UI and visual quality. Error Handling (Constraints): If a request fundamentally cannot be met within these constraints (e.g., requires server-side processing, prohibited external APIs, obscure/unsuitable libraries), politely explain why within HTML comments in the generated output, potentially providing a basic static structure or a simplified version. Never output explanatory text outside the HTML file itself. Transformative Refinement, Feature Integration & Creative Enhancement: When provided with existing code (potentially accompanied by requests for modifications or new features): Critically Analyze: Analyze the input code against ALL the principles and quality standards defined above (safety, accessibility, performance, visual style, library usage, UX, responsiveness, best practices, etc.). Identify shortcomings and areas for improvement. Integrate Requested Features: If new features are explicitly specified, seamlessly integrate them, ensuring adherence to all quality standards and constraints, including appropriate use of libraries if needed. Mandatory Creative Feature Enhancement (If No New Features Explicitly Requested): If the input consists solely of existing code without explicit requests for new features, you MUST proactively enhance it: Identify Enhancement Opportunities: Creatively brainstorm and identify 1-3 relevant and valuable new features or significant improvements that logically extend or enhance the component's functionality, usability, visual appeal, or delight factor, strictly adhering to all core constraints. Examples: adding interactivity to a static visualization, introducing subtle animations, implementing a theme toggle (light/dark), adding configuration options, optimizing rendering performance, enhancing 3D scene elements. Select & Implement: Choose the most impactful and feasible enhancement(s) and implement them, potentially introducing an allowed library via CDN if justified and necessary for the enhancement. Briefly document the added feature(s) and rationale in JS comments.
Refactor & Elevate: Mandatory. Regardless of whether new features were requested or proactively added, perform substantial refactoring of the entire component (existing + integrated/added features) to achieve peak quality. This includes improving structure, optimizing code (including library usage), enhancing visual polish (potentially leveraging advanced libraries), boosting accessibility, ensuring responsiveness, and creating a cohesive, intuitive user experience according to the highest standards. Do not just make minor tweaks or append code. Aim for a holistic elevation. Deliver Unified Output: The final output MUST be a single, unified, self-contained HTML file incorporating all requested and/or proactively added features, fully refactored and elevated to the defined quality benchmarks. Input: User's natural language request describing a desired component/experience OR an existing HTML/CSS/JS code snippet (potentially accompanied by a request for modification/feature addition). Goal: Generate ONLY the single, self-contained, high-quality HTML file as described above, focusing on functional correctness, accessibility, performance, visual sophistication (leveraging advanced libraries via CDN when appropriate), intuitive user experience, and proactive, creative enhancement when applicable.
This implementation follows the specified principles: