I've been struggling to get my code to work. I want my image to move continuously while pressing W,A,S, or D instead of having to repeatedly tap the key, but my code keeps having problems. Right now, it says that the video system is not initialized. I don't understand why this is popping up - I already have pygame.init() in my code.
import pygame
#set up the initial pygame window
pygame.init()
screen = pygame.display.set_mode([900,600])
#set background color
background = pygame.Surface(screen.get_size())
background.fill([204,255,229])
screen.blit(background, (0,0))
#Pull in the image to the program
my_image = pygame.image.load("google_logo.png")
#copy the image pixels to the screen
left_side = 50
height = 50
screen.blit(my_image, [left_side, height])
#Display changes
pygame.display.flip()
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
#set up pygame event loop
while True:
for event in pygame.event.get():
print event
if event.type == pygame.quit():
running = False
if event.type == pygame.KEYDOWN:
# change the keyboard variables
if event.key == K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == pygame.KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
pygame.quit()
Thanks!
I've had a bit of a muck around with your code and have fixed some of your little errors... Hopefully you can read through my comments some of the reasoning of why I've changed a few things. Also, your code was getting the video error because of a few reasons I believe: 1. You were constantly calling pygame.quit() because it was checking if the key 'escape' was not being pressed (pygame.KEYUP) 2. You are meant to put 'pygame.display.flip()' into the game loop itself so it can update the screen not just once and that's it.
You also needed to import sys in order to use the sys.exit() call.
Although the video error is fixed, your image doesn't move... Hopefully you figure out why.. :) Happy Coding!
-Travis
import pygame
# Initialize pygame and create the window!
pygame.init()
screen = pygame.display.set_mode((800,600))
#Creating background Surface and setting the colour.
background = pygame.Surface(screen.get_size())
background.fill((255,255,0))
# Loading a few needed variables.
my_image = pygame.image.load("dogtest.png")
left_side = 50
height = 50
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
# These varibales are standard when making a game of some sort!
total_frames = 0 #How many frames have passed.
clock = pygame.time.Clock() # Use this in the main loop to set game running
# at a certain speed!
FPS = 60
running = True #The game condition (whether the loop runs or not!)
while running:
# This is constantly repeating if the user presses the 'x' to close the
# program so the program closes safely and efficiently!
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.quit()
if event.type == pygame.KEYDOWN: # This handles Key Presses!
if event.key == pygame.K_ESCAPE:
running = False
pygame.quit()
sys.exit()
if event.key == pygame.K_LEFT or event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == pygame.K_RIGHT or event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == pygame.K_UP or event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == pygame.K_DOWN or event.key == ord('s'):
moveUp = False
moveDown = True
if event.type == pygame.KEYUP: # This is checking if the key ISN'T being pressed!
if event.key == pygame.K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == pygame.K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == pygame.K_UP or event.key == ord('w'):
moveUp = False
if event.key == pygame.K_DOWN or event.key == ord('s'):
moveDown = False
# Blitting the Background surface and image!
screen.blit(background, (0, 0))
screen.blit(my_image, (left_side, height))
clock.tick(FPS) # Sets the speed in which the code runs, (and the game!)
total_frames += 1 # Keeps a variable storing the number of frames have passed
pygame.display.update() # Constanly updates the screen! You can also use: pygame.display.flip()
quit()
Related
This question already has an answer here:
Python Pygame press two direction key and another key to shoot there's no bullet
(1 answer)
Closed 2 years ago.
I'm making my first pygame project and it has been going smoothly. I wrote the following code to check for inputs and so far it was working ok.
def check_events(self):
for event in pygame.event.get():
if event.type == pygame.QUIT:
self.running, self.playing = False, False
self.curr_menu = False
self.curr_level.run_level = False
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
self.DOWN_KEY = True
if event.key == pygame.K_UP:
self.UP_KEY = True
if event.key == pygame.K_RETURN:
self.START_KEY = True
if event.key == pygame.K_BACKSPACE or event.key == pygame.K_ESCAPE:
self.BACK_KEY = True
if event.key == pygame.K_LEFT:
self.LEFT_KEY = True
if event.key == pygame.K_RIGHT:
self.RIGHT_KEY = True
if event.key == pygame.K_SPACE:
self.SPACE_KEY = True
if event.key == pygame.K_RSHIFT or event.key == pygame.K_LSHIFT:
self.SHIFT_KEY = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
self.DOWN_KEY = False
if event.key == pygame.K_UP:
self.UP_KEY = False
if event.key == pygame.K_RETURN:
self.START_KEY = False
if event.key == pygame.K_BACKSPACE or event.key == pygame.K_ESCAPE:
self.BACK_KEY = False
if event.key == pygame.K_LEFT:
self.LEFT_KEY = False
if event.key == pygame.K_RIGHT:
self.RIGHT_KEY = False
if event.key == pygame.K_SPACE:
self.SPACE_KEY = False
if event.key == pygame.K_RSHIFT or event.key == pygame.K_LSHIFT:
self.SHIFT_KEY = False
I wanted to add a sprinting for the x (SHIFT) and y (SPACE) axis it doesn't work properly. Whenever hold down SPACE and RIGHT, pygame doesn't register the UP key getting pressed and whenever I hold SPACE and LEFT, pygame doesn't register both UP and DOWN.
Somehow, holding shift doesn't mess with the registration of the arrow keys.
Because of the issues I was experiencing with the sprinting I started investigating further and realized that pygame doesn't recognize me pressing the UP key when LEFT and RIGHT are pressed simultaneously, but recognizes the DOWN key press.
Is the problem in my code?
If you want to deal with pressed events you need to use:
pygame.key.get_pressed()
It returns the state of the key is pressed or not (True, False)
Example:
key_pressed = pygame.key.get_pressed()
if key_pressed[pygame.K_LSHIFT]:
sprintX()
if key_pressed[pygame.K_SPACE]:
sprintY()
I've got the code below, the image ain't moving. Please tell me what's wrong so I can fix it real quick. Also, try to keep the answers short and to the point.
I can hear the music and all, the escape button and the quit is working too, directional keys are not.
PlayerImage = pygame.image.load("ch.jpg")
Player = pygame.Rect(675, 350, 40, 4)
StretchPlayer = pygame.transform.scale(PlayerImage, (40, 40))
goLeft = False
goRight = False
goUp = False
goDown = False
Velocity = 3
EatSound = pygame.mixer.Sound("sound.wav")
pygame.mixer.music.load("X.mp3")
pygame.mixer.music.play(-1, 0.0)
musicPlaying = True
while True :
for event in pygame.event.get() :
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == ord('A'):
goRight = False
goLeft = True
if event.key == pygame.K_RIGHT or event.key == ord('D'):
goRight = True
goLeft = False
if event.key == pygame.K_UP or event.key == ord('W'):
goUp = True
goDown = False
if event.key == pygame.K_DOWN or event.key == ord('S'):
goUp = False
goDown = True
if event.type == pygame.KEYUP:
if event.key == pygame.K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == pygame.K_LEFT or event.key == ord('A'):
goLeft = False
if event.key == pygame.K_RIGHT or event.key == ord('D'):
goRight = False
if event.key == pygame.K_UP or event.key == ord('W'):
goUp = False
if event.key == pygame.K_DOWN or event.key == ord('S'):
goDown = False
DisplayScreen.blit(StretchPlayer, Player)
pygame.display.update()
Just change the location of the rectangle Player dependent on goLeft, goRight, goUp and goDown, e.g. by .move:
dx = -1 if goLeft else 1 if goRight else 0
dy = -1 if goUp else 1 if goDown else 0
Player = Player.move(dx, dy)
DisplayScreen.blit(StretchPlayer, Player)
This question already has answers here:
How to draw images and sprites in pygame?
(4 answers)
How do I blit a PNG with some transparency onto a surface in Pygame?
(4 answers)
Closed 1 year ago.
I'm trying to download the images stored in a subdirectory called "images" in pygame, but I get the File is not a Windows BMP file. I am running python 2.7 in Spyder on a Mac OS. I have pygame.image.get_extended() = 1 so not sure what the issue is. My pygame doesn't seem corrupted as it can run fine without a png (tried out a different game). Been struggling to figure out a solution. I already tried using .png and .bmp extensions for the images. Thank you
# From Al Sweigart's book
import pygame, sys, time, random, os
from pygame.locals import *
print os.getcwd()
# set up pygame
pygame.init()
mainClock = pygame.time.Clock()
# Set up window
windowWidth = 400
windowHeight = 400
windowSurface = pygame.display.set_mode((windowWidth, windowHeight), 0, 32)
pygame.display.set_caption("Sprites and Sounds")
# Set up colors
white = (255,255,255)
# Set up block data structure
player = pygame.Rect(300, 100, 40, 40)
playerImage = pygame.image.load("images/ninja.bmp")
playerStretchedImage = pygame.transform.scale(playerImage, (40,40))
foodImage = pygame.image.load("images/apple.bmp")
foodStretchedImage = pygame.transform.scale(foodImage, (15,15))
foods = []
for i in range(20):
foods.append(pygame.Rect(random.randint(0, windowWidth- 20),
random.randint(0, windowHeight-20), 20, 20))
foodCounter = 0
newfood = 40
# set up keyboard vars
moveLeft = False
moveRight = False
moveUp = False
moveDown = False
movespeed = 6
## Add sound here
# Run game loop
while True:
# check for quit event
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN:
# change keyboard variables
if event.key == K_LEFT or event.key == K_a:
moveRight = False
moveLeft = True
if event.key == K_RIGHT or event.key == K_d:
moveLeft = False
moveRight = True
if event.key == K_UP or event.key == K_w:
moveDown = False
moveUp = True
if event.key == K_DOWN or event.key == K_s:
moveUp = False
moveDown = True
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == K_a:
moveLeft = False
if event.key == K_RIGHT or event.key == K_d:
moveRight = False
if event.key == K_UP or event.key == K_w:
moveUp = False
if event.key == K_DOWN or event.key == K_s:
moveDown = False
if event.key == K_x:
player.top = random.randint(0, windowHeight-player.height)
player.left = random.randint(0, windowWidth-player.width)
if event.type == MOUSEBUTTONUP:
foods.append(pygame.Rect(event.pos[0], event.pos[1], 20, 20))
## Draw white background onto surface
windowSurface.fill(White)
## move player
if moveDown and player.bottom < windowHeight:
player.top += movespeed
if moveUp and player.top > 0:
player.top -= movespeed
if moveLeft and player.left >0:
player.left -= movespeed
if moveRight and player.right < windowWidth:
player.left += movespeed
# draw block image onto surface player object
windowSurface.blit(playerStretchedImage, player)
# check whether player has intersected with food squares
for food in foods[:]:
if player.colliderect(food):
foods.remove(food)
player = pygame.Rect(player.left, player.top,
player.width+2, player.height +2)
playerStretchedImage = pygame.transform.scale(playerImage,
(player.width, player.height))
# draw food
for food in foods:
windowSurface.blit(foodImage,food)
# draw window
pygame.display.update()
mainClock.tick(40)
Im working on a simple game( a semi copy of the 'Dodger' game), and the game runs, yet displays nothing. I have a while loop running, so why is nothing showing up? Is it a problem with spacing, the images themselves, or am i just overlooking something?
import pygame,sys,random, os
from pygame.locals import *
pygame.init()
#This One Works!!!!!!!
WINDOWHEIGHT = 1136
WINDOWWIDTH = 640
FPS = 40
TEXTCOLOR = (255,255,255)
BACKGROUNDCOLOR = (0,0,0)
PLAYERMOVEMENT = 6
HARVEYMOVEMENT = 5
TJMOVEMENT = 7
LASERMOVEMENT = 10
ADDNEWBADDIERATE = 8
COLOR = 0
TJSIZE = 65
HARVEYSIZE = 65
#Check the sizes for these
def terminate():
if pygame.event() == QUIT:
pygame.quit()
def startGame():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
def playerHasHitBaddies(playerRect,TjVirus,HarVirus):
for b in TjVirus and HarVirus:
if playerRect.colliderect(b['rect']):
return True
return False
def drawText(text,font,surface, x, y):
textobj = font.render(text, 1, TEXTCOLOR)
textrect = textobj.get_rect()
textrect.topleft = (x, y)
surface.blit(textobj, textrect)
mainClock = pygame.time.Clock()
WindowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT))
pygame.mouse.set_visible(False)
pygame.display.set_caption('Virus')
#Player Images
# Check the name of the .png file
TjImage = pygame.image.load('Virus_TJ_edited-1.png')
TjRect = TjImage.get_rect()
#chanhe this part from the baddies variable in the 'baddies' area
playerImage = pygame.image.load('Tank_RED.png')
playerRect = playerImage.get_rect()
LaserImage = pygame.image.load('laser.png')
LaserRect = LaserImage.get_rect()
pygame.display.update()
startGame()
while True:
TjVirus = []#the red one / make a new one for the blue one
HarVirus = []#The BLue one / Need to create a new dictionary for this one
playerRect.topleft = (WINDOWWIDTH / 2, WINDOWHEIGHT - 50)
moveLeft = moveRight = moveUp = moveDown = laser = False
baddieAddCounter = 0
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == ord('a'):
moveRight = False
moveLeft = True
if event.key == ord('d'):
moveLeft = False
moveRight = True
if event.key == ord('w'):
moveDown = False
moveUp = True
if event.key == ord('s'):
moveUp = False
moveDown = True
if event.key == K_SPACE:
lasers = True
if event.type == KEYUP:
if evnet.type == K_ESCAPE:
terminate()
if event.key == K_LEFT or event.key == ord('a'):
moveLeft = False
if event.key == K_RIGHT or event.key == ord('d'):
moveRight = False
if event.key == K_UP or event.key == ord('w'):
moveUp = False
if event.key == K_DOWN or event.key == ord('s'):
moveDown = False
if event.key == K_SPACE:
LaserImage.add(LaserRect)
if event.key == ord('j'):
COLOR = 2
if event.key == ord('k'):
if COLOR == 2:
COLOR = 1
playerImage = pygame.image.load('Tank_RED.png')
if COLOR == 1:
COLOR = 2
playerImage = pygame.image.load('Tank_BLUE.png')
if event.type == MOUSEMOTION:
playerRect.move_ip(event.pos[0] - playerRect.centerx, event.pos[1] - playerRect.centery)
if baddieAddCounter == ADDNEWBADDIERATE:
baddieAddCounter = 0
#Dict for TJ(RED) VIRUS
baddieSize = (TJSIZE)
NewTjVirus = {'rect':pygame.Rect(random.rantint(0,WINDOWWIDTH - TJSIZE),0 - TJSIZE,TJSIZE,TJSIZE),
'speed':(TJMOVEMENT),
'surface':pygame.transform.scale(TJImage,(TJSIZE,TJSIZE)),
}
TjVirus.append(NewTjVirus)
#Dict for Harvey(BLUE) virus
baddieSize = (HARVEYSIZE)
NewHarveyVirus = {'rect':pygame.Rect(random.randint(0,WINDOWWIDTH - HARVEYSIZE),0 - HARVEYSIZE,HARVEYSIZE,HARVEYSIZE),
'speed':(HARVEYMOVEMENT),
'surface':pygame.transform.scale(HARVEYSIZE,(HARVEYSIZE,HARVEYSIZE))
}
HarVirus.append(NewHarveyVirus)
#Player Movement
if moveLeft and playerRect.left >0:
playerRect.move_ip(-1*PLAYERMOVEMENT,0)
if moveRight and playerRect.right < WINDOWWIDTH:
playerRect.move_ip(PLAYERMOVEMENT,0)
if moveUp and playerRect.top >0:
playerRect.move_ip(0,-1*PLAYERMOVEMENT)
if moveDown and playerRect.bottom < WINDOWHEIGHT:
playerRect.move_ip(0,PLAYERMOVEMENT)
pygame,mouse.set_pos(playerRect.centerx,playerRect.centery)
#Need to change for each individual virus
for b in HarVirus and TjVirus:
b['rect'].move_ip(0,b['speed'])
for b in HarVirus and TjVirus:
if b['rect'].top > WINDOWHEIGHT:
baddies.remove(b)
windowSurface.fill(pygame.image.load('Background_Proto copy.png'))
for b in HarVirus and TjVirus:
windowSurface.blit(b['surface'],b['rect'])
pygame.display.update()
if playerHasHitBaddies(playerRect,HarVirus,TjVirus):
break
for b in TjVirus and HarVirus[:]:
if b['rect'].top < WINDOWHEIGHT:
HarVirus.remove(b)
TjVirus.remove(b)
mainClock.tick(FPS)
Usally I use pygame.display.flip() not pygame.display.update()
You call your startGame() in your script, which looks like this:
def startGame():
while True:
for event in pygame.event.get():
if event.type == QUIT:
terminate()
if event.type == KEYDOWN:
if event.key == K_ESCAPE:
terminate()
return
The game is stuck in that while loop until you press a key.
That's your current problem, but there are other errors as well, like
def terminate():
if pygame.event() == QUIT:
pygame.quit()
pygame.event() is not callable. Maybe you wanted to pass an event as argument here?
And also
pygame,mouse.set_pos(playerRect.centerx,playerRect.centery)
, instead of .
I've been working on a school project, and I need some assistance with player movement. The problem is I have to manually tap the arrow / WASD keys for the player to move one spot at a time. The player won't move if I hold in the keys. How do I fix this issue?
Note - I'm using an outdated Python - Python 2.7.3
Code:
# Begin 'The Maze'
# Import modules
import os, sys, time, pygame
from pygame.locals import *
from pygame.time import *
# Initialise Pygame + Clock
pygame.init()
mainClock = pygame.time.Clock()
# Window Setup
WINDOWHEIGHT = 480
WINDOWWIDTH = 600
windowSurface = pygame.display.set_mode((WINDOWWIDTH, WINDOWHEIGHT), 0, 32)
pygame.display.set_caption('The Maze')
# Player Variables
player = pygame.Rect(50, 50, 50, 50)
# Colour Setup
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
RED = (255, 0, 0)
BLUE = (0, 0, 255)
GREEN = (0, 255, 0)
# Movement Variables
moveLEFT = False
moveRIGHT = False
moveUP = False
moveDOWN = False
MOVESPEED = 7
x,y = 0,0
charx,chary = 0,0
movex,movey = 0,0
# Game Loop & Events + Updates
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Change the keyboard variables
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = True
movex = -0.5
if event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = True
movex = -0.5
if event.key == K_UP or event.key == ord('w'):
moveUP = True
movey = 0.5
if event.key == K_DOWN or event.key == ord('s'):
moveDOWN = True
movey = -0.5
if event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = False
movex = 0
if event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = False
movex = 0
if event.key == K_UP or event.key == ord ('w'):
moveUP = False
movey = 0
if event.key == K_DOWN or event.key == ord('s'):
moveDOWN = False
movey = 0
# Background Setup
windowSurface.fill(WHITE)
# Player Setup + Updating Screen
if moveDOWN and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUP and player.top > 0:
player.top-= MOVESPEED
if moveLEFT and player.left > 0:
player.left -= MOVESPEED
if moveRIGHT and player.right < WINDOWWIDTH:
player.right += MOVESPEED
pygame.draw.rect(windowSurface, GREEN, player)
pygame.display.update()
mainClock.tick(40)
Thanks!
A simple dedent of the block of code after # Background Setup did the job.
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
# Change the keyboard variables
if event.type == KEYDOWN:
if event.key == K_LEFT or event.key == ord('a'):
moveLEFT = True
elif event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = True
elif event.key == K_UP or event.key == ord('w'):
moveUP = True
elif event.key == K_DOWN or event.key == ord('s'):
moveDOWN = True
elif event.type == KEYUP:
if event.key == K_ESCAPE:
pygame.quit()
sys.exit()
elif event.key == K_LEFT or event.key == ord('a'):
moveLEFT = False
elif event.key == K_RIGHT or event.key == ord('d'):
moveRIGHT = False
elif event.key == K_UP or event.key == ord ('w'):
moveUP = False
elif event.key == K_DOWN or event.key == ord('s'):
moveDOWN = False
# <-- Dedent
# Background Setup
windowSurface.fill(WHITE)
# Player Setup + Updating Screen
if moveDOWN and player.bottom < WINDOWHEIGHT:
player.top += MOVESPEED
if moveUP and player.top > 0:
player.top-= MOVESPEED
if moveLEFT and player.left > 0:
player.left -= MOVESPEED
if moveRIGHT and player.right < WINDOWWIDTH:
player.right += MOVESPEED
pygame.draw.rect(windowSurface, GREEN, player)
pygame.display.update()
mainClock.tick(40)