python

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

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

이번에는 똥 피하기 게임을 만들어 보겠습니다.

import pygame
import random

#크기설정
WIDTH=200 
HEIGHT=400
#프레임
FPS=35
#블록하나 사이즈
BLOCK_SIZE=8
#똥이 가속도를 붙이고 떨어지므로,, 가속도 설정
GRAVITY=0.1
#초기 위치
INIT_POS=(WIDTH//2,HEIGHT-30)

BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (139, 69, 19) 

#기본 설정
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("POOP GAME score: 0")
clock=pygame.time.Clock()

#플레이어 클래스
#기본적으로 pygame.sprite.Sprite를 상속합니다
class Player(pygame.sprite.Sprite):
    def __init__(self):
        #super().__init__()은  상위 클래스의 __init__() 메서드를 호출합니다.
        super().__init__()
        #sprite는 image,rect요소들을 가집니다
        #크기설정
        self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
        #색깔
        self.image.fill(WHITE)
        self.rect = self.image.get_rect()
        self.rect.x = WIDTH//2
        self.rect.y = HEIGHT-30
    #업데이트
    def update(self):
        #키보드 입력
        keys = pygame.key.get_pressed()
        if keys[pygame.K_LEFT]:
            self.rect.x -= BLOCK_SIZE
        if keys[pygame.K_RIGHT]:
            self.rect.x += BLOCK_SIZE
        if self.rect.x < 0:
            self.rect.x = 0
        elif self.rect.x > WIDTH-BLOCK_SIZE:
            self.rect.x = WIDTH -BLOCK_SIZE
#똥 클래스
class Poop(pygame.sprite.Sprite):
    def __init__(self):
        super().__init__()
        self.image = pygame.Surface([BLOCK_SIZE, BLOCK_SIZE])
        self.image.fill(RED)
        self.rect = self.image.get_rect()
        self.rect.x = random.randint(0, WIDTH - 20)
        self.rect.y = 0
        #속도 설정
        self.speed = 0
    #업데이트
    def update(self):
        #가속도
        self.speed+=GRAVITY
        #위치
        self.rect.y += self.speed
        if self.rect.y > HEIGHT:
            self.kill()
poops = pygame.sprite.Group()
Sprites=pygame.sprite.Group()
player=Player()
Sprites.add(player)

def game_loop():
    temp=0
    while True:
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                quit()
        #특정 시간이 지날때마다 똥을 소환합니다!
        time = pygame.time.get_ticks()//100
        if temp < time :
            p=Poop()
            poops.add(p)
            Sprites.add(p)
            temp=time
        #부딪혔는지 확인하는 매소드입니다!
        if pygame.sprite.spritecollide(player, poops, False):
            pygame.quit()
            quit()
        
        screen.fill(BLACK)    
        #모든 스프라이트를 업데이트하고, 스크린에 그립니다!
        Sprites.update()
        Sprites.draw(screen)
        #매번 프레임을 그려야하므로, flip은 지우고 재생성하는 매소드입니다
        pygame.display.flip()
        clock.tick(FPS)
game_loop()

이번에는 스프라이트를 사용했습니다!

스프라이트는 기본적으로 pygame에서 사용하는 모든 그림이 있는 컴포넌트를 가리킵니다.

그리고 그 스프라이트는 기본적으로 그룹으로 묶어 사용할 수있습니다.

예를들어 똥을 만들경우...

모든 똥을하나의 리스트(그룹)에 담아서 사용할 수 있습니다.

따라서 플레이어와 모든 똥을 담아서 하나의 그룹(all_sprites)에 담으면,

게임 루프안에서 

sprites.udpate 와 sprite.draw를 통해 한번에 업데이트와 그리기를 수행할 수 있습니다.

 

spritecollide(sprite,spritegroup,bool erase)는 스프라이트 하나와, 스프라이트 그룹내의 스프라이트의 충돌을 감지합니다

 

따라서 spritecollide(player,poop_groups,True)로 작성하면

player와 모든 똥들의충돌을 감지하고, True이므로 충돌한 똥은 사라지게됩니다!

 

 

똥이 가속도를 가지고 떨어집니다!