在初学者的项目中,我正在为电报组创建一个战斗游戏,一个玩家向另一个挑战,然后在聊天中发生战斗。现在,我想为其实现“超时”功能。我设法使它使用_thread起作用:
import _thread
class Battle:
def __init__(self, chat_id):
self.chat = chat
print('Instance of battle started on chat %s' % self.chat)
self.pcount = 0
self.p1score = 0
self.p2score = 0
def reset(self):
self.pcount = 0
self.p1score = 0
self.p2score = 0
def timeout(chat_id):
time.sleep(90)
battle = battledic[chat_id]
if battledic[chat_id].timer == 1:
sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
battle.reset()
else:
return
battle = Battle(chat_id)
if message == "challenge":
if battle.pcount == 0:
_thread.start_new_thread(timeout, (chat_id,))
...
因此,基本上我正在做的是调用超时功能,该功能将在另一个线程中睡眠90秒,然后检查是否只有一个玩家(pcount == 1)进行战斗。 ,它会向聊天室发送一条消息,告知他们战斗未开始,然后重置战斗实例。
这里的问题是我经常提出异常,即使它在大多数情况下都能正常工作,但有时也达不到预期的效果,导致正在进行的战斗结束。经过研究,我发现这样做并不是理想的方式,但是我找不到更好的解决方案,也许我也想同时进行其他聊天中的其他战斗。在这种情况下应该使用什么?合作多任务处理?多处理?trheading模块?感谢您完成此任务的任何提示!
我已经让你开始了。我不确定您将如何聊天或记录谁在玩。
我最初的想法是运行线程,但是while循环更容易。
# from threading import Thread
from time import sleep
no_one = True
battledic = {} # your dict here. It may be better to use a list of objects (classes) for your opponents
class Battle(object):
def __init__(self, chat_id):
self.chat_id = chat_id
self.pcount = 0
self.p1score = 0
self.p2score = 0
print('Instance of battle started on chat %s' % self.chat_id)
def reset(self):
self.pcount = 0
self.p1score = 0
self.p2score = 0
def wheres_waldo():
x = 0; no_one = True
while x < 90: # waits 90 seconds unless found
for player in battledic.keys():
if player.is_requesting: # found someone
no_one = False
break # quit looking
else:
print('No one yet')
sleep(1); x+= 1
if no_one:
sendmessage(chat_id, 'no one accepted') # first parameter is the chat address and the second one is the message
battle.reset()
else:
sendmessage(chat_id, 'Found someone')
def sendmessage(chat_id,message):
print('%s on chat %s' % (message,chat_id))
battle = Battle(chat_id)
while True:
message = raw_input('Command? ')
if message == "challenge":
if battle.pcount == 0:
wheres_waldo()
# first thoughts were to run threads but the while loop is easier
# wait = Thread(target=timeout, args=(chat_id))
# where = Thread(target=wheres_waldo)
# wait.start();where.start()
# wait.join();where.join()
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句