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

时间:2015-10-25 18:25:08

标签: python multithreading

所以我和我堂兄一起编写了一个小项目,但由于我们没有Python 3.x的经验,我们无法为我可以购买的其中一个项目创建一个后台循环。店。我是唯一一个在多线程方面有一点经验的人(请注意,我几乎不知道任何事情),所以我到处寻找解决方案,我没有这样做。到目前为止,这是我的代码:

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_loop,我还需要了解多线程XD的某些方面。任何帮助表示赞赏!

1 个答案:

答案 0 :(得分:0)

如果你是Python新手,不确定你需要的是背景循环你最好用数学来模拟时间,但是,这是我个人的观点。我允许自己检查/重写你的代码,因为我发现了一些错误,比如没有遵循PEP8规则,或者出现了错误的if/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)