Skip to content

Instantly share code, notes, and snippets.

@tyage

tyage/bingo.cgi Secret

Last active February 19, 2018 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tyage/a520c7c6e3f8ee765c75280f2c417f6b to your computer and use it in GitHub Desktop.
Save tyage/a520c7c6e3f8ee765c75280f2c417f6b to your computer and use it in GitHub Desktop.
#!/usr/bin/python
# -*- coding: utf-8 -*-
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
import SocketServer
import urlparse
import os
import sys
import random
import json
import cgi
import cv2
status = json.loads(open("status.json").read())
bingotitle = cv2.imread("bingotitle.jpg")
blue_images = {}
for n in range(75):
blue_images[n+1] = cv2.imread("numbers/blue_" + ("%02d" % (n + 1)) + ".jpg")
gray_images = {}
for n in range(99):
gray_images[n+1] = cv2.imread("numbers/gray_" + ("%02d" % (n + 1)) + ".jpg")
def rnd(digit):
s = ""
for i in range(digit):
s += str(random.randint(0, 9))
return s
def new_bingo(max_number=75):
num_base = []
if max_number == 75:
I15 = [i+1 for i in range( 0, 15)]
I30 = [i+1 for i in range(15, 30)]
I45 = [i+1 for i in range(30, 45)]
I60 = [i+1 for i in range(45, 60)]
I75 = [i+1 for i in range(60, 75)]
random.shuffle(I15)
random.shuffle(I30)
random.shuffle(I45)
random.shuffle(I60)
random.shuffle(I75)
for i in range(5):
num_base.append(I15[i])
num_base.append(I30[i])
num_base.append(I45[i])
num_base.append(I60[i])
num_base.append(I75[i])
else:
for i in range(max_number):
num_base.append(i+1)
random.shuffle(num_base)
num_base[12] = 99
return num_base[:25]
def check_bingo(bingo, called_nums):
ck_list = [
# yoko
[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10,11,12,13,14],
[15,16,17,18,19],
[20,21,22,23,24],
# tate
[ 0, 5,10,15,20],
[ 1, 6,11,16,21],
[ 2, 7,12,17,22],
[ 3, 8,13,18,23],
[ 4, 9,14,19,24],
# naname
[ 0, 6,12,18,24],
[ 4, 8,12,16,20]
]
for ck in ck_list:
flag = True
for i in range(5):
if not bingo[ck[i]] in called_nums:
flag = False
break
if flag == True:
return 1
return 0
def save_jpg_for_size(original, size, baseurl):
cv2.imwrite(baseurl + "/" + str(size) + ".jpg", original)
def make_imagemap_from_data(userid, bingo, called_nums):
global status
global bingotitle
global blue_images
global gray_images
card = [bingotitle]
for i in range(5):
line_ = []
for j in range(5):
n = bingo[ (i * 5) + j ]
if not n in called_nums:
one = blue_images[n]
else:
one = gray_images[n]
line_.append(one)
card.append(cv2.hconcat(line_))
img = cv2.vconcat(card)
baseurl = status["local_pics_path"] + userid
if os.path.isdir(baseurl) == False:
os.mkdir(baseurl)
imageid = rnd(20)
baseurl = status["local_pics_path"] + userid + "/" + imageid
os.mkdir(baseurl)
save_jpg_for_size(img, 305, baseurl)
return status["web_pics_path"] + userid + "/" + imageid
def make_image_from_data(userid, bingo, called_nums):
global bingotitle
global blue_images
global gray_images
card = [bingotitle]
for i in range(5):
line_ = []
for j in range(5):
n = bingo[ (i * 5) + j ]
if not n in called_nums:
one = blue_images[n]
else:
one = gray_images[n]
line_.append(one)
card.append(cv2.hconcat(line_))
return cv2.vconcat(card)
def save_image(img, userid, bingo, called_nums):
global status
baseurl = status["local_pics_path"] + userid
if os.path.isdir(baseurl) == False:
os.mkdir(baseurl)
imageid = rnd(20)
baseurl = status["local_pics_path"] + userid + "/" + imageid
os.mkdir(baseurl)
save_jpg_for_size(img, 305, baseurl)
return status["web_pics_path"] + userid + "/" + imageid
def html(text):
print "Content-Type: application/json"
print
print "{'result': '" + text + "'}"
sys.exit()
def branch():
form = cgi.FieldStorage()
num = form.getvalue("num")
if num != None:
return (0, num)
uid = form.getvalue("uid")
call = form.getvalue("call")
if uid != None and call != None:
return (1, uid, call)
return (-1, "error")
def main():
result = branch()
if result[0] == 0:
routineA(result[1])
return
if result[0] == 1:
routineB(result[1], result[2])
return
html("404 not found")
return
def routineA(num):
global status
if num == None:
html('404 not found')
if int(num) < 1:
html('404 not found')
num = int(num)
if os.path.exists("a_cache"):
return open("a_cache").read()
uid = rnd(30)
data= {
'data': [],
'result': 'ok',
'called': [99]
}
for i in range(num):
bingo = new_bingo(75)
img = make_image_from_data(uid, bingo, [99])
url = save_image(img, uid, bingo, [99])
one = {
"url": url,
"data": bingo
}
data['data'].append(one)
path = status["local_pics_path"] + uid + "/" + "ginfo.json"
open(path, "w").write(json.dumps(data, indent=4))
a_cache = json.dumps(data, indent=4)
open('a_cache', "w").write(a_cache)
return a_cache
def routineB(uid, call):
global status
path = status["local_pics_path"] + uid + "/" + "ginfo.json"
ginfo= json.loads(open(path).read())
if not int(call) in ginfo["called"]:
ginfo["called"].append(int(call))
if os.path.exists("b_cache"):
data = json.loads(open("b_cache").read())
data["called"] = ginfo["called"]
return json.dumps(data, indent=4)
data = {
'data': [],
'result': 'ok',
'called': ginfo["called"]
}
for v in ginfo["data"]:
url = make_imagemap_from_data(uid, v["data"], ginfo["called"])
one = {
"url": url,
"data": v["data"],
"bingo": check_bingo(v["data"], ginfo["called"])
}
data['data'].append(one)
open(path, "w").write(json.dumps(data, indent=4))
else:
data = ginfo
b_cache = json.dumps(data, indent=4)
open("b_cache", "w").write(b_cache)
return b_cache
class S(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'application/json')
self.end_headers()
def do_GET(self):
parsed_path = urlparse.urlparse(self.path)
self._set_headers()
queries = {}
for q in parsed_path.query.split('&'):
queries[q.split('=')[0]] = q.split('=')[1]
result = branch()
if 'num' in queries:
self.wfile.write(routineA(queries['num']))
else:
self.wfile.write(routineB(queries['uid'], queries['call']))
def run(server_class=HTTPServer, handler_class=S, port=80):
server_address = ('', port)
httpd = server_class(server_address, handler_class)
print 'Starting httpd...'
httpd.serve_forever()
if __name__ == "__main__":
from sys import argv
if len(argv) == 2:
run(port=int(argv[1]))
else:
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment