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.
windows,linux, tutorials, tutorial, pygame, ,development,programming,source code,code,example,examples,All with pygame python module. The pygame-catalin is a blog created by Catalin George Festila.
sâmbătă, 28 decembrie 2019
PyGame : Game pygame-medic-snake.
Posted by
Cătălin George Feștilă
Labels:
2019,
Fedora,
Fedora 31,
game,
games,
linux,
pygame,
python,
python 3,
python module,
python package,
source code,
tutorial,
tutorials
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:
... and for the second one:
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:
Posted by
Cătălin George Feștilă
Labels:
2019,
Box2D,
Fedora,
Fedora 31,
linux,
pybox2d,
pygame,
python,
python 3,
python module,
python package,
source code,
tutorial,
tutorials
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.
Posted by
Cătălin George Feștilă
Labels:
2019,
Fedora,
Fedora 31,
linux,
pygame,
python,
python 3,
python module,
python package,
source code,
tutorial,
tutorials
joi, 1 august 2019
PyGame : First interface - part 11.
This is python module named pygameMenu can help us to develop another step into the interface issue.
This python module is simple, lightweight and easy to use and the last release from a day ago comes with the version is 2.0.1.
The install step is easy with the pip tool:
pip install pygame-menu==2.0.1
Collecting pygame-menu==2.0.1
...
Successfully uninstalled pygame-menu-1.96.1
Successfully installed pygame-menu-2.0.1 pyperclip-1.7.0
This python module are supported by currently python 2.7+ and 3.4+ (3.4, 3.5, 3.6, 3.7).
You need to have the pygame python module install it on your operating system.
If not you will get this error then reinstall the pygame with pip3 tool:
...
from pygame.base import *
ModuleNotFoundError: No module named 'pygame.base'
You cam find more here.
Let's see one simple example:
import sys
import pygame
import pygameMenu
from random import randint
from random import randrange
from pygame.locals import *
from pygameMenu.locals import*
# create the menu
class GameMenu():
# this will used on click's
def test(self):
print('test')
# this will create the menu with some features
def my_menu_game(self):
self.my_menu_game = pygameMenu.Menu(get_display,
font=pygameMenu.font.FONT_BEBAS,
dopause=False,
menu_color=(0, 10, 176), # Background color
menu_color_title=(0, 76, 76),
menu_height= 240,
menu_width=320,
onclose=pygameMenu.events.DISABLE_CLOSE,
option_shadow=True,
option_shadow_position=pygameMenu.locals.POSITION_SOUTHEAST,
title='Help',
window_height=480,
window_width=640
)
# add some items on menu
self.my_menu_game.add_option('Test!', self.test)
self.my_menu_game.add_selector('Select', [('eazy', 'EASY'),
('medium', 'MEDIUM'),
('hard', 'HARD')],
onreturn = False,
onchange = self.test)
self.my_menu_game.add_option('Exit', self.test)
# Loop the game and get menu events
while True:
# clock count
clock.tick(60)
# events for menu
events = pygame.event.get()
for event in events:
if event.type == QUIT:
pygame.quit()
sys.exit()
# create menu
self.my_menu_game.mainloop(events)
# the flip display function
pygame.display.flip()
# init the pygame
pygame.init()
# default pygame init
get_display=pygame.display.set_mode((640,480))
pygame.display.set_caption("My Menu")
clock = pygame.time.Clock()
# create the menu
game_menu = GameMenu()
game_menu.my_menu_game()
The result of this source code can be see into the next screenshot:
Posted by
Cătălin George Feștilă
Labels:
2019,
2019 news,
news,
pygame,
pygame-menu,
python,
python 3,
python module,
tutorial,
tutorials
sâmbătă, 6 iulie 2019
PyGame : Using the fullscreen with PyGame.
In this tutorial, I will show you how to use the fullscreen feature with pygame python module.
The scrip I used uses two keys: F12 for fullscreen and ESC for quit to windows.
The script starts with the default initialization of the PyGame python module.
The open the window in fullscreen with a resolution of 1024x768.
Using the while True condition you can change it into window mode with a resolution of 640x480 by pressing the F12 key.
In this loop is set the key ESC to quit the application.
The scrip I used uses two keys: F12 for fullscreen and ESC for quit to windows.
The script starts with the default initialization of the PyGame python module.
The open the window in fullscreen with a resolution of 1024x768.
Using the while True condition you can change it into window mode with a resolution of 640x480 by pressing the F12 key.
In this loop is set the key ESC to quit the application.
import pygame,sys
pygame.init()
#set the fullscreen - my display is 1024 by 576
screen = pygame.display.set_mode((1024, 576),pygame.FULLSCREEN,32)
pygame.display.set_caption("Example fullscreen")
cursor_x,cursor_y = 0,0
cmddown = False
fullscreen = True
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
#Toggle Fullscreen (press escape to exit/enter fullscreen)
if event.key == pygame.K_F12:
if fullscreen == True:
#exits fullscreen
screen = pygame.display.set_mode((640, 480))
pygame.display.set_caption("Example window 640x480")
fullscreen = False
else:
screen = pygame.display.set_mode((1024, 576),pygame.FULLSCREEN,32)
pygame.display.set_caption("Example fullscreen 1024x768")
fullscreen = True
if event.key == pygame.K_ESCAPE:
if cmddown == True:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYUP:
cmddown = False
screen.fill((0,0,0))
pygame.display.flip()
sâmbătă, 1 iunie 2019
PyGame : Testing example of pygame module.
The Pygame python module is a good way to start programming games.
This python module comes with examples, see the official webpage.
These should help get you started with Pygame.
The source code for these examples is in the public domain.
Today I will show you how to find and run an example from this python module.
Let's start with these commands:
This python module comes with examples, see the official webpage.
These should help get you started with Pygame.
The source code for these examples is in the public domain.
Today I will show you how to find and run an example from this python module.
Let's start with these commands:
C:\Python373>python
Python 3.7.3 (v3.7.3:ef4ec6ed12, Mar 25 2019, 22:22:05) [MSC v.1916 64 bit (AMD6
4)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pygame.examples.aliens
pygame 1.9.6
Hello from the pygame community. https://www.pygame.org/contribute.html
>>> pygame.examples.aliens.__file__
'C:\\Python373\\lib\\site-packages\\pygame\\examples\\aliens.py'
>>> pygame.examples.aliens.main()
The result of running the aliens game.
Posted by
Cătălin George Feștilă
Labels:
2019,
pygame,
python,
python 3,
python module,
tutorial,
tutorials
joi, 30 mai 2019
PyGame : First interface - part 10.
Today I will create a maze can be used into pygame interface gaming area.
The algorithm starts at a random cell.
Mark the current cell as visited, and get a list of its neighbors.
Now, for each neighbor, starting with a randomly selected neighbor.
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor.
Use this recourse idea with that neighbor as the current cell.
Let's see the source code:
The algorithm starts at a random cell.
Mark the current cell as visited, and get a list of its neighbors.
Now, for each neighbor, starting with a randomly selected neighbor.
If that neighbor hasn't been visited, remove the wall between this cell and that neighbor.
Use this recourse idea with that neighbor as the current cell.
Let's see the source code:
import os
import pygame
from pygame.locals import *
from random import choice
# create a maze cell with rect sized 6 pixels
class maze_cell(pygame.sprite.Sprite):
w, h = 6, 6
def __init__(self, x, y, maze):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface([self.w, self.h])
self.image.fill((0, 0, 255))
self.rect = self.image.get_rect()
self.rect.x = x * self.w
self.rect.y = y * self.h
self.x = x
self.y = y
self.maze = maze
self.nbs = [(x + nx, y + ny) for nx, ny in ((-2, 0), (0, -2), (2, 0), (0, 2))
if 0 <= x + nx < maze.w and 0 <= y + ny < maze.h]
# draw screen with pygame blit
def draw(self, screen):
screen.blit(self.image, self.rect)
# create the maze wall
class maze_wall(maze_cell):
def __init__(self, x, y, maze):
super(maze_wall, self).__init__(x, y, maze)
self.image.fill((0, 0, 0))
self.type = 0
# create the maze by generate into grid
class create_maze:
def __init__(self, size):
self.w, self.h = size[0] // maze_cell.w, size[1] // maze_cell.h
self.grid = [[maze_wall(x, y, self) for y in range(self.h)] for x in range(self.w)]
def get(self, x, y):
return self.grid[x][y]
def place_maze_wall(self, x, y):
self.grid[x][y] = maze_wall(x, y, self)
def draw(self, screen):
for row in self.grid:
for maze_cell in row:
maze_cell.draw(screen)
def generate(self, screen=None, animate=False):
unvisited = [c for r in self.grid for c in r if c.x % 2 and c.y % 2]
cur = unvisited.pop()
stack = []
while unvisited:
try:
n = choice([c for c in map(lambda x: self.get(*x), cur.nbs) if c in unvisited])
stack.append(cur)
nx, ny = cur.x - (cur.x - n.x) // 2, cur.y - (cur.y - n.y) // 2
self.grid[nx][ny] = maze_cell(nx, ny, self)
self.grid[cur.x][cur.y] = maze_cell(cur.x, cur.y, self)
cur = n
unvisited.remove(n)
if animate:
self.draw(screen)
pygame.display.update()
pygame.time.wait(10)
except IndexError:
if stack:
cur = stack.pop()
def draw_maze(screen):
maze = create_maze(WINSIZE)
maze.generate(screen, True)
WINSIZE = (maze_cell.w * 76, maze_cell.h * 76)
def main():
pygame.init()
screen = pygame.display.set_mode(WINSIZE)
pygame.display.set_caption('Generate maze')
screen.fill((0, 0, 0))
clock = pygame.time.Clock()
draw_maze(screen)
done = 0
while not done:
for e in pygame.event.get():
if e.type == QUIT or (e.type == KEYUP and e.key == K_ESCAPE):
done = 1
pygame.display.update()
clock.tick()
if __name__ == '__main__':
main()
The result of this source code:
Posted by
Cătălin George Feștilă
Labels:
2019,
pygame,
python,
python 3,
python module,
tutorial,
tutorials
marți, 28 mai 2019
PyGame : First interface - part 9.
Today I start with another tutorial with pygame python module and python version 3.7.3.
For this series of tutorials, I will introduce you a radar interface.
The advantages of using such an interface are evident from technical considerations and not only. This type of interface is very used in games because most users have become accustomed to it.
Let's start installing the pygame python module.
For this series of tutorials, I will introduce you a radar interface.
The advantages of using such an interface are evident from technical considerations and not only. This type of interface is very used in games because most users have become accustomed to it.
Let's start installing the pygame python module.
C:\Python373\Scripts>pip install pygame
Requirement already satisfied: pygame in c:\python373\lib\site-packages (1.9.6)
I try to follow some goals, like:- install pygame with pip tool for python 3.7.3;
- create an interface for drawing;
- use a configuration with values, see: screen_size;
- use events to stop the script;
- use line and circle with math and radians;
- use the pygame.gfxdraw module to draw lines and circles;
import pygame
import math
from pygame.locals import *
import pygame.gfxdraw
configuration = {
'screen_size': (500,500),
}
pygame.init()
screen = pygame.display.set_mode(configuration['screen_size'])
FPSCLOCK = pygame.time.Clock()
done = False
screen.fill((0, 0, 0))
azimuth_degrees=0
while not done:
screen.fill(0)
# get events
for e in pygame.event.get():
if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
done = True
break
screen.fill((0, 0, 0))
# radar position on window
radar = (250,250)
# radar lenght
radar_len = 276
for x in range(1, 250, 30):
# radar circle position on window
pygame.gfxdraw.circle(screen,radar[0],radar[1],x,(0,0,255))
# calculate the x and y radar beam
x = radar[0] + math.cos(math.radians( azimuth_degrees)) * radar_len
y = radar[1] + math.sin(math.radians( azimuth_degrees)) * radar_len
# then render the line radar with value (x,y)
pygame.gfxdraw.line(screen, radar[0],radar[1], int(x),int(y), Color("blue"))
pygame.display.flip()
azimuth_degrees+=1
FPSCLOCK.tick(40)
Posted by
Cătălin George Feștilă
Labels:
2019,
pygame,
python,
python 3,
python module,
tutorial,
tutorials
luni, 4 iunie 2018
PyGame : First interface - part 8.
The PyGame - first interface is a series of python tutorials using PyGame python module and other python modules that help us create a good interface.
If you look at the Wikipedia website then the first phrase is clear:
In computing, an interface is a shared boundary across which two or more separate components of a computer system exchange information.
Today I will start with ThorPy python module.
This python module comes with the version 1.5.9.
You can read more about this python and test examples at the official webpage.
You can install this python module with the pip tool:
This is the result of submenus from official website.
If you look at the Wikipedia website then the first phrase is clear:
In computing, an interface is a shared boundary across which two or more separate components of a computer system exchange information.
Today I will start with ThorPy python module.
This python module comes with the version 1.5.9.
You can read more about this python and test examples at the official webpage.
You can install this python module with the pip tool:
c:\Python364\Scripts>pip install thorpy
Collecting thorpy
Downloading https://files.pythonhosted.org/packages/09/aa/...
.../thorpy-1.6.tar.gz (373kB)
100% |████████████████████████████████| 378kB 374kB/s
<5 .10="" python_version=""><2 .0.0=""><2 .0.0="">...
Installing collected packages: thorpy
Successfully installed thorpy-1.62>2>5>
This is the result of submenus from official website.
Posted by
Cătălin George Feștilă
Labels:
2018,
GUI,
pygame,
python,
python 3,
python module,
thorpy,
tutorial,
tutorials
duminică, 28 ianuarie 2018
PyGame : Test with an animated image.
This is a simple tutorial about how to create a bouncing ball effect with pygame python module.
The source code is very simple and you need a transparent image named earth.png .
The variables I used is size, speed, ball, ballrect.
I used ballrect with get_rect().
The result get pygame Rect object.
This has several virtual attributes which can be used to move and align the Rect:
All of these attributes can be assigned to ballrect variable.
The source code is very simple and you need a transparent image named earth.png .
The variables I used is size, speed, ball, ballrect.
I used ballrect with get_rect().
The result get pygame Rect object.
This has several virtual attributes which can be used to move and align the Rect:
- x,y
- top, left, bottom, right
- topleft, bottomleft, topright, bottomright
- midtop, midleft, midbottom, midright
- center, centerx, centery
- size, width, height
- w,h
All of these attributes can be assigned to ballrect variable.
import sys
import pygame
pygame.init()
size = width, height = 640, 420
speed = [1, 1]
black = 0, 0, 0
screen = pygame.display.set_mode(size)
ball = pygame.image.load("earth.png")
ballrect = ball.get_rect()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
ballrect = ballrect.move(speed)
if ballrect.left < 0 or ballrect.right > width:
speed[0] = -speed[0]
if ballrect.top < 0 or ballrect.bottom > height:
speed[1] = -speed[1]
screen.fill(black)
screen.blit(ball, ballrect)
pygame.display.flip()
pygame.display.update()
The result of this source code :
Posted by
Cătălin George Feștilă
Labels:
2.7,
2018,
pygame,
pygame.display,
python,
python module,
tutorial,
tutorials
luni, 21 august 2017
PyGame : The pymunk python module.
First about pymunk python module:
Pymunk is an easy-to-use pythonic 2d physics library that can be used whenever you need 2d rigid body physics from Python. Perfect when you need 2d physics in your game, demo or other application!
I install it with pip and python 2.7 and I test it with one example from the official website.
The source code is this:
I test with this command:
Pymunk is an easy-to-use pythonic 2d physics library that can be used whenever you need 2d rigid body physics from Python. Perfect when you need 2d physics in your game, demo or other application!
I install it with pip and python 2.7 and I test it with one example from the official website.
The source code is this:
import sys, random
import os
description = """
---- Newton's Cradle ----
A screensaver version of Newton's Cradle with an interactive mode
/s - Run in fullscreen screensaver mode
/p #### - Display a preview of the screensaver using a window handler
/i - Interactive mode
"""
if len(sys.argv) < 2:
print(description)
sys.exit()
is_interactive = False
display_flags = 0
if sys.argv[1] == "/p": # preview mode
os.environ['SDL_VIDEODRIVER'] = 'windib'
os.environ['SDL_WINDOWID'] = sys.argv[2]
display_size = (100, 100)
is_interactive = False
### We must set OS env before the pygame imports..
import pygame
from pygame.locals import *
from pygame.color import *
if sys.argv[1] == "/s": # fullscreen screensaver mode
display_size = (0, 0)
is_interactive = False
display_flags = display_flags | FULLSCREEN # FULLSCREEN) # | DOUBLEBUF | HWSURFACE )
elif sys.argv[1] == "/i": # interactive
display_size = (600, 600)
is_interactive = True
import pymunk as pm
from pymunk import Vec2d
def drawcircle(image, colour, origin, radius, width=0):
if width == 0:
pygame.draw.circle(image, colour, origin, int(radius))
else:
if radius > 65534 / 5:
radius = 65534 / 5
circle = pygame.Surface([radius * 2 + width, radius * 2 + width]).convert_alpha()
circle.fill([0, 0, 0, 0])
pygame.draw.circle(circle, colour, [circle.get_width() / 2, circle.get_height() / 2], radius + (width / 2))
if int(radius - (width / 2)) > 0:
pygame.draw.circle(circle, [0, 0, 0, 0], [circle.get_width() / 2, circle.get_height() / 2],
abs(int(radius - (width / 2))))
image.blit(circle, [origin[0] - (circle.get_width() / 2), origin[1] - (circle.get_height() / 2)])
def reset_bodies(space):
for body in space.bodies:
body.position = Vec2d(body.start_position)
body.force = 0, 0
body.torque = 0
body.velocity = 0, 0
body.angular_velocity = 0
color = random.choice(list(THECOLORS.values()))
for shape in space.shapes:
shape.color = color
def main():
pygame.init()
screen = pygame.display.set_mode(display_size, display_flags)
width, height = screen.get_size()
def to_pygame(p):
"""Small hack to convert pymunk to pygame coordinates"""
return int(p.x), int(-p.y + height)
def from_pygame(p):
return to_pygame(p)
clock = pygame.time.Clock()
running = True
font = pygame.font.Font(None, 16)
### Physics stuff
space = pm.Space()
space.gravity = (0.0, -1900.0)
space.damping = 0.999 # to prevent it from blowing up.
mouse_body = pm.Body(body_type=pm.Body.KINEMATIC)
bodies = []
for x in range(-100, 150, 50):
x += width / 2
offset_y = height / 2
mass = 10
radius = 25
moment = pm.moment_for_circle(mass, 0, radius, (0, 0))
body = pm.Body(mass, moment)
body.position = (x, -125 + offset_y)
body.start_position = Vec2d(body.position)
shape = pm.Circle(body, radius)
shape.elasticity = 0.9999999
space.add(body, shape)
bodies.append(body)
pj = pm.PinJoint(space.static_body, body, (x, 125 + offset_y), (0, 0))
space.add(pj)
reset_bodies(space)
selected = None
if not is_interactive:
pygame.time.set_timer(USEREVENT + 1, 70000) # apply force
pygame.time.set_timer(USEREVENT + 2, 120000) # reset
pygame.event.post(pygame.event.Event(USEREVENT + 1))
pygame.mouse.set_visible(False)
while running:
for event in pygame.event.get():
if event.type == QUIT:
running = False
elif event.type == KEYDOWN and event.key == K_p:
pygame.image.save(screen, "newtons_cradle.png")
if event.type == pygame.USEREVENT + 1:
r = random.randint(1, 4)
for body in bodies[0:r]:
body.apply_impulse_at_local_point((-6000, 0))
if event.type == pygame.USEREVENT + 2:
reset_bodies(space)
elif event.type == KEYDOWN and event.key == K_r and is_interactive:
reset_bodies(space)
elif event.type == KEYDOWN and event.key == K_f and is_interactive:
r = random.randint(1, 4)
for body in bodies[0:r]:
body.apply_impulse_at_local_point((-6000, 0))
elif event.type == MOUSEBUTTONDOWN and is_interactive:
if selected != None:
space.remove(selected)
p = from_pygame(Vec2d(event.pos))
hit = space.point_query_nearest(p, 0, pm.ShapeFilter())
if hit != None:
shape = hit.shape
rest_length = mouse_body.position.get_distance(shape.body.position)
ds = pm.DampedSpring(mouse_body, shape.body, (0, 0), (0, 0), rest_length, 1000, 10)
space.add(ds)
selected = ds
elif event.type == MOUSEBUTTONUP and is_interactive:
if selected != None:
space.remove(selected)
selected = None
elif event.type == KEYDOWN:
running = False
elif event.type == MOUSEBUTTONDOWN:
running = False
mpos = pygame.mouse.get_pos()
p = from_pygame(Vec2d(mpos))
mouse_body.position = p
### Clear screen
screen.fill(THECOLORS["black"])
### Draw stuff
for c in space.constraints:
pv1 = c.a.position + c.anchor_a
pv2 = c.b.position + c.anchor_b
p1 = to_pygame(pv1)
p2 = to_pygame(pv2)
pygame.draw.aalines(screen, THECOLORS["lightgray"], False, [p1, p2])
for ball in space.shapes:
p = to_pygame(ball.body.position)
drawcircle(screen, ball.color, p, int(ball.radius), 0)
# pygame.draw.circle(screen, ball.color, p, int(ball.radius), 0)
### Update physics
fps = 50
iterations = 25
dt = 1.0 / float(fps) / float(iterations)
for x in range(iterations): # 10 iterations to get a more stable simulation
space.step(dt)
### Flip screen
if is_interactive:
screen.blit(font.render("fps: " + str(clock.get_fps()), 1, THECOLORS["white"]), (0, 0))
screen.blit(font.render("Press left mouse button and drag to interact", 1, THECOLORS["darkgrey"]),
(5, height - 35))
screen.blit(font.render("Press R to reset, any other key to quit", 1, THECOLORS["darkgrey"]),
(5, height - 20))
pygame.display.flip()
clock.tick(fps)
if __name__ == '__main__':
sys.exit(main()
I test with this command:
C:\Python27>python.exe newtons_cradle.py /i
The result work well, see the next image:
Posted by
Cătălin George Feștilă
Labels:
2.7,
2017,
pygame,
pymunk,
python,
python module,
tutorial,
tutorials
sâmbătă, 29 iulie 2017
PyGame : The experimental gfxdraw.
This is a tutorial about gfxdraw how to use.
Note: this is an EXPERIMENTAL feature for PyGame ( meaning this API may change, or disappear in later pygame releases).
First about this gfxdraw we can use this:
This class used pygame.gfxdraw.aaellipse , see the doc:
pygame.gfxdraw.aaellipse()
draw an anti-aliased ellipse
aaellipse(surface, x, y, rx, ry, color) -> None
Draws anti aliased edges of an ellipse onto a surface.
The shell_print is used just to print a input text to python shell.
The aaellipse take all inputs for the default pygame.gfxdraw.ellipse.
The result is a simple blue ellipse at 300 and 200 points and sized with 100 and 60.
Another aspect to note is use of the surface into show.aaellipse : show.screen.
This means that the drawing screen is used and not another defined surface.
Of course we can change Screen class to help us - decorators, other defining surfaces, initializations...
Note: this is an EXPERIMENTAL feature for PyGame ( meaning this API may change, or disappear in later pygame releases).
First about this gfxdraw we can use this:
- pygame module for drawing shapes
- pygame.gfxdraw.pixel — place a pixel
- pygame.gfxdraw.hline — draw a horizontal line
- pygame.gfxdraw.vline — draw a vertical line
- pygame.gfxdraw.rectangle — draw a rectangle
- pygame.gfxdraw.box — draw a box
- pygame.gfxdraw.line — draw a line
- pygame.gfxdraw.circle — draw a circle
- pygame.gfxdraw.arc — draw an arc
- pygame.gfxdraw.aacircle — draw an anti-aliased circle
- pygame.gfxdraw.filled_circle — draw a filled circle
- pygame.gfxdraw.ellipse — draw an ellipse
- pygame.gfxdraw.aaellipse — draw an anti-aliased ellipse
- pygame.gfxdraw.filled_ellipse — draw a filled ellipse
- pygame.gfxdraw.pie — draw a pie
- pygame.gfxdraw.trigon — draw a triangle
- pygame.gfxdraw.aatrigon — draw an anti-aliased triangle
- pygame.gfxdraw.filled_trigon — draw a filled trigon
- pygame.gfxdraw.polygon — draw a polygon
- pygame.gfxdraw.aapolygon — draw an anti-aliased polygon
- pygame.gfxdraw.filled_polygon — draw a filled polygon
- pygame.gfxdraw.textured_polygon — draw a textured polygon
- pygame.gfxdraw.bezier — draw a Bézier curve
This class used pygame.gfxdraw.aaellipse , see the doc:
pygame.gfxdraw.aaellipse()
draw an anti-aliased ellipse
aaellipse(surface, x, y, rx, ry, color) -> None
Draws anti aliased edges of an ellipse onto a surface.
#!/usr/bin/python
import random
import math
import pygame
from pygame.locals import *
from pygame import *
from pygame import gfxdraw
#create a math function
def linear_interp(a, b, x):
return a*(1-x) + b*x
#a class python to show on display
class Screen():
def __init__(self):
pygame.init()
self.display_flags = DOUBLEBUF
rect = self.width, self.height = 640, 480
if pygame.display.mode_ok(rect, self.display_flags):
self.screen = pygame.display.set_mode(rect, self.display_flags)
def shell_print(self,text):
print text
def aaellipse(self,surface, x, y, rx, ry, color):
pygame.gfxdraw.ellipse(surface, x, y, rx, ry, color)
show = Screen()
run = 1
clock = pygame.time.Clock()
show.shell_print("test")
show.aaellipse(show.screen, x=300, y=200, rx=100, ry=60, color=(8, 8, 160))
while run:
events = pygame.event.get()
for event in events:
if event.type == QUIT:
run = 0
pygame.display.flip()
clock.tick(60)
To understand the class methods I used two: shell_print and aaellipse.The shell_print is used just to print a input text to python shell.
The aaellipse take all inputs for the default pygame.gfxdraw.ellipse.
The result is a simple blue ellipse at 300 and 200 points and sized with 100 and 60.
Another aspect to note is use of the surface into show.aaellipse : show.screen.
This means that the drawing screen is used and not another defined surface.
Of course we can change Screen class to help us - decorators, other defining surfaces, initializations...
Posted by
Cătălin George Feștilă
Labels:
2017,
gfxdraw,
pygame,
python,
python module,
tutorial,
tutorials
vineri, 26 mai 2017
PyGame : First interface - part 7.
Today I will start with another feature: add text from the keyboard.
The interface needs to be filled with text and a good way is to read the keyboard.
My example using this feature and print the text into one row and let you erase chars when you typing.
First, you need to know I used python version 2.7.13 and the last pygame version 1.9.2.0a from here.
I used also the PyCharm version Community Edition 2017.1.3.
Let see the source code for this example:
The interface needs to be filled with text and a good way is to read the keyboard.
My example using this feature and print the text into one row and let you erase chars when you typing.
First, you need to know I used python version 2.7.13 and the last pygame version 1.9.2.0a from here.
I used also the PyCharm version Community Edition 2017.1.3.
Let see the source code for this example:
import pygame
from pygame.locals import *
def name():
pygame.init()
screen = pygame.display.set_mode((480, 360))
name = ""
font = pygame.font.Font(None, 50)
while True:
for evt in pygame.event.get():
if evt.type == KEYDOWN:
if evt.unicode.isalpha():
name += evt.unicode
elif evt.key == K_BACKSPACE:
name = name[:-1]
elif evt.key == K_SPACE:
name = name+str(" ")
elif evt.type == QUIT:
return
screen.fill((0, 0, 0))
block = font.render(name, True, (255, 255, 255))
rect = block.get_rect()
rect.center = screen.get_rect().center
screen.blit(block, rect)
pygame.display.flip()
if __name__ == "__main__":
name()
The result of this python script can see into image below:
Abonați-vă la:
Postări (Atom)