[파이썬 게임]약초 캐는 엘프

약초 캐는 엘프라는 이름의 파이썬 게임이며, 아래 캐릭터 이미지를 다운받아서 파이썬 파일과 같은 위치에 두어야 동작이 됩니다. 이 게임은 터틀그래픽에서 동작하는 프로그램입니다.

파이썬 코드

import turtle as t
import random
import time

BGCOLOR = "#FFAB76"


def move_up():
    player.setheading(90)


def move_down():
    player.setheading(270)


def move_left():
    player.setheading(180)


def move_right():
    player.setheading(0)


# 그래픽 창 설정
t.setup(500, 500)
t.title("약초 캐는 엘프")
t.bgcolor(BGCOLOR)
t.tracer(0)
t.ht()
t.color("green")
t.penup()
t.goto(0, 200)  # 게임 종료 메시지 위치

# 캐릭터 이미지 등록
player_img = "player.gif"
t.addshape(player_img)

# 플레이어 생성
player = t.Turtle()
player.shape(player_img)
player.penup()
player.goto(200, -200)
player.setheading(180)

# 아이템 생성
item_list = []
for i in range(20):
    item = t.Turtle()
    item.shape("triangle")
    item.color("green")
    item.setheading(90)
    item.penup()
    item.goto(random.randint(-220, 220), random.randint(-220, 220))
    item_list.append(item)

# 장애물 생성
obstacles = []

for i in range(2):
    ob = t.Turtle()
    ob.shape("square")
    ob.shapesize(20, 1)
    ob.penup()
    ob.setheading(90)
    obstacles.append(ob)

obstacles[0].goto(-100, 50)
ob0_speed = -2
obstacles[1].goto(100, -50)
ob1_speed = 2

# 플레이어 방향 전환
t.onkeypress(move_up, "Up")
t.onkeypress(move_down, "Down")
t.onkeypress(move_right, "Right")
t.onkeypress(move_left, "Left")
t.listen()

game_on = True
start_time = time.time()

while game_on:
    player.forward(7)

    obstacles[0].forward(ob0_speed)
    obstacles[1].forward(ob1_speed)

    # 장애물 방향 전환
    if obstacles[0].ycor() < -200 or obstacles[0].ycor() > 200:
        ob0_speed *= -1
    if obstacles[1].ycor() < -200 or obstacles[1].ycor() > 200:
        ob1_speed *= -1

    # 플레이어가 장애물에 닿았는지 감지
    for ob in obstacles:
        if ob.distance(player) < 210 and \
                ob.ycor() - 30 < player.ycor() < ob.ycor() + 30:
            game_on = False
            t.write("미션 실패!!", False, "center", ("나눔바른펜", 30))

    # 플레이어가 아이템에 닿았는지 감지
    for item in item_list:
        if item.distance(player) < 20:
            item.ht()
            item_list.remove(item)
            if len(item_list) == 0:
                game_on = False
                t.write("미션 성공!!", False, "center", ("나눔바른펜", 30))

    # 플레이어가 벽에 닿으면 미션 실패
    if player.xcor() < -230 or player.xcor() > 230 or \
            player.ycor() < -230 or player.ycor() > 230:
        game_on = False
        t.write("미션 실패!!", False, "center", ("나눔바른펜", 30))

    cur_time = time.time()
    if cur_time - start_time > 20:
        game_on = False
        t.write("시간 초과!!", False, "center", ("나눔바른펜", 30))

    t.update()
    time.sleep(0.03)

t.done()

Loading

댓글 남기기