Create custom cursor class, use hjkl to move cursor, draw hud

This commit is contained in:
Joseph Ferano 2023-10-28 18:20:22 +07:00
parent 2dc9f89431
commit 7bd04be46f

View File

@ -1,11 +1,21 @@
import pygame as pg
from pygame import Rect, Vector2 as v2
from dataclasses import dataclass
import os
@dataclass
class Cursor:
row: int = 5
col: int = 5
oswinx, oswiny = 1940,50
os.environ['SDL_VIDEO_WINDOW_POS'] = "%d,%d" % (oswinx,oswiny)
pg.init()
screen = pg.display.set_mode((900, 900))
pg.display.set_caption("Pydoku")
pg.key.set_repeat(200, 35)
title_font = pg.font.Font(None, 64)
clock = pg.time.Clock()
running = True
@ -17,7 +27,10 @@ GRID_Y = screen.get_height() / 2 - 9 * CELL_SIZE // 2
cursorSurface = pg.Surface((CURSOR_SIZE, CURSOR_SIZE), pg.SRCALPHA)
# Not used for now
padding = 0
cursor_pos = v2(5, 5)
cursor = Cursor()
board = [0] * (81)
def draw_grid():
for row in range(9):
@ -45,26 +58,39 @@ def draw_grid():
def draw_cursor():
pad_diff = (CURSOR_SIZE - CELL_SIZE) // 2
pg.draw.rect(cursorSurface, (100, 0, 155, 100), [0, 0, CURSOR_SIZE, CURSOR_SIZE])
rect = Rect(CELL_SIZE * (cursor_pos.x - 1) + GRID_X - pad_diff,
CELL_SIZE * (cursor_pos.y - 1) + GRID_Y - pad_diff,
rect = Rect(CELL_SIZE * (cursor.col - 1) + GRID_X - pad_diff,
CELL_SIZE * (cursor.row - 1) + GRID_Y - pad_diff,
CURSOR_SIZE, CURSOR_SIZE)
screen.blit(cursorSurface, rect)
title = title_font.render("Pydoku", True, "black")
def draw_hud():
screen.blit(title, (screen.get_width() // 2 - title.get_width() // 2, 70))
while running:
for event in pg.event.get():
if event.type == pg.QUIT:
running = False
if event.type == pg.KEYDOWN:
keys = pg.key.get_pressed()
# keys = pg.key.get_pressed()
if event.key == pg.K_h and cursor.col > 1:
cursor.col -= 1
if event.key == pg.K_k and cursor.row > 1:
cursor.row -= 1
if event.key == pg.K_j and cursor.row < 9:
cursor.row += 1
if event.key == pg.K_l and cursor.col < 9:
cursor.col += 1
num = pg.key.name(event.key)
if num.isdigit() and num != '0':
num = int(num)
idx = (cursor.row - 1) * 9 + cursor.col - 1
board[idx] = num
if event.key == pg.K_F1:
print(board)
if keys[pg.K_w] and cursor_pos.y > 1:
cursor_pos.y -= 1
if keys[pg.K_s] and cursor_pos.y < 9:
cursor_pos.y += 1
if keys[pg.K_a] and cursor_pos.x > 1:
cursor_pos.x -= 1
if keys[pg.K_d] and cursor_pos.x < 9:
cursor_pos.x += 1
# playerPos += dir * (speed * dt)
@ -72,6 +98,7 @@ while running:
draw_grid()
draw_cursor()
draw_hud()
pg.display.flip()