我需要帮助在python中创建一个后台循环

我需要帮助在python中创建一个后台循环,python,multithreading,Python,Multithreading,因此,我正在与我的堂兄一起编写一个小项目,但由于我们没有使用Python3.x的经验,我们无法为我的一个项目创建一个后台while循环,您可以在商店中购买。我是唯一一个在多线程方面有一点儿经验的人,请注意,我对多线程几乎一无所知,所以我到处寻找解决方案,但我没有。以下是我目前的代码: import time import random import subprocess import os import sys import threading from queue import Queue

因此,我正在与我的堂兄一起编写一个小项目,但由于我们没有使用Python3.x的经验,我们无法为我的一个项目创建一个后台while循环,您可以在商店中购买。我是唯一一个在多线程方面有一点儿经验的人,请注意,我对多线程几乎一无所知,所以我到处寻找解决方案,但我没有。以下是我目前的代码:

import time
import random
import subprocess
import os
import sys
import threading
from queue import Queue

print_lock = threading.Lock()




def cap_scavengerJob(worker) :
    player_value = 0
    scav = 0
    magnet = 0
    press = 0

    print()
    print("Welcome to Cap Scavenger!")
    print()
    time.sleep(1)
    print("Searching for caps.")
    time.sleep(0.5)
    print("Searching for caps..")
    time.sleep(0.5)
    print("Searching for caps...")
    time.sleep(1)

    start_chance = random.randint(65,125)
    print("You have found ", start_chance ,"caps!")
    player_value = player_value+start_chance
    print("Your goal is to find as many caps as you can!")

    while True :
        decision_search_1 = input("Would you like to (search) for more caps, (check) how many caps you have or go to the (shop)? \n")
        if decision_search_1 == "search" :
            print("Searching for caps.")
            time.sleep(0.5)
            print("Searching for caps..")
            time.sleep(0.5)
            print("Searching for caps...")
            time.sleep(1)
            search_chance = random.randint(0,100)
            if search_chance >= 50 :
                cap_chance = random.randint(10,50)
                print("You have found ", cap_chance ,"caps!")
                player_value = player_value+cap_chance
                print()
                print("You now have", player_value ,"caps!")
                print()

            elif search_chance >= 85  :
                cap_chance = random.randint(5,10)
                print("You have found", cap_chance ,"caps!")
                player_value = player_value+cap_chance
                print()
                print("You now have", player_value ,"caps!")
                print()

            elif search_chance >= 40 :
                cap_chance = random.randint(25,75)
                print("You have found", cap_chance ,"caps! You got lucky!")
                player_value = player_value+cap_chance
                print()
                print("You now have", player_value ,"caps!")
                print()

            elif search_chance >= 25 :
                cap_chance = random.randint(40,120)
                print("You have found", cap_chance ,"caps! You got lucky!")
                player_value = player_value+cap_chance
                print()
                print("You now have", player_value ,"caps!")
                print()

            elif search_chance <= 10 :
                cap_chance = random.randint(60,250)
                print("You have found", cap_chance ,"caps! You hit the jackpot!")
                player_value = player_value+cap_chance
                print()
                print("You now have", player_value ,"caps!")
                print()

            else :
                print("You haven't found any caps.")
                print("You now have", player_value ,"caps!")

        elif decision_search_1 == "shop" :
            print("Welcome to the shop!")
            time.sleep(1)
            print("Here you can buy items which will produce caps, making your job easier!")
            time.sleep(1)
            shop_option = input("Would you like to (buy) or (exit)? \n")
            time.sleep(0.4)
            while shop_option == "buy" :
                print("(S)cavenger (10 caps per second) : 500 caps")
                print("(C)ap magnet (20 caps per second) : 1000 caps")
                print("(F)actory cap press (100 caps per second) : 5000 caps")

                buy_option = input()

                if buy_option == "S" :
                    if player_value < 500 :
                        print("Sorry, you don't have enough caps. Get more!")
                    elif player_value >=500 :
                        player_value = player_value-500
                        scav = scav+1
                        print("Thank you for purchasing a Scavenger, you now have ", scav ,"Scavengers!")

                        shop_option = input("Please enter anything to exit the shop. \n")

        elif decision_search_1 == "check" :
            print("You have ", player_value ,"caps!")
            print("You have ", scav ,"Scavengers!")
            print("You have ", magnet ,"Cap magnets!")
            print("You have ", press ,"Factory cap presses!")

        elif decision_search_1 == "debug_mode" :
            print("Debug Mode activated!")
            player_value = player_value+10000


def scav_loopJob(worker):
    while True:
        player_value += 1
        time.sleep(1)

def threader():
    while True:
        worker = q.get()
        cap_scavengerJob(worker)
        q.task_done()

def threader():
    while True:
        worker = q.get()
        scav_loopJob(worker)
        q.task_done()

q = Queue()

for x in range(1):
    t = threading.Thread(target = threader)
    t.daemon = True
    t.start()

start =time.time()

for worker in range(20):
    q.put(worker)

q.join()

我真正需要的帮助是如何同时运行主程序和scav_循环,我还需要了解多线程XD的一些方面。感谢您的帮助

不确定您需要的是一个后台循环如果您是Python新手,最好使用数学来模拟时间,但是,这是我个人的观点。我允许自己检查/重写您的代码,因为我发现了一些错误,比如不遵守PEP8规则,或者如果/elif/elif/elif块明显错误,等等

我在这里的建议远非完美,但应该开始帮助你以更好的方式组织自己。让你的代码可读,让你的变量正确命名,让你的方法正确命名,明天就可以自己阅读了

希望有帮助

#!/usr/bin/env python3

import time
import random
from datetime import datetime


"""
1) Trying to use 'input' from like 20 thread simultaneously is probably
   not a great idea.
2) You should read the PEP8
3) Good thing you're using Python 3 :-)
4) You should write shorter methods, aroudn 25 lines max
5) Why do you need background tasks ?

If you think you need background tasks to increment a variable each
second, that's probably not the easier way to start. A good may may
probably better to "simulated" this, like storing the last time the
player have seen its credits, computing the number of seconds since
then, and adding it just before printing again.

Don't forget to drop a line or two of doc to explain what you're
doing.
"""

class Shop():
    def __init__(self):
        """Initial stock, as an example about the class Shop managing its own rules
        """
        self.scavs = 100

    def player_enters(self, player):
        print("Welcome to the shop!")
        time.sleep(1)
        print("Here you can buy items which will produce caps, making your "
              "job easier!")
        time.sleep(1)
        shop_option = input("Would you like to (buy) or (exit)? \n")
        time.sleep(0.4)
        while shop_option == "buy":
            print("(S)cavenger (10 caps per second) : 500 caps")
            print("(C)ap magnet (20 caps per second) : 1000 caps")
            print("(F)actory cap press (100 caps per second) : 5000 caps")

            buy_option = input()

            if buy_option == "S":
                if self.scavs < 1:
                    print("Sorry, no moar scavs here")
                elif player.value < 500:
                    print("Sorry, you don't have enough caps. Get more!")
                elif player.value >= 500:
                    player.give(500)
                    player.scav += 1
                    print("Thank you for purchasing a Scavenger, "
                          "you now have ", player.scav, "Scavengers!")
                    shop_option = input("Please enter anything to exit "
                                        "the shop. \n")


class Player():
    """That's not completly necessary, but a good example, you can use a
    class to store information about something, and how to modify it.
    """
    def __init__(self):
        self._value = 0
        self.scav = 0
        self.magnet = 0
        self.press = 0
        self.last_checked = datetime.now()

    def give(self, value):
        self._value -= value

    def receive(self, value):
        self._value += value

    @property
    def value(self):
        now = datetime.now()
        seconds = (now - self.last_checked).total_seconds()
        self.last_checked = now
        self._value += int((self.scav * 10 +
                            self.magnet * 20 +
                            self.press * 100) * seconds)
        return self._value

    def will_find_some_caps(self, rand_min, rand_max):
        """Here you should find a better name for this method. Naming is
        important (and complicated).
        """
        cap_chance = random.randint(rand_min, rand_max)
        print("You have found {} caps!".format(cap_chance))
        self._value += cap_chance
        print("\nYou now have {} caps!\n".format(self.value))

    def search(self):
        """Here, your succession of if/elsif is wrong, the first one is >= 50,
        which completly hide the second one, being >= 85.  I also
        doubt about using random to choose a range for random, you're
        not adding randomness to randomness, that's useless, what
        about a single, simple, self.will_find_some_caps(0, 250) ?
        """
        progress("Searching for caps.")
        search_chance = random.randint(0, 100)
        if search_chance >= 50:
            self.will_find_some_caps(10, 50)
        elif search_chance >= 85:
            self.will_find_some_caps(5, 10)
        elif search_chance >= 40:
            self.will_find_some_caps(25, 75)
        elif search_chance >= 25:
            self.will_find_some_caps(40, 120)
        elif search_chance <= 10:
            self.will_find_some_caps(60, 250)
        else:
            print("You haven't found any caps.")
            print("You now have {} caps!".format(self.value))

    def goto_shop(self, shop):
        shop.player_enters(self)

    def check(self):
        print("You have ", self.value, "caps!")
        print("You have ", self.scav, "Scavengers!")
        print("You have ", self.magnet, "Cap magnets!")
        print("You have ", self.press, "Factory cap presses!")


def progress(text):
    """Print text twice, with little sleeps in between
    """
    print(text + '.')
    time.sleep(.5)
    print(text + '..')
    time.sleep(.5)
    print(text + '...')
    time.sleep(1)


def cap_scavengerJob(player, shop):
    print("\nWelcome to Cap Scavenger!\n")
    time.sleep(1)
    progress("Searching for caps")

    start_chance = random.randint(65, 125)
    print("You have found ", start_chance, "caps!")
    player.receive(start_chance)
    print("Your goal is to find as many caps as you can!")
    while True:
        decision_search_1 = input(
            "Would you like to (search) for more caps, "
            "(check) how many caps you have or go to the (shop)? \n")
        if decision_search_1 == "search":
            player.search()
        elif decision_search_1 == "shop":
            player.goto_shop(shop)
        elif decision_search_1 == "check":
            player.check()
        elif decision_search_1 == "debug_mode":
            print("Debug Mode activated!")
            player.receive(10000)

player1 = Player()
main_shop = Shop()

while True:
    cap_scavengerJob(player1, main_shop)

你可能必须缩小你的问题范围,明确你的问题是什么。顺便问一下,你的表弟怎么样了?什么是scav_循环?老实说,这个问题可能比你想的要容易得多,所以试着做一个新窗口,做商店代码,然后玩它。换言之,将其剥离到骨骼中,以找出问题所在。问题是,当您在商店中购买某个物品时,本案例中的清道夫应该每秒为您的玩家值添加1,但由于我对多线程非常不在行,因此不会。scav循环是添加玩家值的while循环,非常感谢!我甚至不知道有PEP8规则xD。我将尝试该程序,看看是否正确工作,并给你一些反馈,再次感谢!不客气,请毫不犹豫地与Python社区交流和分享,您会学到很多东西,比如在freenode上的IRC、Python或Python fr上。如果您是法国人,我就是这样,所以我在-fr one:p上。通常在没有IRC客户端时使用。