무료
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 해결됨파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
세 번째 공부터 바닥에 튕기지 않습니다.
코드를 다 작성하고 게임을 진행했습니다. 그런데 세 번째 공만 바닥에 튕기지 않고 사라집니다. 어느 코드가 잘못 입력되었는지 찾아보려고 노력은 했습니다만 찾지 못했습니다. 혹시 어디가 잘못 입력 되었는지 알려주실 수 있으신가요? import os import pygame ############################################################################### # 기본 초기화 (반드시 해야 하는 것들) pygame.init() # 화면 크기 설정 screen_width = 640 # 가로 크기 screen_height = 480 # 세로 크기 screen = pygame.display.set_mode((screen_width, screen_height)) # 화면 타이틀 설정 pygame.display.set_caption("Nado Pang") # 게임 이름 # FPS clock = pygame.time.Clock() ############################################################################### # 1. 사용자 게임 초기화 (배경 화면, 게임 이미지, 좌표, 속도, 폰트 등) current_path = os.path.dirname(__file__) # 현재 파일 위치 변환 image_path = os.path.join(current_path, "images") # images 폴더 반환 # 배경 만들기 background = pygame.image.load(os.path.join(image_path, "backgroung.png")) # 스테이지 만들기 stage = pygame.image.load(os.path.join(image_path, "stage.png")) stage_size = stage.get_rect().size stage_height = stage_size[1] # 스테이지의 높이 위에 캐릭터를 두기 위해 사용 # 캐릭터 만들기 character = pygame.image.load(os.path.join(image_path, "character.png")) character_size = character.get_rect().size character_width = character_size[0] character_height = character_size[1] character_x_pos = (screen_width / 2) - (character_width /2) character_y_pos = screen_height - character_height - stage_height # 방향 character_to_x = 0 # 속도 character_speed = 5 # 무기 만들기 weapon = pygame.image.load(os.path.join(image_path, "weapon.png")) weapon_size = weapon.get_rect().size weapon_width = weapon_size[0] # 무기는 한번에 여러발 발사 가능 weapons = [] # 무기 이동 속도 weapon_speed = 10 # 공 만들기 ball_images = [ pygame.image.load(os.path.join(image_path, "ball1.png")), pygame.image.load(os.path.join(image_path, "ball2.png")), pygame.image.load(os.path.join(image_path, "ball3.png")), pygame.image.load(os.path.join(image_path, "ball4.png"))] # 공 크기에 따른 최초 스피드 ball_speed_y = [-18, -15, 12, -9] # index 0, 1, 2, 3에 해당하는 값 # 공들 balls = [] # 최초 발생하는 큰 공 추가 balls.append({ "pos_x" : 50, # 공의 x 좌표 "pos_y" : 50, # 공의 y 좌표 "img_idx" : 0, # 공의 이미지 인덱스 "to_x": 3, # x축 이동방향, -3이면 왼쪽, 3이면 오른쪽 "to_y": -6, # y축 이동방향 "init_spd_y": ball_speed_y[0]}) # y 최초 속도 # 사라질 무기, 공 정보 저장 변수 weapon_to_remove = -1 ball_to_remove = -1 # Font 정의 game_font = pygame.font.Font(None, 40) total_time = 100 start_ticks = pygame.time.get_ticks() # 게임 종료 메시지 # Time Out(시간 초과 실패) # Mission Complete(성공) # Game Over (캐릭터가 공에 맞아서 실패) game_result = "Game Over" running = True while running: dt = clock.tick(30) # 2. 이벤트 처리 (키보드, 마우스 등) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: character_to_x -= character_speed elif event.key == pygame.K_RIGHT: character_to_x += character_speed elif event.key == pygame.K_SPACE: # 무기 발사 weapon_x_pos = character_x_pos + (character_width / 2) - (weapon_width / 2) weapon_y_pos = character_y_pos weapons.append([weapon_x_pos, weapon_y_pos]) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: character_to_x = 0 # 3. 게임 캐릭터 위치 정의 character_x_pos += character_to_x if character_x_pos < 0: character_x_pos = 0 elif character_x_pos > screen_width - character_width: character_x_pos = screen_width - character_width # 무기 위치 조정 # 100, 200 -> 180, 160, 140, ... # 500, 200 -> 180, 160, 140, ... weapons = [ [w[0], w[1] - weapon_speed] for w in weapons] # 무기 위치를 위로 # 천장에 닿은 무기 없애기 weapons = [ [w[0], w[1] - weapon_speed] for w in weapons if w[1] > 0] # 공 위치 정의 for ball_idx, ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] ball_size = ball_images[ball_img_idx].get_rect().size ball_width = ball_size[0] ball_height = ball_size[1] # 가로벽에 닿았을 때 공 이동 위치 변경(튕겨나오는 효과) if ball_pos_x < 0 or ball_pos_x > screen_width - ball_width: ball_val["to_x"] = ball_val["to_x"] * -1 # 세로 위치 # 스테이지에 튕겨서 올라가는 처리 if ball_pos_y >= screen_height - stage_height - ball_height: ball_val["to_y"] = ball_val["init_spd_y"] # 씨발 키 하나때문에 시간 잡아먹게 하지 마라 else: # 그 외의 모든 경우에는 속도를 증가 ball_val["to_y"] +=0.5 ball_val["pos_x"] += ball_val["to_x"] ball_val["pos_y"] += ball_val["to_y"] # 4. 충돌 처리 # 캐릭터 rect 정보 업데이트 character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos for ball_idx, ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] # 공 rect 정보 업데이트 ball_rect = ball_images[ball_img_idx].get_rect() ball_rect.left = ball_pos_x ball_rect.top = ball_pos_y # 공과 캐릭터 충돌 처리 if character_rect.colliderect(ball_rect): running = False break # 공과 무기들 충돌 처리 for weapon_idx, weapon_val in enumerate(weapons): weapon_pos_x = weapon_val[0] weapon_pos_y = weapon_val[1] # 무기 rect 정보 업데이트 weapon_rect = weapon.get_rect() weapon_rect.left = weapon_pos_x weapon_rect.top = weapon_pos_y # 충돌 체크 if weapon_rect.colliderect(ball_rect): weapon_to_remove = weapon_idx # 해당 무기 없애기 위한 값 설정 ball_to_remove = ball_idx # 해당 공 없애기 위한 값 설정 # 가장 작은 크기의 공이 아니라면 다음 단계의 공으로 나눠주기 if ball_img_idx < 3: # 현재 공 크기 정보를 가지고 옴 ball_width = ball_rect.size[0] ball_height = ball_rect.size[1] # 나눠진 공 정보 small_ball_rect = ball_images[ball_img_idx + 1].get_rect() small_ball_width = small_ball_rect.size[0] small_ball_height = small_ball_rect.size[1] # 왼쪽으로 튕겨나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width /2) - (small_ball_width / 2), "pos_y" : ball_pos_y + (ball_height /2) - (small_ball_height / 2), "img_idx" : ball_img_idx + 1, "to_x": -3, "to_y": -6, "init_spd_y": ball_speed_y[ball_img_idx + 1]}) # 오른쪽으로 튕겨나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width /2) - (small_ball_width / 2), "pos_y" : ball_pos_y + (ball_height /2) - (small_ball_height / 2), "img_idx" : ball_img_idx + 1, "to_x": 3, "to_y": -6, "init_spd_y": ball_speed_y[ball_img_idx + 1]}) break else: # 계속 게임을 진행 continue # 안쪽 for 문이 조건이 맞지 않으면 continue. 바깥 for문 계속 수행 break # 안쪽 for문에서 break를 만나면 여기로 진입 가능. 이중 for문을 한번에 # 충돌된 공이나 무기 없애기 if ball_to_remove > -1: del balls[ball_to_remove] ball_to_remove = -1 if weapon_to_remove > -1: del weapons[weapon_to_remove] weapon_to_remove = -1 # 모든 공을 없앤 경우 게임 종료 (성공) if len(balls) == 0: game_result = "Mission Complete" running = False # 5. 화면에 그리기 screen.blit(background, (0,0)) for weapon_x_pos, weapon_y_pos in weapons: # weapon_y_pos을 weapon_x_pos으로 입력한 결과 1시간 이상 낭비 screen.blit(weapon, (weapon_x_pos, weapon_y_pos)) for idx, val in enumerate(balls): ball_pos_x = val["pos_x"] ball_pos_y = val["pos_y"] ball_img_idx = val["img_idx"] screen.blit(ball_images[ball_img_idx], (ball_pos_x, ball_pos_y)) screen.blit(stage, (0 ,screen_height - stage_height)) screen.blit(character, (character_x_pos, character_y_pos)) # 경과 시간 계산 elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 # ms -> s timer = game_font.render("Time : {}".format(int(total_time - elapsed_time)), True, (255, 255, 255)) screen.blit(timer, (10, 10)) # 시간 초과시 if total_time - elapsed_time <= 0: game_result = "Time Out" running = False pygame.display.update() # 게임화면을 다시 그리기 # 게임 오버 메시지 msg = game_font.render(game_result, True, (255, 255, 0)) # 노란색 msg_rect = msg.get_rect(center= (int(screen_width / 2), int(screen_height / 2))) screen.blit(msg, msg_rect) pygame.display.update() # 2초 대기 pygame.time.delay(2000) pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
pygame.quit()
import pygame pygame.init() screan_width = 480 screan_height = 640 screan = pygame.display.set_mode((screan_width, screan_height)) pygame.display.set_caption("Nado Game") background = pygame.image.load("C:/Users/koko4/OneDrive/Desktop/PyCharm/PyGame/pygame_basic/BackGround.png") Running = True while Running : for event in pygame.event.get(): if event.type == pygame.QUIT : Running == False screan.blit(background, (0, 0)) pygame.display.update() pygame.display.update() pygame.quit() 소스코드는 보여드리는 바와 같이 똑같이 작성 하였습니다. 실행은 잘되는대 끌려고 X 버튼을 누르니 종료 되지 않 습니다. 어떻게 해야 되죠? * 개발환경과 파이썬은 잘 설치 되있으며 최신버전으로 설치 되어있습니다.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
Linting
파이참은 어디서 설정해야 될지 모르겠습니다.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공에 무기가 닿았을 때 공이 안 사라져요
import pygame, os from pygame.constants import K_LEFT, K_RIGHT pygame.init() # 초기화 (항상 적어야 하는것) pygame.mixer.init() # 화면 크기 screen_width = 640 # 가로 screen_height = 480 # 세로 screen = pygame.display.set_mode((screen_width, screen_height)) # 화면 설정 # 화면 타이틀 pygame.display.set_caption("dudcks pang") # 게임 이름 current_path = os.path.dirname(__file__) # 현재 파일의 위치 반환 image_path = os.path.join(current_path, "images") music_path = os.path.join(current_path, "music") # 배경 만들기 background = pygame.image.load(os.path.join(image_path, "background.png")) # 스테이지 만들기 stage = pygame.image.load(os.path.join(image_path, "stage.png")) stage_size = stage.get_rect().size stage_height = stage_size[1] # 스테이지의 높이 위에 캐릭터를 두기 위해 사용 # 캐릭터 만들기 character = pygame.image.load(os.path.join(image_path, "character.png")) character_size = character.get_rect().size character_width = character_size[0] character_height = character_size[1] character_x = (screen_width / 2) - (character_width / 2 ) character_y = screen_height - character_height - stage_height # 캐릭터 이동 방향 character_to_x = 0 # 캐릭터 이동 속도 character_speed = 5 # 무기 만들기 weapon = pygame.image.load(os.path.join(image_path, "weapon.png")) weapon_size = weapon.get_rect().size weapon_width = weapon_size[0] # 무기는 한 번에 여러발 발사 가능 weapons = [] # 무기 이동 속도 weapon_speed = 10 # 공 만들기 (4개 따로 처리) ball_images = [ pygame.image.load(os.path.join(image_path, "balloon1.png")), pygame.image.load(os.path.join(image_path, "balloon2.png")), pygame.image.load(os.path.join(image_path, "balloon3.png")), pygame.image.load(os.path.join(image_path, "balloon4.png"))] # 공 크기에 따른 최초 스피드 ball_speed_y = [-18, -15, -12, -9] # index 0, 1, 2, 3 에 해당되는 값 # 공들 balls = [] # 최초 발생하는 큰 공 추가 balls.append({ "pos_x" : 50, # 공의 x좌표 "pos_y" : 50, # 공의 y좌표 "img_idx" : 0, # 공의 이미지 인덱스 "to_x" : 3, # x축 이동방향 "to_y" : -6, # y축 이동방향 "init_spd_y" : ball_speed_y[0] }) # y 최초 속도 # 사라질 무기, 공 정보 저장 변수 weapon_to_remove = -1 ball_to_remove = -1 # 음악 music = pygame.mixer.music.load(os.path.join(music_path, "music.mp3")) pygame.mixer.music.set_volume(0.2) pygame.mixer.music.play() MUSIC_END_EVENT = pygame.USEREVENT + 1 pygame.mixer.music.set_endevent(MUSIC_END_EVENT) # FPS clock = pygame.time.Clock() # 이벤트 루트 running = True while running: dt = clock.tick(30) # 초당 프레임 수 for event in pygame.event.get(): # 들어오는 이벤트를 받아옴 if event.type == pygame.QUIT: # X버튼을 눌렀을때 running = False if event.type == pygame.KEYDOWN: # 키 이벤트 if event.key == pygame.K_LEFT: character_to_x -= character_speed elif event.key == pygame.K_RIGHT: character_to_x += character_speed elif event.key == pygame.K_SPACE: # 무기 발사 weapon_x = character_x + (character_width / 2) - (weapon_width / 2) weapon_y = character_y weapons.append([weapon_x, weapon_y]) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: character_to_x = 0 if event.type == MUSIC_END_EVENT: pygame.mixer.music.play() # 캐릭터 위치 정의 character_x += character_to_x if character_x < 0: character_x = 0 elif character_x > screen_width - character_width: character_x = screen_width - character_width # 무기 위치 조정 # 100, 200 -> 180, 160, 140, ... # 500, 200 -> 180, 160, 140, ... weapons = [ [w[0], w[1] - weapon_speed] for w in weapons] # 천장에 닿은 무기 없애기 weapons = [ [w[0], w[1] - weapon_speed] for w in weapons if w[1] > 0] # 공 위치 정의 for ball_idx, ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] ball_size = ball_images[ball_img_idx].get_rect().size ball_width = ball_size[0] ball_height = ball_size[1] # 가로 벽에 닿았을때 공 이동 위치 변경 (튕겨 나오는 효과) if ball_pos_x <= 0 or ball_pos_x > screen_width - ball_width: ball_val["to_x"] = ball_val["to_x"] * -1 # 세로 위치 # 스테이지에 튕겨서 올라가는 처리 if ball_pos_y > screen_height - stage_height - ball_height: ball_val["to_y"] = ball_val["init_spd_y"] else: # 그 외의 모든 경우에는 속도를 증가 ball_val["to_y"] += 0.5 ball_val["pos_x"] += ball_val["to_x"] ball_val["pos_y"] += ball_val["to_y"] character_rect = character.get_rect() character_rect.left = character_x character_rect.top = character_y for ball_idx, ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] # 공 rect 정보 업데이트 ball_rect = ball_images[ball_img_idx].get_rect() ball_rect.left = ball_pos_x ball_rect.top = ball_pos_y # 공과 캐릭터 충돌 처리 if character_rect.colliderect(ball_rect): running = False break # 공과 무기들 충돌 처리 for weapon_idx, weapon_val in enumerate(weapons): weapon_x = weapon_val[0] weapon_y = weapon_val[1] # 무기 rect 정보 업데이트 weapon_rect = weapon.get_rect() weapon_rect.left = weapon_x weapon_rect.top = weapon_y # 충돌 처리 if weapon_rect.colliderect(ball_rect): weapon_to_remove = weapon_idx ball_to_remove = ball_idx # 가장 작은 크기의 공이 아니라면 다음 단계의 공으로 나눠주기 if ball_img_idx < 3: # 현재 공 크기 정보를 가지고 옴 ball_width = ball_rect.size[0] ball_height = ball_rect.size[1] # 나눠진 공 정보 small_ball_rect = ball_images[ball_img_idx + 1].get_rect() small_ball_width = small_ball_rect.size[0] small_ball_height = small_ball_rect.size[1] # 왼쪽으로 튕겨나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), # 공의 x좌표 "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), # 공의 y좌표 "img_idx" : ball_img_idx + 1, # 공의 이미지 인덱스 "to_x" : -3, # x축 이동방향 "to_y" : -6, # y축 이동방향 "init_spd_y" : ball_speed_y[ball_img_idx + 1] }) # y 최초 속도 # 오른쪽으로 튕겨나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), # 공의 x좌표 "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), # 공의 y좌표 "img_idx" : ball_img_idx + 1, # 공의 이미지 인덱스 "to_x" : 3, # x축 이동방향 "to_y" : -6, # y축 이동방향 "init_spd_y" : ball_speed_y[ball_img_idx + 1] }) # y 최초 속도 break # 충돌된 공 or 무기 삭제 if ball_to_remove > -1: del balls[ball_to_remove] ball_to_remove = -1 if weapon_to_remove > -1: del weapons[weapon_to_remove] weapon_to_remove = -1 # 화면 그리기 screen.blit(background, (0, 0)) for weapon_x, weapon_y in weapons: screen.blit(weapon, (weapon_x, weapon_y)) for idx, val in enumerate(balls): ball_pos_x = val["pos_x"] ball_pos_y = val["pos_y"] ball_img_idx = val["img_idx"] screen.blit(ball_images[ball_img_idx], (ball_pos_x, ball_pos_y)) screen.blit(stage, (0, screen_height - stage_height)) screen.blit(character, (character_x, character_y)) pygame.display.update() # 게임 화면 다시 그리기 (항상 적어야 하는것) # pygame 종료 pygame.quit 이렇게 해봤는데 어떨때는 잘 되고 어떨때는 작은 공들이 우수수 나와요
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
충돌감지에서 궁금한점
character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos enemy_rect = enemy.get_rect() enemy_rect.left = enemy_x_pos enemy_rect.top = enemy_y_pos 여기서 .left 랑 .top가 left인데 왜 오른쪽 충돌도 인식하는지 top도 왜 아래쪽 충돌도 인식하는지 궁금합니다. 그리고 양옆 충돌은 충돌로 인식안하고 위아래 충돌만 충돌이라고 인식하고 싶어서 위에 코드에서 character_rect = character.get_rect() character_rect.top = character_y_pos enemy_rect = enemy.get_rect() enemy_rect.top = enemy_y_pos 이렇게 두번째 줄을 지웠는데 창이 열리자마자 충돌로 인식하고 꺼지는건 왜그런건가요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
실행을 할때 실행 화면이 안뜨는데 어떤 문제가 있는걸까요?
코드는 전부 뜰린게 없는데 배경을 설정할 때부터 실행할 때 검은색 화면이 나오질 않습니다. 어떤 문제가 있는걸 까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
실행이안돼요
import pygame pygame.init() # 초기화 (반드시 필요) # 화면 크기 설정 screen_width = 480 # 가로 크기 screen_height = 640 # 세로 크기 screen = pygame.display.set_mode((screen_width, screen_height)) # 화면 타이틀 설정 pygame.display.set_caption("123") # 게임 이름 # FPS clock = pygame.time.Clock() # 배경 이미지 불러오기 background = pygame.image.load("C:/Users/ibosk/OneDrive/바탕 화면/PythonWorkspace/pygame/background.png") # 캐릭터 (스프라이트) 불러오기 character = pygame.image.load("C:/Users/ibosk/OneDrive/바탕 화면/PythonWorkspace/pygame/character.png") character_size = character.get_rect().size # 이미지의 크기를 구해본다 character_width = character_size[0] # 캐릭터의 가로크기 character_height = character_size[1] # 캐릭터의 세로크기 character_x_pos = (screen_width / 2) - (character_width / 2) # 화면 가로의 절반 크기에 해당 하는 곳에 위치 character_y_pos = screen_height - character_height # 화면 세로크기 가장 아래에 해당 하는 곳에 위치 # 이동할 좌표 to_x = 0 to_y = 0 # 이동 속도 character_speed = 0.6 #적 enemy 캐릭터 enemy = pygame.image.load("C:/Users/ibosk/OneDrive/바탕 화면/PythonWorkspace/pygame/enemy.png") enemy_size = enemy.get_rect().size # 이미지의 크기를 구해본다 enemy_width = enemy_size[0] # 캐릭터의 가로크기 enemy_height = enemy_size[1] # 캐릭터의 세로크기 enemy_x_pos = (screen_width / 2) - (enemy_width / 2) # 화면 가로의 절반 크기에 해당 하는 곳에 위치 enemy_y_pos = (screen_height / 2) - (enemy_height / 2) # 화면 세로크기 가장 아래에 해당 하는 곳에 위치 # 이벤트 루프 running = True # 게임이 진행중인가? while running: dt = clock.tick(60) #게임화면의 초당 프레임 수를 설정 print("fps : " + str(clock.get_fps())) for event in pygame.event.get(): # 어떤 이벤트가 발생하였는가> if event.type == pygame.QUIT: # 창이 닫히는 이벤트가 발생하였는가? running = False # 게임이 진행중이 아님 if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: to_x -= character_speed elif event.key == pygame.K_RIGHT: to_x += character_speed elif event.key == pygame.K_UP: to_y -= character_speed elif event.key == pygame.K_DOWN: to_y += character_speed if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: to_x = 0 if event.key == pygame.K_UP or event.key == pygame.K_DOWN: to_y = 0 character_x_pos += to_x * dt character_y_pos += to_y * dt if character_x_pos < 0: character_x_pos = 0 elif character_x_pos > screen_width - character_width: character_x_pos = screen_width - character_width if character_y_pos < 0: character_y_pos = 1 elif character_y_pos > screen_height - character_y_pos: character_y_pos = screen_height - character_y_pos #충돌 처리를 위한 rect 정보 업데이트 character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos enemy_rect = enemy.get_rect() enemy_rect.left = enemy_x_pos enemy_rect.top = enemy_y_pos # 충돌 체크 if character_rect.collidercet(enemy_rect): print("충돌했어요") running = False screen.blit(background, (0, 0)) # 배경 그리기 screen.blit(character, (character_x_pos, character_y_pos)) #캐릭터 그리기 screen.blit(enemy, (enemy_x_pos , enemy_y_pos)) #적 그리기 pygame.display.update() # 게임 화면을 다시 그리기! # pygame 종료 pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
델타값 질문입니다.
dt값은 tick 함수로 쪼개는거라 특정 값을 나눠주는건가요? 프레임값이 낮아질수록 높아지는걸로 보면 그런거같은데 확실하지가 않아서....
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
elapsed_time
253번 줄에 elapsed_time = pygame.time.get_ticks() - start_ticks로 되어있는데 89번줄에 start_ticks = pygame.time.get_ticks() 로 되어있습니다. 즉, 동일한 두개를 서로 빼는 것이 아닌가 하는 의문이 듭니다
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
character_x_pos와 character_to_x 차이
x_pos와 to_x를 별개로 두는 이유가 있나요?? to_x 없이 LEFT KEY를 눌렀을 때 (x_pos) - (x_speed)를 하면 동일한 효과를 받을 수 있지 않나요? 지금 제 환경이 환경인지라 컴파일을 할 수 없어서 죄송합니다..
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
2:31, line 70 질문
장애물은 위에서 아래로 내려오는데 왜 -= 가 아닌 += 인건가요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
video system not initialized
pygame.error: video system not initialized 라는 오류가 for문에서 뜨는데 검색을 해봐도 어떤 문제인지 잘 모르겠어요 !!
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
"pip install pygame"이라고 입력했을 때 오류가 뜹니다.
"pip install pygame"이라고 입력했을 때 아래와 같은 오류가 뜹니다. pip : 'pip' 용어가 cmdlet, 함수, 스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다. 이름이 정확한지 확인하고 경로가 포함된 경우 경로가 올바른지 검증한 다음 다시 시도하십시오. 위치 줄:1 문자:1 + pip install pygame + ~~~ + CategoryInfo : ObjectNotFound: (pip:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException 어떤 문제이고, 어떻게 해야 해결할 수 있을까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
그림들 어디서 다운로드 하는지 알려주실 수 있나요?
알려주시면 감사하겠습니다
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
1_create_frame.py에서 이렇게 뜨고 2_background부터는 안뜨네여..
어디서부터 잘못된건지 확인해 봐야 할까요...ㅜㅜㅜ?̊̈?̊̈
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
이렇게 뜨고 안됩니다.
창이 안켜지고 이렇게 떠요 'C:/Users/---/AppData/Local/Programs/Python/Python39/python.exe' 용어가 cmdlet, 함수, 스크립트 파일 또는 실행할 수 있는 프로그램 이름으로 인식되지 않습니다. 이름이 정확한지 확인하고 경로가 포함된 경우 경로가 올바른지 검증한 다음 다시 시도하십시오. 위치 줄:1 문자:3 + & C:/Users/우리집/AppData/Local/Programs/Python/Python39/python.exe "c:/ ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : ObjectNotFound: (C:/Users/우리집/Ap...on39/python.exe:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
무기랑 공이 닿으면 쪼개지는데 쪼개진 공2개중 오른쪽으로 나오는 공은 잘 움직이는데 왼쪽으로 움직여야되는 공이 멈춤니다
if ball_img_idx < 3: #현재 공 크기 정보 ball_width = ball_rect.size[0] ball_height = ball_rect.size[1] #나눠진 공 정보 small_ball_rect = ball_images[ball_img_idx + 1].get_rect() small_ball_width = small_ball_rect.size[0] small_ball_height = small_ball_rect.size[1] #왼쪽으로 팅겨 나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), #공의 x좌표 "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), #공의 y좌표 "img_idx" : ball_img_idx + 1, #공의 이미지 인덱스 "to_x": -3, #x축 이동 방향(+ 오른쪽, - 왼쪽) "to_y": -6, #t축 이동 방향 "init_spd_y" : ball_speed_y[ball_img_idx + 1] #y 최초 속도 }) #오른쪽으로 튕겨 나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), #공의 x좌표 "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), #공의 y좌표 "img_idx" : ball_img_idx + 1, #공의 이미지 인뎃스 "to_x": +3, #x축 이동 방향(+ 오른쪽, - 왼쪽) "to_y": -6, #t축 이동 방향 "init_spd_y" : ball_speed_y[ball_img_idx + 1] #y 최초 속도 }) break
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
오류인것 같은데 잘 모르겠습니다 도와주세요
제가 뭘 잘못쓴건지는 모르겠는데 이렇게 나오네요 이게 뭔가요? 그리고 해결책도 알려주세요
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
NameError라는데 뭔지 모르겠어요
코드는 이렇게 적었는데 계속 이렇게 떠요 이거 어떻게 해야되나요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
무기를 쓰고 0.5초 정도 기다리게 하고 싶어요
전체코드: import pygame ############################################################################## #기본 초기화 (반드시) pygame.init() #화면크기설정 screen_width = 640 screen_height = 480 screen = pygame.display.set_mode((screen_width, screen_height)) #화면 타이틀 설정 pygame.display.set_caption("pang game") # FPS clock = pygame.time.Clock() ############################################################################## #배경 만들기 background = pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\background.png") #스테이지 만들기 stage = pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\stage.png") stage_size = stage.get_rect().size stage_height = stage_size[1] #캐릭터 만들기 character = pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\character.png") character_size = character.get_rect().size character_width = character_size[0] character_height = character_size[1] character_x_pos = (screen_width / 2) - (character_width / 2) character_y_pos = screen_height - character_height - stage_height #캐릭터 이동 방향 character_to_x_LEFT = 0 character_to_x_RIGHT = 0 #캐릭터 이동 속도 character_speed = 5 #무기 만들기 weapon = pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\weapon.png") weapon_size = weapon.get_rect().size weapon_width = weapon_size[0] #무기는 한 번에 여러 발 발사 가능 weapons = [] #무기 이동 속도 weapon_speed = 10 #공 만들기 (4개 크기에 대해 따로 처리) ball_images = [ pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\balloon1.png"), pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\balloon2.png"), pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\balloon3.png"), pygame.image.load("C:\\Users\\w10\\Desktop\\python work space\\pygame_basic\\pygame_project\\images\\balloon4.png")] #공 크기에 따른 최초 스피드 ball_speed_y = [-18, -15, -12, -9] #공들 balls = [] #최초 발생하는 큰 공 추가 balls.append({ "pos_x" : 50, "pos_y" : 50, "img_idx" : 0, "to_x": 3, "to_y": -6, "init_spd_y": ball_speed_y[0]}) #사라질 무기, 공 정보 저장 변수 weapon_to_remove = -1 ball_to_remove = -1 #Font 정의 game_font = pygame.font.Font(None, 40) total_time = 100 start_ticks = pygame.time.get_ticks() #게임 종료 메시지 game_result = "Game Over" #이벤트 루프 running = True while running: dt = clock.tick(30) #키보드 이벤트 for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: character_to_x_LEFT -= character_speed elif event.key == pygame.K_RIGHT: character_to_x_RIGHT += character_speed elif event.key == pygame.K_SPACE: weapon_x_pos = character_x_pos + (character_width / 2) - (weapon_width / 2) weapon_y_pos = character_y_pos weapons.append([weapon_x_pos, weapon_y_pos]) if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT: character_to_x_LEFT = 0 elif event.key == pygame.K_RIGHT: character_to_x_RIGHT = 0 #게임 캐릭터 위치 정의 character_x_pos += character_to_x_LEFT + character_to_x_RIGHT if character_x_pos < 0: character_x_pos = 0 elif character_x_pos > screen_width - character_width: character_x_pos = screen_width - character_width #무기 위치 조정 weapons = [ [w[0], w[1] - weapon_speed] for w in weapons] #천장에 닿은 무기 없애기 weapons = [ [w[0], w[1]] for w in weapons if w[1] > 0] #공 위치 정의 for ball_idx, ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] ball_size = ball_images[ball_img_idx].get_rect().size ball_width = ball_size[0] ball_height = ball_size[1] #가로 벽에 닿았을 때 공 이동 위치 변경 (튕겨 나오는 효과) if ball_pos_x < 0 or ball_pos_x > screen_width - ball_width: ball_val["to_x"] = ball_val["to_x"] * -1 #세로 위치 #스테이지에 튕겨서 올라가는 처리 if ball_pos_y >= screen_height - stage_height - ball_height: ball_val["to_y"] = ball_val["init_spd_y"] else: ball_val["to_y"] += 0.5 ball_val["pos_x"] += ball_val["to_x"] ball_val["pos_y"] += ball_val["to_y"] #충돌 처리 #캐릭터 rect 정보 업데이트 character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos for ball_idx, ball_val in enumerate(balls): ball_pos_x = ball_val["pos_x"] ball_pos_y = ball_val["pos_y"] ball_img_idx = ball_val["img_idx"] #공 rect 정보 업데이트 ball_rect = ball_images[ball_img_idx].get_rect() ball_rect.left = ball_pos_x ball_rect.top = ball_pos_y #공과 캐릭터 충돌 체크 if character_rect.colliderect(ball_rect): running = False break #공과 무기들 충돌 처리 for weapon_idx, weapon_val in enumerate(weapons): weapon_x_pos = weapon_val[0] weapon_y_pos = weapon_val[1] #무기 rect 정보 업데이트 weapon_rect = weapon.get_rect() weapon_rect.left = weapon_x_pos weapon_rect.top = weapon_y_pos #충돌체크 if weapon_rect.colliderect(ball_rect): weapon_to_remove = weapon_idx ball_to_remove = ball_idx #가장 작은 크기의 공이 아니라면 다음 단계의 공으로 나눠주기 if ball_img_idx < 3: #현재 공 크기 정보를 가지고 옴 ball_width = ball_rect.size[0] ball_height = ball_rect.size[1] #나눠진 공 정보 small_ball_rect = ball_images[ball_img_idx + 1].get_rect() small_ball_width = small_ball_rect.size[0] small_ball_height = small_ball_rect.size[1] #왼쪽으로 튕겨나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), "img_idx" : ball_img_idx + 1, "to_x": -3, "to_y": -6, "init_spd_y": ball_speed_y[ball_img_idx + 1]}) #오른쪽으로 튕겨나가는 작은 공 balls.append({ "pos_x" : ball_pos_x + (ball_width / 2) - (small_ball_width / 2), "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), "img_idx" : ball_img_idx + 1, "to_x": 3, "to_y": -6, "init_spd_y": ball_speed_y[ball_img_idx + 1]}) break else: continue break #충돌된 공 or 무기 없애기 if ball_to_remove > -1: del balls[ball_to_remove] ball_to_remove = -1 if weapon_to_remove > -1: del weapons[weapon_to_remove] weapon_to_remove = -1 if len(balls) == 0: game_result = "Mission Complete" running = False # 화면에 그리기 screen.blit(background, (0, 0)) for weapon_x_pos, weapon_y_pos in weapons: screen.blit(weapon, (weapon_x_pos, weapon_y_pos)) for idx, val in enumerate(balls): ball_pos_x = val["pos_x"] ball_pos_y = val["pos_y"] ball_img_idx = val["img_idx"] screen.blit(ball_images[ball_img_idx], (ball_pos_x, ball_pos_y)) screen.blit(stage, (0, screen_height - stage_height)) screen.blit(character, (character_x_pos, character_y_pos)) #경과 시간 계산 elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 timer = game_font.render("Time : {}".format(int(total_time - elapsed_time)), True, (255, 255, 255)) screen.blit(timer, (10, 10)) if total_time - elapsed_time <= 0: game_result = "Time Over" running = False pygame.display.update() msg = game_font.render(game_result, True, (255, 0, 0)) msg_rect = msg.get_rect(center=(int(screen_width / 2), int(screen_height / 2))) screen.blit(msg, msg_rect) pygame.display.update() pygame.time.delay(2000) #파이게임 종료 pygame.quit()