aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorlonkaars <l.leblansch@gmail.com>2021-02-20 13:03:04 +0100
committerlonkaars <l.leblansch@gmail.com>2021-02-20 13:03:04 +0100
commite1978a9b80f3f7f5a36ca4af5f6df62f494a0d6d (patch)
tree27b2a142ad1c267f002e7c7e09ea337e4da688ac
parent16044fbf61b06f4d53e2ffcab67569721b3792e2 (diff)
/game/random endpoint
-rw-r--r--api/game/new.py2
-rw-r--r--api/game/random.py31
-rw-r--r--api/game/voerbak_connector.py6
-rw-r--r--api/main.py2
-rwxr-xr-xapi/tests.sh125
-rw-r--r--components/voerBord.tsx3
-rw-r--r--database/init_db.sql1
-rw-r--r--pages/game.tsx50
8 files changed, 155 insertions, 65 deletions
diff --git a/api/game/new.py b/api/game/new.py
index fd65019..1b63110 100644
--- a/api/game/new.py
+++ b/api/game/new.py
@@ -19,7 +19,7 @@ def index():
game_id = new_uuid("games")
timestamp = int( time.time() * 1000 )
- cursor.execute("insert into games values (?, NULL, NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, \"wait_for_opponent\", ?) ", (game_id, user_id, timestamp, json.dumps(game_settings)))
+ cursor.execute("insert into games values (?, NULL, NULL, ?, NULL, NULL, ?, NULL, NULL, NULL, \"wait_for_opponent\", ?, TRUE) ", (game_id, user_id, timestamp, json.dumps(game_settings)))
connection.commit()
return { "id": game_id }, 200
diff --git a/api/game/random.py b/api/game/random.py
new file mode 100644
index 0000000..bbddedc
--- /dev/null
+++ b/api/game/random.py
@@ -0,0 +1,31 @@
+from flask import Blueprint, request, make_response
+from db import cursor, connection
+from randid import new_uuid
+import time
+import json
+import random
+
+random_game = Blueprint('random', __name__)
+
+@random_game.route('/random', methods = ['POST'])
+def index():
+ data = request.get_json()
+
+ user_id = data.get("user_id") or ""
+ if not user_id:
+ print("a temporary user should be set up here")
+
+ public_games = cursor.execute("select game_id from games where private = FALSE and status = \"wait_for_opponent\"").fetchall()
+ print(public_games)
+ if len(public_games) == 0:
+ game_id = new_uuid("games")
+
+ cursor.execute("insert into games values (?, NULL, NULL, ?, NULL, NULL, 0, NULL, NULL, NULL, \"wait_for_opponent\", \"default\", FALSE) ", (game_id, user_id))
+ connection.commit()
+ else:
+ game_id = random.choice(public_games)[0]
+ timestamp = int( time.time() * 1000 )
+ cursor.execute("update games set player_2_id = ?, status = \"in_progress\", timestamp = ? where game_id = ?", (user_id, timestamp, game_id))
+ connection.commit()
+
+ return { "id": game_id }, 200
diff --git a/api/game/voerbak_connector.py b/api/game/voerbak_connector.py
index 5ccaed8..65551ca 100644
--- a/api/game/voerbak_connector.py
+++ b/api/game/voerbak_connector.py
@@ -32,12 +32,17 @@ class bord:
def get_output(self):
return self.process.stdout.readline().decode()[:-1]
+ def kill_voerbak(self):
+ self.process.stdin.write(bytearray("0", "utf-8"))
+ self.process.stdin.flush()
+
def update_board(self):
buffer = self.get_output()
while not buffer.isdigit():
if buffer.startswith("w:"):
self.win_positions.append(buffer[2:].split("-"))
log.info(f"won: {buffer[2:].split('-')}")
+ self.kill_voerbak()
elif buffer.startswith("e:"):
log.warning(buffer[2:])
elif buffer.startswith("m:"):
@@ -45,6 +50,7 @@ class bord:
self.player_1 = True if substr == "true" else False
elif buffer.startswith("d:"):
self.board_full = True
+ self.kill_voerbak()
buffer = self.get_output()
self.board = buffer
diff --git a/api/main.py b/api/main.py
index 5588138..052a6eb 100644
--- a/api/main.py
+++ b/api/main.py
@@ -9,6 +9,7 @@ from auth.signup import signup
from auth.login import login
from auth.login_token import token
from game.new import new_game
+from game.random import random_game
from game.socket import run
app.register_blueprint(status, url_prefix='/')
@@ -17,5 +18,6 @@ app.register_blueprint(signup, url_prefix='/auth')
app.register_blueprint(login, url_prefix='/auth')
app.register_blueprint(token, url_prefix='/auth')
app.register_blueprint(new_game, url_prefix='/game')
+app.register_blueprint(random_game, url_prefix='/game')
if __name__ == "__main__": run(app)
diff --git a/api/tests.sh b/api/tests.sh
index 1b2b216..ce30af3 100755
--- a/api/tests.sh
+++ b/api/tests.sh
@@ -1,48 +1,48 @@
#!/bin/sh
-username="test_$RANDOM"
-email="$username@example.com"
-password=$(echo $RANDOM | base64)
+# username="test_$RANDOM"
+# email="$username@example.com"
+# password=$(echo $RANDOM | base64)
-signup () {
- curl -X POST \
- -H "Content-Type: application/json" \
- -d "{
- \"username\": \"$username\",
- \"email\": \"$email\",
- \"password\": \"$password\"
- }" \
- localhost:5000/api/auth/signup
-}
+# signup () {
+# curl -X POST \
+# -H "Content-Type: application/json" \
+# -d "{
+# \"username\": \"$username\",
+# \"email\": \"$email\",
+# \"password\": \"$password\"
+# }" \
+# localhost:5000/api/auth/signup
+# }
-login_username () {
- curl -X POST \
- -H "Content-Type: application/json" \
- -d "{
- \"email\": \"$username\",
- \"password\": \"$password\"
- }" \
- localhost:5000/api/auth/login
-}
+# login_username () {
+# curl -X POST \
+# -H "Content-Type: application/json" \
+# -d "{
+# \"email\": \"$username\",
+# \"password\": \"$password\"
+# }" \
+# localhost:5000/api/auth/login
+# }
-login_email () {
- curl -X POST \
- -H "Content-Type: application/json" \
- -d "{
- \"email\": \"$email\",
- \"password\": \"$password\"
- }" \
- localhost:5000/api/auth/login
-}
+# login_email () {
+# curl -X POST \
+# -H "Content-Type: application/json" \
+# -d "{
+# \"email\": \"$email\",
+# \"password\": \"$password\"
+# }" \
+# localhost:5000/api/auth/login
+# }
-user_info () {
- curl -X GET \
- -H "Content-Type: application/json" \
- -d '{
- "username": "loekaars"
- }' \
- localhost:5000/user/info
-}
+# user_info () {
+# curl -X GET \
+# -H "Content-Type: application/json" \
+# -d '{
+# "username": "loekaars"
+# }' \
+# localhost:5000/user/info
+# }
# login_token () {
# curl -X POST \
@@ -54,23 +54,40 @@ user_info () {
# localhost:5000/api/auth/token
# }
-new_game () {
+# new_game () {
+# curl -X POST \
+# -H "Content-Type: application/json" \
+# -d '{
+# "user_id": "4577c119-c768-4ad5-afec-b53a5c19baf4",
+# "settings": {
+# "ranked": true,
+# "timelimit": {
+# "minutes": 5,
+# "seconds": 30,
+# "enabled": true,
+# "shared": "false"
+# }
+# }
+# }' \
+# localhost:5000/game/new
+# }
+
+random_game_1 () {
+ curl -X POST \
+ -H "Content-Type: application/json" \
+ -d '{ "user_id": "e6162c82-3e60-4479-ac96-a1af508e49c4" }' \
+ localhost:2080/api/game/random
+}
+
+random_game_2 () {
curl -X POST \
-H "Content-Type: application/json" \
- -d '{
- "user_id": "4577c119-c768-4ad5-afec-b53a5c19baf4",
- "settings": {
- "ranked": true,
- "timelimit": {
- "minutes": 5,
- "seconds": 30,
- "enabled": true,
- "shared": "false"
- }
- }
- }' \
- localhost:5000/game/new
+ -d '{ "user_id": "de960155-7d58-46b3-a4f6-7d33aa034ad9" }' \
+ localhost:2080/api/game/random
}
-new_game
+sleep 3
+random_game_1
+sleep 10
+random_game_2
diff --git a/components/voerBord.tsx b/components/voerBord.tsx
index 74db65d..8ee758b 100644
--- a/components/voerBord.tsx
+++ b/components/voerBord.tsx
@@ -11,6 +11,7 @@ export function VoerBord(props: {
width: number;
height: number;
onMove: (move: number) => void;
+ active: boolean;
}) {
return <table className="voerBord" style={{
borderSpacing: 8,
@@ -37,7 +38,7 @@ export function VoerBord(props: {
borderRadius: 6,
border: "2px solid var(--background-alt)",
opacity: .5,
- cursor: "pointer"
+ cursor: props.active ? "pointer" : "default"
}} id={`pos-${(props.height - row - 1) * props.width + column}`} onClick={event => {
props.onMove(Number((event.target as HTMLElement).id.split("-")[1]))
}}/>
diff --git a/database/init_db.sql b/database/init_db.sql
index 6e47853..5b9e0a7 100644
--- a/database/init_db.sql
+++ b/database/init_db.sql
@@ -29,6 +29,7 @@ create table if not exists games (
rating_delta_player_2 integer,
status text not null,
ruleset text not null,
+ private boolean not null,
foreign key(player_1_id) references users(user_id),
foreign key(player_2_id) references users(user_id)
);
diff --git a/pages/game.tsx b/pages/game.tsx
index 57eca5e..5f610f8 100644
--- a/pages/game.tsx
+++ b/pages/game.tsx
@@ -98,7 +98,7 @@ class VoerGame extends Component<VoerGameProps> {
maxWidth: "100vh",
margin: "0 auto"
}}>
- <VoerBord width={this.width} height={this.height} onMove={m => this.move(m % this.width + 1)}/>
+ <VoerBord width={this.width} height={this.height} onMove={m => this.move(m % this.width + 1)} active={this.state.outcome == -1}/>
<GameBar turn={this.state.turn}/>
<GameOutcomeDialog outcome={this.state.outcome} visible={this.state.outcome != -1}/>
</div>
@@ -133,11 +133,11 @@ function GameOutcomeDialog(props: {
6 Optimale zetten<br/>
0 Blunders
</p> }
- <IconLabelButton text="Opnieuw spelen" icon={<RefreshIcon/>} style={{
+ { false && <IconLabelButton text="Opnieuw spelen" icon={<RefreshIcon/>} style={{
float: "none",
marginTop: 24,
padding: "12px 32px"
- }}/>
+ }}/> }
</div>
</DialogBox>
}
@@ -168,13 +168,35 @@ var InviteButtonLabelStyle: CSSProperties = {
userSelect: "none"
}
-export default function GamePage() {
- return (
- <div>
+export default class GamePage extends Component {
+ constructor(props: {}) {
+ super(props);
+
+ if (typeof window === "undefined") return;
+ if (document.cookie.includes("token") == false) return;
+ axios.request<userInfo>({
+ method: "get",
+ url: `/api/user/info`,
+ headers: {"content-type": "application/json"}
+ })
+ .then(request => this.setState({ userID: request.data.id }))
+ .catch(() => {});
+ }
+
+ state: {
+ userID: string;
+ gameID: string;
+ } = {
+ userID: "",
+ gameID: "",
+ }
+
+ render() {
+ return <div>
<NavBar/>
<CenteredPage width={900} style={{ height: "100vh" }}>
<VoerGame/>
- {false && <DialogBox title="Nieuw spel">
+ {true && <DialogBox title="Nieuw spel">
<CurrentGameSettings/>
<div style={{
marginTop: 24,
@@ -182,7 +204,16 @@ export default function GamePage() {
gridTemplateColumns: "1fr 1fr",
gridGap: 24
}}>
- <Button style={InviteButtonStyle}>
+ <Button style={InviteButtonStyle} onclick={() => {
+ axios.request<{ id: string }>({
+ method: "post",
+ url: "/api/game/random",
+ headers: {"content-type": "application/json"},
+ data: { user_id: this.state.userID }
+ })
+ .then(request => this.setState({ gameID: request.data.id }))
+ .catch(() => {});
+ }}>
<WifiTetheringRoundedIcon style={{
color: "var(--disk-b)",
...InviteButtonIconStyle
@@ -198,9 +229,10 @@ export default function GamePage() {
</Button>
</div>
<SearchBar label="Zoeken in vriendenlijst"/>
+ <p>{this.state.gameID}</p>
</DialogBox>}
</CenteredPage>
</div>
- );
+ }
}