This question already has answers here:
pygame.error: video system not initialized
(5 answers)
why is the exit window button work but the exit button in the game does not work?
(1 answer)
Closed 1 year ago.
Here is my underdeveloped pygame ping-pong game, but my sprites(player&opponent) ain't moving, on giving a keyboard input. And when I quit the program, it yells an error pygame.error: video system not initialized. My pygame is the latest 1.9.6 version with all the files up-to-daee. However, I am certain that pygame.display is generating this error, but I even tried pygame.display.init() and that too didn't worked :(
import pygame
# Initialization
pygame.init()
# Screen, Caption and Icon
width = 800
height = 600
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('PyGame')
icon = pygame.image.load('ping-pong.png')
pygame.display.set_icon(icon)
# Create Rects
player = pygame.Rect((5, 230), (10, 120))
opponent = pygame.Rect((785, 230), (10, 120))
# Game Variables
playerY_change = 0
opponentY_change = 0
game_over = False
while not game_over:
# Coloring the Screen
screen.fill((27, 35, 43))
# Draw Rects
pygame.draw.rect(screen, (255,255,255), player)
pygame.draw.rect(screen, (255,255,255), opponent)
# Managing Events
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
pygame.quit()
if event.type == pygame.KEYUP:
if event.type == pygame.K_UP:
opponentY_change -= 3
if event.type == pygame.K_DOWN:
opponentY_change += 3
if event.type == pygame.K_w:
playerY_change -= 3
if event.type == pygame.K_s:
playerY_change += 3
if event.type == pygame.KEYDOWN:
if (event.type == pygame.K_UP) or (event.type == pygame.K_DOWN):
opponentY_change = 0
if (event.type == pygame.K_w) or (event.type == pygame.K_s):
playerY_change = 0
# Moving my sprites
player.y += playerY_change
opponent.y += opponentY_change
# Updating the screen on every iter of loop
pygame.display.update()
Here, you have two different problems :
First the movement is not working because to differentiate the keys, you use event.type to compare where it should be event.key. Try with for example :
if event.key == pygame.K_UP:
opponentY_change -= 3
The other problem is that when the game is over, you use pygame.quit() but later on the loop, you use pygame.display.update(). You should put the display update at the beginning of the loop.
Related
This question already has answers here:
How can I move the ball instead of leaving a trail all over the screen in pygame?
(1 answer)
How can I make a sprite move when key is held down
(6 answers)
Closed 4 months ago.
So i programmed a block which should move in pygame
But when i press any of the movement buttons it doesnt move the block it just duplicates it and moves it and the old square doesnt do anything
Yeah im probably really retarded and the answer is really obviousä
here is the script:
import pygame
from sys import exit
pygame.init()
width=800
height=800
screen = pygame.display.set_mode((width,height))
posy=500
posx=500
clock = pygame.time.Clock()
pygame.display.set_caption("Block")
while True:
for event in pygame.event.get():
pygame.draw.rect(screen, "red", pygame.Rect(posy, posx, 60, 60))
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
posx=posx-10
elif event.key == pygame.K_s:
posx=posx+10
elif event.key == pygame.K_a:
posy=posy-10
elif event.key == pygame.K_d:
posy=posy+10
if event.key == pygame.K_ESCAPE:
pygame.event.post(pygame.event.Event(exit()))
pygame.display.update()
clock.tick(60)
It looks like you're creating a new object every time, so you need to adjust your code like this:
rect = pygame.Rect(posy, posx, 60, 60)
for event in pygame.event.get():
pygame.draw.rect(screen, "red", rect)
if event.type == pygame.QUIT:
pygame.quit()
exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_w:
rect.move_ip(0, -10)
elif event.key == pygame.K_s:
rect.move_ip(0, 10)
elif event.key == pygame.K_a:
rect.move_ip(-10, 0)
elif event.key == pygame.K_d:
rect.move_ip(10, 0)
I am trying to make a small game in pygame. The player is the left hand red rectangle (if you run it) and I am just trying to make the rocket variable move to the left quickly. Whenever I run the program if I press any key or move my mouse it moves the rocket.
Here is the code:
import pygame,sys,random
pygame.init()
pygame.key.set_repeat(1, 100)
size=width,height=1280,830
screen = pygame.display.set_mode(size)
black = [0, 0, 0]
white = [255, 255, 255]
sky_blue = ((0,255,255))
red = ((255,0,0))
font = pygame.font.SysFont("Arial",14)
rocket=pygame.Rect(1200,350,150,50)
player= pygame.Rect(250,350,250,50)
hull=100
player_speed=100
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type==pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
player_speed=player_speed+100
if event.key == pygame.K_LEFT:
player_speed=player_speed-100
if event.key == pygame.K_UP:
player.top=player.top-50
if event.key == pygame.K_DOWN:
player.top=player.top+50
if player_speed>1000:
player_speed=1000
if player_speed<100:
player_speed=100
if player.top<0:
player.top=0
elif player.bottom>height:
player.bottom=height
#rocket code
if player.colliderect(rocket):
hull=hull-100
if player_speed>99:
rocket.right=rocket.right-5
screen.fill(sky_blue)
pygame.draw.rect(screen,red,player)
pygame.draw.rect(screen,red,rocket)
renderedText = font.render("Speed: "+str(player_speed),1,black)
screen.blit(renderedText, (width/2+50,10))
if hull<1:
renderedText = font.render("GAME OVER",1,black)
screen.blit(renderedText, (width/2+500,500))
pygame.display.flip()
pygame.time.wait(10)
You indentation is incorrect which is causing a logic error.
if player_speed>1000:
...
rocket.right=rocket.right-5
The code between these lines need to be one indent lower. Else this code will only be run when there is a event. Since the for loop will skip execution of any code within if there is no events.
This question already has an answer here:
How to get if a key is pressed pygame [duplicate]
(1 answer)
Closed 1 year ago.
click here to see the image
PROGRAMING LANGUAGE THAT I USE IS PYTHON
As on the photo,i have a character(square) and i want when i press the left, right, up, down keys, it has to keep moving in that direction until it hits the wall then stops.But when i press those keys, it only moves once and not continuously like i thought.how to make it move continuously
import pygame
pygame.init()
clock = pygame.time.Clock()
#display
window = pygame.display.set_mode((600,600))
caption = pygame.display.set_caption('SwipeIt')
#player
square = pygame.image.load('asset/square.png').convert_alpha()
square_rect = square.get_rect(center = (100,150))
#wall
wall1 = pygame.image.load('asset/wall1.png').convert()
wall2 = pygame.image.load('asset/wall2.png').convert()
screw = pygame.image.load('asset/screw.png').convert()
white = (255,252,252)
gravity = 0.25
swipe = 0
loop = True
while loop:
print(window)
window.fill(white)
#wall
window.blit(wall1,(0,0))
window.blit(wall2,(0,0))
window.blit(wall2,(565,0))
window.blit(wall1,(0,566))
window.blit(screw,(0,0))
window.blit(screw,(0,566))
window.blit(screw,(565,0))
window.blit(screw,(565,566))
#player
window.blit(square,(square_rect))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
swipe += gravity
square_rect.centery += swipe
if event.key == pygame.K_UP:
swipe -= gravity
square_rect.centery -= swipe
if event.key == pygame.K_RIGHT:
swipe += gravity
square_rect.centerx += swipe
if event.key == pygame.K_LEFT:
swipe -= gravity
square_rect.centerx -= swipe
if event.type == pygame.QUIT:
loop = False
pygame.display.flip()
pygame.display.update()
clock.tick(120)
If you need, here is the link to download the files I have used .
''https://www.mediafire.com/file/ilogoklz3t9abpa/asset.rar/file''
I've made a snake game before and how I did it is by using a variable called direction.
Here is a little snippet from it.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
direction = "up"
if event.key == pygame.K_DOWN:
direction = "down"
if event.key == pygame.K_RIGHT:
direction = "right"
if event.key == pygame.K_LEFT:
direction = "left"
Then I would check the current direction and change the position depending on the direction.
For example:
one would be
if direction == "up":
player_y += 5
This question already has answers here:
How to get keyboard input in pygame?
(11 answers)
How can I make a sprite move when key is held down
(6 answers)
Closed 2 years ago.
I created a program with pygame. The background and player are appearing but the player is not moving. The program is not giving any errors, can you help me? I am using python 3.8.6. Here is some of my code.
# Game Loop
running = True
while running:
for event in pygame.event.get():
player(playerX, playerY)
pygame.display.update()
# Movment
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
player_x_change -= 10
if event.key == pygame.K_d:
player_x_change += 10
if event.key == pygame.K_w:
player_y_change -= 10
if event.key == pygame.K_s:
player_y_change += 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_a:
player_x_change = 0
if event.key == pygame.K_d:
player_x_change = 0
# Close the game
if event.type == pygame.QUIT:
running = False
Your code is just displaying the player, not moving him.
To move the player, you have, in a first step, to define a speed variable. Then you have to get the rectangle of your player. That will allow you to modify player position by using the speed variable you defined.
Also, if you want to move your player, you have to draw the background before drawing the player. Otherwise, every player you draw will not disappear.
And don't forget to define the game speed.
Code
#!/usr/bin/python3
import pygame
# set the game speed
delay = 10
screen = pygame.display.set_mode((800, 600))
# loading player image and get pos
player = pygame.image.load('pixel_ship_yellow.png')
player_pos = player.get_rect()
# define speed variable
speed = [1, 1]
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
break
# drawing background
screen.fill((0,0,0))
# apply speed (position is automatically updated)
player_pos = player_pos.move(speed)
# drawing player
screen.blit(player, player_pos)
pygame.display.flip()
# set the game speed
pygame.time.delay(delay)
You need to check for the event when a user pressed a button to move the character and then update the players position. For example, here's checking if the player pressed the right arrow:
while running:
for event in pygame.event.get():
player(playerX, playerY)
pygame.display.update()
# checking if right arrow is being pressed
if events.type == pygame.KEYDOWN:
if events.key == pygame.K_RIGHT
# update players x position here to move right
# for example, player.x += 2
# Close the game
if event.type == pygame.QUIT:
running = False
I have started making something on pygame but I have encountered an issue when moving left or right. if I quickly change from pressing the right arrow key to pressing the left one and also let go of the right one the block just stops moving. this is my code
bg = "sky.jpg"
ms = "ms.png"
import pygame, sys
from pygame.locals import *
x,y = 0,0
movex,movey=0,0
pygame.init()
screen=pygame.display.set_mode((664,385),0,32)
background=pygame.image.load(bg).convert()
mouse_c=pygame.image.load(ms).convert_alpha()
m = 0
pygame.event.pump()
while 1:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type==KEYDOWN:
if event.key==K_LEFT:
movex =-0.5
m = m + 1
if event.key==K_RIGHT:
movex=+0.5
m = m + 1
elif event.type == KEYUP:
if event.key==K_LEFT and not event.key==K_RIGHT:
movex = 0
if event.key==K_RIGHT and not event.key==K_LEFT:
movex =0
x+=movex
y=200
screen.blit(background, (0,0))
screen.blit(mouse_c,(x,y))
pygame.display.update()
is there a way I can change this so if the right arrow key is pressed and the left arrow key is released that it will go right instead of stopping?
P.S
I am still learning pygame and am very new to the module. I'm sorry if this seems like a stupid question but i couldn't find any answers to it.
Your problem is that when you test the KEYDOWN events with
if event.key==K_LEFT and not event.key==K_RIGHT:
you always get True, because when event.key==K_LEFT is True,
it also always is not event.key==K_RIGHT (because the key of the event is K_LEFT after all).
My approach to this kind of problem is to separate
the intent from the action. So, for the key
events, I would simply keep track of what action
is supposed to happen, like this:
moveLeft = False
moveRight = False
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
if event.key == K_LEFT: moveLeft = True
if event.key == K_RIGHT: moveRight = True
elif event.type == KEYUP:
if event.key == K_LEFT: moveLeft = False
if event.key == K_RIGHT: moveRight = False
Then, in the "main" part of the loop, you can
take action based on the input, such as:
while True:
for event in pygame.event.get():
...
if moveLeft : x -= 0.5
if moveRight : x += 0.5
the problem is that you have overlapping key features; If you hold down first right and then left xmove is first set to 1 and then changes to -1. But then you release one of the keys and it resets xmove to 0 even though you are still holding the other key. What you want to do is create booleans for each key. Here is an example:
demo.py:
import pygame
window = pygame.display.set_mode((800, 600))
rightPressed = False
leftPressed = False
white = 255, 255, 255
black = 0, 0, 0
x = 250
xmove = 0
while True:
window.fill(white)
pygame.draw.rect(window, black, (x, 300, 100, 100))
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
rightPressed = True
if event.key == pygame.K_LEFT:
leftPressed = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
rightPressed = False
if event.key == pygame.K_LEFT:
leftPressed = False
xmove = 0
if rightPressed:
xmove = 1
if leftPressed:
xmove = -1
x += xmove
pygame.display.flip()
One way could be to create a queue that keeps track of the button that was pressed last. If we press the right arrow key we'll put the velocity first in the list, and if we then press the left arrow key we put the new velocity first in the list. So the button that was pressed last will always be first in the list. Then we just remove the button from the list when we release it.
import pygame
pygame.init()
screen = pygame.display.set_mode((720, 480))
clock = pygame.time.Clock()
FPS = 30
rect = pygame.Rect((350, 220), (32, 32)) # Often used to track the position of an object in pygame.
image = pygame.Surface((32, 32)) # Images are Surfaces, so here I create an 'image' from scratch since I don't have your image.
image.fill(pygame.Color('white')) # I fill the image with a white color.
velocity = [0, 0] # This is the current velocity.
speed = 200 # This is the speed the player will move in (pixels per second).
dx = [] # This will be our queue. It'll keep track of the horizontal movement.
while True:
dt = clock.tick(FPS) / 1000.0 # This will give me the time in seconds between each loop.
for event in pygame.event.get():
if event.type == pygame.QUIT:
raise SystemExit
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
dx.insert(0, -speed)
elif event.key == pygame.K_RIGHT:
dx.insert(0, speed)
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
dx.remove(-speed)
elif event.key == pygame.K_RIGHT:
dx.remove(speed)
if dx: # If there are elements in the list.
rect.x += dx[0] * dt
screen.fill((0, 0, 0))
screen.blit(image, rect)
pygame.display.update()
# print dx # Uncomment to see what's happening.
You should of course put everything in neat functions and maybe create a Player class.
I know my answer is pretty late but im new to Pygame to and for beginner like me doing code like some previous answer is easy to understand but i have a solution to.I didn`t use the keydown line code, instead i just put the moving event code nested in the main game while loop, im bad at english so i give you guy an example code.
enter code here
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT or event.type == pygame.K_ESCAPE:
run = False
win.blit(bg, (0, 0))
pressed = pygame.key.get_pressed()
if pressed[pygame.K_LEFT]:
x -= 5
if pressed[pygame.K_RIGHT]:
x += 5
if pressed[pygame.K_UP]:
y -= 5
if pressed[pygame.K_DOWN]:
y += 5
win.blit(image,(x,y))
pygame.display.update()
pygame.quit()
This will make the image move rapidly without repeating pushing the key, at long the code just in the main while loop with out inside any other loop.