Pages

Se afișează postările cu eticheta linux. Afișați toate postările
Se afișează postările cu eticheta linux. Afișați toate postările

duminică, 16 ianuarie 2022

PyGame : How to use Box2D python package - part 002.

I've written a tutorial in the past about the python package called box2d, see this tutorial.
Today I will be more precise and I will show you a source code related to 2D simulation.
I installed the python package in the Fedora 35 Linux distribution with the DNF tool:
[root@fedora mythcat]# dnf search pybox2d
...
python3-pybox2d.x86_64 : A 2D rigid body simulation library for Python
[root@fedora mythcat]# dnf install python3-pybox2d.x86_64
Last metadata expiration check: 0:18:37 ago on Sun 16 Jan 2022 10:15:43 AM EET.
Dependencies resolved.
...
Installed:
  python3-pybox2d-2.3.2-17.fc35.x86_64                                          

Complete!
I created the working folders and the first python file named example001.py:
[mythcat@fedora ~]$ mkdir PyGameProjects
[mythcat@fedora ~]$ cd PyGameProjects/
[mythcat@fedora PyGameProjects]$ touch example001.py
[mythcat@fedora PyGameProjects]$ vi example001.py
It contains a default source code:
from Box2D import (b2PolygonShape, b2World)
# create word 
world = b2World()  
# set the world 
groundBody = world.CreateStaticBody(position=(0, -10),
                                    shapes=b2PolygonShape(box=(50, 10)),
                                    )
# create a dynamic body at position
body = world.CreateDynamicBody(position=(0, 4))

# add and set a box fixture onto it with a nonzero density, so it will move
box = body.CreatePolygonFixture(box=(1, 1), density=1, friction=0.3)

# use a time step of 1/60 of a second
timeStep = 1.0 / 60

# simulation scenario with 6 velocity/2 position iterations
vel_iters, pos_iters = 6, 2

# the game loop.
for i in range(60):
    # use step of simulation
    world.Step(timeStep, vel_iters, pos_iters)

    # clear body forces even I didn't apply any forces
    world.ClearForces()

    # print the position and angle of the body.
    print(body.position, body.angle)
The result of the run looks like this:
...
b2Vec2(1.8719e-08,1.01496) 6.208252216310939e-06
b2Vec2(1.90152e-08,1.01497) 4.9494738050270826e-06
For a more complex example we created two python files.
One is a class for a box and a file that calls the class.
The first file contains the following source code is named box.py:
import pygame
from Box2D import (b2EdgeShape, b2FixtureDef, b2PolygonShape, b2_dynamicBody,
                   b2_kinematicBody, b2_staticBody, b2World)

class Box:
    def __init__(self, x, y, l, world):
        self.x = x / l
        self.y = y / l
        self.w = .2
        self.h = .2

        self.world = world
        self.attachment = self.world.CreateDynamicBody(
            position=(self.x, self.y),
            fixtures=b2FixtureDef(
                shape=b2PolygonShape(box=(self.w, self.h)), density=0.4, friction = 0.4),)
                
    def display(self, screen):
        for body in self.world.bodies:
            for fixture in body.fixtures:
                shape = fixture.shape
                vertices = [(body.transform * v) * 20 for v in shape.vertices]
                pygame.draw.polygon(screen, 'azure', vertices)
                pygame.draw.polygon(screen, 'blue', vertices,width=3)
The file calling the class has the following source code:
import pygame
from box import Box
from Box2D import b2World

l = 20
fps = 60
frame_rate = 1.0 / fps

pygame.init()
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Physics")
clock = pygame.time.Clock()

# A list for all of our rectangles
list_boxes = []
world = b2World(gravity=(0, 9.8), doSleep=False)

close = False

while not close:
    
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            close = True
    
    screen.fill('white')

    click, _, _ = pygame.mouse.get_pressed()    
    if click == 1:
        x,y = pygame.mouse.get_pos()
        box = Box(x, y, l, world)
        list_boxes.append(box)

    for box in list_boxes:
        box.display(screen)

    world.Step(frame_rate, 10, 10)
    pygame.display.flip()
    clock.tick(fps)

pygame.quit()
The result of running this file looks like this screenshot with some squares moving to the bottom:

sâmbătă, 7 noiembrie 2020

PyGame : Install pygame 2.0 from GitHub on Linux.

Let's install all Fedora packages need for this python package:
[root@desk pygame]# dnf install SDL2-devel.x86_64 
...
Installed:
  SDL2-devel-2.0.12-4.fc33.x86_64                                               

Complete!
[root@desk pygame]# dnf install SDL2_ttf-devel.x86_64
...
Installed:
  SDL2_ttf-2.0.15-6.fc33.x86_64       SDL2_ttf-devel-2.0.15-6.fc33.x86_64      

Complete!
[root@desk pygame]# dnf install SDL2_image-devel.x86_64
...
Installed:
  SDL2_image-2.0.5-5.fc33.x86_64      SDL2_image-devel-2.0.5-5.fc33.x86_64     

Complete!
[root@desk pygame]# dnf install SDL2_mixer-devel.x86_64 
...
Installed:
  SDL2_mixer-2.0.4-7.fc33.x86_64      SDL2_mixer-devel-2.0.4-7.fc33.x86_64     

Complete!
[root@desk pygame]# dnf install SDL2_gfx-devel.x86_64 
...
Installed:
  SDL2_gfx-1.0.4-3.fc33.x86_64        SDL2_gfx-devel-1.0.4-3.fc33.x86_64       

Complete!
[root@desk pygame]# dnf install portmidi-devel.x86_64 
...
Installed:
  portmidi-devel-217-38.fc33.x86_64                                             

Complete!
Use this command to clone it from GitHub and install it:
[mythcat@desk ~]$ git clone https://github.com/pygame/pygame
Cloning into 'pygame'...
remote: Enumerating objects: 4, done.
remote: Counting objects: 100% (4/4), done.
remote: Compressing objects: 100% (4/4), done.
remote: Total 38509 (delta 0), reused 0 (delta 0), pack-reused 38505
Receiving objects: 100% (38509/38509), 17.78 MiB | 11.66 MiB/s, done.
Resolving deltas: 100% (29718/29718), done.
[mythcat@desk ~]$ cd pygame/
[mythcat@desk pygame]$ python3.9 setup.py install --user


WARNING, No "Setup" File Exists, Running "buildconfig/config.py"
Using UNIX configuration...


Hunting dependencies...
SDL     : found 2.0.12
FONT    : found
IMAGE   : found
MIXER   : found
PNG     : found
JPEG    : found
SCRAP   : found
PORTMIDI: found
PORTTIME: found
FREETYPE: found 23.4.17

If you get compiler errors during install, double-check
the compiler flags in the "Setup" file.
...
copying docs/pygame_tiny.gif -> build/bdist.linux-x86_64/egg/pygame/docs
creating build/bdist.linux-x86_64/egg/EGG-INFO
copying pygame.egg-info/PKG-INFO -> build/bdist.linux-x86_64/egg/EGG-INFO
copying pygame.egg-info/SOURCES.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying pygame.egg-info/dependency_links.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying pygame.egg-info/entry_points.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
copying pygame.egg-info/not-zip-safe -> build/bdist.linux-x86_64/egg/EGG-INFO
copying pygame.egg-info/top_level.txt -> build/bdist.linux-x86_64/egg/EGG-INFO
writing build/bdist.linux-x86_64/egg/EGG-INFO/native_libs.txt
creating dist
creating 'dist/pygame-2.0.1.dev1-py3.9-linux-x86_64.egg' and adding 'build/bdist.linux-x86_64/egg' to it
removing 'build/bdist.linux-x86_64/egg' (and everything under it)
Processing pygame-2.0.1.dev1-py3.9-linux-x86_64.egg
creating /home/mythcat/.local/lib/python3.9/site-packages/pygame-2.0.1.dev1-py3.9-linux-x86_64.egg
Extracting pygame-2.0.1.dev1-py3.9-linux-x86_64.egg to /home/mythcat/.local/lib/python3.9/site-packages
Adding pygame 2.0.1.dev1 to easy-install.pth file

Installed /home/mythcat/.local/lib/python3.9/site-packages/pygame-2.0.1.dev1-py3.9-linux-x86_64.egg
Processing dependencies for pygame==2.0.1.dev1
Finished processing dependencies for pygame==2.0.1.dev1
Let's test it:
[mythcat@desk pygame]$ ls
build	     dist  examples	    README.rst	setup.cfg  src_c   test
buildconfig  docs  pygame.egg-info  Setup	setup.py   src_py
[mythcat@desk pygame]$ python3.9
Python 3.9.0 (default, Oct  6 2020, 00:00:00) 
[GCC 10.2.1 20200826 (Red Hat 10.2.1-3)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame 2.0.1.dev1 (SDL 2.0.12, python 3.9.0)
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> 

sâmbătă, 28 decembrie 2019

PyGame : Game pygame-medic-snake.

I made this game because I had a broken tooth and now I haven't found a dentist for the holidays.
Until I get the pain or I get to the dentist I started writing this game.
The game is simple to use and comes today with version 0.0.1.
See the full source code at my GitHub account.

joi, 26 decembrie 2019

PyGame : How to use Box2D python package - part 001.

About this python package the official GitHub comes with this intro:
pybox2d is a 2D physics library for your games and simple simulations. It's based on the Box2D library, written in C++. It supports several shape types (circle, polygon, thin line segments), and quite a few joint types (revolute, prismatic, wheel, etc.).
In the first step, you need to install the swig Fedora package.
About swig the official webpage tells us:
SWIG is an interface compiler that connects programs written in C and C++ with scripting languages such as Perl, Python, Ruby, and Tcl. It works by taking the declarations found in C/C++ header files and using them to generate the wrapper code that scripting languages need to access the underlying C/C++ code. In addition, SWIG provides a variety of customization features that let you tailor the wrapping process to suit your application.
I install it with DNF tool:
[root@desk mythcat]# dnf install swig.x86_64
Last metadata expiration check: 0:00:43 ago on Thu 26 Dec 2019 10:40:53 PM EET.
Dependencies resolved.
====================================================================================
 Package         Architecture      Version                 Repository          Size
====================================================================================
Installing:
 swig            x86_64            4.0.1-3.fc31            updates            1.4 M

Transaction Summary
====================================================================================
Install  1 Package

Total download size: 1.4 M
Installed size: 5.7 M
Is this ok [y/N]: y
Downloading Packages:
swig-4.0.1-3.fc31.x86_64.rpm                        1.7 MB/s | 1.4 MB     00:00    
------------------------------------------------------------------------------------
Total                                               863 kB/s | 1.4 MB     00:01     
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
  Preparing        :                                                            1/1 
  Installing       : swig-4.0.1-3.fc31.x86_64                                   1/1 
  Running scriptlet: swig-4.0.1-3.fc31.x86_64                                   1/1 
  Verifying        : swig-4.0.1-3.fc31.x86_64                                   1/1 

Installed:
  swig-4.0.1-3.fc31.x86_64                                                          

Complete!
I used the last version of the Box2D python package:
[mythcat@desk ~]$ git clone https://github.com/pybox2d/pybox2d
Cloning into 'pybox2d'...
remote: Enumerating objects: 2922, done.
remote: Total 2922 (delta 0), reused 0 (delta 0), pack-reused 2922
Receiving objects: 100% (2922/2922), 9.12 MiB | 4.04 MiB/s, done.
Resolving deltas: 100% (1832/1832), done.
[mythcat@desk ~]$ cd pybox2d/
[mythcat@desk pybox2d]$ python setup.py clean
Using setuptools (version 41.2.0).
running clean
[mythcat@desk pybox2d]$ python setup.py build
Using setuptools (version 41.2.0).
running build
running build_py
creating build
creating build/lib.linux-x86_64-3.7
creating build/lib.linux-x86_64-3.7/Box2D
...
[mythcat@desk pybox2d]$ python setup.py install --user
Using setuptools (version 41.2.0).
running install
running bdist_egg
running egg_info
...
Processing dependencies for Box2D==2.3.2
Finished processing dependencies for Box2D==2.3.2
Let's try these two examples from the official webpage:
[mythcat@desk ~]$ python3 simple_01.py
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Done!
[mythcat@desk ~]$ python3 simple_02.py
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
Done!
These screenshots results for the first script:

... and for the second one:

sâmbătă, 21 decembrie 2019

PyGame : Install and test pygame on Fedora 31 distro.

The install of the python package named pygame on Fedora Linux distro is very simple with the pip3 tool for python 3 version.
[mythcat@desk ~]$ pip3 install pygame --user
Collecting pygame
...
Installing collected packages: pygame
Successfully installed pygame-1.9.6
After install you can check this python package with this source code:
[mythcat@desk ~]$ python3 
Python 3.7.5 (default, Dec 15 2019, 17:54:26) 
[GCC 9.2.1 20190827 (Red Hat 9.2.1-1)] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> from pygame import *
>>> print(pygame.__version__)
1.9.6
>>> dir(pygame)
['ACTIVEEVENT', 'ANYFORMAT', 'ASYNCBLIT', 'AUDIODEVICEADDED', 'AUDIODEVICEREMOVED', 
'AUDIO_ALLOW_ANY_CHANGE', 'AUDIO_ALLOW_CHANNELS_CHANGE', 'AUDIO_ALLOW_FORMAT_CHANGE',
 'AUDIO_ALLOW_FREQUENCY_CHANGE', 'AUDIO_S16', 'AUDIO_S16LSB', 'AUDIO_S16MSB', 'AUDIO_S16SYS',
 'AUDIO_S8', 'AUDIO_U16', 'AUDIO_U16LSB', 'AUDIO_U16MSB', 'AUDIO_U16SYS', 'AUDIO_U8', 
'BIG_ENDIAN', 'BLEND_ADD', 'BLEND_MAX', 'BLEND_MIN', 'BLEND_MULT', 'BLEND_PREMULTIPLIED', 'BLEND_RGBA_ADD',
 'BLEND_RGBA_MAX', 'BLEND_RGBA_MIN', 'BLEND_RGBA_MULT', 'BLEND_RGBA_SUB', 'BLEND_RGB_ADD', 'BLEND_RGB_MAX',
 'BLEND_RGB_MIN', 'BLEND_RGB_MULT', 'BLEND_RGB_SUB', 'BLEND_SUB', 'BUTTON_LEFT', 'BUTTON_MIDDLE', 'BUTTON_RIGHT',
 'BUTTON_WHEELDOWN', 'BUTTON_WHEELUP', 'BUTTON_X1', 'BUTTON_X2', 'BufferError', 'BufferProxy', 'Color',
 'DOUBLEBUF', 'DROPBEGIN', 'DROPCOMPLETE', 'DROPFILE', 'DROPTEXT', 'FINGERDOWN', 'FINGERMOTION', 'FINGERUP',
 'FULLSCREEN', 'GL_ACCELERATED_VISUAL', 'GL_ACCUM_ALPHA_SIZE', 'GL_ACCUM_BLUE_SIZE', 'GL_ACCUM_GREEN_SIZE',
 'GL_ACCUM_RED_SIZE', 'GL_ALPHA_SIZE', 'GL_BLUE_SIZE', 'GL_BUFFER_SIZE', 'GL_DEPTH_SIZE', 'GL_DOUBLEBUFFER',
 'GL_GREEN_SIZE', 'GL_MULTISAMPLEBUFFERS', 'GL_MULTISAMPLESAMPLES', 'GL_RED_SIZE', 'GL_STENCIL_SIZE', 'GL_STEREO',
 'GL_SWAP_CONTROL', 'HAT_CENTERED', 'HAT_DOWN', 'HAT_LEFT', 'HAT_LEFTDOWN', 'HAT_LEFTUP', 'HAT_RIGHT', 
'HAT_RIGHTDOWN', 'HAT_RIGHTUP', 'HAT_UP', 'HAVE_NEWBUF', 'HWACCEL', 'HWPALETTE', 'HWSURFACE', 'IYUV_OVERLAY',
 'JOYAXISMOTION', 'JOYBALLMOTION', 'JOYBUTTONDOWN', 'JOYBUTTONUP', 'JOYHATMOTION', 'KEYDOWN', 'KEYUP', 'KMOD_ALT',
 'KMOD_CAPS', 'KMOD_CTRL', 'KMOD_LALT', 'KMOD_LCTRL', 'KMOD_LMETA', 'KMOD_LSHIFT', 'KMOD_META', 'KMOD_MODE',
 'KMOD_NONE', 'KMOD_NUM', 'KMOD_RALT', 'KMOD_RCTRL', 'KMOD_RMETA', 'KMOD_RSHIFT', 'KMOD_SHIFT', 'K_0', 'K_1',
 'K_2', 'K_3', 'K_4', 'K_5', 'K_6', 'K_7', 'K_8', 'K_9', 'K_AMPERSAND', 'K_ASTERISK', 'K_AT', 'K_BACKQUOTE',
 'K_BACKSLASH', 'K_BACKSPACE', 'K_BREAK', 'K_CAPSLOCK', 'K_CARET', 'K_CLEAR', 'K_COLON', 'K_COMMA', 'K_DELETE',
 'K_DOLLAR', 'K_DOWN', 'K_END', 'K_EQUALS', 'K_ESCAPE', 'K_EURO', 'K_EXCLAIM', 'K_F1', 'K_F10', 'K_F11', 'K_F12',
 'K_F13', 'K_F14', 'K_F15', 'K_F2', 'K_F3', 'K_F4', 'K_F5', 'K_F6', 'K_F7', 'K_F8', 'K_F9', 'K_FIRST', 'K_GREATER',
 'K_HASH', 'K_HELP', 'K_HOME', 'K_INSERT', 'K_KP0', 'K_KP1', 'K_KP2', 'K_KP3', 'K_KP4', 'K_KP5', 'K_KP6', 'K_KP7',
 'K_KP8', 'K_KP9', 'K_KP_DIVIDE', 'K_KP_ENTER', 'K_KP_EQUALS', 'K_KP_MINUS', 'K_KP_MULTIPLY', 'K_KP_PERIOD',
 'K_KP_PLUS', 'K_LALT', 'K_LAST', 'K_LCTRL', 'K_LEFT', 'K_LEFTBRACKET', 'K_LEFTPAREN', 'K_LESS', 'K_LMETA', 
'K_LSHIFT', 'K_LSUPER', 'K_MENU', 'K_MINUS', 'K_MODE', 'K_NUMLOCK', 'K_PAGEDOWN', 'K_PAGEUP', 'K_PAUSE',
 'K_PERIOD', 'K_PLUS', 'K_POWER', 'K_PRINT', 'K_QUESTION', 'K_QUOTE', 'K_QUOTEDBL', 'K_RALT', 'K_RCTRL',
 'K_RETURN', 'K_RIGHT', 'K_RIGHTBRACKET', 'K_RIGHTPAREN', 'K_RMETA', 'K_RSHIFT', 'K_RSUPER', 'K_SCROLLOCK',
 'K_SEMICOLON', 'K_SLASH', 'K_SPACE', 'K_SYSREQ', 'K_TAB', 'K_UNDERSCORE', 'K_UNKNOWN', 'K_UP', 'K_a', 'K_b',
 'K_c', 'K_d', 'K_e', 'K_f', 'K_g', 'K_h', 'K_i', 'K_j', 'K_k', 'K_l', 'K_m', 'K_n', 'K_o', 'K_p', 'K_q',
 'K_r', 'K_s', 'K_t', 'K_u', 'K_v', 'K_w', 'K_x', 'K_y', 'K_z', 'LIL_ENDIAN', 'MOUSEBUTTONDOWN', 'MOUSEBUTTONUP',
 'MOUSEMOTION', 'MOUSEWHEEL', 'MULTIGESTURE', 'Mask', 'NOEVENT', 'NOFRAME', 'NUMEVENTS', 'OPENGL', 'OPENGLBLIT',
 'Overlay', 'PREALLOC', 'PixelArray', 'PygameVersion', 'QUIT', 'RESIZABLE', 'RLEACCEL', 'RLEACCELOK', 'Rect',
 'SCRAP_BMP', 'SCRAP_CLIPBOARD', 'SCRAP_PBM', 'SCRAP_PPM', 'SCRAP_SELECTION', 'SCRAP_TEXT', 'SRCALPHA',
 'SRCCOLORKEY', 'SWSURFACE', 'SYSWMEVENT', 'Surface', 'SurfaceType', 'TEXTEDITING', 'TEXTINPUT',
 'TIMER_RESOLUTION', 'USEREVENT', 'USEREVENT_DROPFILE', 'UYVY_OVERLAY', 'VIDEOEXPOSE', 'VIDEORESIZE',
 'Vector2', 'Vector3', 'WINDOWEVENT', 'WINDOWEVENT_CLOSE', 'YUY2_OVERLAY', 'YV12_OVERLAY', 'YVYU_OVERLAY',
 '__builtins__', '__cached__', '__color_constructor','__color_reduce', '__doc__', '__file__', '__loader__',
 '__name__', '__package__', '__path__', '__rect_constructor', '__rect_reduce', '__spec__', '__version__',
'_numpysndarray', '_numpysurfarray', 'base', 'bufferproxy', 'cdrom', 'color', 'colordict', 'compat',
 'constants', 'cursors', 'display', 'draw', 'encode_file_path', 'encode_string', 'error', 'event', 'fastevent',
 'font', 'get_array_interface', 'get_error', 'get_init', 'get_sdl_byteorder', 'get_sdl_version', 'image',
 'init', 'joystick', 'key', 'mask', 'math', 'mixer', 'mixer_music', 'mouse', 'movie', 'overlay',
 'packager_imports','pixelarray', 'pixelcopy', 'quit', 'rect', 'register_quit', 'rev', 'rwobject',
 'scrap', 'segfault', 'set_error', 'sndarray', 'sprite', 'surface', 'surfarray', 'sysfont', 'threads',
 'time', 'transform', 'ver', 'vernum', 'version', 'warn_unwanted_files']
This shows us all the features of the pygame package.