从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏
从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏
·
Flask框架
Flask框架中文网
建议在开发环境和生产环境下都使用虚拟环境来管理项目的依赖。虚拟环境可以为每一个项目安装独立的 Python 库,这样就可以隔离不同项目之间的 Python 库,也可以隔离项目与操作系统之间的 Python 库。
如果你使用Python 3版本,可以按以下方式配置虚拟环境和Flask环境。
创建虚拟环境
创建一个项目文件夹
cd 文件夹路径
mkdir myproject
cd myproject
python3 -m venv venv
pip3 install virtualenv
如果此时提醒诸如WARNING: You are using pip version 22.0.4; however, version 22.1.2 is available.
就按照提示升级PHP版本。
在Windows下
py -3 -m venv venv
Python27\Scripts\virtualenv.exe venv
pip3 install Flask
激活虚拟环境
. venv/bin/activate
在Windows下
> venv\Scripts\activate
安装Flask
在已激活的虚拟环境中可以使用如下命令安装 Flask:
pip install Flask
SQLite
前往SQLite下载或SQLite中文下载载预编译的二进制文件。Windows系统请下载
基于您的电脑选择适用于32位或64位的文件。
创建文件夹 C:\sqlite,并在此文件夹下解压上面两个压缩文件,将得到以下文件:
添加 C:\sqlite 到 PATH 环境变量
运行sqlite3
Pycharm中创建Flask项目
申请百度语音识别接口
代码实现
前端登录
login.html
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>登录</title></head>
<script type="text/javascript" src="static/js/jquery-3.4.1.min.js"></script>
<link rel="stylesheet" type="text/css" href="static/css/bar.css"/>
<style type=text/css>
* {
margin: 0;
padding: 0;
}
html {
height: 100%;
width: 100%;
overflow: hidden;
margin: 0;
padding: 0;
}
body {
display: flex;
align-items: center;
justify-content: center;
height: 100%;
}
#loginDiv {
width: 100%;
display: flex;
justify-content: center;
align-items: center;
height: 300px;
box-shadow: 7px 7px 17px rgba(52, 56, 66, 0.5);
border-radius: 5px;
}
#name_trip {
margin-left: 50px;
color: red;
}
p {
margin-top: 30px;
margin-left: 20px;
color: #26b3b3;
}
input {
margin-left: 15px;
border-radius: 5px;
border-style: hidden;
height: 30px;
width: 140px;
background-color: rgba(216, 191, 216, 0.5);
outline: none;
color: #000000;
}
.button {
border-color: cornsilk;
background-color: rgba(100, 149, 237, .7);
color: aliceblue;
border-style: hidden;
border-radius: 5px;
width: 100px;
height: 31px;
font-size: 16px;
}
input {
margin-top: 10px
}
label { width:150px; text-align:right; margin-left: 30px;}
</style>
<body>
<div id="main">
<div id="loginDiv">
<form action="/Login" method="post">
<h1 style="text-align: center;color: #6489d5;">LOGIN</h1>
<p><label>用户名:</label><input id="username" type="text" name="username"><label id="name_trip"></label></p>
<p><label>密码:</label><input id="pwd1" type="password" name="pwd1"><label id="password_trip"></label></p>
<div style="text-align: center;margin-top: 30px;">
<input type="submit" class="button" value="登录">
<br>
<input type="button" class="button" value="注册" id="regist">
</div>
</form>
</div>
</div>
<script type="text/javascript">
var username = $("#username").val();
$("#username").blur(function () {
username = $("#username").val();
$.post("/CheckUserID", {username: username}, function (rtnSvr) {
console.log(rtnSvr)
if (username.length != 0) {
if (rtnSvr != "0") {
alert("该用户不存在")
$("#username").val("")
return false
}
}
})
});
$("form").submit(function () {
var username = $("#username").val();
var pwd1 = $("#pwd1").val();
if (pwd1.length == 0 || username.length == 0) {
alert("输入不能为空")
return false;
}
$.post("/CheckUser",{username:username,pwd1:pwd1},function (data){
if (data== '0'){
alert("密码输入错误")
return false
}
})
});
$("#regist").click(function (){
$(location).attr("href","signin")
})
</script>
</body>
</html>
FLASK实现五子棋逻辑判断
judgement.py
import json
from flask import request, jsonify
from BlackChess import BlackChess
from WhiteChess import WhiteChess
from Subject import Subject
def judge(i, j):
result = json.loads(request.form.get('data'))
# result = request.form.get('data')
checkBox = result.get('checkBox')
value = checkBox[i][j]
winner = 0
# flag = result.get('flag')
flag = False
for x in range(j - 4, j + 5):
if x >= 0 and x + 4 < 15:
if checkBox[i][x] == value and checkBox[i][x + 1] == value and checkBox[i][x + 2] == value and checkBox[i][
x + 3] == value and checkBox[i][x + 4] == value:
flag = True
break
pass
for x in range(i - 4, i + 5): # 纵向有没有出现5连(在边缘依次逐一遍历,是否五个棋子的类型一样)
if x >= 0 and x + 4 < 15:
if checkBox[x][j] == value and \
checkBox[x + 1][j] == value and \
checkBox[x + 2][j] == value and \
checkBox[x + 3][j] == value and \
checkBox[x + 4][j] == value:
flag = True
break
pass
# 先判断右斜方向的对角下输赢 x 列轴, y是行轴 , i 是行 j 是列(右斜向)(在边缘依次逐一遍历,是否五个棋子的类型一样)
for x, y in zip(range(j + 4, j - 5, -1), range(i - 4, i + 5)):
if x >= 0 and x + 4 < 15 and y + 4 >= 0 and y < 15:
if checkBox[y][x] == value and \
checkBox[y - 1][x + 1] == value and \
checkBox[y - 2][x + 2] == value and \
checkBox[y - 3][x + 3] == value and \
checkBox[y - 4][x + 4] == value:
flag = True
# 2、判断左斜对角下输赢 x 列轴, y是行轴 , i 是行 j 是列(左斜向)(在边缘依次逐一遍历,是否五个棋子的类型一样)
for x, y in zip(range(j - 4, j + 5), range(i - 4, i + 5)):
if x >= 0 and x + 4 < 15 and y >= 0 and y + 4 < 15:
if checkBox[y][x] == value and \
checkBox[y + 1][x + 1] == value and \
checkBox[y + 2][x + 2] == value and \
checkBox[y + 3][x + 3] == value and \
checkBox[y + 4][x + 4] == value:
flag = True
if flag:
subject = Subject()
black_chess = BlackChess(x, y, subject)
white_chess = WhiteChess(x, y, subject)
if value == 2:
winner = 1
subject.setWiner(white_chess)
else:
winner = 2
subject.setWiner(black_chess)
return winner
语音控制功能
AudioLocation.py
import wave
import pyaudio
import requests
import time
import base64
from pyaudio import paInt16
framerate = 16000 # 采样率
num_samples = 2000 # 采样点
channels = 1 # 声道
sampwidth = 2 # 采样宽度2bytes
FILEPATH = 'speech.wav'
HOST = 'https://aip.baidubce.com/oauth/2.0/token?grant_type=client_credentials&client_id=这里写百度语音识别的API Key&client_secret=这里写百度语音识别的Secret Key'
response = requests.get(HOST)
if response:
print(response.json())
def getToken(host):
res = requests.post(host)
print(res.json())
return res.json()['access_token']
def save_wave_file(filepath, data):
wf = wave.open(filepath, 'wb')
wf.setnchannels(channels)
wf.setsampwidth(sampwidth)
wf.setframerate(framerate)
wf.writeframes(b''.join(data))
wf.close()
def my_record():
pa = pyaudio.PyAudio()
stream = pa.open(format=paInt16, channels=channels,
rate=framerate, input=True, frames_per_buffer=num_samples)
my_buf = []
# count = 0
t = time.time()
print('正在录音...')
while time.time() < t + 4: # 秒
string_audio_data = stream.read(num_samples)
my_buf.append(string_audio_data)
print('录音结束.')
save_wave_file(FILEPATH, my_buf)
stream.close()
def get_audio(file):
with open(file, 'rb') as f:
data = f.read()
# print(data)
return data
def speech2text(speech_data, token, dev_pid=1537):
FORMAT = 'wav'
RATE = '16000'
CHANNEL = 1
CUID = 'DC-71-96-C9-44-E6'
SPEECH = base64.b64encode(speech_data).decode('utf-8')
data = {
'format': FORMAT,
'rate': RATE,
'channel': CHANNEL,
'cuid': CUID,
'len': len(speech_data),
'speech': SPEECH,
'token': token,
'dev_pid': dev_pid
}
url = 'http://vop.baidu.com/server_api'
headers = {'Content-Type': 'application/json'}
# r=requests.post(url,data=json.dumps(data),headers=headers)
print('正在识别...')
r = requests.post(url, json=data, headers=headers)
Result = r.json()
if 'result' in Result:
return Result['result'][0]
else:
return Result
def getLocation():
my_record()
TOKEN = getToken(HOST)
speech = get_audio(FILEPATH)
result = speech2text(speech, TOKEN, int(1537))
print(result)
return result
源码
更多推荐
已为社区贡献1条内容
所有评论(0)