3.猜拳游戏:石头、剪刀、布的游戏
##不用render_template函数,把html代码放在py文件里,不用单独写html文件
from flask import Flask, request
import random
app = 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()
html文件单独拿出来是这样的:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Rock Paper Scissors</title>
</head>
<body>
<form method="POST" action="/play">
<label>输入:1石头,2剪刀,3布:</label>
<input type="text" name="user_input">
<input type="submit" value="提交">
</form>
</body>
</html>
caiquan2.py
#方法二
from flask import Flask, render_template, request
import random
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
#return '123333'
@app.route('/play', methods=['POST','GET'])
def play():
computer = random.randint(1, 3)
#user_input = request.form['user_input']
user_input = request.form.get('user_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()