무료
다른 수강생들이 자주 물어보는 질문이 궁금하신가요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공의 충돌처리, 지역 변수
공의 충돌 처리를 위해서, 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"] 이부분이 한번 더 들어가잖아요?이걸 덜 쓸수 잇는 방법이 있을까요??전역 변수로 바꿔서 사용하면 되려나...아닌데, 흐음..
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
키를 눌렀다가 떼는 이벤트에서,
if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: character_to_x = 0 두번째 줄을 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or pygame.K_RIGHT: character_to_x = 0 이렇게 바꿔도 작동하는거 같은데, 이렇게 하면 안되는 이유가 있을까요???
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공이 가만히 있습니다
잘 따라 한 것 같은데... 공이 가만히 있습니다. 전체코드(뒤죽박죽 올렸을 수도 있습니다ㅎㅎ ctrl + 마우스 스크롤 올려서 보세요.):
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공 만들기에서(공 불러오기) 오류가 뜹니다
(사진)
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
좌우 방향성이 있는 그림 뒤집기
좌우 방향성이 있는 그림을 좌 키 눌렀을떄와 우키 눌렀을떄 방향을 그에 맞춰 뒤집는 방법에 대해 궁금합니다. 제가 해본 코드는 다음과 같은데, ### 캐릭터 이미지 설정 부분에서 ch0 와 ch1 을 설정해서, 하나는 기본값으로 다른 하난 뒤집은 상태로 초기 값을 정의하고, ch = pygame.image.load("이미지 주소") ch0 = ch ch1 = pygame.transform.flip(ch, True, False) ### 이하 방향키 이벤트에서, if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT: to_x -= move ch = ch0 elif event.key == pygame.K_RIGHT: to_x += move ch = ch1 로 이미지를 교체 하면 어떨까 하는데, 이렇게 하면 제 가 보기에는 잘 작동하는 것으로 보입니다. 그러나, flip의 기준점을 모르기 떄문에, 픽셀상의 오차가 발생하지는 않을지, 하는 문제가 궁금하고, 위와 같은 방식이 괜찮은지 혹은 안괜찮다면, 다른 대안이 있는지 궁금합니다.
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
FPS 값에 따라 속도가 변하지 않도록 하기 위해서, dt 를 적용해 봤는데,
en_y += drop ch_x += to_x * dt 이렇게 하면 작동은 하는데, 똥이 속도가 변하기 떄문에, 똥도 똑같이 dt 를 곱했는데, 작동을 하지 않더라구요. 어떤 문제가 있는것인지 머리에서는 이해가 되지 않네요. 이해대한 이유와, 해결책을 알 수 있을 까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
preference > setting > linting
linting : bandit Enable 을 체크 해제 했는데, 이건 그냥 미관상의 역할 인가요?다른 효과는 없는건가요? 그럼 굳이 체크 해제 하지 않아도 될까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
pygame.quit() 작성하지 않아도 되지 않나요?
# 이벤트 루프 running = True # 게임이 진행중? while running: for event in pygame.event.get(): # 이벤트 체크 if event.type == pygame.QUIT: # 종료버튼 QUIT 은 대문자 running = False # pygame 종료 pygame.quit()에서 " pygame.quit() "이 부분을 작성하지 않아도, 이벤트가 없으면 자동으로 꺼지는게 기본 값으로 보이는데, pygame.quit() 이부분을 작성하지 않아도, 종료 되지 않나요?? 작성해야만 하는 이유가 있을까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
캐릭터 움직임의 오류
안녕하세요 선생님 강의 잘 듣고 있습니다. 항상 감사드립니다. 제가 강의를 따라하다가 문제가 생겼는데 세 번이나 반복해봤지만 같은 상황이라 고민 중에 질문을 드립니다. 선생님께서 알려주신 대로 event type == pygame.KEYDOWN 부분 중 to_x, to_y 값에 +- 5를 했을 때 저는 캐릭터 상자가 너무 빨라서 창 안에서 보이질 않더라구요. 그래서 혹시나 값에 1을 주었는데 그제서야 선생님과 비슷하게 움직이는데(완전 같지 않음) 이 문제는 어떠한 것과 관계가 있는 건지 모르겠습니다. 제가 무엇을 잘못했을까요? 아래는 제가 실행한 코드입니다. import pygame pygame.init() #초기화 반드시 필요 #화면 크기 설정 screen_width = 480 screen_height = 640 screen = pygame.display.set_mode((screen_width,screen_height)) #화면 타이틀 설정 pygame.display.set_caption("Nado Game") #배경이미지 불러오기 background = pygame.image.load("E:/Study/Python/PythonWorkSpace/pygame_basic/background.png") character = pygame.image.load("E:/Study/Python/PythonWorkSpace/pygame_basic/character.png") character_size = character.get_rect().size #이미지 크기 구해옴 character_width = character_size[0] character_heigth = character_size[1] character_x_pos = (screen_width / 2) - (character_width / 2) character_y_pos = screen_height - character_heigth #화면 세로 크기 가장 아래에 위치 to_x = 0 to_y = 0 #이벤트루프 running = True #게임이 진행 중인가? while running : 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 -= 5 elif event.key == pygame.K_RIGHT : to_x += 5 elif event.key == pygame.K_UP : to_y -= 5 elif event.key == pygame.K_DOWN : to_y += 5 if event.type == pygame.KEYUP : if event.key == pygame.K_LEFT or pygame.K_RIGHT : to_x = 0 elif event.key == pygame.K_UP or pygame.K_DOWN : to_y = 0 character_x_pos += to_x character_y_pos += to_y #가로 경계값 처리 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 = 0 elif character_y_pos > screen_height - character_heigth : character_x_pos = screen_height - character_heigth screen.blit(background, (0, 0)) #배경그리기 screen.blit(character, (character_x_pos,character_y_pos)) pygame.display.update() #게임 화면 다시 그리기(반드시) #pygame 종료 pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
설치부터 다음과 같은 오류가 납니다
Could not fetch URL https://pypi.org/simple/pygame/: There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): Max retries exceeded with url: /simple/pygame/ (Caused by SSLError(SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: self signed certificate in certificate chain (_ssl.c:1123)'))) - skipping ERROR: Could not find a version that satisfies the requirement pygame (from versions: none)
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
공이 안없어집니다..
공(고양이)가 안없어집니다.. 이미지를 바꾸면서 ball을 cat으로, to_remove를 _rm으로 바꾼 것 양해부탁드립니다. # 1. 모든 공을 없애면 게임 종료, 성공 # 2. 강아지가 고양이에 닿으면 게임 종료, 실패 # 3. 시간 제한 99초 초과 시 게임 종료, 실패 import pygame, os 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. 사용자 게임 초기화 # 이미지 불러오기 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, "puppy.png")) # 70*70 캐릭터 불러오기 character_size = character.get_rect().size # 캐릭터 이미지의 가로 세로 크기를 가져옴 character_width = character_size[0] # 캐릭터의 가로 크기 character_height = character_size[1] # 캐릭터의 세로 크기 character_pos_x = (screen_width - character_width) / 2 # x position = 화면 가로의 절반에 위치 하도록 (캐릭터의 x 좌표) character_pos_y = screen_height - stage_height - character_height + 10 # 이동할 좌표 chracter_to_x = 0 # 이동 속도 character_speed = 0.4 # 무기 만들기 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 # target cat_images = [ pygame.image.load(os.path.join(image_path, "cat0.png")), pygame.image.load(os.path.join(image_path, "cat1.png")), pygame.image.load(os.path.join(image_path, "cat2.png")), pygame.image.load(os.path.join(image_path, "cat3.png")) ] # 타겟 크기에 따른 최초 스피드 cat_speed_y = [-18, -15, -12, -9] # index 0 1 2 3 - cat 1 2 3 4 # 타겟들 cats = [] # 최초 발생하는 큰 고양이 추가 cats.append({ "pos_x" : 50, # 고양이의 x 좌표 "pos_y" : 50, # 고양이의 y 좌표 "img_idx" : 0, # 고양이의 이미지 인덱스 "to_x" : 3, # 고양이의 x축 이동 방향, -3이면 왼쪽으로 3이면 오른쪽ㅇfh "to_y" : -6, # y축 이동 방향 "init_spd_y" : cat_speed_y[0] # y축 최초 속도 }) # 사라질 츄르, 고양이 정보 저장 변수 weapon_rm = -1 cat_rm = -1 # 폰트 정의 game_font = pygame.font.Font(None, 40) # 폰트 객체 생성 (폰트, 크기) # 게임 총 시간 total_time= 100 # 시작 시간 계산 start_ticks = pygame.time.get_ticks() # 현재 tick 정보를 받아옴 # Game Over, TIME OVER, Mission Complete game_result = "GAME OVER" # event loop running = True # 게임이 진행 중인가? while running: dt = clock.tick(30) # delta = clock. FPS 설정 for event in pygame.event.get(): # 키보드에 맞는 이벤트 실행되면 if event.type == pygame.QUIT: # 창 끄기 이벤트 발생 시 running = False if event.type == pygame.KEYDOWN: # 키가 눌러졌는데 확인 if event.key == pygame.K_RIGHT: chracter_to_x += character_speed elif event.key == pygame.K_LEFT: chracter_to_x -= character_speed elif event.key == pygame.K_SPACE: # 스페이스바 누르면 무기 발사 weapon_pos_x = character_pos_x + (character_width / 2) - (weapon_width / 2) weapon_pos_y = character_pos_y weapons.append([weapon_pos_x, weapon_pos_y]) elif event.key == pygame.K_UP: pass elif event.key == pygame.K_DOWN: pass if event.type == pygame.KEYUP: # 방향키를 뗐을 때 if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT: chracter_to_x = 0 elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: pass # 캐릭터 움직이기 character_pos_x += chracter_to_x * dt # FPS에 따라 속도가 변하지 않게 delta 값을 곱해주어 고정해줌 # 캐릭터 가로 경계값 처리 if character_pos_x < 0: character_pos_x = 0 elif character_pos_x > screen_width - character_width: character_pos_x = screen_width - character_width # 무기 위치 조정 weapons = [[w[0], w[1] - weapon_speed] for w in weapons] # 무기가 천장에 닿으면 없애기 # weapons = [[w[0], w[1]] for w in wea pons if w[1] > 0] # 타겟 위치 정의 for cat_idx, cat_val in enumerate(cats): cat_pos_x = cat_val["pos_x"] cat_pos_y = cat_val["pos_y"] cat_img_idx = cat_val["img_idx"] cat_size = cat_images[cat_img_idx].get_rect().size cat_width = cat_size[0] cat_height = cat_size[1] # 가로 경계값: 타겟의 경계값 처리 -> 경계값이 닿으면 반대 쪽으로 튕김 if cat_pos_x < 0 or cat_pos_x > (screen_width - cat_width): cat_val["to_x"] *= -1 # 세로 경계값: 스테이지에 튕겨서 올라감 if cat_pos_y >= (screen_height - stage_height - cat_height): cat_val["to_y"] = cat_val["init_spd_y"] else: # 그 외 모든 경우에는 to_y를 증가 cat_val["to_y"] += 0.5 cat_val["pos_x"] += cat_val["to_x"] cat_val["pos_y"] += cat_val["to_y"] # 충돌 처리를 위한 rect 정보 update character_rect = character.get_rect() character_rect.left = character_pos_x character_rect.top = character_pos_y for cat_idx, cat_val in enumerate(cats): cat_pos_x = cat_val["pos_x"] cat_pos_y = cat_val["pos_y"] cat_img_idx = cat_val["img_idx"] # cat rect 정보 업뎃 cat_rect = cat_images[cat_img_idx].get_rect() cat_rect.left = cat_pos_x cat_rect.top = cat_pos_y # cat과 puppy 충돌 처리 if character_rect.colliderect(cat_rect): running = False break # cat과 츄르 충돌 처리 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(cat_rect): weapon_rm = weapon_idx # 해당 츄르 없애기 위한 값 설정 cat_rm = cat_idx # 해당 고양이 없애기 위한 값 설정 if cat_img_idx < 3: # 0 1 2 -> 가장 작은 공이 아니라면 # 현재 고양이 크기 정보 cat_width = cat_rect.size[0] cat_height = cat_rect.size[1] #나눠질 고양이 정보 small_cat_rect = cat_images[cat_img_idx + 1].get_rect() small_cat_width = small_cat_rect.size[0] small_cat_heigth = small_cat_rect.size[1] # 왼쪽으로 튕겨나가는 작은 고양이 cats.append({ "pos_x" : cat_pos_x + (cat_width / 2) - (small_cat_width / 2), "pos_y" : cat_pos_y + (cat_height / 2) - (small_cat_heigth / 2), # 고양이의 y 좌표 "img_idx" : cat_img_idx + 1, "to_x" : -3, # 고양이의 x축 이동 방향, -3이면 왼쪽으로 3이면 오른쪽ㅇfh "to_y" : -6, # y축 이동 방향 "init_spd_y" : cat_speed_y[cat_img_idx + 1] # y축 최초 속도 }) # 오른쪽으로 튕겨나가는 작은 고양이 cats.append({ "pos_x" : cat_pos_x + (cat_width / 2) - (small_cat_width / 2), "pos_y" : cat_pos_y + (cat_height / 2) - (small_cat_heigth / 2), # 고양이의 y 좌표 "img_idx" : cat_img_idx + 1, "to_x" : +3, # 고양이의 x축 이동 방향, -3이면 왼쪽으로 3이면 오른쪽ㅇfh "to_y" : -6, # y축 이동 방향 "init_spd_y" : cat_speed_y[cat_img_idx + 1] # y축 최초 속도 }) break else: continue # 충돌된 cat or 무기 없애기 if cat_rm > -1: del cats[cat_rm] cat_rm = -1 if weapon_rm > -1: del weapons[weapon_rm] weapon_rm = -1 # 모든 cat이 없어졌을 때 if(len(cats)==0): game_result = "MISSION COMPLETE" running = False # screen.fill((r, g, b)) # rgb 값으로 배경색 채울 수도 있음 screen.blit(background, (0, 0)) # 배경 이미지를 어디서부터 나타내줄건지. 0, 0 -> 왼쪽 맨 위부터 for weapon_pos_x, weapon_pos_y in weapons: screen.blit(weapon, (weapon_pos_x, weapon_pos_y)) for idx, val in enumerate(cats): cat_pos_x = val["pos_x"] cat_pos_y = val["pos_y"] cat_img_idx = val["img_idx"] screen.blit(cat_images[cat_img_idx], (cat_pos_x, cat_pos_y)) screen.blit(stage, (0, screen_height - stage_height)) screen.blit(character, (character_pos_x, character_pos_y)) # 캐릭터 그리기 # 타이머, 경과 시간 계산 elapsed_time = (pygame.time.get_ticks() - start_ticks) / 1000 # 초단위로 표시 timer = game_font.render("Time: {}".format(int(total_time - elapsed_time)), True, (255, 0, 0)) screen.blit(timer, (10, 10)) # 시간이 0 이하면 game over if(total_time - elapsed_time <= 0): game_result = "TIME OVER" running = False pygame.display.update() # 게임 화면 다시 그리기 # 잠시 대기 pygame.time.delay(1000) # 2초 대기 # 게임 오버 메세지 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 종료 pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
무기가 안 움직여요
weapons = [[ w[0], w[1] - weapon_speed] for w in weapons] 코드는 이거거든요? 왜 안될까요?
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
실행해서 무기와 공이 맞닿으면 로딩상태로 멈추네요
import pygame import os ############################################ # 0. 기본 초기화 (반드시 해야 하는 것들) 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. 사용자 게임 초기화 (배경 화면, 게임 이미지, 좌표, 속도, 폰트 등) # 현재 파일의 위치를 반환 e:\PythonWorkspace\pygame_basic\pygame_project current_path = os.path.dirname(__file__) # images 폴더 위치 반환 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_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 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. 충돌 처리 # 캐릭터 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"] # ball 정보 업데이트 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({ # 공의 x 좌표 "pos_x": ball_pos_x + (ball_width/2) - (small_ball_width/2), # 공의 y좌표 "pos_y": ball_pos_y + (ball_height/2) - (small_ball_height/2), "img_idx": ball_img_idx + 1, # 공의 이미지 인덱스 "to_x": -3, # x축 이동 방향, -3 이면 왼쪽으로, +3 이면 오른쪽으로 "to_y": -6, # y축 이동방향 # y 최초 속도 "init_spd_y": ball_speed_y[ball_img_idx + 1] }) # 오른쪽으로 튕겨나가는 작은공 balls.append({ # 공의 x 좌표 "pos_x": ball_pos_x + (ball_width/2) - (small_ball_width/2), # 공의 y좌표 "pos_y": ball_pos_y + (ball_height/2) - (small_ball_height/2), "img_idx": ball_img_idx + 1, # 공의 이미지 인덱스 "to_x": 3, # x축 이동 방향, -3 이면 왼쪽으로, +3 이면 오른쪽으로 "to_y": -6, # y축 이동방향 # y 최초 속도 "init_spd_y": ball_speed_y[ball_img_idx + 1] }) 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 # 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() 무기를 발사하면 공과 무기가 맞닿는 순간 무한루프처럼 로딩이 되는데 왜 그런지 모르겠습니다 의심가는 곳을 주석처리하고 실행해 봤을 때 append 코드를 만나면 로딩이 길어지는 것 같은데 정확한 원인이 뭔지 모르겠어요 도와주세요 ㅠㅠ
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
키이벤트 작성할 때
if event.type==pygame.KEYDOWN: #키가 눌렸는지 확인 if event.key == pygame.K_LEFT: #캐릭터 왼쪽으로 to_x -=5 #to_x= to_x-5 elif event.key == pygame.K_RIGHT: #캐릭터 오른쪽으로 to_x +=5 elif event.key == pygame.K_UP: #캐릭터 위로 to_y -=5 # 2D 개념 / 길이-이동범위/ 위에서부터 길이 elif event.key ==pygame.K_DOWN: #캐릭터 아래로 to_y +=5 if event.type ==pygame.KEYUP: # 방향키를 떼면 멈춤 if event.key == pygame.K_LEFT or event.key ==pygame.K_RIGHT: to_x=0 elif event.key==pygame.K_UP or event.key==pygame.K_DOWN: to_y=0 왜 키 눌릴 때/ 키에서 땔 때를 이분법적으로 나누어 if와 elif로 설정하지 않고, 각각 따로 if문을 만드는 건가요?^^
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
TypeError: invalid destination position for blit
위와 같은 에러가 납니다.. ball을 cat으로 쓴 점 감안해주시면 감사하겠습니다. error: File "c:\Users\user\Desktop\pygame_basic\1_create_frame.py", line 159, in <module> screen.blit(cat_images[cat_img_idx], (cat_pos_x, cat_pos_y)) TypeError: invalid destination position for blit --source import pygame, os 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. 사용자 게임 초기화 # 이미지 불러오기 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, "puppy.png")) # 70*70 캐릭터 불러오기 character_size = character.get_rect().size # 캐릭터 이미지의 가로 세로 크기를 가져옴 character_width = character_size[0] # 캐릭터의 가로 크기 character_height = character_size[1] # 캐릭터의 세로 크기 character_x_pos = (screen_width - character_width) / 2 # x position = 화면 가로의 절반에 위치 하도록 (캐릭터의 x 좌표) character_y_pos = screen_height - stage_height - character_height + 10 # 이동할 좌표 chracter_to_x = 0 # 이동 속도 character_speed = 0.4 # 무기 만들기 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 # target cat_images = [ pygame.image.load(os.path.join(image_path, "cat0.png")), pygame.image.load(os.path.join(image_path, "cat1.png")), pygame.image.load(os.path.join(image_path, "cat2.png")), pygame.image.load(os.path.join(image_path, "cat3.png")) ] # 타겟 크기에 따른 최초 스피드 cat_speed_y = [-18, -15, -12, -9] # index 0 1 2 3 - cat 1 2 3 4 # 타겟들 cats = [] # 최초 발생하는 큰 고양이 추가 cats.append({ "pos_x" : 50, # 고양이의 x 좌표 "pos_y" : 50, # 고양이의 y 좌표 "img_idx" : 0, # 고양이의 이미지 인덱스 "to_x" : 3, # 고양이의 x축 이동 방향, -3이면 왼쪽으로 3이면 오른쪽ㅇfh "to_y" : -6, # y축 이동 방향 "init_spd_y" : cat_speed_y[0] # y축 최초 속도 }) # 폰트 정의 game_font = pygame.font.Font(None, 40) # 폰트 객체 생성 (폰트, 크기) # 게임 총 시간 total_time= 10 # 시작 시간 계산 start_ticks = pygame.time.get_ticks() # 현재 tick 정보를 받아옴 # event loop running = True # 게임이 진행 중인가? while running: dt = clock.tick(30) # delta = clock. FPS 설정 for event in pygame.event.get(): # 키보드에 맞는 이벤트 실행되면 if event.type == pygame.QUIT: # 창 끄기 이벤트 발생 시 running = False if event.type == pygame.KEYDOWN: # 키가 눌러졌는데 확인 if event.key == pygame.K_RIGHT: chracter_to_x += character_speed elif event.key == pygame.K_LEFT: chracter_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]) elif event.key == pygame.K_UP: pass elif event.key == pygame.K_DOWN: pass if event.type == pygame.KEYUP: # 방향키를 뗐을 때 if event.key == pygame.K_RIGHT or event.key == pygame.K_LEFT: chracter_to_x = 0 elif event.key == pygame.K_UP or event.key == pygame.K_DOWN: pass # 캐릭터 움직이기 character_x_pos += chracter_to_x * dt # FPS에 따라 속도가 변하지 않게 delta 값을 곱해주어 고정해줌 # 캐릭터 가로 경계값 처리 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 wea pons if w[1] > 0] # 타겟 위치 정의 for cat_idx, cat_val in enumerate(cats): cat_pos_x = cat_val["pos_x"] cat_pos_y = cat_val["pos_y"] cat_img_idx = cat_val["img_idx"] cat_size = cat_images[cat_img_idx].get_rect().size cat_width = cat_size[0] cat_height = cat_size[1] # 가로 경계값: 타겟의 경계값 처리 -> 경계값이 닿으면 반대 쪽으로 튕김 if cat_pos_x < 0 or cat_pos_x > (screen_width - cat_width): cat_val["to_x"] *= -1 # 세로 경계값: 스테이지에 튕겨서 올라감 if cat_pos_y >= (screen_height - stage_height - cat_height): cat_val["to_y"] = cat_val["init_spd_y"] else: # 그 외 모든 경우에는 to_y를 증가 cat_val["to_y"] += 0.5 cat_val["pos_x"] += cat_val["pos_x"] cat_val["pos_y"] += cat_val["pos_y"] # 충돌 처리를 위한 rect 정보 update character_rect = character.get_rect() character_rect.left = character_x_pos character_rect.top = character_y_pos # screen.fill((r, g, b)) # rgb 값으로 배경색 채울 수도 있음 screen.blit(background, (0, 0)) # 배경 이미지를 어디서부터 나타내줄건지. 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(cats): cat_pos_x = val["pos_x"] cat_pos_y = val["pos_y"] cat_img_idx = val["img_idx"] screen.blit(cat_images[cat_img_idx], (cat_pos_x, cat_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(str(int(total_time - elapsed_time)), True, (255, 0, 0)) screen.blit(timer, (10, 10)) # 시간이 0 이하면 game over if(total_time - elapsed_time <= 0): print("Game Over") running = False pygame.display.update() # 게임 화면 다시 그리기 # 잠시 대기 pygame.time.delay(2000) # 2초 대기 # pygame 종료 pygame.quit()
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
랜덤함수
선생님 저는 다른건 같은데 똥 x pos에서 랜덤함수를 randint로 사용안하고 enemy_x_pos = random.randrange(0, screen_width - enemy_width) randrange로 사용했는데 이렇게 사용해도 되는건가요? 두개의 차이점이 뭔지 잘 모르겠어요~
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
세로 경계값 쓰고 나니까 창이 없어져요
(사진)
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
세상에나.. 게임을 만들어보는 날이 오네요
강의 끝까지 열심히 하겠습니다
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
배경 색
배경 색이 이렇게ㅡ나와요
- 미해결파이썬 무료 강의 (활용편1) - 추억의 오락실 게임 만들기 (3시간)
폰트 색상 지정
폰트 색상 검은색으로 하고 싶은데 어떻게 할 수 있나요?