宾果数ch

2024-05-13 09:22:01 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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 ...

但它只是打开然后关闭。文件中没有错误或任何文本。它不需要转到文件。我只是想,如果是这样的话,我可以在最后添加一个searchfile特性,知道这个号码是否被调用。 如果“中奖”的号码是真的打电话来的,最好的办法是什么?


Tags: and文件程序ifdefrandompopfile1
1条回答
网友
1楼 · 发布于 2024-05-13 09:22:01

我将累积在set中调用的数字,这些数字将从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'),但重复打开要追加的文件通常不是一个好的解决方案)。

相关问题 更多 >