Python用户输入棋盘
在我的作业中,我尝试制作一个5 x 5的棋盘,由用户选择颜色和正方形大小。我学会了如何根据用户输入制作正方形大小和颜色,但我在如何开始循环或如何创建5 x 5棋盘上遇到了一些问题。我只是不知道我能做些什么来移动乌龟来制作一个5x5板。到目前为止,我已经做了很多,如果有人能帮助我开始,我将非常感激Python用户输入棋盘,python,input,turtle-graphics,Python,Input,Turtle Graphics,在我的作业中,我尝试制作一个5 x 5的棋盘,由用户选择颜色和正方形大小。我学会了如何根据用户输入制作正方形大小和颜色,但我在如何开始循环或如何创建5 x 5棋盘上遇到了一些问题。我只是不知道我能做些什么来移动乌龟来制作一个5x5板。到目前为止,我已经做了很多,如果有人能帮助我开始,我将非常感激 import turtle def main(): length = int(input("Enter a desired length (from 1-150.)")) keepGo
import turtle
def main():
length = int(input("Enter a desired length (from 1-150.)"))
keepGoing = 'y'
while keepGoing == 'y':
print("What color would you like to draw?")
print(" Enter 1 for Black")
print(" 2 for Blue")
print(" 3 for Red")
print(" 4 for Green")
choice = int(input(" Your choice?"))
if choice == 1:
square(0,0,length,'black')
elif choice == 2:
square(0,0,length,'blue')
elif choice == 3:
square(0,0,length,'red')
elif choice == 4:
square(0,0,length,'green')
else:
print("ERROR: only enter 1-4.")
def square(x, y, width, color):
turtle.clear()
turtle.penup() # Raise the pen
turtle.goto(x, y) # Move to (X,Y)
turtle.fillcolor(color) # Set the fill color
turtle.pendown() # Lower the pen
turtle.begin_fill() # Start filling
for count in range(4): # Draw a square
turtle.forward(width)
turtle.left(90)
turtle.end_fill()
#calling main function
main()
首先,您开发了用户界面,但没有任何界面可供使用——下次您可能会以另一种方式开始。其次,不要重新发明布尔语(例如,keepGoing='y')。第三,对于绘制一个正方形所需的代码量,我们可以对整个网格进行标记:
from turtle import Turtle, Screen
COLORS = ["Black", "Blue", "Red", "Green"]
GRID = 5
STAMP_UNIT = 20
def main():
length = int(input("Enter a desired length (from 1-150): "))
keepGoing = True
while keepGoing:
print("What color would you like to draw?")
for i, color in enumerate(COLORS, start=1):
print(" Enter {} for {}".format(i, color))
choice = int(input(" Your choice? "))
if 1 <= choice <= len(COLORS):
grid(-length * GRID // 2, -length * GRID // 2, length, COLORS[choice - 1])
keepGoing = False
else:
print("ERROR: only enter 1-{}.".format(len(COLORS)))
def grid(x, y, width, color):
tortoise = Turtle('square', visible=False)
tortoise.shapesize(width / STAMP_UNIT)
tortoise.color(color)
tortoise.penup()
for dy in range(0, GRID):
tortoise.goto(x, y + width * dy)
for dx in range(dy % 2, GRID, 2):
tortoise.setx(x + width * dx)
tortoise.stamp()
screen = Screen()
main()
screen.exitonclick()
输出
这是一个完美的例子,说明冲压可以使事情比绘图更简单、更快。只需绘制并填充每个正方形。在所有方块上打圈,确定它们的位置。然后在每个位置画一个颜色合适的正方形。
> python3 test.py
Enter a desired length (from 1-150): 30
What color would you like to draw?
Enter 1 for Black
Enter 2 for Blue
Enter 3 for Red
Enter 4 for Green
Your choice? 2