Skip to content

Commit

Permalink
feat: general improvements
Browse files Browse the repository at this point in the history
  • Loading branch information
AiroPi committed Jan 8, 2025
1 parent 9109a85 commit 22cc95f
Show file tree
Hide file tree
Showing 71 changed files with 121 additions and 978 deletions.
4 changes: 1 addition & 3 deletions golang/src/connect4img.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,6 @@ var HIGHLIGHT_WIN_COLOR = color.RGBA{100, 255, 100, 255}
var FACE font.Face

func init() {
log.Print("Loaded!")
var err error
FACE, err = gg.LoadFontFace("./resources/fonts/Roboto-Regular.ttf", float64(FONT_SIZE))
if err != nil {
Expand All @@ -39,7 +38,6 @@ func init() {

//export GenerateBoard
func GenerateBoard(board [][]int, isOver bool, winner int, turn int, winPositions [][]int) {
log.Print(winPositions)
const width = 7*(TOKEN_DIAMETER+INTERSPACE) + INTERSPACE
const heigh = 6*(TOKEN_DIAMETER+INTERSPACE) + INTERSPACE + BOX_HEIGHT
dc := gg.NewContext(
Expand Down Expand Up @@ -99,7 +97,7 @@ func GenerateBoard(board [][]int, isOver bool, winner int, turn int, winPosition
}
}

err := dc.SavePNG("./data/connect4.png") // TODO
err := dc.SavePNG("./data/connect4.png") // TODO: allow to customise the path
if err != nil {
log.Fatalf("could not save to file: %+v", err)
}
Expand Down
2 changes: 0 additions & 2 deletions python/src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,3 @@ def get_readme():
with open("./README.out.md") as f:
markdown_text = f.read()
return HTMLResponse(markdown(markdown_text))

# return FileResponse("./readme.html")
32 changes: 21 additions & 11 deletions python/src/routers/connect4_router/__init__.py
Original file line number Diff line number Diff line change
@@ -1,26 +1,36 @@
import os
from functools import partial
from pathlib import Path
from time import time

from connect4 import ColumnFull, Connect4
from fastapi import APIRouter, Query
from fastapi.responses import FileResponse, RedirectResponse

from utils import RESOURCES_PATH, file_response, load_image, png_response, redirect_to_readme

from .go_library import generate_board

GITHUB_PROFILE_URL = os.environ["GITHUB_PROFILE_URL"]
IMAGE_PATH = Path("./data/connect4.png")
GENERATED_BOARD_PATH = Path("./data/connect4.png")
DYNAMIC_IMAGES_PATH = RESOURCES_PATH / "images" / "connect4"

DISABLED_RESTART = load_image(DYNAMIC_IMAGES_PATH / "restart_disabled.png")
RESTART = load_image(DYNAMIC_IMAGES_PATH / "restart.png")

last_play_time = time()
c4 = Connect4()
router = APIRouter(prefix="/connect4", on_startup=[partial(generate_board, c4)])


@router.get("/image")
def get_image():
return FileResponse(IMAGE_PATH, headers={"Cache-Control": "no-cache, max-age=0"})
@router.get("/img/{target}")
def get_image(target: str):
match target:
case "board":
return file_response(GENERATED_BOARD_PATH)
case "restart":
if not c4.is_over and time() - last_play_time < 10:
return png_response(DISABLED_RESTART)
return png_response(RESTART)
case _:
return redirect_to_readme("#connect4")


@router.get("/play")
Expand All @@ -35,14 +45,14 @@ def play(column: int = Query(title="The column ID you want to play to.", ge=0, l
else:
generate_board(c4)
last_play_time = time()
return RedirectResponse(f"{GITHUB_PROFILE_URL}#connect4")
return redirect_to_readme("#connect4")


@router.get("/reset")
@router.get("/restart")
def reset():
if not c4.is_over and time() - last_play_time < 300:
return RedirectResponse(f"{GITHUB_PROFILE_URL}#connect4")
return redirect_to_readme("#connect4")

c4.reset()
generate_board(c4)
return RedirectResponse(f"{GITHUB_PROFILE_URL}#connect4")
return redirect_to_readme("#connect4")
74 changes: 18 additions & 56 deletions python/src/routers/minesweeper_router.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,9 @@
import os
from pathlib import Path

import minesweeper
from fastapi import APIRouter, Response
from fastapi.responses import RedirectResponse
from fastapi import APIRouter

from utils import RESOURCES_PATH, load_image, png_response, redirect_to_readme

GITHUB_PROFILE_URL = os.environ["GITHUB_PROFILE_URL"]
BASE_PATH = Path("./resources/images/minesweeper/png/")
BASE_PATH = RESOURCES_PATH / "images" / "minesweeper"
SIZE = (10, 12)
BOMBS = 20

Expand All @@ -15,110 +12,75 @@
flag_mode = False


def load_image(path: Path):
with path.open("rb") as f:
return f.read()


RED_MINE = load_image(BASE_PATH / "mine_red.png")
MINE = load_image(BASE_PATH / "mine.png")
FLAG = load_image(BASE_PATH / "flag.png")
DEACTIVATED_FLAG = load_image(BASE_PATH / "deactivated_flag.png")
CLOSED = load_image(BASE_PATH / "closed.png")
HEADER = load_image(BASE_PATH / "header.png")
UNDO = load_image(BASE_PATH / "undo.png")
FACE = load_image(BASE_PATH / "face.png")
FACE_LOSE = load_image(BASE_PATH / "face_lose.png")

DIGITS = {i: load_image(BASE_PATH / f"{i}.png") for i in range(9)}


def get_header():
return {
"Cache-Control": "no-cache, max-age=0",
# "Last-Modified": datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"),
# "ETag": etag,
}


def response_img(img: bytes):
"""
Maybe some optimisations could be done here.
I'm pretty sure that the request *could* be cached but without being cached.
Like -> if the content didn't change, don't send it again, otherwise send it.
Also, the tiles are "shared" between the image, so maybe there is a way for the browser to reuse the same image.
I don't want to dig more into this, but it's a thought.
"""
# etag = hashlib.md5(img).hexdigest()
return Response(img, media_type="image/png", headers=get_header())


def redirect_to_github():
return RedirectResponse(f"{GITHUB_PROFILE_URL}#minesweeper")


@router.get("/img/{i}/{j}")
def get_board_img(i: int, j: int):
if (i, j) in game.revealed:
if game.board[i][j] == -1:
return response_img(RED_MINE)
return response_img(DIGITS[game.board[i][j]])
return png_response(RED_MINE)
return png_response(DIGITS[game.board[i][j]])
if game.game_over and game.board[i][j] == -1:
return response_img(MINE)
return png_response(MINE)
if (i, j) in game.flags:
return response_img(FLAG)
return response_img(CLOSED)
return png_response(FLAG)
return png_response(CLOSED)


@router.get("/img/{text}")
def get_img(text: str):
match text:
case "flag-toggle":
if flag_mode:
return response_img(FLAG)
return png_response(FLAG)
else:
return response_img(DEACTIVATED_FLAG)
case "header":
return response_img(HEADER)
case "undo":
return response_img(UNDO)
return png_response(DEACTIVATED_FLAG)
case "face":
if game.game_over:
return response_img(FACE_LOSE)
return png_response(FACE_LOSE)
else:
return response_img(FACE)
return png_response(FACE)
case _:
return 404


@router.get("/play/{i}/{j}")
def play(i: int, j: int):
if game.game_over:
return redirect_to_github()
return redirect_to_readme("#minesweeper")

if flag_mode:
game.toggle_flag(i, j)
else:
if (i, j) not in game.flags:
game.play(i, j)
return redirect_to_github()
return redirect_to_readme("#minesweeper")


@router.get("/toggle-flag")
def flag_toggle():
global flag_mode
flag_mode = not flag_mode
return redirect_to_github()
return redirect_to_readme("#minesweeper")


@router.get("/reset")
def reset():
global game
game = minesweeper.Minesweeper(SIZE, BOMBS)
return redirect_to_github()
return redirect_to_readme("#minesweeper")


@router.get("/undo")
def undo():
# TODO: Implement undo
return redirect_to_github()
return redirect_to_readme("#minesweeper")
41 changes: 41 additions & 0 deletions python/src/utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
import os
from pathlib import Path

from fastapi import Response
from fastapi.responses import FileResponse, RedirectResponse

GITHUB_PROFILE_URL = os.environ["GITHUB_PROFILE_URL"]
RESOURCES_PATH = Path("./resources/")


def get_header():
return {
"Cache-Control": "no-cache, max-age=0",
# "Last-Modified": datetime.now().strftime("%a, %d %b %Y %H:%M:%S GMT"),
# "ETag": etag,
}


def png_response(img: bytes):
"""
Maybe some optimisations could be done here.
I'm pretty sure that the request *could* be cached but without being cached.
Like -> if the content didn't change, don't send it again, otherwise send it.
Also, the tiles are "shared" between the image, so maybe there is a way for the browser to reuse the same image.
I don't want to dig more into this, but it's a thought.
"""
# etag = hashlib.md5(img).hexdigest()
return Response(img, media_type="image/png", headers=get_header())


def file_response(path: Path):
return FileResponse(path, headers=get_header())


def redirect_to_readme(anchor: str = ""):
return RedirectResponse(f"{GITHUB_PROFILE_URL}{anchor}")


def load_image(path: Path):
with path.open("rb") as f:
return f.read()
Binary file added resources/images/connect4/restart.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added resources/images/connect4/restart_disabled.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
File renamed without changes
Binary file removed resources/images/minesweeper/png/d0.png
Binary file not shown.
Binary file removed resources/images/minesweeper/png/d1.png
Binary file not shown.
Binary file removed resources/images/minesweeper/png/d2.png
Binary file not shown.
Binary file removed resources/images/minesweeper/png/d3.png
Binary file not shown.
Binary file removed resources/images/minesweeper/png/d4.png
Binary file not shown.
Binary file removed resources/images/minesweeper/png/d5.png
Binary file not shown.
Binary file removed resources/images/minesweeper/png/d6.png
Diff not rendered.
Binary file removed resources/images/minesweeper/png/d7.png
Diff not rendered.
Binary file removed resources/images/minesweeper/png/d8.png
Diff not rendered.
Binary file removed resources/images/minesweeper/png/d9.png
Diff not rendered.
Binary file removed resources/images/minesweeper/png/dnull.png
Diff not rendered.
Binary file removed resources/images/minesweeper/png/header.png
Diff not rendered.
20 changes: 0 additions & 20 deletions resources/images/minesweeper/svg/0.svg
Diff not rendered.
22 changes: 0 additions & 22 deletions resources/images/minesweeper/svg/1.svg
Diff not rendered.
22 changes: 0 additions & 22 deletions resources/images/minesweeper/svg/2.svg
Diff not rendered.
22 changes: 0 additions & 22 deletions resources/images/minesweeper/svg/3.svg
Diff not rendered.
22 changes: 0 additions & 22 deletions resources/images/minesweeper/svg/4.svg
Diff not rendered.
Loading

0 comments on commit 22cc95f

Please sign in to comment.