NameError: name 'textSuface' is not defined - python

After the player rect has collided with the window width I am now getting an error suggesting that textSurface has not been defined even though it has been defined under def message_display(text):
The help would be greatly appreciated.
Here is my source code:
https://pythonprogramming.net/displaying-text-pygame-screen/?completed=/adding-boundaries-pygame-video-game/
And here is the source video:
https://www.youtube.com/watch?v=dX57H9qecCU&index=5&list=PLQVvvaa0QuDdLkP8MrOXLe_rKuf6r80KO
Contrasting here is my code:
# This just imports all the Pygame modules
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
# This initates your colors
black = (0,0,0)
# You have 256 color options so you only use 255 because one of those is 0
white = (255,255,255)
red = (255,0,0)
plyrImg_width = 30
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Bit Racer')
clock = pygame.time.Clock()
plyrImg = pygame.image.load('Sprite-01 double size.png')
def player(x,y):
gameDisplay.blit(plyrImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSuface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def killed():
message_display('You Died')
def game_loop():
x = (display_width * 0.45)
y = (display_height * 0.8)
x_change = 0
gameExit = False
while not gameExit:
# This handles any and all events in the game
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -5
if 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
# Make sure to write the background before the player
gameDisplay.fill(white)
player(x,y)
if x > display_width - plyrImg_width or x < 0:
killed()
pygame.display.update()
clock.tick(60)
# This is how you un-initiate pygame
# This is what closes the window so always have this
# If you want to end your game loop enter this
game_loop()
pygame.quit()
quit()

Try to spell it correctly. Surface, not suface.

Related

Sprite change when key is pressed

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

Pygame KEYUP, KEYDOWN causing ghost movement

I took a stab at learning KEYUP and KEYDOWN. Bascily, after the user crashes into any side of the window the game resets like intended. What is not intended is for the square to begin moving again even though no key has been pressed or released.
Ideal series of events:
- User Crashes
- Game resets with square in the original starting potion (stationary)
- press a movement key and square moves
Any insight into why this is happening would be great.
Thanks
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
car_width = 75
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
def game_loop():
x = 200
y = 200
x_change = 0
y_change = 0
gameExit = False
while not gameExit:
# Movement logic
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x_change += 5
if event.key == pygame.K_LEFT:
x_change += -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x_change += -5
if event.key == pygame.K_LEFT:
x_change += 5
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change += -5
if event.key == pygame.K_DOWN:
y_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
y_change += 5
if event.key == pygame.K_DOWN:
y_change += -5
x += x_change
y += y_change
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, red, [x, y, 75, 75])
# Check if border hit
if x > display_width - car_width or x < 0:
crash()
if y > display_height - car_width or y < 0:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Screw global variables, events and lots of flags.
Just use pygame.key.get_pressed to get the current state of the keyboard. Assign each arrow key a movement vector, add them up, normalize it, and there you go.
Also, if you want to do something with something rectangular, just use the Rect class. It will make your live a lot easier.
Here's a running example:
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
car_width = 75
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
keymap = {
pygame.K_RIGHT: pygame.math.Vector2(1, 0),
pygame.K_LEFT: pygame.math.Vector2(-1, 0),
pygame.K_UP: pygame.math.Vector2(0, -1),
pygame.K_DOWN: pygame.math.Vector2(0, 1)
}
def game_loop():
# we want to draw a rect, so we simple use Rect
rect = pygame.rect.Rect(200, 200, 75, 75)
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
# get the state of the keyboard
pressed = pygame.key.get_pressed()
# get all the direction vectors from the keymap of all keys that are pressed
vectors = (keymap[key] for key in keymap if pressed[key])
# add them up to we get a single vector of the final direction
direction = pygame.math.Vector2(0, 0)
for v in vectors:
direction += v
# if we have to move, we normalize the direction vector first
# this ensures we're always moving at the correct speed, even diagonally
if direction.length() > 0:
rect.move_ip(*direction.normalize()*5)
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, red, rect)
# Check if border hit
# See how easy the check is
if not gameDisplay.get_rect().contains(rect):
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
There are some other issues with your code:
For example, if you use time.sleep(2), your entire program will freeze. This means you can't close the window while waiting and the window will not be redrawn by the window manager etc.
Also, your code contains an endless loop. If you hit the wall often enough, you'll run into a stack overflow, because game_loop calls crash which in turn calls game_loop again. This is probably not a big issue at first, but something to keep in mind.
What you need is to set your game variables (x, y, x_change, y_change) back to defaults, most probably in crash() function after crash. pygame won't do that for you.
Either make your variables global, or use some mutable object (like dictionary) to access them from other methods.
As Daniel Kukiela says, you can make "x_change" and "y_change" into global variables, along with giving them the value of 0 at the start, here is the working project as far as I understand.
import pygame
import time
pygame.init()
display_width = 800
display_height = 600
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
car_width = 75
x_change = 0
y_change = 0
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
def game_loop():
x = 200
y = 200
global x_change
x_change == 0
global y_change
y_change == 0
gameExit = False
while not gameExit:
# Movement logic
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
x_change += 5
if event.key == pygame.K_LEFT:
x_change += -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_RIGHT:
x_change += -5
if event.key == pygame.K_LEFT:
x_change += 5
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change += -5
if event.key == pygame.K_DOWN:
y_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
y_change += 5
if event.key == pygame.K_DOWN:
y_change += -5
x += x_change
y += y_change
gameDisplay.fill(white)
pygame.draw.rect(gameDisplay, red, [x, y, 75, 75])
# Check if border hit
if x > display_width - car_width or x < 0:
crash()
if y > display_height - car_width or y < 0:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()

How do you make images in pygame and make them move?

I have been working on a game for a school project and I have these blocks come down the screen and you need to dodge them. I need to turn the blank drawn rectangles coming down the screen into a picture of a car I have.
This is my code so far:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
#^^NEED TO CHANGE TO AN IMAGE CALLED TAXI.PNG CAN SOMEONE PLEASE FIX FOR ME
def man(x,y):
gameDisplay.blit(manImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
pygame.mixer.music.play(-1)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
dodged = 0
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.key == pygame.K_LEFT:
x_change = -5
if 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)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
objects(object_startx, object_starty, object_width, object_height, cyan)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
if x > display_width - man_width or x < 0:
crash()
if object_starty > display_height:
object_starty = 0 - object_height
object_startx = random.randrange(0, display_width)
dodged += 1
object_speed += 0.7
object_width += (dodged * 1)
if y < object_starty+object_height:
print('y crossover')
if x > object_startx and x < object_startx + object_width or x+man_width > object_startx and x + man_width < object_startx+object_width:
print('x crossover')
crash()
pygame.display.update()
clock.tick(60)
game_intro()
game_loop()
pygame.quit()
quit()
If someone could fix it so it displays taxi.png instead of the rectangles as objects it would be greatly appreciated.
To draw the picture of the car instead of a rectangle, just do the same thing that you are doing with the man.
Under the line that is manImg = pygame.image.load('skater1.png'), put this line: carImg= pygame.image.load('taxi.png') This will load the picture of the car and it will be called carImg.
Now, you need to draw that picture onto the screen. Replace your objects function:
def objects(objectx, objecty, objectw, objecth, color):
pygame.draw.rect(gameDisplay, color, [objectx, objecty, objectw, objecth])
with a function to draw a car.
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
Notice how it is very similar to the man function, the only difference is the image that is drawn.
The last thing you need to do is actually call that drawCar function. Replace this line
objects(object_startx, object_starty, object_width, object_height, cyan)
with this one: drawCar(object_startx,object_starty)
I would recommend doing these changes yourself, it will help you learn. But if you're in a hurry, the final code, with all of these changes made, should be:
import pygame
import time
import random
pygame.init()
skate_sound = pygame.mixer.Sound("skateboard.wav")
pygame.mixer.music.load("menu_audio.wav")
ouch = pygame.mixer.Sound("ouch.wav")
display_width = 800
display_height = 600
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
cyan = (71, 148, 192)
green = (0, 255, 0)
dark_red = (200, 0 ,0)
dark_green = (0, 180 ,0)
grass_green = (39, 131, 51)
man_width = 35
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('Skate or Die')
clock = pygame.time.Clock()
manImg = pygame.image.load('skater1.png')
carImg= pygame.image.load('taxi.png')
def objects_dodged(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, black)
gameDisplay.blit(text, (0,0))
def drawCar(x,y):
pygameDisplay.blit(carImg,(x,y))
def man(x,y):
gameDisplay.blit(manImg,(x,y))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
pygame.mixer.Sound.play(ouch)
pygame.mixer.Sound.stop(skate_sound)
message_display("You Died!")
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
#print(click)
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
if click[0] == 1 and action != None:
if action == "play":
game_loop()
elif action == "quit":
pygame.quit()
quit()
else:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
gameDisplay.blit(textSurf, textRect)
def game_intro():
pygame.mixer.music.play(-1)
intro = True
while intro:
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(white)
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects("Skate or Die!", largeText)
TextRect.center = ((display_width/2),(display_height/2))
gameDisplay.blit(TextSurf, TextRect)
button("Start",150,450,100,50,dark_green,green,"play")
button("Quit",550,450,100,50,dark_red,red,"quit")
#pygame.draw.rect(gameDisplay, red,(550,450,100,50))
pygame.display.update()
clock.tick(3)
def game_loop():
pygame.mixer.Sound.stop(ouch)
pygame.mixer.music.stop()
pygame.mixer.Sound.play(skate_sound)
x = (display_width * 0.45)
y = (display_height * 0.75)
x_change = 0
object_startx = random.randrange(0, display_width)
object_starty = -600
object_speed = 8
object_width = 100
object_height = 80
dodged = 0
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.key == pygame.K_LEFT:
x_change = -5
if 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)
bg = pygame.image.load("bg.png")
gameDisplay.blit(bg, (0, 0))
man(x,y)
# objects(objectx, objecty, objectw, objecth, color)
drawCar(object_startx,object_starty)
object_starty += object_speed
man(x,y)
objects_dodged(dodged)
When you follow tutorials online, don't just copy and paste the code. Make sure that you understand what is happening so that in the future, you can do it yourself.

What would be a good condensed way to have a camera move with my player model? [duplicate]

This question already has answers here:
Add scrolling to a platformer in pygame
(4 answers)
Closed 5 years ago.
I'm a beginner at python and pygame. What would be a good condensed way to have a camera move with the play? (With the player being in the middle of the screen always) I've tried multiple things but they just don't work the way I want them to. Again I'm new so if it's a dumb question, let me know. Thanks in advance to anyone who bothers answering at all.
import pygame
import random
import time
pygame.init()
display_width = 1200
display_height = 1000
black = (0,0,0)
white = (255,255,255)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
player_width = 24
player_height = 42
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('Random RPG')
clock = pygame.time.Clock()
PMF = ("PlayerModel_Forward.png")
playerSprt = pygame.image.load(PMF)
def player(x,y):
gameDisplay.blit(playerSprt,(x,y))
def enemy1(enemy1x, enemy1y, enemy1w, enemy1h, color):
pygame.draw.rect(gameDisplay, color, [enemy1x, enemy1y, enemy1w, enemy1h])
def death():
message_display('Game Over')
def text_objects(text, font):
textSurface = font.render(text,
True, black)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf', 115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2), (display_height/2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
pygame.display.update()
game_loop()
def frames(fps):
font = pygame.font.SysFont(None, 25)
text = font.render(str(fps), True, black)
gameDisplay.blit(text,(0,0))
def xcoord(x_coord):
font = pygame.font.SysFont(None, 25)
text = font.render((str(x_coord)), True, black)
gameDisplay.blit(text,(display_width/2,0))
def ycoord(y_coord):
font = pygame.font.SysFont(None, 25)
text = font.render((str(y_coord)), True, black)
gameDisplay.blit(text,(display_width/2,25))
def text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def game_loop():
x = (display_width/2)
y = (display_height/2)
x_change = 0
y_change = 0
enemy1_startx = random.randrange(0, display_width)
enemy1_starty = random.randrange (0, display_height)
enemy1_x_change = random.randrange (-5,5)
enemy1_y_change = random.randrange (-5,5)
enemy1_width = 100
enemy1_height = 100
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
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
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
y_change = 5
elif event.key == pygame.K_UP:
y_change = -5
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0
x+= x_change
y+= y_change
Fps = 30
#Logic
if gameExit == True:
pygame.quit()
quit()
if x > display_width - player_width or x < 0:
death()
if y > enemy1_starty and y < enemy1_starty + enemy1_width or y+player_width > enemy1_starty and y + player_width < enemy1_starty + enemy1_width:
if x > enemy1_startx and x < enemy1_startx + enemy1_width or x+player_width > enemy1_startx and x + player_width < enemy1_startx + enemy1_width:
death()
time.sleep(2)
game_loop()
if enemy1_starty > display_height or enemy1_starty < 0 or enemy1_startx > display_width or enemy1_startx < 0:
enemy1_starty = random.randrange (0, display_height)
enemy1_startx = random.randrange(0, display_width)
enemy1_x_change = random.randrange (-5,5)
enemy1_y_change = random.randrange (-5,5)
#Drawing:
gameDisplay.fill(black)
player(x,y)
enemy1 (enemy1_startx, enemy1_starty, enemy1_width, enemy1_height, red)
enemy1_starty += enemy1_y_change
enemy1_startx += enemy1_x_change
frames((Fps))
xcoord (x)
ycoord (y)
pygame.display.update()
clock.tick(Fps)
game_loop()
pygame.quit()
quit()
You're doing really well! I think you may have taken the wrong approach, because instead of an actual camera moving ( which is insanely difficult to implement), the same effect can be reached, by moving every other element on the screen. So when the user presses right, instead of the player moving right, move the enemy left!: relevant code:
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
enemy1_startx = enemy1_startx+10
elif event.key == pygame.K_RIGHT:
enemy1_startx = enemy1_startx-10
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x_change = 0
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
enemy1_starty = enemy1_starty - 10
elif event.key == pygame.K_UP:
enemy1_starty = enemy1_starty + 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN or event.key == pygame.K_UP:
y_change = 0

How do you invert an animation on a shape in Python?

I'm currently working on making a game in my grade 10 Computer Science class, and my game is to (so far) have the player move a car up and down with the arrow keys while avoiding different shapes (right now the only shape is one square at the moment for testing), and if it touches the top or bottom of the screen the game is over and the code automatically repeats. I see that the square moves from left to right, but is there a way to make it move from right to left? Here's my code so far.
import pygame
import time
import random
pygame.init()
gameExit=False
display_width=800
display_height=600
car_height=188
gameDisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption('A bit Racey')
clock = pygame.time.Clock()
black = (0,0,0)
white = (255,255,255)
red=(255,0,0)
blue=(0,0,255)
crashed = False
carImg = pygame.image.load('racecar.png')
def car(x,y):
gameDisplay.blit(carImg, (x,y))
def things(thingx, thingy, thingw, thingh, colour):
pygame.draw.rect(gameDisplay, colour, [thingx, thingy, thingw, thingh])
def text_objects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def message_display(text):
largeText = pygame.font.Font('freesansbold.ttf',115)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width/2),(display_height/8))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
game_loop()
def crash():
message_display('You Crashed')
def game_loop():
x = (display_width * 0)
y = (display_height * 0.68)
gameExit=False
y_change=0
thing_starty=random.randrange(0, display_height)
thing_startx=-300
thing_speed=7
thing_width=100
thing_height=100
while not gameExit:
for event in pygame.event.get():
print(event)
if event.type == pygame.QUIT:
pygame.quit()
quit()
#Key bindings
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_change = -10
elif event.key == pygame.K_DOWN:
y_change = 10
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y_change = 0
y +=y_change
gameDisplay.fill(white)
# things(thingx, thingy, thingw, thingh, colour)
things(thing_startx, thing_starty, thing_width, thing_height, blue)
thing_startx += thing_speed
car(x,y)
if y > display_height - car_height or y < 0:
crash()
pygame.display.update()
clock.tick(60)
game_loop()
pygame.quit()
quit()
Changething_startx=-300 to thing_startx = display_width and thing_speed = 7 to thing_speed = -7.

Categories

Resources