본문 바로가기

Python/Game

🌟 파이썬으로 만든 아케이드 게임: "별을 피해라!"

반응형
SMALL

안녕하세요, 코딩 enthusiasts 여러분! 오늘은 파이썬과 Pygame을 사용해 만든 흥미진진한 아케이드 게임, "별을 피해라!"를 소개해드리려고 합니다. 이 게임은 단순한 규칙과 조작법을 가졌지만, 놀라울 정도로 중독성 있는 게임플레이를 제공합니다.

📌 목차

  1. 게임 소개
  2. 게임 방법
  3. 주요 특징
  4. 조작법
  5. 게임의 목표
  6. 개발 정보
  7. 코드 하이라이트

🎮 게임 소개

"별을 피해라!"는 클래식한 아케이드 게임의 감성을 현대적으로 재해석한 게임입니다. 플레이어는 끊임없이 움직이는 별들 사이에서 살아남아야 하는 파란색 사각형을 조종합니다. 단순해 보이지만, 시간이 지날수록 난이도가 올라가며 플레이어의 반사신경과 전략을 시험합니다.

🔍 게임 방법

  1. 캐릭터: 파란색 사각형이 여러분의 분신입니다.
  2. 장애물: 빨간색 별들이 화면을 돌아다니며 여러분을 위협합니다.
  3. 생존: 방향키를 이용해 별들을 피해 최대한 오래 살아남으세요.
  4. 파워업: 노란색 아이템을 먹으면 잠시 동안 무적 상태가 됩니다.
  5. 점수: 생존 시간에 비례해 점수가 올라갑니다.

🌟 주요 특징

  • 시작 화면: 게임 시작 전 메인 화면에서 최고 점수를 확인할 수 있습니다.
  • 게임 오버 화면: 게임 종료 후 점수를 확인하고 재도전할 수 있습니다.
  • 점수 시스템: 현재 점수와 생존 시간이 실시간으로 표시됩니다.
  • 파워업 시스템: 무적 아이템으로 전략적 플레이가 가능합니다.
  • 최고 점수 저장: 자신의 최고 기록에 도전할 수 있습니다.

🕹️ 조작법

기능
왼쪽으로 이동
오른쪽으로 이동
위로 이동
아래로 이동

🏆 게임의 목표

이 게임의 궁극적인 목표는 자신의 한계에 도전하는 것입니다. 별들을 피해 가능한 한 오래 살아남으며, 최고 점수를 경신해보세요. 매 순간 긴장감 넘치는 플레이를 즐기실 수 있습니다!

💻 개발 정보

  • 언어: Python 3.x
  • 라이브러리: Pygame
  • 개발 환경: Visual Studio Code
  • 버전 관리: Git & GitHub

이 게임은 Python과 Pygame을 학습하는 과정에서 만들어졌습니다. 게임 개발의 기초를 배우기에 아주 좋은 프로젝트입니다.

🖥️ 코드 하이라이트

게임의 핵심 로직을 소개합니다:

import pygame
import random
import json


# 게임 설명:
# "별을 피해라!"는 간단하지만 재미있는 아케이드 스타일의 게임입니다.
#
# 게임 방법:
# 1. 플레이어는 파란색 사각형을 조종합니다.
# 2. 빨간색 별들이 화면 주위를 움직입니다.
# 3. 방향키를 사용해 별들을 피해 최대한 오래 살아남으세요.
# 4. 노란색 파워업 아이템을 먹으면 잠시 동안 무적 상태가 됩니다.
# 5. 시간이 지날수록 점수가 올라갑니다.
#
# 게임 특징:
# - 시작 화면과 게임 오버 화면이 있습니다.
# - 최고 점수가 저장되고 표시됩니다.
# - 현재 점수와 생존 시간이 화면에 표시됩니다.
# - 무적 상태일 때는 "무적!" 메시지가 표시됩니다.
#
# 조작법:
# - 왼쪽 화살표: 왼쪽으로 이동
# - 오른쪽 화살표: 오른쪽으로 이동
# - 위쪽 화살표: 위로 이동
# - 아래쪽 화살표: 아래로 이동
#
# 목표:
# 가능한 한 오래 살아남아 최고 점수를 갱신하세요!

# 게임을 시작하려면 아무 키나 누르세요.

# Game settings
CONFIG = {
    "width": 1200,
    "height": 750,
    "player_speed": 5,
    "star_speed_multiplier": 1,
    "star_count": 25,
    "powerup_chance": 0.005,
    "invincibility_duration": 3000,
}

# Colors
COLORS = {
    "WHITE": (255, 255, 255),
    "RED": (255, 0, 0),
    "GREEN": (0, 255, 0),
    "BLUE": (0, 0, 255),
    "BLACK": (0, 0, 0),
    "YELLOW": (255, 255, 0),
}

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode((CONFIG["width"], CONFIG["height"]))
        pygame.display.set_caption("Dodge the Stars!")
        self.clock = pygame.time.Clock()
        self.font = pygame.font.SysFont(None, 35)
        self.load_highscore()

    def load_highscore(self):
        try:
            with open("highscore.json", "r") as f:
                self.highscore = json.load(f)["highscore"]
        except:
            self.highscore = 0

    def save_highscore(self):
        with open("highscore.json", "w") as f:
            json.dump({"highscore": self.highscore}, f)

    def run(self):
        self.show_start_screen()
        while True:
            score = self.play_game()
            self.show_game_over_screen(score)

    def show_start_screen(self):
        self.screen.fill(COLORS["WHITE"])
        self.draw_text("Dodge the Stars!", 64, CONFIG["width"] // 2, CONFIG["height"] // 4)
        self.draw_text("Use arrow keys to move and avoid stars", 22, CONFIG["width"] // 2, CONFIG["height"] // 2)
        self.draw_text("Press any key to start", 18, CONFIG["width"] // 2, CONFIG["height"] * 3 // 4)
        self.draw_text(f"High Score: {self.highscore}", 22, CONFIG["width"] // 2, CONFIG["height"] * 3 // 4 + 40)
        pygame.display.flip()
        self.wait_for_key()

    def show_game_over_screen(self, score):
        self.screen.fill(COLORS["WHITE"])
        self.draw_text("Game Over", 64, CONFIG["width"] // 2, CONFIG["height"] // 4)
        self.draw_text(f"Score: {score}", 22, CONFIG["width"] // 2, CONFIG["height"] // 2)
        if score > self.highscore:
            self.highscore = score
            self.save_highscore()
            self.draw_text("New High Score!", 22, CONFIG["width"] // 2, CONFIG["height"] // 2 + 40)
        self.draw_text("Press any key to play again", 18, CONFIG["width"] // 2, CONFIG["height"] * 3 // 4)
        pygame.display.flip()
        self.wait_for_key()

    def wait_for_key(self):
        waiting = True
        while waiting:
            self.clock.tick(30)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    pygame.quit()
                if event.type == pygame.KEYUP:
                    waiting = False

    def draw_text(self, text, size, x, y):
        font = pygame.font.Font(None, size)
        text_surface = font.render(text, True, COLORS["BLACK"])
        text_rect = text_surface.get_rect()
        text_rect.midtop = (x, y)
        self.screen.blit(text_surface, text_rect)

    def play_game(self):
        player = Player()
        stars = pygame.sprite.Group()
        powerups = pygame.sprite.Group()
        all_sprites = pygame.sprite.Group(player)

        for _ in range(CONFIG["star_count"]):
            star = Star()
            stars.add(star)
            all_sprites.add(star)

        start_time = pygame.time.get_ticks()
        score = 0
        running = True

        while running:
            self.clock.tick(60)
            current_time = pygame.time.get_ticks()
            elapsed_time = (current_time - start_time) / 1000

            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    running = False

            keys = pygame.key.get_pressed()
            player.update(keys)

            if random.random() < CONFIG["powerup_chance"]:
                powerup = PowerUp()
                powerups.add(powerup)
                all_sprites.add(powerup)

            stars.update()
            powerups.update()

            if pygame.sprite.spritecollide(player, powerups, True):
                player.invincible = True
                player.invincible_timer = pygame.time.get_ticks()

            if not player.invincible and pygame.sprite.spritecollide(player, stars, False):
                running = False

            if player.invincible and current_time - player.invincible_timer > CONFIG["invincibility_duration"]:
                player.invincible = False

            self.screen.fill(COLORS["WHITE"])
            all_sprites.draw(self.screen)

            score = int(elapsed_time * 10)
            self.draw_text(f"Score: {score}", 22, 100, 10)
            self.draw_text(f"Time: {int(elapsed_time)}s", 22, CONFIG["width"] - 100, 10)

            if player.invincible:
                self.draw_text("Invincible!", 22, CONFIG["width"] // 2, 10)

            pygame.display.flip()

        return score

class Player(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([20, 20])
        self.image.fill(COLORS["BLUE"])
        self.rect = self.image.get_rect()
        self.rect.center = (CONFIG["width"] // 2, CONFIG["height"] // 2)
        self.invincible = False
        self.invincible_timer = 0

    def update(self, keys):
        if keys[pygame.K_LEFT]:
            self.rect.x -= CONFIG["player_speed"]
        if keys[pygame.K_RIGHT]:
            self.rect.x += CONFIG["player_speed"]
        if keys[pygame.K_UP]:
            self.rect.y -= CONFIG["player_speed"]
        if keys[pygame.K_DOWN]:
            self.rect.y += CONFIG["player_speed"]

        self.rect.clamp_ip(pygame.Rect(0, 0, CONFIG["width"], CONFIG["height"]))

class Star(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([20, 20])
        self.image.fill(COLORS["RED"])
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, CONFIG["width"])
        self.rect.y = random.randint(0, CONFIG["height"])
        self.speed = [random.choice([-3, -2, -1, 1, 2, 3]) * CONFIG["star_speed_multiplier"] for _ in range(2)]

    def update(self):
        self.rect.x += self.speed[0]
        self.rect.y += self.speed[1]
        if self.rect.left < 0 or self.rect.right > CONFIG["width"]:
            self.speed[0] = -self.speed[0]
        if self.rect.top < 0 or self.rect.bottom > CONFIG["height"]:
            self.speed[1] = -self.speed[1]

class PowerUp(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([15, 15])
        self.image.fill(COLORS["YELLOW"])
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, CONFIG["width"])
        self.rect.y = random.randint(0, CONFIG["height"])

    def update(self):
        pass

if __name__ == "__main__":
    game = Game()
    game.run()
반응형
LIST

'Python > Game' 카테고리의 다른 글

🚀 탱크 게임 #python  (1) 2024.10.14
🔢 2048 게임 #python  (0) 2024.10.14
🐍 Snake(꼬리잡기) 게임 코드 #python  (0) 2024.10.14
⚡ 반응속도 테스트 게임 #python  (0) 2024.10.14
⛄ 눈 내리는 파이썬 !  (3) 2024.09.12