简体   繁体   English

创建具有函数和类的 python 2 玩家游戏

[英]creating a python 2 player game with functions & classes

This is a game where player 1 gets asked questions and store all player 1 answers in a list.这是一个游戏,玩家 1 被问到问题并将所有玩家 1 的答案存储在一个列表中。 After player 1 finishes his/her turn, then player 2 gets to play and ask the same exact questions as player 1 and store player 2 answers in a different list.在玩家 1 完成他/她的回合后,玩家 2 开始游戏并提出与玩家 1 相同的问题,并将玩家 2 的答案存储在不同的列表中。

I have player 1 in a function, problem is once player1 function is done running the program exits.我在 function 中有玩家 1,问题是一旦 player1 function 完成运行程序退出。

1- how do I make it so player2 gets asked the same questions as player1. 1-我如何做到这一点,以便玩家 2 被问到与玩家 1 相同的问题。 Also, that once player1 function is done running that the program goes to player2 function.此外,一旦 player1 function 运行完成,程序将转到 player2 function。

2- would it be better to store my list of dict questions in a class, because I intend to increase the number of questions in the qa list, and how do I do so? 2-将我的 dict 问题列表存储在 class 中会更好,因为我打算增加 qa 列表中的问题数量,我该怎么做? Please see code below.请看下面的代码。

import random

qa = [{"question": 'mi', 'yes': 'si', 'no': 'bay'}, {"question": 'see', 'yes': 'boom', 'no': 'dos'}, {"question": 'do', 'yes': 'fool', 'no': 'sil'}, {"question": 're', 'yes': 'but', 'no': 'fool'}]

user1 = []
user2 = []

# this function is for bad input
def valid_input(prompt, opt1, opt2):
    while True:
        response = input(prompt).lower()
        if opt1 in response:
            break
        elif opt2 in response:
            break
        else:
            print('error, enter again')
    return response

def player1():
    cap = len(qa)
    i = 0
    print("Hello player 1")
    while i < cap:
        rand_q = random.choice(qa)
        print(rand_q["question"])
        answer1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
        if 'yes' in answer1:
            user1.append('yes')
            print(rand_q.get(answer1, ''))

            answer1_1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
            if 'yes' in answer1_1:
                user1.append('correct')
                qa.remove(rand_q)
                i += 1

            elif 'no' in answer1_1:
                user1.append('wrong')
                qa.remove(rand_q)
                i += 1


        elif 'no' in answer1:
            user1.append('no')
            print(rand_q.get(answer1, ''))

            answer1_1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
            if 'yes' in answer1_1:
                user1.append('correct')
                qa.remove(rand_q)
                i += 1

            elif 'no' in answer1_1:
                user1.append('wrong')
                qa.remove(rand_q)
                i += 1
def player2():
    cap = len(qa)
    i = 0
    print("Hello player 2")
    while i < cap:
        rand_q = random.choice(qa)
        print(rand_q["question"])
        answer1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
        if 'yes' in answer1:
            user1.append('yes')
            print(rand_q.get(answer1, ''))

            answer1_1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
            if 'yes' in answer1_1:
                user1.append('correct')
                qa.remove(rand_q)
                i += 1

            elif 'no' in answer1_1:
                user1.append('wrong')
                qa.remove(rand_q)
                i += 1


        elif 'no' in answer1:
            user1.append('no')
            print(rand_q.get(answer1, ''))

            answer1_1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
            if 'yes' in answer1_1:
                user1.append('correct')
                qa.remove(rand_q)
                i += 1

            elif 'no' in answer1_1:
                user1.append('wrong')
                qa.remove(rand_q)
                i += 1

def play():
    player1()
    player2()
    
play()

since I'm new at coding I'm wondering if this the best approach for a 2 player game since I plan on growing the size of the game.因为我是编码新手,所以我想知道这是否是 2 人游戏的最佳方法,因为我计划扩大游戏的规模。 Any suggestions, ideas are welcome.欢迎任何建议,想法。 Thank you.谢谢你。

Here's a very quick refactor to make it so you don't have to copy and paste the quiz logic for each player.这是一个非常快速的重构,因此您不必为每个玩家复制和粘贴测验逻辑。 Note that we don't pop the questions out of qa (instead we just shuffle the list), which makes it easier to reuse the same questions -- currently your program exits after player1() because that function empties the question list and leaves nothing for player2 to do, but the below code should fix that.请注意,我们不会将问题从qa中弹出(而是我们只是将列表打乱),这样可以更轻松地重用相同的问题 - 目前您的程序在shuffle player1()之后退出,因为 function 清空了问题列表并且什么都没有为player2做,但下面的代码应该解决这个问题。

(edit to reflect comments -- just shuffle once, and declare everything in play() ) (编辑以反映评论——只需洗牌一次,并在play()中声明所有内容)

def quiz(qa, user):
    for rand_q in qa:
        print(rand_q["question"])
        answer1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
        if 'yes' in answer1:
            user.append('yes')
            print(rand_q.get(answer1, ''))

            answer1_1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
            if 'yes' in answer1_1:
                user.append('correct')
            elif 'no' in answer1_1:
                user.append('wrong')
        elif 'no' in answer1:
            user.append('no')
            print(rand_q.get(answer1, ''))

            answer1_1 = valid_input("enter 'yes' or 'no'\n", "yes", "no")
            if 'yes' in answer1_1:
                user.append('correct')
            elif 'no' in answer1_1:
                user.append('wrong')

def play():
    qa = [
        {"question": 'mi', 'yes': 'si', 'no': 'bay'}, 
        {"question": 'see', 'yes': 'boom', 'no': 'dos'}, 
        {"question": 'do', 'yes': 'fool', 'no': 'sil'}, 
        {"question": 're', 'yes': 'but', 'no': 'fool'},
    ]
    user1, user2 = [], []

    random.shuffle(qa)

    print("Hello player 1")
    quiz(qa, user1)
    print("Hello player 2")
    quiz(qa, user2)
    
play()

As mentioned in the comments your indentation for the while loops are incorrect. 如评论中所述,您对 while 循环的缩进不正确。 It is just running the next line ( rand_q = random.choice(qa) ), and due to that the value of i is never incremented (as it never reaches the next lines of code), the while loop keeps running forever. 它只是运行下一行( rand_q = random.choice(qa) ),并且由于 i的值永远不会增加(因为它永远不会到达下一行代码),while 循环将永远运行。

EDIT - Seems like the code was properly intended in the OP after reading the comments编辑 - 阅读评论后,似乎代码在 OP 中是正确的

I will answer the questions now updated-我将回答现在更新的问题-

  1. because in the player1 you keep removing values from the qa list, by the time it runs the player2 code, the qa list is empty and hence the while i < cap: condition is never true and player2 code never runs.因为在player1中,您不断从qa列表中删除值,当它运行player2代码时, qa列表为空,因此while i < cap:条件永远不会为真,并且 player2 代码永远不会运行。

    You can create a copy of qa list for processing in both the codes, this can be done by您可以创建qa列表的副本以在两个代码中进行处理,这可以通过

    qa_copy = list(qa) # OR qa_copy = qa.copy() # Since python 3.3

    So instead of using qa directly in each player function, you will create a copy first and only use that copy in the function.因此,不要在每个播放器 function 中直接使用qa ,而是先创建一个副本,并且只在 function 中使用该副本。

  2. Depends on how you want to add the questions,取决于您要如何添加问题,

    is it to be added programmatically?是否以编程方式添加?

    If so, you can use list.append(new_question) to add a new question如果是这样,您可以使用list.append(new_question)添加新问题

    If the questions are static but there are a lot of them and you are worried they will make the code untidy如果问题是 static 但问题很多,您担心它们会使代码不整洁

    you can store these in a separate file and load the file on start of the python program.您可以将这些存储在单独的文件中,并在 python 程序启动时加载文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM