How do I reset the Flask server using if within the algorithm?

Asked

Viewed 119 times

0

Next, I am creating a game in order to learn, however, I need this game to "reset" when the amount of attempts is reached. At the beginning of the code I have the following:

from random import randint
number = (randint(1, 100))

It generates the random value so that the user tries to hit it. The user has 10 chances to hit, however, at the moment, after the 10 attempts the game continues to have as reference the same value "number"

This "game" runs on the flask server with a front in HTML, I would like to know how I do so that arriving in 10 attempts it gives a "reset" on the server, thus generating a new number for a new game.

Follow the server code:

#       // Function import for use make_response for cookies
from flask import Flask, make_response
#       //Function import request in directory static local server
from flask import Flask, request, send_from_directory
#       //Function that uploads files to the local server at http://localhost:5000/index.html
from flask import Flask, request
app = Flask(__name__, static_url_path="", static_folder="static")
#       //Function to generate a random integer value in the variable number
from random import randint
number = (randint(1, 100))
print(number)
#       //Route function to receive the POST of the guess form
@app.route('/adivinhar', methods=['POST'])
def adivinhar():
#       //Reference number of html for variable N for comparison purposes   
    n = int(request.form.get('number'))
#       //Guard clause for cookie not defined    
    if  request.cookies.get('attemp'):
#       //Transform cookie string in interger for var a      
        a = request.cookies.get('attemp')
        a = int(a)
    else:
        a = 0
#       //the print(a) will shit if there is no cookie
#       //RETURN FOR LOSE

3 answers

1

Can you do this using a class, if it is the most suitable and most recommended way? Probably not.

Generally Apis are built to be stateless, meaning they don’t keep the "status" of the information that goes through it.

from flask import Flask
from random import randint

class Adivinhar:
      def __init__(self):
            self.number = (randint(1, 100))
            self.cont = 0

      def check(self, n):
            state = True if (str(self.number) == str(n)) else False
            self.number = (randint(5, 10)) if(self.cont >= 10) else self.number
            self.cont = 0 if(self.cont >= 10) else (self.cont + 1)
            return { 'num': self.number, 'cont': self.cont, 'acertou?': state}

adivinhar= Adivinhar()
app = Flask(__name__)

@app.route('/teste/<n>', methods=['GET'])
def teste(n):
      return str(adivinhar.check(n))

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

@Edit

I don’t know what kind of application you’re building, but if you’re going to use an API, a recommendation is to use the library Flask-Restful (pip install Flask-Restful).

Resource.py

from flask_restful import Resource
class MyClass(Resource):
      def __init__(self):
            #do something...
            pass
      
      def get(self, *args):
            #do something...
            pass

      def post(self, *args):
            #do something
            pass

app py.


from flask import Flask
from flask_restful import Api
from .resource import MyClass

app = Flask(__name__)
api = Api(app)

api.add_resource(MyClass, '/nome_da_rota_que_quero')

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

If you make a GET request for the route '/name_caly_caly_wish', it will access what is inside the GET method/function, and so for the other requests.

  • The idea is not to use any application and not to use JS, thanks for the tip.

0

A game often relies on reading user input and reacts to it very quickly. Within game development there is a pattern that resolves this problem called game loop [²]. A game loop is literally a loop made with a repeating structure that only ends when the user reaches his goal.

flask works differently. It works on user feedback but not as imperative as a game loop does.

What I advise you is to implement the structure of a gameloop in your frontend and use flask only to validate whether the user is correct.

You could create this structure with pure javascript by making ajax requests for flask or opt for a framework for this kind of thing like Canvas.

  • I think you confused the name of the theory, see Game theory is not about video games.

  • Well noted @Augustovasques, I even confused, already edited my answer.

  • Hello, dear, thank you for the explanation, I will try to take another approach, but first, I will try to use a different route direction to reset cookies and reset 'NUMBER'. I’ll search for Canvas.

-1

Good afternoon, I managed to solve the problem by performing a route redirection, was created a route, when the POST hits the "lost", it sends me to another page, in this another page I zero cookies and run Random. I appreciate the help. Follow the code:

# -- generating random number -- # 
from random import randint 
number = (randint(1, 100))
print(number)

# -- Defining "lost" route in POST -- #
@app.route('/perdeu', methods=['POST'])
def perdeu():
    number = (randint(1, 100))
    print(number)
    m = str(request.form.get('reset'))
    res = make_response(app.send_static_file('index.html'))
    res.set_cookie('attemp', '1')
    return res

# -- Defining "adivinhar" route in POST -- #
@app.route('/adivinhar', methods=['POST'])
def adivinhar():
# -- Reference number of html for variable N for comparison purposes -- #

Browser other questions tagged

You are not signed in. Login or sign up in order to post.