Spaces:
Runtime error
Runtime error
Added keyboard as input.
Browse files
app.py
CHANGED
|
@@ -1,43 +1,44 @@
|
|
| 1 |
import gradio as gr
|
| 2 |
from PIL import Image, ImageDraw
|
| 3 |
|
| 4 |
-
# Initial game state
|
| 5 |
player_pos = [50, 50]
|
| 6 |
canvas_size = (200, 200)
|
| 7 |
step_size = 10
|
| 8 |
|
| 9 |
-
def update_frame(action):
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
player_pos[1] += step_size
|
| 17 |
-
elif action == "a":
|
| 18 |
-
player_pos[0] -= step_size
|
| 19 |
-
elif action == "d":
|
| 20 |
-
player_pos[0] += step_size
|
| 21 |
|
| 22 |
-
|
| 23 |
-
player_pos[0] = max(0, min(canvas_size[0], player_pos[0]))
|
| 24 |
-
player_pos[1] = max(0, min(canvas_size[1], player_pos[1]))
|
| 25 |
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 33 |
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
outputs=gr.Image(type="pil"),
|
| 38 |
-
live=False,
|
| 39 |
-
title="Simple WASD Game",
|
| 40 |
-
description="Move the blue dot using WASD!"
|
| 41 |
-
)
|
| 42 |
|
| 43 |
-
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
from PIL import Image, ImageDraw
|
| 3 |
|
|
|
|
| 4 |
player_pos = [50, 50]
|
| 5 |
canvas_size = (200, 200)
|
| 6 |
step_size = 10
|
| 7 |
|
| 8 |
+
def update_frame(action, prev_pos):
|
| 9 |
+
x, y = prev_pos
|
| 10 |
+
if action == "w": y -= step_size
|
| 11 |
+
elif action == "s": y += step_size
|
| 12 |
+
elif action == "a": x -= step_size
|
| 13 |
+
elif action == "d": x += step_size
|
| 14 |
+
x = max(0, min(canvas_size[0], x))
|
| 15 |
+
y = max(0, min(canvas_size[1], y))
|
| 16 |
+
img = Image.new("RGB", canvas_size, color="white")
|
| 17 |
+
draw = ImageDraw.Draw(img)
|
| 18 |
+
draw.ellipse((x-5, y-5, x+5, y+5), fill="blue")
|
| 19 |
+
return img, [x, y]
|
| 20 |
|
| 21 |
+
with gr.Blocks() as demo:
|
| 22 |
+
state = gr.State([50, 50])
|
| 23 |
+
img_output = gr.Image(type="pil", interactive=False)
|
| 24 |
+
action_box = gr.Textbox(label="Press keys (WASD)", interactive=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 25 |
|
| 26 |
+
demo.load(update_frame, ["", state], [img_output, state]) # initial frame
|
|
|
|
|
|
|
| 27 |
|
| 28 |
+
custom_js = """
|
| 29 |
+
<script>
|
| 30 |
+
document.addEventListener('keydown', function(event) {
|
| 31 |
+
let key = event.key.toLowerCase();
|
| 32 |
+
if (["w","a","s","d"].includes(key)) {
|
| 33 |
+
document.querySelector('textarea[aria-label="Press keys (WASD)"]').value = key;
|
| 34 |
+
document.querySelector('button').click();
|
| 35 |
+
}
|
| 36 |
+
});
|
| 37 |
+
</script>
|
| 38 |
+
"""
|
| 39 |
|
| 40 |
+
html_box = gr.HTML(custom_js)
|
| 41 |
+
action_button = gr.Button("Update") # hidden trigger
|
| 42 |
+
action_button.click(update_frame, [action_box, state], [img_output, state])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
+
demo.launch()
|