Explore all Pygame open source software, libraries, packages, source code, cloud functions and APIs.

Popular New Releases in Pygame

pygame

2.1.3.dev4 - the peace and solidarity pre-release

thonny

Version 4.0.0b2

art

Version 5.6

mu

1.1.1 stable

pibooth

v2.0.5

Popular Libraries in Pygame

pygame

by pygame doticoncdoticon

star image 4680 doticon

pygame (the library) is a Free and Open Source python programming language library for making multimedia applications like games built on top of the excellent SDL library. C, Python, Native, OpenGL.

Games

by CharlesPikachu doticonpythondoticon

star image 3117 doticonMIT

Create interesting games by pure python.

free-python-games

by grantjenks doticonpythondoticon

star image 2009 doticonNOASSERTION

Free Python Games

Mario-Level-1

by justinmeister doticonpythondoticon

star image 1864 doticon

The first level of Super Mario Bros made with Python and Pygame.

thonny

by thonny doticonpythondoticon

star image 1626 doticonMIT

Python IDE for beginners

picamera

by waveform80 doticonpythondoticon

star image 1382 doticonBSD-3-Clause

A pure Python interface to the Raspberry Pi camera module

art

by sepandhaghighi doticonpythondoticon

star image 1375 doticonMIT

🎨 ASCII art library for Python

clumsy-bird

by ellisonleao doticonjavascriptdoticon

star image 1316 doticonGPL-3.0

:bird: :video_game: A MelonJS port of the famous Flappy Bird Game

pcc_2e

by ehmatthes doticonhtmldoticon

star image 1221 doticon

Online resources for Python Crash Course (Second Edition), from No Starch Press

Trending New libraries in Pygame

com.unity.multiplayer.docs

by Unity-Technologies doticonjavascriptdoticon

star image 316 doticonNOASSERTION

Open Source documentation for Unity Multiplayer, which includes Netcode for GameObjects, the Unity Transport Package and Educational references and Sample Games such as Boss Room.

SuperSimple2DKit

by atmosgames doticoncsharpdoticon

star image 312 doticon

A simple kit meant to help jump start the creation of your 2D Unity game!

TKinterDesigner

by honghaier-game doticonpythondoticon

star image 294 doticon

TKinterDesigner is a tool software to develop the Python User Interface for Python programmer.

dotnet-console-games

by ZacharyPatten doticoncsharpdoticon

star image 248 doticonMIT

Game examples implemented in .NET console applications primarily for educational purposes.

pandemic-ventilator-2.0

by Mascobot doticonpythondoticon

star image 242 doticon

Open Source Pandemic Ventilator with Raspberry Pi and Arduino

Sorting-Algorithms-Visualizer

by LucasPilla doticonpythondoticon

star image 210 doticonMIT

Program made with Python and Pygame module for visualizing sorting algorithms

rxjs-fruits

by GregorBiswanger doticontypescriptdoticon

star image 183 doticonMIT

A game for learning RxJS 🍎🍌

sudoku-solver

by robovirmani doticonpythondoticon

star image 129 doticon

GUI Sudoku Solver using Pygame

Abstract-Art-Generator

by Burakcoli doticonpythondoticon

star image 112 doticonGPL-3.0

A python program that generates abstract art with variety of shapes, styles and randomization using pygame.

Top Authors in Pygame

1

techwithtim

11 Libraries

star icon795

2

StanislavPetrovV

10 Libraries

star icon111

3

MysteryCoder456

7 Libraries

star icon26

4

kivy-garden

7 Libraries

star icon57

5

tech35

7 Libraries

star icon21

6

IDMNYU

6 Libraries

star icon56

7

asweigart

6 Libraries

star icon139

8

EricsonWillians

6 Libraries

star icon38

9

Pabitra145

5 Libraries

star icon11

10

kwoolter

5 Libraries

star icon16

1

11 Libraries

star icon795

2

10 Libraries

star icon111

3

7 Libraries

star icon26

4

7 Libraries

star icon57

5

7 Libraries

star icon21

6

6 Libraries

star icon56

7

6 Libraries

star icon139

8

6 Libraries

star icon38

9

5 Libraries

star icon11

10

5 Libraries

star icon16

Trending Kits in Pygame

No Trending Kits are available at this moment for Pygame

Trending Discussions on Pygame

Why can't pip find winrt?

How to make a character jump in Pygame?

How to register an exact X/Y boundary crossing when object is moving more than 1 pixel per update?

Problem with slowing down ball in pong game

What does ''event.pos[0]'' mean in the pygame library? I saw an example using it to get the X axis of the cursor and ignore the Y axis

Pip cannot install anything after upgrading to Python 3.10.0 on windows

How to draw rectangle and circles in Pygame environment

Pip command line "ImportError: No Module Named Typing"

How to use KEYDOWN?

Python Pygame Font x coordinate

QUESTION

Why can't pip find winrt?

Asked 2022-Feb-12 at 19:19

I just bought a new laptop and I'm trying to set it up with python. I am using python 3.10.0, windows 10, pip v21.3. For the most part, pip seems to be working correctly, I've already used it to install multiple packages such as pygame. When I try to install winrt, however, I get this error

1C:\Users\matth>pip install winrt
2ERROR: Could not find a version that satisfies the requirement winrt (from versions: none)
3ERROR: No matching distribution found for winrt
4

My old laptop is still able to uninstall and reinstall winrt using pip without a problem, and again pip works on my new laptop for other packages, just not winrt. Any idea what the problem is and how I fix it?

ANSWER

Answered 2021-Oct-18 at 02:51

Your new laptop may have an old CPU and winrt may not have been compiled for that CPU. Check the model of your CPU.

Source https://stackoverflow.com/questions/69610231

QUESTION

How to make a character jump in Pygame?

Asked 2022-Jan-05 at 10:47

I want to make my character jump. In my current attempt, the player moves up as long as I hold down SPACEv and falls down when I release SPACE.

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32

However, I want the character to jump if I hit the SPACE once. I want a smooth jump animation to start when SPACE is pressed once. How would I go about this step by step?

ANSWER

Answered 2022-Jan-05 at 10:47

To make a character jump you have to use the KEYDOWN event, but not pygame.key.get_pressed(). pygame.key.get_pressed () is for continuous movement when a key is held down. The keyboard events are used to trigger a single action or to start an animation such as a jump. See alos How to get keyboard input in pygame?

pygame.key.get_pressed() returns a sequence with the state of each key. If a key is held down, the state for the key is True, otherwise False. Use pygame.key.get_pressed() to evaluate the current state of a button and get continuous movement.

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36

Use pygame.time.Clock ("This method should be called once per frame.") you control the frames per second and thus the game speed and the duration of the jump.

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39

The jumping should be independent of the player's movement or the general flow of control of the game. Therefore, the jump animation in the application loop must be executed in parallel to the running game.

When you throw a ball or something jumps, the object makes a parabolic curve. The object gains height quickly at the beginning, but this slows down until the object begins to fall faster and faster again. The change in height of a jumping object can be described with the following sequence:

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40

Such a series can be generated with the following algorithm (y is the y coordinate of the object):

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40jumpMax = 10
41if jump:
42    y -= jumpCount
43    if jumpCount > -jumpMax:
44        jumpCount -= 1
45    else:
46        jump = False 
47

A more sophisticated approach is to define constants for the gravity and player's acceleration as the player jumps:

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40jumpMax = 10
41if jump:
42    y -= jumpCount
43    if jumpCount > -jumpMax:
44        jumpCount -= 1
45    else:
46        jump = False 
47acceleration = 10
48gravity = 0.5
49

The acceleration exerted on the player in each frame is the gravity constant, if the player jumps then the acceleration changes to the "jump" acceleration for a single frame:

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40jumpMax = 10
41if jump:
42    y -= jumpCount
43    if jumpCount > -jumpMax:
44        jumpCount -= 1
45    else:
46        jump = False 
47acceleration = 10
48gravity = 0.5
49acc_y = gravity
50for event in pygame.event.get():
51    if event.type == pygame.KEYDOWN: 
52        if vel_y == 0 and event.key == pygame.K_SPACE:
53            acc_y = -acceleration
54

In each frame the vertical velocity is changed depending on the acceleration and the y-coordinate is changed depending on the velocity. When the player touches the ground, the vertical movement will stop:

1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40jumpMax = 10
41if jump:
42    y -= jumpCount
43    if jumpCount > -jumpMax:
44        jumpCount -= 1
45    else:
46        jump = False 
47acceleration = 10
48gravity = 0.5
49acc_y = gravity
50for event in pygame.event.get():
51    if event.type == pygame.KEYDOWN: 
52        if vel_y == 0 and event.key == pygame.K_SPACE:
53            acc_y = -acceleration
54vel_y += acc_y
55y += vel_y
56if y > ground_y:
57    y = ground_y
58    vel_y = 0
59    acc_y = 0
60
1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40jumpMax = 10
41if jump:
42    y -= jumpCount
43    if jumpCount > -jumpMax:
44        jumpCount -= 1
45    else:
46        jump = False 
47acceleration = 10
48gravity = 0.5
49acc_y = gravity
50for event in pygame.event.get():
51    if event.type == pygame.KEYDOWN: 
52        if vel_y == 0 and event.key == pygame.K_SPACE:
53            acc_y = -acceleration
54vel_y += acc_y
55y += vel_y
56if y > ground_y:
57    y = ground_y
58    vel_y = 0
59    acc_y = 0
60import pygame
61
62pygame.init()
63window = pygame.display.set_mode((300, 300))
64clock = pygame.time.Clock()
65
66rect = pygame.Rect(135, 220, 30, 30) 
67vel = 5
68jump = False
69jumpCount = 0
70jumpMax = 15
71
72run = True
73while run:
74    clock.tick(50)
75    for event in pygame.event.get():
76        if event.type == pygame.QUIT:
77            run = False
78        if event.type == pygame.KEYDOWN: 
79            if not jump and event.key == pygame.K_SPACE:
80                jump = True
81                jumpCount = jumpMax
82
83    keys = pygame.key.get_pressed()    
84    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
85    
86    if jump:
87        rect.y -= jumpCount
88        if jumpCount > -jumpMax:
89            jumpCount -= 1
90        else:
91            jump = False 
92
93    window.fill((0, 0, 64))
94    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
95    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
96    pygame.display.flip()
97
98pygame.quit()
99exit() 
100
1import pygame
2
3pygame.init()
4window = pygame.display.set_mode((300, 300))
5clock = pygame.time.Clock()
6
7rect = pygame.Rect(135, 220, 30, 30) 
8vel = 5
9
10run = True
11while run:
12    clock.tick(100)
13    for event in pygame.event.get():
14        if event.type == pygame.QUIT:
15            run = False
16
17    keys = pygame.key.get_pressed()    
18    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
19    
20    if keys[pygame.K_SPACE]:
21        rect.y -= 1
22    elif rect.y < 220:
23        rect.y += 1
24
25    window.fill((0, 0, 64))
26    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
27    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
28    pygame.display.flip()
29
30pygame.quit()
31exit() 
32while True:
33    for event in pygame.event.get():
34        if event.type == pygame.KEYDOWN and event.key == pygame.K_SPACE:
35            jump = True
36clock = pygame.time.Clock()
37while True:
38   clock.tick(100)
39[10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, -1, -2, -3, -4, -5, -6, -7, -8, -9, -10]
40jumpMax = 10
41if jump:
42    y -= jumpCount
43    if jumpCount > -jumpMax:
44        jumpCount -= 1
45    else:
46        jump = False 
47acceleration = 10
48gravity = 0.5
49acc_y = gravity
50for event in pygame.event.get():
51    if event.type == pygame.KEYDOWN: 
52        if vel_y == 0 and event.key == pygame.K_SPACE:
53            acc_y = -acceleration
54vel_y += acc_y
55y += vel_y
56if y > ground_y:
57    y = ground_y
58    vel_y = 0
59    acc_y = 0
60import pygame
61
62pygame.init()
63window = pygame.display.set_mode((300, 300))
64clock = pygame.time.Clock()
65
66rect = pygame.Rect(135, 220, 30, 30) 
67vel = 5
68jump = False
69jumpCount = 0
70jumpMax = 15
71
72run = True
73while run:
74    clock.tick(50)
75    for event in pygame.event.get():
76        if event.type == pygame.QUIT:
77            run = False
78        if event.type == pygame.KEYDOWN: 
79            if not jump and event.key == pygame.K_SPACE:
80                jump = True
81                jumpCount = jumpMax
82
83    keys = pygame.key.get_pressed()    
84    rect.centerx = (rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
85    
86    if jump:
87        rect.y -= jumpCount
88        if jumpCount > -jumpMax:
89            jumpCount -= 1
90        else:
91            jump = False 
92
93    window.fill((0, 0, 64))
94    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
95    pygame.draw.circle(window, (255, 0, 0), rect.center, 15)
96    pygame.display.flip()
97
98pygame.quit()
99exit() 
100import pygame
101
102pygame.init()
103window = pygame.display.set_mode((300, 300))
104clock = pygame.time.Clock()
105
106player = pygame.sprite.Sprite()
107player.image = pygame.Surface((30, 30), pygame.SRCALPHA)
108pygame.draw.circle(player.image, (255, 0, 0), (15, 15), 15)
109player.rect = player.image.get_rect(center = (150, 235))
110all_sprites = pygame.sprite.Group([player])
111
112y, vel_y = player.rect.bottom, 0
113vel = 5
114ground_y = 250
115acceleration = 10
116gravity = 0.5
117
118run = True
119while run:
120    clock.tick(100)
121    acc_y = gravity
122    for event in pygame.event.get():
123        if event.type == pygame.QUIT:
124            run = False
125        if event.type == pygame.KEYDOWN: 
126            if vel_y == 0 and event.key == pygame.K_SPACE:
127                acc_y = -acceleration
128
129    keys = pygame.key.get_pressed()    
130    player.rect.centerx = (player.rect.centerx + (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel) % 300
131    
132    vel_y += acc_y
133    y += vel_y
134    if y > ground_y:
135        y = ground_y
136        vel_y = 0
137        acc_y = 0
138    player.rect.bottom = round(y)
139
140    window.fill((0, 0, 64))
141    pygame.draw.rect(window, (64, 64, 64), (0, 250, 300, 100))
142    all_sprites.draw(window)
143    pygame.display.flip()
144
145pygame.quit()
146exit() 
147

Source https://stackoverflow.com/questions/70591591

QUESTION

How to register an exact X/Y boundary crossing when object is moving more than 1 pixel per update?

Asked 2021-Dec-26 at 20:16

I'm trying to learn Python/Pygame and I made a simple Pong game. However I cannot get the square to bounce off the sides at the perfect pixel as the drawing of the square is updating let's say 3 pixels every frame.

I have a code to decide when the square is hitting the edges and bounce in a reverse direction like this:

1if y_ball < 100:
2        y_ball_change = y_ball_change * -1     
3if y_ball > 675:
4        y_ball_change = y_ball_change * -1
5if x_ball > 775:
6        x_ball_change = x_ball_change * -1
7
8if x_ball <= x_rect + 25 and y_ball >= y_rect -25 and not y_ball > y_rect + 150:
9        x_ball_change = x_ball_change * -1 +2
10

It's keeping the square inside the boundaries of the screen however it's not pixel perfect since

1if y_ball < 100:
2        y_ball_change = y_ball_change * -1     
3if y_ball > 675:
4        y_ball_change = y_ball_change * -1
5if x_ball > 775:
6        x_ball_change = x_ball_change * -1
7
8if x_ball <= x_rect + 25 and y_ball >= y_rect -25 and not y_ball > y_rect + 150:
9        x_ball_change = x_ball_change * -1 +2
10x_ball_change
11y_ball_change
12

is often more/less than 1 since they are randomized between -5 and 5 (except 0) to make starting direction of the ball random every new game.

Thanks for any help!

ANSWER

Answered 2021-Dec-26 at 20:16

You also need to correct the position of the ball when changing the direction of the ball. The ball bounces on the boundaries and moves the excessive distance in the opposite direction like a billiard ball:

e.g.:

1if y_ball < 100:
2        y_ball_change = y_ball_change * -1     
3if y_ball > 675:
4        y_ball_change = y_ball_change * -1
5if x_ball > 775:
6        x_ball_change = x_ball_change * -1
7
8if x_ball <= x_rect + 25 and y_ball >= y_rect -25 and not y_ball > y_rect + 150:
9        x_ball_change = x_ball_change * -1 +2
10x_ball_change
11y_ball_change
12if y_ball < 100:
13    y_ball = 100 + (100 - y_ball)
14    y_ball_change = y_ball_change * -1     
15
16if y_ball > 675:
17    y_ball = 675 - (y_ball - 675)
18    y_ball_change = y_ball_change * -1
19
20if x_ball > 775:
21    x_ball = 775 - (x_ball - 775)
22    x_ball_change = x_ball_change * -1
23
24if x_ball <= x_rect + 25 and y_rect -25 <= y_ball <= y_rect + 150:
25    x_ball = x_rect + 25 + (x_rect + 25 - x_ball)    
26    x_ball_change = x_ball_change * -1 +2
27

Source https://stackoverflow.com/questions/70489368

QUESTION

Problem with slowing down ball in pong game

Asked 2021-Dec-25 at 09:13

I've been making pong with pygame and I got the ball to bounce around the screen and on the paddles. However, the speed is too high and I want to decrease it. This is what the code looks like for the Ball object:

1import pygame as pg
2BLACK = (0, 0, 0)
3
4
5class Ball(pg.sprite.Sprite):
6    def __init__(self, color, width, height, radius):
7        super().__init__()
8
9        self.x_vel = 1
10        self.y_vel = 1
11        self.image = pg.Surface([width * 2, height * 2])
12        self.image.fill(BLACK)
13        self.image.set_colorkey(BLACK)
14
15        pg.draw.circle(self.image, color, center=[width, height], radius=radius)
16
17        self.rect = self.image.get_rect()
18
19    def update_ball(self):
20        self.rect.x += self.x_vel
21        self.rect.y += self.y_vel
22

If I try to set the velocity as a float, it stops the ball completely. Can someone help me?

ANSWER

Answered 2021-Dec-25 at 08:52

Use pygame.time.Clock to control the frames per second and thus the game speed.

The method tick() of a pygame.time.Clock object, delays the game in that way, that every iteration of the loop consumes the same period of time. See pygame.time.Clock.tick():

This method should be called once per frame.

That means that the loop:

1import pygame as pg
2BLACK = (0, 0, 0)
3
4
5class Ball(pg.sprite.Sprite):
6    def __init__(self, color, width, height, radius):
7        super().__init__()
8
9        self.x_vel = 1
10        self.y_vel = 1
11        self.image = pg.Surface([width * 2, height * 2])
12        self.image.fill(BLACK)
13        self.image.set_colorkey(BLACK)
14
15        pg.draw.circle(self.image, color, center=[width, height], radius=radius)
16
17        self.rect = self.image.get_rect()
18
19    def update_ball(self):
20        self.rect.x += self.x_vel
21        self.rect.y += self.y_vel
22clock = pygame.time.Clock()
23run = True
24while run:
25   clock.tick(100)
26

runs 100 times per second.


Since pygame.Rect is supposed to represent an area on the screen, a pygame.Rect object can only store integral data.

The coordinates for Rect objects are all integers. [...]

The fraction part of the coordinates gets lost when the movement of the object is assigned to the Rect object.

If you want to store object positions with floating point accuracy, you have to store the location of the object in separate variables respectively attributes and to synchronize the pygame.Rect object. round the coordinates and assign it to the location of the rectangle:

1import pygame as pg
2BLACK = (0, 0, 0)
3
4
5class Ball(pg.sprite.Sprite):
6    def __init__(self, color, width, height, radius):
7        super().__init__()
8
9        self.x_vel = 1
10        self.y_vel = 1
11        self.image = pg.Surface([width * 2, height * 2])
12        self.image.fill(BLACK)
13        self.image.set_colorkey(BLACK)
14
15        pg.draw.circle(self.image, color, center=[width, height], radius=radius)
16
17        self.rect = self.image.get_rect()
18
19    def update_ball(self):
20        self.rect.x += self.x_vel
21        self.rect.y += self.y_vel
22clock = pygame.time.Clock()
23run = True
24while run:
25   clock.tick(100)
26class Ball(pg.sprite.Sprite):
27    def __init__(self, color, width, height, radius):
28        # [...]
29
30        self.rect = self.image.get_rect()
31        self.x = self.rect.x
32        self.y = self.rect.y
33
34    def update_ball(self):
35        self.x += self.x_vel
36        self.y += self.y_vel
37        self.rect.x = round(self.x)
38        self.rect.y = round(self.y)
39

Source https://stackoverflow.com/questions/70477302

QUESTION

What does ''event.pos[0]'' mean in the pygame library? I saw an example using it to get the X axis of the cursor and ignore the Y axis

Asked 2021-Dec-17 at 21:49

I don't understand how it works. I don't know if I understood the purpose of this function wrong. I tried to search what posx=event.pos[0] means but all I found was that if you want to take x, write the code of posx,posy=pygame.mouse.get_pos() and then take posx. But I still can't understand the method he followed in the example I saw.

ANSWER

Answered 2021-Dec-17 at 21:49

See pygame.event module. The MOUSEMOTION, MOUSEBUTTONUP and MOUSEBUTTONDOWN events provide a position property pos with the position of the mouse cursor. pos is a tuple with 2 components, the x and y coordinate.

e.g.:

1for event in pygame.event.get():
2    if event.type == pygame.MOUSEBUTTONDOWN:
3        print("mouse cursor x", event.pos[0])
4        print("mouse cursor y", event.pos[1])
5

pygame.mouse.get_pos() returns a Tuple and event.pos is a Tuple. Both give you the position of the mouse pointer as a tuple with 2 components:

1for event in pygame.event.get():
2    if event.type == pygame.MOUSEBUTTONDOWN:
3        print("mouse cursor x", event.pos[0])
4        print("mouse cursor y", event.pos[1])
5ex, ey = event.pos
6mx, my = pygame.mouse.get_pos()
7

pygame.mouse.getpos() returns the current position of the mouse. The pos attribute stores the position of the mouse when the event occurred. Note that you can call pygame.event.get() much later than the event occurred. If you want to know the position of the mouse at the time of the event, you can call it up using the pos attribute.

Source https://stackoverflow.com/questions/70393064

QUESTION

Pip cannot install anything after upgrading to Python 3.10.0 on windows

Asked 2021-Oct-09 at 05:31

I recently upgraded to the latest version of python version 3.10.0 and upgraded pip also to the latest version 21.2.4.

Now I cannot use pip to install anything. This is the error it gives for anything I try to install.

1C:\Users\AMAL>pip install numpy
2Collecting numpy
3  Using cached numpy-1.21.2.zip (10.3 MB)
4  Installing build dependencies ... done
5  Getting requirements to build wheel ... done
6    Preparing wheel metadata ... done
7Building wheels for collected packages: numpy
8  Building wheel for numpy (PEP 517) ... error
9  ERROR: Command errored out with exit status 1:
10   command: 'C:\Users\AMAL\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' build_wheel 'C:\Users\AMAL\AppData\Local\Temp\tmpemhtoti3'
11       cwd: C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7
12  Complete output (208 lines):
13  setup.py:63: RuntimeWarning: NumPy 1.21.2 may not yet support Python 3.10.
14    warnings.warn(
15  Running from numpy source directory.
16  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\tools\cythonize.py:69: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
17    from distutils.version import LooseVersion
18  Processing numpy/random\_bounded_integers.pxd.in
19  Processing numpy/random\bit_generator.pyx
20  Processing numpy/random\mtrand.pyx
21  Processing numpy/random\_bounded_integers.pyx.in
22  Processing numpy/random\_common.pyx
23  Processing numpy/random\_generator.pyx
24  Processing numpy/random\_mt19937.pyx
25  Processing numpy/random\_pcg64.pyx
26  Processing numpy/random\_philox.pyx
27  Processing numpy/random\_sfc64.pyx
28  Cythonizing sources
29  blas_opt_info:
30  blas_mkl_info:
31  No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
32  customize MSVCCompiler
33    libraries mkl_rt not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
34    NOT AVAILABLE
35
36  blis_info:
37    libraries blis not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
38    NOT AVAILABLE
39
40  openblas_info:
41    libraries openblas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
42  get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
43  customize GnuFCompiler
44  Could not locate executable g77
45  Could not locate executable f77
46  customize IntelVisualFCompiler
47  Could not locate executable ifort
48  Could not locate executable ifl
49  customize AbsoftFCompiler
50  Could not locate executable f90
51  customize CompaqVisualFCompiler
52  Could not locate executable DF
53  customize IntelItaniumVisualFCompiler
54  Could not locate executable efl
55  customize Gnu95FCompiler
56  Could not locate executable gfortran
57  Could not locate executable f95
58  customize G95FCompiler
59  Could not locate executable g95
60  customize IntelEM64VisualFCompiler
61  customize IntelEM64TFCompiler
62  Could not locate executable efort
63  Could not locate executable efc
64  customize PGroupFlangCompiler
65  Could not locate executable flang
66  don't know how to compile Fortran code on platform 'nt'
67    NOT AVAILABLE
68
69  accelerate_info:
70    NOT AVAILABLE
71
72  atlas_3_10_blas_threads_info:
73  Setting PTATLAS=ATLAS
74    libraries tatlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
75    NOT AVAILABLE
76
77  atlas_3_10_blas_info:
78    libraries satlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
79    NOT AVAILABLE
80
81  atlas_blas_threads_info:
82  Setting PTATLAS=ATLAS
83    libraries ptf77blas,ptcblas,atlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
84    NOT AVAILABLE
85
86  atlas_blas_info:
87    libraries f77blas,cblas,atlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
88    NOT AVAILABLE
89
90  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
91      Optimized (vendor) Blas libraries are not found.
92      Falls back to netlib Blas library which has worse performance.
93      A better performance should be easily gained by switching
94      Blas library.
95    if self._calc_info(blas):
96  blas_info:
97    libraries blas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
98    NOT AVAILABLE
99
100  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
101      Blas (http://www.netlib.org/blas/) libraries not found.
102      Directories to search for the libraries can be specified in the
103      numpy/distutils/site.cfg file (section [blas]) or by setting
104      the BLAS environment variable.
105    if self._calc_info(blas):
106  blas_src_info:
107    NOT AVAILABLE
108
109  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
110      Blas (http://www.netlib.org/blas/) sources not found.
111      Directories to search for the sources can be specified in the
112      numpy/distutils/site.cfg file (section [blas_src]) or by setting
113      the BLAS_SRC environment variable.
114    if self._calc_info(blas):
115    NOT AVAILABLE
116
117  non-existing path in 'numpy\\distutils': 'site.cfg'
118  lapack_opt_info:
119  lapack_mkl_info:
120    libraries mkl_rt not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
121    NOT AVAILABLE
122
123  openblas_lapack_info:
124    libraries openblas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
125    NOT AVAILABLE
126
127  openblas_clapack_info:
128    libraries openblas,lapack not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
129    NOT AVAILABLE
130
131  flame_info:
132    libraries flame not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
133    NOT AVAILABLE
134
135  atlas_3_10_threads_info:
136  Setting PTATLAS=ATLAS
137    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
138    libraries tatlas,tatlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
139    libraries lapack_atlas not found in C:\
140    libraries tatlas,tatlas not found in C:\
141    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
142    libraries tatlas,tatlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
143  <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
144    NOT AVAILABLE
145
146  atlas_3_10_info:
147    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
148    libraries satlas,satlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
149    libraries lapack_atlas not found in C:\
150    libraries satlas,satlas not found in C:\
151    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
152    libraries satlas,satlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
153  <class 'numpy.distutils.system_info.atlas_3_10_info'>
154    NOT AVAILABLE
155
156  atlas_threads_info:
157  Setting PTATLAS=ATLAS
158    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
159    libraries ptf77blas,ptcblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
160    libraries lapack_atlas not found in C:\
161    libraries ptf77blas,ptcblas,atlas not found in C:\
162    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
163    libraries ptf77blas,ptcblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
164  <class 'numpy.distutils.system_info.atlas_threads_info'>
165    NOT AVAILABLE
166
167  atlas_info:
168    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
169    libraries f77blas,cblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
170    libraries lapack_atlas not found in C:\
171    libraries f77blas,cblas,atlas not found in C:\
172    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
173    libraries f77blas,cblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
174  <class 'numpy.distutils.system_info.atlas_info'>
175    NOT AVAILABLE
176
177  lapack_info:
178    libraries lapack not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
179    NOT AVAILABLE
180
181  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:1858: UserWarning:
182      Lapack (http://www.netlib.org/lapack/) libraries not found.
183      Directories to search for the libraries can be specified in the
184      numpy/distutils/site.cfg file (section [lapack]) or by setting
185      the LAPACK environment variable.
186    return getattr(self, '_calc_info_{}'.format(name))()
187  lapack_src_info:
188    NOT AVAILABLE
189
190  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:1858: UserWarning:
191      Lapack (http://www.netlib.org/lapack/) sources not found.
192      Directories to search for the sources can be specified in the
193      numpy/distutils/site.cfg file (section [lapack_src]) or by setting
194      the LAPACK_SRC environment variable.
195    return getattr(self, '_calc_info_{}'.format(name))()
196    NOT AVAILABLE
197
198  numpy_linalg_lapack_lite:
199    FOUND:
200      language = c
201      define_macros = [('HAVE_BLAS_ILP64', None), ('BLAS_SYMBOL_SUFFIX', '64_')]
202
203  Warning: attempted relative import with no known parent package
204  C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros'
205    warnings.warn(msg)
206  running bdist_wheel
207  running build
208  running config_cc
209  unifing config_cc, config, build_clib, build_ext, build commands --compiler options
210  running config_fc
211  unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
212  running build_src
213  build_src
214  building py_modules sources
215  creating build
216  creating build\src.win-amd64-3.10
217  creating build\src.win-amd64-3.10\numpy
218  creating build\src.win-amd64-3.10\numpy\distutils
219  building library "npymath" sources
220  error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
221  ----------------------------------------
222  ERROR: Failed building wheel for numpy
223Failed to build numpy
224ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly
225

I tried downgrading both python and pip back but the issue still persists. Also tried to create a virtualenv and in that also the same issue persists.

When I downgraded the following is the error

1C:\Users\AMAL>pip install numpy
2Collecting numpy
3  Using cached numpy-1.21.2.zip (10.3 MB)
4  Installing build dependencies ... done
5  Getting requirements to build wheel ... done
6    Preparing wheel metadata ... done
7Building wheels for collected packages: numpy
8  Building wheel for numpy (PEP 517) ... error
9  ERROR: Command errored out with exit status 1:
10   command: 'C:\Users\AMAL\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' build_wheel 'C:\Users\AMAL\AppData\Local\Temp\tmpemhtoti3'
11       cwd: C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7
12  Complete output (208 lines):
13  setup.py:63: RuntimeWarning: NumPy 1.21.2 may not yet support Python 3.10.
14    warnings.warn(
15  Running from numpy source directory.
16  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\tools\cythonize.py:69: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
17    from distutils.version import LooseVersion
18  Processing numpy/random\_bounded_integers.pxd.in
19  Processing numpy/random\bit_generator.pyx
20  Processing numpy/random\mtrand.pyx
21  Processing numpy/random\_bounded_integers.pyx.in
22  Processing numpy/random\_common.pyx
23  Processing numpy/random\_generator.pyx
24  Processing numpy/random\_mt19937.pyx
25  Processing numpy/random\_pcg64.pyx
26  Processing numpy/random\_philox.pyx
27  Processing numpy/random\_sfc64.pyx
28  Cythonizing sources
29  blas_opt_info:
30  blas_mkl_info:
31  No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
32  customize MSVCCompiler
33    libraries mkl_rt not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
34    NOT AVAILABLE
35
36  blis_info:
37    libraries blis not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
38    NOT AVAILABLE
39
40  openblas_info:
41    libraries openblas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
42  get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
43  customize GnuFCompiler
44  Could not locate executable g77
45  Could not locate executable f77
46  customize IntelVisualFCompiler
47  Could not locate executable ifort
48  Could not locate executable ifl
49  customize AbsoftFCompiler
50  Could not locate executable f90
51  customize CompaqVisualFCompiler
52  Could not locate executable DF
53  customize IntelItaniumVisualFCompiler
54  Could not locate executable efl
55  customize Gnu95FCompiler
56  Could not locate executable gfortran
57  Could not locate executable f95
58  customize G95FCompiler
59  Could not locate executable g95
60  customize IntelEM64VisualFCompiler
61  customize IntelEM64TFCompiler
62  Could not locate executable efort
63  Could not locate executable efc
64  customize PGroupFlangCompiler
65  Could not locate executable flang
66  don't know how to compile Fortran code on platform 'nt'
67    NOT AVAILABLE
68
69  accelerate_info:
70    NOT AVAILABLE
71
72  atlas_3_10_blas_threads_info:
73  Setting PTATLAS=ATLAS
74    libraries tatlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
75    NOT AVAILABLE
76
77  atlas_3_10_blas_info:
78    libraries satlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
79    NOT AVAILABLE
80
81  atlas_blas_threads_info:
82  Setting PTATLAS=ATLAS
83    libraries ptf77blas,ptcblas,atlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
84    NOT AVAILABLE
85
86  atlas_blas_info:
87    libraries f77blas,cblas,atlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
88    NOT AVAILABLE
89
90  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
91      Optimized (vendor) Blas libraries are not found.
92      Falls back to netlib Blas library which has worse performance.
93      A better performance should be easily gained by switching
94      Blas library.
95    if self._calc_info(blas):
96  blas_info:
97    libraries blas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
98    NOT AVAILABLE
99
100  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
101      Blas (http://www.netlib.org/blas/) libraries not found.
102      Directories to search for the libraries can be specified in the
103      numpy/distutils/site.cfg file (section [blas]) or by setting
104      the BLAS environment variable.
105    if self._calc_info(blas):
106  blas_src_info:
107    NOT AVAILABLE
108
109  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
110      Blas (http://www.netlib.org/blas/) sources not found.
111      Directories to search for the sources can be specified in the
112      numpy/distutils/site.cfg file (section [blas_src]) or by setting
113      the BLAS_SRC environment variable.
114    if self._calc_info(blas):
115    NOT AVAILABLE
116
117  non-existing path in 'numpy\\distutils': 'site.cfg'
118  lapack_opt_info:
119  lapack_mkl_info:
120    libraries mkl_rt not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
121    NOT AVAILABLE
122
123  openblas_lapack_info:
124    libraries openblas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
125    NOT AVAILABLE
126
127  openblas_clapack_info:
128    libraries openblas,lapack not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
129    NOT AVAILABLE
130
131  flame_info:
132    libraries flame not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
133    NOT AVAILABLE
134
135  atlas_3_10_threads_info:
136  Setting PTATLAS=ATLAS
137    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
138    libraries tatlas,tatlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
139    libraries lapack_atlas not found in C:\
140    libraries tatlas,tatlas not found in C:\
141    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
142    libraries tatlas,tatlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
143  <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
144    NOT AVAILABLE
145
146  atlas_3_10_info:
147    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
148    libraries satlas,satlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
149    libraries lapack_atlas not found in C:\
150    libraries satlas,satlas not found in C:\
151    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
152    libraries satlas,satlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
153  <class 'numpy.distutils.system_info.atlas_3_10_info'>
154    NOT AVAILABLE
155
156  atlas_threads_info:
157  Setting PTATLAS=ATLAS
158    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
159    libraries ptf77blas,ptcblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
160    libraries lapack_atlas not found in C:\
161    libraries ptf77blas,ptcblas,atlas not found in C:\
162    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
163    libraries ptf77blas,ptcblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
164  <class 'numpy.distutils.system_info.atlas_threads_info'>
165    NOT AVAILABLE
166
167  atlas_info:
168    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
169    libraries f77blas,cblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
170    libraries lapack_atlas not found in C:\
171    libraries f77blas,cblas,atlas not found in C:\
172    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
173    libraries f77blas,cblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
174  <class 'numpy.distutils.system_info.atlas_info'>
175    NOT AVAILABLE
176
177  lapack_info:
178    libraries lapack not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
179    NOT AVAILABLE
180
181  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:1858: UserWarning:
182      Lapack (http://www.netlib.org/lapack/) libraries not found.
183      Directories to search for the libraries can be specified in the
184      numpy/distutils/site.cfg file (section [lapack]) or by setting
185      the LAPACK environment variable.
186    return getattr(self, '_calc_info_{}'.format(name))()
187  lapack_src_info:
188    NOT AVAILABLE
189
190  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:1858: UserWarning:
191      Lapack (http://www.netlib.org/lapack/) sources not found.
192      Directories to search for the sources can be specified in the
193      numpy/distutils/site.cfg file (section [lapack_src]) or by setting
194      the LAPACK_SRC environment variable.
195    return getattr(self, '_calc_info_{}'.format(name))()
196    NOT AVAILABLE
197
198  numpy_linalg_lapack_lite:
199    FOUND:
200      language = c
201      define_macros = [('HAVE_BLAS_ILP64', None), ('BLAS_SYMBOL_SUFFIX', '64_')]
202
203  Warning: attempted relative import with no known parent package
204  C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros'
205    warnings.warn(msg)
206  running bdist_wheel
207  running build
208  running config_cc
209  unifing config_cc, config, build_clib, build_ext, build commands --compiler options
210  running config_fc
211  unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
212  running build_src
213  build_src
214  building py_modules sources
215  creating build
216  creating build\src.win-amd64-3.10
217  creating build\src.win-amd64-3.10\numpy
218  creating build\src.win-amd64-3.10\numpy\distutils
219  building library "npymath" sources
220  error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
221  ----------------------------------------
222  ERROR: Failed building wheel for numpy
223Failed to build numpy
224ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly
225C:\Users\AMAL>python -m pip install torch
226Collecting torch
227  Downloading https://files.pythonhosted.org/packages/8e/57/3066077aa16a852f3da0239796fa487baba0104ca2eb26f9ca4f56a7a86d/torch-1.7.0-cp38-cp38m-win_amd64.whl (184.0MB)
228     |████████████████████████████████| 184.0MB 67kB/s
229ERROR: Exception:
230Traceback (most recent call last):
231  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
232    status = self.run(options, args)
233  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\commands\install.py", line 345, in run
234    resolver.resolve(requirement_set)
235  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 196, in resolve
236    self._resolve_one(requirement_set, req)
237  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 362, in _resolve_one
238    dist = abstract_dist.get_pkg_resources_distribution()
239  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\distributions\wheel.py", line 13, in get_pkg_resources_distribution
240    return list(pkg_resources.find_distributions(
241IndexError: list index out of range
242
243C:\Users\AMAL>python --version
244Python 3.8.4rc1
245C:\Users\AMAL>python -m pip install torch
246Collecting torch
247  Downloading https://files.pythonhosted.org/packages/8e/57/3066077aa16a852f3da0239796fa487baba0104ca2eb26f9ca4f56a7a86d/torch-1.7.0-cp38-cp38m-win_amd64.whl (184.0MB)
248     |████████████████████████████████| 184.0MB 67kB/s
249ERROR: Exception:
250Traceback (most recent call last):
251  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
252    status = self.run(options, args)
253  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\commands\install.py", line 345, in run
254    resolver.resolve(requirement_set)
255  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 196, in resolve
256    self._resolve_one(requirement_set, req)
257  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 362, in _resolve_one
258    dist = abstract_dist.get_pkg_resources_distribution()
259  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\distributions\wheel.py", line 13, in get_pkg_resources_distribution
260    return list(pkg_resources.find_distributions(
261IndexError: list index out of range
262
263C:\Users\AMAL>python --version
264Python 3.8.4rc1
265
266

I would greatly appreciate guidance on how to install the latest version of python and pip that supports libraries like pygame and numpy.

ANSWER

Answered 2021-Oct-09 at 05:14

Try to upgrade your pip

1C:\Users\AMAL>pip install numpy
2Collecting numpy
3  Using cached numpy-1.21.2.zip (10.3 MB)
4  Installing build dependencies ... done
5  Getting requirements to build wheel ... done
6    Preparing wheel metadata ... done
7Building wheels for collected packages: numpy
8  Building wheel for numpy (PEP 517) ... error
9  ERROR: Command errored out with exit status 1:
10   command: 'C:\Users\AMAL\AppData\Local\Programs\Python\Python310\python.exe' 'C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib\site-packages\pip\_vendor\pep517\in_process\_in_process.py' build_wheel 'C:\Users\AMAL\AppData\Local\Temp\tmpemhtoti3'
11       cwd: C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7
12  Complete output (208 lines):
13  setup.py:63: RuntimeWarning: NumPy 1.21.2 may not yet support Python 3.10.
14    warnings.warn(
15  Running from numpy source directory.
16  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\tools\cythonize.py:69: DeprecationWarning: The distutils package is deprecated and slated for removal in Python 3.12. Use setuptools or check PEP 632 for potential alternatives
17    from distutils.version import LooseVersion
18  Processing numpy/random\_bounded_integers.pxd.in
19  Processing numpy/random\bit_generator.pyx
20  Processing numpy/random\mtrand.pyx
21  Processing numpy/random\_bounded_integers.pyx.in
22  Processing numpy/random\_common.pyx
23  Processing numpy/random\_generator.pyx
24  Processing numpy/random\_mt19937.pyx
25  Processing numpy/random\_pcg64.pyx
26  Processing numpy/random\_philox.pyx
27  Processing numpy/random\_sfc64.pyx
28  Cythonizing sources
29  blas_opt_info:
30  blas_mkl_info:
31  No module named 'numpy.distutils._msvccompiler' in numpy.distutils; trying from distutils
32  customize MSVCCompiler
33    libraries mkl_rt not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
34    NOT AVAILABLE
35
36  blis_info:
37    libraries blis not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
38    NOT AVAILABLE
39
40  openblas_info:
41    libraries openblas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
42  get_default_fcompiler: matching types: '['gnu', 'intelv', 'absoft', 'compaqv', 'intelev', 'gnu95', 'g95', 'intelvem', 'intelem', 'flang']'
43  customize GnuFCompiler
44  Could not locate executable g77
45  Could not locate executable f77
46  customize IntelVisualFCompiler
47  Could not locate executable ifort
48  Could not locate executable ifl
49  customize AbsoftFCompiler
50  Could not locate executable f90
51  customize CompaqVisualFCompiler
52  Could not locate executable DF
53  customize IntelItaniumVisualFCompiler
54  Could not locate executable efl
55  customize Gnu95FCompiler
56  Could not locate executable gfortran
57  Could not locate executable f95
58  customize G95FCompiler
59  Could not locate executable g95
60  customize IntelEM64VisualFCompiler
61  customize IntelEM64TFCompiler
62  Could not locate executable efort
63  Could not locate executable efc
64  customize PGroupFlangCompiler
65  Could not locate executable flang
66  don't know how to compile Fortran code on platform 'nt'
67    NOT AVAILABLE
68
69  accelerate_info:
70    NOT AVAILABLE
71
72  atlas_3_10_blas_threads_info:
73  Setting PTATLAS=ATLAS
74    libraries tatlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
75    NOT AVAILABLE
76
77  atlas_3_10_blas_info:
78    libraries satlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
79    NOT AVAILABLE
80
81  atlas_blas_threads_info:
82  Setting PTATLAS=ATLAS
83    libraries ptf77blas,ptcblas,atlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
84    NOT AVAILABLE
85
86  atlas_blas_info:
87    libraries f77blas,cblas,atlas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
88    NOT AVAILABLE
89
90  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
91      Optimized (vendor) Blas libraries are not found.
92      Falls back to netlib Blas library which has worse performance.
93      A better performance should be easily gained by switching
94      Blas library.
95    if self._calc_info(blas):
96  blas_info:
97    libraries blas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
98    NOT AVAILABLE
99
100  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
101      Blas (http://www.netlib.org/blas/) libraries not found.
102      Directories to search for the libraries can be specified in the
103      numpy/distutils/site.cfg file (section [blas]) or by setting
104      the BLAS environment variable.
105    if self._calc_info(blas):
106  blas_src_info:
107    NOT AVAILABLE
108
109  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:2026: UserWarning:
110      Blas (http://www.netlib.org/blas/) sources not found.
111      Directories to search for the sources can be specified in the
112      numpy/distutils/site.cfg file (section [blas_src]) or by setting
113      the BLAS_SRC environment variable.
114    if self._calc_info(blas):
115    NOT AVAILABLE
116
117  non-existing path in 'numpy\\distutils': 'site.cfg'
118  lapack_opt_info:
119  lapack_mkl_info:
120    libraries mkl_rt not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
121    NOT AVAILABLE
122
123  openblas_lapack_info:
124    libraries openblas not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
125    NOT AVAILABLE
126
127  openblas_clapack_info:
128    libraries openblas,lapack not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
129    NOT AVAILABLE
130
131  flame_info:
132    libraries flame not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
133    NOT AVAILABLE
134
135  atlas_3_10_threads_info:
136  Setting PTATLAS=ATLAS
137    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
138    libraries tatlas,tatlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
139    libraries lapack_atlas not found in C:\
140    libraries tatlas,tatlas not found in C:\
141    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
142    libraries tatlas,tatlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
143  <class 'numpy.distutils.system_info.atlas_3_10_threads_info'>
144    NOT AVAILABLE
145
146  atlas_3_10_info:
147    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
148    libraries satlas,satlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
149    libraries lapack_atlas not found in C:\
150    libraries satlas,satlas not found in C:\
151    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
152    libraries satlas,satlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
153  <class 'numpy.distutils.system_info.atlas_3_10_info'>
154    NOT AVAILABLE
155
156  atlas_threads_info:
157  Setting PTATLAS=ATLAS
158    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
159    libraries ptf77blas,ptcblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
160    libraries lapack_atlas not found in C:\
161    libraries ptf77blas,ptcblas,atlas not found in C:\
162    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
163    libraries ptf77blas,ptcblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
164  <class 'numpy.distutils.system_info.atlas_threads_info'>
165    NOT AVAILABLE
166
167  atlas_info:
168    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
169    libraries f77blas,cblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib
170    libraries lapack_atlas not found in C:\
171    libraries f77blas,cblas,atlas not found in C:\
172    libraries lapack_atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
173    libraries f77blas,cblas,atlas not found in C:\Users\AMAL\AppData\Local\Programs\Python\Python310\libs
174  <class 'numpy.distutils.system_info.atlas_info'>
175    NOT AVAILABLE
176
177  lapack_info:
178    libraries lapack not found in ['C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\', 'C:\\Users\\AMAL\\AppData\\Local\\Programs\\Python\\Python310\\libs']
179    NOT AVAILABLE
180
181  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:1858: UserWarning:
182      Lapack (http://www.netlib.org/lapack/) libraries not found.
183      Directories to search for the libraries can be specified in the
184      numpy/distutils/site.cfg file (section [lapack]) or by setting
185      the LAPACK environment variable.
186    return getattr(self, '_calc_info_{}'.format(name))()
187  lapack_src_info:
188    NOT AVAILABLE
189
190  C:\Users\AMAL\AppData\Local\Temp\pip-install-d1uxnt6o\numpy_5af9ff0d696c40848bc7d07b456797b7\numpy\distutils\system_info.py:1858: UserWarning:
191      Lapack (http://www.netlib.org/lapack/) sources not found.
192      Directories to search for the sources can be specified in the
193      numpy/distutils/site.cfg file (section [lapack_src]) or by setting
194      the LAPACK_SRC environment variable.
195    return getattr(self, '_calc_info_{}'.format(name))()
196    NOT AVAILABLE
197
198  numpy_linalg_lapack_lite:
199    FOUND:
200      language = c
201      define_macros = [('HAVE_BLAS_ILP64', None), ('BLAS_SYMBOL_SUFFIX', '64_')]
202
203  Warning: attempted relative import with no known parent package
204  C:\Users\AMAL\AppData\Local\Programs\Python\Python310\lib\distutils\dist.py:274: UserWarning: Unknown distribution option: 'define_macros'
205    warnings.warn(msg)
206  running bdist_wheel
207  running build
208  running config_cc
209  unifing config_cc, config, build_clib, build_ext, build commands --compiler options
210  running config_fc
211  unifing config_fc, config, build_clib, build_ext, build commands --fcompiler options
212  running build_src
213  build_src
214  building py_modules sources
215  creating build
216  creating build\src.win-amd64-3.10
217  creating build\src.win-amd64-3.10\numpy
218  creating build\src.win-amd64-3.10\numpy\distutils
219  building library "npymath" sources
220  error: Microsoft Visual C++ 14.0 is required. Get it with "Build Tools for Visual Studio": https://visualstudio.microsoft.com/downloads/
221  ----------------------------------------
222  ERROR: Failed building wheel for numpy
223Failed to build numpy
224ERROR: Could not build wheels for numpy which use PEP 517 and cannot be installed directly
225C:\Users\AMAL>python -m pip install torch
226Collecting torch
227  Downloading https://files.pythonhosted.org/packages/8e/57/3066077aa16a852f3da0239796fa487baba0104ca2eb26f9ca4f56a7a86d/torch-1.7.0-cp38-cp38m-win_amd64.whl (184.0MB)
228     |████████████████████████████████| 184.0MB 67kB/s
229ERROR: Exception:
230Traceback (most recent call last):
231  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
232    status = self.run(options, args)
233  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\commands\install.py", line 345, in run
234    resolver.resolve(requirement_set)
235  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 196, in resolve
236    self._resolve_one(requirement_set, req)
237  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 362, in _resolve_one
238    dist = abstract_dist.get_pkg_resources_distribution()
239  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\distributions\wheel.py", line 13, in get_pkg_resources_distribution
240    return list(pkg_resources.find_distributions(
241IndexError: list index out of range
242
243C:\Users\AMAL>python --version
244Python 3.8.4rc1
245C:\Users\AMAL>python -m pip install torch
246Collecting torch
247  Downloading https://files.pythonhosted.org/packages/8e/57/3066077aa16a852f3da0239796fa487baba0104ca2eb26f9ca4f56a7a86d/torch-1.7.0-cp38-cp38m-win_amd64.whl (184.0MB)
248     |████████████████████████████████| 184.0MB 67kB/s
249ERROR: Exception:
250Traceback (most recent call last):
251  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\cli\base_command.py", line 188, in main
252    status = self.run(options, args)
253  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\commands\install.py", line 345, in run
254    resolver.resolve(requirement_set)
255  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 196, in resolve
256    self._resolve_one(requirement_set, req)
257  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\legacy_resolve.py", line 362, in _resolve_one
258    dist = abstract_dist.get_pkg_resources_distribution()
259  File "C:\Users\AMAL\AppData\Local\Programs\Python\Python38\lib\site-packages\pip\_internal\distributions\wheel.py", line 13, in get_pkg_resources_distribution
260    return list(pkg_resources.find_distributions(
261IndexError: list index out of range
262
263C:\Users\AMAL>python --version
264Python 3.8.4rc1
265
266pip install --upgrade pip
267

Source https://stackoverflow.com/questions/69503887

QUESTION

How to draw rectangle and circles in Pygame environment

Asked 2021-Aug-19 at 20:42

I am trying to create a pygame environment with various shapes of sprites but my code seems not working. Here is what I have:

1class Object(pygame.sprite.Sprite):
2
3    def __init__(self, position, color, size, type):
4
5        # create square sprite
6        pygame.sprite.Sprite.__init__(self)
7        if type == 'agent':
8            self.image = pygame.Surface((size, size))
9            self.image.fill(color)
10            self.rect = self.image.get_rect()
11        else:
12            red = (200,0,0)
13            self.image = pygame.display.set_mode((size, size))
14            self.image.fill(color)
15            self.rect = pygame.draw.circle(self.image, color,(), 20)
16
17
18        # initial conditions
19        self.start_x = position[0]
20        self.start_y = position[1]
21        self.state = np.asarray([self.start_x, self.start_y])
22        self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
23        self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
24

Does anyone notice any issues with the Object class?

ANSWER

Answered 2021-Aug-19 at 20:36

You have to create a pygame.Surface, instead of creating a new window (pygame.display.set_mode).
The pixel format of the Surface must include a per-pixel alpha (SRCALPHA). The center point of the circle must be the center of the Surface. The radius must be half the size of the Surface:

1class Object(pygame.sprite.Sprite):
2
3    def __init__(self, position, color, size, type):
4
5        # create square sprite
6        pygame.sprite.Sprite.__init__(self)
7        if type == 'agent':
8            self.image = pygame.Surface((size, size))
9            self.image.fill(color)
10            self.rect = self.image.get_rect()
11        else:
12            red = (200,0,0)
13            self.image = pygame.display.set_mode((size, size))
14            self.image.fill(color)
15            self.rect = pygame.draw.circle(self.image, color,(), 20)
16
17
18        # initial conditions
19        self.start_x = position[0]
20        self.start_y = position[1]
21        self.state = np.asarray([self.start_x, self.start_y])
22        self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
23        self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
24self.image = pygame.Surface((size, size), pygame.SRCALPHA)
25radius = size // 2
26pygame.draw.circle(self.image, color, (radius, radius), radius)
27

Class Object:

1class Object(pygame.sprite.Sprite):
2
3    def __init__(self, position, color, size, type):
4
5        # create square sprite
6        pygame.sprite.Sprite.__init__(self)
7        if type == 'agent':
8            self.image = pygame.Surface((size, size))
9            self.image.fill(color)
10            self.rect = self.image.get_rect()
11        else:
12            red = (200,0,0)
13            self.image = pygame.display.set_mode((size, size))
14            self.image.fill(color)
15            self.rect = pygame.draw.circle(self.image, color,(), 20)
16
17
18        # initial conditions
19        self.start_x = position[0]
20        self.start_y = position[1]
21        self.state = np.asarray([self.start_x, self.start_y])
22        self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
23        self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
24self.image = pygame.Surface((size, size), pygame.SRCALPHA)
25radius = size // 2
26pygame.draw.circle(self.image, color, (radius, radius), radius)
27class Object(pygame.sprite.Sprite):
28
29    def __init__(self, position, color, size, type):
30
31        # create square sprite
32        pygame.sprite.Sprite.__init__(self)
33
34        self.image = pygame.Surface((size, size), pygame.SRCALPHA)
35        self.rect = self.image.get_rect()
36        
37        if type == 'agent':
38            self.image.fill(color)
39        else:
40            radius = size // 2
41            pygame.draw.circle(self.image, color, (radius, radius), radius)
42
43        # initial conditions
44        self.start_x = position[0]
45        self.start_y = position[1]
46        self.state = np.asarray([self.start_x, self.start_y])
47        self.rect.x = int((self.start_x * 500) + 100 - self.rect.size[0] / 2)
48        self.rect.y = int((self.start_y * 500) + 100 - self.rect.size[1] / 2)
49

Source https://stackoverflow.com/questions/68854226

QUESTION

Pip command line "ImportError: No Module Named Typing"

Asked 2021-Jun-04 at 12:10

Running the Command gives me the following error:

C:\Python34\Scripts> pip install pygame

Error Stack :

1Traceback (most recent call last):
2  File "C:\Python34\lib\runpy.py", line 171, in _run_module_as_main
3    "__main__", mod_spec)
4  File "C:\Python34\lib\runpy.py", line 86, in _run_code
5    exec(code, run_globals)
6  File "C:\Python34\Scripts\pip.exe\__main__.py", line 5, in <module>
7  File "C:\Python34\lib\site-packages\pip\__init__.py", line 1, in <module>
8    from typing import List, Optional
9ImportError: No module named 'typing'
10

ANSWER

Answered 2021-Apr-27 at 06:40

It looks like you are importing from the package 'typing' but you do not have it installed. Try installing the package:

1Traceback (most recent call last):
2  File "C:\Python34\lib\runpy.py", line 171, in _run_module_as_main
3    "__main__", mod_spec)
4  File "C:\Python34\lib\runpy.py", line 86, in _run_code
5    exec(code, run_globals)
6  File "C:\Python34\Scripts\pip.exe\__main__.py", line 5, in <module>
7  File "C:\Python34\lib\site-packages\pip\__init__.py", line 1, in <module>
8    from typing import List, Optional
9ImportError: No module named 'typing'
10pip install typing
11

Source https://stackoverflow.com/questions/67278017

QUESTION

How to use KEYDOWN?

Asked 2021-Jun-04 at 08:29

I am trying to exit the program when the escape key is pressed. I am having some trouble doing that.

When I take out the door() line it works;

1while True:
2    for event in pygame.event.get():
3        if event.type == pygame.KEYDOWN:
4            print("key pressed")
5            if event.key == pygame.K_ESCAPE:
6                print("key pressed")
7                pygame.quit()
8                sys.exit()
9    #door()
10

This is the command prompt readout

1while True:
2    for event in pygame.event.get():
3        if event.type == pygame.KEYDOWN:
4            print("key pressed")
5            if event.key == pygame.K_ESCAPE:
6                print("key pressed")
7                pygame.quit()
8                sys.exit()
9    #door()
10C:\Users\Me\Documents\Fan game>python testing_file.py
11pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
12Hello from the pygame community. https://www.pygame.org/contribute.html
13key pressed
14key pressed
15
16C:\Users\Me\Documents\Fan game>
17

But as soon as I add that line back in, it stops working.

My door function;

1while True:
2    for event in pygame.event.get():
3        if event.type == pygame.KEYDOWN:
4            print("key pressed")
5            if event.key == pygame.K_ESCAPE:
6                print("key pressed")
7                pygame.quit()
8                sys.exit()
9    #door()
10C:\Users\Me\Documents\Fan game>python testing_file.py
11pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
12Hello from the pygame community. https://www.pygame.org/contribute.html
13key pressed
14key pressed
15
16C:\Users\Me\Documents\Fan game>
17def door():
18    
19    global var_door
20    
21    image_door_1 = pygame.image.load(r'textures\door\frame_1.png')
22    image_door_2 = pygame.image.load(r'textures\door\frame_2.png')
23    image_door_3 = pygame.image.load(r'textures\door\frame_3.png')
24    image_door_4 = pygame.image.load(r'textures\door\frame_4.png')
25    image_door_5 = pygame.image.load(r'textures\door\frame_5.png')
26    image_door_6 = pygame.image.load(r'textures\door\frame_6.png')
27    
28    image_door_1_size = image_door_1.get_rect().size
29    image_door_2_size = image_door_2.get_rect().size
30    image_door_3_size = image_door_3.get_rect().size
31    image_door_4_size = image_door_4.get_rect().size
32    image_door_5_size = image_door_5.get_rect().size
33    image_door_6_size = image_door_6.get_rect().size
34    
35    centered_image_door_1 = [(display_size[0] - image_door_1_size[0])/2, (display_size[1] - image_door_1_size[1])/2]
36    centered_image_door_2 = [(display_size[0] - image_door_2_size[0])/2, (display_size[1] - image_door_2_size[1])/2]
37    centered_image_door_3 = [(display_size[0] - image_door_3_size[0])/2, (display_size[1] - image_door_3_size[1])/2]
38    centered_image_door_4 = [(display_size[0] - image_door_4_size[0])/2, (display_size[1] - image_door_4_size[1])/2]
39    centered_image_door_5 = [(display_size[0] - image_door_5_size[0])/2, (display_size[1] - image_door_5_size[1])/2]
40    centered_image_door_6 = [(display_size[0] - image_door_6_size[0])/2, (display_size[1] - image_door_6_size[1])/2]
41    
42    mouse_down = False
43    
44    for event in pygame.event.get():
45        if event.type == QUIT:
46            pygame.quit()
47            sys.exit()
48        elif event.type == MOUSEBUTTONDOWN:
49            mouse_down = True
50    
51    x, y = pygame.mouse.get_pos()
52    if 0 < x < 253 and 0 < y < 226:
53        if mouse_down:
54            if var_door == 0:
55                screen.blit(image_door_1, centered_image_door_1)
56                pygame.display.update()
57                time.sleep(0.01)
58                    
59                screen.blit(image_door_2, centered_image_door_2)
60                pygame.display.update()
61                time.sleep(0.01)
62
63                screen.blit(image_door_3, centered_image_door_3)
64                pygame.display.update()
65                time.sleep(0.01)
66
67                screen.blit(image_door_4, centered_image_door_4)
68                pygame.display.update()
69                time.sleep(0.01)
70
71                screen.blit(image_door_5, centered_image_door_5)
72                pygame.display.update()
73                time.sleep(0.01)
74
75                screen.blit(image_door_6, centered_image_door_6)
76                pygame.display.update()
77                        
78                var_door = 1
79                    
80            else:
81                screen.blit(image_door_6, centered_image_door_6)
82                pygame.display.update()
83                time.sleep(0.01)
84                    
85                screen.blit(image_door_5, centered_image_door_5)
86                pygame.display.update()
87                time.sleep(0.01)
88
89                screen.blit(image_door_4, centered_image_door_4)
90                pygame.display.update()
91                time.sleep(0.01)
92
93                screen.blit(image_door_3, centered_image_door_3)
94                pygame.display.update()
95                time.sleep(0.01)
96
97                screen.blit(image_door_2, centered_image_door_2)
98                pygame.display.update()
99                time.sleep(0.01)
100
101                screen.blit(image_door_1, centered_image_door_1)
102                pygame.display.update()
103                        
104                var_door = 0
105

I do not understand why it does not work. I tried rearranging the order that the while loop checks but even that doesn't work. My guess is for some reason it never checks if the escape key is pressed and its getting stuck on the door function, but the door function doesn't have any loops in it.

ANSWER

Answered 2021-Jun-01 at 03:05

Place the door() function cose to the left side aligning below the while . As python works the door() is under while loop. Inform me if it works or please add detail about why is the door() in while loop and the use of door().

Source https://stackoverflow.com/questions/67782206

QUESTION

Python Pygame Font x coordinate

Asked 2021-May-13 at 08:03

I am trying to make a 2d password generator in pygame and I have to ask the user and take text input from the user about how many length in numbers he wants his password to be. I know that the text input will be short but what if the user types a big string that the text input passes my screen width so my question is how do I detect if the font passes my screen width so from now on whatever the user inputs will get displayed on a new Line because if the text is not in a newline my user wont be able to see what he is entering now.

Here is my text input function:

1def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
2               thing_x=None, thing_y=None):
3    """
4
5    :param x: Defines the x axis or the width position where the text input should be drawn.
6    :param y: Defines the y axis or the height position where the text input should be drawn.
7    :param color: Defines the color of the text input.
8    :param char: If the parameter char in not entered it does not do anything otherwise it display's the the parameter
9                 char's text on the screen
10    :param char_x: If the parameter char is entered char_x Defines the x axis or the width position where the text
11                   should be drawn.
12    :param char_y: If the parameter char is entered char_y Defines the y axis or the height position where the text
13                   should be drawn.
14    :param char_color: Defines the color of the text of the parameter char in rgb color pixels.
15    :param fill: If the parameter fill is entered it fills the display with the tuple of the rgb color pixels which the
16                 user entered. But if the parameter fill is not entered it fills the display with the rgb color code
17                 black.
18    :param thing: If the user wants some thing to been drawn on the display the fill the parameter thing with the object
19                  they want to draw. But if the parameter thing is not entered. The thing parameter should be a pygame
20                  Surface.
21    :param thing_x: If the parameter thing is entered thing_x Defines the x axis or the width position where the
22                    parameter thing should be drawn
23    :param thing_y: If the parameter thing is entered thing_y Defines the y axis or the height position where the
24                    parameter thing should be drawn.
25    :return: It Display's the text input and the other parameters which were entered on the window and the updates it.
26    """
27
28    characters = ""
29    WINDOW.fill(fill)
30    if thing is not None:
31        draw(thing, thing_x, thing_y)
32    if char is not None:
33        char_text = str(char)
34        char_text_surface = FONT.render(char_text, True, char_color)
35        draw(char_text_surface, char_x, char_y, True)
36    pygame.display.update()
37
38    while True:
39        for detect in pygame.event.get():
40            if detect.type == QUIT:
41                exit()
42
43            elif detect.type == KEYDOWN:
44                if detect.key == K_BACKSPACE:
45                    characters = characters[:-1]
46                elif detect.key == K_RETURN:
47                    global text
48                    text = characters
49                    return text
50
51                else:
52                    characters = characters + detect.unicode
53
54                WINDOW.fill(fill)
55                if thing is not None:
56                    draw(thing, thing_x, thing_y)
57                if char is not None:
58                    char_text = str(char)
59                    char_text_surface = FONT.render(char_text, True, char_color)
60                    draw(char_text_surface, char_x, char_y, True)
61
62                text = FONT.render(f"{characters}", True, color)
63                print(char_x)
64                draw(text, x, y, True)
65

If you wonder what the draw function is here is the code for it:

1def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
2               thing_x=None, thing_y=None):
3    """
4
5    :param x: Defines the x axis or the width position where the text input should be drawn.
6    :param y: Defines the y axis or the height position where the text input should be drawn.
7    :param color: Defines the color of the text input.
8    :param char: If the parameter char in not entered it does not do anything otherwise it display's the the parameter
9                 char's text on the screen
10    :param char_x: If the parameter char is entered char_x Defines the x axis or the width position where the text
11                   should be drawn.
12    :param char_y: If the parameter char is entered char_y Defines the y axis or the height position where the text
13                   should be drawn.
14    :param char_color: Defines the color of the text of the parameter char in rgb color pixels.
15    :param fill: If the parameter fill is entered it fills the display with the tuple of the rgb color pixels which the
16                 user entered. But if the parameter fill is not entered it fills the display with the rgb color code
17                 black.
18    :param thing: If the user wants some thing to been drawn on the display the fill the parameter thing with the object
19                  they want to draw. But if the parameter thing is not entered. The thing parameter should be a pygame
20                  Surface.
21    :param thing_x: If the parameter thing is entered thing_x Defines the x axis or the width position where the
22                    parameter thing should be drawn
23    :param thing_y: If the parameter thing is entered thing_y Defines the y axis or the height position where the
24                    parameter thing should be drawn.
25    :return: It Display's the text input and the other parameters which were entered on the window and the updates it.
26    """
27
28    characters = ""
29    WINDOW.fill(fill)
30    if thing is not None:
31        draw(thing, thing_x, thing_y)
32    if char is not None:
33        char_text = str(char)
34        char_text_surface = FONT.render(char_text, True, char_color)
35        draw(char_text_surface, char_x, char_y, True)
36    pygame.display.update()
37
38    while True:
39        for detect in pygame.event.get():
40            if detect.type == QUIT:
41                exit()
42
43            elif detect.type == KEYDOWN:
44                if detect.key == K_BACKSPACE:
45                    characters = characters[:-1]
46                elif detect.key == K_RETURN:
47                    global text
48                    text = characters
49                    return text
50
51                else:
52                    characters = characters + detect.unicode
53
54                WINDOW.fill(fill)
55                if thing is not None:
56                    draw(thing, thing_x, thing_y)
57                if char is not None:
58                    char_text = str(char)
59                    char_text_surface = FONT.render(char_text, True, char_color)
60                    draw(char_text_surface, char_x, char_y, True)
61
62                text = FONT.render(f"{characters}", True, color)
63                print(char_x)
64                draw(text, x, y, True)
65def draw(thing, x, y, update=None):
66    """
67
68    :param thing: The object what needs to be drawn on the screen
69    :param x: Defines the x axis or the width position where the object should be drawn.
70    :param y: Defines the y axis or the height position where the object should be drawn.
71    :param update: If the parameter update is not passed we don't update the display.
72                   But if the parameter update is passed as True we update the display.
73    :return: It returns the object on the display at its specific place or it returns
74            the object on the display at its specific place and updates and updates the display based on the parameter
75            update.
76    """
77
78    if update is True:
79        WINDOW.blit(thing, (x, y))
80        return pygame.display.update()
81
82    else:
83        return WINDOW.blit(thing, (x, y)
84

If you want to know my full code just ask me I will edit this post:

ANSWER

Answered 2021-May-13 at 08:03

Use pygame.font.Font.size to determine the amount of space needed to render text:

1def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
2               thing_x=None, thing_y=None):
3    """
4
5    :param x: Defines the x axis or the width position where the text input should be drawn.
6    :param y: Defines the y axis or the height position where the text input should be drawn.
7    :param color: Defines the color of the text input.
8    :param char: If the parameter char in not entered it does not do anything otherwise it display's the the parameter
9                 char's text on the screen
10    :param char_x: If the parameter char is entered char_x Defines the x axis or the width position where the text
11                   should be drawn.
12    :param char_y: If the parameter char is entered char_y Defines the y axis or the height position where the text
13                   should be drawn.
14    :param char_color: Defines the color of the text of the parameter char in rgb color pixels.
15    :param fill: If the parameter fill is entered it fills the display with the tuple of the rgb color pixels which the
16                 user entered. But if the parameter fill is not entered it fills the display with the rgb color code
17                 black.
18    :param thing: If the user wants some thing to been drawn on the display the fill the parameter thing with the object
19                  they want to draw. But if the parameter thing is not entered. The thing parameter should be a pygame
20                  Surface.
21    :param thing_x: If the parameter thing is entered thing_x Defines the x axis or the width position where the
22                    parameter thing should be drawn
23    :param thing_y: If the parameter thing is entered thing_y Defines the y axis or the height position where the
24                    parameter thing should be drawn.
25    :return: It Display's the text input and the other parameters which were entered on the window and the updates it.
26    """
27
28    characters = ""
29    WINDOW.fill(fill)
30    if thing is not None:
31        draw(thing, thing_x, thing_y)
32    if char is not None:
33        char_text = str(char)
34        char_text_surface = FONT.render(char_text, True, char_color)
35        draw(char_text_surface, char_x, char_y, True)
36    pygame.display.update()
37
38    while True:
39        for detect in pygame.event.get():
40            if detect.type == QUIT:
41                exit()
42
43            elif detect.type == KEYDOWN:
44                if detect.key == K_BACKSPACE:
45                    characters = characters[:-1]
46                elif detect.key == K_RETURN:
47                    global text
48                    text = characters
49                    return text
50
51                else:
52                    characters = characters + detect.unicode
53
54                WINDOW.fill(fill)
55                if thing is not None:
56                    draw(thing, thing_x, thing_y)
57                if char is not None:
58                    char_text = str(char)
59                    char_text_surface = FONT.render(char_text, True, char_color)
60                    draw(char_text_surface, char_x, char_y, True)
61
62                text = FONT.render(f"{characters}", True, color)
63                print(char_x)
64                draw(text, x, y, True)
65def draw(thing, x, y, update=None):
66    """
67
68    :param thing: The object what needs to be drawn on the screen
69    :param x: Defines the x axis or the width position where the object should be drawn.
70    :param y: Defines the y axis or the height position where the object should be drawn.
71    :param update: If the parameter update is not passed we don't update the display.
72                   But if the parameter update is passed as True we update the display.
73    :return: It returns the object on the display at its specific place or it returns
74            the object on the display at its specific place and updates and updates the display based on the parameter
75            update.
76    """
77
78    if update is True:
79        WINDOW.blit(thing, (x, y))
80        return pygame.display.update()
81
82    else:
83        return WINDOW.blit(thing, (x, y)
84text_width, text_height = FONT.size(text)
85

The line space of the font can be get with get_linesize

Use this methods to render the text line by line:

1def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
2               thing_x=None, thing_y=None):
3    """
4
5    :param x: Defines the x axis or the width position where the text input should be drawn.
6    :param y: Defines the y axis or the height position where the text input should be drawn.
7    :param color: Defines the color of the text input.
8    :param char: If the parameter char in not entered it does not do anything otherwise it display's the the parameter
9                 char's text on the screen
10    :param char_x: If the parameter char is entered char_x Defines the x axis or the width position where the text
11                   should be drawn.
12    :param char_y: If the parameter char is entered char_y Defines the y axis or the height position where the text
13                   should be drawn.
14    :param char_color: Defines the color of the text of the parameter char in rgb color pixels.
15    :param fill: If the parameter fill is entered it fills the display with the tuple of the rgb color pixels which the
16                 user entered. But if the parameter fill is not entered it fills the display with the rgb color code
17                 black.
18    :param thing: If the user wants some thing to been drawn on the display the fill the parameter thing with the object
19                  they want to draw. But if the parameter thing is not entered. The thing parameter should be a pygame
20                  Surface.
21    :param thing_x: If the parameter thing is entered thing_x Defines the x axis or the width position where the
22                    parameter thing should be drawn
23    :param thing_y: If the parameter thing is entered thing_y Defines the y axis or the height position where the
24                    parameter thing should be drawn.
25    :return: It Display's the text input and the other parameters which were entered on the window and the updates it.
26    """
27
28    characters = ""
29    WINDOW.fill(fill)
30    if thing is not None:
31        draw(thing, thing_x, thing_y)
32    if char is not None:
33        char_text = str(char)
34        char_text_surface = FONT.render(char_text, True, char_color)
35        draw(char_text_surface, char_x, char_y, True)
36    pygame.display.update()
37
38    while True:
39        for detect in pygame.event.get():
40            if detect.type == QUIT:
41                exit()
42
43            elif detect.type == KEYDOWN:
44                if detect.key == K_BACKSPACE:
45                    characters = characters[:-1]
46                elif detect.key == K_RETURN:
47                    global text
48                    text = characters
49                    return text
50
51                else:
52                    characters = characters + detect.unicode
53
54                WINDOW.fill(fill)
55                if thing is not None:
56                    draw(thing, thing_x, thing_y)
57                if char is not None:
58                    char_text = str(char)
59                    char_text_surface = FONT.render(char_text, True, char_color)
60                    draw(char_text_surface, char_x, char_y, True)
61
62                text = FONT.render(f"{characters}", True, color)
63                print(char_x)
64                draw(text, x, y, True)
65def draw(thing, x, y, update=None):
66    """
67
68    :param thing: The object what needs to be drawn on the screen
69    :param x: Defines the x axis or the width position where the object should be drawn.
70    :param y: Defines the y axis or the height position where the object should be drawn.
71    :param update: If the parameter update is not passed we don't update the display.
72                   But if the parameter update is passed as True we update the display.
73    :return: It returns the object on the display at its specific place or it returns
74            the object on the display at its specific place and updates and updates the display based on the parameter
75            update.
76    """
77
78    if update is True:
79        WINDOW.blit(thing, (x, y))
80        return pygame.display.update()
81
82    else:
83        return WINDOW.blit(thing, (x, y)
84text_width, text_height = FONT.size(text)
85def render_text(font, text, color, x, y, max_length = 100, update=False):
86
87    line_y = y
88    si = 0
89    ei = 1
90    while ei < len(text)+1:
91        text_width, text_height = font.size(text[si:ei])
92        if text_width > max_length:
93            text_surf = font.render(text[si:ei-1], True, color)
94            WINDOW.blit(text_surf, (x, line_y))
95            line_y += font.get_linesize()
96            si = ei-1
97        ei += 1
98    if si < len(text):
99        text_width, text_height = font.size(text[si:])
100        text_surf = font.render(text[si:], True, color)
101        WINDOW.blit(text_surf, (x, line_y))
102    
103    if update:
104        pygame.display.update()
105
1def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
2               thing_x=None, thing_y=None):
3    """
4
5    :param x: Defines the x axis or the width position where the text input should be drawn.
6    :param y: Defines the y axis or the height position where the text input should be drawn.
7    :param color: Defines the color of the text input.
8    :param char: If the parameter char in not entered it does not do anything otherwise it display's the the parameter
9                 char's text on the screen
10    :param char_x: If the parameter char is entered char_x Defines the x axis or the width position where the text
11                   should be drawn.
12    :param char_y: If the parameter char is entered char_y Defines the y axis or the height position where the text
13                   should be drawn.
14    :param char_color: Defines the color of the text of the parameter char in rgb color pixels.
15    :param fill: If the parameter fill is entered it fills the display with the tuple of the rgb color pixels which the
16                 user entered. But if the parameter fill is not entered it fills the display with the rgb color code
17                 black.
18    :param thing: If the user wants some thing to been drawn on the display the fill the parameter thing with the object
19                  they want to draw. But if the parameter thing is not entered. The thing parameter should be a pygame
20                  Surface.
21    :param thing_x: If the parameter thing is entered thing_x Defines the x axis or the width position where the
22                    parameter thing should be drawn
23    :param thing_y: If the parameter thing is entered thing_y Defines the y axis or the height position where the
24                    parameter thing should be drawn.
25    :return: It Display's the text input and the other parameters which were entered on the window and the updates it.
26    """
27
28    characters = ""
29    WINDOW.fill(fill)
30    if thing is not None:
31        draw(thing, thing_x, thing_y)
32    if char is not None:
33        char_text = str(char)
34        char_text_surface = FONT.render(char_text, True, char_color)
35        draw(char_text_surface, char_x, char_y, True)
36    pygame.display.update()
37
38    while True:
39        for detect in pygame.event.get():
40            if detect.type == QUIT:
41                exit()
42
43            elif detect.type == KEYDOWN:
44                if detect.key == K_BACKSPACE:
45                    characters = characters[:-1]
46                elif detect.key == K_RETURN:
47                    global text
48                    text = characters
49                    return text
50
51                else:
52                    characters = characters + detect.unicode
53
54                WINDOW.fill(fill)
55                if thing is not None:
56                    draw(thing, thing_x, thing_y)
57                if char is not None:
58                    char_text = str(char)
59                    char_text_surface = FONT.render(char_text, True, char_color)
60                    draw(char_text_surface, char_x, char_y, True)
61
62                text = FONT.render(f"{characters}", True, color)
63                print(char_x)
64                draw(text, x, y, True)
65def draw(thing, x, y, update=None):
66    """
67
68    :param thing: The object what needs to be drawn on the screen
69    :param x: Defines the x axis or the width position where the object should be drawn.
70    :param y: Defines the y axis or the height position where the object should be drawn.
71    :param update: If the parameter update is not passed we don't update the display.
72                   But if the parameter update is passed as True we update the display.
73    :return: It returns the object on the display at its specific place or it returns
74            the object on the display at its specific place and updates and updates the display based on the parameter
75            update.
76    """
77
78    if update is True:
79        WINDOW.blit(thing, (x, y))
80        return pygame.display.update()
81
82    else:
83        return WINDOW.blit(thing, (x, y)
84text_width, text_height = FONT.size(text)
85def render_text(font, text, color, x, y, max_length = 100, update=False):
86
87    line_y = y
88    si = 0
89    ei = 1
90    while ei < len(text)+1:
91        text_width, text_height = font.size(text[si:ei])
92        if text_width > max_length:
93            text_surf = font.render(text[si:ei-1], True, color)
94            WINDOW.blit(text_surf, (x, line_y))
95            line_y += font.get_linesize()
96            si = ei-1
97        ei += 1
98    if si < len(text):
99        text_width, text_height = font.size(text[si:])
100        text_surf = font.render(text[si:], True, color)
101        WINDOW.blit(text_surf, (x, line_y))
102    
103    if update:
104        pygame.display.update()
105def text_input(x, y, color, char=None, char_x=None, char_y=None, char_color=None, fill=(0, 0, 0), thing=None,
106               thing_x=None, thing_y=None):
107    # [...]
108
109    while True:
110        for detect in pygame.event.get():
111            if detect.type == QUIT:
112                exit()
113
114            elif detect.type == KEYDOWN:
115                # [...]
116
117                render_text(FONT, characters, color, x, y, 100, True)
118

Source https://stackoverflow.com/questions/67514758

Community Discussions contain sources that include Stack Exchange Network

Tutorials and Learning Resources in Pygame

Tutorials and Learning Resources are not available at this moment for Pygame

Share this Page

share link

Get latest updates on Pygame