{"id":20299851,"url":"https://github.com/python-ninja-hebi/pygame-cookbook","last_synced_at":"2025-09-08T19:40:03.169Z","repository":{"id":178031428,"uuid":"383430252","full_name":"Python-Ninja-Hebi/pygame-cookbook","owner":"Python-Ninja-Hebi","description":"Pygame Cookbook- Writing Games with Python","archived":false,"fork":false,"pushed_at":"2023-07-02T10:28:46.000Z","size":2054,"stargazers_count":5,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-09-08T19:40:02.584Z","etag":null,"topics":["cookbook","games","pygame","python"],"latest_commit_sha":null,"homepage":"","language":"Jupyter Notebook","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/Python-Ninja-Hebi.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2021-07-06T10:32:18.000Z","updated_at":"2024-10-10T08:27:41.000Z","dependencies_parsed_at":null,"dependency_job_id":"5d00aeb0-812b-45aa-8e9c-fc8056f0d3ae","html_url":"https://github.com/Python-Ninja-Hebi/pygame-cookbook","commit_stats":null,"previous_names":["python-ninja-hebi/pygame-cookbook"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/Python-Ninja-Hebi/pygame-cookbook","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Ninja-Hebi%2Fpygame-cookbook","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Ninja-Hebi%2Fpygame-cookbook/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Ninja-Hebi%2Fpygame-cookbook/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Ninja-Hebi%2Fpygame-cookbook/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/Python-Ninja-Hebi","download_url":"https://codeload.github.com/Python-Ninja-Hebi/pygame-cookbook/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/Python-Ninja-Hebi%2Fpygame-cookbook/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":274231435,"owners_count":25245585,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-09-08T02:00:09.813Z","response_time":121,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["cookbook","games","pygame","python"],"created_at":"2024-11-14T16:16:32.297Z","updated_at":"2025-09-08T19:40:03.149Z","avatar_url":"https://github.com/Python-Ninja-Hebi.png","language":"Jupyter Notebook","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Pygame Cookbook - Recipes for Mastering Pygame\n\nHi,\n\nin the last years I used **Python** and the module **Pygame** to create some games. I found many information about **Pygame** on many different places in the web. I would prefer one book where I can look for solutions. So I started to write this `Pygame Cookbook`.  \n\n**Pygame** (https://www.pygame.org) is a create library for making your own games with python. **Pygame** uses the **SDL** library.\n\nThis `Pygame Cookbook` tries to explain the building blocks of a game simple and in detail.\n\nThe official documentation of **Pygame** is available at https://www.pygame.org/docs/.\n\nIf you like `Pygame Cookbook`, use it. If you have some suggestions, tell me (hebi@python-ninja.com).\n\nAll game assets that I use in recipes are from https://www.kenney.nl. Thank you.\n\nHave fun.\n\nHebi, on the way to Python Ninja\n\n`Edition 0.32, July 2023`\n\n## install pygame\n\nPrerequisite for using the `Pygame Cookbook` is that the Python library **Pygame** is installed on your computer.\n$ pip install pygame\nMore about installing pygame https://www.pygame.org/wiki/GettingStarted#Pygame%20Installation\n\nYou can use **Pygame** with different programming environments. A very convenient way to try the recipes of this Cookbook is to copy the **Jupyter Notebook** version (file *pygame-cookbook.ipynb*) to your computer and evaluate the cells your interested in.\n\n## pygame and jupyter notebooks\n\n#### Task: Using pygame with Jupyter Notebooks\n\n**Solution:**\n\nOpen a window that shows the drawing of pygame.  \n\nYou can \n\n\n```python\n%gui qt\nimport pygame\n \npygame.init() #start the pygame module\n\nscreen = pygame.display.set_mode((400, 300)) #get access to the display\n\npygame.display.update() #update the display\n```\n\n    pygame 2.0.1 (SDL 2.0.14, Python 3.8.8)\n    Hello from the pygame community. https://www.pygame.org/contribute.html\n\n\nNow you can use another jupyter cell to draw a rectangle.\n\n\n```python\npygame.draw.rect(screen, (0, 128, 255), pygame.Rect(30, 30, 60, 60)) #draw a rectangle\n\npygame.display.update() #update display\n```\n\nAt least close the pygame window.\n\n\n```python\npygame.quit() #stop the pygame module\n```\n\n\u003cimg src=\"img/jupyter_pygame.png\" width=\"280\" align=\"left\"\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\n**Explanation:**\n\nWith the magic command`%gui qt` **Jupyter** can work together with **Pygame**. This enables the use of the Jupyter GUI and the entries in the Pygame window at the same time. Therefore every recipe in this `Pygame Cookbook` has the magic command`%gui qt` in the first line.\n\nYou don't need that, if you want to try a recipe in a different Python environment.\n\n**More:**\n\nhttps://ipython.readthedocs.io/en/stable/config/eventloops.html\n\n## simple gameloop\n\n#### Task: simple program structure that works with every game\n\n**Solution:**\n\nOpens a window that shows the drawing of pygame.\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nBLACK = 0, 0, 0\nBLUE = 0, 0, 255\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    \n    # ---- draw ----\n    screen.fill(BLACK)\n    pygame.draw.rect(screen, BLUE, pygame.Rect(30, 30, 60, 60)) #draw a rectangle\n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n\u003cimg src=\"img/simple_gameloop.png\" width=\"280\" align=\"left\"\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\n**Explanation:**\n\nEvery game consists of the same building blocks:\n    \n* **Input**: Read input from player. Which keys are pressed? Did the  mouse move? Any other input device lika a joystick?\n* **Update**: Do the changes in the game world\n* **Draw**: Show the changes on the screen  \n    \n* and start all over again\n\nThis is called **game loop** or **event loop**.\n\n`import pygame` .. import the Pygame module  \n`init() -\u003e (numpass, numfail)` .. initialize all imported Pygame modules. Some Pygame modules needs to be initialized. Return value *numfail* shows how many modules could not be initialized by Pygame.\n\n`pygame.display.set_mode()` .. return a *Surface* object on which python can draw. The first parameters define the size. The created display will be the best supported by the system. \n\nThere are many additional flags:\n\n`pygame.FULLSCREEN` .. fullscreen no window  \n`pygame.HWSURFACE` .. hardware accelerated (only fullscreen). \n`pygame.OPENGL` .. create an OpenGL-renderable display  \n`pygame.RESIZABLE` .. resizable window  \n`pygame.NOFRAME` .. window without border or controls  \n\n`pygame.event.get(eventtype=None) -\u003e Eventlist` .. get next event from Pygame.   \n`if event.type == pygame.QUIT: ` .. user clicked on the close control of the window.\n\n`screen.fill(BLACK)` .. fill the complete display with color   \n`pygame.draw.rect` .. draw a rectangle on the display\n\n`pygame.display.flip()` .. show changed display on the screen\n\n`pygame.quit() -\u003e None` .. uninitialize all imported Pygame modules\n\nThis **loop** will be used in the most recipes.\n\n**more**  \n* Pygame documentaion https://www.pygame.org/docs/\n\n## gameloop with timing\n\n#### Task: integrating time into the game loop\n\n**Solution:**\n\nusing class **pygame.time.clock** to get a good timing\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nBLACK = 0, 0, 0\nBLUE = 0, 0, 255\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nclock = pygame.time.Clock() #create clock object\n\nFRAMES_PER_SECOND = 30      #who many pictures per second should pygame generate?\n\nx_position = 60             #position of the blue rectangel\nPIXELS_PER_SECOND = 40      #how many pixels per second should the rectangele be moved?\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    delta_time = clock.tick(FRAMES_PER_SECOND)     # time since last frame\n    \n    x_position = x_position + delta_time/1000 * PIXELS_PER_SECOND #next position of the rectanel\n \n    if x_position \u003e WIDTH: #rectangele vanishes right start from left again\n        x_position = 0\n    \n    # ---- draw ----\n    screen.fill(BLACK)\n    pygame.draw.rect(screen, BLUE, pygame.Rect(int(x_position), 30, 60, 60)) #draw a rectangle\n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n**Explanation:**\n\n**Pygame** comes with an integrated class for timing: **pygame.time.Clock**\n\n**-Initialize-**\n\nFirst you have to create your own **clock** object.  \n\n`clock = pygame.time.Clock()`\n\n`FRAMES_PER_SECOND = 30` .. you have to define how many frames (pictures) should be maximal drawn by **Pygame** in a second\n\n`x_position = 60` .. the blue rectangle will move from left to right. In every frame the script will use the time since the last frame to calculate the new position.  \n\n`PIXELS_PER_SECOND = 40` .. the speed (velocity) of the rectangle will be 40 pixels in one second.\n\n**-Game loop update()-**\n\n`delta_time = clock.tick(FRAMES_PER_SECOND)` .. returns the milliseconds since the last frame.   \nThe parameter *FRAMES_PER_SECOND* defines the maximal number of frames per second. It limits the runtime. **Pygame** will not draw more frames per second.\n\n`x_position = x_position + delta_time/1000 * PIXELS_PER_SECOND` .. to get the distance covered since the last frame you have to multiply the elapsed time by the velocity. *delta_time* is in milliseconds but you need the time in seconds. So you have to divide with thousand.\n \n`if x_position \u003e WIDTH: x_position = 0`.. before the rectangel is vanishing from the screen you have to start from the left side again\n\n## basics\n\n#### coordinates\n\n\n```python\n\n```\n\n#### colors \u003ca id='colors'\u003e\u003c/a\u003e\n\n\n```python\n\n```\n\n#### Rect \u003ca id='Rect'\u003e\u003c/a\u003e\n\n\n```python\n\n```\n\n\u003cimg src=\"img/rect.png\" width=\"320\" align=\"left\"\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\n## draw\n\n### rectangle\n\n#### Task: drawing a rectangle\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nwhile running:\n    \n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n            \n    screen.fill(pygame.Color('black'))\n    pygame.draw.rect(screen, pygame.Color('blue'), pygame.Rect(30, 30, 60, 60))\n    pygame.display.flip()\n\npygame.quit()\n```\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 120\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    \n    # ---- draw ----\n    screen.fill(BLACK)\n    \n    pygame.draw.rect(screen, pygame.Color('blue'), pygame.Rect(30, 30, 60, 60)) #fill area\n    \n    pygame.draw.rect(screen, pygame.Color('blue'), pygame.Rect(120, 30, 60, 60), width=1) #border\n    \n    pygame.draw.rect(screen, pygame.Color('blue'), pygame.Rect(210, 30, 60, 60), width=2, border_radius=8) #rounded border\n    \n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n\u003cimg src=\"img/draw_rectangle.png\" width=\"560\" align=\"left\"\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\n**Explanation:**\n\nA rectangle can consist of a fill area and a border.\n\n**Drawing the fill area with function rect**\n\n`rect(surface, color, rect) -\u003e Rec` .. draws a rectangle to the output surface and returns an object of the class **Rect**  \n\n`surface`.. Surface to draw on\n\n`color` .. different ways to describe a [color](#colors) in **Pygame**\n\n`rec` .. rectangle that describes position, width and height\n\nWith\n\n`Rect(left, top, width, height) -\u003e Rect` .. you can create a new [Rect](#Rect) from position (left, top) and dimension (width, height)\n\n**Drawing the border with function rect**\n\n`rect(surface, color, rect, width=0, border_radius=0) -\u003e Rect` .. draws the border of a rectangle to the output surface and returns an object of the class **Rect**\n\n`width`.. thickness of the border in Pixel. (if is 0, **Pygame** draws a filled rectangle)\n\n`border_radius`.. draws border with rounded corners (if is 0, no rounded corners)\n\n\n**more**  \n* Pygame documentation http://www.pygame.org/docs/ref/draw.html\n\n### polygon, circle, ellipse, arc \n\n\n```python\n\n```\n\n### line\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## image\n\n## text\n\n#### Task: draw text\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\nrunning = True\n\nWHITE = (255,255,255)\nBLUE = (0,0,255)\n\npygame.init()\nscreen = pygame.display.set_mode((640, 340))\n\nsysfont = pygame.font.get_default_font()\nprint(sysfont)\n\nfont = pygame.font.SysFont(None, 24)\n\npygame.display.flip()\n\nwhile running:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    screen.fill(WHITE)\n    \n    img = font.render(\"text\", True, BLUE)\n    rect = img.get_rect()\n    rect.midtop = (40,40)\n    screen.blit(img, rect)\n    \n    pygame.display.flip()\n            \npygame.quit()\n```\n\n    pygame 2.1.2 (SDL 2.0.18, Python 3.9.16)\n    Hello from the pygame community. https://www.pygame.org/contribute.html\n    freesansbold.ttf\n\n\n**Explanation:**\n\n`get_default_font() -\u003e str` .. returns the name of the default font\n\n\n`SysFont(name, size) -\u003e Font` .. create a Font object from the system fonts\n\n`name`.. name of the font, can be None\n\n`size`.. font size\n\n\n`Font(filename, size) -\u003e Font`.. create Font from file\n\n`filename`.. file name of the font\n\n`size`.. font size\n\n\n`render(text, antialias, color, background=None) -\u003e Surface` .. creates a new surface with text\n\n`text`.. as string  \n`antialias`.. if True than with antialias\n\n\nThe text can only be a single line. The Surface will be of the dimensions required to hold the text.\n\n\n```python\n\n```\n\n## transparent\n\n#### Task: draw a transparent surface\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 640, 340\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nWHITE = (255,255,255)\nBLUE = (0,0,255)\nGREY_1 = (160, 160, 160)\nGREY_2 = (192, 192, 192)\n\nTILE_SIZE = 24\nbackground = pygame.Surface(SIZE) # background image\n\nfor x in range(0,WIDTH//TILE_SIZE+1):\n    for y in range(0,HEIGHT//TILE_SIZE+1):\n        color = GREY_1\n        if (x+y) % 2 == 0:\n            color = GREY_2\n        pygame.draw.rect(background, color, (x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE))\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    \n    # ---- draw ----\n    screen.blit(background, (0, 0))\n    \n    surface = pygame.Surface((200,200))  # new surface\n    surface.set_alpha(128)               # set alpha\n    surface.fill(BLUE)             \n    \n    screen.blit(surface, (0,0))\n    \n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n\n    ---------------------------------------------------------------------------\n\n    KeyboardInterrupt                         Traceback (most recent call last)\n\n    Cell In[5], line 48\n         44     surface.fill(BLUE)             \n         46     screen.blit(surface, (0,0))\n    ---\u003e 48     pygame.display.flip()\n         50 # ---- Quit ----\n         52 pygame.quit()\n\n\n    KeyboardInterrupt: \n\n\nIf you want a **transparent** image (surface) you have to that the so called **alpha value** of the\nsurface. Use the set_alpha method for this.  \n\nIf the alpha value is 0 it's totaly transparent. You see nothing.\nIf the value is 255 it's not transpartent.\n\n`set_alpha(value) -\u003e None` .. set alpha value of surface\n\n\u003cimg src=\"img/transparent_surface.png\" width=\"560\" align=\"left\"\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\n#### Task: make every pixel of an image transparent\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 140\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nWHITE = (255,255,255)\nBLUE = (0,0,255)\nGREY_1 = (160, 160, 160)\nGREY_2 = (192, 192, 192)\n\nTILE_SIZE = 24\nbackground = pygame.Surface(SIZE) # background image\n\nfor x in range(0,WIDTH//TILE_SIZE+1):\n    for y in range(0,HEIGHT//TILE_SIZE+1):\n        color = GREY_1\n        if (x+y) % 2 == 0:\n            color = GREY_2\n        pygame.draw.rect(background, color, (x*TILE_SIZE, y*TILE_SIZE, TILE_SIZE, TILE_SIZE))\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    \n    # ---- draw ----\n    screen.blit(background, (0, 0))\n    \n    RADIUS = 50\n    \n    surface = pygame.Surface((100,100),pygame.SRCALPHA)  # new surface per pixel alpha\n    pygame.draw.circle(surface, (0,0,255,128), (RADIUS, RADIUS), RADIUS) # with alpha\n    screen.blit(surface,(0,0))\n    \n    surface = pygame.Surface((100,100),pygame.SRCALPHA)  # new surface per pixel alpha\n    pygame.draw.circle(surface, (0,0,255,64), (RADIUS, RADIUS), RADIUS) # with alpha\n    screen.blit(surface,(75,0))\n    \n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n`surface = pygame.Surface((100,100),pygame.SRCALPHA)`\n\nIf you want to set an alpha value (transparence) separatly for every pixel to have\nto use **pygame.SRCALPHA** when creating a surface. Now pygame knows that you wants\nto use alpha values.\n\n`pygame.draw.circle(surface, (0,0,255,128), (RADIUS, RADIUS), RADIUS)`\n\nIn the color value you can now add the alpha value (128), too.\n\n\u003cimg src=\"img/transparent_pixel.png\" width=\"560\" align=\"left\"\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\u003cbr\u003e\n\n**more** \n* Draw a transparent rectangle in pygame https://stackoverflow.com/questions/6339057/draw-a-transparent-rectangle-in-pygame\n\n## mouse\n\n#### Task: drag with the mouse\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nBLACK = 0, 0, 0\nBLUE = 0, 0, 255\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nrectangle = pygame.rect.Rect(176, 134, 80, 80)\ndraging = False\n\npygame.mouse.set_visible(True)\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n            \n        elif event.type == pygame.MOUSEBUTTONDOWN:           \n            if rectangle.collidepoint(event.pos):\n                draging = True\n                mouse_x, mouse_y = event.pos\n                offset_x = rectangle.x - mouse_x\n                offset_y = rectangle.y - mouse_y\n\n        elif event.type == pygame.MOUSEBUTTONUP:          \n            draging = False\n\n        elif event.type == pygame.MOUSEMOTION:\n            if draging:\n                mouse_x, mouse_y = event.pos\n                rectangle.x = mouse_x + offset_x\n                rectangle.y = mouse_y + offset_y\n    \n    # ---- update ---- \n    \n    # ---- draw ----\n    screen.fill(BLACK)\n    pygame.draw.rect(screen, BLUE, rectangle) #draw a rectangle\n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n\n```python\n\n```\n\n\n```python\n\n```\n\n## keyboard\n\n#### Task: get every pressed key\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\nrunning = True\n\nWHITE = (255,255,255)\nBLUE = (0,0,255)\nGREEN = (0,255,0)\n\nscreen = pygame.display.set_mode((640, 340))\n\nrectangle = pygame.rect.Rect(200, 150, 40, 40)\nrect_color = BLUE\n\nwhile running:\n\n    right_color = GREEN\n    left_color = GREEN\n    up_color = GREEN\n    down_color = GREEN\n    \n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n            \n    keys=pygame.key.get_pressed()\n    \n    if keys[pygame.K_RIGHT]:\n        right_color = BLUE\n        \n    if keys[pygame.K_LEFT]:\n        left_color = BLUE\n        \n    if keys[pygame.K_UP]:\n        up_color = BLUE\n        \n    if keys[pygame.K_DOWN]:\n        down_color = BLUE\n    \n    screen.fill(WHITE)\n    \n    pygame.draw.rect(screen, right_color, (200, 100, 100, 100))\n    pygame.draw.rect(screen, left_color, (0, 100, 100, 100))\n    pygame.draw.rect(screen, up_color, (100, 0, 100, 100))\n    pygame.draw.rect(screen, down_color, (100, 200, 100, 100))\n    \n    pygame.display.flip()\n\npygame.quit()\n```\n\n    pygame 2.1.2 (SDL 2.0.18, Python 3.9.16)\n    Hello from the pygame community. https://www.pygame.org/contribute.html\n\n\n`get_pressed() -\u003e bools` .. get a boolean value for every key on the keybaord. Is *True* if key is pressed.\n\n## events\n\n## collision\n\n### point - rectangle\n\n#### Task: detecting a point in a rectangle\n\n**Solution:**\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nWHITE =  255, 255 ,255\nBLUE = 0, 0, 255\nGREEN = 0, 255, 0\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nrectangle = pygame.rect.Rect(50, 50, 100, 100)\nrect_color = BLUE\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n        elif event.type == pygame.MOUSEMOTION:           \n            if rectangle.collidepoint(event.pos):\n                rect_color = GREEN\n            else:         \n                rect_color = BLUE\n    \n    # ---- update ---- \n\n    # ---- draw ----\n    screen.fill(WHITE)\n    pygame.draw.rect(screen, rect_color, rectangle)\n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n\n```\n\n**Explanation:**\n\n`rect.collidepoint((x,y)) -\u003e bool` returns True if point is within rect  \n\n**more**  \n* pygame documentation rect https://www.pygame.org/docs/ref/rect.html\n\n### rectangle - rectangle\n\n\n```python\n\n```\n\n`rect.colliderect(Rect) -\u003e bool` returns True if rectangles overlap  \n`rect.collidelist(list) -\u003e index` returns index of the *first* rectangle that overlaps; -1 if nothing is found\n`rect.collidelistall(list) -\u003e indices` returns indexes of all rectangles that overlap\n\n\n### rectangle - line\n\n#### Task: detecting a line in a rectangle\n\n\n```python\n%gui qt\nimport pygame\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nWHITE = 255, 255, 255\nBLACK = 0, 0, 0\nBLUE = 0, 0, 255\nGRAY = 127, 127, 127\nGREEN = 0, 255, 0\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE)\n\nclock = pygame.time.Clock() #create clock object\n\nFRAMES_PER_SECOND = 30      #who many pictures per second should pygame generate?\n\nx_position = 60             #position of the blue rectangel\nPIXELS_PER_SECOND = 40      #how many pixels per second should the rectangele be moved?\n\nstart_pos = (120,0)\nend_pos = (120,200)\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    delta_time = clock.tick(FRAMES_PER_SECOND)     # time since last frame\n    \n    x_position = x_position + delta_time/1000 * PIXELS_PER_SECOND #next position of the rectanel\n \n    if x_position \u003e WIDTH: #rectangele vanishes right start from left again\n        x_position = 0\n    \n    # ---- draw ----\n    screen.fill(BLACK)\n    rect = pygame.Rect(int(x_position), 30, 60, 60)\n    \n    clip = rect.clipline(start_pos,end_pos)\n    \n    if len(clip) \u003e 0:\n        pygame.draw.rect(screen, GRAY, rect)\n        pygame.draw.line(screen, WHITE, start_pos, end_pos, width=1)\n        pygame.draw.line(screen, GREEN, clip[0], clip[1])\n    else:\n        pygame.draw.rect(screen, BLUE, rect)\n        pygame.draw.line(screen, WHITE, start_pos, end_pos, width=1)\n    \n    \n    pygame.display.flip()\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n    pygame 2.1.1 (SDL 2.0.18, Python 3.9.7)\n    Hello from the pygame community. https://www.pygame.org/contribute.html\n\n\n`clipline(x1, y1, x2, y2) -\u003e ((cx1, cy1), (cx2, cy2))` ..\nreturns the coordinates of a line that in rectangle; an empty tuble when line complete out rectangle\n\n### pixel - pixel\n\n\n```python\n%gui qt\nimport pygame\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 320, 240\nBLACK = 0, 0, 0\n\nrunning = True\nclock = pygame.time.Clock()\nfps = 30\nscreen = pygame.display.set_mode(SIZE)\n\nball = pygame.image.load(\"Freddy.png\")\nballrect = ball.get_rect()\nballrect.center = (200,100)\nballmask = pygame.mask.from_surface(ball)\n\n\nball2 = pygame.image.load(\"Freddy.png\")\nballrect2 = ball2.get_rect()\nballmask2 = pygame.mask.from_surface(ball2)\n\nposition = pygame.Vector2(100, 100)\nvelocity = pygame.Vector2(10,0)\n\nwhile running:\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n\n    delta_time = clock.tick(fps) / 1000.0\n    position = position + velocity * delta_time\n    ballrect2.center = position\n    \n    offset_x = ballrect2.left - ballrect.left\n    offset_y = ballrect2.top - ballrect.top\n    \n    if ballmask.overlap(ballmask2, (offset_x, offset_y)) != None:\n        print('collision')\n        \n    screen.fill(BLACK)\n    screen.blit(ball, ballrect)\n    screen.blit(ball2, ballrect2)\n    pygame.display.flip()\n\npygame.quit()\n```\n\n\n```python\npygame.quit()\n```\n\n`from_surface(Surface) -\u003e Mask`.. Creates a *Mask* object from the *Surface* by setting all the opaque pixels and not setting the transparent pixels  \n`overlap(othermask, offset) -\u003e (x, y)`.. Returns the first point of intersection encountered between this mask and *othermask*. *None* if there is no overlaping. *offset* is the distance between the two masks.\n\n### sprite - sprite\n\n\n```python\n\n```\n\n**more**  \n* Collision Detection in PyGame LMU 2017 https://www.medien.ifi.lmu.de/lehre/ss17/mmp/uebung/uebung7/mmp_uebung_7_ss17.pdf\n* pygame documentation rect https://www.pygame.org/docs/ref/rect.html\n* pygame documentation sprite https://www.pygame.org/docs/ref/sprite.html\n* pygame documentation mask https://www.pygame.org/docs/ref/mask.html\n\n\n```python\n\n```\n\n## opengl\n\n### start\n\n#### Task: using OpenGl with pygame\n\n**Solution:**\n\ninstall Python packages **numpy**,**PyOpenGL** and **PyOpenGL_accelerate**\n\n`\npip install numpy PyOpenGL PyOpenGL_accelerate\n`\n\n\n```python\n%gui qt\nimport pygame\n\nfrom OpenGL.GL import *\nfrom OpenGL.GLU import *\n\nverticies = ((1, -1, -1),(1, 1, -1),(-1, 1, -1),(-1, -1, -1),\n             (1, -1, 1),(1, 1, 1),(-1, -1, 1),(-1, 1, 1))\n\nedges = ((0,1),(0,3),(0,4),(2,1),\n         (2,3),(2,7),(6,3),(6,4),\n         (6,7),(5,1),(5,4),(5,7))\n\n# ---- Initialize ----\n\npygame.init()\n\nSIZE = WIDTH, HEIGHT = 640, 480\nBLACK = 0, 0, 0\nBLUE = 0, 0, 255\n\n#pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLEBUFFERS,1) #antialiasing\n#pygame.display.gl_set_attribute(pygame.GL_MULTISAMPLESAMPLES,4)\n\n#pygame.display.gl_set_attribute(pygame.GL_CONTEXT_PROFILE_MASK, #compatibility\n#                                pygame.GL_CONTEXT_PROFILE_CORE)\n\nrunning = True\nscreen = pygame.display.set_mode(SIZE,pygame.DOUBLEBUF | pygame.OPENGL)\n\ngluPerspective(45, (WIDTH/HEIGHT), 0.1, 50)\nglTranslatef(0.0,0.0,-5)\n\n# ---- Game loop ----\n\nwhile running:\n    \n    # ---- input ----\n    for event in pygame.event.get():\n        if event.type == pygame.QUIT: \n            running = False\n    \n    # ---- update ---- \n    \n    # ---- draw ----\n    glRotatef(1, 3, 1, 1)\n    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT)\n    \n    glBegin(GL_LINES)\n    for edge in edges:\n        for vertex in edge:\n            glVertex3fv(verticies[vertex])\n    glEnd()\n    \n    pygame.display.flip()\n    pygame.time.wait(10)\n\n# ---- Quit ----\n\npygame.quit()\n```\n\n\n```python\n\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpython-ninja-hebi%2Fpygame-cookbook","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fpython-ninja-hebi%2Fpygame-cookbook","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fpython-ninja-hebi%2Fpygame-cookbook/lists"}