23.03.16 Day33

오윤범·2023년 3월 16일
0

하얀 점 움직이기(pygame framework 사용)

  • pip install pygame
#Python으로 게임 만들기 - PyGame Game Framework 사용
#pip install pygame
import pygame

pygame.init() # 1. 게임 초기화 / 필수

width,height=500,500
win=pygame.display.set_mode((width,height)) #윈도우 사이즈 설정 / tuple 이라 괄호 한번 더 사용
pygame.display.set_caption('게임 만들기')
icon = pygame.image.load('./PyGame/game_icon.png')
pygame.display.set_icon(icon)

# object 설정
x,y=250,250
radius=10
vel_x=10
vel_y=10
jump=False

run=True

while run:
    win.fill((0,0,0)) # 사용자가 원하는대로 display.update 해주고 다시 윈도우를 검은색으로 초기화
    pygame.draw.circle(win,(255,255,255), (x,y), radius)

    #이벤트 = 시그널
    for event in pygame.event.get(): # 2. 이벤트 받기
        if event.type == pygame.QUIT:
            run = False # QUIT 일때 false로 만들고 탈출

    # 객체이동
    userInput=pygame.key.get_pressed()
    if userInput[pygame.K_LEFT] and x>10:
        x-=vel_x #왼쪽으로 10씩 
    if userInput[pygame.K_RIGHT] and x<width-10:
        x+=vel_x
    # if userInput[pygame.K_UP] and y>10:
    #     y-=vel_x # y좌표는 빼줘야 위로 올라감 주의
    # if userInput[pygame.K_DOWN]and y<height-10:
    #     y+=vel_x

    # 객체점프
    if jump == False and userInput[pygame.K_SPACE]:
        jump = True 

    if jump==True:
        y -= vel_y * 2
        vel_y -= 1
        if vel_y<-10:
            jump=False
            vel_y=10

    pygame.time.delay(10)    
    pygame.display.update() # 3.화면 업데이트(전환)

  • 키보드 방향키를 통해 이동 가능

배경 설정

import pygame

pygame.init() #초기화
win=pygame.display.set_mode((1000,500)) 

bg_img=pygame.image.load('./PyGame/Assets/background.png')
bg=pygame.transform.scale(bg_img,(1000,500)) # win에 맞춰서 사이즈 조정

pygame.display.set_caption('게임 만들기')
icon = pygame.image.load('./PyGame/game_icon.png')
pygame.display.set_icon(icon)

width=1000
loop=0
run=True
while run:
    win.fill((0,0,0))

    # 이벤트 = 시그널
    for event in pygame.event.get(): # 2. 이벤트 받기
        if event.type == pygame.QUIT:
            run = False # QUIT 일때 false로 만들고 탈출

    # 배경 그리기
    win.blit(bg,(loop,0))
    win.blit(bg,(width+loop,0))

    if loop==-width:
        loop=0

    loop-=1

    pygame.display.update()

DinoRun

# DinoRun / 공룡 달리기(크롬)
import pygame
import os

pygame.init()

ASSETS='./PyGame/Assets/' #경로 계속 적기 귀찮으니까 하나의 변수로 지정
SCREEN=pygame.display.set_mode((1100,600))

# form 상단에 나오는 이름 / 이미지 출력
pygame.display.set_caption('다이노 런')
icon = pygame.image.load('./PyGame/dinoRun.png')
pygame.display.set_icon(icon)

bg=pygame.image.load(os.path.join(f'{ASSETS}Other','Track.png'))

#뛰는 모션
RUNNING = [pygame.image.load(f'{ASSETS}Dino/DinoRun1.png'),
           pygame.image.load(f'{ASSETS}Dino/DinoRun2.png'),]

#숙이는 모션
DUCKING = [pygame.image.load(f'{ASSETS}Dino/DinoDuck1.png'),
           pygame.image.load(f'{ASSETS}Dino/DinoDuck1.png'),]

#점프 모션
JUMPING = pygame.image.load(f'{ASSETS}Dino/DinoJump.png') # 점프는 사진 하나라 배열로 선언X

# 공룡 클래스
class Dino: 
    X_POS=80 ; Y_POS = 310 ; Y_POS_DUCK = 340 ; JUMP_VEL = 9.0

    def __init__(self) -> None:
        self.run_img=RUNNING
        self.duck_img=DUCKING
        self.jump_img=JUMPING

        self.dino_run=True
        self.dino_duck=False
        self.dino_jump=False

        self.step_index=0
        self.jump_vel=self.JUMP_VEL # 점프 초기값 9.0
        self.image=self.run_img[0]
        self.dino_rect=self.image.get_rect() # 이미지 사각형 정보
        self.dino_rect.x=self.X_POS
        self.dino_rect.y=self.Y_POS


    def update(self,userInput) -> None:
        if self.dino_run:
            self.run()
        elif self.dino_duck:
            self.duck()
        elif self.dino_jump:
            self.jump()

        if self.step_index>=10 : self.step_index=0 # 애니메이션 스텝을 위해서 씀

        if userInput[pygame.K_UP] and not self.dino_jump : #점프
            self.dino_run=False
            self.dino_duck=False
            self.dino_jump=True
        elif userInput[pygame.K_DOWN] and not self.dino_jump: #숙이기
            self.dino_run=False
            self.dino_duck=True
            self.dino_jump=False
        elif not (self.dino_jump or userInput[pygame.K_DOWN]): # 달리기
            self.dino_run=True
            self.dino_duck=False
            self.dino_jump=False

    # 공룡 달리는 부분
    def run(self): 
        self.image=self.run_img[self.step_index//5]  # run_img
        self.dino_rect=self.image.get_rect() # 이미지 사각형 정보
        self.dino_rect.x=self.X_POS
        self.dino_rect.y=self.Y_POS
        self.step_index+=1

    # 공룡 숙이는 부분
    def duck(self):
        self.image=self.duck_img[self.step_index//5] # duck_img
        self.dino_rect=self.image.get_rect() # 이미지 사각형 정보
        self.dino_rect.x=self.X_POS
        self.dino_rect.y=self.Y_POS_DUCK # 이미지 높이 따로 설정
        self.step_index+=1

    # 공룡 점프하는 부분
    def jump(self):
        self.image=self.jump_img
        if self.dino_jump:
            self.dino_rect.y-=self.jump_vel * 4
            self.jump_vel -= 0.8
        if self.jump_vel<-self.JUMP_VEL: # 초기에 설정해둔 9.0이 되버리면 점프 중단
            self.dino_jump=False
            self.jump_vel=self.JUMP_VEL # 9.0으로 다시 초기화


    def draw(self,SCREEN) -> None:
        SCREEN.blit(self.image,(self.dino_rect.x,self.dino_rect.y))


def main():
    run=True
    clock=pygame.time.Clock()
    dino=Dino() # 공룡 객체 생성

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

        SCREEN.fill((255,255,255)) # 배경 흰색
        userInput=pygame.key.get_pressed() #키보드입력

        dino.draw(SCREEN) # 공룡 그리기
        dino.update(userInput)

        clock.tick(30)
        pygame.display.update() # 초당 30번 update 수행함

if __name__=='__main__':
    main()

0개의 댓글