Deepseek ArtifactsDeepseek Artifacts

打造太空入侵者游戏

4.0
en
编程与开发
游戏开发
编程教程
太空入侵者

Prompt

create a space invaders game

Generated Result

import React, { useState, useEffect, useRef } from 'react';
import './App.css';

const App = () => {
  const [playerPosition, setPlayerPosition] = useState(250);
  const [invaders, setInvaders] = useState([{ x: 50, y: 50 }, { x: 150, y: 50 }, { x: 250, y: 50 }]);
  const [bullets, setBullets] = useState([]);
  const gameAreaRef = useRef(null);

  useEffect(() => {
    const interval = setInterval(moveInvaders, 1000);
    return () => clearInterval(interval);
  }, [invaders]);

  const moveInvaders = () => {
    setInvaders(prevInvaders => prevInvaders.map(invader => ({ ...invader, y: invader.y + 10 })));
  };

  const movePlayer = (direction) => {
    const newPosition = direction === 'left' ? playerPosition - 10 : playerPosition + 10;
    if (newPosition >= 0 && newPosition <= 500) {
      setPlayerPosition(newPosition);
    }
  };

  const shootBullet = () => {
    setBullets(prevBullets => [...prevBullets, { x: playerPosition, y: 450 }]);
  };

  useEffect(() => {
    const interval = setInterval(() => {
      setBullets(prevBullets => prevBullets.map(bullet => ({ ...bullet, y: bullet.y - 10 })).filter(bullet => bullet.y > 0));
    }, 50);
    return () => clearInterval(interval);
  }, [bullets]);

  useEffect(() => {
    const handleKeyDown = (e) => {
      if (e.key === 'ArrowLeft') {
        movePlayer('left');
      } else if (e.key === 'ArrowRight') {
        movePlayer('right');
      } else if (e.key === ' ') {
        shootBullet();
      }
    };
    window.addEventListener('keydown', handleKeyDown);
    return () => window.removeEventListener('keydown', handleKeyDown);
  }, [playerPosition]);

  return (
    <div className='bg-black min-h-screen flex flex-col justify-center items-center' ref={gameAreaRef}>
      <div className='relative w-[500px] h-[500px] bg-gray-800 border-4 border-gray-700'>
        <div className='absolute w-[40px] h-[20px] bg-blue-500' style={{ bottom: '10px', left: `${playerPosition}px` }}></div>
        {invaders.map((invader, index) => (
          <div key={index} className='absolute w-[30px] h-[30px] bg-red-500' style={{ top: `${invader.y}px`, left: `${invader.x}px` }}></div>
        ))}
        {bullets.map((bullet, index) => (
          <div key={index} className='absolute w-[5px] h-[10px] bg-yellow-400' style={{ top: `${bullet.y}px`, left: `${bullet.x + 17}px` }}></div>
        ))}
      </div>
    </div>
  );
};

export default App;

More Recommendations

View All