Pygame Not Respounding - python

I am a newbie in Pygame (I use many libraries in python) There is a severe problem I face that is My pygame window is not responding I don't know why but this is happening every time I
run the code.
Here is the window
here is the code:
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 20
height = 60
vel = 5
x1 = 100
y1 = 100
width1 = 20
height1 = 60
vel1 = 5
run = True
while run:
pygame.time.delay(100)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 245 - vel - width:
x += vel
if keys[pygame.K_UP] and y > vel :
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
win.fill((255,255,255)) # Fills the screen with black
pygame.draw.circle(win , (255,0,0), (x,y), width)
pygame.draw.circle(win , (255,0,0), (x1,y1), width)
pygame.draw.rect(win, (0,0,0), (245, 0, 20, 500))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
Could you just please help to deal wit this problem.

It's just a matter of Indentation. You have implemented an infinite loop, therefore the window does not respond. You need to draw the scene and handle the event in the application loop instead of after the application loop.
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 20
height = 60
vel = 5
x1 = 100
y1 = 100
width1 = 20
height1 = 60
vel1 = 5
run = True
while run:
pygame.time.delay(100)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 245 - vel - width:
x += vel
if keys[pygame.K_UP] and y > vel :
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
# INDENTATION
#-->|
win.fill((255,255,255)) # Fills the screen with black
pygame.draw.circle(win , (255,0,0), (x,y), width)
pygame.draw.circle(win , (255,0,0), (x1,y1), width)
pygame.draw.rect(win, (0,0,0), (245, 0, 20, 500))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()

Your issue is caused by the indentation of your script.
pygame.display.update() will update the screen, that should be inside the while run!
The 'Fills screen with black' can be done above the while, since you want that just once.
Same story for the for loop that will set run = False, the button and event's is something you want to check every iteration, so move it inside the while
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("First Game")
x = 50
y = 50
width = 20
height = 60
vel = 5
x1 = 100
y1 = 100
width1 = 20
height1 = 60
vel1 = 5
run = True
win.fill((255,255,255)) # Fills the screen with black
pygame.draw.circle(win , (255,0,0), (x,y), width)
pygame.draw.circle(win , (255,0,0), (x1,y1), width)
pygame.draw.rect(win, (0,0,0), (245, 0, 20, 500))
while run:
# pygame.time.delay(100)
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 245 - vel - width:
x += vel
if keys[pygame.K_UP] and y > vel :
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()

Related

How do i keep my player in pygame from going off of the screen

So i've been working lately on some 2D game for my school's final project...
And i needed to make my player or the controlled object so it doesn't go off of the screen/window
I've only managed to make the right and the buttom side of the screen
Here is the entire code
Thanks to whoever can help!
import pygame
import os
from pygame import draw
pygame.font.init()
WIDTH, HEIGHT = 900, 500
WIN = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption("Hello, World!")
FPS = 60
WHITE = pygame.color.Color('#FFFFFF')
x, y = 20, 20
player = pygame.image.load(os.path.join("Assests", "player1.png"))
player = pygame.transform.scale(player, (200, 200))
player_vel = 5
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
# redraw_window()
WIN.fill(WHITE)
keys = pygame.key.get_pressed()
global x, y
pressed = pygame.key.get_pressed()
if pressed[pygame.K_w]: y -= 5
if pressed[pygame.K_s] and y < HEIGHT - 140: y += 5
if pressed[pygame.K_a]: x -= 5
if pressed[pygame.K_d] and x < WIDTH - 120: x += 5
WIN.blit(player, (x, y))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
WIN.blit(player, (x, y))
pygame.quit()
main()
The answer for this is:
if pressed[pygame.K_w] and y-67 > 0: y -= 5
if pressed[pygame.K_s] and y < HEIGHT - 140: y += 5
if pressed[pygame.K_a]: x - 127 > 0 -= 5 # Try changing the numbers to get it right
if pressed[pygame.K_d] and x < WIDTH - 120: x += 5

Move two rects seperately with wasd and arrow keys in pygame?

I am new to programming with pygame and python itself. I was trying to make a simple local multiplayer game using pygame. I wrote my code while watching a tutorial on moving only one rectangle because I did not find anything on what I am trying to do. When I finished, I copied the part of the script with the variables and the movement for the rectangle and then pasted it and changed the variable names so it does not crash or something. Now, here comes my problem: because the movement is simple, it would print a new rectangle, if I press the buttons to move. Because of that, the background is refreshing its color all the time (or something like that) so only the one rectangle I want to move is shown. But if there is a second rect, the color covers it, and only one is visible all the time. How can I fix that?
Here is the code:
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("local multiplayer")
#variables player 1
X = 200
Y = 200
Width = 40
Height = 60
Vel = 5
#variables player 2
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
#player 1
if keys[pygame.K_a]:
X -= Vel
if keys[pygame.K_d]:
X += Vel
if keys[pygame.K_w]:
Y -= Vel
if keys[pygame.K_s]:
Y += Vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 255, 255), (X, Y, Width, Height))
pygame.display.update()
#player 2
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
pygame.display.update()
pygame.quit()
When you call win.fill((0, 0, 0)) the entire display is cleared. You have to draw the rectangles at once after clearing the display.
Update of the display at the end of the application loop. Multiple calls to pygame.display.update() or pygame.display.flip() cause flickering (see Why is the PyGame animation is flickering).
Simplify the code and use pygame.Rect objects to represent the players. Use pygame.Rect.clamp_ip to prevent the player from leaving the screen.
import pygame
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("local multiplayer")
clock = pygame.time.Clock()
player1 = pygame.Rect(200, 200, 40, 60)
vel1 = 1
player2 = pygame.Rect(50, 40, 40, 60)
vel2 = 1
run = True
while run:
clock.tick(50)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
player1.x += (keys[pygame.K_d] - keys[pygame.K_a]) * vel1
player1.y += (keys[pygame.K_s] - keys[pygame.K_w]) * vel1
player2.x += (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT]) * vel2
player2.y += (keys[pygame.K_DOWN] - keys[pygame.K_UP]) * vel2
player1.clamp_ip(win.get_rect())
player2.clamp_ip(win.get_rect())
win.fill((0, 0, 0))
pygame.draw.rect(win, (255, 255, 255), player1)
pygame.draw.rect(win, (255, 255, 255), player2)
pygame.display.update()
pygame.quit()
The typical PyGame application loop has to:
limit the frames per second to limit CPU usage with pygame.time.Clock.tick
handle the events by calling either pygame.event.pump() or pygame.event.get().
update the game states and positions of objects dependent on the input events and time (respectively frames)
clear the entire display or draw the background
draw the entire scene (blit all the objects)
update the display by calling either pygame.display.update() or pygame.display.flip()
You are doing win.fill((0, 0, 0)) right after displaying player 1. Remove this code before you display the second character. Also, keep the fill line at the top of your app loop. This would give:
pygame.init()
win = pygame.display.set_mode((500, 500))
pygame.display.set_caption("local multiplayer")
#variables player 1
X = 200
Y = 200
Width = 40
Height = 60
Vel = 5
#variables player 2
x = 50
y = 50
width = 40
height = 60
vel = 5
run = True
while run:
win.fill((0, 0, 0))
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
#player 1
if keys[pygame.K_a]:
X -= Vel
if keys[pygame.K_d]:
X += Vel
if keys[pygame.K_w]:
Y -= Vel
if keys[pygame.K_s]:
Y += Vel
pygame.draw.rect(win, (255, 255, 255), (X, Y, Width, Height))
#player 2
if keys[pygame.K_LEFT]:
x -= vel
if keys[pygame.K_RIGHT]:
x += vel
if keys[pygame.K_UP]:
y -= vel
if keys[pygame.K_DOWN]:
y += vel
pygame.draw.rect(win, (255, 255, 255), (x, y, width, height))
pygame.display.update()
pygame.quit()
It is also good practice to only update the screen once per loop. Another thing I would do is put the input all in the same if block (but that is not necessary). To further improve your code- consider making a player class that has a render function to display itself, along with an update function to handle control.

How to put an image on this rectangle? [duplicate]

This question already has an answer here:
How can I add an image or icon to a button rectangle in Pygame?
(1 answer)
Closed 1 year ago.
How can I stick an image to a rectangle? I think it has something to do with the blit function. I want to blit the image onto the rectangle on line 50.
import pygame
import sys
pygame.init()
FPS = 60
start_smallfont = pygame.font.SysFont('Corbel', 45)
start_text = start_smallfont.render('Start', True, (255, 255, 255))
rect_smallfont = pygame.font.SysFont('Corbel', 33)
rect_text = rect_smallfont.render('You', True, (255, 255, 255))
x = 375
y = 335
vel = 0.1
startWIDTH, startHEIGHT = 170, 80
screenWIDTH, screenHEIGHT = 800, 720
WIN = pygame.display.set_mode((screenWIDTH, screenHEIGHT))
pygame.display.set_caption(":D")
def main():
clock = pygame.time.Clock()
run = True
while run:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
pygame.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if 800/2-85 <= mouse[0] <= 800/2-85+startWIDTH and 720/2-40 <= mouse[1] <= 720/2-40+startHEIGHT:
clock.tick(FPS)
run = False
while True:
global x, y
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
WIN.fill((0, 0, 0))
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < screenWIDTH - 50 - vel:
x += vel
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < screenHEIGHT - 50 - vel:
y += vel
pygame.draw.rect(WIN, (255, 0, 0), (x, y, 50, 50))
pygame.display.update()
mouse = pygame.mouse.get_pos()
if 800/2-85 <= mouse[0] <= 800/2-85+startWIDTH and 720/2-40 <= mouse[1] <= 720/2-40+startHEIGHT:
pygame.draw.rect(WIN, (255, 91, 91), (800/2-85, 720/2-40, startWIDTH, startHEIGHT))
else:
pygame.draw.rect(WIN, (255, 0, 0), (800/2-85, 720/2-40, startWIDTH, startHEIGHT))
WIN.blit(start_text, (800/2-85+42,720/2-40+20))
pygame.display.update()
if __name__ == "__main__":
main()
Any basic tutorial like this one shows how to do it, so it's not clear what you're having trouble with, since you didn't specify what issues you're having. This should work in your code though:
# goes at the top of the script:
image_to_draw = pygame.image.load('something.png')
# to draw the image:
WIN.blit(image_to_draw, (x, y, 50, 50))

I am having a problem with a pygame jumping system. Please tell me what's wrong in my code [duplicate]

This question already has answers here:
Pygame doesn't let me use float for rect.move, but I need it
(2 answers)
Closed 2 years ago.
Warning (from warnings module):
File "C:\Users\LENOVO\AppData\Local\Programs\Python\Python38-32\rect 2.py", line 57
pygame.draw.rect(win,(0, 0, 255), (x, y, width, height))
DeprecationWarning: an integer is required (got type float). Implicit conversion to integers using
__int__ is deprecated, and may be removed in a future version of Python.
This is the error I am getting from Shell and below is the code I typed:
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("nyumph")
x = 50
y = 425
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - width - vel:
x += vel
if not(isJump):
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
if keys[pygame.K_SPACE]:
isJump = True
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -=1
else:
isJump = False
jumpCount = 10
win.fill((0, 0, 0))
pygame.draw.rect(win,(0, 0, 255), (x, y, width, height))
pygame.display.update()
pygame.quit()
This code is supposed to display a rectangle and make it jump on pressing the keys. I am not able to understand the error and what is the meaning of it and I also don't know what I'm supposed to do? The jumping is not working somehow. Please help me with it.
This is not an error, it is a warning. The warning is caused by the fact that the rectangle argument for pygame.draw.rect has to be a tuple with integral values. In your application the coordinates (x, y) are floating point values.
You can get rid of the warning by rounding the x and y coordinate to integral values. Use the function round:
pygame.draw.rect(win,(0, 0, 255), (x, y, width, height))
pygame.draw.rect(win,(0, 0, 255), (round(x), round(y), width, height))
The jumping does not work in your application because of the wrong Indentation in the if statements.
See the working example:
import pygame
pygame.init()
win = pygame.display.set_mode((500,500))
pygame.display.set_caption("nyumph")
x = 50
y = 425
width = 40
height = 60
vel = 5
isJump = False
jumpCount = 10
run = True
while run:
pygame.time.delay(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
keys = pygame.key.get_pressed()
if keys[pygame.K_LEFT] and x > vel:
x -= vel
if keys[pygame.K_RIGHT] and x < 500 - width - vel:
x += vel
#<--| INDENTATION
if not(isJump):
if keys[pygame.K_UP] and y > vel:
y -= vel
if keys[pygame.K_DOWN] and y < 500 - height - vel:
y += vel
if keys[pygame.K_SPACE]:
isJump = True
#<------| INDENTATION
else:
if jumpCount >= -10:
neg = 1
if jumpCount < 0:
neg = -1
y -= (jumpCount ** 2) * 0.5 * neg
jumpCount -=1
else:
isJump = False
jumpCount = 10
win.fill((0, 0, 0))
pygame.draw.rect(win,(0, 0, 255), (round(x), round(y), width, height))
pygame.display.update()
pygame.quit()

Weird Keyboard Interrupt error that happens after ending program [duplicate]

This question already has an answer here:
How to get if a key is pressed pygame [duplicate]
(1 answer)
Closed 2 years ago.
I'm able to run the game and all of the graphics work but I cant get keyboard input to work even though it worked briefly the first time I used it. Additionally, it only gives the error after I close the program. Other pygame features, such as closing the program with the red x also don't work
import pygame
from essentials import *
import random
pygame.init()
screen_height = 640
screen_width = 640
win = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("The Room")
# button class
class button:
def __init__(self, color, x, y, width, height, text=''):
self.color = color
self.x = x
self.y = y
self.width = width
self.height = height
self.text = text
player_width = 25
player_height = 25
player_pos_x = 600
player_pos_y = 600
vel = 40 # set to ten for release
keys = pygame.key.get_pressed()
run2 = True
while run2:
win.fill((0, 0, 0))
# the circle
circle = pygame.draw.circle(win, GREEN, (50, 50), 5)
# the player square
player = pygame.draw.rect(win, RED, (player_pos_x, player_pos_y, player_width, player_height))
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
if keys[pygame.K_LEFT] and player_pos_x > vel:
player_pos_x -= vel
if keys[pygame.K_RIGHT] and player_pos_x < screen_width - player_width - vel:
player_pos_x += vel
if keys[pygame.K_UP] and player_pos_y > vel:
player_pos_y -= vel
if keys[pygame.K_DOWN] and player_pos_y < screen_height - player_height - vel:
player_pos_y += vel
if isOver(player, (50, 50)):
print("Ding!")
pygame.display.update()
isOver:
def isOver(self, pos):
if pos[0] > self.x and pos[0] < self.x + self.width:
if pos[1] > self.y and pos[1] < self.y + self.height:
return True
*note that I am using Ubuntu and am fairly new to it
keys = pygame.key.get_pressed() returns the current state of the keys. You have to retrieve the state of the keys continuously in the main application loop, rather than once before the loop:
# keys = pygame.key.get_pressed() <--- REMOVE
while run2:
keys = pygame.key.get_pressed() # <--- INSERT
Furthermore there is a type. In the condition of the while loop the variable run2 is evaluated, but in the event loop run is set:

Categories