基于flask实现五子棋小游戏

本文实例为大家分享了基于flask实现五子棋小游戏的具体代码,供大家参考,具体内容如下

前言

首先说明一下,本人方向是java后端,只因老师布置了一个作业,要用flask来做一个五子棋,没办法被逼上梁山,程序不太美观,但是应付作业还是够了的。

废话不多说,下面开锤!

首先整个程序是一个web应用,前端html+css+javaScript(有用到jquery)(基本都是现学的,所以程序很多注释也很丑),后端用的flask框架。

准备工作

**1.**python环境、安装flask

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

pip install flask_cors
pip install flask_sqlalchemy

**3.**创建一个flask项目,并将一下代码复制运行

文件结构

图片资源

不做代码的生产者,只做代码的搬运工

前端

游戏页面




        
        五子棋
 



            
        
        

登录页面




    
    
    
    
    




gobang账户登录
登录

欢迎界面

说明:此界面可有可无,对整个游戏没有影响




    
    Title






欢迎来玩五子棋:

加载页面的位置

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

下面是后端的内容

后端

配置文件

SQLALCHEMY_DATABASE_URI = "mysql://root:password@localhost:3306/gobang"
# "数据库://用户名:密码@host:port/数据库名称"

SQLALCHEMY_TRACK_MODIFICATIONS = False
# 这一行不加会有警告

启动类

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

#1.导入flask扩展
# 2.创建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中定义路由是通过装饰器来实现的,访问路由会自动调用路由下跟的方法,并将执行结果返回


@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": "继续"}
           

   

#会运行起一个小型服务器,就会将我们的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');

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

你可能感兴趣的:(基于flask实现五子棋小游戏)