对于一个课堂项目,我正在尝试使用Python(3.7.3)Turtle制作类似于Rogue的游戏。我想知道画布屏幕是否有可能以我的乌龟“播放器”模块为中心,这样它就不会超出用户的视野并且用户不必使用滚动条。
我尝试查找许多不同的解决方案,但似乎都与我的问题无关。我也曾尝试查看Python网站的“乌龟”部分,但我不知道会有什么帮助。
# Draw border
border_pen = turtle.Turtle()
border_pen.speed(0)
border_pen.color('black')
border_pen.penup()
border_pen.setposition(-600,-600)
border_pen.pendown()
border_pen.pensize(3)
for side in range(4):
border_pen.fd(600)
border_pen.lt(90)
border_pen.hideturtle()
以上只是我用来制作画布本身的代码。如您所见,它相当大(需要)。我最初并不认为这是一个问题,但是现在我发现这是一个相当困难的问题。正如我所说,我的模块可以移出屏幕。
答案 0 :(得分:1)
下面是在tkinter级别操纵滚动以获得所需行为的示例。在这种情况下,我将乌龟固定在屏幕中央,但使用箭头键将其移动到其下方。
### Generate a landscape ...
和### Finished generating a ...
之间的代码来自我之前回答的一个SO问题,可以用来探索有趣的分形景观:
from turtle import Turtle, Screen
from random import random
MAGNIFICATION = 10
def move_left():
canvas.xview_scroll(-1, "units")
turtle.setx(turtle.xcor() - MAGNIFICATION)
def move_right():
canvas.xview_scroll(1, "units")
turtle.setx(turtle.xcor() + MAGNIFICATION)
def move_up():
canvas.yview_scroll(-1, "units")
turtle.sety(turtle.ycor() + MAGNIFICATION)
def move_down():
canvas.yview_scroll(1, "units")
turtle.sety(turtle.ycor() - MAGNIFICATION)
screen = Screen()
width, height = screen.screensize()
screen.screensize(width * MAGNIFICATION, height * MAGNIFICATION)
canvas = screen.getcanvas()
canvas.config(xscrollincrement=str(MAGNIFICATION))
canvas.config(yscrollincrement=str(MAGNIFICATION))
# turtle initialization
turtle = Turtle("turtle", visible=False)
turtle.width(MAGNIFICATION)
turtle.resizemode('auto')
### Generate a landscape to explore
screen.tracer(False)
RULES = {'x':'x+yf+', 'y':'-fx-y', 'f':'f', '+':'+', '-':'-'}
sub_string = string = "fx"
LEVEL = 13
for _ in range(LEVEL):
turtle.pencolor(random(), random(), random())
for character in sub_string:
if character == '+':
turtle.right(90)
elif character == '-':
turtle.left(90)
elif character == 'f':
turtle.forward(5 * MAGNIFICATION)
screen.update()
full_string = "".join(RULES[character] for character in string)
sub_string = full_string[len(string):]
string = full_string
screen.tracer(True)
### Finished generating a landscape to explore
turtle.penup()
turtle.home()
turtle.setheading(90)
turtle.color('dark green', 'light green')
turtle.showturtle()
screen.onkey(move_left, "Left")
screen.onkey(move_right, "Right")
screen.onkey(move_up, "Up")
screen.onkey(move_down, "Down")
screen.listen()
screen.mainloop()
滚动条反映了整个空间的运动。不幸的是,滚动条仍然处于活动状态,并且会向歪斜的方向扔东西(改为使用箭头键),并且需要在横向边缘附近工作,但这只是一个示例,它表明如果花些时间可以进行几乎所有操作探索tkinter / Tk的基础。