6.3 공의 반사와 블록격파 구현하기
TITLE = 'Breakout'
WIDTH = 800
HEIGHT = 600
GAP_FROM_SCREEN = 50
ball = Actor('ball', (WIDTH / 2, HEIGHT / 2))
bar = Actor('bar', (WIDTH / 2, HEIGHT - GAP_FROM_SCREEN))
# 4행*8열짜리 블록더미 만들기
blocks = []
for block_row in range(4):
for block_col in range(8):
block = Actor(
'block',
(block_col * 100, block_row * 32 + GAP_FROM_SCREEN),
anchor=('left', 'top')
)
blocks.append(block)
# 볼의 초기 (방향이 있는)속도값
vx = 5
vy = -5
def draw():
screen.blit('space', (0, 0))
ball.draw()
bar.draw()
for block in blocks:
block.draw()
def update():
global vx, vy
# 반사판의 이동을 화면 안에 안에 가두기
if bar.left < 0:
bar.left = 0
if bar.right > WIDTH:
bar.right = WIDTH
# 각각의 x와 y 방향으로 거리 vx와 vy만큼 공을 이동시키기
ball.move_ip(vx, vy)
# 공이 외쪽 또는 오른쪽 벽에 부딪힐 때, x의 방향을 반대로하기
if ball.left < 0 or ball.right > WIDTH:
vx = -vx
sounds.wall.play()
# 공이 위쪽벽 또는 반사판에 부딪힐 때, y의 방향을 반대로하기
if ball.top < 0 or ball.colliderect(bar) == True:
vy = -vy
sounds.wall.play()
# 공이 블록과 부딪 때
b_index = ball.collidelist(blocks)
if b_index != -1:
vy = -vy
sounds.block.play()
blocks.pop(b_index)
# 게임종료
if ball.bottom > HEIGHT:
sounds.die.play()
game.exit()
if not blocks:
sounds.win.play()
vx = 0
vy = 0
def on_mouse_move(pos):
x, y = pos
bar.centerx = x
Last updated