我正在摆弄我从CSGO reddit收到的一些代码,使用刚刚发布的游戏状态集成实现炸弹计时器,我已设法使代码使用HTTP Post JSON,如下所示:
import time
import SimpleHTTPServer
import SocketServer
import logging
import cgi
import sys
import json
import signal
PORT = 3000
planted = False
#If we ctrl+C out of python, make sure we close the serial port first
#handler catches and closes it
def signal_handler(signal, frame):
ser.close()
sys.exit(0)
class ServerHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
def do_GET(self):
SimpleHTTPServer.SimpleHTTPRequestHandler.do_GET(self)
#SimpleHTTPServer doesn't handle post by default. Hacked up way to do it here
def do_POST(self):
length = int(self.headers["Content-Length"])
jsonString = str(self.rfile.read(length))
print jsonString
print "---"
jsonDict = json.loads(jsonString)
#From here we have a JSON dict, that has whatever data CS is sending
#For the timer, all we care about is the the 'round' key
if 'round' in jsonDict:
rounds = jsonDict['round']
if 'bomb' in rounds:
if rounds['bomb'] == "planted":
planted = True
print "Bomb has been planted"
#timer code here
def main():
x = 10
for i in range(x + 1):
time.sleep(1)
print(formatTime(x))
x -= 1
def formatTime(x):
minutes = int(x / 60)
seconds_rem = int(x % 60)
if (seconds_rem < 10):
return(str(minutes) + ":0" + str(seconds_rem))
else:
return(str(minutes) + ":" + str(seconds_rem))
main()
#If bomb has been defused, then send the 'C' message
if rounds['bomb'] == "defused":
planted = False
print "bomb has been defused"
#if the round ends, either bomb exploded or everyone died.
#Send the 'C' message to stop timer.
if 'previously' in jsonDict:
if 'round' in jsonDict['previously']:
if 'bomb' in jsonDict['previously']['round']:
planted = False
print "Round ran out"
#not sure if a response is really required. Send it anyway
response = bytes("This is the response.") #create response
self.send_response(200) #create header
self.send_header("Content-Length", str(len(response)))
self.end_headers()
self.wfile.write(response) #send response
Handler = ServerHandler
#On windows, Serial ports are usually COM1-3
#On mac/linux this will be different
#Set up our handler for ctrl+c
signal.signal(signal.SIGINT, signal_handler)
#Start server
httpd = SocketServer.TCPServer(("", PORT), Handler)
#Run server
httpd.serve_forever()
然而,这部分代码:
def main():
x = 10
for i in range(x + 1):
time.sleep(1)
print(formatTime(x))
x -= 1
def formatTime(x):
minutes = int(x / 60)
seconds_rem = int(x % 60)
if (seconds_rem < 10):
return(str(minutes) + ":0" + str(seconds_rem))
else:
return(str(minutes) + ":" + str(seconds_rem))
main()
运行自己两次,如python shell日志中所示,并且它说炸弹已被种植,即使该回合已经完全结束,想知道是否有人知道它为什么会自行运行两次。