I've been following a tutorial from here to build a small python game.
This would be the code behind it:
import pygame
pygame.init()
display_width = 1280
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Racing Game")
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
carImg = pygame.image.load("racecar.png")
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
car_speed = 0
crashed = True
while crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = False
## <code to remove>
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type = pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
## </code to remove>
print(event)
x += x_change
gameDisplay.fill((255,255,255))
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
quit()
When I try to run it the window opens and immediately closes. If I remove however the code between the two ## <code to remove> and ## </code to remove> everything works fine. What is causing in that piece of code for this to happen?
This is caused by the syntax error at if event.type = pygame.KEYUP:. Opening the file will cause it to close instantly, but running it in the interpreter (IDLE) will show you that error. Just change it to if event.type == pygame.KEYUP: and everything will work fine.
UPDATE:
Running code from the file rather than the interpreter (IDLE) won't always open. It is best to run it in IDLE.
Code:
import pygame
pygame.init()
display_width = 1280
display_height = 720
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Racing Game")
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
carImg = pygame.image.load("racecar.png")
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = display_width * 0.45
y = display_height * 0.8
x_change = 0
car_speed = 0
crashed = True
while crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = False
#############################
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
#############################
print(event)
x += x_change
gameDisplay.fill((255,255,255))
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
quit()
Related
I am currently following a pygame tutorial on a chromebook on which i have installed and linux to use IDLE. i am writing a block of code which assigns and x-axis increase or decrase to the arrow keys:
import pygame
pygame.init()
displayWidth = 800
displayHeight = 600
black = (0, 0, 0)
white = (255, 255, 255)
clock = pygame.time.Clock()
crashed = False
carImg = pygame.image.load('racecar.png')
def car(x,y):
gameDisplay.blit(carImg, (x,y))
x = (displayWidth * 0.45)
y = (displayHeight * 0.8)
x_change = 0
car_speed = 0
gameDisplay = pygame.display.set_mode((displayHeight, displayWidth))
pygame.display.set_caption('Zoomer')
clock = pygame.time.Clock()
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.fill(white)
car(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
when i try to run the code, the car sprite won't budge. is this due to the fact that i am on chromebook and key names are different or is it an other reason? thanks.
It doesn't work because you have wrong indentations.
You check pygame.KEYDOWN inside if ... pygame.QUIT: which is executed only when you close window.
You need all if event.type start in the same column
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
I've been following an youtube tutorial to begin with python and pygmae but started doing modifications before finishing it(https://www.youtube.com/watch?v=dX57H9qecCU&index=5&list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO). I wanted to add this same "sprite change when pressed" (how to change a sprite on the screen after pressing a key in pygame) to my code but i get nothing. the game just runs as if there was no code at all for this.
import pygame
import time
pygame.init() #as important as import pygame, always init pygame
display_width = 600
display_height = 900
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
starship_width = 60
gameDisplay = pygame.display.set_mode((display_width,display_height)) #sets window size. Put between () so it's seen as a single parameter
pygame.display.set_caption("Starship") #changes window title display
clock = pygame.time.Clock() #sets clock as frames per second
ship_image_names = ["starship", "move_right", "move_left"]
ship_sprites = dict(((img_name, pygame.image.load(img_name + ".png"))
for img_name in ship_image_names))
starshipImp = ship_sprites["starship"]
def starship(x,y): #sets image position
gameDisplay.blit(starshipImp,(x,y))
def text_objects(text,font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def kb_disable():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or pygame.K_RIGHT or pygame.K_UP or pygame.K_DOWN:
pass
def message_display(text):
largeText = pygame.font.Font("theboldfont.ttf",70)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2-170))
gameDisplay.blit(TextSurf,TextRect)
def message_display1(text):
largeText = pygame.font.Font("theboldfont.ttf",70)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2-100))
gameDisplay.blit(TextSurf,TextRect)
pygame.display.update()
while not kb_disable():
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_y:
game_loop()
elif event.key == pygame.K_n:
pygame.quit()
quit()
def replay():
message_display("You Crashed")
message_display1("Replay? (Y)(N)")
def game_loop():
x = (display_width * 0.5 - 45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
game_Exit = False # beginning game loop
while not game_Exit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
elif event.key == pygame.K_RIGHT:
x_change = 5
if event.key == pygame.K_UP:
y_change = -5
elif event.key == pygame.K_DOWN:
y_change = 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
x += x_change
y += y_change
gameDisplay.fill(white) #background
starship(x,y) #shows starship image
if x_change == 0:
starshipImp = ship_sprites["starship"]
if x_change > 0:
starshipImp = ship_sprites["move_right"]
if x_change < 0:
starshipImp = ship_sprites["move_left"]
if x > display_width - starship_width or x < 0: #setting boundaries to left and right border
replay()
pygame.display.update() #update the screen
clock.tick(120)
game_loop()
pygame.quit()
quit()
I also added some kind of replay function but it's buggy, when I press the designated key, it doesn't always work, dont know why.
Any help would be greatly appreciated
near pygame.K_DOWN or other with pygame.K_
after pygame.K_ command add you r desired contorl key name
My name is Jeremy and I am learning Python. I am a beginner and I just started a couple of days ago.
I am making a simple game in Python, and I would like my block/player to move continuously while the respective arrow key is held down. As of now, it only moves once when pressing down the arrow keys. Any help is greatly appreciated. Thank you!
Here is the code I've written:
import pygame
import time
import random
pygame.init()
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (200,0,0)
green = (0,200,0)
bright_red = (255,0,0)
bright_green = (0,255,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Game')
clock = pygame.time.Clock()
blockImg = pygame.image.load('blockpic.png')
def block(x,y):
gameDisplay.blit(blockImg, (x,y))
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
y_change = 0
crashed = False
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
if event.key == pygame.K_RIGHT:
x_change = 10
if event.key == pygame.K_UP:
y_change = -10
if event.key == pygame.K_DOWN:
y_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
x += x_change
y += y_change
gameDisplay.fill(white)
block(x,y)
pygame.display.update()
clock.tick(60)
pygame.quit()
quit()
Your code is not indented correctly. The line x += x_change and the five lines beneath are inside of the event loop, so they get executed once per event in the event queue. Just dedent these lines to fix the program.
while not crashed:
for event in pygame.event.get():
if event.type == pygame.QUIT:
crashed = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -10
if event.key == pygame.K_RIGHT:
x_change = 10
if event.key == pygame.K_UP:
y_change = -10
if event.key == pygame.K_DOWN:
y_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
# The following lines should be executed once per frame not
# once per event in the event queue.
x += x_change
y += y_change
gameDisplay.fill(white)
block(x,y)
pygame.display.update()
clock.tick(60)
I have the game come up and the rectangle rendered.
When I press my KEYDOWN it doesn't move the rectangle, it just makes it longer.
I have tried tons of stuff. I am new to Pygame.
Any help would be amazing.
Here is the code:
import pygame
import time
import random
import math
import sys
pygame.init()
display_width = 1200
display_height = 800
white = (255,255,255)
black = (0,0,0)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Vertical Pong')
clock = pygame.time.Clock()
def pongBoard(x,y,):
pygame.draw.rect(gameDisplay,white,(x,y,250,25))
def gameLoop():
x = 325
y = 750
xChange = 0
inGame = True
while inGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
xChange = -5
print("Left")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
xChange = 5
print("Right")
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
xChange = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
xChange = 0
pongBoard(x,y)
x += xChange
pygame.display.update()
clock.tick(60)
gameLoop()
pygame.quit()
quit()
So the problem is this:
The rectangle is being constantly redrawn at a different coord, but the screen is not being drawn over the rectangle to cover up the part that is not supposed to be there. In simpler terms, we need to constantly draw the background.
So now the code in the main game loop:
while inGame:
#This code below draws the background
pygame.draw.rect(gameDisplay, black, (0, 0, display_width, display_height))
That is it! The background will constantly cover up the pong ball, and the pong ball will be constantly blitted to a new position!
P.S, there is a better way to do arrow key movement here: How to get keyboard input in pygame?
it actualy does move it, but the old one just stays there, making it look like it does not move but just grows. one way to change that would be to change the old ones color to the background color
try this code it works :-)
import pygame
import time
import random
import math
import sys
pygame.init()
display_width = 1200
display_height = 800
white = (255,255,255)
black = (0,0,0)
red = (123,11,45)
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Vertical Pong')
clock = pygame.time.Clock()
def pongBoard(x,y,xold):
pygame.draw.rect(gameDisplay,white,[x,y,250,25])
pygame.draw.rect(gameDisplay,red,[xold,y,250,25])
def gameLoop():
x = 325
y = 750
xChange = 0
inGame = True
while inGame:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
xChange = -50
pongBoard(x,y,xold)
print("Left")
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
xChange = 50
pongBoard(x,y,xold)
print("Right")
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_RIGHT:
xChange = 0
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or event.key == pygame.K_LEFT:
xChange = 0
xold = x
x += xChange
xold = x-xChange
pygame.display.update()
clock.tick(60)
gameLoop()
pygame.quit()
quit()
I did a bit of research to see if i could solve the issue that way, but didn't seem to find anything to solve my problem. I found both of these : Why isn't my pygame display displaying anything? and Confused at why PyGame display's a black screen. I tried to solve my problem with what was adviced in the comments but it didn't work, or the reason for the problem was different than mine.
When i run the code the pygame window shows, but is just completely black, but no errors are called.
so here is the code (might be a bit long).
import pygame
import time
import random
pygame.init()
display_width = 700
display_height = 900
player_width = 140
player_height = 100
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Baby shower')
clock = pygame.time.Clock()
greenkidimg = pygame.image.load('kid green.png')
bluekidimg = pygame.image.load('kid blue.png')
redkidimg = pygame.image.load('kid red.png')
catcherimg = pygame.image.load('catcher.png')
background = pygame.image.load('background.png')
#image loads
def player(x,y):
gameDisplay.blit(catcherimg,(x,y))
def bluekid(bluex, bluey, bluew, blueh):
gameDisplay.blit(bluekidimg, (bluex, bluey))
def redkid(redx, redy, redw, redh):
gameDisplay.blit(redkidimg, (redx,redy))
def greenkid(greenx, greeny, greenw, greenh):
gameDisplay.blit(greenkidimg(greenx, greeny))
def game_loop():
x = (display_width*0.45)
y = (display_height*0.8)
x_change = 0
blue_width = 66
bluex_start = random.randrange (0, display_width-blue_width)
bluey_start = -600
blue_speed = 15
blue_height = 78
green_width = 66
greenx_start = random.randrange (0, display_width-green_width)
greeny_start = -600
green_speed = 15
green_height = 78
red_width = 66
redx_start = random.randrange (0, display_width-red_width)
redy_start = -600
red_speed = 15
red_heigth = 78
#greenkid,redkid,bluekid-start,speed,h/w
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
x_change = -20
elif event.type == pygame.K_RIGHT:
x_change = 20
if event.type == pygame.KEYUP:
if event.type == pygame.K_LEFT or pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.blit(background(0,0))
player(x,y)
bluekid(bluex, bluey, bluew, blueh)
redkid(redx, redy, redw, redh)
greenkid(greenx, greeny, greenw, greenh)
#display
pygame.display.update()
clock.tick(30)
game_loop()
pygame.quit()
quit()
The rendering logic in the game loop just needs to be indented to it is a part of the while loop inside it, like this:
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_LEFT:
x_change = -20
elif event.type == pygame.K_RIGHT:
x_change = 20
if event.type == pygame.KEYUP:
if event.type == pygame.K_LEFT or pygame.K_RIGHT:
x_change = 0
x += x_change
gameDisplay.blit(background(0,0))
player(x,y)
bluekid(bluex, bluey, bluew, blueh)
redkid(redx, redy, redw, redh)
greenkid(greenx, greeny, greenw, greenh)
pygame.display.update()
clock.tick(30)