각도 관련된것을 알려면 삼각함수를 알아야 한다.

 

radian - 호 도 법  - 각의크기를 나타내는 방법(각도의 단위)

 

★각도(육십분법)      실수(호도법)

180도                            파이

90도                           2분의 파이

60도                           3분의 파이

45도                           4분의 파이

30도                           6분의 파이

120도                         3분의 2 파이

150도                         6분의 5 파이

300도                         3분의 5 파이

2분의 3 파이(호도법)   270도(육십분법)

 

 

 

 

각도를 구하는 FPS총게임 등 만들수 있다.

 

육십분법 출력 값  = 8.085580866682552

 

 

 

출력값 - 53.13010235415598

 

 

★소스 이용해서 토끼 게임 만들기

 

게임 소스 https://www.raywenderlich.com/

pygame을 검색한다.

 

 

 

here 을 눌러 다운로드 파일을 프로젝트 폴더에 넣는다.

 

파이참에서 새파일을 만들어준다.

 

 

from pygame.locals import * 필요한 라이브러리 를 쓸수 있다. 보통 이렇게 사용한다.

게임 루프 while문

 

#Import library
import math #회전 함수
import random
import pygame
from pygame.locals import *

#초기 게임설정
pygame.init()
pygame.mixer.init()
width, height = 640, 480
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption("동동 이미지")
#속도 제어
FPS = 50
fpsClock=pygame.time.Clock()

#키 입력 체크
keys = [False, False, False, False]
#플레이어 버니 위치
playerpos = [100, 100]
#화살 발사 횟수
acc = [0, 0]
#화살 각도
arrows = []
#적생성
badtimer = 100
# badtimer만큼 줄인다.
badtimer1 = 0
#적 좌표 리스트
badguys = [[640, 100]]
healthvalue = 194

# Load images
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("kakao_mu.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")

#Load audio
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("FIVE.mp3")
pygame.mixer.music.play(-1, 0.0)
pygame.mixer.music.set_volume(0.25)

# keep looping through
running = 1
exitcode = 0
while running:
# 5 - clear the screen before drawing it again
screen.fill(0)

#잔디를 그린다.
for x in range(width//grass.get_width()+1): #잔디 100픽셀 (5)
for y in range(height//grass.get_height()+1):
screen.blit(grass, (x*100, y*100))

#성을 배치
screen.blit(castle, (0, 30))
screen.blit(castle, (0, 135))
screen.blit(castle, (0, 240))
screen.blit(castle, (0, 345))
# 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
velx = math.cos(bullet[0])*10
vely = math.sin(bullet[0])*10
bullet[1] += velx
bullet[2] += vely
if bullet[1]<-64 or bullet[1]>640 or bullet[2]<-64 or bullet[2]>480:
arrows.pop(index)
#화살을 그려주고 제거하는 역할
index += 1
for projectile in arrows:
arrow1 = pygame.transform.rotate(arrow, 360-projectile[0]*57.29)
screen.blit(arrow1, (projectile[1], projectile[2]))
# 6.3 - Draw badgers
if badtimer == 0: #적이 0이 될때 생성
badguys.append([640, random.randint(50, 430)])
badtimer = 100 - (badtimer1 * 2)
if badtimer1 >= 35:
badtimer1 = 35
else:
badtimer1 += 5
index = 0
for badguy in badguys:
if badguy[0] < -64:
badguys.pop(index)
badguy[0] -= 7
# 6.3.1 - Attack castle
badrect = pygame.Rect(badguyimg.get_rect())
badrect.top = badguy[1]
badrect.left = badguy[0]
if badrect.left < 64:
hit.play()
healthvalue -= random.randint(5,20)
badguys.pop(index)
# 6.3.2 - Check for collisions
# 충돌 체크
index1 = 0
for bullet in arrows:
bullrect = pygame.Rect(arrow.get_rect()) #적을헤치우는 좌표
bullrect.left = bullet[1]
bullrect.top = bullet[2]
if badrect.colliderect(bullrect):
enemy.play()
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 - Draw clock
# 시계
font = pygame.font.Font(None, 24)
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 - Draw health bar
screen.blit(healthbar, (5, 5))
for health1 in range(healthvalue):
screen.blit(health, (health1 + 8, 8))
# update the screen
pygame.display.flip()
fpsClock.tick(FPS)
# loop through the events
for event in pygame.event.get():
#키를 누를때
if event.type == 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
#키를 뗄때 동작이 자동으로 멈춘다.False
if event.type == KEYUP:
if event.key == K_w:
keys[0] = False
elif event.key == K_a:
keys[1] = False
elif event.key == K_s:
keys[2] = False
elif event.key == K_d:
keys[3] = False
if event.type == QUIT:
# if it is quit the game
pygame.quit()
exit(0)
if event.type == MOUSEBUTTONDOWN:
shoot.play()
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])
# 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
badtimer -= 1
# 10 - Win/Lose check
if pygame.time.get_ticks() >= 90000:
running = 0
exitcode = 1
if healthvalue <= 0:
running = 0
exitcode = 0
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)
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))
screen.blit(text, textRect)

while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
exit(0)
pygame.display.flip()

 

 

음악이랑 이미지 확인

 

★이미지 보여주기

 

이미지한장을 구해 파이참 프로젝트 폴더 에 넣어준다.

 

 

display_width 와 display_height 나중에 값을 편하게 바꿀수있게 변수를 지정해준다.

보여줄 이미지 업로드 이미지 파일 이름을 넣어준다.

mying이라는 함수를 만들어준다.

스크린에 이미지가 보여줘야하므로 blit 을 사용한다. x,y는 이미지 위치지정

끝나지 않았다면을 설정해주고 이벤트를 만들어준다.

fill은 스크린 색상.

mying(x,y) 이미지 위치

pygame.display.flip() 이 업데이트 코드가 없으면 코드 출력이 안된다.

 

pygame.quit()

quit() 두줄은 없어도 무방하다.

 

pygame.display.set_caption("동동 이미지")

- 이코드를 넣으면 윈도우창 이름 동동 이미지


★음악넣기

 

음악 파일을 파이참 프로젝트 폴더에 넣어준다.

 

pygame.mixer.music.load 에는 음악 파일 이름

mixer를 빼면안된다. 모듈이다.

 

play(0)은 한번 재생이고 무한대로 재생하고 싶으면 (-1)

 

 

창이 뜨자마자 음악이 나오게된다. 음악재생!!!

 

이전에 배운 K_SPACE 말고 K_1 하면 하면 1번키

UP,DOWN 등등

 

사각형을 움직이게 할려면 기존 사각형을 없애는 코드를 만들어야한다

사각형이 옮겨지면 너무 순식간이라 프레임 설정을 해줘야한다.

속도도 설정해주어야 한다.

 

 

x,y 변수를 지정해 x,y좌표를 설정해 준다.

pygame.time.Clock() 초 설정을 해준다.

 

키를 눌르는 이벤트를 만들어 줘야하므로 pressed라는 변수를 만들어 준다.

몇칸을 옮길지 설정.3칸

사각형이 옮겨지면서 기존의 사각형은 없어져야 하므로 ourScreen.fill fill이라는 옵션사용.

너무 빨리 움직이므로 clock.tick(60)사용.

 

 

★윈도우 창 띄우기

 

★pycharm에서 pygame을 시작할때

 

import pygame

pygame.init()

 

이 두 줄은 반드시 시작해야 한다.

 

윈도우 화면 = 윈도우 서피스라 통칭

 

 

코드 대문자 소문자 문법 주의

pygame.event.get() 끊임없는 이벤트 체크

 

flip - ex) 책장계속넘기 면서 그림이 저절로 움직이는 착시현상

 

★게임 루프 개념 구현

 

핸들 이벤트 - 마우스를 눌르던가 키보드 입력

 

update game state - 게임의 변수들 을 업데이트

 

draw screen - 화면에 보여지는

 

★윈도우 창에 사각형 그리기

 

0,128,255 <-색깔 RGB지정

0,0,60,60 <- 0,0 xy좌표  60,60 사각형 크기

 

이벤트 키는 키 스페이스를 누르면 발생

스페이스를 누르면 블루가 아니다

만약 블루 색상 이면 키보드를 누르면 블루가 아니다

그러면은 하얀색으로 발생

 

'Python > Pygame' 카테고리의 다른 글

Pygame/ 삼각함수 math모듈  (0) 2017.07.19
Pygame/ 토끼 슈팅 게임 만들기  (0) 2017.07.14
Pygame/ 이미지, 음악 넣기  (0) 2017.07.13
Pygame/ 사각형 움직이게 하기  (0) 2017.07.08
Pygame/ pycharm 개발환경 구축  (0) 2017.07.06

 

pygame 다운로드 사이트

http://www.pygame.org/download.shtml

 

내가 64비트여도

64비트는 비공식,불안정

32비트는 안정적

 

pycharm 사용 할거면 파이썬이랑 pygame을 32비트로 그리고 둘다 같은버전으로.

pygame-1.9.1.win32-py3.1.msi 3MB

 

Windows x86 MSI Installer (3.1) (sig)

 

pycharm에서는 다른프로그램이 64비트면 안된다.

 

Pycharm

- 자바 이클립스 처럼 파이썬 개발 환경

- JetBrain 님이 개발한 프로그램, 코드분석,그래픽디버깅,통합장치테스트 등의 목적으로 사용되는 프로그램

 

 

pygame 모듈 돌아가는거 확인.

 

pycharm community설치 - https://www.jetbrains.com/pycharm/download/download-thanks.html?platform=windows

 

 

 

new python file 열어서 파일 생성하고 Alt+shift+F10 pygame 모듈 돌아가는거 확인.

+ Recent posts