[英]drawing a barcode with turtle graphics on python
我知道用 Python 做很多事情都有一些疯狂的捷径,这就是我在介绍 CIS 类的这个项目中遇到麻烦的地方。 我已经搜索了我的问题的变体,但没有运气..所以:
该项目是让我们的“海龟”使用将输入到命令行中的 ZIP 绘制条形码。 我完成了很多结构性工作,即:特定数字的编码并告诉乌龟为特定数字绘制条形多长时间..但是,现在我坚持编写 for 循环来实际将这两部分放在一起并获取绘制条形码的程序。
这是我所拥有的:
import argparse # Used in main program to obtain 5-digit ZIP code from command
# line
import time # Used in main program to pause program before exit
import turtle # Used in your function to print the bar code
## Constants used by this program
SLEEP_TIME = 30 # number of seconds to sleep after drawing the barcode
ENCODINGS = [[1, 1, 0, 0, 0], # encoding for '0'
[0, 0, 0, 1, 1], # encoding for '1'
[0, 0, 1, 0, 1], # encoding for '2'
[0, 0, 1, 1, 0], # encoding for '3'
[0, 1, 0, 0, 1], # encoding for '4'
[0, 1, 0, 1, 0], # encoding for '5'
[0, 1, 1, 0, 0], # encoding for '6'
[1, 0, 0, 0, 1], # encoding for '7'
[1, 0, 0, 1, 0], # encoding for '8'
[1, 0, 1, 0, 0] # encoding for '9'
]
SINGLE_LENGTH = 25 # length of a short bar, long bar is twice as long
def compute_check_digit(digits):
sum = 0
for i in range(len(digits)):
sum = sum + digits[i]
check_digit = 10 - (sum % 10)
if (check_digit == 10):
check_digit = 0
return check_digit
def draw_bar(my_turtle, digit):
my_turtle.left(90)
if digit == 0:
length = SINGLE_LENGTH
else:
length = 2 * SINGLE_LENGTH
my_turtle.forward(length)
my_turtle.up()
my_turtle.backward(length)
my_turtle.right(90)
my_turtle.forward(10)
my_turtle.down()
def draw_zip(my_turtle, zip):
# WHAT DO I DO
print("My code to draw the barcode needs to replace this print statement")
def main():
parser = argparse.ArgumentParser()
parser.add_argument("ZIP", type=int)
args = parser.parse_args()
zip = args.ZIP
if zip <= 0 or zip > 99999:
print("zip must be > 0 and < 100000; you provided", zip)
else:
my_turtle = turtle.Turtle()
draw_zip(my_turtle, zip)
time.sleep(SLEEP_TIME)
if __name__ == "__main__":
main()
开始和结束时的 argparse/parser 东西是在我们开始每个项目时提供给我们的。
我知道下一行在某处会有所帮助,我查找了地图功能,我知道我需要将编码从字符串转换为整数。
地图(列表,str(zip))
谢谢!
您需要遍历 zip 的数字。 对于每个数字,您遍历 5 个小节。
for str_digit in str(zip):
digit = int(str_digit)
for bar_bit in ENCODINGS[digit]:
draw_bar(my_turtle, bar_bit)
<move turtle to next bar's starting point>
我希望这对你来说是可以理解的。 您可以使用各种 Python 技术缩短代码,但这很容易理解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.