반응형
SMALL
먼저 메인함수 안에서 새롭게 초기화 한 값들이다.
def main():
running = 1
badtimer = 50
badguys = [[800,random.randint(50,450)]] # 적 처음 위치
enemy = Enemy()
player = Player()
padlockToKey = False
gameOver = 0
gameWin = 0
gameLose = 0
padlock_y = [13,113,213,313,413] # 자물쇠 이미지의 y좌표값
arrows=[] # 총알각도, 총알 x좌표, 총알 y좌표
keys=[False,False]
timer = Timer()
timer.start()
arrows[] 에서 총알각도, 총알x좌표, 총알y좌표를 하나로 묶어서 처리하여 [[],[],[]..] 이런식으로 나타낸다.
(리스트 안에 리스트를 넣음)
다음으로 while running: ... 안의 코드를 게임오버가 아닐 때와 게임오버일 때로 나누었다.
(메인함수에서 실행됨)
첫 번째로 배경, 자물쇠, 플레이어를 화면에 그린다.
while running :
if not gameOver:
timerResult = round(timer.get_elapsed())
badtimer -= 2
screen.fill((102,62,37)) # 갈색 배경으로 초기화
# 화면 구성
for x in range(int(width/soil.get_width()+1)):
for y in range(int(height/soil.get_width()+1)):
screen.blit(soil,(x*100,y*100)) # 이미지의 왼쪽 위 좌표
for y in padlock_y:
padlock = Padlock(y) # 자물쇠의 y좌표값을 인자로 전달하여 초기화함
if padlock.ifPadlockHp0(): # 모든 자물쇠의 hp가 0이면 key이미지를 나타냄
screen.blit(pygame.image.load(os.path.join(image_path,'key.png')),(10,y+10))
padlockToKey = True
else:
padlock.draw() # 자물쇠를 그림
screen.blit(padlock.small_healthbar,(0,y+72)) # 각각 자물쇠 hp 틀 그리기(빨간색)
player.draw() # 플레이어를 올바른 위치에 그림
두 번째로 총알을 그린다. (노란색 사각형)
# 총알 그리기
for bullet in arrows:
index=0
velx=math.cos(bullet[0])*20 # 20은 총알의 속도
vely=math.sin(bullet[0])*20
bullet[1]+=velx
bullet[2]+=vely
# 범위 벗어나면 총알 삭제
if bullet[1]>1000 or bullet[2]>500 or bullet[1]<-64 or bullet[2]<-64 :
arrows.pop(index)
index+=1
shot = Shot(bullet[1],bullet[2])
shot.draw()
arrows 리스트의 원소는 리스트이므로
bullet[0] -> 총알각도
bullet[1] -> 총알x좌표
bullet[2] -> 총알y좌표
총알과 자물쇠를 충돌처리하지 않고 총알의 x좌표가 자물쇠의 x좌표보다 작아지면 총알을 삭제하는 것으로 하였다.
세 번째로 적을 생성하고 그리는 과정을 처리한다.
# 적 그리기
enemy_y = random.randint(50,450) # 적의 y좌표가 50부터 450중의 하나로 랜덤 생성됨
if badtimer==0: # 타이머가 0이되면 적 생성
badguys.append([800,enemy_y])
badtimer=100-(enemy.badtimer1*2) # 지금까지 badtimer가 몇 번 실행되었는지에 따라 badtimer 재설정.
# 시간 지날수록 적 생성 속도 빨라짐
if enemy.badtimer1>=35:
enemy.badtimer1=35
else:
enemy.badtimer1+=5
index = 0
for badguy in badguys:
badguy[0]-=9 # 적의 x좌표를 조정하여 이동속도 조절 가능
# 자물쇠와 적의 충돌처리
# 좌표를 벗어나면 hp감소하는 걸로 함.
bangy = badguy[1]+5 # 폭탄이 터지는 이미지 처리
padlock.collision(badguy,badguys,bangy,enemy,index)
# 총알과 적의 충돌처리
index1 = 0
for bullet in arrows:
shot.rect.left = bullet[1] # 총알 x좌표
shot.rect.top = bullet[2] # 총알 y좌표
if enemy.rect.colliderect(shot.rect):
badguys.pop(index) # 적 삭제
arrows.pop(index1) # 총알 삭제
index1 += 1
# 캐릭터와 적의 충돌처리
player.rect.left = player.playerpos1[0] # 플레이어 x좌표
player.rect.top = player.playerpos1[1] # 플레이어 y좌표
if enemy.rect.colliderect(player.rect):
badguys.pop(index) # 적 삭제
player.hp -= 1
# 다음 적 생성
index += 1
# 모든 적을 그림
for badguy in badguys:
enemy.draw(badguy)
네 번째로 자물쇠 hp, 캐릭터 hp, 시계 표시를 처리한다.
# 자물쇠 hp 처리
hpy = 86
for key,value in padlock.padlock_info.items():
for smallHealth in range(value+3):
screen.blit(padlock.small_health,(smallHealth+1,hpy))
hpy += 100
# 캐릭터 hp 처리
hpx = 750
for hp in range(0,player.hp):
screen.blit(heart,(hpx-hp,10))
hpx -= 55
# 시계 표시
font = pygame.font.Font(None,80)
timeValue = 90-timerResult # 90초 카운트다운
if timeValue<=10:
timerText = font.render(str(timeValue),True,(255,255,62)) # 10초 이하로 남으면 시계 숫자 색 변함
else:
timerText = font.render(str(timeValue),True,(0,0,0))
screen.blit(timerText,(720,420))
다섯 번째로 키 이벤트와 마우스를 처리한다.
# 키 이벤트 처리
for event in pygame.event.get():
if event.type==pygame.QUIT:
pygame.quit()
exit(0)
# 키를 누를 때
elif event.type==pygame.KEYDOWN:
if event.key==pygame.K_w:
if player.playerpos[1]<=100:
player.playerpos[1]=455 # 플레이어가 화면 밖을 벗어나지 않도록
else: player.playerpos[1] -= 100
elif event.key==pygame.K_a:
keys[0]=True
elif event.key==pygame.K_s:
if player.playerpos[1]>=400:
player.playerpos[1]=55 # 플레이어가 화면 밖을 벗어나지 않도록
else: player.playerpos[1] +=100
elif event.key==pygame.K_d:
keys[1]=True
# 키를 뗄 때
elif event.type==pygame.KEYUP:
if event.key==pygame.K_a:
keys[0]=False
elif event.key==pygame.K_d:
keys[1]=False
# 마우스 클릭시
elif event.type==pygame.MOUSEBUTTONDOWN:
mousepos=pygame.mouse.get_pos()
arrows.append([math.atan2(mousepos[1]-player.playerpos1[1],mousepos[0]-player.playerpos1[0]),player.playerpos1[0]+32,player.playerpos1[1]+32])
if keys[0]:
player.playerpos[0]-=10
elif keys[1]:
player.playerpos[0]+=10
여섯 번째로 게임오버/게임승리를 체크하고 화면을 업데이트한다.
# 게임오버 / 게임승리 체크
if player.hp<=0 or padlockToKey:
gameOver = 1 # 게임종료
gameLose=1
if timeValue<=0:
gameOver = 1
gameWin=1
# 화면 업데이트
pygame.display.flip()
fpsClock.tick(FPS)
마지막으로 게임오버는 handleGameOver라는 함수를 따로 만들어서 처리하였다.
if gameOver:
handleGameOver(padlock,gameWin,gameLose)
메인함수 끝!!
다음 글에서는 게임오버를 처리하는 handleGameOver함수와 게임시작 화면을 구성하는 함수를 정리하겠다.
반응형
LIST
'python 프로젝트(pygame)' 카테고리의 다른 글
4. 게임 오버화면과 시작화면 구성(마지막) (0) | 2020.08.13 |
---|---|
2. pygame 기본적인 클래스 구성 + 코드 (0) | 2020.08.11 |
1. pygame 게임 실행화면 (0) | 2020.08.11 |
댓글