3

I have a simple game about hanoi towers that currently works in terminal. It allows the player to input his turn in terminal and outputs a visualization to terminal.

My task is to make a flask app that will open an html page where a JS script would poll the server for info about the game and double the visualization from terminal to the web page.

My problem is that both the game and flask have a main loop and if I run them sequently they won't work parallel.

So I need the game to run in terminal and the player to make turns in terminal, but I need the web server to get the game state and display it.

My question: what should I use for this? Threads of multiprocessing?

Say I have a flask view

from game import game

@app.route('/get_updates')
def get_updates():
   return flask.jsonify(game.instance().board)

How is it gonna work if flask and the game are running in separate threads? How can I get the game object from another thread?

qvpham
  • 1,896
  • 9
  • 17
Euphe
  • 3,531
  • 6
  • 39
  • 69
  • You could start another thread and run Flask server in it, not that difficult. – laike9m Apr 14 '16 at 08:45
  • check this http://stackoverflow.com/questions/14384739/how-can-i-add-a-background-thread-to-flask – Sepehr Hamzehlooy Apr 14 '16 at 08:47
  • 1
    multi-threading is the simplest solution. You can share variables, objects between separate threads. You give the game object as parameter for the constructor of your flask thread – qvpham Apr 14 '16 at 09:03

2 Answers2

11

May be its better to run your game in s different thread?

import threading
import time
from flask import Flask, render_template

class myGame(threading.Thread):
    def __init__(self, threadID, name, counter):
        threading.Thread.__init__(self)
        self.board = 1

    def run(self):
        pass


app = Flask(__name__)
game = myGame()

@app.route('/get_updates') 
def get_updates(): 
    return flask.jsonify(game.board)

if __name__ == "__main__":
    game.start()
    app.run(port=81, host='0.0.0.0', debug=False, use_reloader=False)
Alexey Smirnov
  • 2,573
  • 14
  • 20
0

Just start another thread and run Flask server in it.

laike9m
  • 18,344
  • 20
  • 107
  • 140