python

pygame을 사용해 간단한 아케이드게임을 만들어보자 - 뱀 게임

윤만석 2023. 5. 16. 16:36

파이썬의 라이브러리인 pygame을 이용해 간단한 아케이드 게임 몇개를 만들어봤습니다(정말 간단함)

 

먼저 뱀 게임입니다.

뱀은 움직이면서 지도에 떨어진 사과를 먹습니다.

사과를 먹으면 길이가 1늘어납니다.

뱀이 지도밖으로 벗어나거나, 머리와 몸이 부딪히면 게임은 종료됩니다.

 

import pygame
import random

WIDTH = 600 //가로길이
HEIGHT = 400 //세로길이
FPS = 12 //프레임
BLOCK_SIZE = 20 //블록의 크기
SNAKE_INIT_LEN = 3 //초기 뱀의 길이
INIT_POS = (WIDTH//2, HEIGHT//2) //초기 시작 위치

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)

pygame.init() //pygame 초기화
screen = pygame.display.set_mode((WIDTH, HEIGHT)) //크기 설정
pygame.display.set_caption("SNAKE GAME score: 0")
clock = pygame.time.Clock() 

class Snake: //뱀 클래스 설정
    def __init__(self):
        self.blocks = [INIT_POS for _ in range(SNAKE_INIT_LEN)]//뱀의 신체
        self.direction = 'right' //뱀의 초기 방향 설정

    def move(self): //move 매소드 제작 
        x, y = self.blocks[0]  //x,y는 뱀의 머리의 위치입니다.
        if self.direction == 'right':
            x += BLOCK_SIZE
        elif self.direction == 'left':
            x -= BLOCK_SIZE
        elif self.direction == 'up':
            y -= BLOCK_SIZE
        elif self.direction == 'down':
            y += BLOCK_SIZE
        self.blocks.pop()
        self.blocks.insert(0, (x, y))

    def grow(self)://grow 매소드
        self.blocks.append(self.blocks[-1]) //맨 마지막위치에 추가합니다.

    def draw(self): //draw 매소드 각 신체별로 그립니다
        for x, y in self.blocks:
            pygame.draw.rect(screen, WHITE, [x, y, BLOCK_SIZE, BLOCK_SIZE], 2)
            pygame.draw.rect(screen, BLACK, [x+2, y+2, BLOCK_SIZE-4, BLOCK_SIZE-4])

    def collide_with_wall(self): //벽과 부딪히는 로직 매소드
        x, y = self.blocks[0]
        if x < 0 or x >= WIDTH or y < 0 or y >= HEIGHT:
            return True
        return False

    def collide_with_self(self): //자기 자신과 부딪히는 매소드
        head = self.blocks[0]
        for block in self.blocks[1:]:
            if head == block:
                return True
        return False
class Apple: //사과 클래스입니다
    def __init__(self): //초기화. 위치는 랜덤입니다
        self.position = (random.randrange(0, WIDTH-BLOCK_SIZE, BLOCK_SIZE), 
                         random.randrange(0, HEIGHT-BLOCK_SIZE, BLOCK_SIZE))

    def draw(self):
        pygame.draw.rect(screen, RED, [self.position[0], self.position[1], BLOCK_SIZE, BLOCK_SIZE])
  
def game_loop(): //게임 루프입니다
    global score //score는 전역변수로 지정되어있습니다.
    score=0
    snake = Snake() //뱀 생성
    apple = Apple() //사과 생성
    while True://무한 반복합니다
        for event in pygame.event.get(): //이벤트를 입력받습니다
            if event.type==pygame.QUIT: //x버튼을 누르면 나가집니다
                pygame.quit()
                quit()
            elif event.type == pygame.KEYDOWN: //움직이는경우 뱀의 방향이 변합니다.
                if event.key == pygame.K_UP:
                    snake.direction = 'up'
                elif event.key == pygame.K_DOWN:
                    snake.direction = 'down'
                elif event.key == pygame.K_LEFT:
                    snake.direction = 'left'
                elif event.key == pygame.K_RIGHT:
                    snake.direction = 'right'
        snake.move() //방향에 맞춰 뱀이 움직입니다.
        if snake.blocks[0] == apple.position: #만약 뱀의 머리가 사과와 같으면
            score+=1
            print(score)
            pygame.display.set_caption("score: "+str(score))
            snake.grow() //뱀이 성장합니다.
            apple = Apple() //새로운 사과
        elif snake.collide_with_wall() or snake.collide_with_self():
            game_over() //벽과 부딪히거나 몸에 부딪히면 게임오버
        screen.fill(BLACK)
        snake.draw()
        apple.draw()
        pygame.display.update() //업데이트합니다
        clock.tick(FPS)
def game_over():
    pygame.quit()
    quit() 
game_loop()

 

라이브러리 pygame을 사용했습니다. 

일단 pygame을 사용할 줄만 알면 만드는 시간은 굉장히 짧습니다........

우선 알아야 할건 기본적으로 게임의 구조는

매 프레임마다 객체들의 위치나 데이터들을 업데이트 후에

객체들을 다시 그려주는겁니다.

 

매 객체들은 클래스로 만들어주고, 무한루프 내에서 업데이트와 드로우를 반복하면 됩니다.