반응형
로직
- 거북이는 총 6마리로 ["red", "orange", "yellow", "green", "blue", "purple"] 각각의 색깔을 갖는다
- screen 의 사이즈는 500 x 400 이고 거북이가 x 축 왼쪽 끝에서 y 축 오른쪽 끝에 닿을 때 경기는 종료된다
- 경주 시작 전 input 으로 한 색깔을 고른다.
- 객체를 이용해 6마리의 거북이를 생성하고 경주 시키기
코드
# 거북이 경주 만들기
# def create_turtle(name, x, y):
# color = colors.pop(0)
# name = Turtle(shape="turtle")
# name.penup()
# name.goto(x, y)
# name.color(color)
# create_turtle("timmy", -230, 90)
# create_turtle("jimmy", -230, 60)
# create_turtle("uimmy", -230, 30)
# create_turtle("oimmy", -230, -30)
# create_turtle("qimmy", -230, -60)
# create_turtle("eimmy", -230, -90)
## 거북이 경주 만들기
screen = Screen()
screen.setup(width=500, height=400)
user_input = screen.textinput(title="Who is the winner", prompt="Color of the turtle: ")
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
y_position = [-70, -40, -10, 20, 50, 80]
is_race_on = False
all_turtles = []
for turtle_index in range(0, 6):
# 동일한 객체를 여러번 생성 할 수 있다.
# new_turtle 이라는 네임은 그냥 object 네임일 뿐 어차피 print 시 메모리 번지를 출력해줌
# 크게 신경 안써도 어차피 다른 오브젝트로 인식함.
new_turtle = Turtle(shape="turtle")
new_turtle.penup()
new_turtle.goto(x=-230, y=y_position[turtle_index])
new_turtle.color(colors[turtle_index])
all_turtles.append(new_turtle)
if user_input :
is_race_on = True
while is_race_on :
for turtle in all_turtles:
rand_move = random.randint(0, 20)
turtle.forward(rand_move)
if turtle.xcor() > 230:
win_color = turtle.pencolor()
if win_color == user_input :
print(f"Winner turtle is {win_color} you bet {user_input}. \nYou Win!")
else:
print(f"Winner turtle is {win_color} you bet {user_input}. \nYou Lose!")
is_race_on = False
screen.exitonclick()
맨위 주석처리된 부분을 보면 알겠지만 처음엔 Class 를 이용해 객체를 선언할 때 무조건 다른 네임으로 선언해야하는 것으로 이해해 함수화 시켜 name 을 따로 받아서 function 을 여러번 호출해 주었다.
강의를 보다 보니 그렇게 하지 않아도 각자 다른 객체로 인식해 for 반복문으로 할당 해주어도 되겠어서 로직을 수정했다.
강의에서 안내해주는 로직을 거의 그대로 코딩했다.
3줄 요약
객체를 굳이 다른 이름으로 선언해 줄 필요는 없다.
반응형
'프로그래밍 > Python' 카테고리의 다른 글
Python 부트 캠프 - turtle 모듈을 이용한 퐁게임 만들기 (0) | 2023.06.07 |
---|---|
Python 부트 캠프 - turtle 모듈을 이용한 소과제 해결하기 (0) | 2023.05.24 |
Python 부트 캠프 - OOP를 이용한 퀴즈 생성기 (0) | 2023.05.23 |
Python 부트 캠프 - OOP를 이용한 커피 머신 생성 (0) | 2023.05.21 |
Python 부트 캠프 - 커피 머신 생성 (2) | 2023.05.19 |