首页 > 解决方案 > 如何在 HTML 页面上呈现 Python 猜数字游戏

问题描述

我刚刚从一本名为 Automate the Boring Stuff With Python 的书中学会了猜数字游戏(代码如下)。我让它使用终端工作,但我想知道如何设置它以在 html 页面上呈现。理想情况下,我现在想使用 Flask 并在本地渲染 html 页面。

import random

correct = random.randint(1,20)

print('I am thinking of a number between 1 and 20.')

for guessesTaken in range(1,6):
    print('Take a guess.')
    guess = int(input())

    if guess < correct:
        print('Your number is too low')

    elif guess > correct:
        print('Your number is too high')
    else:
        break

if guess == correct:
    print('Good work! You got the number in '+ str(guessesTaken)+ ' guesses')
else:
    print('Nope. The number I was thinking of was ' + str(correct))

标签: pythonhtml

解决方案


创建一个文件夹,其中包含 1 个名为 app.py 的文件和 1 个名为 templates 的文件夹,其中包含 a.html

1) 应用程序.py

from flask import Flask
from flask import request
from flask import render_template
import random

correct = random.randint(1,20)
count=0
app = Flask(__name__)

@app.route('/new')
def my_form():
    return render_template("a.html") # this should be the name of your html file

@app.route('/new', methods=['POST'])
def my_form_post():
    global correct
    global count
    msg = ''
    print(count)
    if count<6:
        count+=1
        text1 = request.form['text1']
        text1 = int(text1)

        if text1 < correct:
            msg = 'Your number is too low'
            return render_template("a.html", msg=msg)
        elif text1 > correct:
            msg = 'Your number is too high'
            return render_template("a.html", msg=msg)
        else:
            if text1 == correct:
                msg = 'Good work! You got the number in '+ str(count)+ ' guesses'
                count = 0
                correct = random.randint(1,20)
                return render_template("a.html", msg=msg)
    else:
        num = 'Nope. The number I was thinking of was ' + str(correct)
        correct = random.randint(1,20)
        msg = ''
        count=0
        return render_template("a.html", num=num)

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

2)一个.html

<!DOCTYPE html>
<html lang="en">
<body>
    <h1>I am thinking of a number between 1 and 20.</h1>
    <form action="/new" method="POST">
        <input type="text" name="text1">
        <input type="submit" name="my-form" value="Check !">
    </form>
    <h1>{{ msg }}</h1>
    <h1>{{ num }}</h1>
</body>
</html>


推荐阅读