본문 바로가기
파이썬/파이게임(Pygame)

[파이게임.003] pygame 키보드 입력처리

by 긱펀 2022. 5. 11.
반응형

 

[파이게임.003] pygame 키보드 입력처리

 

 

[1] 이번시간에는 vscode 에디터에서 파일을 하나 만들어 코딩을 시작하겠습니다.

파이게임(pygame)라이브러리를 불러와 게임 프로그래밍에 필요한 키보드 입력을 처리하는 부분부터 알아보겠습니다.

 

 

[2] vscode에서 폴더와 파일 생성하기

vscode의 상단 메뉴에서 "파일" > "폴더열기"를 눌러줍니다.

 

 

그리고 내가 원하는 곳에 빈 폴더를 하나 만들어 그 폴더를 선택해 줍니다.

 

아래 그림과 같이 파이썬 파일(xxx.py)을 하나 만들어 줍니다. xxx에는 내가 원하는 이름을 영어로 작성하시면 됩니다.

 

[3] 기본코드

파이게임 라이브러리를 불러오며 게임 프로그래밍에 필요한 기본적인 코드를 아래에서 볼 수 있습니다.

1
2
3
4
5
6
7
8
9
10
11
12
13
import pygame
 
pygame.init() # 파이게임 초기화
background = pygame.display.set_mode((480,360)) # 창 사이즈
pygame.display.set_caption("my game"# 탭 제목
 
play = True
while play: # 창을 종료하기 전까지 창을 유지하기
    for event in pygame.event.get(): #입력된 이벤트를 반복문으로 확인
        if event.type == pygame.QUIT: #현재 이벤트가 종료라면?
            play = False  #play를 False로
 
pygame.quit()
cs

 

 

[4] 코드 실행방법

위 [3]번과 같이 코딩을 하셨다면, vscode에서 실행방법은 아래와 같이 화살표 버튼을 누르거나, 마우스 우클릭 후 "Run Python File in Terminal"을 클릭하시면 됩니다.

 

파이썬 코드 실행법 1
=>vscode 화면 오른쪽 상단의 화살표 클릭하기

파이썬 코드 실행법 2
=> 마우스 오른쪽 클릭 후 나타나는 메뉴 중,
"Run Python File in Terminal"을 클릭하기

 

 

[4] 키보드 입력값 테스트 하기(방향키 값 출력)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
import pygame
 
pygame.init() # 파이게임 초기화
background = pygame.display.set_mode((480,360)) # 창 사이즈
pygame.display.set_caption("my game"# 탭 제목
 
play = True
while play: # 창을 종료하기 전까지 창을 유지하기
    for event in pygame.event.get(): #입력된 이벤트를 반복문으로 확인
        #(1) event.type 확인해보기
        #print(event.type) #입력된 이벤트의 type확인(키보드,마우스 입력 등)
        if event.type == pygame.QUIT: #창 닫기버튼(X)을 눌렀다면
            play = False  #play를 False로
        if event.type == pygame.KEYDOWN: #키보드를 누를 때
            ''' #(3) event.key와 pygame.K_xx 확인하기
            print("pressed:", event.key) # 키보드 아스키(event.key)
            if event.key == pygame.K_a: # 키보드 a를 눌렀다면
                print("a key is pressed")
            if event.key == 98: # 키보드 b를 눌렀다면(아스키값)
                print("b key is pressed")
            '''
            #(4)키보드 방향키 코딩
            if event.key == pygame.K_UP:
                print('UP')
            elif event.key == pygame.K_DOWN:
                print('DOWN')
            elif event.key == pygame.K_RIGHT:
                print('RIGHT')
            elif event.key == pygame.K_LEFT:
                print('LEFT')
            
 
        #(2) event.type 다른값 확인해보기
        #if event.type == pygame.KEYUP: #키보드를 눌렀다 뗄 때
        #    print("released:" , event.key)
 
pygame.quit() #pygame 종료
cs

 

-실행결과

키보드 입력값 테스트 하기(방향키 값 출력)

 

 

[5] 키보드 방향키로 동그라미 움직이기(계속 누름 X)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#키보드 방향키로 동그라미 움직이기(계속 누름 X)
 
import pygame
 
pygame.init() # 파이게임 초기화
background = pygame.display.set_mode((480,360)) # 창 사이즈
pygame.display.set_caption("my game"# 탭 제목
 
x_pos = background.get_size()[0// 2 #240
y_pos = background.get_size()[1// 2 #180
#print(background.get_size()) #(480,360)
 
play = True
while play: # 창을 종료하기 전까지 창을 유지하기
    for event in pygame.event.get(): #입력된 이벤트를 반복문으로 확인
        if event.type == pygame.QUIT: #창 닫기버튼(X)을 눌렀다면
            play = False  #play를 False로
        if event.type == pygame.KEYDOWN: #키보드를 누를 때
            #키보드 방향키 코딩
            if event.key == pygame.K_UP:
                print('UP')
                y_pos -= 10
            elif event.key == pygame.K_DOWN:
                print('DOWN')
                y_pos += 10
            elif event.key == pygame.K_RIGHT:
                print('RIGHT')
                x_pos += 10
            elif event.key == pygame.K_LEFT:
                print('LEFT')
                x_pos -= 10
            
    background.fill((255,0,0)) #(R,G,B)
    #pygame.draw.circle(surface, color(R,G,B), center, radius)
    pygame.draw.circle(background, (0,0,255), (x_pos, y_pos), 5)
    pygame.display.update()
    
 
pygame.quit()
cs

-실행결과

키보드 방향키로 동그라미 움직이기 (계속 누름 X)

 

 

[6] 키보드 방향키로 동그라미 움직이기(계속 누름 O)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#키보드 방향키로 동그라미 움직이기(계속 누름 O)
import pygame
 
pygame.init() # 파이게임 초기화
background = pygame.display.set_mode((480,360)) # 창 사이즈
pygame.display.set_caption("my game"# 탭 제목
 
fps = pygame.time.Clock()
 
x_pos = background.get_size()[0// 2 #240
y_pos = background.get_size()[1// 2 #180
 
to_x = 0
to_y = 0
 
play = True
while play: # 창을 종료하기 전까지 창을 유지하기
    deltaTime = fps.tick(60# 60 fps
    for event in pygame.event.get(): #입력된 이벤트를 반복문으로 확인
        if event.type == pygame.QUIT: #창 닫기버튼(X)을 눌렀다면
            play = False  #play를 False로
        if event.type == pygame.KEYDOWN: #키보드를 누를 때
            #키보드 방향키 코딩
            if event.key == pygame.K_UP:
                to_y = -1
            elif event.key == pygame.K_DOWN:
                to_y = 1
            elif event.key == pygame.K_RIGHT:
                to_x = 1
            elif event.key == pygame.K_LEFT:
                to_x = -1
 
        if event.type == pygame.KEYUP: #키보드를 뗄 때
            # to_x = 0
            # to_y = 0
            if event.key == pygame.K_UP:
                to_y = 0
            elif event.key == pygame.K_DOWN:
                to_y = 0
            elif event.key == pygame.K_RIGHT:
                to_x = 0
            elif event.key == pygame.K_LEFT:
                to_x = 0
 
    x_pos += to_x
    y_pos += to_y
 
    background.fill((255,0,0)) #(R,G,B)
    #pygame.draw.circle(surface, color(R,G,B), center, radius)
    pygame.draw.circle(background, (0,0,255), (x_pos, y_pos), 5)
    pygame.display.update()
    
 
pygame.quit()
cs

 

-실행결과

키보드 방향키로 동그라미 움직이기 (계속 누름 O)

 

 

 

 

 

 

 

728x90
반응형

댓글