从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

Flask框架

Flask框架中文网
建议在开发环境和生产环境下都使用虚拟环境来管理项目的依赖。虚拟环境可以为每一个项目安装独立的 Python 库,这样就可以隔离不同项目之间的 Python 库,也可以隔离项目与操作系统之间的 Python 库。

如果你使用Python 3版本,可以按以下方式配置虚拟环境和Flask环境。

创建虚拟环境

创建一个项目文件夹
cd 文件夹路径
mkdir myproject
cd myproject
python3 -m venv venv
pip3 install virtualenv

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏
如果此时提醒诸如 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

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

激活虚拟环境

. venv/bin/activate

在Windows下

> venv\Scripts\activate

安装Flask

在已激活的虚拟环境中可以使用如下命令安装 Flask:

pip install Flask

SQLite

前往SQLite下载SQLite中文下载载预编译的二进制文件。Windows系统请下载

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏
基于您的电脑选择适用于32位或64位的文件。

创建文件夹 C:\sqlite,并在此文件夹下解压上面两个压缩文件,将得到以下文件:

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

添加 C:\sqlite 到 PATH 环境变量

运行 sqlite3

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

; Pycharm中创建Flask项目

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

申请百度语音识别接口

百度语音识别

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

; 代码实现

前端登录

从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏
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;">LOGINh1>
            <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="登录">

                <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'))

    checkBox = result.get('checkBox')
    value = checkBox[i][j]
    winner = 0

    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):
        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

    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

    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
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 = []

    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()

    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'}

    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

源码

源码见:基于Python Flask框架、SQLite的语音识别五子棋web小游戏

Original: https://blog.csdn.net/sevenlob/article/details/125110009
Author: sevenlob
Title: 从零开始的基于Python Flask框架、SQLite的语音识别五子棋web小游戏

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/817205/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球