学富五车的你,敢来迎战Python开发的成语接龙游戏吗?
导读:快过年了,很多小伙伴可能要原地过年了,而且线下聚会也不是好办法,那怎么过?今天就来搞事情吧。用3W+的成语数据库,开发一款成语接龙的小游戏。适合自娱自乐,也可以跟亲朋好友PK一下。
CREATE TABLE rank (
name VARCHAR (50) NOT NULL,
round_num INT NOT NULL
);
from pypinyin import pinyin
pinyin('唇枪舌剑')
# output:
[['chún'], ['qiāng'], ['shé'], ['jiàn']]
# 此处为一个嵌套列表,我们需要转化为数据库中的格式
' '.join(map(lambda x: x[0], pinyin('唇枪舌剑')))
# output:
'chún qiāng shé jiàn'
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1 ,user-scalable=no">
<title>清风pythontitle>
<link rel="icon" href="{{ url_for('static',filename='favicon.ico') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/bootstrap.min.css') }}">
<link rel="stylesheet" href="{{ url_for('static',filename='css/main.css') }}">
<script src="{{ url_for('static',filename='js/jquery.min.js') }}">script>
head>
<body>
<div class="container container-small">
<div class="content">
<div class="header">
成语接龙
div>
<div class="block-info">
{% block contents %}
{% endblock %}
div>
div>
<div class="footer">
©2019-欢迎关注我的公众号:<a href="https://www.jianshu.com/u/d23fd5012bed">清风Pythona>
div>
div>
body>
html>
login.html涉及到挑战者排行和用户名提交与页面跳转 game.html主要负责成语接龙游戏的监控与AJAX数据的后台刷新。
import sqlite3
from flask import Flask, render_template, request, g, session, redirect, url_for, jsonify
import random
from pypinyin import pinyin
app = Flask(__name__)
DATABASE = 'static/db/database.db'
app.secret_key = 'Breeze Python'
def connect_db():
return sqlite3.connect(DATABASE)
@app.before_request
def before_request():
g.db = connect_db()
@app.teardown_request
def teardown_request(exception):
if hasattr(g, 'db'):
g.db.close()
def query_db(query, args=(), one=True):
cur = g.db.execute(query, args)
rv = [dict((cur.description[idx][0], value)
for idx, value in enumerate(row)) for row in cur.fetchall()]
if not query.startswith('select'):
g.db.commit()
return (rv[0] if rv else None) if one else rv
@app.route('/', methods=['GET', 'POST'])
def index():
if request.method == 'POST':
user = request.form.get('name')
session['user'] = user
session['round'] = 1
return redirect(url_for('game'))
rank_list = query_db('select * from rank order by round_num desc limit 5',one=False)
print(rank_list)
return render_template('login.html', rank_list=rank_list)
@app.route('/game')
48def game():
if not session.get('user'):
return redirect(url_for('index'))
id = random.randint(1, 30000)
idiom = query_db('select * from idiom where id = ?',
[id])
return render_template('game.html', user=session.get('user'), idiom=idiom)
@app.route('/more/')
def more(user_idiom):
speak_list = pinyin(user_idiom)
print(speak_list[0][-1])
idiom_speak = ' '.join(map(lambda x: x[0], speak_list))
if query_db('select * from idiom where speak = ?',
[idiom_speak]):
new_idiom = query_db("select * from idiom where speak like ('%s%%')" % speak_list[-1][0])
session['round'] = session.get('round') + 1
print({'code': 200, 'round': session.get('round'), 'info': new_idiom})
return jsonify({'code': 200, 'round': session.get('round') + 1, 'info': new_idiom})
else:
query_db('replace into rank (name,round_num) values (?,?)',
[session.get('user'), session.get('round')])
return jsonify({'code': 404, 'error': "挑战结束:用户输入的成语是自己编的吧!", 'url': request.host_url})
干货直达👇
评论