본문 바로가기
PYTHON(파이썬)/PYGAME(GAME)

ChatGPT Canvas로 5분만에 만든 게임

by eplus 2024. 10. 13.

# pip install pygame

import pygame
import time
import random

# 초기화
pygame.init()

# 색상 정의
white = (255, 255, 255)  # 배경 색상
black = (0, 0, 0)  # 뱀 색상
red = (213, 50, 80)  # 게임 종료 메시지 색상
green = (0, 255, 0)  # 먹이 색상
blue = (50, 153, 213)  # 점수 색상

# 화면 크기 설정
width = 600
height = 400

display = pygame.display.set_mode((width, height))  # 게임 화면 생성
pygame.display.set_caption('Snake Game')  # 게임 제목 설정

clock = pygame.time.Clock()  # 게임 속도 조절을 위한 시계 객체 생성

snake_block = 10  # 뱀의 크기 설정
snake_speed = 15  # 뱀의 속도 설정

# 폰트 스타일 설정
font_style = pygame.font.SysFont("bahnschrift", 25)
score_font = pygame.font.SysFont("comicsansms", 35)

def your_score(score):
    # 현재 점수를 화면에 표시
    value = score_font.render("Your Score: " + str(score), True, blue)
    display.blit(value, [0, 0])

def our_snake(block, snake_list):
    # 뱀의 각 블록을 화면에 그리기
    for x in snake_list:
        pygame.draw.rect(display, black, [x[0], x[1], block, block])

def message(msg, color):
    # 화면에 메시지 출력
    mesg = font_style.render(msg, True, color)
    display.blit(mesg, [width / 6, height / 3])

def gameLoop():  # 게임의 메인 루프
    game_over = False  # 게임이 완전히 종료되었는지 여부
    game_close = False  # 플레이어가 졌을 때 상태

    # 뱀의 초기 위치 설정
    x1 = width / 2
    y1 = height / 2

    # 뱀의 이동 방향 초기화
    x1_change = 0
    y1_change = 0

    # 뱀의 몸을 구성하는 블록 리스트와 초기 길이 설정
    snake_list = []
    length_of_snake = 1

    # 먹이의 초기 위치 설정
    foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
    foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0

    while not game_over:
        print(f"Game loop started. Snake length: {length_of_snake}")  # 디버그 로그

        while game_close:
            # 게임 종료 화면 표시
            display.fill(white)
            message("You Lost! Press Q-Quit or C-Play Again", red)
            your_score(length_of_snake - 1)
            pygame.display.update()

            print("Game close state active.")  # 디버그 로그

            # 게임 종료 또는 재시작 이벤트 처리
            for event in pygame.event.get():
                if event.type == pygame.KEYDOWN:
                    if event.key == pygame.K_q:
                        print("Quit key pressed.")  # 디버그 로그
                        game_over = True  # 게임 종료
                        game_close = False
                    if event.key == pygame.K_c:
                        print("Restart key pressed.")  # 디버그 로그
                        gameLoop()  # 게임 재시작

        # 키 입력에 따른 뱀의 방향 변경 처리
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                print("Quit event triggered.")  # 디버그 로그
                game_over = True
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_LEFT and x1_change == 0:
                    print("Left key pressed.")  # 디버그 로그
                    x1_change = -snake_block  # 왼쪽으로 이동
                    y1_change = 0
                elif event.key == pygame.K_RIGHT and x1_change == 0:
                    print("Right key pressed.")  # 디버그 로그
                    x1_change = snake_block  # 오른쪽으로 이동
                    y1_change = 0
                elif event.key == pygame.K_UP and y1_change == 0:
                    print("Up key pressed.")  # 디버그 로그
                    y1_change = -snake_block  # 위로 이동
                    x1_change = 0
                elif event.key == pygame.K_DOWN and y1_change == 0:
                    print("Down key pressed.")  # 디버그 로그
                    y1_change = snake_block  # 아래로 이동
                    x1_change = 0

        # 뱀이 화면 경계를 넘으면 게임 종료 상태로 변경
        if x1 >= width or x1 < 0 or y1 >= height or y1 < 0:
            print(f"Snake hit the boundary at ({x1}, {y1}).")  # 디버그 로그
            game_close = True

        # 뱀의 위치 업데이트
        x1 += x1_change
        y1 += y1_change
        display.fill(white)  # 화면을 흰색으로 채우기
        pygame.draw.rect(display, 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:
            print("Removing tail segment.")  # 디버그 로그
            del snake_list[0]

        # 뱀이 자기 자신과 충돌하면 게임 종료 상태로 변경
        for x in snake_list[:-1]:
            if x == snake_head:
                print("Snake collided with itself.")  # 디버그 로그
                game_close = True

        # 업데이트된 뱀을 화면에 그리기
        our_snake(snake_block, snake_list)
        your_score(length_of_snake - 1)  # 점수 표시
        pygame.display.update()

        # 뱀이 먹이를 먹었을 때 처리
        if x1 == foodx and y1 == foody:
            print(f"Food eaten at ({foodx}, {foody}).")  # 디버그 로그
            # 새로운 먹이의 위치 설정
            foodx = round(random.randrange(0, width - snake_block) / 10.0) * 10.0
            foody = round(random.randrange(0, height - snake_block) / 10.0) * 10.0
            length_of_snake += 1  # 뱀의 길이 증가

        # 게임 속도 설정
        clock.tick(snake_speed)


    # 게임 종료 처리
    print("Game over. Exiting.")  # 디버그 로그
    pygame.quit()
    quit()

gameLoop()

'''

80년대 vb로 몇일을 고민하면서 만들었던 추억의 게임 이제는 ChatGPT가 5분만에 뚝딱 만드네...

'''

다운로드

 

728x90
반응형

'PYTHON(파이썬) > PYGAME(GAME)' 카테고리의 다른 글

YouTube 보고 구현한 게임  (0) 2024.10.20