Repository navigation
Expand file tree
/
Copy pathhadouken.py
More file actions
567 lines (472 loc) · 19.1 KB
/
Copy pathhadouken.py
File metadata and controls
567 lines (472 loc) · 19.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
"""
GESTURE COMBAT — Punch the AI Boss
====================================
Punch the air toward the camera to attack. Hold an open palm steady
to block the boss's telegraphed attacks.
Controls:
C - toggle camera preview (small window bottom-right)
R - restart after game over
ESC - quit
Architecture (why it stays smooth):
- Camera capture + MediaPipe hand tracking run in a background
thread and only ever write to a lock-protected shared state.
- The pygame render loop runs on a fixed clock (TARGET_FPS) and
just READS the latest gesture snapshot each frame. It never
waits on the camera or on MediaPipe, so a slow frame from the
camera thread cannot cause a stutter in the game itself.
- MediaPipe runs on a small downscaled frame (not full camera
res) with model_complexity=0 (the "lite" model) for speed.
"""
import cv2
import mediapipe as mp
import pygame
import threading
import time
import random
import math
from collections import deque
CAM_INDEX = 0
CAM_CAPTURE_W, CAM_CAPTURE_H = 640, 480
PROC_W, PROC_H = 320, 240
WINDOW_W, WINDOW_H = 1000, 620
TARGET_FPS = 60
PUNCH_SPEED_THRESHOLD = 2.2
PUNCH_RESET_THRESHOLD = 0.7
PUNCH_COOLDOWN = 0.30
BLOCK_HOLD_TIME = 0.20
PLAYER_MAX_HP = 100
BOSS_MAX_HP = 150
PUNCH_DMG_RANGE = (8, 14)
BOSS_DMG_RANGE = (10, 18)
BOSS_IDLE_TIME_RANGE = (1.2, 2.4)
BOSS_TELEGRAPH_TIME = 0.85
BOSS_ATTACK_FLASH_TIME = 0.15
BOSS_COOLDOWN_TIME = 0.6
BOSS_STAGGER_TIME = 0.35
WHITE = (240, 240, 245)
RED = (220, 60, 60)
GREEN = (70, 200, 120)
BLUE = (80, 150, 230)
YELLOW = (240, 200, 60)
DARK = (20, 20, 28)
PANEL = (35, 35, 48)
class InputState:
def __init__(self):
self.lock = threading.Lock()
self.hand_detected = False
self.punch_event = False
self.is_blocking = False
self.wrist_norm = (0.5, 0.5)
self.preview_surface = None
self.cam_fps = 0.0
def push_punch(self):
with self.lock:
self.punch_event = True
def set(self, hand_detected, blocking, wrist_norm):
with self.lock:
self.hand_detected = hand_detected
self.is_blocking = blocking
self.wrist_norm = wrist_norm
def set_preview(self, surf):
with self.lock:
self.preview_surface = surf
def set_fps(self, fps):
with self.lock:
self.cam_fps = fps
def snapshot_and_clear_punch(self):
with self.lock:
punch = self.punch_event
self.punch_event = False
return {
"hand_detected": self.hand_detected,
"punch": punch,
"blocking": self.is_blocking,
"wrist": self.wrist_norm,
"preview": self.preview_surface,
"cam_fps": self.cam_fps,
}
class HandWorker(threading.Thread):
def __init__(self, state: InputState):
super().__init__(daemon=True)
self.state = state
self._stop_flag = threading.Event()
self.cap = cv2.VideoCapture(CAM_INDEX)
self.cap.set(cv2.CAP_PROP_FRAME_WIDTH, CAM_CAPTURE_W)
self.cap.set(cv2.CAP_PROP_FRAME_HEIGHT, CAM_CAPTURE_H)
self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)
self.mp_hands = mp.solutions.hands
self.hands = self.mp_hands.Hands(
max_num_hands=1,
model_complexity=0,
min_detection_confidence=0.6,
min_tracking_confidence=0.5,
)
self.history = deque(maxlen=4)
self.punch_armed = True
self.last_punch_time = 0.0
self.open_palm_since = None
self._frame_counter = 0
def stop(self):
self._stop_flag.set()
def _fingers_up(self, lm):
"""Return list of 1/0 for index,middle,ring,pinky extended,
using a simple tip-vs-pip y-comparison heuristic."""
tips = [8, 12, 16, 20]
pips = [6, 10, 14, 18]
out = []
for tip, pip in zip(tips, pips):
out.append(1 if lm[tip].y < lm[pip].y else 0)
return out
def _process_landmarks(self, lm, now):
wrist = lm[0]
wx, wy = wrist.x, wrist.y
self.history.append((now, wx, wy))
speed = 0.0
if len(self.history) >= 2:
t0, x0, y0 = self.history[0]
t1, x1, y1 = self.history[-1]
dt = max(t1 - t0, 1e-3)
dist = math.hypot(x1 - x0, y1 - y0)
speed = dist / dt
punched = False
if self.punch_armed and speed > PUNCH_SPEED_THRESHOLD:
if now - self.last_punch_time > PUNCH_COOLDOWN:
punched = True
self.last_punch_time = now
self.punch_armed = False
elif not self.punch_armed and speed < PUNCH_RESET_THRESHOLD:
self.punch_armed = True
fingers = self._fingers_up(lm)
is_open_palm = sum(fingers) >= 3 and speed < 1.0
if is_open_palm:
if self.open_palm_since is None:
self.open_palm_since = now
else:
self.open_palm_since = None
blocking = (
self.open_palm_since is not None
and (now - self.open_palm_since) >= BLOCK_HOLD_TIME
)
return punched, blocking, (wx, wy)
def run(self):
prev_t = time.time()
smoothed_fps = 0.0
while not self._stop_flag.is_set():
ok, frame = self.cap.read()
if not ok:
time.sleep(0.01)
continue
frame = cv2.flip(frame, 1)
small = cv2.resize(frame, (PROC_W, PROC_H), interpolation=cv2.INTER_LINEAR)
rgb = cv2.cvtColor(small, cv2.COLOR_BGR2RGB)
rgb.flags.writeable = False
results = self.hands.process(rgb)
now = time.time()
hand_detected = False
blocking = False
wrist_norm = (0.5, 0.5)
if results.multi_hand_landmarks:
hand_detected = True
lm = results.multi_hand_landmarks[0].landmark
punched, blocking, wrist_norm = self._process_landmarks(lm, now)
if punched:
self.state.push_punch()
mp.solutions.drawing_utils.draw_landmarks(
small, results.multi_hand_landmarks[0], self.mp_hands.HAND_CONNECTIONS
)
else:
self.history.clear()
self.open_palm_since = None
self.state.set(hand_detected, blocking, wrist_norm)
self._frame_counter += 1
if self._frame_counter % 2 == 0:
rgb_small_for_ui = cv2.cvtColor(small, cv2.COLOR_BGR2RGB)
surf = pygame.image.frombuffer(
rgb_small_for_ui.tobytes(), (PROC_W, PROC_H), "RGB"
)
self.state.set_preview(surf)
dt = now - prev_t
prev_t = now
if dt > 0:
inst_fps = 1.0 / dt
smoothed_fps = smoothed_fps * 0.9 + inst_fps * 0.1
self.state.set_fps(smoothed_fps)
self.cap.release()
self.hands.close()
class Particle:
__slots__ = ("x", "y", "vx", "vy", "life", "color", "size")
def __init__(self, x, y, color):
angle = random.uniform(0, math.tau)
speed = random.uniform(80, 260)
self.x, self.y = x, y
self.vx = math.cos(angle) * speed
self.vy = math.sin(angle) * speed
self.life = random.uniform(0.25, 0.5)
self.color = color
self.size = random.randint(2, 5)
def update(self, dt):
self.x += self.vx * dt
self.y += self.vy * dt
self.vy += 300 * dt
self.life -= dt
return self.life > 0
def draw(self, screen):
if self.life > 0:
pygame.draw.circle(screen, self.color, (int(self.x), int(self.y)), self.size)
class Boss:
"""Simple telegraphed state machine so hits are fair & readable:
IDLE -> TELEGRAPH (player should block!) -> ATTACK -> COOLDOWN -> IDLE
The player can land punches on the boss at any time except DEAD."""
IDLE, TELEGRAPH, ATTACK, STAGGER, COOLDOWN, DEAD = range(6)
def __init__(self):
self.hp = BOSS_MAX_HP
self.state = Boss.IDLE
self.state_timer = random.uniform(*BOSS_IDLE_TIME_RANGE)
self.shake = 0.0
self.pulse = 0.0
def take_hit(self, dmg):
if self.state == Boss.DEAD:
return
self.hp = max(0, self.hp - dmg)
self.shake = 10.0
if self.hp <= 0:
self.state = Boss.DEAD
elif self.state == Boss.IDLE:
self.state = Boss.STAGGER
self.state_timer = BOSS_STAGGER_TIME
def update(self, dt, player):
"""Returns 'attack_landed' or 'attack_blocked' or None for events
the game needs to react to (damage / sound / particles)."""
event = None
self.shake = max(0.0, self.shake - dt * 40)
self.pulse += dt
if self.state == Boss.DEAD:
return None
self.state_timer -= dt
if self.state_timer <= 0:
if self.state == Boss.IDLE:
self.state = Boss.TELEGRAPH
self.state_timer = BOSS_TELEGRAPH_TIME
elif self.state == Boss.TELEGRAPH:
self.state = Boss.ATTACK
self.state_timer = BOSS_ATTACK_FLASH_TIME
if player.is_blocking:
event = "attack_blocked"
else:
dmg = random.randint(*BOSS_DMG_RANGE)
player.take_hit(dmg)
event = "attack_landed"
elif self.state == Boss.ATTACK:
self.state = Boss.COOLDOWN
self.state_timer = BOSS_COOLDOWN_TIME
elif self.state in (Boss.COOLDOWN, Boss.STAGGER):
self.state = Boss.IDLE
self.state_timer = random.uniform(*BOSS_IDLE_TIME_RANGE)
return event
def color(self):
if self.state == Boss.DEAD:
return (60, 60, 60)
if self.state == Boss.TELEGRAPH:
return YELLOW
if self.state == Boss.ATTACK:
return RED
if self.state == Boss.STAGGER:
return BLUE
return (170, 90, 220)
def radius(self):
base = 70
if self.state == Boss.TELEGRAPH:
base += 10 * math.sin(self.pulse * 12)
if self.state == Boss.ATTACK:
base += 25
return base
class Player:
def __init__(self):
self.hp = PLAYER_MAX_HP
self.is_blocking = False
self.hit_flash = 0.0
self.punch_flash = 0.0
def take_hit(self, dmg):
self.hp = max(0, self.hp - dmg)
self.hit_flash = 0.25
def update(self, dt):
self.hit_flash = max(0.0, self.hit_flash - dt)
self.punch_flash = max(0.0, self.punch_flash - dt)
class Game:
MENU, PLAYING, GAMEOVER = range(3)
def __init__(self):
pygame.init()
pygame.display.set_caption("Gesture Combat — Punch the Boss")
self.screen = pygame.display.set_mode((WINDOW_W, WINDOW_H))
self.clock = pygame.time.Clock()
self.font_big = pygame.font.SysFont("arial", 54, bold=True)
self.font_med = pygame.font.SysFont("arial", 30, bold=True)
self.font_small = pygame.font.SysFont("arial", 20)
self.state = InputState()
self.worker = HandWorker(self.state)
self.worker.start()
self.show_preview = True
self.mode = Game.MENU
self.particles = []
self.messages = []
self.reset_game()
def reset_game(self):
self.boss = Boss()
self.player = Player()
self.particles.clear()
self.messages.clear()
def add_message(self, text, color, x, y):
self.messages.append([text, color, x, y, 1.0])
def spawn_particles(self, x, y, color, n=18):
for _ in range(n):
self.particles.append(Particle(x, y, color))
def run(self):
running = True
while running:
dt = self.clock.tick(TARGET_FPS) / 1000.0
running = self.handle_events()
snap = self.state.snapshot_and_clear_punch()
if self.mode == Game.MENU:
if snap["hand_detected"]:
self.mode = Game.PLAYING
elif self.mode == Game.PLAYING:
self.update_playing(dt, snap)
elif self.mode == Game.GAMEOVER:
pass
self.draw(snap)
pygame.display.flip()
self.worker.stop()
self.worker.join(timeout=1.0)
pygame.quit()
def handle_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
return False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
return False
if event.key == pygame.K_c:
self.show_preview = not self.show_preview
if event.key == pygame.K_r and self.mode == Game.GAMEOVER:
self.reset_game()
self.mode = Game.PLAYING
return True
def update_playing(self, dt, snap):
self.player.is_blocking = snap["blocking"]
self.player.update(dt)
if snap["punch"] and self.boss.state != Boss.DEAD:
dmg = random.randint(*PUNCH_DMG_RANGE)
self.boss.take_hit(dmg)
self.player.punch_flash = 0.15
bx, by = self.boss_screen_pos()
self.spawn_particles(bx, by, YELLOW)
self.add_message(f"-{dmg}", YELLOW, bx + random.randint(-20, 20), by - 40)
event = self.boss.update(dt, self.player)
if event == "attack_landed":
self.spawn_particles(*self.player_screen_pos(), RED)
self.add_message("HIT!", RED, WINDOW_W // 2, WINDOW_H - 160)
elif event == "attack_blocked":
self.spawn_particles(*self.player_screen_pos(), BLUE, n=10)
self.add_message("BLOCKED!", BLUE, WINDOW_W // 2, WINDOW_H - 160)
self.particles = [p for p in self.particles if p.update(dt)]
for m in self.messages:
m[4] -= dt * 1.2
m[3] -= dt * 30
self.messages = [m for m in self.messages if m[4] > 0]
if self.player.hp <= 0 or self.boss.hp <= 0:
self.mode = Game.GAMEOVER
def boss_screen_pos(self):
shake_x = random.uniform(-1, 1) * self.boss.shake
return (WINDOW_W // 2 + shake_x, 190)
def player_screen_pos(self):
return (WINDOW_W // 2, WINDOW_H - 110)
def draw(self, snap):
self.screen.fill(DARK)
if self.mode == Game.MENU:
self.draw_menu(snap)
elif self.mode == Game.PLAYING:
self.draw_arena(snap)
elif self.mode == Game.GAMEOVER:
self.draw_arena(snap)
self.draw_gameover()
if self.show_preview and snap["preview"] is not None:
self.draw_preview(snap)
self.draw_hud_footer(snap)
def draw_menu(self, snap):
title = self.font_big.render("GESTURE COMBAT", True, WHITE)
self.screen.blit(title, title.get_rect(center=(WINDOW_W // 2, 160)))
sub = self.font_med.render("Show your hand to the camera to begin", True, YELLOW)
self.screen.blit(sub, sub.get_rect(center=(WINDOW_W // 2, 230)))
lines = [
"PUNCH the air toward the screen to attack the boss",
"HOLD an open palm steady to BLOCK the boss's glowing attack",
"Watch for YELLOW pulse = incoming attack, block it in time!",
]
for i, line in enumerate(lines):
t = self.font_small.render(line, True, WHITE)
self.screen.blit(t, t.get_rect(center=(WINDOW_W // 2, 320 + i * 32)))
if not snap["hand_detected"]:
warn = self.font_small.render("(no hand detected — check camera / lighting)", True, RED)
self.screen.blit(warn, warn.get_rect(center=(WINDOW_W // 2, 440)))
def draw_arena(self, snap):
# Boss
bx, by = self.boss_screen_pos()
pygame.draw.circle(self.screen, self.boss.color(), (int(bx), int(by)), int(self.boss.radius()))
if self.boss.state == Boss.TELEGRAPH:
warn = self.font_med.render("!", True, DARK)
self.screen.blit(warn, warn.get_rect(center=(int(bx), int(by))))
# Boss HP bar
self.draw_bar(WINDOW_W // 2 - 200, 60, 400, 26, self.boss.hp, BOSS_MAX_HP, RED, "BOSS")
# Player HP bar
self.draw_bar(WINDOW_W // 2 - 200, WINDOW_H - 60, 400, 26, self.player.hp, PLAYER_MAX_HP, GREEN, "YOU")
# Player indicator (fist / open palm) at bottom
px, py = self.player_screen_pos()
if self.player.is_blocking:
pygame.draw.circle(self.screen, BLUE, (int(px), int(py)), 44, 6)
lbl = self.font_small.render("BLOCKING", True, BLUE)
self.screen.blit(lbl, lbl.get_rect(center=(px, py + 65)))
else:
size = 34 + (10 if self.player.punch_flash > 0 else 0)
pygame.draw.circle(self.screen, WHITE, (int(px), int(py)), size)
if self.player.hit_flash > 0:
overlay = pygame.Surface((WINDOW_W, WINDOW_H))
overlay.set_alpha(int(90 * (self.player.hit_flash / 0.25)))
overlay.fill(RED)
self.screen.blit(overlay, (0, 0))
for p in self.particles:
p.draw(self.screen)
for text, color, x, y, life in self.messages:
alpha_font = self.font_med.render(text, True, color)
self.screen.blit(alpha_font, alpha_font.get_rect(center=(int(x), int(y))))
def draw_bar(self, x, y, w, h, hp, max_hp, color, label):
pygame.draw.rect(self.screen, PANEL, (x, y, w, h), border_radius=6)
frac = max(0, hp) / max_hp
pygame.draw.rect(self.screen, color, (x, y, int(w * frac), h), border_radius=6)
pygame.draw.rect(self.screen, WHITE, (x, y, w, h), 2, border_radius=6)
lbl = self.font_small.render(f"{label} {max(0,hp)}/{max_hp}", True, WHITE)
self.screen.blit(lbl, (x, y - 24))
def draw_gameover(self):
overlay = pygame.Surface((WINDOW_W, WINDOW_H))
overlay.set_alpha(180)
overlay.fill(DARK)
self.screen.blit(overlay, (0, 0))
won = self.boss.hp <= 0
text = "VICTORY!" if won else "DEFEATED"
color = GREEN if won else RED
t = self.font_big.render(text, True, color)
self.screen.blit(t, t.get_rect(center=(WINDOW_W // 2, WINDOW_H // 2 - 30)))
sub = self.font_med.render("Press R to fight again", True, WHITE)
self.screen.blit(sub, sub.get_rect(center=(WINDOW_W // 2, WINDOW_H // 2 + 30)))
def draw_preview(self, snap):
surf = snap["preview"]
scaled = pygame.transform.smoothscale(surf, (200, 150))
x, y = WINDOW_W - 210, WINDOW_H - 160
self.screen.blit(scaled, (x, y))
pygame.draw.rect(self.screen, WHITE, (x, y, 200, 150), 2)
def draw_hud_footer(self, snap):
fps = self.clock.get_fps()
info = f"Game FPS: {fps:4.0f} Cam FPS: {snap['cam_fps']:4.0f} [C] toggle cam [ESC] quit"
t = self.font_small.render(info, True, (150, 150, 160))
self.screen.blit(t, (10, WINDOW_H - 24))
if __name__ == "__main__":
Game().run()