佳木斯湛栽影视文化发展公司

主頁 > 知識庫 > 基于flask實現五子棋小游戲

基于flask實現五子棋小游戲

熱門標簽:Win7旗艦版 硅谷的囚徒呼叫中心 電話運營中心 呼叫中心市場需求 客戶服務 語音系統(tǒng) 百度AI接口 企業(yè)做大做強

本文實例為大家分享了基于flask實現五子棋小游戲的具體代碼,供大家參考,具體內容如下

前言

首先說明一下,本人方向是java后端,只因老師布置了一個作業(yè),要用flask來做一個五子棋,沒辦法被逼上梁山,程序不太美觀,但是應付作業(yè)還是夠了的。

廢話不多說,下面開錘!

首先整個程序是一個web應用,前端html+css+javaScript(有用到jquery)(基本都是現學的,所以程序很多注釋也很丑),后端用的flask框架。

準備工作

**1.**python環(huán)境、安裝flask

**2.**導入需要用到的包

pip install flask_cors
pip install flask_sqlalchemy

**3.**創(chuàng)建一個flask項目,并將一下代碼復制運行

文件結構

圖片資源

不做代碼的生產者,只做代碼的搬運工

前端

游戲頁面

!DOCTYPE html>
html lang="en">
head>
        meta charset="UTF-8">
        title>五子棋/title>
 style>
 * {
    margin: 0;
    padding: 0;
 }

 body {
    margin-top: 20px;
    margin-left: 20px;
 }

 canvas {
    background-image: url("img/backgroud.jpg");
    border: 1px solid #000;
 }

 .mybutton {
            width: 200px;
            line-height: 40px;
            text-align: center;
            background-color: cornflowerblue;
            margin: 0 auto;
            margin-top: 20px;
            font-size: 20px;
            color: #fff;
        }
 /style>
/head>

body>
        canvas width="600" height="600" onclick="play(event)">/canvas>    
        
        div>
            input type="button" value="重新開始" onclick="replay()" class="mybutton">    
        /div>
          

script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js">/script>
script>
 /*準備工作: 1獲取畫布,獲取畫筆對象 */
    var mcanvas = document.querySelector("canvas");
    var ctx = mcanvas.getContext("2d");

    /*準備工作:2創(chuàng)建一個二維數組 用來定義繪制棋盤線*/
    var count = 15;//用來定義棋盤的行數和列數
    var map = new Array(count);

    for (var i = 0; i  map.length; i++) {
        map[i] = new Array(count);
        for (var j = 0; j  map[i].length; j++) {
            map[i][j] = 0;
        }
    }

    /*準備工作:3初始化棋子*/
    var black = new Image();
    var white = new Image();
    black.src = "img/black.png";
    white.src = "img/white.png";


    //開始繪制 1繪制棋盤線
    ctx.strokeStyle = "#fff";
    var rectWH = 40; //設置繪制矩形的大小
    for (var i = 0; i  map.length; i++) {
        for (var j = 0; j  map[i].length; j++) {
            ctx.strokeRect(j * rectWH, i * rectWH, rectWH, rectWH);
        }
    }

    // 用來進行黑白子的切換
    var isBlack = true;

 //開始繪制 2下子
 function play(e) {
    //獲取點擊canvas的位置值默認,canvas的左上角為(0,0) 點
    var leftOffset = 20;//body 的margin
    var x = e.clientX - leftOffset;
    var y = e.clientY - leftOffset;
    // console.log(x+" "+y);
    // 設置點擊點后棋子下在哪里,獲取點擊的位置進行判斷如果超過格子的一半則繪制到下一個點如果小于 則繪制在上一個點上
    var xv = (x - rectWH / 2) / rectWH;
    var yv = (y - rectWH / 2) / rectWH;

    var col = parseInt(xv) + 1;
    var row = parseInt(yv) + 1;
    console.log(xv + " " + yv + " , " + col + " " + row);

    //嚴格點需要驗證 ,驗證所輸入的點是否在數組中已經存在 ,如果存在 則返回
    if (map[row][col] != 0) {
        alert("此處已經落子");
        return;
    }

    // 切換繪制黑白子
    if (isBlack) {
        ctx.drawImage(black, col * 40 - 20, row * 40 - 20);
        isBlack = false;
        map[row][col] = 1;

        $.ajax({
            url: "http://127.0.0.1:5000/yes",//請求的url地址
            type: 'post',//設置請求的http方式,method也可以
            dataType: 'json',//將服務器端返回的數據直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉化為js對象),服務器返回的默認格式是text/html格式
            data: {//向服務器端發(fā)送的數據
                t: 1,
                row: row,
                col: col,
                
            },
            success: function (data) {//請求成功之后執(zhí)行的回調函數
                if(data.code===201){
                    alert('黑棋獲勝')
                }else if(data.code===202){
                    alert('白棋獲勝')
                }
                
            },
            error: function(error){
                console.log(error)
            }
        });

        // Yes(1,row,col)

    } else {
        ctx.drawImage(white, col * 40 - 20, row * 40 - 20);
        isBlack = true;
        map[row][col] = 2;
        $.ajax({
            url: "http://127.0.0.1:5000/yes",//請求的url地址
            type: 'post',//設置請求的http方式,method也可以
            dataType: 'json',//將服務器端返回的數據直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉化為js對象),服務器返回的默認格式是text/html格式
            data: {//向服務器端發(fā)送的數據
                t: 2,
                row: row,
                col: col,
              
            },
            success: function (data) {//請求成功之后執(zhí)行的回調函數
                if(data.code===201){
                    alert('黑棋獲勝')
                }else if(data.code===202){
                    alert('白棋獲勝')
                }
                
            },
            error: function(error){
                console.log(error)
            }
        });
        // Yes(2,row,col)
    }


 }

 function replay(){
    $.ajax({
            url: "http://127.0.0.1:5000/replay",//請求的url地址
            type: 'post',//設置請求的http方式,method也可以
            dataType: 'json',//將服務器端返回的數據直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉化為js對象),服務器返回的默認格式是text/html格式
            data: {//向服務器端發(fā)送的數據
                isReplay: true
            },
            success: function (data) {//請求成功之后執(zhí)行的回調函數
                window.location.href = "game.html";                
            },
            error: function(error){
                console.log(error)
            }
        });
 }


 /*功能擴充:
 1當勝利后 彈框:a是否在來一局 b 精彩回復
 a 如果點擊在來一句 清空數據重新開始
 b 精彩回放將棋盤黑白子按照下棋的順序進行棋子編號2悔棋功能
 3對算法的擴充
 a如果是雙三 則直接彈出勝利
 b若是桶四 則直接彈出勝利
 */
/script>
/body>
/html>

登錄頁面

!DOCTYPE html>
html>
head lang="en">
    meta charset="UTF-8">
    meta content="width=device-width, initial-scale=1.0, user-scalable=no" name="viewport">
    title>/title>
    
    style>
        * {
            margin: 0px;
            padding: 0px;
        }

        .title {
            font-size: 20px;
            background-color: cornflowerblue;
            color: #fff;
           /*
            * 里面的文字居中
            */
            line-height: 50px;
            text-align: center;
            /*
             *絕對定位
             */
            position: fixed;
            top: 0px;
            left: 0px;
            width: 100%;
        }

        .content {
            margin-top: 110px;
        }

        .mybutton {
            width: 200px;
            line-height: 40px;
            text-align: center;
            background-color: cornflowerblue;
            margin: 0 auto;
            margin-top: 20px;
            font-size: 20px;
            color: #fff;
        }

        .shurukuang {
            display: block;
            margin: 0 auto;
            width: 200px;
            height: 25px;
            margin-top: 1px;
            border: none;
            border-bottom: 1px solid;
            margin-top: 5px;
            text-indent: 4px;
            outline: none;
        }
    /style>
/head>
body>


div class="title">
    gobang賬戶登錄
/div>

div class="content">
    input id="username" class="shurukuang" type="text" placeholder="手機號" value="yokna">
    input id="password" class="shurukuang" type="password" placeholder="密碼" value="123456">
/div>
div class="mybutton" onclick="myClick()">登錄/div>


script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js">/script>
script>

    // 請求路徑
    var httpurl = "http://127.0.0.1:5000/login";
    // 數據請求
    function myClick() {
        var usernamestr = document.getElementById("username").value;
        var passwordstr = document.getElementById("password").value;
      

        $.ajax({
            url: httpurl,//請求的url地址
            type: 'post',//設置請求的http方式,method也可以
            dataType: 'json',//將服務器端返回的數據直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉化為js對象),服務器返回的默認格式是text/html格式
            data: {//向服務器端發(fā)送的數據
                username: usernamestr,
                password: passwordstr,
            },
            success: function (data) {//請求成功之后執(zhí)行的回調函數
                console.log(data.code);
                if(data.code!==200){
                    alert("用戶名或密碼錯誤")
                }else{
                    window.location.href = "game.html";
                }
                
            },
            error: function(error){
                console.log(error)
            }
        });
    }

/script>

/body>
/html>

歡迎界面

說明:此界面可有可無,對整個游戲沒有影響

!DOCTYPE html>
html lang="en">
head>
    meta charset="UTF-8">
    title>Title/title>
/head>
body>

script type="text/javascript">

    window.onload = function f(){
        var myDate = new Date();
        document.getElementById('currentTime').innerText = myDate.getTime();
    }

    function loadPage(){
        var targetURL = document.querySelector('#url').value;
        console.log(targetURL);
        document.querySelector('#iframePosition').src = targetURL;
    }

/script>


div>
    
        歡迎來玩五子棋:             
        input type="text" id="url" value="http://127.0.0.1:5500/templates/game.html" hidden>
        input type="button" value="開始游戲" onclick="loadPage()">

/div>

div>
    h3>加載頁面的位置/h3>
    iframe style="width: 100%;height: 600px" id="iframePosition">

    /iframe>
/div>

/body>
/html>

至此,前端的頁面就展示完了

下面是后端的內容

后端

配置文件

SQLALCHEMY_DATABASE_URI = "mysql://root:password@localhost:3306/gobang"
# "數據庫://用戶名:密碼@host:port/數據庫名稱"

SQLALCHEMY_TRACK_MODIFICATIONS = False
# 這一行不加會有警告

啟動類

# -*- coding:utf-8 -*-

#1.導入flask擴展
# 2.創(chuàng)建flask應用程序實例
# 3.定義路由及視圖函數
# 4.啟動程序
from flask import Flask, render_template, request
from flask_cors import  *
import pymysql
pymysql.install_as_MySQLdb()
from flask_sqlalchemy import SQLAlchemy
import config

#需要傳入__name__ 為了確定資源所在路徑
app = Flask(__name__)
CORS(app, supports_credentials=True)
app.config.from_object(config)
db = SQLAlchemy(app)
global map
map = [[0 for i in range(15)] for j in range(15)]
# #flask中定義路由是通過裝飾器來實現的,訪問路由會自動調用路由下跟的方法,并將執(zhí)行結果返回


@app.route('/login',methods=["GET","POST"])
def login():
    if request.method == "POST":
        # 以POST方式傳參數,通過form取值
        # 如果Key之不存在,報錯KeyError,返回400的頁面
        username = request.form['username']
        password = request.form['password']
        user = queryUser(username,password)
        if len(user) > 0:
            return {"code": 200, "msg": "成功"}
        else:
            return {"code": 400, "msg": "驗證失敗"}
            println('驗證失敗')
        print(username+password)
    else:
        # 以GET方式傳參數,通過args取值
        username = request.args['username']
        print(username)
    return {"code": 200,"msg":"成功"}

class User(db.Model):
    __tablename__ = 'user'
    username = db.Column(db.String(255))
    password = db.Column(db.String(255))
    id = db.Column(db.Integer,primary_key=True)


def index():
    user = User(username='你好你好',password='456456')
    #調用添加方法
    db.session.add(user)
    #提交入庫,上面已經導入了提交配置,所以不需要在提交了
    db.session.commit()
    return '這是首頁'


def queryUser(username,password):
    user = User.query.filter_by(username=username,password=password).all()
    db.session.commit()
    return user

@app.route('/replay',methods=["POST"])
def replay():
    global map
    map = [[0 for i in range(15)] for j in range(15)]
    return {"code": 200,"msg":"成功"}


@app.route('/yes',methods=["POST"])
def yes():
    print('this is yes ')
    t = int(request.form['t'])
    print(t)
    tmprow = request.form['row']
    print(tmprow)
    tmpcol = request.form['col']
    print(tmpcol)
    row = int(tmprow)
    col = int(tmpcol)
    total = 1

    map[int(row)][int(col)] = t
    chessboard = map
    print(chessboard)
    print('this is yes ')
    print(t)
    print(tmprow)
    print(tmpcol)
    #不寫注釋真容易看混,本少俠就勉強寫一點吧
    #這里是要判斷水平方向上是否滿足獲勝條件
    while col - 1 > 0 and chessboard[row][col - 1] == t:
        total = total + 1
        col = col - 1

    row = int(tmprow)
    col = int(tmpcol)
    while col + 1  15 and chessboard[row][col + 1] == t:
        total = total + 1
        col = col + 1
    
    if total >= 5:
        if t == 1:
            return {"code": 201, "msg": "黑棋獲勝"}
        else:
            return {"code": 202, "msg": "白棋獲勝"}

    #判斷垂直方向上是否滿足獲勝條件
    row = int(tmprow)
    col = int(tmpcol)
    while row - 1 > 0 and chessboard[row - 1][col] == t:
        total = total + 1
        row = row - 1

    row = int(tmprow)
    col = int(tmpcol)
    while row + 1  15 and chessboard[row + 1][col] == t:
        total = total + 1
        row = row + 1
    
    if total >= 5:
        if t == 1:
            return {"code": 201, "msg": "黑棋獲勝"}
        else:
            return {"code": 202, "msg": "白棋獲勝"}

    
    #判斷pie上是否滿足獲勝條件
    row = int(tmprow)
    col = int(tmpcol)
    while row - 1 > 0 and col + 1  15 and chessboard[row - 1][col + 1] == t:
        total = total + 1
        row = row - 1
        col = col + 1

    row = int(tmprow)
    col = int(tmpcol)
    while row + 1  15 and col - 1 > 0 and chessboard[row + 1][col - 1] == t:
        total = total + 1
        row = row + 1
        col = col - 1
    
    if total >= 5:
        if t == 1:
            return {"code": 201, "msg": "黑棋獲勝"}
        else:
            return {"code": 202, "msg": "白棋獲勝"}


    #判斷na上是否滿足獲勝條件
    row = int(tmprow)
    col = int(tmpcol)
    while row - 1 > 0 and col - 1 > 0 and chessboard[row - 1][col - 1] == t:
        total = total + 1
        row = row - 1
        col = col - 1

    row = int(tmprow)
    col = int(tmpcol)
    while row + 1  15 and col + 1  15 and chessboard[row + 1][col + 1] == t:
        total = total + 1
        row = row + 1
        col = col + 1
    
    if total >= 5:
        if t == 1:
            return {"code": 201, "msg": "黑棋獲勝"}
        else:
            return {"code": 202, "msg": "白棋獲勝"}

    return {"code": 203, "msg": "繼續(xù)"}
           

   

#會運行起一個小型服務器,就會將我們的flask程序運行在一個簡單的服務器上,服務器由flask提供,用于測試

if __name__ == '__main__':
 app.run()

數據庫表

SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `username` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL,
  `password` varchar(255) NOT NULL,
  `id` int(16) NOT NULL AUTO_INCREMENT,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('yokna', '123456', '1');
INSERT INTO `user` VALUES ('你好你好', '456456', '2');
INSERT INTO `user` VALUES ('你好你好', '456456', '3');
INSERT INTO `user` VALUES ('orange', '123456', '4');

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

您可能感興趣的文章:
  • python版本五子棋的實現代碼
  • python實現五子棋小游戲
  • python pygame實現五子棋小游戲
  • python實現簡單五子棋游戲
  • python實現五子棋小程序
  • 使用python實現簡單五子棋游戲
  • python實現五子棋游戲
  • python實現五子棋游戲(pygame版)
  • python使用minimax算法實現五子棋
  • python五子棋游戲的設計與實現

標簽:長沙 濟南 海南 山西 山西 崇左 安康 喀什

巨人網絡通訊聲明:本文標題《基于flask實現五子棋小游戲》,本文關鍵詞  ;如發(fā)現本文內容存在版權問題,煩請?zhí)峁┫嚓P信息告之我們,我們將及時溝通與處理。本站內容系統(tǒng)采集于網絡,涉及言論、版權與本站無關。
  • 相關文章
  • 收縮
    • 微信客服
    • 微信二維碼
    • 電話咨詢

    • 400-1100-266
    丹巴县| 翁牛特旗| 甘肃省| 满洲里市| 哈巴河县| 福海县| 荔波县| 定远县| 响水县| 屏东市| 崇义县| 福海县| 崇明县| 铁岭市| 民县| 明星| 新安县| 元阳县| 延庆县| 浙江省| 周宁县| 都匀市| 怀集县| 枣庄市| 克山县| 丰城市| 响水县| 托克托县| 察隅县| 益阳市| 高唐县| 克拉玛依市| 吴桥县| 楚雄市| 惠州市| 高平市| 黄冈市| 旺苍县| 惠水县| 乌鲁木齐市| 桐城市|