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