您好,登錄后才能下訂單哦!
這篇文章主要介紹了flask如何實現(xiàn)五子棋小游戲,具有一定借鑒價值,感興趣的朋友可以參考下,希望大家閱讀完這篇文章之后大有收獲,下面讓小編帶著大家一起了解一下。
**1.**python環(huán)境、安裝flask
**2.**導入需要用到的包
pip install flask_cors pip install flask_sqlalchemy
**3.**創(chuàng)建一個flask項目,并將一下代碼復制運行
圖片資源
不做代碼的生產(chǎn)者,只做代碼的搬運工
游戲頁面
<!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)建一個二維數(shù)組 用來定義繪制棋盤線*/ var count = 15;//用來定義棋盤的行數(shù)和列數(shù) 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); //嚴格點需要驗證 ,驗證所輸入的點是否在數(shù)組中已經(jīng)存在 ,如果存在 則返回 if (map[row][col] != 0) { alert("此處已經(jīng)落子"); 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',//將服務器端返回的數(shù)據(jù)直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉(zhuǎn)化為js對象),服務器返回的默認格式是text/html格式 data: {//向服務器端發(fā)送的數(shù)據(jù) t: 1, row: row, col: col, }, success: function (data) {//請求成功之后執(zhí)行的回調(diào)函數(shù) 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',//將服務器端返回的數(shù)據(jù)直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉(zhuǎn)化為js對象),服務器返回的默認格式是text/html格式 data: {//向服務器端發(fā)送的數(shù)據(jù) t: 2, row: row, col: col, }, success: function (data) {//請求成功之后執(zhí)行的回調(diào)函數(shù) 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',//將服務器端返回的數(shù)據(jù)直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉(zhuǎn)化為js對象),服務器返回的默認格式是text/html格式 data: {//向服務器端發(fā)送的數(shù)據(jù) isReplay: true }, success: function (data) {//請求成功之后執(zhí)行的回調(diào)函數(shù) window.location.href = "game.html"; }, error: function(error){ console.log(error) } }); } /*功能擴充: 1當勝利后 彈框:a是否在來一局 b 精彩回復 a 如果點擊在來一句 清空數(shù)據(jù)重新開始 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"; // 數(shù)據(jù)請求 function myClick() { var usernamestr = document.getElementById("username").value; var passwordstr = document.getElementById("password").value; $.ajax({ url: httpurl,//請求的url地址 type: 'post',//設置請求的http方式,method也可以 dataType: 'json',//將服務器端返回的數(shù)據(jù)直接認定為是這個格式,然后會做一些自動的處理(如果是json字符串,會自動轉(zhuǎn)化為js對象),服務器返回的默認格式是text/html格式 data: {//向服務器端發(fā)送的數(shù)據(jù) username: usernamestr, password: passwordstr, }, success: function (data) {//請求成功之后執(zhí)行的回調(diào)函數(shù) 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> <h4>加載頁面的位置</h4> <iframe id="iframePosition"> </iframe> </div> </body> </html>
至此,前端的頁面就展示完了
下面是后端的內(nèi)容
配置文件
SQLALCHEMY_DATABASE_URI = "mysql://root:password@localhost:3306/gobang" # "數(shù)據(jù)庫://用戶名:密碼@host:port/數(shù)據(jù)庫名稱" SQLALCHEMY_TRACK_MODIFICATIONS = False # 這一行不加會有警告
啟動類
# -*- coding:utf-8 -*- #1.導入flask擴展 # 2.創(chuàng)建flask應用程序?qū)嵗? # 3.定義路由及視圖函數(shù) # 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中定義路由是通過裝飾器來實現(xiàn)的,訪問路由會自動調(diào)用路由下跟的方法,并將執(zhí)行結果返回 @app.route('/login',methods=["GET","POST"]) def login(): if request.method == "POST": # 以POST方式傳參數(shù),通過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方式傳參數(shù),通過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') #調(diào)用添加方法 db.session.add(user) #提交入庫,上面已經(jīng)導入了提交配置,所以不需要在提交了 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()
數(shù)據(jù)庫表
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');
感謝你能夠認真閱讀完這篇文章,希望小編分享的“flask如何實現(xiàn)五子棋小游戲”這篇文章對大家有幫助,同時也希望大家多多支持億速云,關注億速云行業(yè)資訊頻道,更多相關知識等著你來學習!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。