Skip to content
TheChatArchiveThe Chat Archive
o1-preview-2024-09-12· OpenAIAi2 WildChat-4.8M (AI2)

Write a code in Python that implements a game "Spacewar!" 1962

  1. User

    Write a code in Python that implements a game "Spacewar!" 1962

  2. Assistant

    Here's a Python implementation of the classic "Spacewar!" game from 1962 using the pygame library. This code simulates two spaceships battling each other in space, influenced by the gravitational pull of a central star.

    import pygame
    import math
    import sys
    
    # Initialize Pygame
    pygame.init()
    
    # Set up display
    WIDTH, HEIGHT = 800, 600
    screen = pygame.display.set_mode((WIDTH, HEIGHT))
    pygame.display.set_caption("Spacewar! 1962")
    
    # Clock to control frame rate
    clock = pygame.time.Clock()
    
    # Colors
    BLACK = (0, 0, 0)
    WHITE = (255, 255, 255)
    
    # Star parameters
    STAR_POS = (WIDTH // 2, HEIGHT // 2)
    STAR_RADIUS = 30
    STAR_MASS = 5000  # Adjust gravity strength
    
    # Ship parameters
    SHIP_SIZE = 10
    SHIP_THRUST = 0.2
    SHIP_ROTATE_SPEED = 5  # degrees per frame
    SHIP_MAX_SPEED = 5
    
    # Missile parameters
    MISSILE_SPEED = 7
    MISSILE_LIFE = 60  # frames
    
    # Define Ship class
    class Ship:
        def __init__(self, x, y, angle, color, controls):
            self.x = x
            self.y = y
            self.angle = angle  # in degrees
            self.vx = 0
            self.vy = 0
            self.color = color
            self.controls = controls  # Dict with 'left', 'right', 'thrust', 'fire'
            self.missiles = []
            self.respawn()
    
        def respawn(self):
            self.x = random.randint(100, WIDTH - 100)
            self.y = random.randint(100, HEIGHT - 100)
            self.angle = random.randint(0, 360)
            self.vx = 0
            self.vy = 0
            self.missiles = []
    
        def update(self, keys_pressed):
            # Handle rotation
            if keys_pressed[self.controls['left']]:
                self.angle = (self.angle - SHIP_ROTATE_SPEED) % 360
            if keys_pressed[self.controls['right']]:
                self.angle = (self.angle + SHIP_ROTATE_SPEED) % 360
    
            # Handle thrust
            if keys_pressed[self.controls['thrust']]:
                rad = math.radians(self.angle)
                self.vx += SHIP_THRUST * math.cos(rad)
                self.vy += SHIP_THRUST * math.sin(rad)
                # Limit speed
                speed = math.hypot(self.vx, self.vy)
                if speed > SHIP_MAX_SPEED:
                    scale = SHIP_MAX_SPEED / speed
                    self.vx *= scale
                    self.vy *= scale
    
            # Apply gravity from the star
            dx = STAR_POS[0] - self.x
            dy = STAR_POS[1] - self.y
            dist = math.hypot(dx, dy)
            if dist > STAR_RADIUS:
                force = STAR_MASS / (dist ** 2)
                angle_to_star = math.atan2(dy, dx)
                self.vx += force * math.cos(angle_to_star)
                self.vy += force * math.sin(angle_to_star)
            else:
                # Ship has crashed into the star
                self.respawn()
    
            # Update position
            self.x += self.vx
            self.y += self.vy
    
            # Screen wrap-around
            self.x %= WIDTH
            self.y %= HEIGHT
    
            # Fire missile
            if keys_pressed[self.controls['fire']]:
                if len(self.missiles) < 3:  # Limit number of missiles on screen
                    self.fire_missile()
    
            # Update missiles
            for missile in self.missiles[:]:
                missile.update()
                if missile.life <= 0:
                    self.missiles.remove(missile)
    
        def fire_missile(self):
            rad = math.radians(self.angle)
            mx = self.x + SHIP_SIZE * math.cos(rad)
            my = self.y + SHIP_SIZE * math.sin(rad)
            mvx = self.vx + MISSILE_SPEED * math.cos(rad)
            mvy = self.vy + MISSILE_SPEED * math.sin(rad)
            missile = Missile(mx, my, mvx, mvy)
            self.missiles.append(missile)
    
        def draw(self, surface):
            # Draw ship as a triangle
            rad = math.radians(self.angle)
            point1 = (self.x + SHIP_SIZE * math.cos(rad),
                      self.y + SHIP_SIZE * math.sin(rad))
            rad_left = math.radians(self.angle + 140)
            point2 = (self.x + SHIP_SIZE * math.cos(rad_left),
                      self.y + SHIP_SIZE * math.sin(rad_left))
            rad_right = math.radians(self.angle - 140)
            point3 = (self.x + SHIP_SIZE * math.cos(rad_right),
                      self.y + SHIP_SIZE * math.sin(rad_right))
            pygame.draw.polygon(surface, self.color, [point1, point2, point3])
    
            # Draw missiles
            for missile in self.missiles:
                missile.draw(surface)
    
    # Define Missile class
    class Missile:
        def __init__(self, x, y, vx, vy):
            self.x = x
            self.y = y
            self.vx = vx
            self.vy = vy
            self.life = MISSILE_LIFE
    
        def update(self):
            self.x += self.vx
            self.y += self.vy
            self.x %= WIDTH
            self.y %= HEIGHT
            self.life -= 1
    
        def draw(self, surface):
            pygame.draw.circle(surface, WHITE, (int(self.x), int(self.y)), 2)
    
    # Set up ships
    ship1_controls = {'left': pygame.K_a, 'right': pygame.K_d, 'thrust': pygame.K_w, 'fire': pygame.K_SPACE}
    ship2_controls = {'left': pygame.K_LEFT, 'right': pygame.K_RIGHT, 'thrust': pygame.K_UP, 'fire': pygame.K_RETURN}
    
    ship1 = Ship(WIDTH // 4, HEIGHT // 2, 0, (0, 255, 0), ship1_controls)
    ship2 = Ship(3 * WIDTH // 4, HEIGHT // 2, 180, (0, 0, 255), ship2_controls)
    
    # Main game loop
    running = True
    while running:
        clock.tick(60)  # 60 FPS
    
        # Event handling
        keys_pressed = pygame.key.get_pressed()
    
        for event in pygame.event.get():
            if event.type == pygame.QUIT or keys_pressed[pygame.K_ESCAPE]:
                running = False
    
        # Update game objects
        ship1.update(keys_pressed)
        ship2.update(keys_pressed)
    
        # Check for missile collisions
        for missile in ship1.missiles:
            if math.hypot(missile.x - ship2.x, missile.y - ship2.y) < SHIP_SIZE:
                ship2.respawn()
                ship1.missiles.remove(missile)
                break
    
        for missile in ship2.missiles:
            if math.hypot(missile.x - ship1.x, missile.y - ship1.y) < SHIP_SIZE:
                ship1.respawn()
                ship2.missiles.remove(missile)
                break
    
        # Draw everything
        screen.fill(BLACK)
    
        # Draw star
        pygame.draw.circle(screen, WHITE, STAR_POS, STAR_RADIUS)
    
        ship1.draw(screen)
        ship2.draw(screen)
    
        pygame.display.flip()
    
    pygame.quit()
    sys.exit()
    

    Instructions:

    1. Install Pygame: Ensure you have Pygame installed. You can install it using pip:

      pip install pygame
      
    2. Run the Script: Save the code to a file named spacewar.py (or any name you prefer) and run it using Python 3:

      python spacewar.py
      

    Controls:

    • Player 1 (Green Ship):

      • Rotate Left: A key
      • Rotate Right: D key
      • Thrust: W key
      • Fire: Space bar
    • Player 2 (Blue Ship):

      • Rotate Left: Left Arrow key
      • Rotate Right: Right Arrow key
      • Thrust: Up Arrow key
      • Fire: Enter key

    Game Features:

    • Spaceships: Each player controls a spaceship that can rotate, thrust forward, and fire missiles.
    • Gravity: A central star exerts gravitational force on the ships. Ships must avoid crashing into the star.
    • Missiles: Ships can fire missiles to destroy the opponent. Each missile has a limited lifespan.
    • Collision Detection: If a missile hits the opponent's ship, the hit ship respawns at a random location.
    • Screen Wrap-Around: Ships and missiles that move off one edge of the screen reappear on the opposite side.
    • Respawning: When ships crash into the star or are hit by a missile, they respawn at a new random position.

    Notes:

    • The game aims to capture the essence of the original "Spacewar!" game, providing a simple yet engaging experience.
    • This is a basic implementation and can be enhanced with additional features such as scoring, improved graphics, sound effects, and more.
    • Feel free to modify and expand the code to add new functionalities or improve gameplay.

    Enjoy battling among the stars!