Example "keyboard input" in Python
01/01/20 18:53 Filed in:
python | RaylibThis example uses python 3 with a Raylib (
https://www.raylib.com) wrapper (
https://pypi.org/project/raylib/) that uses CFFI API static bindings (this is the fastest approach, and keeps the code as close as possible to the original C, which I feel is the best approach when using a C library).
https://www.raylib.com/examples/web/core/loader.html?name=core_input_keysThe original C example, edited for easier comparison:
#include "raylib.h"
int main(void)
{
const int screenWidth = 800;
const int screenHeight = 450;
InitWindow(screenWidth, screenHeight, "raylib [core] example - keyboard input");
Vector2 ballPosition = { (float)screenWidth/2, (float)screenHeight/2 };
SetTargetFPS(60); // Set our game to run at 60 frames-per-second
while (!WindowShouldClose()) // Detect window close button or ESC key
{
if (IsKeyDown(KEY_RIGHT)) ballPosition.x += 2.0f;
if (IsKeyDown(KEY_LEFT)) ballPosition.x -= 2.0f;
if (IsKeyDown(KEY_UP)) ballPosition.y -= 2.0f;
if (IsKeyDown(KEY_DOWN)) ballPosition.y += 2.0f;
BeginDrawing();
ClearBackground(RAYWHITE);
DrawText("move the ball with arrow keys", 10, 10, 20, DARKGRAY);
DrawCircleV(ballPosition, 50, MAROON);
EndDrawing();
}
CloseWindow(); // Close window and OpenGL context
return 0;
}
And now the Python version:
from raylib.static import *
screenWidth = 800
screenHeight = 450
InitWindow(screenWidth, screenHeight, b"raylib [core] example - keyboard input")
# Vector2 may be list or tuple or dict or struct-cdata...going with dictionary for ballPosition
ballPosition = {'x': screenWidth/2, 'y': screenHeight/2}
SetTargetFPS(60)
while not WindowShouldClose():
if IsKeyDown(KEY_RIGHT):
ballPosition["x"] += 2.0
if IsKeyDown(KEY_LEFT):
ballPosition["x"] -= 2.0
if IsKeyDown(KEY_UP):
ballPosition["y"] -= 2.0
if IsKeyDown(KEY_DOWN):
ballPosition["y"] += 2.0
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText(b"move the ball with arrow keys", 10, 10, 20, LIGHTGRAY)
DrawCircleV(ballPosition, 50, MAROON)
EndDrawing()
CloseWindow()
Tags: keyboard input