I use Python and Flask to display a randomized playing field and try to allow people to return to the same game using seed.
However, regardless of whether I use random seed or specify a seed, I seem to get the same pseudorandom sequences.
I cut out most of my code (I do a lot of splitting and connecting with numpy), but even the simple code below shows an error: no matter what seed value I give to the form, the number displayed on submit is the same. Submitting a form without specifying a seed shows a different number, but despite displaying different seeding values ββon reboot, this other number is always the same.
Am I doing something wrong with sowing?
from flask import Flask, request, render_template import numpy as np import random app = Flask(__name__) @app.route( '/' ) def single_page(): return render_template( 'page.html', title = 'empty form' ) @app.route( '/number', methods = [ 'POST', 'GET' ] ) def render_page( title = 'generated random number', error = [] ): error = [] if request.method == 'POST': if request.form['seed'].isdigit(): seed = int( request.form['seed'] ) error.append( "seed set: " + str( seed ) + "." ) np.random.seed( seed/100000 ) else: seed = int( 100000 * random.random() ) error.append( "seed not set, " + str( seed ) + " instead." ) np.random.seed( seed/100000 ) n = np.random.random() * 100; return render_template('page.html', title=title, error=error, n=n, seed=seed ) else: return render_template( 'page.html', title = 'empty form' ) if __name__ == '__main__': app.debug = True app.run()
Here is the HTML flash drive template
<!doctype html> <html> <head><title>{{title}}</title> </head> <body> {% if error != '' %} {% for message in error %} <h2>{{message}}</h2> {% endfor %} {% endif %} {% if n %} <h2>Random number is {{n}}</h2> <h6>seed = {{ seed }}</h6> {% else %} <div id="form"> <form id="the_form" method="POST" action="number"> Seed: <input type="number" min="1" max="99999" id="seed" name="seed"><br> <button id="submit" type="submit">Submit</button> </form> {% endif %} </div> </body> </html>
I multiply and divide the seeds by 100,000 to give a more memorable value (say, 4231 instead of 4.231479094 ...). Is there a better way to have a useful integer value for seeds?
UPDATED: Yes, there is a better way to do integer seed values ββ- don't confuse division at all. So far this is what I am doing:
import numpy as np import random . . . if request.form['seed'].isdigit(): seed = int( request.form['seed'] ) error.append( "seed set: " + str( seed ) + "." ) random.seed( seed ) else: seed = int( 100000 * np.random.random() ) error.append( "seed not set, " + str( seed ) + " instead." ) random.seed( seed ) n = random.random() * 100; return render_template('page.html', title=title, error=error, n=n, seed=seed )
It works great. np.random.seed () doesn't seem to always get the same sequence, but random.seed () doesn't mind an integer, so I use the latter.