0

所以我为我的妻子建立了一个小型宾果游戏程序,供她在蜡烛派对上使用。板已经生成。这只是一个调用数字的程序。

import random
a = []
a = list(range(1,76))
random.shuffle(a)

def pop(x):
    while 1:
        b = a.pop(0)
        if b <= 15:
            print 'b', b,
        elif b > 15 and b <=30:
            print 'i', b,
        elif b > 30 and b <=45:
            print 'n', b,
        elif b > 45 and b <=60:
            print 'g', b,
        else:
            print 'o', b,
        raw_input('')

pop(1)

现在她的派对越来越大,她担心有人作弊,所以我想添加一个功能,我可以输入应该赢得的号码,并让程序让我知道这些号码是否确实被调用。我试过将它运行到一个文件中

def pop(x):
    while 1:
        b = a.pop(0)
        with open('bingo.txt', 'w') as file1:
            file1.write(b,'\n')
        if b ...

但它只是打开然后关闭。文件中没有错误或任何文本。它不需要转到文件。我只是想,如果确实如此,我可以在最后添加一个搜索文件功能,并知道该号码是否被调用。找出“获胜”线上的数字是否真的被调用的最佳方法是什么?

4

1 回答 1

4

我会累积在 aset中调用的数字,这些数字将从pop. 然后我会添加一个函数来读取“获胜”数字(进入一个集合)并检查该新集合是否是被调用数字的子集:

import random
import ast

def pop(a,accumulated=None):
    print "type q to move on to verification"
    if accumulated is None:
        accumulated = set()
    v = 'I can put any string here, as long as it is not "q" :-)'
    while v.lower() != 'q':
        b = a.pop(0)
        if b <= 15:
            print 'b', b,
        elif b > 15 and b <=30:
            print 'i', b,
        elif b > 30 and b <=45:
            print 'n', b,
        elif b > 45 and b <=60:
            print 'g', b,
        else:
            print 'o', b,
        accumulated.add(b)
        v = raw_input('')
    return accumulated

def verify(numbers):
    new_nums = raw_input("enter numbers separated by ',': ")
    nums = ast.literal_eval(new_nums)
    assert( len(nums) == 5 ) #Need 5 numbers to win
    result = set(nums).issubset(numbers)
    print "Verified? ",result
    return result
    #alternatively, and probably slightly more efficient
    # print numbers.issuperset(nums)
    #I prefer the other though as `subset` is easier for me to remember


def robust_verify(numbers):
   """
   keep trying to verify the numbers until we succeed
   """
   try:
       verify(numbers)
   except (AssertionError,SyntaxError,TypeError):  #other error conditions might go here too, but these are the ones I can think of right now ...
       robust_verify(numbers)


def play_bingo(game_vals=None,accumulated=None):
    if game_vals is None:
        game_vals = list(range(1,76))  #list strictly not necessary here, but why not?
        random.shuffle(game_vals)

    nums = pop(game_vals,accumulated=accumulated)
    if not robust_verify(nums):
        play_bingo(game_vals=game_vals,accumulated=nums)


play_bingo()

通过确保verify成功(例如,您的用户不会意外输入数字作为15a,17,22,...) ,这会变得更加健壮

作为旁注,您使用文件的尝试失败了,因为您正在打开一个文件,向其中写入一个数字并在每次“绘制”一个新数字时关闭它。由于您正在打开文件,因为'w'任何已经存在的文件都会被破坏 - 因此您只能存储该方法绘制的最后一个数字。您希望将while循环移动到with语句中以使该方法正常工作(或打开文件以进行附加 ( 'a'),但重复打开文件以进行附加通常不是一个好的解决方案)。

于 2012-11-14T17:38:30.527 回答