在python上绘制带有龟图形的条形码

时间:2015-10-16 20:41:26

标签: python turtle-graphics

我知道使用Python做很多事情都有疯狂的捷径,这就是我在我的简介CIS课程中遇到这个项目的麻烦。我搜索了我的问题的变化,但没有运气.. SO:

该项目是让我们的“乌龟”使用将输入命令行的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。

我知道下一行在某处会有所帮助,我查找了地图功能,我知道我需要将编码转换为字符串中的整数。

map(list,str(zip))

谢谢!

1 个答案:

答案 0 :(得分:2)

您需要遍历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技术缩短代码,但这很容易理解。