Single_Player_Chess/main.py

55 lines
1.5 KiB
Python
Raw Normal View History

2019-09-10 22:29:59 +02:00
from bottle import template, get, run, post, request, redirect, response
2019-09-10 22:01:20 +02:00
from chess import Game
2019-09-10 22:29:59 +02:00
KEY = "abcdefgh"
2019-09-11 01:14:34 +02:00
TEMPLATE = "template.tpl"
2019-09-10 22:01:20 +02:00
games = dict()
def is_submitted(name):
2019-09-10 23:33:28 +02:00
"""Return True if form element with name was submitted."""
2019-09-10 22:01:20 +02:00
return request.forms.get(name) != None
@get("/")
def index():
2019-09-10 23:33:28 +02:00
"""Drop cookie if it doesn't exist. Redirect to /game/."""
2019-09-10 22:29:59 +02:00
if request.get_cookie("gameid", secret=KEY) not in games.keys():
game = Game()
id = str(max(list(map(int, games.keys()))+[0]) + 1)
games[id] = game
response.set_cookie("gameid", id, path='/', secret=KEY)
redirect("/game/")
@get("/game/")
def show():
2019-09-10 23:33:28 +02:00
"""Show board. Redirect to index if id given by cookie not in games."""
2019-09-10 22:29:59 +02:00
id = request.get_cookie("gameid", secret=KEY)
if id not in games:
redirect("/")
2019-09-10 22:01:20 +02:00
return template(TEMPLATE, game=games[id], valid=True)
2019-09-10 22:29:59 +02:00
@post("/game/")
def move():
2019-09-10 23:33:28 +02:00
"""Catch form submissions and manipulate the game instance."""
2019-09-10 22:29:59 +02:00
id = request.get_cookie("gameid", secret=KEY)
2019-09-10 22:01:20 +02:00
valid = True
if is_submitted("newgame"):
2019-09-11 01:10:53 +02:00
del games[id]
2019-09-10 22:01:20 +02:00
redirect("/")
if is_submitted("prev"):
games[id].prev()
elif is_submitted("first"):
games[id].first()
elif is_submitted("next"):
games[id].next()
elif is_submitted("last"):
games[id].last()
else:
AN = request.forms.get("move")
valid = games[id].AN_move(AN)
return template(TEMPLATE, game=games[id], valid=valid)
run(host="localhost", port=8080)