게임이 실행되지만 캐릭터가 움직이지 않습니다. 어디에서 오류가 난 걸까요?
조회수 782회
import pygame
import random
from time import sleep
#윈도우 크기
window_width = 480
window_height = 800
#색을 지정하는 변수
black = (0,0,0)
white = (255,255,255)
gray = (150,150,150)
red = (255,0,0)
############################################################
# 자동차게임에 필요한 객체 = car
class Car:
image_car = ['pygame_racing/RacingCar01.png','pygame_racing/RacingCar02.png','pygame_racing/RacingCar03.png',\
'pygame_racing/RacingCar04.png','pygame_racing/RacingCar05.png','pygame_racing/RacingCar06.png',\
'pygame_racing/RacingCar07.png','pygame_racing/RacingCar08.png','pygame_racing/RacingCar09.png',\
'pygame_racing/RacingCar10.png','pygame_racing/RacingCar11.png','pygame_racing/RacingCar12.png',\
'pygame_racing/RacingCar13.png','pygame_racing/RacingCar14.png','pygame_racing/RacingCar15.png',\
'pygame_racing/RacingCar16.png','pygame_racing/RacingCar17.png','pygame_racing/RacingCar18.png',\
'pygame_racing/RacingCar19.png','pygame_racing/RacingCar20.png',]
def __init__(self,x=0,y=0,dx=0,dy=0):
self.image= ""
self.x = x
self.y = y
self.dx = dx
self.dy = dy
def load_image(self): # 가져온 이미지들을 로드하는 함수
self.image = pygame.image.load(random.choice(self.image_car))
# 이미지를 로드하는데, 랜덤으로 초이스(선택)하고 그 이미지는 1~20된 이미지_카에서
# 가져와라
self.width = self.image.get_rect().size[0] # 0이 width 1:height
self.height = self.image.get_rect().size[1]
def draw_image(self):
screen.blit(self.image,[self.x,self.y])
# 그림을 그려줌(스크린.블릿) 화면에 실제적으로 이미지를 드류해주는 것
# self.image를 그릴거고 self.x , self.y에 그릴 거다 (좌표에 그려달라)
def move_x(self):
self.x += self.dx
def move_y(self):
self.y += self.dy
def check_out_of_screen(self): # 화면을 넘어가지 않도록 제한을 거는 것
if self.y + self.width > window_width or self.x < 0:
self.x -= self.dx
def check_crash(self,car): # 충돌처리, 충돌이기에 자동차라는 객체를 받아와야함
# 그래서 self 말고 car 도 받아옴
if (self.x+self.width > car.x) and (self.x < car.x+car.width) and \
(self.y < car.y + car.height) and (self.y+self.height > car.y) :
return True
else:
return False
def draw_main_menu():
draw_x = (window_width / 2) - 200 # 중앙부터 살짝 왼쪽 좌표
draw_y = window_height / 2 # 높이도 중앙
image_intro = pygame.image.load('pygame_racing/PyCar.png')
screen.blit(image_intro, [draw_x,draw_y- 280])
font_40 = pygame.font.SysFont("FixedSys", 40,True,False)
font_30 = pygame.font.SysFont("FixedSys", 30,True,False)
text_title = font_40.render("KoJe Game", True, black)
screen.blit(text_title, [draw_x,draw_y])
text_score =font_40.render("Score: "+ str(score),True, black)
# 몇점 받았는 지 알려주는 것 (게임이 중간에 죽어서 게임에 나와졌을 때)
screen.blit(text_score, [draw_x,draw_y + 70])
text_start = font_30.render("Press Space Key to Start", True, red)
screen.blit(text_start, [draw_x,draw_y + 140])
pygame.display.flip() # flip -> 실제 화면에 들어가도록 걸어주는 것
def draw_score(): # 게임 중에 스코어 띄워주는 것
font_30 = pygame.font.SysFont("FixedSys",30,True,False)
text_score = font_30.render("Score: " + str(score), True, black)
screen.blit(text_score, [15,15])
if __name__ == '__main__' : # 처음 시작하는 부분
pygame.init()
screen = pygame.display.set_mode((window_width,window_height))
pygame.display.set_caption("KoJe Game") # 게임 타이틀
clock = pygame.time.Clock() # 게임 시간
# 믹서 : 노래넣는 것 music : 배경음악
pygame.mixer.music.load("pygame_racing/race.wav")
sound_crash = pygame.mixer.Sound("pygame_racing/crash.wav") # 충돌소리 변수
sound_engine = pygame.mixer.Sound("pygame_racing/engine.wav") # 게임 시작할때 낼 엔진소리
# 유저
player = Car(window_width/2, window_height - 150,0,0)
# width/2 -> 현 크기의 반 (중앙에 위치하겠다.)
# height - 150 -> 높이 ( 밑에서 150 쯤 띄우겠다.)
# 실제 dx,dy는 반응하는게 없으니 0 으로
player.load_image() # 20개의 이미지 중에 하나를 랜덤으로 초이스한 것을 넣는다
cars = [] # 실 플레이어의 자동차 말고 다른 자동차들 이기에 리스트로 만듬
car_count = 3 # 3개로 만듬 너무 많으면 복잡하니까 , 2개는 피하기 쉬움
for i in range(car_count):
x = random.randrange(0, window_width-55)
# 랜덤인 이유: 계속 생성되던 곳에 생성되면 재미 없으니
y = random.randrange(-150,-50) # 윗부분에서 출몰해야하니
car = Car(x,y,0,random.randint(5, 10))
# 5~ 10 사이의 디렉션을 조정해 차마다 속도를 다르게 나타내는 것 (dx,dy)
car.load_image()
cars.append(car) # 실제 car 라고 만든 객체를 cars에 추가를 하는 것
# 박진감을 위해 움직이는 것을 표현하기 위해 차선 움직이는 것을 표현 함
lanes =[]
lane_width = 10
lane_height = 80
lane_margin = 20
lane_count = 20 # 화면에 라인이 20개 표현할 것이다
lane_x = (window_width - lane_width) / 2
lane_y = -10
for i in range(lane_count):
lanes.append([lane_x, lane_y])
lane_y += lane_height + lane_margin
# 점수
score = 0
# 크래시 , 자동차가 충돌됬을 때의 크래시 이벤트
crash = True
game_on = True
while game_on:
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_on = False
if crash:
if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
crash = False
for i in range(car_count):
cars[i].x = random.randrange(0, window_width - cars[i].width)
cars[i].y = random.randrange(-150,-50)
cars[i].load_image()
player.load_image()
player.x = 175
player.dx = 0
score = 0
pygame.mouse.set_visible(False)
sound_engine.play()
sleep(5)
pygame.mixer.music.play(-1) # -1 은 반복해서 수행하게 해줌
if not crash:
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player.dx = 4
elif event.key == pygame.K_LEFT:
player.dx = -4
if event.type == pygame.KEYUP: # 키 업 ; 키를 땟을 때
if event.key == pygame.K_LEFT:
player.dx = 0 # 키 땟으니 움직이면 안됨
elif event.key == pygame.K_RIGHT:
player.dx = 0
screen.fill(gray) # 이제 게임이 그려져야 함
if not crash:
for i in range(lane_count):
pygame.draw.rect(screen, white,[lanes[i][0], lanes[i][1], lane_width, lane_height])
lanes[i][1] += 10
if lanes[i][1] > window_height: # 차선이 화면밖으로 나가면 다시 올리는것
lanes[i][1] = -40 - lane_height
player.draw_image()
player.move_x()
player.check_out_of_screen()
for i in range(car_count):
cars[i].draw_image()
cars[i].y += cars[i].dy
if cars[i].y > window_height:
score += 10
cars[i].x = random.randrange(0, window_width - car[i].width)
cars[i].y = random.randrange(-150,-50)
cars[i].dy = random.randint(5, 10)
cars[i].load_image()
for i in range(car_count): # 충돌!
if player.check_crash(cars[i]):
crash = True # 트루, 즉 충돌했다면
pygame.mixer.music.stop() # 충돌했으니 노래 끄고
sound_crash.play() # 크래시 소리 on
sleep(2) # 충돌했으니 2초 정도 대기
pygame.mouse.set_visible(True)
break
draw_score()
pygame.display.flip()
else:
draw_main_menu()
clock.tick(60)
pygame.quit()
게임이 실행이 되고, 소리도 나고, 배경도 잘 적용이 되어있습니다. 캐릭터는 움직이지 않는데 어디에서 오류가 난걸까요?
댓글 입력