Series entry

Programming Tetris Robot in Python3

Design ideas

Record the history of manually played games by users and automatically played games by AI, and store it in the database for later analysis. In order not to rely on a particular data system, a general database interface is designed to facilitate switching between different databases at the application level.

Interface design

Class baseTao (object): def select(self, tablename, params={}, fields=None): Query parameters (ORM rules are included in the dictionary, see the next log); Return data field Fields = [] if Fields == None else Fields # Python's default parameter behavior is very different. Return dbhelper.select(tablename, params, fields) # True query implementation, DbHelper is a database specific interface implementation def insert(self, tablename, params={}, fields=[]): # new interface, CURD function parameter form is consistent, this design is easy to use for REST microservices, If '_id_' in params and len(params) < 2 or '_id_' not in params and len(params) < 1: Return {"code": 301, "err": "The params is error."} return dbhelper.insert(tablename, params) def update(self, tablename, params={}, fields=[]): if '_id_' not in params or len(params) < 2: return {"code": 301, "err": "The params is error."} return dbhelper.update(tablename, params) def delete(self, tablename, params={}, fields=[]): if '_id_' not in params: return {"code": 301, "err": "The params is error."} return dbhelper.delete(tablename, params) def querySql(self, sql, values = [], params = {}, QuerySQL (SQL, values, params, fields) def execSQL (self, values, values = []): Return dbhelper.exec_sql(SQL, values) def insertBatch(self, tablename, elements: List): Return dbHelper. insertBatch(tablename,elements) def transGo(elements = [], isAsync = False)

The concrete implementation (Sqlit3)

Firstly, the operation interface of SQLit3 is implemented.

The function that directly faces Sqlit3

Def exec_sql(SQL, values, opType = 0): # opType: 0 1 - Batch operation statement; 2 - The query returns a dataset; Error = {} if not os.path.exists("./dist"): error = {} if not os.path.exists(". Cos.mkdir ("dist") conn = DBHandle.connect ("./dist/log.db") Num = cur.execute(SQL, values) if opType == 2: FetchAll () else: conn.mit () # print('Sql: ', 'Values:') ', values) except Exception as err: # error = True error = err print(' error: ', err) finally: Conn. Close () # Finishes processing and formats the return result if flag: return False, error, num if 'num' in dir() else 0 return True, result if 'result' in dir() else [], len(result) if opType == 2 else num.rowcount if 'num' in dir() else 0

Query function

See the next log for an explanation of how to include the ORM in the dictionary.

def select(tablename, params={}, fields=None, sql = None, values = None): where = "" AndJoinStr = ' and ' reserveKeys = {} for rk in ["sort", "search", "page", "size", "sum", "count", "group"]: For k, v in params.items(): whereExtra = "" if k == "ins": Elif reserveKeys. Get ('search'): # WhereExtra += k + "=? "Values.append (v) where += whereExtra # RS = exec_sql(SQL, values, 2) return {"code": 200, "rows": rs[1], "total": rs[2]}

Insert the function

Delete and update are similar to insert, and the insert function is explained here

def insert(tablename, params={}): SQL = "insert into %s (" % tablename # id = params.keys() vs = [] ps = "" for al in ks: SQL > select * from a list where p = p, p = p, p = p; "," # Python's sqlit3 encapsulation cannot be fed into a list object to write tuple data. Vs.append (params[al]) SQL = SQL [:-1] + ") VALUES (" + PS [:-1] + ")" If rs[0]: # return {"code": 200, "info": "create success.", "total": rs[2]} else: return {"code": 701, "error": rs[1].args[0], "total": rs[2]}

Bulk insert

As it turns out, the inserts are so inefficient that the AI can’t keep up with the data being written.

Def insertBatch(tablename, elements: List): if len(elements) == 0: # return {"code": 201, "info": "There is no elements exist.", "total": 0} elif len(elements) == 1: # has only one element, Return insert(tablename, elements[0]) SQL = "insert into %s (" % tablename isFirst = True # VS = [] ps = "" for ele in elements: if isFirst: isFirst = False ks = ele.keys() for al in ks: SQL += al + ", ps += ", p += ", p += ", p +=" ," # items = [] for bl in ks: # add write parameter values one by one in order of key Items.append (ele[bl]) vs.append(items) SQL = SQL [:-1] + ") VALUES (" + ps[:-1] + ")" # items.append(ele[bl]) vs.append(items) SQL = SQL [:-1] + ") VALUES (" + ps[:-1] + ") Return {"code": 200, "info": "create success.", "total": rs[2]} else: return {"code": 701, "error": rs[1].args[0], "total": rs[2]}

Content forecast

The next post explains how to design and use the ORM rules incorporated into the dictionary. With this set of rules, there is no need to write SQL statements. How about the future, please keep paying attention, thank you!

The project address

https://gitee.com/zhoutk/ptetris or https://github.com/zhoutk/ptetris

Operation method

1. install python3, git
2. git clone https://gitee.com/zhoutk/ptetris (or download and unzip source code)
3. cd ptetris
4. python3 tetris

This project surpport windows, linux, macOs

on linux, you must install tkinter first, use this command:  
sudo apt install python3-tk

Related projects

C++ version has been implemented, project address:

https://gitee.com/zhoutk/qtetris