노는게 제일 좋습니다.

이벤트 받아 움직이며 상자 먹기 본문

Python/기타 공부

이벤트 받아 움직이며 상자 먹기

노는게 제일 좋습니다. 2016. 2. 7. 17:31

원 코드 출처 http://inventwithpython.com/collisionDetection.py


흰색이 캐릭터. 초록색이 상자


파이게임 윈도우 내에서 마우스로 이벤트를 주거나, 키보드를 입력하면 event.get()으로 리스트가 반환되고

그 때마다 캐릭터가 움직이는 코드가 실행된다.


캐릭터와 상자가 충돌하면 상자가 사라진다.



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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
import pygame, sys, random
from pygame.locals import *
 
def doRectsOverlap(rect1, rect2):
    for a, b in [(rect1,rect2), (rect2, rect1)]:
        if ((isPointInsideRect(a.left, a.top, b)) or
            (isPointInsideRect(a.left, a.bottom, b)) or
            (isPointInsideRect(a.right, a.top, b)) or
            (isPointInsideRect(a.right, a.bottom, b))):
            return True
    return False
 
def isPointInsideRect(x,y,rect):
    if ( x > rect.left) and ( x<rect.right ) and ( y>rect.top ) and ( y<rect.bottom ):
        return True
    else :
        return False
 
pygame.init()
mainClock = pygame.time.Clock()
 
WINDOWWIDTH = 400
WINDOWHEIGHT = 400
windowSurface = pygame.display.set_mode((WINDOWWIDTH,WINDOWHEIGHT),0,32)
pygame.display.set_caption('Collision Detection')
 
DOWNLEFT =1
DOWNRIGHT = 3
UPLEFT = 7
UPRIGHT = 9
 
MOVESPEED = 4
 
BLACK = (0,0,0)
GREEN = (02550)
WHITE = (255,255,255)
 
foodCounter = 0
NEWFOOD = 40
FOODSIZE = 20
bouncer = {'rect':pygame.Rect(300,100,50,50), 'dir':UPLEFT}
foods = []
for i in range(20):
    foods.append(pygame.Rect(random.randint(0, WINDOWWIDTH - FOODSIZE), random.randint(0,WINDOWHEIGHT-FOODSIZE), FOODSIZE, FOODSIZE))
 
while True:
    for event in pygame.event.get():
        if event.type == QUIT:
            pygame.quit()
            sys.exit()
 
        foodCounter += 1
        if foodCounter >= NEWFOOD:
            foodCounter = 0
            foods.append(pygame.Rect(random.randint(0,WINDOWWIDTH-FOODSIZE), random.randint(0,WINDOWHEIGHT-FOODSIZE), FOODSIZE, FOODSIZE))
 
        windowSurface.fill(BLACK)
 
        if bouncer['dir'== DOWNLEFT:
            bouncer['rect'].left -= MOVESPEED
            bouncer['rect'].top += MOVESPEED
        if bouncer['dir'== DOWNRIGHT:
            bouncer['rect'].left += MOVESPEED
            bouncer['rect'].top += MOVESPEED
        if bouncer['dir'== UPLEFT:
            bouncer['rect'].left -= MOVESPEED
            bouncer['rect'].top -= MOVESPEED
        if bouncer['dir'== UPRIGHT:
            bouncer['rect'].left += MOVESPEED
            bouncer['rect'].top -= MOVESPEED
 
 
        if bouncer['rect'].top < 0:
            # bouncer has moved past the top
            if bouncer['dir'== UPLEFT:
                bouncer['dir'= DOWNLEFT
            if bouncer['dir'== UPRIGHT:
                bouncer['dir'= DOWNRIGHT
        if bouncer['rect'].bottom > WINDOWHEIGHT:
            # bouncer has moved past the bottom
            if bouncer['dir'== DOWNLEFT:
                bouncer['dir'= UPLEFT
            if bouncer['dir'== DOWNRIGHT:
                bouncer['dir'= UPRIGHT
        if bouncer['rect'].left < 0:
            # bouncer has moved past the left side
            if bouncer['dir'== DOWNLEFT:
                bouncer['dir'= DOWNRIGHT
            if bouncer['dir'== UPLEFT:
                bouncer['dir'= UPRIGHT
        if bouncer['rect'].right > WINDOWWIDTH:
            # bouncer has moved past the right side
            if bouncer['dir'== DOWNRIGHT:
                bouncer['dir'= DOWNLEFT
            if bouncer['dir'== UPRIGHT:
                bouncer['dir'= UPLEFT
 
        pygame.draw.rect(windowSurface,WHITE,bouncer['rect'])
 
        for food in foods[:]:
            if doRectsOverlap(bouncer['rect'], food):
                foods.remove(food)
 
        for i in range(len(foods)):
            pygame.draw.rect(windowSurface, GREEN, foods[i])
 
        pygame.display.update()
        mainClock.tick(40)
 
 
cs







Comments