1. 코딩 명령문
# 1 - 라이브러리 가져오기
import pygame #pygame 불러오기
from pygame.locals import * #import 안에 모든 필요한 것을 불러오겠다(?)
import math #math 함수 불러오기
import random #random 함수 불러오기
# 2 - 게임 초기화(의 의미?)
pygame.init() #pygame 시작하는 함수
width, height = 640, 480 #초기 창 크기 지정
screen = pygame.display.set_mode((width, height))
FPS = 60 #초당 프레임 60으로 지정
fpsClock = pygame.time.Clock() #프레임 시간 관련한 함수
#키 입력 체크
keys = [False, False, False, False] #현재 우리는 키보드를 움직이지 않고 있으므로 false
playerpos=[100,100] #플레이어의 위치 설정
#플레이어 위치(버니)
acc=[0,0] #뒷 배경등 모두 0, 0으로 위치 설정
arrows=[] #화살 리스트 설정
badtimer=100
badtimer1=0
badguys=[[640, 100]] #적의 위치 설정
healthvalue = 194 #pH, 즉 체력바 크기 설정
pygame.mixer.init() #pygame 업데이트
# 3 - 영상 로드하ㅣ기
player = pygame.image.load("resources/images/dude.png") #플레이어의 이미지 로드
grass = pygame.image.load("resources/images/grass.png") #잔디 이미지 로드
castle = pygame.image.load("resources/images/castle.png") #성 이미지 로드
arrow = pygame.image.load("resources/images/bullet.png") #화살 이미지 로드
badguyimg1 = pygame.image.load("resources/images/badguy.png") #적 이미지 로드
badguyimg=badguyimg1
healthbar = pygame.image.load("resources/images/healthbar.png") #체력바 이미지 로드
health = pygame.image.load("resources/images/health.png") #체력 이미지 로드 (빨간색)
gameover = pygame.image.load("resources/images/gameover.png") #게임오버 문구 로드
youwin = pygame.image.load("resources/images/youwin.png") #이겼다는 문구 로드
# 3.1 = 오디오 불러오기
hit = pygame.mixer.Sound("resources/audio/explode.wav") #적을 맞췄을때 효과음 로드
enemy = pygame.mixer.Sound("resources/audio/enemy.wav") #적이 오는 효과음 로드
shoot = pygame.mixer.Sound("resources/audio/shoot.wav") #화살 쏠 때 효과음 로드
hit.set_volume(0.05) #적을 맞췄을 때 소리의 크기를 설정
enemy.set_volume(0.05) #적이 등장할때 소리의 크기를 설정
shoot.set_volume(0.05) #화살 쏠 때 소리의 크기를 설정
pygame.mixer.music.load("resources/audio/moonlight.wav") #배경음악 로드
pygame.mixer.music.play(-1, 0.0) #배경음악을 반복재생
pygame.mixer.music.set_volume(0.25) #배경음악의 크기를 설정
# 4 - 루핑 계속하기
running = 1 #딱 한번 게임을 진행함(게임오버되면 다시 시작할 수 있게 자동 재생이 아님)
exitcode = 0
while running: #게임이 진행되는 동안
badtimer-=1 #시간은 점점 줄어듦
# 5 - clear the screen before drawing it again
screen.fill(0) #게임이 진행될 때 배경을 채움
# 잔디를 그린다
for x in range(int(width/grass.get_width()) + 1): #잔디의 너비를 설정해줌
for y in range( int(height/grass.get_height()) + 1): #잔디의 높이를 설정해줌
screen.blit(grass,(x*100,y*100)) #blit은 위치를 지정해주는 명령문
# 성을 배치
screen.blit(castle,(0,30)) #첫 번째 성의 위치 지정
screen.blit(castle, (0, 135)) #두 번째 성의 위치 지정
screen.blit(castle, (0, 240)) #세 번째 성의 위치 지정
screen.blit(castle, (0,345)) #네 번째 성의 위치 지정
# 6 - draw the screen elements # 칸 맞춰줘야 이동 : x
# 6.1 - Set player position and rotation
position = pygame.mouse.get_pos() #마우스 위치가 화살 위치가 되도록 지정
angle = math.atan2(position[1]-(playerpos[1]+32),position[0]-(playerpos[0]+26)) #화면의 앵글 설정
playerrot = pygame.transform.rotate(player, 360-angle*57.29) #토끼가 마우스를 쳐다보는대로 고개를 돌리기 설정
playerpos1 = (playerpos[0]-playerrot.get_rect().width/2, playerpos[1]-playerrot.get_rect().height/2)
screen.blit(playerrot, playerpos1) #화면을 우리가 지정해준 위치로 지정
# 6.2 - Draw arrows
for bullet in arrows: #화살에 대한 모든 함수 불러오기
index = 0 #0으로 이름 지정
velx=math.cos(bullet[0])*10 #x의 위치 지정
vely=math.sin(bullet[0])*10 #y의 위치 지정
bullet[1]+=velx #화살의 위치를 x로 지정
bullet[2]+=vely #화살의 위치를 y로 지정
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:#만약 1번 화살이 640보다 작으면
arrows.pop(index) #화살이 만나 없어지게 설정
index+=1 #그러면 인덱스 0에서 1이 추가됨
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29) #화살 1의 방향을 돌아가도록 설정
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - 오소리 그리기
if badtimer==0: #오소리가 등장하는 그 구간을 0으로 일단 지정
badguys.append([640, random.randint(50, 430)]) #적이 무작위하게 등장하도록 설정
badtimer=100-(badtimer1*2) #오드타이머가 몇 번 돌았는지에 대한 식
if badtimer1>35: #만약 오드타이머가 35보다 더 뛰었다면
badtimer1=35 #딱 그만큼의 구간만큼 오소리가 등장하도록 지정
else:
badtimer1+=5 # #만약 오드타이머가 35보다 더 안돌았다면 더 많은 구간의 오소리가 등장하도록 지정
index=0 #오소리 위치 업데이트
for badguy in badguys: #오소리의 모든 함수에서
if badguy[0]<-64: #오소리가 화면 밖에 얼마나 나왔는지 점검
badguys.pop(index)
badguy[0] -= 7
# 6.3.1 - 오소리가 성을 공격하게 만들기
badrect = pygame.Rect(badguyimg.get_rect())
badrect.top=badguy[1]
badrect.left=badguy[0]
if badrect.left<64: #오소리의 값이 64보다 작으면
healthvalue -= random.randint(5,20) #오소리를 삭제하고 게임의 상태 값을 5~20사이의 임의의 값으로 줄임 (더 느린 화면 만들기)
badguys.pop(index) #상태 업데이트
#6.3.2 - 충돌 여부 점검
index1=0 #상태 업데이트
for bullet in arrows: #화살의 모든 함수에서
bullrect=pygame.Rect(arrow.get_rect())
bullrect.left=bullet[1]
bullrect.top=bullet[2]
if badrect.colliderect(bullrect): #화살을 반복해서 쏘게 하기
acc[0]+=1 #충돌하는지 확인
badguys.pop(index) #충돌, 업데이트
arrows.pop(index1) #충돌, 업데이트
index1+=1
# 6.3.3 - Next bad guy
index+=1
for badguy in badguys:
screen.blit(badguyimg, badguy)
# 6.4 - 시계 그리기
font = pygame.font.Font(None, 24) #24사이즈로 지정된 기본 pygame 글꼴 사용
survivedtext = font.render(str((90000-pygame.time.get_ticks())/60000)+":"+str((90000-pygame.time.get_ticks())/1000%60).zfill(2), True, (0,0,0))
textRect = survivedtext.get_rect() #텍스트 변수 만들기
textRect.topright=[635, 5] #텍스트 위치
screen.blit(survivedtext, textRect) #텍스트 업데이트
# 6.5 - 체력바 만들기
screen.blit(healthbar, (5,5)) #체력바 위치 설정
for health1 in range(healthvalue):
screen.blit(health, (health1+8,8)) #체력바 업데이트
# 7 - 화면 업데이트
pygame.display.flip() #화면 업데이트
fpsClock.tick(FPS) #시간 설정
# 8 - 이벤트를 통한 루프 구현
for event in pygame.event.get():
# 이벤트가 x버튼인지 먼저 확인
if event.type==pygame.QUIT:
# 만약 게임이 끝나지 않았다면
pygame.quit()
exit(0)
# 키를 누를 때
if event.type == pygame.KEYDOWN:
if event.key==K_w:
keys[0]=True #위와
elif event.key==K_a:
keys[1]=True #왼쪽
elif event.key==K_s:
keys[2]=True #아래쪽
elif event.key==K_d:
keys[3]=True #오른쪽으로 화살을 쏜다
#키를 뗄 때
if event.type == pygame.KEYUP:
if event.key==pygame.K_w: #위와
keys[0]=False
elif event.key==pygame.K_a: #인쪽과
keys[1]=False
elif event.key==pygame.K_s: #아래쪽과
keys[2]=False
elif event.key==pygame.K_d: #오른쪽으로 화살을 쏘지 않음
keys[3]=False
# 9 - Move player 플레이어 움직이게 하기
if keys[0]:
playerpos[1]-=5
elif keys[2]:
playerpos[1]+=5
if keys[1]:
playerpos[0]-=5
elif keys[3]:
playerpos[0]+=5
if event.type==pygame.MOUSEBUTTONDOWN:#마우스를 아래로 누른다면
position=pygame.mouse.get_pos() #위치가 바뀌고
acc[1]+=1 #화살을 쏜다
arrows.append([math.atan2(position[1]-(playerpos1[1]+32),position[0]-(playerpos1[0]+26)),playerpos1[0]+32,playerpos1[1]+32])
# 10 - Win/Lose check #승패를 확인하기
if pygame.time.get_ticks()>=90000:
running=0 #게임이 계속 진행되고 있고
exitcode=1
if healthvalue<=0: #체력이 0보다 작다면
running=0 #게임은 계속 진행되지만
exitcode=0 #텍스트 문구가 뜸 (game over)
if acc[1]!=0:
accuracy=acc[0]*1.0/acc[1]*100
else:
accuracy=0
# 11 - Win/Lose display #승패시 화면
if exitcode==0: #졌을때의 화면
pygame.font.init()
font = pygame.font.Font(None, 24) #폰트의 크기를 24로 하겠음
text = font.render("Accuracy: "+str(accuracy)+"%", True, (255,0,0)) #폰트의 색 설정
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx #폰트의 크기 설정
textRect.centery = screen.get_rect().centery+24 #폰트의 크기 설정
screen.blit(gameover, (0,0)) #게임 오버 뜨기
screen.blit(text, textRect) #업데이트
else: #진게 아니라면 = 이긴거라면
pygame.font.init()
font = pygame.font.Font(None, 24) #폰트의 크기 설정
text = font.render("Accuracy: "+str(accuracy)+"%", True, (0,255,0)) #폰트의 색 설정
textRect = text.get_rect()
textRect.centerx = screen.get_rect().centerx #폰트의 크기 설정
textRect.centery = screen.get_rect().centery+24 #폰트의 크기 설정
screen.blit(youwin, (0,0)) #you win이라는 문구 뜨게 하기
screen.blit(text, textRect)
while 1: #게임이 계속 진행되는 동안에는 (마지막 마무리 이벤트 함수)
for event in pygame.event.get():
if event.type == pygame.QUIT:#만약 게임이 끝난다면
pygame.quit() #게임을 그만둘 때
exit(0) #게임이 끝난다
pygame.display.flip() #마지막 총 업데이트
2. 잘못된 영상
3. 토끼게임
'pygame > 02. 토끼게임 만들기' 카테고리의 다른 글
1. 토끼 게임을 만들기 위한 소스 다운받기 (0) | 2021.02.23 |
---|