diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..4d17a00 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,52 @@ +## Contributing to raylib-python-cffi + +Hello contributors! Welcome to **raylib-python-cffi** AKA **pyray**! + +Do you enjoy pyray and want to contribute? Nice! You can help with the following points: + +- `Python programming` - Can you write/review/test/improve the code? +- `Documentation/Tutorials/Example` - Can you write some tutorial/example? +- `Porting Examples from C to Python` - Can you port the raylib examples in c to python? +- `Build For Web` - Can you help [the issue](https://github.com/electronstudio/raylib-python-cffi/issues/58)? +- `Testing` - Can you find some bugs in pyray? + +This document contains a set of guidelines to contribute to the project. These are mostly guidelines, not rules. +Use your best judgement, and feel free to propose changes to this document in a pull request. + +### raylib philosophy + + - raylib is a tool to **ENJOY** videogames programming, every function in raylib is designed as a mini-tutorial on itself. + - raylib is **SIMPLE** and **EASY-TO-USE**, I tried to keep it compact with a small set of functions, if a function is too complex, better not including it. + - raylib is open source and free; educators and institutions can use this tool to **TEACH** videogames programming completely for free. + - raylib is collaborative; contribution of tutorials / code examples / bug fixes / code comments are highly appreciated. + - raylib's license (and its external libs respective licenses) allow using raylib on commercial projects. + +### raylib python coding conventions + +Despite being written in C, pyray is a python bindings for raylib. so the conventions are also python independent +look at [Python API Coding Style Conventions](https://github.com/raysan5/raylib/wiki/raylib-coding-conventions), + +Source code is extensively commented for that purpose, raylib primary learning method is: + + > `Learn by reading code and examples` + +### Opening new Issues + +To open new issue for raylib (bug, enhancement, discussion...), just try to follow these rules: + + - Make sure the issue has not already been reported before by searching on GitHub under Issues. + - If you're unable to find an open issue addressing the problem, open a new one. Be sure to include a + title and clear description, as much relevant information as possible, and a code sample demonstrating the unexpected behavior. + - If applies, attach some screenshot of the issue and a .zip file with the code sample and required resources. + - On issue description, add a brackets tag about the raylib module that relates to this issue. + If don't know which module, just report the issue, I will review it. + - You can check other issues to see how is being done! + +### Sending a Pull-Request + + - Make sure the PR description clearly describes the problem and solution. Include the relevant issue number if applicable. + - Don't send big pull requests (lots of changelists), they are difficult to review. It's better to send small pull requests, one at a time. + - Verify that changes don't break the build (at least on Windows platform). As many platforms where you can test it, the better, but don't worry + if you cannot test all the platforms. + +Thank you very much for your time! :) diff --git a/PYTHON_API_CONVENTIONS.md b/PYTHON_API_CONVENTIONS.md new file mode 100644 index 0000000..a990e6c --- /dev/null +++ b/PYTHON_API_CONVENTIONS.md @@ -0,0 +1,193 @@ +## Python API Coding Style Conventions + +Here is a list with some code conventions used by raylib in python: + +| Code element | Convention | Example | +|---------------------|:-----------------------------------:|-------------------------------------------| +| Variables | lower_case | `delta_time = 0`, `player_age = 18` | +| Local variables | lower_case | `player_position = Vector2(0, 0)` | +| Global variables | lower_case | `window_ready = False` | +| Constants variables | ALL_CAPS | `MAX_VALUE = 8`, `SCREEN_WIDTH = 800` | +| Definitions values | ALL_CAPS | `MAX_BUILDINGS = 5`[^1] | +| string values | always "" | `output = "Hello"`, `"welcome"` | +| float values | always x.x | `gravity = 10.0` | +| Operators | value1 * value2 | `product = value * 6` | +| Operators | value1 / value2 | `division = value / 4` | +| Operators | value1 + value2 | `sum = value + 10` | +| Operators | value1 - value2 | `res = value - 5` | +| Class | TitleCase | `class TextureFormat` | +| Enum Class members | ALL_CAPS | `PIXELFORMAT_UNCOMPRESSED_R8G8B8` | +| Class members | lowerCase | `texture.width`, `color.r` | +| Functions | lowerCase & wordSeparationBy_ | `init_window()`, `update_camera_center()` | +| Functions params | lowerCase | `width`, `height` | +| Ternary Operator | result1 if condition else result2 | `print("yes" if value == 0 else "no")` | +[^1] like `macro definitions` of value in C + +Some other conventions to follow: + - **ALWAYS** initialize all defined variables. + - **use TABS / 4 spaces**. + - Avoid trailing spaces, please, avoid them + - Avoid using **semicolon** as you can + - Control flow statements always are followed **by a space**: +```python +if condition : value = 0 + +while not window_should_close(): + #Do something here! + +for i in range(NUM_VALUES): print(i) +``` + - All conditions checks are **always between parenthesis** but not boolean values: +```python +if value > 1 and value1 < 50 and valueActive: + #Do something here! +``` + +**If proposing new functions, please try to use a clear naming for function-name and functions-parameters, in case of doubt, open an issue for discussion.** + +## Import libraries and Module + - import libraries with the form `from library import *` + - import modules/variables from libraries with the form `from library import (module1, ..., variable1, ...)` +```python +from pyray import * +from raylib.colors import ( + RAYWHITE, + DARKGRAY, + ... +) +``` + +## Files and Directories Naming Conventions + + - Directories will be named using `snake_case`: `resources/models`, `resources/fonts` + + - Files will be named using `snake_case`: `main_title.png`, `cubicmap.png`, `sound.wav` + +_NOTE: Avoid any space or special character in the files/dir naming!_ + +## Games/Examples Directories Organization Conventions + + - Data files should be organized by context and usage in the game, think about the loading requirements for data and put all the resources that need to be loaded at the same time together. + - Use descriptive names for the files, it would be perfect if just reading the name of the file, it was possible to know what is that file and where fits in the game. + - Here is an example, note that some resources require to be loaded all at once while other require to be loaded only at initialization (gui, font). + +``` +resources/audio/fx/long_jump.wav +resources/audio/music/main_theme.ogg +resources/screens/logo/logo.png +resources/screens/title/title.png +resources/screens/gameplay/background.png +resources/characters/player.png +resources/characters/enemy_slime.png +resources/common/font_arial.ttf +resources/common/gui.png +``` + +## Example Conventions For Python API + - examples ***should*** have the following structure +```python +""" + +raylib [raylib module] example - Name Of The Example + +""" + +# Import +# ------------------------------------------------------------------------------------ +# Do something here! +# ------------------------------------------------------------------------------------ + +# Definitions +# ------------------------------------------------------------------------------------ +# Define you functions/global variables here +# ------------------------------------------------------------------------------------ + +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ------------------------------------------------------------------------------------ + # Do something here! + # ------------------------------------------------------------------------------------ + + # Main game loop + while ... : + # Update + # ---------------------------------------------------------------------------------- + # Do something here! + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + # Do something here! + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + # Do something here! + # ---------------------------------------------------------------------------------- + +# Execute the main function +if __name__ == '__main__': + main() +``` + - temple (basic window example): +```python +""" + +raylib [core] example - Basic Window + +""" + +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ------------------------------------------------------------------------------------ + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - basic window") + + # TODO: Load resources / Initialize variables at this point + + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ------------------------------------------------------------------------------------ + + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + # TODO: Update variables / Implement example logic at this point + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + + clear_background(RAYWHITE) + draw_text("Congrats! You created your first window!", 190, 200, 20, LIGHTGRAY) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + + # TODO: Unload all loaded resources at this point + + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + + +# Execute the main function +if __name__ == '__main__': + main() + +``` diff --git a/examples/core/core_2d_camera.py b/examples/core/core_2d_camera.py index e70b516..3ce80d0 100644 --- a/examples/core/core_2d_camera.py +++ b/examples/core/core_2d_camera.py @@ -1,10 +1,12 @@ """ -raylib [core] example - 2d camera +raylib [core] example - 2D Camera """ -import pyray +# Import +# ------------------------------------------------------------------------------------ +from pyray import * from raylib.colors import ( RAYWHITE, DARKGRAY, @@ -14,125 +16,131 @@ BLUE, BLACK, ) +# ------------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + MAX_BUILDINGS = 100 + screenWidth = 800 + screenHeight = 450 + init_window(screenWidth, screenHeight, "raylib [core] example - 2d camera") + player = Rectangle(400, 280, 40, 40) + buildings = [] + build_colors = [] + spacing = 0 -# Initialization -MAX_BUILDINGS = 100 -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, - 'raylib [core] example - 2d camera') - -player = pyray.Rectangle(400, 280, 40, 40) -buildings = [] -build_colors = [] -spacing = 0 - -for i in range(MAX_BUILDINGS): - width = pyray.get_random_value(50, 200) - height = pyray.get_random_value(100, 800) - y = SCREEN_HEIGHT - 130 - height - x = -6000 + spacing - - buildings.append(pyray.Rectangle(x, y, width, height)) + for i in range(MAX_BUILDINGS): + width = get_random_value(50, 200) + height = get_random_value(100, 800) + y = screenHeight - 130 - height + x = -6000 + spacing - spacing += width + buildings.append(Rectangle(x, y, width, height)) - build_colors.append(pyray.Color( - pyray.get_random_value(200, 240), - pyray.get_random_value(200, 240), - pyray.get_random_value(200, 250), - 255 - )) + spacing += width -camera = pyray.Camera2D() -camera.target = pyray.Vector2(player.x + 20, player.y + 20) -camera.offset = pyray.Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) -camera.rotation = 0.0 -camera.zoom = 1.0 + build_colors.append(Color(get_random_value(200, 240), get_random_value(200, 240), get_random_value(200, 250), 255)) -pyray.set_target_fps(60) # Set our game to run at 60 frames-per-second + camera = Camera2D() + camera.target = Vector2(player.x + 20, player.y + 20) + camera.offset = Vector2(screenWidth / 2, screenHeight / 2) + camera.rotation = 0.0 + camera.zoom = 1.0 + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- -# Main game loop -while not pyray.window_should_close(): # Detect window close button or ESC key - # Update + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + # Player movement + if is_key_down(KeyboardKey.KEY_RIGHT): + player.x += 2 + elif is_key_down(KeyboardKey.KEY_LEFT): + player.x -= 2 - # Player movement - if pyray.is_key_down(pyray.KEY_RIGHT): - player.x += 2 - elif pyray.is_key_down(pyray.KEY_LEFT): - player.x -= 2 + # Camera target follows player + camera.target = Vector2(player.x + 20, player.y + 20) - # Camera target follows player - camera.target = pyray.Vector2(player.x + 20, player.y + 20) + # Camera rotation controls + if is_key_down(KeyboardKey.KEY_A): + camera.rotation -= 1 + elif is_key_down(KeyboardKey.KEY_S): + camera.rotation += 1 - # Camera rotation controls - if pyray.is_key_down(pyray.KEY_A): - camera.rotation -= 1 - elif pyray.is_key_down(pyray.KEY_S): - camera.rotation += 1 + # Limit camera rotation to 80 degrees (-40 to 40) + if camera.rotation > 40: + camera.rotation = 40 + elif camera.rotation < -40: + camera.rotation = -40 - # Limit camera rotation to 80 degrees (-40 to 40) - if camera.rotation > 40: - camera.rotation = 40 - elif camera.rotation < -40: - camera.rotation = -40 + # Camera zoom controls + camera.zoom += get_mouse_wheel_move() * 0.05 - # Camera zoom controls - camera.zoom += pyray.get_mouse_wheel_move() * 0.05 + if camera.zoom > 3.0: + camera.zoom = 3.0 + elif camera.zoom < 0.1: + camera.zoom = 0.1 - if camera.zoom > 3.0: - camera.zoom = 3.0 - elif camera.zoom < 0.1: - camera.zoom = 0.1 + # Camera reset (zoom and rotation) + if is_key_pressed(KeyboardKey.KEY_R): + camera.zoom = 1.0 + camera.rotation = 0.0 + # ---------------------------------------------------------------------------------- - # Camera reset (zoom and rotation) - if pyray.is_key_pressed(pyray.KEY_R): - camera.zoom = 1.0 - camera.rotation = 0.0 + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + clear_background(RAYWHITE) - # Draw - pyray.begin_drawing() - pyray.clear_background(RAYWHITE) + begin_mode_2d(camera) - pyray.begin_mode_2d(camera) + draw_rectangle(-6000, 320, 13000, 8000, DARKGRAY) - pyray.draw_rectangle(-6000, 320, 13000, 8000, DARKGRAY) + for i in range(MAX_BUILDINGS): + draw_rectangle_rec(buildings[i], build_colors[i]) - for i in range(MAX_BUILDINGS): - pyray.draw_rectangle_rec(buildings[i], build_colors[i]) + draw_rectangle_rec(player, RED) - pyray.draw_rectangle_rec(player, RED) + x = int(camera.target.x) + y = int(camera.target.y) + draw_line(x, -screenHeight * 10, x, screenHeight * 10, GREEN) + draw_line(-screenWidth * 10, y, screenWidth * 10, y, GREEN) - x = int(camera.target.x) - y = int(camera.target.y) - pyray.draw_line(x, -SCREEN_HEIGHT * 10, x, SCREEN_HEIGHT * 10, GREEN) - pyray.draw_line(-SCREEN_WIDTH * 10, y, SCREEN_WIDTH * 10, y, GREEN) + end_mode_2d() - pyray.end_mode_2d() + draw_text('SCREEN AREA', 640, 10, 20, RED) - pyray.draw_text('SCREEN AREA', 640, 10, 20, RED) + draw_rectangle(0, 0, screenWidth, 5, RED) + draw_rectangle(0, 5, 5, screenHeight - 10, RED) + draw_rectangle(screenWidth - 5, 5, 5, screenHeight - 10, RED) + draw_rectangle(0, screenHeight - 5, screenWidth, 5, RED) - pyray.draw_rectangle(0, 0, SCREEN_WIDTH, 5, RED) - pyray.draw_rectangle(0, 5, 5, SCREEN_HEIGHT - 10, RED) - pyray.draw_rectangle(SCREEN_WIDTH - 5, 5, 5, SCREEN_HEIGHT - 10, RED) - pyray.draw_rectangle(0, SCREEN_HEIGHT - 5, SCREEN_WIDTH, 5, RED) + draw_rectangle(10, 10, 250, 113, fade(SKYBLUE, 0.5)) + draw_rectangle_lines(10, 10, 250, 113, BLUE) - pyray.draw_rectangle(10, 10, 250, 113, pyray.fade(SKYBLUE, 0.5)) - pyray.draw_rectangle_lines(10, 10, 250, 113, BLUE) + draw_text('Free 2d camera controls:', 20, 20, 10, BLACK) + draw_text('- Right/Left to move Offset', 40, 40, 10, DARKGRAY) + draw_text('- Mouse Wheel to Zoom in-out', 40, 60, 10, DARKGRAY) + draw_text('- A / S to Rotate', 40, 80, 10, DARKGRAY) + draw_text('- R to reset Zoom and Rotation', 40, 100, 10, DARKGRAY) - pyray.draw_text('Free 2d camera controls:', 20, 20, 10, BLACK) - pyray.draw_text('- Right/Left to move Offset', 40, 40, 10, DARKGRAY) - pyray.draw_text('- Mouse Wheel to Zoom in-out', 40, 60, 10, DARKGRAY) - pyray.draw_text('- A / S to Rotate', 40, 80, 10, DARKGRAY) - pyray.draw_text('- R to reset Zoom and Rotation', 40, 100, 10, DARKGRAY) + end_drawing() + # ---------------------------------------------------------------------------------- - pyray.end_drawing() + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- -# De-Initialization -pyray.close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/core/core_2d_camera_mouse_zoom.py b/examples/core/core_2d_camera_mouse_zoom.py index ad4e1b9..eda59a3 100644 --- a/examples/core/core_2d_camera_mouse_zoom.py +++ b/examples/core/core_2d_camera_mouse_zoom.py @@ -1,67 +1,92 @@ """ -raylib [core] example - 2d camera mouse zoom + +raylib [core] example - 2D Camera Mouse Zoom + """ -import pyray +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + screenWidth = 800 + screenHeight = 450 -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 + init_window(screenWidth, screenHeight, "raylib [core] example - 2d camera mouse zoom") -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - 2d camera mouse zoom") + camera = Camera2D() + camera.zoom = 1.0 -pyray.set_target_fps(60) + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- -camera = pyray.Camera2D() + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + # Translate based on mouse right click + if is_mouse_button_down(MouseButton.MOUSE_BUTTON_RIGHT): + delta = get_mouse_delta() + delta = vector2_scale(delta, -1.0 / camera.zoom) + camera.target = vector2_add(camera.target, delta) -camera = pyray.Camera2D() -camera.zoom = 1.0 + # zoom based on mouse wheel + wheel = get_mouse_wheel_move() + if wheel != 0: + # Get the world point that is under the mouse + mouseWorldPos = get_screen_to_world_2d(get_mouse_position(), camera) -pyray.set_target_fps(60); + # Set the offset to where the mouse is + camera.offset = get_mouse_position() -# main game loop -while not pyray.window_should_close(): - # update - if pyray.is_mouse_button_down(pyray.MOUSE_BUTTON_RIGHT): - delta = pyray.get_mouse_delta() - delta = pyray.vector2_scale(delta, -1.0 / camera.zoom) - camera.target = pyray.vector2_add(camera.target, delta) + # Set the target to match, so that the camera maps the world space point + # under the cursor to the screen space point under the cursor at any zoom + camera.target = mouseWorldPos - # zoom based on mouse wheel - wheel = pyray.get_mouse_wheel_move() - if wheel != 0: + # Zoom increment + zoomIncrement = 0.125 - mouseWorldPos = pyray.get_screen_to_world_2d(pyray.get_mouse_position(), camera) - - camera.offset = pyray.get_mouse_position() + camera.zoom += wheel * zoomIncrement + if camera.zoom < zoomIncrement: camera.zoom = zoomIncrement - camera.target = mouseWorldPos + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - ZOOM_INCREMENT = 0.125 + clear_background(BLACK) - camera.zoom += (wheel*ZOOM_INCREMENT) - if (camera.zoom < ZOOM_INCREMENT): camera.zoom = ZOOM_INCREMENT + begin_mode_2d(camera) + # Draw the 3d grid, rotated 90 degrees and centered around 0,0 + # just so we have something in the XY plane + rl_push_matrix() + rl_translatef(0, 25*50, 0) + rl_rotatef(90, 1, 0, 0) + draw_grid(100, 50) + rl_pop_matrix() - # draw - pyray.begin_drawing() - pyray.clear_background(pyray.BLACK) + # Draw a reference circle + draw_circle(100, 100, 50, YELLOW) - pyray.begin_mode_2d(camera) + end_mode_2d() - pyray.rl_push_matrix() - pyray.rl_translatef(0, 25*50, 0) - pyray.rl_rotatef(90, 1, 0, 0) - pyray.draw_grid(100, 50) - pyray.rl_pop_matrix() + draw_text("Mouse right button drag to move, mouse wheel to zoom", 10, 10, 20, WHITE) - pyray.draw_circle(100, 100, 50, pyray.YELLOW) - - pyray.end_mode_2d() + end_drawing() + # ---------------------------------------------------------------------------------- - pyray.draw_text("Mouse right button drag to move, mouse wheel to zoom", 10, 10, 20, pyray.WHITE); - - pyray.end_drawing() + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- -# de-Initialization -pyray.close_window() +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/core/core_2d_camera_platformer.py b/examples/core/core_2d_camera_platformer.py index a4e7648..88eaa3d 100644 --- a/examples/core/core_2d_camera_platformer.py +++ b/examples/core/core_2d_camera_platformer.py @@ -1,88 +1,46 @@ """ -raylib [core] example - 2d camera platformer +raylib [core] example - 2D Camera Platformer """ -from math import sqrt -import pyray -from raylib.colors import ( - DARKGRAY, - RED, - BLACK, - GRAY, - LIGHTGRAY, -) - - - -# Initialization -global g_evening_out, g_even_out_target -g_evening_out = False +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ +# Definitions +# ------------------------------------------------------------------------------------ G = 400 PLAYER_JUMP_SPD = 350.0 PLAYER_HOR_SPD = 200.0 -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, - 'raylib [core] example - 2d camera') - - -# Raylib Math -def vector2_subtract(v1, v2): - return pyray.Vector2(v1.x - v2.x, v1.y - v2.y) - - -def vector2_add(v1, v2): - return pyray.Vector2(v1.x + v2.x, v1.y + v2.y) - - -def vector2_length(v): - return sqrt((v.x * v.x) + (v.y * v.y)) - - -def vector2_scale(v, scale): - return pyray.Vector2(v.x * scale, v.y * scale) - - class Player: - - def __init__(self, position, speed, can_jump): + def __init__(self, position, speed, canJump): self.position = position self.speed = speed - self.can_jump = can_jump + self.canJump = canJump class EnvItem: - def __init__(self, rect, blocking, color): self.rect = rect self.blocking = blocking self.color = color - def update_player(player, env_items, delta): - if pyray.is_key_down(pyray.KEY_LEFT): + if is_key_down(KeyboardKey.KEY_LEFT): player.position.x -= PLAYER_HOR_SPD * delta - if pyray.is_key_down(pyray.KEY_RIGHT): + if is_key_down(KeyboardKey.KEY_RIGHT): player.position.x += PLAYER_HOR_SPD * delta - if pyray.is_key_down(pyray.KEY_SPACE) and player.can_jump: + if is_key_down(KeyboardKey.KEY_SPACE) and player.canJump: player.speed = -PLAYER_JUMP_SPD - player.can_jump = False + player.canJump = False hit_obstacle = False for ei in env_items: p = player.position - if ( - ei.blocking and - ei.rect.x <= p.x and - ei.rect.x + ei.rect.width >= p.x and - ei.rect.y >= p.y and - ei.rect.y < p.y + player.speed * delta - ): + if ei.blocking and ei.rect.x <= p.x <= ei.rect.x + ei.rect.width and p.y <= ei.rect.y < p.y + player.speed * delta: hit_obstacle = True player.speed = 0.0 p.y = ei.rect.y @@ -90,23 +48,16 @@ def update_player(player, env_items, delta): if not hit_obstacle: player.position.y += player.speed * delta player.speed += G * delta - player.can_jump = False + player.canJump = False else: - player.can_jump = True - + player.canJump = True -def update_camera_center( - camera, player, env_items, delta, width, height -): - camera.offset = pyray.Vector2(width / 2, height / 2) +def update_camera_center(camera, player, env_items, delta, width, height): + camera.offset = Vector2(width / 2, height / 2) camera.target = player.position - - -def update_camera_center_inside_map( - camera, player, env_items, delta, width, height -): +def update_camera_center_inside_map(camera, player, env_items, delta, width, height): camera.target = player.position - camera.offset = pyray.Vector2(width / 2, height / 2) + camera.offset = Vector2(width / 2, height / 2) minX = 1000 minY = 1000 @@ -120,8 +71,8 @@ def update_camera_center_inside_map( minY = min(ei.rect.y, minY) maxY = max(ei.rect.y + ei.rect.height, maxY) - wmax = pyray.get_world_to_screen_2d(pyray.Vector2(maxX, maxY), camera) - wmin = pyray.get_world_to_screen_2d(pyray.Vector2(minX, minY), camera) + wmax = get_world_to_screen_2d(Vector2(maxX, maxY), camera) + wmin = get_world_to_screen_2d(Vector2(minX, minY), camera) if wmax.x < width: camera.offset.x = width - (wmax.x - width / 2) @@ -132,182 +83,168 @@ def update_camera_center_inside_map( if wmin.y > 0: camera.offset.y = height / 2 - wmin.y - -def update_camera_center_smooth_follow( - camera, player, env_items, delta, width, height -): - min_speed = 30 - min_effect_length = 10 +def update_camera_center_smooth_follow(camera, player, env_items, delta, width, height): + minSpeed = 30 + minEffectLength = 10 fraction_speed = 0.8 - camera.offset = pyray.Vector2(width / 2, height / 2) + camera.offset = Vector2(width / 2, height / 2) diff = vector2_subtract(player.position, camera.target) length = vector2_length(diff) - if length > min_effect_length: - speed = max(fraction_speed * length, min_speed) - camera.target = vector2_add( - camera.target, vector2_scale(diff, speed * delta / length) - ) + if length > minEffectLength: + speed = max(fraction_speed * length, minSpeed) + camera.target = vector2_add(camera.target, vector2_scale(diff, speed * delta / length)) +def update_camera_even_out_on_landing(camera, player, env_items, delta, width, height): + evenOutSpeed = 700.0 + eveningOut = False + evenOutTarget = 0.0 -def update_camera_even_out_on_landing( - camera, player, env_items, delta, width, height -): - global g_evening_out, g_even_out_target - - even_out_speed = 700 - - camera.offset = pyray.Vector2(width / 2, height / 2) + camera.offset = Vector2(width / 2, height / 2) camera.target.x = player.position.x - if g_evening_out: - if g_even_out_target > camera.target.y: - camera.target.y += even_out_speed * delta + if eveningOut: + if evenOutTarget > camera.target.y: + camera.target.y += evenOutSpeed * delta - if camera.target.y > g_even_out_target: - camera.target.y = g_even_out_target - g_evening_out = False + if camera.target.y > evenOutTarget: + camera.target.y = evenOutTarget + eveningOut = False else: - camera.target.y -= even_out_speed * delta - if camera.target.y < g_even_out_target: - camera.target.y = g_even_out_target - g_evening_out = False + camera.target.y -= evenOutSpeed * delta + if camera.target.y < evenOutTarget: + camera.target.y = evenOutTarget + eveningOut = False else: - if ( - player.can_jump and - (player.speed == 0) and - (player.position.y != camera.target.y) - ): - g_evening_out = True - g_even_out_target = player.position.y - - -def update_camera_player_bounds_push( - camera, player, env_items, delta, width, height -): - bbox = pyray.Vector2(0.2, 0.2) - - bbox_world_min = pyray.get_world_to_screen_2d( - pyray.Vector2((1 - bbox.x) * 0.5 * width, - (1 - bbox.y) * 0.5 * height), - camera - ) - bbox_world_max = pyray.get_world_to_screen_2d( - pyray.Vector2((1 + bbox.x) * 0.5 * width, - (1 + bbox.y) * 0.5 * height), - camera - ) - camera.offset = pyray.Vector2((1 - bbox.x) * 0.5 * width, - (1 - bbox.y) * 0.5 * height) + if (player.can_jump and player.speed == 0) and (player.position.y != camera.target.y): + eveningOut = True + evenOutTarget = player.position.y + +def update_camera_player_bounds_push(camera, player, env_items, delta, width, height): + bbox = Vector2(0.2, 0.2) + + bboxWorldMin = get_world_to_screen_2d(Vector2((1 - bbox.x) * 0.5 * width, (1 - bbox.y) * 0.5 * height), camera) + bbox_world_max = get_world_to_screen_2d(Vector2((1 + bbox.x) * 0.5 * width,(1 + bbox.y) * 0.5 * height), camera) + camera.offset = Vector2((1 - bbox.x) * 0.5 * width, (1 - bbox.y) * 0.5 * height) - if player.position.x < bbox_world_min.x: + if player.position.x < bboxWorldMin.x: camera.target.x = player.position.x - if player.position.y < bbox_world_min.y: + if player.position.y < bboxWorldMin.y: camera.target.y = player.position.y if player.position.x > bbox_world_max.x: - camera.target.x = ( - bbox_world_min.x + (player.position.x - bbox_world_max.x) - ) + camera.target.x = bboxWorldMin.x + (player.position.x - bbox_world_max.x) if player.position.y > bbox_world_max.y: - camera.target.y = ( - bbox_world_min.y + (player.position.y - bbox_world_max.y) - ) - - -# Main intialization -player = Player(pyray.Vector2(400, 280), 0, False) -env_items = ( - EnvItem(pyray.Rectangle(0, 0, 1000, 400), 0, LIGHTGRAY), - EnvItem(pyray.Rectangle(0, 400, 1000, 200), 1, GRAY), - EnvItem(pyray.Rectangle(300, 200, 400, 10), 1, GRAY), - EnvItem(pyray.Rectangle(250, 300, 100, 10), 1, GRAY), - EnvItem(pyray.Rectangle(650, 300, 100, 10), 1, GRAY), -) - -camera = pyray.Camera2D() -camera.target = player.position -camera.offset = pyray.Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) -camera.rotation = 0.0 -camera.zoom = 1.0 - -pyray.set_target_fps(60) # Set our game to run at 60 frames-per-second - -# Store pointers to the multiple update camera functions -camera_updaters = ( - update_camera_center, - update_camera_center_inside_map, - update_camera_center_smooth_follow, - update_camera_even_out_on_landing, - update_camera_player_bounds_push, -) -camera_option = 0 -camera_updaters_length = len(camera_updaters) - -camera_descriptions = ( - 'Follow player center', - 'Follow player center, but clamp to map edges', - 'Follow player center smoothed', - ('Follow player center horizontally ' - 'update player center vertically after landing'), - 'Player push camera on getting too close to screen edge', -) - -# Main game loop -while not pyray.window_should_close(): # Detect window close button or ESC key - # Update - delta_time = pyray.get_frame_time() - - update_player(player, env_items, delta_time) - - camera.zoom += pyray.get_mouse_wheel_move() * 0.05 - - if camera.zoom > 3.0: - camera.zoom = 3.0 - elif camera.zoom < 0.25: - camera.zoom = 0.25 - - if pyray.is_key_pressed(pyray.KEY_R): - camera.zoom = 1.0 - player.position = pyray.Vector2(400, 280) - - if pyray.is_key_pressed(pyray.KEY_C): - camera_option = (camera_option + 1) % camera_updaters_length - - # Call update camera function by its pointer - camera_updaters[camera_option]( - camera, player, env_items, delta_time, - SCREEN_WIDTH, SCREEN_HEIGHT + camera.target.y = bboxWorldMin.y + (player.position.y - bbox_world_max.y) +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + screenWidth = 800 + screenHeight = 450 + + init_window(screenWidth, screenHeight, "raylib [core] example - 2d camera") + + player = Player(Vector2(400, 280), 0, False) + envItems = ( + EnvItem(Rectangle(0, 0, 1000, 400), 0, LIGHTGRAY), + EnvItem(Rectangle(0, 400, 1000, 200), 1, GRAY), + EnvItem(Rectangle(300, 200, 400, 10), 1, GRAY), + EnvItem(Rectangle(250, 300, 100, 10), 1, GRAY), + EnvItem(Rectangle(650, 300, 100, 10), 1, GRAY), ) - # Draw - pyray.begin_drawing() - pyray.clear_background(LIGHTGRAY) + camera = Camera2D() + camera.target = player.position + camera.offset = Vector2(screenWidth / 2, screenHeight / 2) + camera.rotation = 0.0 + camera.zoom = 1.0 + + # Store pointers to the multiple update camera functions + cameraUpdaters = ( + update_camera_center, + update_camera_center_inside_map, + update_camera_center_smooth_follow, + update_camera_even_out_on_landing, + update_camera_player_bounds_push, + ) + cameraOption = 0 + cameraUpdatersLength = len(cameraUpdaters) + + cameraDescriptions = ( + "Follow player center", + "Follow player center, but clamp to map edges", + "Follow player center smoothed", + ("Follow player center horizontally " + "update player center vertically after landing"), + "Player push camera on getting too close to screen edge", + ) - pyray.begin_mode_2d(camera) + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- - for env_item in env_items: - pyray.draw_rectangle_rec(env_item.rect, env_item.color) + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + delta_time = get_frame_time() - player_rect = pyray.Rectangle( - int(player.position.x) - 20, - int(player.position.y) - 40, - 40, 40 - ) - pyray.draw_rectangle_rec(player_rect, RED) + update_player(player, envItems, delta_time) + + camera.zoom += get_mouse_wheel_move() * 0.05 + + if camera.zoom > 3.0: + camera.zoom = 3.0 + elif camera.zoom < 0.25: + camera.zoom = 0.25 + + if is_key_pressed(KeyboardKey.KEY_R): + camera.zoom = 1.0 + player.position = Vector2(400, 280) + + if is_key_pressed(KeyboardKey.KEY_C): + cameraOption = (cameraOption + 1) % cameraUpdatersLength + + # Call update camera function by its pointer + cameraUpdaters[cameraOption](camera, player, envItems, delta_time, screenWidth, screenHeight) + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + clear_background(LIGHTGRAY) + + begin_mode_2d(camera) + + for envItem in envItems: + draw_rectangle_rec(envItem.rect, envItem.color) + + player_rect = Rectangle(player.position.x - 20, player.position.y - 40, 40, 40) + draw_rectangle_rec(player_rect, RED) + + end_mode_2d() + + draw_text("Controls:", 20, 20, 10, BLACK) + draw_text("- Right/Left to move", 40, 40, 10, DARKGRAY) + draw_text("- Space to jump", 40, 60, 10, DARKGRAY) + draw_text("- Mouse Wheel to Zoom in-out, R to reset zoom", 40, 80, 10, DARKGRAY) + draw_text("- C to change camera mode", 40, 100, 10, DARKGRAY) + draw_text("Current camera mode:", 20, 120, 10, BLACK) + draw_text(cameraDescriptions[cameraOption], 40, 140, 10, DARKGRAY) - pyray.end_mode_2d() + end_drawing() + # ---------------------------------------------------------------------------------- - pyray.draw_text('Controls:', 20, 20, 10, BLACK) - pyray.draw_text('- Right/Left to move', 40, 40, 10, DARKGRAY) - pyray.draw_text('- Space to jump', 40, 60, 10, DARKGRAY) - pyray.draw_text('- Mouse Wheel to Zoom in-out, R to reset zoom', - 40, 80, 10, DARKGRAY) - pyray.draw_text('- C to change camera mode', 40, 100, 10, DARKGRAY) - pyray.draw_text('Current camera mode:', 20, 120, 10, BLACK) - pyray.draw_text(camera_descriptions[camera_option], 40, 140, 10, DARKGRAY) + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- - pyray.end_drawing() -# De-Initialization -pyray.close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/core/core_input_gestures.py b/examples/core/core_input_gestures.py index 44b7e79..c8f2519 100644 --- a/examples/core/core_input_gestures.py +++ b/examples/core/core_input_gestures.py @@ -3,101 +3,105 @@ raylib [core] example - Input Gestures Detection """ -import pyray -from raylib.colors import ( - RAYWHITE, - LIGHTGRAY, - DARKGRAY, - MAROON, - GRAY, -) +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ - -# Initialization +# Definitions +# ------------------------------------------------------------------------------------ MAX_GESTURE_STRINGS = 20 -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, - 'raylib [core] example - input gestures') - -touch_position = pyray.Vector2(0, 0) -touch_area = pyray.Rectangle(220, 10, SCREEN_WIDTH - 230, SCREEN_HEIGHT - 20) - -gesture_strings = [] - -current_gesture = pyray.GESTURE_NONE -last_gesture = pyray.GESTURE_NONE - -GESTURE_LABELS = { - pyray.GESTURE_TAP: 'GESTURE TAP', - pyray.GESTURE_DOUBLETAP: 'GESTURE DOUBLETAP', - pyray.GESTURE_HOLD: 'GESTURE HOLD', - pyray.GESTURE_DRAG: 'GESTURE DRAG', - pyray.GESTURE_SWIPE_RIGHT: 'GESTURE SWIPE RIGHT', - pyray.GESTURE_SWIPE_LEFT: 'GESTURE SWIPE LEFT', - pyray.GESTURE_SWIPE_UP: 'GESTURE SWIPE UP', - pyray.GESTURE_SWIPE_DOWN: 'GESTURE SWIPE DOWN', - pyray.GESTURE_PINCH_IN: 'GESTURE PINCH IN', - pyray.GESTURE_PINCH_OUT: 'GESTURE PINCH OUT', -} - -pyray.set_target_fps(60) # Set our game to run at 60 frames-per-second - - -# Main game loop -while not pyray.window_should_close(): # Detect window close button or ESC key - # Update - last_gesture = current_gesture - current_gesture = pyray.get_gesture_detected() - touch_position = pyray.get_touch_position(0) - - if ( - pyray.check_collision_point_rec(touch_position, touch_area) - and current_gesture != pyray.GESTURE_NONE - ): - if current_gesture != last_gesture: - gesture_strings.append(GESTURE_LABELS[current_gesture]) - - # Reset gestures strings - if len(gesture_strings) >= MAX_GESTURE_STRINGS: - gesture_strings = [] - - # Draw - pyray.begin_drawing() - - pyray.clear_background(RAYWHITE) - - pyray.draw_rectangle_rec(touch_area, GRAY) - pyray.draw_rectangle(225, 15, SCREEN_WIDTH - 240, SCREEN_HEIGHT - 30, - RAYWHITE) - pyray.draw_text( - 'GESTURES TEST AREA', - SCREEN_WIDTH - 270, SCREEN_HEIGHT - 40, 20, pyray.fade(GRAY, 0.5) - ) - - for i, val in enumerate(gesture_strings): - if i % 2 == 0: - pyray.draw_rectangle( - 10, 30 + 20 * i, 200, 20, pyray.fade(LIGHTGRAY, 0.5)) - else: - pyray.draw_rectangle( - 10, 30 + 20 * i, 200, 20, pyray.fade(LIGHTGRAY, 0.3)) - - if i < len(gesture_strings) - 1: - pyray.draw_text(val, 35, 36 + 20 * i, 10, DARKGRAY) - else: - pyray.draw_text(val, 35, 36 + 20 * i, 10, MAROON) - - pyray.draw_rectangle_lines(10, 29, 200, SCREEN_HEIGHT - 50, GRAY) - pyray.draw_text('DETECTED GESTURES', 50, 15, 10, GRAY) - - if current_gesture != pyray.GESTURE_NONE: - pyray.draw_circle_v(touch_position, 30, MAROON) - - pyray.end_drawing() - - -# De-Initialization -pyray.close_window() # Close window and OpenGL context +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - input gestures") + + touch_position = Vector2(0, 0) + touch_area = Rectangle(220, 10, SCREEN_WIDTH - 230, SCREEN_HEIGHT - 20) + + gesture_strings = [] + + current_gesture = Gesture.GESTURE_NONE + last_gesture = Gesture.GESTURE_NONE + + GESTURE_LABELS = { + Gesture.GESTURE_TAP: "GESTURE TAP", + Gesture.GESTURE_DOUBLETAP: "GESTURE DOUBLETAP", + Gesture.GESTURE_HOLD: "GESTURE HOLD", + Gesture.GESTURE_DRAG: "GESTURE DRAG", + Gesture.GESTURE_SWIPE_RIGHT: "GESTURE SWIPE RIGHT", + Gesture.GESTURE_SWIPE_LEFT: "GESTURE SWIPE LEFT", + Gesture.GESTURE_SWIPE_UP: "GESTURE SWIPE UP", + Gesture.GESTURE_SWIPE_DOWN: "GESTURE SWIPE DOWN", + Gesture.GESTURE_PINCH_IN: "GESTURE PINCH IN", + Gesture.GESTURE_PINCH_OUT: "GESTURE PINCH OUT", + } + + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- + + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + last_gesture = current_gesture + current_gesture = get_gesture_detected() + touch_position = get_touch_position(0) + + if check_collision_point_rec(touch_position, touch_area) and current_gesture != Gesture.GESTURE_NONE: + if current_gesture != last_gesture: + gesture_strings.append(GESTURE_LABELS[current_gesture]) + + # Reset gestures strings + if len(gesture_strings) >= MAX_GESTURE_STRINGS: + gesture_strings = [] + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + + clear_background(RAYWHITE) + + draw_rectangle_rec(touch_area, GRAY) + draw_rectangle(225, 15, SCREEN_WIDTH - 240, SCREEN_HEIGHT - 30, RAYWHITE) + draw_text("GESTURES TEST AREA", SCREEN_WIDTH - 270, SCREEN_HEIGHT - 40, 20, fade(GRAY, 0.5)) + + for i, val in enumerate(gesture_strings): + if i % 2 == 0: + draw_rectangle(10, 30 + 20 * i, 200, 20, fade(LIGHTGRAY, 0.5)) + else: + draw_rectangle(10, 30 + 20 * i, 200, 20, fade(LIGHTGRAY, 0.3)) + + if i < len(gesture_strings) - 1: + draw_text(val, 35, 36 + 20 * i, 10, DARKGRAY) + else: + draw_text(val, 35, 36 + 20 * i, 10, MAROON) + + draw_rectangle_lines(10, 29, 200, SCREEN_HEIGHT - 50, GRAY) + draw_text("DETECTED GESTURES", 50, 15, 10, GRAY) + + if current_gesture != Gesture.GESTURE_NONE: + draw_circle_v(touch_position, 30, MAROON) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + + +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/core/core_input_keys.py b/examples/core/core_input_keys.py index bfd9465..9eb0848 100644 --- a/examples/core/core_input_keys.py +++ b/examples/core/core_input_keys.py @@ -3,48 +3,58 @@ raylib [core] example - Keyboard input """ -import pyray -from raylib.colors import ( - RAYWHITE, - DARKGRAY, - MAROON, -) +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - keyboard input") -# Initialization -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 + ball_position = Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, - 'raylib [core] example - keyboard input') -ball_position = pyray.Vector2(SCREEN_WIDTH / 2, SCREEN_HEIGHT / 2) + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- -pyray.set_target_fps(60) # Set our game to run at 60 frames-per-second + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + if is_key_down(KeyboardKey.KEY_RIGHT): ball_position.x += 2 + if is_key_down(KeyboardKey.KEY_LEFT): ball_position.x -= 2 + if is_key_down(KeyboardKey.KEY_UP): ball_position.y -= 2 + if is_key_down(KeyboardKey.KEY_DOWN): ball_position.y += 2 + # ---------------------------------------------------------------------------------- + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() -# Main game loop -while not pyray.window_should_close(): # Detect window close button or ESC key - # Update - if pyray.is_key_down(pyray.KEY_RIGHT): - ball_position.x += 2 - if pyray.is_key_down(pyray.KEY_LEFT): - ball_position.x -= 2 - if pyray.is_key_down(pyray.KEY_UP): - ball_position.y -= 2 - if pyray.is_key_down(pyray.KEY_DOWN): - ball_position.y += 2 + clear_background(RAYWHITE) - # Draw - pyray.begin_drawing() + draw_text("move the ball with arrow keys", 10, 10, 20, DARKGRAY) - pyray.clear_background(RAYWHITE) - pyray.draw_text('move the ball with arrow keys', 10, 10, 20, DARKGRAY) - pyray.draw_circle_v(ball_position, 50, MAROON) + draw_circle_v(ball_position, 50, MAROON) - pyray.end_drawing() + end_drawing() + # ---------------------------------------------------------------------------------- + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + + +# execute the main function +if __name__ == '__main__': + main() -# De-Initialization -pyray.close_window() # Close window and OpenGL context diff --git a/examples/core/core_input_mouse.py b/examples/core/core_input_mouse.py index a946965..8a37dcd 100644 --- a/examples/core/core_input_mouse.py +++ b/examples/core/core_input_mouse.py @@ -1,72 +1,66 @@ """ -raylib [core] example - Mouse input +raylib [core] example - Mouse Input """ + +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import ( - RAYWHITE, - DARKGRAY, - MAROON, - LIME, - DARKBLUE, - PURPLE, - YELLOW, - ORANGE, - BEIGE, -) -from raylib import ( - MOUSE_BUTTON_LEFT, - MOUSE_BUTTON_MIDDLE, - MOUSE_BUTTON_RIGHT, - MOUSE_BUTTON_SIDE, - MOUSE_BUTTON_EXTRA, - MOUSE_BUTTON_FORWARD, - MOUSE_BUTTON_BACK -) - -# Initialization -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -init_window(SCREEN_WIDTH, SCREEN_HEIGHT, - 'raylib [core] example - mouse input') - -ball_position = Vector2(-100, -100) -ball_color = DARKBLUE - -set_target_fps(60) # Set our game to run at 60 frames-per-second - -# Main game loop -while not window_should_close(): # Detect window close button or ESC key - # Update - ball_position = get_mouse_position() - - if is_mouse_button_pressed(MOUSE_BUTTON_LEFT): - ball_color = MAROON - elif is_mouse_button_pressed(MOUSE_BUTTON_MIDDLE): - ball_color = LIME - elif is_mouse_button_pressed(MOUSE_BUTTON_RIGHT): - ball_color = DARKBLUE - elif is_mouse_button_pressed(MOUSE_BUTTON_SIDE): - ball_color = PURPLE - elif is_mouse_button_pressed(MOUSE_BUTTON_EXTRA): - ball_color = YELLOW - elif is_mouse_button_pressed(MOUSE_BUTTON_FORWARD): - ball_color = ORANGE - elif is_mouse_button_pressed(MOUSE_BUTTON_BACK): - ball_color = BEIGE - # Draw - begin_drawing() - - clear_background(RAYWHITE) - draw_circle_v(ball_position, 40, ball_color) - draw_text( - 'move ball with mouse and click mouse button to change color', - 10, 10, 20, DARKGRAY - ) - - end_drawing() - -# De-Initialization -close_window() # Close window and OpenGL context +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # -------------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - mouse input") + + ball_position = Vector2(-100, -100) + ball_color = DARKBLUE + + set_target_fps(60) # Set our game to run at 60 frames-per-second + # -------------------------------------------------------------------------------------- + + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + ball_position = get_mouse_position() + + if is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_LEFT): ball_color = MAROON + elif is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_MIDDLE): ball_color = LIME + elif is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_RIGHT): ball_color = DARKBLUE + elif is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_SIDE): ball_color = PURPLE + elif is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_EXTRA): ball_color = YELLOW + elif is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_FORWARD): ball_color = ORANGE + elif is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_BACK): ball_color = BEIGE + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + + clear_background(RAYWHITE) + + draw_circle_v(ball_position, 40, ball_color) + + draw_text("move ball with mouse and click mouse button to change color", 10, 10, 20, DARKGRAY) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + + +# Execute the main function +if __name__ == '__main__': + main() + diff --git a/examples/core/core_input_mouse_wheel.py b/examples/core/core_input_mouse_wheel.py index da020c7..c3bc8a3 100644 --- a/examples/core/core_input_mouse_wheel.py +++ b/examples/core/core_input_mouse_wheel.py @@ -1,52 +1,59 @@ """ -raylib [core] example - Mouse wheel input +raylib [core] example - Mouse Wheel Input """ -import pyray -from raylib.colors import ( - RAYWHITE, - GRAY, - LIGHTGRAY, - MAROON, -) +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # -------------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - input mouse wheel") + box_position_y = SCREEN_HEIGHT // 2 - 40 + scroll_speed = 4 # Scrolling speed in pixels -# Initialization -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 + set_target_fps(60) # Set our game to run at 60 frames-per-second + # -------------------------------------------------------------------------------------- -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, - 'raylib [core] example - input mouse wheel') + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + box_position_y -= int(get_mouse_wheel_move() * scroll_speed) + # -------------------------------------------------------------------------------------- -box_position_y: int = SCREEN_HEIGHT // 2 - 40 -scroll_speed = 4 # Scrolling speed in pixels + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() -pyray.set_target_fps(60) # Set our game to run at 60 frames-per-second + clear_background(RAYWHITE) + draw_rectangle(SCREEN_WIDTH // 2 - 40, box_position_y, 80, 80, MAROON) -# Main game loop -while not pyray.window_should_close(): # Detect window close button or ESC key - # Update - box_position_y -= int(pyray.get_mouse_wheel_move() * scroll_speed) + draw_text("User mouse wheel to move the cube up and down!", 10, 10, 20, GRAY) + draw_text("Box position Y: {:03d}".format(box_position_y), 10, 40, 20, LIGHTGRAY) - # Draw - pyray.begin_drawing() + end_drawing() + # ---------------------------------------------------------------------------------- - pyray.clear_background(RAYWHITE) + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- - pyray.draw_rectangle(SCREEN_WIDTH // 2 - 40, box_position_y, 80, 80, MAROON) - pyray.draw_text('User mouse wheel to move the cube up and down!', - 10, 10, 20, GRAY) - pyray.draw_text('Box position Y: {:03d}'.format(box_position_y), - 10, 40, 20, LIGHTGRAY) +# Execute the main function +if __name__ == '__main__': + main() - pyray.end_drawing() - - -# De-Initialization -pyray.close_window() # Close window and OpenGL context diff --git a/examples/core/core_random_values.py b/examples/core/core_random_values.py index 0983c5b..1fe00b6 100644 --- a/examples/core/core_random_values.py +++ b/examples/core/core_random_values.py @@ -1,54 +1,66 @@ """ -raylib [core] example - random values +raylib [core] example - Random Values """ + +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import ( - RAYWHITE, - MAROON, - LIGHTGRAY -) +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 -# Initialization -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - random values") -init_window(SCREEN_WIDTH, SCREEN_HEIGHT, 'raylib [core] example - random values') + # set_random_seed() # Set a custom random seed if desired, by default: "time(NULL)" -# set_random_seed() // Set a custom random seed if desired, by default: "time(NULL)" + rand_value = get_random_value(-8, 5) # Get a random integer number between -8 and 5 (both included) -randValue = get_random_value(-8, 5) # Get a random integer number between -8 and 5 (both included) + frames_counter = 0 # Variable used to count frames -framesCounter = 0 # Variable used to count frames + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- -set_target_fps(60) # Set our game to run at 60 frames-per-second + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + frames_counter += 1 -# Main game loop -while not window_should_close(): # Detect window close button or ESC key + # Every two seconds (120 frames) a new random value is generated + if ((frames_counter/120) % 2) == 1: + rand_value = get_random_value(-8, 5) + frames_counter = 0 + # ---------------------------------------------------------------------------------- - # Update - # ---------------------------------------------------------------------------------- - framesCounter += 1 + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - # Every two seconds (120 frames) a new random value is generated - if ((framesCounter/120) % 2) == 1: - randValue = get_random_value(-8, 5) - framesCounter = 0 + clear_background(RAYWHITE) - # ---------------------------------------------------------------------------------- + draw_text("Every 2 seconds a new random value is generated:", 130, 100, 20, MAROON) - # Draw - # ---------------------------------------------------------------------------------- - begin_drawing() + draw_text(str(rand_value), 360, 180, 80, LIGHTGRAY) - clear_background(RAYWHITE) + end_drawing() + # ---------------------------------------------------------------------------------- - draw_text("Every 2 seconds a new random value is generated:", 130, 100, 20, MAROON) + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- - draw_text(str(randValue), 360, 180, 80, LIGHTGRAY) - end_drawing() +# Execute the main function +if __name__ == '__main__': + main() -# De-Initialization -close_window() # Close window and OpenGL context diff --git a/examples/core/core_scissor_test.py b/examples/core/core_scissor_test.py index e205773..bce63c8 100644 --- a/examples/core/core_scissor_test.py +++ b/examples/core/core_scissor_test.py @@ -3,63 +3,70 @@ raylib [core] example - Scissor Test """ + +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import ( - RAYWHITE, - LIGHTGRAY, - RED, - BLACK -) -from raylib import ( - KEY_S -) - -# Initialization -# -------------------------------------------------------------------------------------- -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - scissor test") - -scissorArea = Rectangle(0, 0, 300, 300) -scissorMode = True - -set_target_fps(60) # Set our game to run at 60 frames-per-second -# -------------------------------------------------------------------------------------- - -# Main game loop -while not window_should_close(): # Detect window close button or ESC key - # Update - # ---------------------------------------------------------------------------------- - if is_key_pressed(KEY_S): - scissorMode = not scissorMode +# ------------------------------------------------------------------------------------ - # Centre the scissor area around the mouse position - scissorArea.x = get_mouse_x() - scissorArea.width/2 - scissorArea.y = get_mouse_y() - scissorArea.height/2 - # ---------------------------------------------------------------------------------- +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # -------------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - scissor test") - # Draw - # ---------------------------------------------------------------------------------- - begin_drawing() + scissor_area = Rectangle(0, 0, 300, 300) + scissor_mode = True + + set_target_fps(60) # Set our game to run at 60 frames-per-second + # -------------------------------------------------------------------------------------- + + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + if is_key_pressed(KeyboardKey.KEY_S): + scissor_mode = not scissor_mode + + # Centre the scissor area around the mouse position + scissor_area.x = get_mouse_x() - scissor_area.width/2 + scissor_area.y = get_mouse_y() - scissor_area.height/2 + # ---------------------------------------------------------------------------------- - clear_background(RAYWHITE) - if scissorMode: - begin_scissor_mode(int(scissorArea.x), int(scissorArea.y), int(scissorArea.width), int(scissorArea.height)) + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - # Draw full screen rectangle and some text - # NOTE: Only part defined by scissor area will be rendered - draw_rectangle(0, 0, get_screen_width(), get_screen_height(), RED) - draw_text("Move the mouse around to reveal this text!", 190, 200, 20, LIGHTGRAY) + clear_background(RAYWHITE) - if scissorMode: - end_scissor_mode() + if scissor_mode: + begin_scissor_mode(int(scissor_area.x), int(scissor_area.y), int(scissor_area.width), int(scissor_area.height)) - draw_rectangle_lines_ex(scissorArea, 1, BLACK) - draw_text("Press S to toggle scissor test", 10, 10, 20, BLACK) + # Draw full screen rectangle and some text + # NOTE: Only part defined by scissor area will be rendered + draw_rectangle(0, 0, get_screen_width(), get_screen_height(), RED) + draw_text("Move the mouse around to reveal this text!", 190, 200, 20, LIGHTGRAY) + + if scissor_mode: + end_scissor_mode() + + draw_rectangle_lines_ex(scissor_area, 1, BLACK) + draw_text("Press S to toggle scissor test", 10, 10, 20, BLACK) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- - end_drawing() -# De-Initialization -close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/core/core_window_should_close.py b/examples/core/core_window_should_close.py index 4a0e391..75614c0 100644 --- a/examples/core/core_window_should_close.py +++ b/examples/core/core_window_should_close.py @@ -3,72 +3,70 @@ raylib [core] example - Window Should Close """ + +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import ( - RAYWHITE, - LIGHTGRAY, - WHITE, - BLACK -) -from raylib import ( - KEY_NULL, - KEY_ESCAPE, - KEY_Y, - KEY_N -) - -# Initialization -# -------------------------------------------------------------------------------------- -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - window should close") - -set_exit_key(KEY_NULL) # Disable KEY_ESCAPE to close window, X-button still works - -exitWindowRequested = False # Flag to request window to exit -exitWindow = False # Flag to set window to exit - -set_target_fps(60) # Set our game to run at 60 frames-per-second -# -------------------------------------------------------------------------------------- - -# Main game loop -while not exitWindow: - - # Update - # ---------------------------------------------------------------------------------- - # Detect if X-button or KEY_ESCAPE have been pressed to close window - if window_should_close() or is_key_pressed(KEY_ESCAPE): - exitWindowRequested = True +# ------------------------------------------------------------------------------------ - if exitWindowRequested: +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # -------------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 - # A request for close window has been issued, we can save data before closing - # or just show a message asking for confirmation + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [core] example - window should close") - if is_key_pressed(KEY_Y): - exitWindow = True - elif is_key_pressed(KEY_N): - exitWindowRequested = False + set_exit_key(KeyboardKey.KEY_NULL) # Disable KEY_ESCAPE to close window, X-button still works - # ---------------------------------------------------------------------------------- + exit_window_requested = False # Flag to request window to exit + exit_window = False # Flag to set window to exit - # Draw - # ---------------------------------------------------------------------------------- - begin_drawing() + set_target_fps(60) # Set our game to run at 60 frames-per-second + # -------------------------------------------------------------------------------------- + + # Main game loop + while not exit_window: + # Update + # ---------------------------------------------------------------------------------- + # Detect if X-button or KEY_ESCAPE have been pressed to close window + if window_should_close() or is_key_pressed(KeyboardKey.KEY_ESCAPE): + exit_window_requested = True - clear_background(RAYWHITE) + if exit_window_requested: + # A request for close window has been issued, we can save data before closing + # or just show a message asking for confirmation + if is_key_pressed(KeyboardKey.KEY_Y): + exit_window = True + elif is_key_pressed(KeyboardKey.KEY_N): + exit_window_requested = False + # ---------------------------------------------------------------------------------- - if exitWindowRequested: + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - draw_rectangle(0, 100, SCREEN_WIDTH, 200, BLACK) - draw_text("Are you sure you want to exit program? [Y/N]", 40, 180, 30, WHITE) + clear_background(RAYWHITE) - else: - draw_text("Try to close the window to get confirmation message!", 120, 200, 20, LIGHTGRAY) + if exit_window_requested: + draw_rectangle(0, 100, SCREEN_WIDTH, 200, BLACK) + draw_text("Are you sure you want to exit program? [Y/N]", 40, 180, 30, WHITE) - end_drawing() + else: + draw_text("Try to close the window to get confirmation message!", 120, 200, 20, LIGHTGRAY) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + -# De-Initialization -close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/shapes/shapes_draw_rounded_rectangle.py b/examples/shapes/shapes_draw_rounded_rectangle.py index ab948c8..fe7face 100644 --- a/examples/shapes/shapes_draw_rounded_rectangle.py +++ b/examples/shapes/shapes_draw_rounded_rectangle.py @@ -1,17 +1,12 @@ -#/******************************************************************************************* -#* -#* raylib [shapes] example - draw rectangle rounded (with gui options) -#* -#* This example has been created using raylib 2.5 (www.raylib.com) -#* raylib is licensed under an unmodified zlib/libpng license (View raylib.h for details) -#* -#* Example contributed by Vlad Adrian (@demizdor) and reviewed by Ramon Santamaria (@raysan5) -#* -#* Copyright (c) 2018 Vlad Adrian (@demizdor) and Ramon Santamaria (@raysan5) -#* -#********************************************************************************************/ - -import pyray +""" + +raylib [shapes] example - Draw Rounded Rectangle + +""" + +# Import +# ------------------------------------------------------------------------------------ +from pyray import * from raylib.colors import ( RAYWHITE, LIGHTGRAY, @@ -19,67 +14,81 @@ GOLD, MAROON, ) +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ------------------------------------------------------------------------------------ + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [shapes] example - draw rectangle rounded") + + roundness = 0.2 + width = 200 + height = 100 + segments = 0 + lineThick = 1 + + draw_rect = False + draw_rounded_rect = True + draw_rounded_lines = False + + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ------------------------------------------------------------------------------------ + + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + rec = Rectangle((get_screen_width() - width - 250) / 2, (get_screen_height() - height) / 2, width, height) + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + + clear_background(RAYWHITE) + + draw_line(560, 0, 560, get_screen_height(), fade(LIGHTGRAY, 0.6)) + draw_rectangle(560, 0, get_screen_width() - 500, get_screen_height(), fade(LIGHTGRAY, 0.3)) + + if draw_rect: + draw_rectangle_rec(rec, fade(GOLD, 0.6)) + if draw_rounded_rect: + draw_rectangle_rounded(rec, roundness, segments, fade(MAROON, 0.2)) + if draw_rounded_lines: + draw_rectangle_rounded_lines(rec, roundness, segments, lineThick, fade(MAROON, 0.4)) + + # Draw GUI controls + # ------------------------------------------------------------------------------ + width = int(gui_slider_bar(Rectangle(640, 40, 105, 20), "Width", 0, width, 0, get_screen_width() - 300)) + height = int(gui_slider_bar(Rectangle(640, 70, 105, 20), "Height", 0, height, 0, get_screen_height() - 50)) + roundness = gui_slider_bar(Rectangle(640, 140, 105, 20), "Roundness", 0, roundness, 0, 1) + lineThick = int(gui_slider_bar(Rectangle(640, 170, 105, 20), "Thickness", 0, lineThick, 0, 20)) + segments = int(gui_slider_bar(Rectangle(640, 240, 105, 20), "Segments", 0, segments, 0, 60)) + + draw_rounded_rect = gui_check_box(Rectangle(640, 320, 20, 20), "DrawRoundedRect", draw_rounded_rect) + draw_rounded_lines = gui_check_box(Rectangle(640, 350, 20, 20), "DrawRoundedLines", draw_rounded_lines) + draw_rect = gui_check_box(Rectangle(640, 380, 20, 20), "DrawRect", draw_rect) + # ------------------------------------------------------------------------------ + + draw_text(text_format("MODE: %s" % "MANUAL" if segments >= 4 else "AUTO"), 640, 280, 10, MAROON if segments >= 4 else DARKGRAY) + + draw_fps(10, 10) + + end_drawing() + # ------------------------------------------------------------------------------ + + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + -#// Initialization -#//-------------------------------------------------------------------------------------- -SCREEN_WIDTH = 800 -SCREEN_HEIGHT = 450 - -pyray.init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [shapes] example - draw rectangle rounded") - -roundness = 0.2 -width = 200 -height = 100 -segments = 0 -lineThick = 1 - -drawRect = False -drawRoundedRect = True -drawRoundedLines = False - -pyray.set_target_fps(60) #// Set our game to run at 60 frames-per-second -#//-------------------------------------------------------------------------------------- - -#// Main game loop -while not pyray.window_should_close(): #// Detect window close button or ESC key - - #// Update - #//---------------------------------------------------------------------------------- - rec = pyray.Rectangle( (pyray.get_screen_width()-width-250)/2, (pyray.get_screen_height()-height)/2, width, height ) - #//---------------------------------------------------------------------------------- - - #// Draw - #//---------------------------------------------------------------------------------- - pyray.begin_drawing() - pyray.clear_background(RAYWHITE) - - pyray.draw_line(560,0,560,pyray.get_screen_height(),pyray.fade(LIGHTGRAY,0.6)) - pyray.draw_rectangle(560,0,pyray.get_screen_width()-500,pyray.get_screen_height(),pyray.fade(LIGHTGRAY,0.3)) - - if drawRect: - pyray.draw_rectangle_rec(rec,pyray.fade(GOLD,0.6)) - if drawRoundedRect: - pyray.draw_rectangle_rounded(rec,roundness,segments,pyray.fade(MAROON,0.2)) - if drawRoundedLines: - pyray.draw_rectangle_rounded_lines(rec,roundness,segments,lineThick,pyray.fade(MAROON,0.4)) - - #// Draw GUI controls - #//------------------------------------------------------------------------------ - width = int( pyray.gui_slider_bar(pyray.Rectangle(640,40,105,20),"Width",0,width,0,pyray.get_screen_width()-300) ) - height = int( pyray.gui_slider_bar(pyray.Rectangle(640,70,105,20),"Height",0,height,0,pyray.get_screen_height()-50) ) - roundness = pyray.gui_slider_bar(pyray.Rectangle(640,140,105,20),"Roundness",0,roundness,0,1) - lineThick = int( pyray.gui_slider_bar(pyray.Rectangle(640,170,105,20),"Thickness",0,lineThick,0,20) ) - segments = int( pyray.gui_slider_bar(pyray.Rectangle(640,240,105,20),"Segments",0,segments,0,60) ) - - drawRoundedRect = pyray.gui_check_box(pyray.Rectangle(640,320,20,20),"DrawRoundedRect",drawRoundedRect) - drawRoundedLines = pyray.gui_check_box(pyray.Rectangle(640,350,20,20),"DrawRoundedLines",drawRoundedLines) - drawRect = pyray.gui_check_box(pyray.Rectangle(640,380,20,20),"DrawRect",drawRect) - #//------------------------------------------------------------------------------ - - pyray.draw_text(pyray.text_format( "MODE: %s" % "MANUAL" if segments >= 4 else "AUTO" ), 640, 280, 10, MAROON if segments >= 4 else DARKGRAY ) - pyray.draw_fps(10,10) - pyray.end_drawing() - #//------------------------------------------------------------------------------ - -# De-Initialization -pyray.close_window() # Close window and OpenGL context \ No newline at end of file +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/shapes/shapes_following_eyes.py b/examples/shapes/shapes_following_eyes.py index 5f99e0e..374b513 100644 --- a/examples/shapes/shapes_following_eyes.py +++ b/examples/shapes/shapes_following_eyes.py @@ -4,93 +4,100 @@ """ +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import ( - RAYWHITE, - BROWN, - BLACK, - LIGHTGRAY, - DARKGREEN, -) from math import ( atan2, cos, sin ) +# ------------------------------------------------------------------------------------ -# Initialization -# ---------------------------------------------------------------------------------- -screenWidth = 800 -screenHeight = 450 - -init_window(screenWidth, screenHeight, "raylib [shapes] example - following eyes") +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 -scleraLeftPosition = Vector2(screenWidth / 2.0 - 100.0, screenHeight / 2.0) -scleraRightPosition = Vector2(screenWidth / 2.0 + 100.0, screenHeight / 2.0) -scleraRadius = 80.0 + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [shapes] example - following eyes") -irisLeftPosition = Vector2(screenWidth / 2.0 - 100.0, screenHeight / 2.0) -irisRightPosition = Vector2(screenWidth / 2.0 - 100.0, screenHeight / 2.0) -irisRadius = 24.0 + scleraLeftPosition = Vector2(SCREEN_WIDTH / 2.0 - 100.0, SCREEN_HEIGHT / 2.0) + scleraRightPosition = Vector2(SCREEN_WIDTH / 2.0 + 100.0, SCREEN_HEIGHT / 2.0) + sclera_radius = 80.0 -angle = 0.0 -dx, dy, dxx, dyy = 0.0, 0.0, 0.0, 0.0 + irisLeftPosition = Vector2(SCREEN_WIDTH / 2.0 - 100.0, SCREEN_HEIGHT / 2.0) + irisRightPosition = Vector2(SCREEN_WIDTH / 2.0 - 100.0, SCREEN_HEIGHT / 2.0) + iris_radius = 24.0 -set_target_fps(60) -# ---------------------------------------------------------------------------------- + angle = 0.0 + dx, dy, dxx, dyy = 0.0, 0.0, 0.0, 0.0 -# Main game loop -while not window_should_close(): # Detect window close button or ESC key - # Update + set_target_fps(60) # Set our game to run at 60 frames-per-second # ---------------------------------------------------------------------------------- - irisLeftPosition = get_mouse_position() - irisRightPosition = get_mouse_position() - # Check not inside the left eye sclera - if not check_collision_point_circle(irisLeftPosition, scleraLeftPosition, scleraRadius - 20): - dx = irisLeftPosition.x - scleraLeftPosition.x - dy = irisLeftPosition.y - scleraLeftPosition.y + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + irisLeftPosition = get_mouse_position() + irisRightPosition = get_mouse_position() - angle = atan2(dy, dx) + # Check not inside the left eye sclera + if not check_collision_point_circle(irisLeftPosition, scleraLeftPosition, sclera_radius - 20): + dx = irisLeftPosition.x - scleraLeftPosition.x + dy = irisLeftPosition.y - scleraLeftPosition.y - dxx = (scleraRadius - irisRadius)*cos(angle) - dyy = (scleraRadius - irisRadius)*sin(angle) + angle = atan2(dy, dx) - irisLeftPosition.x = scleraLeftPosition.x + dxx - irisLeftPosition.y = scleraLeftPosition.y + dyy + dxx = (sclera_radius - iris_radius) * cos(angle) + dyy = (sclera_radius - iris_radius) * sin(angle) - # Check not inside the right eye sclera - if not check_collision_point_circle(irisRightPosition, scleraRightPosition, scleraRadius - 20): - dx = irisRightPosition.x - scleraRightPosition.x - dy = irisRightPosition.y - scleraRightPosition.y + irisLeftPosition.x = scleraLeftPosition.x + dxx + irisLeftPosition.y = scleraLeftPosition.y + dyy - angle = atan2(dy, dx) + # Check not inside the right eye sclera + if not check_collision_point_circle(irisRightPosition, scleraRightPosition, sclera_radius - 20): + dx = irisRightPosition.x - scleraRightPosition.x + dy = irisRightPosition.y - scleraRightPosition.y - dxx = (scleraRadius - irisRadius)*cos(angle) - dyy = (scleraRadius - irisRadius)*sin(angle) + angle = atan2(dy, dx) - irisRightPosition.x = scleraRightPosition.x + dxx - irisRightPosition.y = scleraRightPosition.y + dyy + dxx = (sclera_radius - iris_radius) * cos(angle) + dyy = (sclera_radius - iris_radius) * sin(angle) - # ---------------------------------------------------------------------------------- + irisRightPosition.x = scleraRightPosition.x + dxx + irisRightPosition.y = scleraRightPosition.y + dyy + # ---------------------------------------------------------------------------------- - # draw - # ---------------------------------------------------------------------------------- - begin_drawing() + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - clear_background(RAYWHITE) + clear_background(RAYWHITE) - draw_circle_v(scleraLeftPosition, scleraRadius, LIGHTGRAY) - draw_circle_v(irisLeftPosition, irisRadius, BROWN) - draw_circle_v(irisLeftPosition, 10, BLACK) + draw_circle_v(scleraLeftPosition, sclera_radius, LIGHTGRAY) + draw_circle_v(irisLeftPosition, iris_radius, BROWN) + draw_circle_v(irisLeftPosition, 10, BLACK) - draw_circle_v(scleraRightPosition, scleraRadius, LIGHTGRAY) - draw_circle_v(irisRightPosition, irisRadius, DARKGREEN) - draw_circle_v(irisRightPosition, 10, BLACK) + draw_circle_v(scleraRightPosition, sclera_radius, LIGHTGRAY) + draw_circle_v(irisRightPosition, iris_radius, DARKGREEN) + draw_circle_v(irisRightPosition, 10, BLACK) - draw_fps(10, 10) + draw_fps(10, 10) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- - end_drawing() -# De-Initialization -close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/shapes/shapes_lines_bezier.py b/examples/shapes/shapes_lines_bezier.py index c3c0952..7e43177 100644 --- a/examples/shapes/shapes_lines_bezier.py +++ b/examples/shapes/shapes_lines_bezier.py @@ -1,16 +1,18 @@ """ -raylib [shapes] example - Lines Bezier +raylib [shapes] example - Cubic-bezier lines """ +# Import +# ------------------------------------------------------------------------------------ from pyray import * from raylib.colors import ( RAYWHITE, GRAY, RED ) - +# ------------------------------------------------------------------------------------ # ------------------------------------------------------------------------------------ # Program main entry point @@ -18,14 +20,14 @@ def main(): # Initialization # ------------------------------------------------------------------------------------ - screenWidth = 800 - screenHeight = 450 + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 set_config_flags(ConfigFlags.FLAG_MSAA_4X_HINT) - init_window(screenWidth, screenHeight, "raylib [shapes] example - cubic-bezier lines") + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [shapes] example - cubic-bezier lines") start = Vector2(0, 0) - end = Vector2(screenWidth, screenHeight) + end = Vector2(SCREEN_WIDTH, SCREEN_HEIGHT) set_target_fps(60) # Set our game to run at 60 frames-per-second # ------------------------------------------------------------------------------------- @@ -56,6 +58,7 @@ def main(): close_window() # Close window and OpenGL context # ---------------------------------------------------------------------------------- -# execute the main function + +# Execute the main function if __name__ == '__main__': main() diff --git a/examples/shapes/shapes_logo_raylib.py b/examples/shapes/shapes_logo_raylib.py index d91bc0b..e824177 100644 --- a/examples/shapes/shapes_logo_raylib.py +++ b/examples/shapes/shapes_logo_raylib.py @@ -1,43 +1,61 @@ """ -raylib [shapes] example - Logo Raylib +raylib [shapes] example - Raylib Logo """ + +# Import +# ------------------------------------------------------------------------------------ from pyray import * from raylib.colors import ( RAYWHITE, BLACK, GRAY ) +# ------------------------------------------------------------------------------------ -# Initialization -screenWidth = 800 -screenHeight = 450 - -init_window(screenWidth, screenHeight, 'raylib [shapes] example - raylib logo using shapes') +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 -set_target_fps(60) # Set our game to run at 60 frames-per-second + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [shapes] example - raylib logo using shapes") -# Main game loop -while not window_should_close(): # Detect window close button or ESC key - # Update - # ---------------------------------------------------------------------------------- - # TODO: Update your variables here + set_target_fps(60) # Set our game to run at 60 frames-per-second # ---------------------------------------------------------------------------------- - # Draw - # ---------------------------------------------------------------------------------- - begin_drawing() + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + # TODO: Update your variables here + # ---------------------------------------------------------------------------------- - clear_background(RAYWHITE) + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - draw_rectangle(int(screenWidth/2 - 128), int(screenHeight/2 - 128), 256, 256, BLACK) - draw_rectangle(int(screenWidth/2 - 112), int(screenHeight/2 - 112), 224, 224, RAYWHITE) - draw_text("raylib", int(screenWidth/2 - 44), int(screenHeight/2 + 48), 50, BLACK) + clear_background(RAYWHITE) - draw_text("this is NOT a texture!", 350, 370, 10, GRAY) + draw_rectangle(int(SCREEN_WIDTH/2 - 128), int(SCREEN_HEIGHT/2 - 128), 256, 256, BLACK) + draw_rectangle(int(SCREEN_WIDTH/2 - 112), int(SCREEN_HEIGHT/2 - 112), 224, 224, RAYWHITE) + draw_text("raylib", int(SCREEN_WIDTH/2 - 44), int(SCREEN_HEIGHT/2 + 48), 50, BLACK) + + draw_text("this is NOT a texture!", 350, 370, 10, GRAY) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- - end_drawing() -# De-Initialization -close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/textures/textures_bunnymark_more_pythonic.py b/examples/textures/textures_bunnymark_more_pythonic.py index 19768af..03bf67e 100644 --- a/examples/textures/textures_bunnymark_more_pythonic.py +++ b/examples/textures/textures_bunnymark_more_pythonic.py @@ -1,110 +1,110 @@ -# Dont use C data structures when we can avoid it. Makes Pypy slightly faster. +""" -from raylib import * -import random +raylib [textures] example - Bunnymark -MAX_BUNNIES = 500000 +""" +# Import +# ------------------------------------------------------------------------------------ +from pyray import * +# ------------------------------------------------------------------------------------ + +# Definitions +# ------------------------------------------------------------------------------------ +MAX_BUNNIES = 50000 # This is the maximum amount of elements (quads) per batch # NOTE: This value is defined in [rlgl] module and can be changed there -MAX_BATCH_ELEMENTS = 8192 - +MAX_BATCH_ELEMENTS = 8192 class Bunny: def __init__(self): - self.position_x = 0.0 - self.position_y = 0.0 - self.speed_x = 0.0 - self.speed_y = 0.0 - self.color_r = 0 - self.color_g = 0 - self.color_b = 0 - self.color_a = 0 - - -# // Initialization -# //-------------------------------------------------------------------------------------- -screenWidth = 1920; -screenHeight = 1080; - -InitWindow(screenWidth, screenHeight, b"raylib [textures] example - bunnymark") - -# // Load bunny texture -texBunny = LoadTexture(b"resources/wabbit_alpha.png") - -bunnies = [] -for i in range(0, MAX_BUNNIES): - bunnies.append(Bunny()) - -bunniesCount = 0; # Bunnies counter - -SetTargetFPS(60); # Set our game to run at 60 frames-per-second -#//-------------------------------------------------------------------------------------- - -#// Main game loop -while not WindowShouldClose(): #// Detect window close button or ESC key - #// Update - #//---------------------------------------------------------------------------------- - if IsMouseButtonDown(MOUSE_BUTTON_LEFT): - #// Create more bunnies - for i in range(0, 100): - if bunniesCount < MAX_BUNNIES: - bunnies[bunniesCount].position_x = GetMousePosition().x - bunnies[bunniesCount].position_y = GetMousePosition().y - bunnies[bunniesCount].speed_x = random.randint(-250, 250)/60.0 - bunnies[bunniesCount].speed_y = random.randint(-250, 250)/60.0 - bunnies[bunniesCount].color_r = random.randint(50,240) - bunnies[bunniesCount].color_g = random.randint(80, 240) - bunnies[bunniesCount].color_b = random.randint(100, 240) - bunnies[bunniesCount].color_a = 255 - bunniesCount+=1 - - - # // Update bunnies - for i in range(0, bunniesCount): - bunnies[i].position_x += bunnies[i].speed_x - bunnies[i].position_y += bunnies[i].speed_y - - if ((bunnies[i].position_x + texBunny.width/2) > GetScreenWidth()) or ((bunnies[i].position_x + texBunny.width/2) < 0): - bunnies[i].speed_x *= -1 - if ((bunnies[i].position_y + texBunny.height/2) > GetScreenHeight()) or ((bunnies[i].position_y + texBunny.height/2 - 40) < 0): - bunnies[i].speed_y *= -1 - - # //---------------------------------------------------------------------------------- - # - # // Draw - # //---------------------------------------------------------------------------------- - BeginDrawing() - - ClearBackground(RAYWHITE) - - for i in range(0, bunniesCount): - # // NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS), - # // a draw call is launched and buffer starts being filled again; - # // before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU... - # // Process of sending data is costly and it could happen that GPU data has not been completely - # // processed for drawing while new data is tried to be sent (updating current in-use buffers) - # // it could generates a stall and consequently a frame drop, limiting the number of drawn bunnies - DrawTexture(texBunny, int(bunnies[i].position_x), int(bunnies[i].position_y), (bunnies[i].color_r,bunnies[i].color_g,bunnies[i].color_b,bunnies[i].color_a)) - - DrawRectangle(0, 0, screenWidth, 40, BLACK) - text = f"bunnies {bunniesCount}" - DrawText(text.encode('utf-8'), 120, 10, 20, GREEN) - text = f"batched draw calls: { 1 + int(bunniesCount/MAX_BATCH_ELEMENTS)}" - DrawText(text.encode('utf-8'), 320, 10, 20, MAROON) - - DrawFPS(10, 10) - - EndDrawing() - #//---------------------------------------------------------------------------------- - - -#// De-Initialization -#//-------------------------------------------------------------------------------------- - - -UnloadTexture(texBunny); #Unload bunny texture - -CloseWindow() # Close window and OpenGL context -#//-------------------------------------------------------------------------------------- - + self.position = Vector2(0, 0) + self.speed = Vector2(0, 0) + self.color = Color(0, 0, 0, 255) +# ------------------------------------------------------------------------------------ + +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 + + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [textures] example - bunnymark") + + # Load bunny texture + tex_bunny = load_texture("resources/wabbit_alpha.png") + + bunnies = [] + for i in range(0, MAX_BUNNIES): + bunnies.append(Bunny()) + + bunnies_count = 0 # Bunnies counter + + set_target_fps(60) # Set our game to run at 60 frames-per-second + # ---------------------------------------------------------------------------------- + + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + if is_mouse_button_down(MouseButton.MOUSE_BUTTON_LEFT): + # Create more bunnies + for i in range(0, 100): + if bunnies_count < MAX_BUNNIES: + bunnies[bunnies_count].position = get_mouse_position() + bunnies[bunnies_count].speed.x = get_random_value(-250, 250) / 60.0 + bunnies[bunnies_count].speed.y = get_random_value(-250, 250) / 60.0 + bunnies[bunnies_count].color = Color(get_random_value(50, 240), get_random_value(80, 240), get_random_value(100, 240), 255) + bunnies_count += 1 + + # Update bunnies + for i in range(0, bunnies_count): + bunnies[i].position.x += bunnies[i].speed.x + bunnies[i].position.y += bunnies[i].speed.y + + if bunnies[i].position.x + tex_bunny.width / 2 > SCREEN_WIDTH or bunnies[i].position.x + tex_bunny.width / 2 < 0: + bunnies[i].speed.x *= -1 + if bunnies[i].position.y + tex_bunny.height / 2 > SCREEN_HEIGHT or bunnies[i].position.y + tex_bunny.height / 2 - 40 < 0: + bunnies[i].speed.y *= -1 + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + + clear_background(RAYWHITE) + + for i in range(0, bunnies_count): + # NOTE: When internal batch buffer limit is reached (MAX_BATCH_ELEMENTS), + # a draw call is launched and buffer starts being filled again; + # before issuing a draw call, updated vertex data from internal CPU buffer is send to GPU... + # Process of sending data is costly, and it could happen that GPU data has not been completely + # processed for drawing while new data is tried to be sent (updating current in-use buffers) + # it could generate a stall and consequently a frame drop, limiting the number of drawn bunnies + # draw_texture(tex_bunny, int(bunnies[i].position.x), int(bunnies[i].position.y), bunnies[i].color) + draw_texture_v(tex_bunny, bunnies[i].position, bunnies[i].color) # more efficient drawing + + draw_rectangle(0, 0, SCREEN_WIDTH, 40, BLACK) + + draw_text(f"bunnies {bunnies_count}", 120, 10, 20, GREEN) + draw_text(f"batched draw calls: {1 + int(bunnies_count / MAX_BATCH_ELEMENTS)}", 320, 10, 20, MAROON) + + draw_fps(10, 10) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization + # ---------------------------------------------------------------------------------- + unload_texture(tex_bunny) # Unload bunny texture + + close_window() # Close window and OpenGL context + # ---------------------------------------------------------------------------------- + + +# Execute the main function +if __name__ == '__main__': + main() diff --git a/examples/textures/textures_mouse_painting.py b/examples/textures/textures_mouse_painting.py index 9cf45c0..215feea 100644 --- a/examples/textures/textures_mouse_painting.py +++ b/examples/textures/textures_mouse_painting.py @@ -3,194 +3,201 @@ raylib [texture] example - Mouse Painting """ +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import * -from raylib import ( - KEY_RIGHT, - KEY_LEFT, - MOUSE_BUTTON_LEFT, - KEY_C, - GESTURE_DRAG, - MOUSE_BUTTON_RIGHT, - KEY_S -) +# ------------------------------------------------------------------------------------ +# Definitions +# ------------------------------------------------------------------------------------ MAX_COLORS_COUNT = 23 # Number of colors available +# ------------------------------------------------------------------------------------ -# Initialization -screenWidth = 800 -screenHeight = 450 - -init_window(screenWidth, screenHeight, "raylib [textures] example - mouse painting") +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 -# Colours to choose from -colors = [RAYWHITE, YELLOW, GOLD, ORANGE, PINK, RED, MAROON, GREEN, LIME, DARKGREEN, - SKYBLUE, BLUE, DARKBLUE, PURPLE, VIOLET, DARKPURPLE, BEIGE, BROWN, DARKBROWN, - LIGHTGRAY, GRAY, DARKGRAY, BLACK] + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [textures] example - mouse painting") -colorsRecs = [] + # Colours to choose from + colors = [RAYWHITE, YELLOW, GOLD, ORANGE, PINK, RED, MAROON, GREEN, LIME, DARKGREEN, + SKYBLUE, BLUE, DARKBLUE, PURPLE, VIOLET, DARKPURPLE, BEIGE, BROWN, DARKBROWN, + LIGHTGRAY, GRAY, DARKGRAY, BLACK] -# Define colorsRecs data (for every rectangle) -for i in range(MAX_COLORS_COUNT): - colorsRecs.append(Rectangle(10 + 30.0 * i + 2 * i, 10, 30, 30)) + colors_recs = [] -colorSelected = 0 -colorSelectedPrev = colorSelected -colorMouseHover = 0 -brushSize = 20.0 -mouseWasPressed = False + # Define colors_recs data (for every rectangle) + for i in range(MAX_COLORS_COUNT): + colors_recs.append(Rectangle(10 + 30.0 * i + 2 * i, 10, 30, 30)) -btnSaveRec = Rectangle(750, 10, 40, 30) -btnSaveMouseHover = False -showSaveMessage = False -saveMessageCounter = 0 + color_selected = 0 + color_selected_prev = color_selected + color_mouse_hover = 0 + brush_size = 20.0 + mouse_was_pressed = False -# Create a RenderTexture2D to use as a canvas -target = load_render_texture(screenWidth, screenHeight) + btn_save_rec = Rectangle(750, 10, 40, 30) + btn_save_mouse_hover = False + show_save_message = False + save_message_counter = 0 -# Clear render texture before entering the game loop -begin_texture_mode(target) -clear_background(colors[0]) -end_texture_mode() + # Create a RenderTexture2D to use as a canvas + target = load_render_texture(SCREEN_WIDTH, SCREEN_HEIGHT) -set_target_fps(120) # Set our game to run at 120 frames-per-second + # Clear render texture before entering the game loop + begin_texture_mode(target) + clear_background(colors[0]) + end_texture_mode() -# Main game loop -while not window_should_close(): # Detect window close button or ESC key - # Update + set_target_fps(120) # Set our game to run at 120 frames-per-second # ---------------------------------------------------------------------------------- - mousePos = get_mouse_position() - - # Move between colors with keys - if is_key_pressed(KEY_RIGHT): - colorSelected += 1 - elif is_key_pressed(KEY_LEFT): - colorSelected -= 1 - - if colorSelected >= MAX_COLORS_COUNT: - colorSelected = MAX_COLORS_COUNT - 1 - elif colorSelected < 0: - colorSelected = 0 - # Choose color with mouse - for i in range(MAX_COLORS_COUNT): - if check_collision_point_rec(mousePos, colorsRecs[i]): - colorMouseHover = i - break + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + mouse_pos = get_mouse_position() + + # Move between colors with keys + if is_key_pressed(KeyboardKey.KEY_RIGHT): + color_selected += 1 + elif is_key_pressed(KeyboardKey.KEY_LEFT): + color_selected -= 1 + + if color_selected >= MAX_COLORS_COUNT: + color_selected = MAX_COLORS_COUNT - 1 + elif color_selected < 0: + color_selected = 0 + + # Choose color with mouse + for i in range(MAX_COLORS_COUNT): + if check_collision_point_rec(mouse_pos, colors_recs[i]): + color_mouse_hover = i + break + else: + color_mouse_hover = -1 + + if color_mouse_hover >= 0 and is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_LEFT): + color_selected = color_mouse_hover + color_selected_prev = color_selected + + # Change brush size + brush_size += get_mouse_wheel_move() * 5 + if brush_size < 2: brush_size = 2 + if brush_size > 50: brush_size = 50 + + if is_key_pressed(KeyboardKey.KEY_C): + # Clear render texture to clear color + begin_texture_mode(target) + clear_background(colors[0]) + end_texture_mode() + + if is_mouse_button_pressed(MouseButton.MOUSE_BUTTON_LEFT) or get_gesture_detected() == Gesture.GESTURE_DRAG: + + # Paint circle into render texture + # NOTE: To avoid discontinuous circles, we could store + # previous-next mouse points and just draw a line using brush size + begin_texture_mode(target) + if mouse_pos.y > 50: + draw_circle(int(mouse_pos.x), int(mouse_pos.y), brush_size, colors[color_selected]) + end_texture_mode() + if is_mouse_button_down(MouseButton.MOUSE_BUTTON_RIGHT): + + if not mouse_was_pressed: + color_selected_prev = color_selected + color_selected = 0 + + mouse_was_pressed = True + + # Erase circle from render texture + begin_texture_mode(target) + if mouse_pos.y > 50: draw_circle(int(mouse_pos.x), int(mouse_pos.y), brush_size, colors[0]) + end_texture_mode() + + elif is_mouse_button_released(MouseButton.MOUSE_BUTTON_RIGHT) and mouse_was_pressed: + + color_selected = color_selected_prev + mouse_was_pressed = False + + # Check mouse hover save button + if check_collision_point_rec(mouse_pos, btn_save_rec): + btn_save_mouse_hover = True else: - colorMouseHover = -1 - - if colorMouseHover >= 0 and is_mouse_button_pressed(MOUSE_BUTTON_LEFT): - colorSelected = colorMouseHover - colorSelectedPrev = colorSelected - - # Change brush size - brushSize += get_mouse_wheel_move() * 5 - if brushSize < 2: brushSize = 2 - if brushSize > 50: brushSize = 50 - - if is_key_pressed(KEY_C): - # Clear render texture to clear color - begin_texture_mode(target) - clear_background(colors[0]) - end_texture_mode() - - if is_mouse_button_pressed(MOUSE_BUTTON_LEFT) or get_gesture_detected() == GESTURE_DRAG: - - # Paint circle into render texture - # NOTE: To avoid discontinuous circles, we could store - # previous-next mouse points and just draw a line using brush size - begin_texture_mode(target) - if mousePos.y > 50: - draw_circle(int(mousePos.x), int(mousePos.y), brushSize, colors[colorSelected]) - end_texture_mode() - if is_mouse_button_down(MOUSE_BUTTON_RIGHT): - - if not mouseWasPressed: - colorSelectedPrev = colorSelected - colorSelected = 0 - - mouseWasPressed = True - - # Erase circle from render texture - begin_texture_mode(target) - if mousePos.y > 50: draw_circle(int(mousePos.x), int(mousePos.y), brushSize, colors[0]) - end_texture_mode() - - elif is_mouse_button_released(MOUSE_BUTTON_RIGHT) and mouseWasPressed: - - colorSelected = colorSelectedPrev - mouseWasPressed = False - - # Check mouse hover save button - if check_collision_point_rec(mousePos, btnSaveRec): - btnSaveMouseHover = True - else: - btnSaveMouseHover = False - - # Image saving logic - # NOTE: Saving painted texture to a default named image - if (btnSaveMouseHover and is_mouse_button_released(MOUSE_BUTTON_LEFT)) or is_key_pressed(KEY_S): - image = load_image_from_texture(target.texture) - image_flip_vertical(image) - export_image(image, "my_amazing_texture_painting.png") - unload_image(image) - showSaveMessage = True - - if showSaveMessage: - # On saving, show a full screen message for 2 seconds - saveMessageCounter += 1 - if saveMessageCounter > 240: - showSaveMessage = False - saveMessageCounter = 0 - + btn_save_mouse_hover = False + + # Image saving logic + # NOTE: Saving painted texture to a default named image + if (btn_save_mouse_hover and is_mouse_button_released(MouseButton.MOUSE_BUTTON_LEFT)) or is_key_pressed(KeyboardKey.KEY_S): + image = load_image_from_texture(target.texture) + image_flip_vertical(image) + export_image(image, "my_amazing_texture_painting.png") + unload_image(image) + show_save_message = True + + if show_save_message: + # On saving, show a full screen message for 2 seconds + save_message_counter += 1 + if save_message_counter > 240: + show_save_message = False + save_message_counter = 0 + + # ---------------------------------------------------------------------------------- + + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() + clear_background(RAYWHITE) + + # NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) + draw_texture_rec(target.texture, Rectangle(0, 0, float(target.texture.width), float(-target.texture.height)), Vector2(0, 0), WHITE) + + # Draw drawing circle for reference + if mouse_pos.y > 50: + if is_mouse_button_down(MouseButton.MOUSE_BUTTON_RIGHT): + draw_circle_lines(int(mouse_pos.x), int(mouse_pos.y), brush_size, GRAY) + else: + draw_circle(get_mouse_x(), get_mouse_y(), brush_size, colors[color_selected]) + # Draw top panel + draw_rectangle(0, 0, get_screen_width(), 50, RAYWHITE) + draw_line(0, 50, get_screen_width(), 50, LIGHTGRAY) + + # Draw color selection rectangles + for i in range(MAX_COLORS_COUNT): + draw_rectangle_rec(colors_recs[i], colors[i]) + draw_rectangle_lines(10, 10, 30, 30, LIGHTGRAY) + + if color_mouse_hover >= 0: draw_rectangle_rec(colors_recs[color_mouse_hover], fade(WHITE, 0.6)) + + draw_rectangle_lines_ex( + Rectangle(colors_recs[color_selected].x - 2, colors_recs[color_selected].y - 2, colors_recs[color_selected].width + 4, + colors_recs[color_selected].height + 4), 2, BLACK) + + # Draw save image button + draw_rectangle_lines_ex(btn_save_rec, 2, RED if btn_save_mouse_hover else BLACK) + draw_text("SAVE!", 755, 20, 10, RED if btn_save_mouse_hover else BLACK) + + if show_save_message: + draw_rectangle(0, 0, get_screen_width(), get_screen_height(), fade(RAYWHITE, 0.8)) + draw_rectangle(0, 150, get_screen_width(), 80, BLACK) + draw_text("IMAGE SAVED: my_amazing_texture_painting.png", 150, 180, 20, RAYWHITE) + + end_drawing() + # ---------------------------------------------------------------------------------- + + # De-Initialization # ---------------------------------------------------------------------------------- + unload_render_texture(target) # Unload render texture - # Draw + close_window() # Close window and OpenGL context # ---------------------------------------------------------------------------------- - begin_drawing() - clear_background(RAYWHITE) - - # NOTE: Render texture must be y-flipped due to default OpenGL coordinates (left-bottom) - draw_texture_rec(target.texture, Rectangle(0, 0, float(target.texture.width), float(-target.texture.height)), - Vector2(0, 0), WHITE) - - # Draw drawing circle for reference - if mousePos.y > 50: - if is_mouse_button_down(MOUSE_BUTTON_RIGHT): - draw_circle_lines(int(mousePos.x), int(mousePos.y), brushSize, GRAY) - else: - draw_circle(get_mouse_x(), get_mouse_y(), brushSize, colors[colorSelected]) - # Draw top panel - draw_rectangle(0, 0, get_screen_width(), 50, RAYWHITE) - draw_line(0, 50, get_screen_width(), 50, LIGHTGRAY) - - # Draw color selection rectangles - for i in range(MAX_COLORS_COUNT): - draw_rectangle_rec(colorsRecs[i], colors[i]) - draw_rectangle_lines(10, 10, 30, 30, LIGHTGRAY) - - if colorMouseHover >= 0: draw_rectangle_rec(colorsRecs[colorMouseHover], fade(WHITE, 0.6)) - - draw_rectangle_lines_ex( - Rectangle(colorsRecs[colorSelected].x - 2, colorsRecs[colorSelected].y - 2, colorsRecs[colorSelected].width + 4, - colorsRecs[colorSelected].height + 4), 2, BLACK) - # Draw save image button - draw_rectangle_lines_ex(btnSaveRec, 2, RED if btnSaveMouseHover else BLACK) - draw_text("SAVE!", 755, 20, 10, RED if btnSaveMouseHover else BLACK) - - if showSaveMessage: - draw_rectangle(0, 0, get_screen_width(), get_screen_height(), fade(RAYWHITE, 0.8)) - draw_rectangle(0, 150, get_screen_width(), 80, BLACK) - draw_text("IMAGE SAVED: my_amazing_texture_painting.png", 150, 180, 20, RAYWHITE) - - end_drawing() - - # ---------------------------------------------------------------------------------- -# De-Initialization -# ---------------------------------------------------------------------------------- -unload_render_texture(target) # Unload render texture +# Execute the main function +if __name__ == '__main__': + main() -close_window() # Close window and OpenGL context diff --git a/examples/textures/textures_to_image.py b/examples/textures/textures_to_image.py index 96c50a4..012848b 100644 --- a/examples/textures/textures_to_image.py +++ b/examples/textures/textures_to_image.py @@ -1,54 +1,64 @@ """ -raylib [texture] example - To image +raylib [texture] example - To Image """ + +# Import +# ------------------------------------------------------------------------------------ from pyray import * -from raylib.colors import * +# ------------------------------------------------------------------------------------ -# Initialization -screenWidth = 800 -screenHeight = 450 +# ------------------------------------------------------------------------------------ +# Program main entry point +# ------------------------------------------------------------------------------------ +def main(): + # Initialization + # ---------------------------------------------------------------------------------- + SCREEN_WIDTH = 800 + SCREEN_HEIGHT = 450 -init_window(screenWidth, screenHeight, "raylib [textures] example - texture to image") + init_window(SCREEN_WIDTH, SCREEN_HEIGHT, "raylib [textures] example - texture to image") -# NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) + # NOTE: Textures MUST be loaded after Window initialization (OpenGL context is required) -image = load_image("resources/raylib_logo.png") # Load image data into CPU memory (RAM) -texture = load_texture_from_image(image) # Image converted to texture, GPU memory (RAM -> VRAM) -unload_image(image) # Unload image data from CPU memory (RAM) + image = load_image("resources/raylib_logo.png") # Load image data into CPU memory (RAM) + texture = load_texture_from_image(image) # Image converted to texture, GPU memory (RAM -> VRAM) + unload_image(image) # Unload image data from CPU memory (RAM) -image = load_image_from_texture(texture) # Load image from GPU texture (VRAM -> RAM) -unload_texture(texture) # Unload texture from GPU memory (VRAM) + image = load_image_from_texture(texture) # Load image from GPU texture (VRAM -> RAM) + unload_texture(texture) # Unload texture from GPU memory (VRAM) -texture = load_texture_from_image(image) # Recreate texture from retrieved image data (RAM -> VRAM) -unload_image(image) # Unload retrieved image data from CPU memory (RAM) -# --------------------------------------------------------------------------------------- + texture = load_texture_from_image(image) # Recreate texture from retrieved image data (RAM -> VRAM) + unload_image(image) # Unload retrieved image data from CPU memory (RAM) + # --------------------------------------------------------------------------------------- + # Main game loop + while not window_should_close(): # Detect window close button or ESC key + # Update + # ---------------------------------------------------------------------------------- + # TODO: Update your variables here + # ---------------------------------------------------------------------------------- -# Main game loop -while not window_should_close(): # Detect window close button or ESC key + # Draw + # ---------------------------------------------------------------------------------- + begin_drawing() - # Update - # ---------------------------------------------------------------------------------- - # TODO: Update your variables here - # ---------------------------------------------------------------------------------- + clear_background(RAYWHITE) - # Draw - # ---------------------------------------------------------------------------------- - begin_drawing() - - clear_background(RAYWHITE) + draw_texture(texture, int(SCREEN_WIDTH/2 - texture.width/2), int(SCREEN_HEIGHT/2 - texture.height/2), WHITE) - draw_texture(texture, int(screenWidth/2 - texture.width/2), int(screenHeight/2 - texture.height/2), WHITE) + draw_text("this IS a texture loaded from an image!", 300, 370, 10, GRAY) - draw_text("this IS a texture loaded from an image!", 300, 370, 10, GRAY) + end_drawing() + # ---------------------------------------------------------------------------------- - end_drawing() + # De-Initialization + # ---------------------------------------------------------------------------------- + close_window() # Close window and OpenGL context # ---------------------------------------------------------------------------------- -# De-Initialization -# ---------------------------------------------------------------------------------- -unload_texture(texture) # Unload render texture -close_window() # Close window and OpenGL context +# Execute the main function +if __name__ == '__main__': + main()