Python 当乌龟到达网格边缘时结束游戏

Python 当乌龟到达网格边缘时结束游戏,python,python-3.x,turtle-graphics,Python,Python 3.x,Turtle Graphics,我必须写一个程序来实现海龟图形的使用。我已经写了大部分的程序,包括网格和多个海龟的创建,但是一旦海龟到达我创建的网格边缘,我就很难结束游戏。以下是我到目前为止的情况: import turtle import random # Setting up Turtle Graphics Window turtle.setup(800,600) window = turtle.Screen() window.title("Turtles Walking through Grid") window.bg

我必须写一个程序来实现海龟图形的使用。我已经写了大部分的程序,包括网格和多个海龟的创建,但是一旦海龟到达我创建的网格边缘,我就很难结束游戏。以下是我到目前为止的情况:

import turtle
import random

# Setting up Turtle Graphics Window
turtle.setup(800,600)
window = turtle.Screen()
window.title("Turtles Walking through Grid")
window.bgcolor("black")


# Making the turtle
grid = turtle.getturtle()
grid.shape("classic")
grid.color("white")
grid.speed(10)

# Creating the Grid (Relative Positioning)
grid.penup()
grid.setposition(-300,200)
grid.pendown()
grid.forward(600)
grid.right(90)
grid.forward(400)
grid.right(90)
grid.forward(600)
grid.right(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(400)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(400)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(600)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(600)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(600)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(600)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(600)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(600)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(600)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(600)
grid.right(90)
grid.forward(40)
grid.right(90)
grid.forward(600)
grid.left(90)
grid.forward(40)
grid.left(90)
grid.forward(600)

# User Input for Speed 
speed = int(input("Enter the speed of the turtles (1-10): "))

# Variable for choosing colors
all_colors =      ["red","white","blue","hotpink","purple","lightgreen","yellow"]

# Creating the turtles
def createTurtles(turtle_count):
    count = []
    for k in range(0, turtle_count):
        lil_guys = turtle.Turtle()
        lil_guys.shape("turtle")
        colors = random.choice(all_colors)
        lil_guys.color(colors)
        lil_guys.speed(speed)
        lil_guys.pendown()
        count.append(lil_guys)
    return count

# Determine where the Turtle should stop
def off_board(self):
    x = self.turtle.xcor()
    y = self.turtle.ycor()
    return x < -160 or 160 < x or y < -160 or 160 < y

# Set Turtle Amount to 5
count = createTurtles(5)
fun = True

while fun:
    for k in range(5):
        coin = random.randrange(0, 2)
        if coin == 0:
            count[k].left(90)
        else:
            count[k].right(90)

        count[k].forward(40)

# Exit on close window
turtle.exitonclick()
导入海龟
随机输入
#设置海龟图形窗口
海龟。设置(800600)
window=turtle.Screen()
窗口标题(“穿过网格的海龟”)
window.bgcolor(“黑色”)
#做海龟
grid=turtle.getturtle()
网格形状(“经典”)
网格颜色(“白色”)
网格速度(10)
#创建栅格(相对定位)
grid.penup()
网格设置位置(-300200)
grid.pendown()
前进网格(600)
网格。右(90)
前进网格(400)
网格。右(90)
前进网格(600)
网格。右(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(400)
左网格(90)
网格向前(40)
左网格(90)
前进网格(400)
网格。右(90)
网格向前(40)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(600)
左网格(90)
网格向前(40)
左网格(90)
前进网格(600)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(600)
左网格(90)
网格向前(40)
左网格(90)
前进网格(600)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(600)
左网格(90)
网格向前(40)
左网格(90)
前进网格(600)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(600)
左网格(90)
网格向前(40)
左网格(90)
前进网格(600)
网格。右(90)
网格向前(40)
网格。右(90)
前进网格(600)
左网格(90)
网格向前(40)
左网格(90)
前进网格(600)
#用户输入速度
速度=整数(输入(“输入海龟的速度(1-10):”)
#用于选择颜色的变量
所有颜色=[“红色”、“白色”、“蓝色”、“粉红”、“紫色”、“浅绿色”、“黄色”]
#创造海龟
def createTurtles(海龟计数):
计数=[]
对于范围内的k(0,乌龟计数):
小家伙们=乌龟。乌龟()
小家伙们,形状(“海龟”)
颜色=随机。选择(所有颜色)
小家伙们,颜色(颜色)
小家伙们,速度(速度)
伙计们,彭敦
计数。追加(小家伙)
返回计数
#确定海龟应该停在哪里
def离板(自):
x=self.turtle.xcor()
y=self.turtle.ycor()
返回x<-160或160
当五只海龟中的一只到达我创建的网格边缘时,程序应该结束。

在网格边缘退出 当海龟到达网格边缘时,可以退出,如下所示:

while fun:
    for k in range(5):
        coin = random.randrange(0, 2)
        if coin == 0:
            count[k].left(90)
        else:
            count[k].right(90)

        count[k].forward(40)

        x = count[k].xcor()          # new lines
        y = count[k].ycor()          # |
                                     # |
        if x < -300 or 300 < x or \  # |
           y < -200 or 200 < y:      # |
            fun = False              # |
            break                    # |
  • 避免使用数字和字符串;将所有这些变量放在
    main
    程序的顶部,并在整个过程中使用它们。具体来说,在这个程序中,您需要
    高度
    宽度
    网格大小
    参数,这些参数将在一个位置定义并控制整个程序的运行(包括确定海龟何时离开网格)。现在,如果我决定网格大小为30,高度为200,宽度为400,例如,我可以在一个地方更改这些数字,一切正常

  • 使用Python的默认参数或字典来减轻函数过多参数的负担。将函数放在脚本顶部,并将它们与
    main
    分开
  • 注释是好的,但代码已经很明显时的注释通常会增加噪音:

    # Exit on close window
    turtle.exitonclick()
    
  • 记住用户:我没有意识到在绘制网格后必须返回终端输入海龟速度。我更愿意提示用户输入海龟速度,然后运行程序的可视部分


  • 可能的重构 综上所述,这里有一个建议的第一次重构(设计改进的空间仍然很大,但这应该提供一些思考的食物):

    导入海龟
    随机输入
    海龟(
    海龟,海龟计数,颜色,速度=10,shape=“海龟”
    ):
    海龟=[]
    对于范围内的(海龟计数):
    tur=海龟。海龟()
    旋转形状(形状)
    颜色(随机选择(颜色))
    转速
    tur.pendown()
    海龟。附加(海龟)
    海龟归来
    def绘制线(海龟、转弯、长度a、长度b、网格大小):
    对于范围内的(0,长度+1,网格大小):
    乌龟
    乌龟。向前(长度_b)
    乌龟
    转弯(90)
    乌龟。前进(网格大小)
    转弯(90)
    乌龟。向前(长度_b)
    转弯(180)
    def绘图网格(
    海龟,宽=600,高=400,网格尺寸=40,
    速度=100,形状=“经典”,颜色=“白色”
    ):
    tur=turtle.getturtle()
    旋转形状(形状)
    颜色(颜色)
    转速
    tur.penup()
    旋转设置位置(-宽度//2,高度//2)
    绘制线(tur、tur.right、高度、宽度、网格大小)
    旋转设置位置(-width//2,
    
    # Exit on close window
    turtle.exitonclick()
    
    import turtle
    import random
    
    def create_turtles(
        turtle, turtle_count, colors, speed=10, shape="turtle"
    ):
        turtles = []
    
        for _ in range(turtle_count):
            tur = turtle.Turtle()
            tur.shape(shape)
            tur.color(random.choice(colors))
            tur.speed(speed)
            tur.pendown()
            turtles.append(tur)
    
        return turtles
    
    def draw_lines(turtle, turn, length_a, length_b, grid_size):
        for _ in range(0, length_a + 1, grid_size):
            turtle.pendown()
            turtle.forward(length_b)
            turtle.penup()
            turn(90)
            turtle.forward(grid_size)
            turn(90)
            turtle.forward(length_b)
            turn(180)
    
    def draw_grid(
        turtle, width=600, height=400, grid_size=40, 
        speed=100, shape="classic", color="white"
    ):
        tur = turtle.getturtle()
        tur.shape(shape)
        tur.color(color)
        tur.speed(speed)
        tur.penup()
    
        tur.setposition(-width // 2, height // 2)
        draw_lines(tur, tur.right, height, width, grid_size)
    
        tur.setposition(-width // 2, height // 2)
        tur.right(90)
        draw_lines(tur, tur.left, width, height, grid_size)
    
        turtle.penup()
        turtle.ht()
    
    def off_grid(turtle, width, height):
        x = turtle.xcor()
        y = turtle.ycor()
    
        return x < -width // 2 or x > width // 2 or \
               y < -height // 2or y > height // 2
    
    
    if __name__ == "__main__":
        grid_size = 40
        height = 400
        width = 600
        all_colors = [
            "red", "white", "blue", "hotpink", 
            "purple", "lightgreen", "yellow"
        ]
    
        speed = int(input("Enter the speed of the turtles (1-10): "))
    
        turtle.setup(800, 600)
        window = turtle.Screen()
        window.title("Turtles Walking through Grid")
        window.bgcolor("black")
    
        draw_grid(turtle, width, height, grid_size)
        turtles = create_turtles(turtle, 5, all_colors, speed)
        running = True
    
        while running:
            for tur in turtles:
                random.choice([tur.left, tur.right])(90)
                tur.forward(grid_size)
    
                if off_grid(tur, width, height):
                    running = False
                    break
    
        turtle.exitonclick()
    
    from turtle import Screen, Turtle
    from random import choice
    
    TURTLE_COUNT = 5
    
    # Variable for choosing colors
    ALL_COLORS = ['red', 'green', 'blue', 'magenta', 'yellow', 'cyan', 'purple']
    
    WINDOW_WIDTH, WINDOW_HEIGHT = 800, 600
    GRID_WIDTH, GRID_HEIGHT = 600, 400
    CELL_SIZE = 40  # should be a divisor of GRID_WIDTH and GRID_HEIGHT, and probably no smaller than CURSOR_SIZE
    
    CURSOR_SIZE = 20
    
    # Creating the turtles
    def create_turtles(turtle_count, speed):
        turtles = []
    
        for index in range(turtle_count):
            lil_guy = Turtle('turtle')
            lil_guy.color(ALL_COLORS[index % TURTLE_COUNT])
            lil_guy.speed(speed)
            lil_guy.penup()
            # to place a turtle cleanly on the grid lines, we have to consider the parity of the grid size
            lil_guy.goto((GRID_WIDTH / CELL_SIZE % 2) * CELL_SIZE/2, (GRID_HEIGHT / CELL_SIZE % 2) * CELL_SIZE/2)
            lil_guy.pendown()
    
            turtles.append(lil_guy)
    
        return turtles
    
    # Determine where the Turtle should stop
    def on_edge(turtle):
        x, y = turtle.position()
        return abs(x) >= (GRID_WIDTH/2 - CELL_SIZE/2) or abs(y) >= (GRID_HEIGHT/2 - CELL_SIZE/2)
    
    # Setting up Turtle Graphics Window
    window = Screen()
    window.setup(WINDOW_WIDTH, WINDOW_HEIGHT)
    window.title("Turtles Walking through Grid")
    window.bgcolor('black')
    
    # Create the grid via stamping
    grid = Turtle(visible=False)
    grid.speed('fastest')
    grid.color('white')
    grid.penup()
    
    grid.setx(-GRID_WIDTH/2)
    grid.shapesize(GRID_HEIGHT*2 / CURSOR_SIZE, 1/CURSOR_SIZE)
    
    for _ in range(GRID_WIDTH // CELL_SIZE + 1):
        grid.stamp()
        grid.forward(CELL_SIZE)
    
    grid.setheading(90)
    
    grid.setposition(0, -GRID_HEIGHT/2)
    grid.shapesize(GRID_WIDTH*2 / CURSOR_SIZE, 1/CURSOR_SIZE)
    
    for _ in range(GRID_HEIGHT // CELL_SIZE + 1):
        grid.stamp()
        grid.forward(CELL_SIZE)
    
    # User Input for Speed
    user_speed = window.numinput("Turtle Speed", "Enter a value (1-10)", default=5, minval=1, maxval=10)
    
    # Set Turtle Amount
    turtles = create_turtles(TURTLE_COUNT, user_speed)
    
    finished = False
    
    while not finished:
        for k in range(5):
            angle = choice([90, -90])
    
            turtles[k].left(angle)
            turtles[k].forward(CELL_SIZE)
    
            finished = on_edge(turtles[k])
            if finished:
                break
    
    # Exit on close window
    window.exitonclick()