무료
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
키이벤트 궁금한점
안녕하세요 나도코딩님 우선 강의 잘 듣고있습니다 이 강의에서 한가지 궁금한 점이 있는데 for문 밖에서 캐릭터 좌표를 더하는 것과 for문 안에서 캐릭터 좌표를 더하는 것의 차이점입니다. for문 안에서 캐릭터 좌표를 더할 경우 키를 누르고 있을 때 움직임이 반복되지 않고 딱 한번만 적용이 되는데 강의 내용처럼 for문 밖에서 캐릭터 좌표를 더할 경우 키를 누르고 있을 때 움직임이 반복되어 어떻게 계속 움직일 수 있는지 궁금합니다. 봐주셔서 감사합니다.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
인텔리센스 설정 궁금합니다.
감사합니다. 강의 잘 보고 있습니다. 혹시 샘플코드: pygame.font.Font() pygame. 입력후 time 또는 display 가 나와야하는데, 저는 안나옵니다. (물론 실행은 잘 됩니다.) 뭐가 문제일까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
사진 편집
음... 사진을 png 파일에서 저렇게 편집하는 방법이 있을까요? 포토샵이나 그런 곳에도 해좠는데 안됩니다ㅠㅠ 어떠카져
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
이건 질문은 아니고..
이건 질문은 아니고 옵션 을추가하고 싶은데 코맨드를 몰라서 멈춰있는 사람들 한테 공유 하고 싶어서 남기는데여 아래에 링크 들어가시면 파이게임 명령어들이 설명이랑 쫙 나와서 올립니다 파이게임 명령어 목록
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공이 한번에 하나씩만 사라져요
공이 가장 처음 쪼개질 때에는 문제 없는데, 이 후에 공격하면 한 번에 한 공만 쪼개집니다... 예를 들어 Ball을 B라고 가정하면, B1->B2,B'2 로 쪼개지고, 각 공에 공격을 가하면 쪼개져야 하는데, B1만 쪼개지고 B'2는 아무리 공격해도 안 없어지더라고요...이후에 B2가 다시 쪼개져도 B3에서 같은 현상이 벌어집니다ㅠㅠ 하단 이미지에선 반드시 해야 하는 설정은 넣지 않았습니다! 실제 코드에선 있어요 #1. 사용자 게임 초기화 (배경 이미지, 캐릭터, 좌표, 폰트, 속도 등) current_path = os.path.dirname(__file__) image_path = os.path.join(current_path, 'images') 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_pos = (screen_width / 2) - (character_width / 2) character_y_pos = screen_height - stage_height - character_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, '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 = [-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[0] }) weapon_to_remove = -1 ball_to_remove = -1 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(60) #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 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'] #4. 충돌 처리 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"] 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] 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[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[ball_img_idx + 1]}) break 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: screen.blit(weapon, (weapon_x_pos, weapon_y_pos)) screen.blit(stage, (0, screen_height - stage_height)) screen.blit(character, (character_x_pos, character_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)) 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,255,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()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
한줄 if가 있는 for문을 풀어주실 수 있나요?
weapons = [[w[0], w[1]] for w in weapons if w[1] > 0] 한줄 코드만으로는 잘 이해가 가지 않습니다. 이 코드를 풀어서 보면 어떤 코드인지 이해에 도움이 될 것 같습니다.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
똑같이 했는데 왜안되죠?
다 작성하고 실행 해봤더니 공이 끝가지 올라가길래 질문 남깁니다. 왜이러는 거죠?1시간 동안 동영상이랑 계속 돌려서 찾아도 안보이네요 왜이러죠?? 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("공 쪼개기 게임") # FPS clock = pygame.time.Clock() ######################################################### # 1. 사용자 게임 초기화 (배경 화면, 게임 이미지, 좌표, 속도, 폰트 등) # 배경 만들기 background = pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\background.png") # 스테이지 만들기 stage = pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\stage.png") stage_size = stage.get_rect().size stage_height = stage_size[1] # 스테이지의 높이 위에 캐릭터를 두기 위해 사용 # 캐릭터 만들기 character = pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\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 = 0 character_speed = 5 # 무기 만들기 weapon = pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\weapon.png") weapon_size = weapon.get_rect().size weapon_width = weapon_size[0] weapon_speed = 10 # 무기는 한 번에 여러 발 발사 가능 weapons = [] # 공 만들기 (4개 크기에 대해 따로 처리) ball_images = [ pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\balloon1.png"), pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\balloon2.png"), pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\balloon4.png"), pygame.image.load("C:\\Users\\c\\Desktop\\서지율\\pythonworkspace\\파이썬.활용편\\pygame_project\\images\\balloon4.png")] # 공 속도 ball_speed_y = [-18, -15, -12, -9] # 공들 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 최초 속도 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 # 무기 위치 조정 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"] # 4. 충돌 처리 # 5. 화면에 그리기 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)) pygame.display.update() pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
빨간 글자 안되나요
elif total_time - elapsed_time <= 3: timer = 3초가 지나면 빨간색으로 되는걸 할려고 하는데 어떻게 해야 하나요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
Pygame 설치 방법
제가 pygame을 설치하려고 하는데 powershell이 저한데는 없어요 ㅠㅠㅠ
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
배경
선생님~~ 제가 지금 3.9버전을 쓰는데 background = pygame.image.load("C:/Users/leeha/Desktop/ python/pygame_basic/background.png") 라고 적었는데 안되요ㅠㅠ 어떻게 해야 하나요
- 미해결파이썬 무료 강의 (활용편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") #image 폴더 위치 반환 #배경 만들기 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_pos = (screen_width / 2) - (character_width / 2) character_y_pos = screen_height - character_height - stage_height #캐릭터 이동 방향 character_to_x = 0 #캐릭터 이동 속도 character_speed = 5 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: pass 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 # 4. 충돌 처리 # 5. 화면에 그리기 screen.blit(background, (0, 0)) screen.blit(stage, (0, screen_height - stage_height)) screen.blit(character, (character_x_pos, character_y_pos)) pygame.display.update() #pygame 종료 pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
왜 그런지 모르겠지만 다른 버그가 있습니다.
공들을 오른쪽으로 나오는 공들을 다 터트리고 왼쪽으로 나눠진 공들을 터트리면 공이 나눠지는 것이 아닌 바로 없어집니다. 예를들어 큰공을 터트렸을때 그 다음 공들이 아래와 같이 나눠진다고 할때 balloon1 -> balloon2_1(왼쪽공) / balloon2_2(오른쪽공) balloon2_2 -> balloon3_1 / Balloon3_2 balloon3-2 -> balloon4_1 / Balloon4_2 (Balloon2_1, Balloon3_1, Balloon4_1은 남아있음) Balloon1 -> Balloon2_2 -> Balloon3_2 -> Balloon4_2 를 터트리고 Balloon2_1을 터트리면 공이 안나눠지고 바로 없어집니다.
- 파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
NameError : name 'clock' is not defined
삭제된 글입니다
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
맥북 사용자입니다 . ㅜㅡㅜ;
맥북 사용자입니다. 댓글에서 Pygame 설치 링크를 보고 따라 했는데 , 링크를 따라 들어가면 자세한 설명이 없어서 어떻게 해야 하는지 모르겠어요, 묘듈을 설치하고 명령어는 terminal에 작성해야 하는 건지 아니면, 더 자세한 설명이 있는 링크 좀 알려주실 수 있나요 ? ㅠㅡㅠ
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
초보잊니다
.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
from pygame import * import pygame 차이점
만약에 from pygame import * 을 했으면 앞에 pygame.을 전부다 빼고 써야하나요? 또 그렇다면 왜 여기서는 쓰지 않는지 궁금합니다.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
게임 화면이 늦게 열려요
한번 봐주시면 감사하겠습니다 # 1. 모든 공을 없애면 게임 종료 (성공) # 2. 캐릭터는 공에 닿으면 게임 종료 (실패) # 3. 시간 제한 99초 초과 시 게임 종료 (실패) 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("Game Name") # 게임 이름 # 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, "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_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 # 공 만들기 (4개 크기에 대해 따로 처리) ball_images = [ pygame.image.load(os.path.join(image_path, "balloon.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축 이동방향, -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() # 시작 시간 정의 # 게임 종료 메시지 # TimeOut(시간 초과, 실패) # 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]] 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), # 공의 x 좌표 "pos_y" : ball_pos_y + (ball_height / 2) - (small_ball_height / 2), # 공의 y 좌표 "img_idx" : ball_img_idx + 1, # 공의 이미지 인덱스 "to_x" : -3, # x축 이동방향, -3이면 왼쪽으로, 3이면 오른쪽으로 "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축 이동방향, -3이면 왼쪽으로, 3이면 오른쪽으로 "to_y" : -6, # y출 이동방향, "init_spd_y" : ball_speed_y[ball_img_idx + 1]}) # y 최초 속도 break else: # 계속 게임을 진행 continue # 안쪽 for 문 조건이 맞지 않으면 continue. 바깥 for 문 계속 수행 break # 안쪽 for 문에서 break를 만나면 여기로 진입 가능. 2중 for 문을 한번에 탈출 #for 바깥조건: # 바깥동작 # for 안쪽조건: # 안쪽동장 # if 충돌하면: # 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 # 5. 화면에 그리기 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 # 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 Over" 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시간)
#충돌된 공 or 무기 없애기 부분인 if ball_to_remove > -1: del balls[ball_to_remove] ball_to_remove = -1 부분이 도저히 이해가 안됩니다.
지금 # 충돌된 공 or 무기 없애기 if ball_to_remove > -1: del balls[ball_to_remove] ball_to_remove = -1 부분이 도저히 이해가 안됩니다. balls.append 해서 최초의 공 (=가장 큰 공) 이 있는건 알겠는데 도대체 어느코드에서 balls의 인덱스 수가 ball_images 만큼 늘어난건가요......제 생각에는 # 최초 발생하는 큰 공 추가 만 되있어서 인덱스는 0이고 값은 딕셔너리의 내용인데요.. (프린트 문으로 이 부분은 확인했습니다!) 아래가 balls 가 포함되있는 코드인데 어디서 ball_images 만큼의 인덱수가 늘어난건가요. # 최초 발생하는 큰 공 추가 balls.append({ "pos_x" : 50, # 공의 x좌표 "pos_y" : 50, # 공의 y좌표 "img_idx" : 0, # 공의 이미지 인덱스,ball_image 리스트 안에서의 이미지의 인덱스 넘버 "to_x": 3, # x축 이동방향 "to_y": -6, # y축 이동방향 "init_spd_y": ball_speed_y[0] # 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"] ball_size = ball_image[ball_img_idx].get_rect().size # 해당 ball의 x,y값이 묶여진 리스트 ball_width = ball_size[0] ball_height = ball_size[1] ... ... # 4. 충돌 처리 ... ... 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() # 공의 크기와 좌표(x,y = left,top) ball_rect.left = ball_pos_x ball_rect.top = ball_pos_y ... ... # 왼쪽으로 튕겨나가는 작은 공 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 len(balls) == 0: game_result = "Mission Complete" running = False
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
파이썬 초보
파이썬 초보 입니다. pc 나 노트북 준비하면 파이썬 프로그램은 어디서 다운로드 받나요??
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공이 쪼개지지 않고 1개가 작아지기만 합니다(에러메세지)
공이 안쪼개지고 아래 실행칸에는 이런 메세지가 뜨는데요 뭐가 문제일까요?? c:/Users/user/Desktop/python work space/pygame_project/5_ball_division.py:160: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python. character_rect.left = character_x_pos c:/Users/user/Desktop/python work space/pygame_project/5_ball_division.py:171: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python. ball_rect.top = ball_pos_y c:/Users/user/Desktop/python work space/pygame_project/5_ball_division.py:246: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python. screen.blit(ball_images[ball_img_idx], (ball_pos_x, ball_pos_y)) # 공 이미지 그려주기 c:/Users/user/Desktop/python work space/pygame_project/5_ball_division.py:250: DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using __int__ is deprecated, and may be removed in a future version of Python. screen.blit(character, (character_x_pos, character_y_pos))