3.猜拳游戏:石头、剪刀、布的游戏
##不用render_template函数,把html代码放在py文件里,不用单独写html文件
from flask import Flask, request
import randomapp = Flask(__name__)@app.route('/')
def index():#下面form标签虽然放在注释里,但是是可以读取的html内容return '''<form method="POST" action="/play"><label>出拳输入:1石头,2剪刀,3布:</label><input type="text" name="user_input"><input type="submit" value="提交"></form>'''@app.route('/play', methods=['POST'])
def play():computer = random.randint(1, 3)user_input = request.form['user_input']#直接从form标签下 input里拿值try:n = int(user_input)if n == computer:return f'平局,对方{computer}'elif (n == 1 and computer == 2) or (n == 2 and computer == 3) or (n == 3 and computer == 1):return f'你赢了!!,对方{computer}'elif n >= 4:return f'请出123石头剪刀布!!,对方{computer}'elif user_input == '':return '请出拳!'elif n == 0:return '游戏结束!!'else:return f'你输了!!,对方{computer}'except ValueError:return '请重新输入123或输入0退出:'if __name__ == '__main__':app.run()