Skip to content
TheChatArchiveThe Chat Archive
Coherecommand-a-03-2025· CohereHugging Face LMArena Human Preference 140K

snake game

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-3-5-haiku-20241022’s answer.
  1. User

    snake game

  2. Cohere Assistant

    The Snake game is a classic arcade game where the player controls a snake that grows longer as it eats food. The objective is to avoid collisions with the walls, the snake's own body, and sometimes other obstacles, while trying to eat as much food as possible to score points.

    Here’s a simple breakdown of how the game works and how you might implement it in Python using the pygame library:


    Game Elements

    1. Snake: A growing line of segments controlled by the player.
    2. Food: Randomly placed on the screen, which the snake eats to grow.
    3. Boundary: The edges of the game window, which the snake must not cross.
    4. Score: Increases as the snake eats food.

    Python Implementation with Pygame

    First, install pygame if you don't have it:

    pip install pygame
    

    Here’s a basic implementation:

    import pygame
    import time
    import random
    
    # Initialize Pygame
    pygame.init()
    
    # 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)
    
    # Display dimensions
    dis_width = 800
    dis_height = 600
    
    # Create the display
    dis = pygame.display.set_mode((dis_width, dis_height))
    pygame.display.set_caption('Snake Game')
    
    # Clock to control the speed
    clock = pygame.time.Clock()
    
    # Snake block size and speed
    snake_block = 10
    snake_speed = 15
    
    # Font styles
    font_style = pygame.font.SysFont("bahnschrift", 25)
    score_font = pygame.font.SysFont("comicsansms", 35)
    
    # Function to display the player's score
    def Your_score(score):
        value = score_font.render("Your Score: " + str(score), True, yellow)
        dis.blit(value, [0, 0])
    
    # Function to draw the snake
    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])
    
    # Function to display messages on the screen
    def message(msg, color):
        mesg = font_style.render(msg, True, color)
        dis.blit(mesg, [dis_width / 6, dis_height / 3])
    
    # Main game loop
    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)
                Your_score(Length_of_snake - 1)
                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)
            Your_score(Length_of_snake - 1)
    
            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()
    
    # Start the game
    gameLoop()
    

    How It Works

    1. Snake Movement: The snake moves in response to arrow key inputs.
    2. Food: When the snake eats the food, it grows longer, and the food reappears in a random location.
    3. Collision Detection: The game ends if the snake collides with the boundary or itself.
    4. Score: The score increases with each piece of food eaten.

    Extensions

    • Add obstacles.
    • Increase speed as the score increases.
    • Add a high-score system.
    • Customize graphics and sounds.

    Let me know if you'd like help with any of these features!

  3. User

    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.

    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.

  4. Cohere Assistant
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <title>Snake Game</title>
      <style>
        :root {
          --primary-color: #3498db;
          --secondary-color: #2ecc71;
          --background-color: #ecf0f1;
          --text-color: #2c3e50;
          --accent-color: #e74c3c;
        }
    
        * {
          box-sizing: border-box;
          margin: 0;
          padding: 0;
        }
    
        body {
          font-family: 'Arial', sans-serif;
          background-color: var(--background-color);
          color: var(--text-color);
          display: flex;
          flex-direction: column;
          align-items: center;
          justify-content: center;
          height: 100vh;
          margin: 0;
        }
    
        #game-container {
          position: relative;
          width: 90vw;
          max-width: 600px;
          height: 90vw;
          max-height: 600px;
          background-color: #fff;
          border-radius: 1rem;
          box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
          overflow: hidden;
        }
    
        canvas {
          display: block;
          width: 100%;
          height: 100%;
        }
    
        #score {
          position: absolute;
          top: 1rem;
          left: 1rem;
          font-size: 1.5rem;
          color: var(--secondary-color);
        }
    
        #game-over {
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);
          text-align: center;
          display: none;
        }
    
        #game-over h2 {
          font-size: 2rem;
          color: var(--accent-color);
        }
    
        #restart-button {
          margin-top: 1rem;
          padding: 0.75rem 1.5rem;
          font-size: 1rem;
          color: #fff;
          background-color: var(--primary-color);
          border: none;
          border-radius: 0.5rem;
          cursor: pointer;
          transition: background-color 0.3s ease;
        }
    
        #restart-button:hover {
          background-color: var(--secondary-color);
        }
    
        @media (max-width: 600px) {
          #game-container {
            width: 95vw;
            height: 95vw;
          }
        }
      </style>
    </head>
    <body>
      <div id="game-container">
        <div id="score">Score: 0</div>
        <div id="game-over">
          <h2>Game Over!</h2>
          <button id="restart-button">Restart</button>
        </div>
        <canvas id="gameCanvas"></canvas>
      </div>
    
      <script>
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        const scoreElement = document.getElementById('score');
        const gameOverElement = document.getElementById('game-over');
        const restartButton = document.getElementById('restart-button');
    
        const gridSize = 20;
        const tileCount = canvas.width / gridSize;
    
        let snake = [{ x: 10, y: 10 }];
        let direction = { x: 0, y: 0 };
        let food = { x: 15, y: 15 };
        let score = 0;
        let gameSpeed = 100;
        let gameInterval;
    
        function draw() {
          ctx.clearRect(0, 0, canvas.width, canvas.height);
    
          // Draw snake
          ctx.fillStyle = '#3498db';
          snake.forEach(segment => {
            ctx.fillRect(segment.x * gridSize, segment.y * gridSize, gridSize, gridSize);
          });
    
          // Draw food
          ctx.fillStyle = '#e74c3c';
          ctx.fillRect(food.x * gridSize, food.y * gridSize, gridSize, gridSize);
        }
    
        function move() {
          const head = { x: snake[0].x + direction.x, y: snake[0].y + direction.y };
    
          // Collision detection
          if (head.x < 0 || head.x >= tileCount || head.y < 0 || head.y >= tileCount || snake.some(segment => segment.x === head.x && segment.y === head.y)) {
            clearInterval(gameInterval);
            gameOverElement.style.display = 'block';
            return;
          }
    
          snake.unshift(head);
    
          // Eat food
          if (head.x === food.x && head.y === food.y) {
            score += 10;
            scoreElement.textContent = `Score: ${score}`;
            placeFood();
          } else {
            snake.pop();
          }
        }
    
        function placeFood() {
          food = {
            x: Math.floor(Math.random() * tileCount),
            y: Math.floor(Math.random() * tileCount)
          };
        }
    
        function startGame() {
          snake = [{ x: 10, y: 10 }];
          direction = { x: 0, y: 0 };
          score = 0;
          scoreElement.textContent = `Score: ${score}`;
          gameOverElement.style.display = 'none';
          placeFood();
          gameInterval = setInterval(() => {
            move();
            draw();
          }, gameSpeed);
        }
    
        // Keyboard controls
        document.addEventListener('keydown', event => {
          switch (event.key) {
            case 'ArrowUp':
              if (direction.y === 0) direction = { x: 0, y: -1 };
              break;
            case 'ArrowDown':
              if (direction.y === 0) direction = { x: 0, y: 1 };
              break;
            case 'ArrowLeft':
              if (direction.x === 0) direction = { x: -1, y: 0 };
              break;
            case 'ArrowRight':
              if (direction.x === 0) direction = { x: 1, y: 0 };
              break;
          }
        });
    
        // Restart button
        restartButton.addEventListener('click', startGame);
    
        // Creative Enhancement: Add a dark mode toggle
        const darkModeToggle = document.createElement('button');
        darkModeToggle.textContent = 'Toggle Dark Mode';
        darkModeToggle.style.position = 'absolute';
        darkModeToggle.style.top = '1rem';
        darkModeToggle.style.right = '1rem';
        darkModeToggle.style.padding = '0.5rem 1rem';
        darkModeToggle.style.fontSize = '0.9rem';
        darkModeToggle.style.color = '#fff';
        darkModeToggle.style.backgroundColor = '#34495e';
        darkModeToggle.style.border = 'none';
        darkModeToggle.style.borderRadius = '0.5rem';
        darkModeToggle.style.cursor = 'pointer';
        document.body.appendChild(darkModeToggle);
    
        let isDarkMode = false;
        darkModeToggle.addEventListener('click', () => {
          isDarkMode = !isDarkMode;
          document.documentElement.style.setProperty('--background-color', isDarkMode ? '#2c3e50' : '#ecf0f1');
          document.documentElement.style.setProperty('--text-color', isDarkMode ? '#ecf0f1' : '#2c3e50');
          darkModeToggle.style.backgroundColor = isDarkMode ? '#2c3e50' : '#34495e';
        });
    
        // Initialize game
        canvas.width = canvas.clientWidth;
        canvas.height = canvas.clientHeight;
        startGame();
      </script>
    </body>
    </html>
    

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.