Paulo Laureano Because coding is fun!

Example "drawing sprites & collision" in Python


This 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).

Create a folder called "resources" (in the same directory as your code) and place the two images (provided bellow) there.

hero_shipufo1


Here is the Python sample code…



from raylib.static import *
from ctypes import *

screenWidth = 800
screenHeight = 600

InitWindow(screenWidth, screenHeight, b"sprites & collision example")

SetTargetFPS(60)

# hero ship
speed = 4.0
ship_size_width = 50
ship_size_height = 75

ship_position={'x': screenWidth/2.0, 'y': screenHeight-ship_size_height}
ship_rectangle = { 'x': ship_position["x"], 'y': ship_position["y"],'width': ship_size_width, 'height': ship_size_height }
image_hero_ship = LoadImage(b"resources/hero_ship.png")

ImageResize(ffi.addressof(image_hero_ship), ship_size_width, ship_size_height)

hero_ship=LoadTextureFromImage(image_hero_ship)


#bad dude ship
baddude_speed = 4.0
baddude_ship_size_width = 100
baddude_ship_size_height = 50

baddude_ship_position={'x': screenWidth/2.0, 'y': 0}
baddude_ship_rectangle = { 'x': baddude_ship_position["x"], 'y': baddude_ship_position["y"], 'width': baddude_ship_size_width, 'height': baddude_ship_size_height }
image_baddude_ship = LoadImage(b"resources/ufo1.png")

ImageResize(ffi.addressof(image_baddude_ship), baddude_ship_size_width, baddude_ship_size_height)

baddude_ship=LoadTextureFromImage(image_baddude_ship)



# detect collision
def my_check_collision_recs(rec1,rec2):
if rec1["x"] < rec2["x"] + rec2["width"] and rec1["x"] + rec1["width"] > rec2["x"] and rec1["y"] < rec2["y"] + rec2["height"] and rec1["y"] + rec1["height"] > rec2["y"]:
return 1
else:
return 0



while not WindowShouldClose():

# control the heroship
if IsKeyDown(KEY_RIGHT):
ship_position["x"] += 2.0
ship_rectangle["x"] += 2.0
if IsKeyDown(KEY_LEFT):
ship_position["x"] -= 2.0
ship_rectangle["x"] -= 2.0
if IsKeyDown(KEY_UP):
ship_position["y"] -= 2.0
ship_rectangle["y"] -= 2.0
if IsKeyDown(KEY_DOWN):
ship_position["y"] += 2.0
ship_rectangle["y"] += 2.0

BeginDrawing()

ClearBackground(RAYWHITE)
DrawTexture(baddude_ship, int(baddude_ship_position["x"]), int(baddude_ship_position["y"]), LIGHTGRAY)
DrawTexture(hero_ship, int(ship_position["x"]), int(ship_position["y"]), LIGHTGRAY)


if my_check_collision_recs(ship_rectangle, baddude_ship_rectangle):
DrawText(b"BOOM", 10, 10, 20, LIGHTGRAY)


EndDrawing()
CloseWindow()


Example "mouse wheel input" in Python

This 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_mouse_wheel

The 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 - input mouse wheel");

int boxPositionY = screenHeight/2 - 40;
int scrollSpeed = 4; // Scrolling speed in pixels

SetTargetFPS(60); // Set our game to run at 60 frames-per-second

while (!WindowShouldClose()) // Detect window close button or ESC key
{
boxPositionY -= (GetMouseWheelMove()*scrollSpeed);

BeginDrawing();

ClearBackground(RAYWHITE);

DrawRectangle(screenWidth/2 - 40, boxPositionY, 80, 80, MAROON);

DrawText("Use mouse wheel to move the cube up and down!", 10, 10, 20, GRAY);
DrawText(FormatText("Box position Y: %03i", boxPositionY), 10, 40, 20, LIGHTGRAY);

EndDrawing();
}

CloseWindow(); // Close window and OpenGL context

return 0;
}



The Python version:



from raylib.static import *

screenWidth = 800
screenHeight = 450

InitWindow(screenWidth, screenHeight, b"raylib [core] example - input mouse wheel")

boxPositionX = screenWidth/2 - 40
boxPositionY = screenHeight/2 - 40
scrollSpeed = 4


SetTargetFPS(60)


while not WindowShouldClose():
boxPositionY -= GetMouseWheelMove()*scrollSpeed

BeginDrawing()
ClearBackground(RAYWHITE)
DrawRectangle(int(boxPositionX), int(boxPositionY), 80, 80, MAROON)

DrawText(b"Use mouse wheel to move the cube up and down!", 10, 10, 20, LIGHTGRAY)

yCoord="Box position Y: {}".format(int(boxPositionY))
DrawText(yCoord.encode('ascii'), 10, 40, 20, LIGHTGRAY)

EndDrawing()
CloseWindow()

Example "mouse input" in Python

This 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_mouse

The 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 - mouse input");

Vector2 ballPosition = { -100.0f, -100.0f };
Color ballColor = DARKBLUE;

SetTargetFPS(60); // Set our game to run at 60 frames-per-second

while (!WindowShouldClose()) // Detect window close button or ESC key
{
ballPosition = GetMousePosition();

if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON;
else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME;
else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE;

BeginDrawing();

ClearBackground(RAYWHITE);

DrawCircleV(ballPosition, 40, ballColor);

DrawText("move ball with mouse and click mouse button to change color", 10, 10, 20, DARKGRAY);

EndDrawing();
}

// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context

return 0;
}



The Python version:



from raylib.static import *

screenWidth = 800
screenHeight = 450

InitWindow(screenWidth, screenHeight, b"raylib [core] example - mouse input")

# Vector2 may be list or tuple or dict or struct-cdata...going with dictionary for ballPosition
ballPosition = {'x': -100, 'y': -100}
ballColor = DARKBLUE


SetTargetFPS(60)


while not WindowShouldClose():
ballPosition = GetMousePosition()

if IsMouseButtonPressed(MOUSE_LEFT_BUTTON):
ballColor = MAROON
elif IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON):
ballColor = LIME
elif IsMouseButtonPressed(MOUSE_RIGHT_BUTTON):
ballColor = DARKBLUE

BeginDrawing()
ClearBackground(RAYWHITE)
DrawText(b"move ball with mouse and click mouse button to change color", 10, 10, 20, LIGHTGRAY)
DrawCircleV(ballPosition, 50, ballColor)
EndDrawing()
CloseWindow()


Example "keyboard input" in Python


This 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_keys

The 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()



Example "basic window" in Python

This 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).

Original Raylib C code in example 1 converted to python…

Python version (using https://pypi.org/project/raylib/#description):


from raylib.static import *

screenWidth = 800
screenHeight = 450

InitWindow(screenWidth, screenHeight, b"raylib [core] example - basic window")

SetTargetFPS(60)


while not WindowShouldClose():
BeginDrawing()
ClearBackground(RAYWHITE)
DrawText(b"Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY)
EndDrawing()
CloseWindow()


Example "drawing sprites & collision" in Rust

Create a folder called "resources" (in the same directory as your code) and place the two images (provided bellow) there.

hero_shipufo1


Here is the Rust code…


extern crate raylib;
use raylib::prelude::*;
use raylib::prelude::KeyboardKey::*;
use raylib::ffi::CheckCollisionRecs;

fn main() {
let screen_width = 800.0;
let screen_height = 600.0;

let (mut rl, thread) = raylib::init()
.size(screen_width as i32, screen_height as i32)
.title("Simple shooter")
.build();

//hero ship
let speed = 4.0;
let ship_size_width = 50;
let ship_size_height = 75;

let mut ship_position = Vector2 {
x: screen_width / 2.0,
y: screen_height - ship_size_height as f32,
};

let mut ship_rectangle = Rectangle {
width: ship_size_width as f32,
height: ship_size_height as f32,
x: ship_position.x,
y: ship_position.y,
};

// graphics load hero ship
let mut image_hero_ship = Image::load_image("resources/hero_ship.png");

let i=image_hero_ship.as_mut().unwrap();
Image::image_resize(i, 50, 75);

let mut hero_ship = rl.load_texture_from_image(&thread, i);
let hs=hero_ship.as_mut().unwrap();

//bad dude ship
let baddude_speed = 4.0;
let baddude_ship_size_width = 75;
let baddude_ship_size_height = 50;

let mut baddude_ship_position = Vector2 {
x: 0.0,
y: 20.0 + baddude_ship_size_height as f32,
};

let mut baddude_ship_rectangle = Rectangle {
width: baddude_ship_size_width as f32,
height: baddude_ship_size_height as f32,
x: baddude_ship_position.x,
y: baddude_ship_position.y,
};

// graphics load bad dude ship
let mut image_baddude_ship = Image::load_image("resources/ufo1.png");

let bi=image_hero_ship.as_mut().unwrap();
Image::image_resize(bi, baddude_ship_size_width, baddude_ship_size_height);

let mut baddude_ship = rl.load_texture_from_image(&thread, bi);
let bs=baddude_ship.as_mut().unwrap();


rl.set_target_fps(60); // Set our game to run at 60 frames-per-second

while !rl.window_should_close() {
// beging drawing operations
let mut d = rl.begin_drawing(&thread);
d.clear_background(Color::BLACK);

// control the hero ship
if d.is_key_down(KEY_RIGHT)
&& ship_position.x < screen_width as f32 - ship_size_width as f32
{
ship_position.x += speed;
}
if d.is_key_down(KEY_LEFT) && ship_position.x > 0.0 {
ship_position.x -= speed;
}

if d.is_key_down(KEY_UP) && ship_position.y > 30.0 {
ship_position.y -= speed;
}
if d.is_key_down(KEY_DOWN)
&& ship_position.y < screen_height as f32 - ship_size_height as f32
{
ship_position.y += speed;
}

// lets make the bad dude move
if baddude_speed as i32 > 0
&& baddude_ship_position.x as i32 + (baddude_speed as i32) < screen_width as i32
{
baddude_ship_position.x += baddude_speed
} else {
baddude_ship_position.x = 0.0 - baddude_ship_size_width as f32;
}

// draw the baddude ship
d.draw_texture(
&bs,
baddude_ship_position.x as i32,
baddude_ship_position.y as i32,
Color::LIGHTGRAY,
);

// keep the collision rectangle up to date on baddude ship
baddude_ship_rectangle.x = baddude_ship_position.x;
baddude_ship_rectangle.y = baddude_ship_position.y;

// draw the hero ship
d.draw_texture(
&hs,
ship_position.x as i32,
ship_position.y as i32,
Color::LIGHTGRAY,
);

// keep the collision rectangle up to date on hero ship
ship_rectangle.x = ship_position.x;
ship_rectangle.y = ship_position.y;

// any collisions????
if my_check_collision_recs(ship_rectangle, baddude_ship_rectangle) {
// BOOOOM
d.draw_text("BOOM", 500, 10, 20, Color::LIGHTGRAY);
}

//scores...
d.draw_text("0", 10, 10, 20, Color::LIGHTGRAY);

}
}



pub fn my_check_collision_recs(rec1: Rectangle, rec2: Rectangle) -> bool {
if rec1.x < rec2.x + rec2.width &&
rec1.x + rec1.width > rec2.x &&
rec1.y < rec2.y + rec2.height &&
rec1.y + rec1.height > rec2.y
{
return true;
}
return false;
}

Example "gamepad input" in Rust


use raylib::prelude::GamepadNumber::*;
use raylib::prelude::*;

fn main() {
let screen_width = 800.0;
let screen_height = 450.0;

// there seems to be no SetConfigFlags() wrapped
// raylib::set_config_flags(FLAG_MSAA_4X_HINT);

let (mut rl, thread) = raylib::init()
.size(screen_width as i32, screen_height as i32)
.title("raylib [core] example - gamepad input")
.build();

rl.set_target_fps(60); // Set our game to run at 60 frames-per-second

while !rl.window_should_close() {
let mut d = rl.begin_drawing(&thread);

d.clear_background(Color::RAYWHITE);

if d.is_gamepad_available(GAMEPAD_PLAYER1 as u32) {
d.draw_text(
&format!("GP1: {:?}", d.get_gamepad_name(GAMEPAD_PLAYER1 as u32)),
10,
10,
10,
Color::BLACK,
);

d.draw_text(
&format!(
"DETECTED AXIS [{}]:",
d.get_gamepad_axis_count(GAMEPAD_PLAYER1 as u32)
),
10,
50,
10,
Color::MAROON,
);

for i in 0..d.get_gamepad_axis_count(GAMEPAD_PLAYER1 as u32) {
d.draw_text(
&format!(
"AXIS {}: {}",
i,
d.get_gamepad_axis_movement(GAMEPAD_PLAYER1 as u32, i as u32)
),
20,
70 + 20 * i,
10,
Color::DARKGRAY,
);
}

d.draw_text(
&format!("DETECTED BUTTON: {:?}", d.get_gamepad_button_pressed()),
10,
430,
10,
Color::RED,
);
} else {
d.draw_text("GP1: NOT DETECTED", 10, 10, 10, Color::GRAY);
}
}
}

Example "mouse wheel input" in Rust


https://www.raylib.com/examples/web/core/loader.html?name=core_input_mouse_wheel

The 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 - input mouse wheel");

int boxPositionY = screenHeight/2 - 40;
int scrollSpeed = 4; // Scrolling speed in pixels

SetTargetFPS(60); // Set our game to run at 60 frames-per-second

while (!WindowShouldClose()) // Detect window close button or ESC key
{
boxPositionY -= (GetMouseWheelMove()*scrollSpeed);

BeginDrawing();

ClearBackground(RAYWHITE);

DrawRectangle(screenWidth/2 - 40, boxPositionY, 80, 80, MAROON);

DrawText("Use mouse wheel to move the cube up and down!", 10, 10, 20, GRAY);
DrawText(FormatText("Box position Y: %03i", boxPositionY), 10, 40, 20, LIGHTGRAY);

EndDrawing();
}

CloseWindow(); // Close window and OpenGL context

return 0;
}



The Rust version:



use raylib::prelude::*;

fn main() {
let screen_width = 800;
let screen_height = 450;

let (mut rl, thread) = raylib::init()
.size(screen_width, screen_height)
.title("raylib [core] example - input mouse wheel")
.build();

let mut box_position_y = screen_height / 2 - 40;
let scroll_speed = 4;

rl.set_target_fps(60); // Set our game to run at 60 frames-per-second

while !rl.window_should_close() {
box_position_y -= rl.get_mouse_wheel_move() * scroll_speed;

let mut d = rl.begin_drawing(&thread);

d.clear_background(Color::RAYWHITE);

d.draw_rectangle(screen_width / 2 - 40, box_position_y, 80, 80, Color::MAROON);

d.draw_text(
"Use mouse wheel to move the cube up and down!",
10,
10,
20,
Color::DARKGRAY,
);

d.draw_text(
&format!("Box position Y: {}", box_position_y), // this is the rust equivalent to FormatText()
10,
40,
20,
Color::LIGHTGRAY,
);
}
}

Example "mouse input" in Rust


https://www.raylib.com/examples/web/core/loader.html?name=core_input_mouse

The 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 - mouse input");

Vector2 ballPosition = { -100.0f, -100.0f };
Color ballColor = DARKBLUE;

SetTargetFPS(60); // Set our game to run at 60 frames-per-second

while (!WindowShouldClose()) // Detect window close button or ESC key
{
ballPosition = GetMousePosition();

if (IsMouseButtonPressed(MOUSE_LEFT_BUTTON)) ballColor = MAROON;
else if (IsMouseButtonPressed(MOUSE_MIDDLE_BUTTON)) ballColor = LIME;
else if (IsMouseButtonPressed(MOUSE_RIGHT_BUTTON)) ballColor = DARKBLUE;

BeginDrawing();

ClearBackground(RAYWHITE);

DrawCircleV(ballPosition, 40, ballColor);

DrawText("move ball with mouse and click mouse button to change color", 10, 10, 20, DARKGRAY);

EndDrawing();
}

// De-Initialization
//--------------------------------------------------------------------------------------
CloseWindow(); // Close window and OpenGL context

return 0;
}



The Rust version:


use raylib::prelude::MouseButton::*;
use raylib::prelude::*;

fn main() {
let screen_width = 800.0;
let screen_height = 450.0;

let (mut rl, thread) = raylib::init()
.size(screen_width as i32, screen_height as i32)
.title("Raylib [core] example - mouse input")
.build();

let mut ball_color = Color::DARKBLUE;

rl.set_target_fps(60); // Set our game to run at 60 frames-per-second

while !rl.window_should_close() {
if rl.is_mouse_button_pressed(MOUSE_LEFT_BUTTON) {
ball_color = Color::MAROON;
} else if rl.is_mouse_button_pressed(MOUSE_MIDDLE_BUTTON) {
ball_color = Color::LIME;
} else if rl.is_mouse_button_pressed(MOUSE_RIGHT_BUTTON) {
ball_color = Color::DARKBLUE;
}

let mut d = rl.begin_drawing(&thread);

d.clear_background(Color::RAYWHITE);
d.draw_text(
"move ball with mouse and click mouse button to change color",
10,
10,
20,
Color::DARKGRAY,
);

d.draw_circle_v(d.get_mouse_position(), 50.0, ball_color);
}
}

Example "keyboard input" in Rust


https://www.raylib.com/examples/web/core/loader.html?name=core_input_keys

The 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 Rust version:



use raylib::prelude::KeyboardKey::*;
use raylib::prelude::*;

fn main() {
let screen_width = 800.0;
let screen_height = 450.0;

let (mut rl, thread) = raylib::init()
.size(screen_width as i32, screen_height as i32)
.title("raylib [core] example - keyboard input")
.build();

let mut ball_position = Vector2 {
x: screen_width / 2.0,
y: screen_height / 2.0,
};

rl.set_target_fps(60); // Set our game to run at 60 frames-per-second

while !rl.window_should_close() {
if rl.is_key_down(KEY_RIGHT) {
ball_position.x += 2.0;
}
if rl.is_key_down(KEY_LEFT) {
ball_position.x -= 2.0;
}
if rl.is_key_down(KEY_UP) {
ball_position.y -= 2.0;
}
if rl.is_key_down(KEY_DOWN) {
ball_position.y += 2.0;
}

let mut d = rl.begin_drawing(&thread);

d.clear_background(Color::RAYWHITE);
d.draw_text("move the ball with arrow keys", 10, 10, 20, Color::DARKGRAY);

d.draw_circle_v(ball_position, 50.0, Color::MAROON);
}
}