【问题标题】:python turtle returning varibles from coordspython海龟从坐标返回变量
【发布时间】:2017-08-28 13:20:29
【问题描述】:

有没有办法根据海龟的位置调用预设的代码行?

我尝试过使用turtle.pos()xcor/ycor,但我无法让它回忆起代码。

我尝试过: if turtle.pos == (0.00,50.00): combat()

我是 Python 乌龟的新手。

import turtle

GRID_UNIT = 50
GRID_SIZE = 5  # code below assumes this is an odd number

####################################################################
def Combat():
print('You encounter a raverous Spider! do you wish to fight it?')
Fight = str(input())
if Fight == 'Yes':
    #########Battle Code Warrior############
    import random
    import time


    While_Loop = 1
    ###########Battle 1############
    print('============================================')
    while While_Loop == 1:
            if Foe >= 0:
                time.sleep(1)
                print('You did', Player_Dmg,'Dmg')
                Foe = Foe - Player_Dmg # checks health remaining
                print('Your Foe has ',Foe,'Hp left')
                print('=============================')
                time.sleep(0.5)
                Player_Dmg = random.randrange(0,10)
                if Foe <= 0:
                    print('You killed it')
                    break

                else:
                    time.sleep(1)
                    if life >= 0:
                        life = life - Foe_Dmg
                        print('You took ', Foe_Dmg,'Dmg')
                        print('You Have', life, 'Hp left')
                        print('=============================')
                        time.sleep(0.5)
                        Foe_Dmg = random.randrange(0, 10)
                        if life <= 0:
                            print('You are dead')

            else:
                print('You die')
                life = 0
                break

elif Fight == 'No':
    print('You Sprint Frantically away from the spider while it chases  you down!')    
def Map_Starting_Area():

turtle.pu()
turtle.goto(-GRID_SIZE/2 * GRID_UNIT, -GRID_SIZE/2 * GRID_UNIT)
turtle.ht()
turtle.pd()

####### Grid ###########

for _ in range(GRID_SIZE // 2):
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.right(90)
    turtle.forward(GRID_UNIT)
    turtle.right(90)

turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.left(90)

for _ in range(GRID_SIZE // 2):
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_UNIT)
    turtle.left(90)
    turtle.forward(GRID_SIZE * GRID_UNIT)
    turtle.right(90)
    turtle.forward(GRID_UNIT)
    turtle.right(90)

turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_UNIT)
turtle.left(90)
turtle.forward(GRID_SIZE * GRID_UNIT)
turtle.pu()
turtle.left(90)
turtle.fd(75)
turtle.left(90)
turtle.fd(25)
###############################################################
# Square = Town
# Circle = Fight
# Arrow = Quest Marker
# Turtle = Weapon Shops
# Triangle = Potion Shop
# Hollow Circle = Chest
turtle.shape('square')
turtle.stamp()
turtle.fd(50)
turtle.right(90)
turtle.fd(50)
turtle.shape('circle')
turtle.stamp()
turtle.back(50)
turtle.left(90)
turtle.fd(50)
turtle.left(90)
turtle.fd(50)
turtle.shape('circle')
turtle.stamp()
turtle.back(50)
turtle.right(90)
turtle.fd(50)
turtle.right(90)
turtle.fd(50)
turtle.shape('circle')
turtle.stamp()
turtle.fd(100)
turtle.shape('square')
turtle.stamp()
turtle.rt(90)
turtle.fd(140)
turtle.rt(90)
turtle.pd()
turtle.circle(10)
turtle.pu()
turtle.fd(150)
turtle.right(90)
turtle.back(10)



###############################################################    
turtle.st()
###############################################################

turtle.speed('fastest')

Map_Starting_Area()

turtle.color('orange')
turtle.shape('classic')

 print('You Continue with your Journey')
 print('You leave the protection of your farm and head into the open land')
print('You Come to a cross road')

while True:
    direction = input('Would you like to go North, South, East or West: ').lower()

if direction == 'north' and turtle.ycor() < GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.sety(turtle.ycor() + GRID_UNIT)
    turtle.update()
elif direction == 'south' and turtle.ycor() > -GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.sety(turtle.ycor() - GRID_UNIT)
    turtle.update()
elif direction == 'east' and turtle.xcor() < GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.setx(turtle.xcor() + GRID_UNIT)
    turtle.update()
elif direction == 'west' and turtle.xcor() > -GRID_UNIT * (GRID_SIZE//2 - 0.5):
    turtle.setx(turtle.xcor() - GRID_UNIT)
    turtle.update()
elif direction == 'quit':
    break
if turtle.pos == (0.00,50.00):
    combat()

【问题讨论】:

  • 还是不行,有些缩进不正确。
  • 嗯,我对这个网站上的编码格式不是很好,因为它需要 indetation 而在 shell 上它不需要
  • 最直接的问题是,我认为乌龟永远不会接近 (0, 50)。当我运行代码并打印位置时,它的偏移量为 (25, 25),并以 50 步移动。但更重要的是,您不能真正依赖浮点相等。
  • 我知道偏移量是 25,每个偏移量是 50,我在一个单独的外壳中用精确的 smae 代码和参数对其进行了测试,这就是我从海龟定位函数中得到的精确坐标

标签: python turtle-graphics


【解决方案1】:

您的代码中存在许多问题,我希望已修复:

#the imports are now all at the start - this is generally considered the way to go
import turtle
import random
import time

#constant declarations
GRID_UNIT = 50
GRID_SIZE = 5

HALF_GRID = GRID_SIZE // 2

SPIDER_LOCATIONS = [(1, 1),
                    (-1, 0)]

TREASURE_LOCATIONS = [(1, -2),
                      (-2, -1)]

TOWN_LOCATIONS = [(-2, -2),
                  (2, -2),
                  (-2, 2),
                  (2, 2)]

#simplified event functions
def combat():
    print("You stepped on a spider!")

def treasure():
    print("You found treasure!")

def town():
    print("You entered a town")

#scaled setpos for use with int grid coords
def grid_setpos(x, y, scale):
    turtle.setpos((x - 0.5) * scale, (y - 0.5) * scale)

#draw a grid
def draw_grid(size, unit):
    for x in range(-size // 2, size // 2 + 1):
        turtle.pu()
        turtle.setpos(x * unit, -size // 2 * unit)
        turtle.pd()
        turtle.setpos(x * unit, size // 2 * unit)

        turtle.pu()
        turtle.setpos(-size // 2 * unit, x * unit)
        turtle.pd()
        turtle.setpos(size // 2 * unit, x * unit)

#draw the map, iterating over stored global coordinates
def map_starting_area(size, unit):
    draw_grid(size, unit)

    # square = town
    # circle = fight
    # arrow = quest marker
    # turtle = weapon shops
    # triangle = potion shop
    # hollow circle = chest

    turtle.shape("circle")
    turtle.pu()

    for x, y in SPIDER_LOCATIONS:
        grid_setpos(x, y, unit)
        turtle.stamp()

    for x, y in TREASURE_LOCATIONS:
        turtle.pu()
        grid_setpos(x, y - 0.25, unit)
        turtle.pd()
        turtle.circle(unit // 4)

    turtle.shape("square")
    turtle.pu()

    for x, y in TOWN_LOCATIONS:
        grid_setpos(x, y, unit)
        turtle.stamp()

turtle.speed('fastest')

map_starting_area(GRID_SIZE, GRID_UNIT)

turtle.color('orange')
turtle.shape('classic')

print('you continue with your journey')
print('you leave the protection of your farm and head into the open land')
print('you come to a cross road')

turtle.showturtle()

turtle_x, turtle_y = 0, 0

grid_setpos(0, 0, GRID_UNIT)

while True:
    direction = input('would you like to go north, south, east or west: ').lower()

    if direction == 'north':
        if turtle_y < HALF_GRID:
            turtle_y += 1
        else:
            print("You hit a wall")

    elif direction == 'south':
        if turtle_y > -HALF_GRID:
            turtle_y -= 1
        else:
            print("You hit a wall")

    elif direction == 'east':
        if turtle_x < HALF_GRID:
            turtle_x += 1
        else:
            print("You hit a wall")

    elif direction == 'west':
        if turtle_x > -HALF_GRID:
            turtle_x -= 1
        else:
            print("You hit a wall")

    elif direction == 'quit':
        break

    grid_setpos(turtle_x, turtle_y, GRID_UNIT)

    if (turtle_x, turtle_y) in SPIDER_LOCATIONS:
        combat()

    if (turtle_x, turtle_y) in TOWN_LOCATIONS:
        town()

    if (turtle_x, turtle_y) in TREASURE_LOCATIONS:
        treasure()

要解决的要点:如何在海龟击中某个位置时“触发”事件。我已经通过对您的代码进行了一些更改来解决这个问题:

首先,由于您的海龟将始终位于网格上,因此我将与海龟分开跟踪 turtle_xturtle_y,作为整数。这很重要,因为可以正确测试整数是否相等。当海龟位于浮点位置时,实际上可能无法检查它是否位于特定点。网格中的每个单元格是-HALF_GRIDHALF_GRID 范围内的一个坐标,位置由1-1 离散更改。现在您还需要知道每个“事件”在哪里。我通过将多个事件的位置存储在文件开头的全局常量列表中来做到这一点。顺便说一句,我还更改了您的地图绘制方法以在这些列表上使用迭代,并为网格绘制使用 for 循环,因为这更清晰(它使代码更易于阅读,因此为我调试,以及更短)。我希望你会同意map_starting_area 现在更容易理解。由于被跟踪的坐标现在是整数,因此无论何时调用setpos,它们都需要“放大”。为此,我编写了一个辅助函数 grid_setpos,用于在网格中设置位置。

简而言之,它现在存储了一对 整数 用作海龟的位置,因此它可以测试是否有任何等于 then 的值。然后它对海龟进行一些数学运算(将每个坐标放大GRID_UNIT)以将整数坐标映射回网格。

以前,海龟的坐标是浮点。这意味着它们是“十进制”数字(这足够接近以纠正它并不重要)。但是,当您在网格上时,您实际上并不需要十进制数。网格上的坐标是离散的(整数)。因此,坐标现在被存储为整数。这意味着可以测试它们是否完全相等。它还使用蜘蛛坐标列表,并使用一些快速 Python 来查看当前坐标是否在此列表中:if (turtle_x, turtle_y) in SPIDER_LOCATIONS:

我已经简化了您处理事件的方法(combat()town()treasure()),以证明他们正在工作,因为这就是这个问题所必需的。您可以扩展它们中的每一个来扩展您的游戏。

我还更改了您的变量名称。在 Python 中,通常约定使用underscore_case,或者可能camelCase 用于变量和函数,但从不使用CapitalCase(因为这是用于类),据我所知,Capital_Underscore_Case 几乎从未使用过。

小改动:

  • 导入语句现在都在顶部
  • 将网格逻辑与地图逻辑分开
  • 隐藏/显示乌龟时的其他一些错误

如果您想更概括这一点,并且有不同的位置、不同的事件属性等,我建议您开始编写一些类(具有诸如xy 之类的属性,也许还有像这样的实例方法encounter。这超出了这个问题的范围(使用海龟坐标进行相等性测试),但有很多关于 Python 类及其用途的tutorials。我建议你从简单开始并建立起来与这个项目的集成。如果你真的被你的类实现卡住了,你当然可以随时问另一个问题。

针对您的评论:通常不建议为每个城镇创建单独的变量。列表适用于当您有很多需要表现相同的事物时。想象一下,如果你有 50 个城镇,都在不同的变量中。如果您希望每个城镇跟踪一个名称/有不同的事件等,请参阅我关于课程的部分。在更熟悉 OO 编程之后,您将需要一份 Town 实例列表。如果您在尝试使用课程后对课程感到非常困惑,请发布一个关于您的问题的具体问题以及您目前所了解的情况

【讨论】:

  • 感谢您的帮助:)
  • 我主要关心的是坐标是如何工作的以及我将如何更改它们,因为我希望每个地图都有不同的位置用于不同的位置
  • 你能说明一下坐标是如何工作的吗?我明白它是如何工作的,但我不明白它是如何映射的
  • 感谢您的帮助
  • 他们会是编辑城镇的特定方式吗?城镇的位置是 TOWN_LOCATIONS = [(-2, -2), (2, -2), (-2, 2), (2, 2)] 并且对于每个我想要有一张不同的地图我可以试探性地使用课程,但我试图避免他们
【解决方案2】:

turtle.pos 是一个函数

import turtle 

print(turtle.pos)
turtle.pos == (0.00,50.00) # is always False

turtle.pos() == (0.00, 0.00) # might be what you want

【讨论】:

  • 只需将最后的turtle.pos 替换为turtle.pos()。但是还有其他问题需要解决,请参阅上面的详细答案。
猜你喜欢
  • 1970-01-01
  • 2013-03-30
  • 2013-10-09
  • 2015-04-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多