I have been coding a program, a survival game, on Python. I seem to have an issue with adding Images/Sprites. I am noticing the images blink. Any way to fix this?
import os
import pygame
import time
import random
from pygame.locals import *
launchLog = pygame.init()
print(launchLog)
white = (255,255,255)
black = (0,0,0)
red=(255,0,0)
blue=(0,0,255)
green=(0,255,0)
skin = (236,227,100)
size = 10
dependant = (green)
rate = 0.0018
weight = 100
bound_x = 600
bound_x2 = bound_x-size
bound_y = 600
bound_y2 = bound_y-size
screen = pygame.display.set_mode((bound_x,bound_y))
pygame.display.set_caption("Survival: EfEs Edition")
clock = pygame.time.Clock()
font = pygame.font.SysFont(None,25)
x = 300
y = 300
roundX = x
roundY = y
img=pygame.image.load("pewds.png")
def hmn(x,y,size):
clothes = pygame.draw.rect(screen,skin,[x,y,size,size-size*2])
snake = pygame.draw.rect(screen, red, [x,y,size,size])
def mesg(msg,color):
txt = font.render(msg, True, color)
screen.blit(txt, [x,y-30])
display.flip(img)
def gameLoop():
global x
global y
jump = 1
quitted = False
starved = 100
eaten = False
restart = False
lead_change = 0
lead_y = 0
randF_x = random.randrange(0,bound_x)
randF_y = random.randrange(0,bound_y)
didX2=round(randF_x/10.0)*10.0
didY2=round(randF_y/10.0)*10.0
while not quitted:
screen.blit(img,(x,y -15))
screen.blit(img,(x,y -15))
pygame.display.update()
hmn(x,y,size)
starved=starved-rate
#print(starved)
if starved<0:
screen.fill(white)
mesg("You died of hunger! Press R to restart.",red)
pygame.display.flip()
time.sleep(0.3)
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_r:
starved = 100
pygame.display.update()
rate = 0.0018
x=300
y=300
for event in pygame.event.get():
#print(event)
if event.type == pygame.QUIT:
pygame.display.update()
quitted = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
lead_change = -.2
elif event.key == pygame.K_d:
lead_change = .2
elif event.key == pygame.K_w:
lead_y = .2
elif event.key == pygame.K_s:
lead_y = -0.2
if event.type == pygame.KEYUP:
if event.key == pygame.K_d or event.key == pygame.K_a:
lead_change = 0
#print(x)
#print(y)
elif event.key == pygame.K_ESCAPE:
#print("Quitting")
quitted = True
elif event.key == pygame.K_w or event.key == pygame.K_s:
#print(y)
lead_y=0
x += lead_change
y -= lead_y
roundX = x
roundY = y
global roundX
global roundY
didX=round(roundX/10)*10
didY=round(roundY/10)*10
screen.fill(white)
s = pygame.draw.rect(screen, red, [bound_x2/15,bound_y2/20, starved * 2, 50])
pygame.draw.rect(screen, dependant, [didX2,didY2,10,10])
pygame.display.update()
#boundary script
if x>bound_x2:
x=bound_x2
elif x<-1:
x=-1
elif y<2:
y=2
elif y>590:
y=590
hmn(x,y,size)
pygame.display.flip()
if didX == didX2 and didY==didY2:
didX2 = round(random.randrange(0,bound_x)/10)*10
didY2 = round(random.randrange(0,bound_y)/10)*10
global dependant
dependant = green
global starved
starved = starved +0.01
global weight
weight = weight + 3
elif weight>150:
mesg("Weight increased! You now get hungry faster.",black)
pygame.display.update()
global rate
rate = rate+0.0008
pygame.display.update()
clock.tick(55)
mesg("Leaving game", black)
screen.blit(img,(x,y-15))
pygame.display.update()
time.sleep(2)
pygame.quit()
quit()
gameLoop()`
Please excuse the bad coding, the game is only in it's earliest state.
The correct sequence is to:
draw everything you want to show on a frame (all the blit()s, draw()s), etc.
do only one of display.update() with a list of all the changed regions OR display.flip() to update the whole screen once you've drawn everything
tl;dr - don't mix draw()s with update()s.
Related
I'm attempting to detect a collision between two objects (both images).
I have rect's for both the objects, but cannot get the collision to be detected.
I've attempted to use rect's, comparing x and y positions.
import sys
import pygame
from pygame.locals import *
#init pygame
pygame.init()
window_width = 840
window_height = 650
size = (window_width, window_height)
screen = pygame.display.set_mode(size)
bg_img = pygame.image.load("img.png").convert_alpha()
crash = False
bot1x = 150
bot1y = 100
x = (window_width * 0.45)
y = (450)
clock = pygame.time.Clock()
fr = clock.tick(30)
x_speed = 0
car_img = pygame.image.load("car.png").convert_alpha()
car_img = pygame.transform.scale(car_img, (125, 175))
bot_img = pygame.image.load("bot.png").convert_alpha()
bot_img = pygame.transform.scale(bot_img, (175, 200))
def car(x, y):
screen.blit(car_img, (x,y))
def bot(x, y):
screen.blit(bot_img, (x,y))
car_rect = pygame.Rect(x, y, 125, 175)
bot_rect = pygame.Rect(bot1x, bot1y, 175, 200)
#game loop
while(crash==False):
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == K_LEFT:
x_speed = -.9
print("Moving Left")
if event.key == K_RIGHT:
x_speed = .9
print("Moving Right")
if event.type == pygame.KEYUP:
if event.key == K_LEFT:
x_speed = 0
if event.key == K_RIGHT:
x_speed= 0
if event.type == pygame.QUIT:
crash = True
bot1y += .5
# Move car
x += x_speed
if car_rect.colliderect(bot_rect):
print("collision deceted")
#blit images to screen
screen.blit(bg_img, [0, 0])
#spawn car
car(x,y)
bot(bot1x, bot1y)
#flip game display
pygame.display.flip()
#end game
pygame.quit()
quit()
I expect the game to output "Collision detected" when the two objects touch eachother.
Thanks,
Lachlan
I'm trying to make the snake game in python, but sadly my snake and my apples aren't appearing on the screen, all i see is a gray screen with nothing on it, can you help me out? thanks!
P.S - i would like an explanation as well about why my current code isn't working so i would avoid it in the future, thanks again.
import pygame, sys, random, time
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
windowWidth = 500
windowHeight = 500
windowSurface = pygame.display.set_mode((windowWidth, windowHeight), 0, 32)
red = (255, 0, 0)
green = (0, 255, 0)
color = (100, 100, 100)
snakeHead = [250, 250]
snakePosition = [[250, 250],[240, 250],[230, 250]]
applePosition = [random.randrange(1,50)*10,random.randrange(1,50)*10]
def collisionBoundarias(snakeHead):
if snakeHead[0] >= 500 or snakeHead[0] < 0 or snakeHead[1] >= 500 or snakeHead[1] < 0:
return 1
else:
return 0
def collisionSelf(SnakePosition):
snakeHead = snakePosition[0]
if snakeHead in snakePosition[1:]:
return 1
else:
return 0
while True:
windowSurface.fill(color)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.type == pygame.K_RIGHT or event.key == pygame.K_d:
snakeHead[0] += 10
if event.type == pygame.K_LEFT or event.key == pygame.K_a:
snakeHead[0] -= 10
if event.type == pygame.K_UP or event.type == pygame.K_w:
snakeHead[1] += 10
if event.type == pygame.K_DOWN or event.type == pygame.K_s:
snakeHead[1] -= 10
def displaySnake(snakePosition):
for position in snakePosition:
pygame.draw.rect(windowSurface ,red,pygame.Rect(position[0],position[1],10,10))
def display_apple(windowSurface, applePosition, apple):
windowSurface.blit(apple ,(applePosition[0], applePosition[1]))
snakePosition.insert(0,list(snakeHead))
snakePosition.pop()
def displayFinalScore(displayText, finalScore):
largeText = pygame.font.Font('freesansbold.ttf',35)
TextSurf = largeText.render(displayText, True, (255, 255, 255))
TextRect = TextSurf.get_rect()
TextRect.center = ((windowWidth/2),(windowHeight/2))
windowSurface.blit(TextSurf, TextRect)
pygame.display.update()
time.sleep(2)
def collisionApple(applePosition, score):
applePosition = [random.randrange(1,50)*10,random.randrange(1,50)*10]
score += 1
return applePosition, score
if snakeHead == applePosition:
applePosition, score = collisionApple(applePosition, score)
snakePosition.insert(0,list(snakeHead))
pygame.display.update()
clock = pygame.time.Clock()
clock.tick(20)
As mentioned in the comments, the objects don't appear because you never draw them by calling the displaySnake and display_apple functions. It also makes no sense to define these functions in the while loop again and again.
Here's a fixed version of the code. I've changed the movement code, so that the snake moves continually each frame. (It could still be improved, but I tried to keep it simple.)
import pygame, sys, random, time
from pygame.locals import *
pygame.init()
mainClock = pygame.time.Clock()
windowWidth = 500
windowHeight = 500
windowSurface = pygame.display.set_mode((windowWidth, windowHeight), 0, 32)
clock = pygame.time.Clock()
red = (255, 0, 0)
green = (0, 255, 0)
color = (100, 100, 100)
snakeHead = [250, 250]
snakePosition = [[250, 250],[240, 250],[230, 250]]
applePosition = [random.randrange(1,50)*10,random.randrange(1,50)*10]
apple = pygame.Surface((10, 10))
apple.fill(green)
score = 0
speed = 10
# Define a velocity variable (a list or better a pygame.Vector2).
velocity = pygame.Vector2(speed, 0)
def collisionBoundarias(snakeHead):
return snakeHead[0] >= 500 or snakeHead[0] < 0 or snakeHead[1] >= 500 or snakeHead[1] < 0
def collisionApple(applePosition, score):
applePosition = [random.randrange(1,50)*10,random.randrange(1,50)*10]
score += 1
return applePosition, score
def displaySnake(snakePosition):
for position in snakePosition:
pygame.draw.rect(windowSurface, red, pygame.Rect(position[0], position[1], 10, 10))
def display_apple(windowSurface, applePosition, apple):
windowSurface.blit(apple, (applePosition[0], applePosition[1]))
while True:
# Event handling.
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
# Replace `type` with `key`.
if event.key == pygame.K_RIGHT or event.key == pygame.K_d:
velocity.x = speed
velocity.y = 0
if event.key == pygame.K_LEFT or event.key == pygame.K_a:
velocity.x = -speed
velocity.y = 0
if event.key == pygame.K_UP or event.key == pygame.K_w:
velocity.x = 0
velocity.y = -speed
if event.key == pygame.K_DOWN or event.key == pygame.K_s:
velocity.x = 0
velocity.y = speed
# Game logic.
snakeHead[0] += velocity.x # Update the x-position every frame.
snakeHead[1] += velocity.y # Update the y-position every frame.
snakePosition.insert(0, snakeHead)
snakePosition.pop()
if snakeHead == applePosition:
applePosition, score = collisionApple(applePosition, score)
snakePosition.insert(0, snakeHead)
# Drawing.
windowSurface.fill(color)
displaySnake(snakePosition)
display_apple(windowSurface, applePosition, apple)
pygame.display.update()
clock.tick(20)
this is my first game I have created using pygame, it's basically snake.
Please do not mind my hideous comments.
## William's Snake Game
import pygame
import time
import random
pygame.init()
##Global variables
# Colours
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
green = (0, 155, 0)
bground = (204, 204, 0)
# Display vars.
display_width = 800
display_height = 600
# Variables
gameDisplay = pygame.display.set_mode((display_width, display_height)) ##resolution, note that this is a tuple.
pygame.display.set_caption("Snake VS Apple") # Title at the top of the screen
icon = pygame.image.load('logoapple32x32.png') # Loads the icon for the top left
pygame.display.set_icon(icon) # Sets the icon for the top left
snakeHeadImg = pygame.image.load("snakeHead.png") # Loads the image for the snake head
appleImg = pygame.image.load("apple20x20.png") # Loads the image for the apple
appleThickness = 20 # Defines how thick apple will be. Note to self: This is changable
clock = pygame.time.Clock() # Starts clocking the game, used later for FPS
blockSize = 20 # Defines how big the snake will be. Changing this will mess up collision detection.
FPS = 15 # Frames per second. Called at the bottom of script
smallfont = pygame.font.SysFont("arial", 25) ## format: ("font", fontsize)
medfont = pygame.font.SysFont("arial", 40) ##
largefont = pygame.font.SysFont("arial", 80) ##
direction = "right" # Starting direction of snake, used in main gameLoop
##
def pauseGame():
gameisPaused = True
while gameisPaused:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
gameisPaused = False
elif event.key == pygame.K_q:
pygame.quit()
quit()
gameDisplay.fill(white)
message_to_screen("Paused",
black,
-100,
size="large")
message_to_screen("Press ESC to continue or Q to quit.",
black,
25,
size="small")
pygame.display.update()
clock.tick(5)
def text_objects(text, color, size): # Function to render text
if size == "small":
textSurface = smallfont.render(text, True, color)
elif size == "medium":
textSurface = medfont.render(text, True, color)
elif size == "large":
textSurface = largefont.render(text, True, color)
return textSurface, textSurface.get_rect()
def message_to_screen(msg, color, y_displace=0, size="medium"): # Function to blit (draw) text to surface
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (display_width / 2), (display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
##
def score(score):
text = smallfont.render("Score: " + str(score), True, black)
gameDisplay.blit(text, [0, 0])
def randAppleGen(): # Function to generate random apples
randAppleX = round(
random.randrange(0, display_width - appleThickness)) # /10.0)*10.0 ##Create another rand X value for new apple
randAppleY = round(
random.randrange(0, display_height - appleThickness)) # /10.0)*10.0 ##Create another rand Y value for new apple
return randAppleX, randAppleY
def gameIntro(): # Function for game menu.
intro = True
while intro: # Event handling during menu
for eachEvent in pygame.event.get():
if eachEvent.type == pygame.QUIT:
pygame.quit()
quit()
if eachEvent.type == pygame.KEYDOWN:
if eachEvent.key == pygame.K_c:
gameLoop()
if eachEvent.key == pygame.K_q:
pygame.quit()
quit()
# Text displayed in menu
gameDisplay.fill(white)
message_to_screen("Welcome to Slither",
green,
-90,
"large")
message_to_screen("The more apples you eat, the longer you are",
black,
100)
message_to_screen("The objective of the game is to eat red apples",
black,
0,
"small")
message_to_screen("If you run into yourself, or the edges, you die!",
black,
30,
"small")
message_to_screen("Press C to play or Q to quit.",
black,
180)
pygame.display.update()
clock.tick(500)
def snake(blockSize, snakeList): # Function to draw snake
if direction == "right":
head = pygame.transform.rotate(snakeHeadImg,
270) # In gameLoop, right,left,up,down are used to change direction of snakeHead
elif direction == "left":
head = pygame.transform.rotate(snakeHeadImg, 90)
elif direction == "up":
head = snakeHeadImg
elif direction == "down":
head = pygame.transform.rotate(snakeHeadImg, 180)
gameDisplay.blit(head, (snakeList[-1][0], snakeList[-1][1])) ##???
for XandY in snakeList[:-1]:
pygame.draw.rect(gameDisplay, green,
[XandY[0], XandY[1], blockSize, blockSize]) ##width height, width height, drawing
##Main Game Loop
def gameLoop():
global direction ## Make direction a global var. Important
# Local variables
gameExit = False
gameOver = False
lead_x = display_width / 2
lead_y = display_height / 2
lead_x_change = 10
lead_y_change = 0
snakeList = []
snakeLength = 3
randAppleX, randAppleY = randAppleGen() # Generate apples. Calls randAppleGen()
# Main Game Loop ##eventHandler
while not gameExit:
snakeHead = [] # Creates list snakeHead
snakeHead.append(lead_x) # Appends snakeHead x value to list
snakeHead.append(lead_y) # Appends snakeHead y value to list
snakeList.append(snakeHead) # Appends coordinates of snakeHead x,y to list
while gameOver == True: # Handles game over
gameDisplay.fill(white)
message_to_screen("Game over",
red,
-50,
size="large")
message_to_screen("Press C to play again or Q to quit",
black,
50,
size="medium")
pygame.display.update()
for event in pygame.event.get(): # eventHandler for loss screen
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
gameExit = True
gameOver = False
if event.key == pygame.K_c:
direction = "right"
gameLoop()
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT or event.key == pygame.K_a: # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif event.key == pygame.K_RIGHT or event.key == pygame.K_d:
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif event.key == pygame.K_UP or event.key == pygame.K_w:
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif event.key == pygame.K_DOWN or event.key == pygame.K_s:
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
# Checks if user has hit screen boundaries.
if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0: # If user hits display boundaries
gameOver = True # They lose
lead_x += lead_x_change # Ensures continous movement of the snake
lead_y += lead_y_change
# Drawing
gameDisplay.fill(bground) # Fills the display background with predefined bground colour (defined at the top)
gameDisplay.blit(appleImg,
(randAppleX, randAppleY)) ##Draws the apple using the appleImg, at random coordinates.
if len(
snakeList) > snakeLength: # If the length of the list of snake body coordinates is greater than the length
del snakeList[0] # Delete the oldest value in the list (as the snake is constantly moving)
for eachSegment in snakeList[:-1]: # For each coordinate in snakeList
if eachSegment == snakeHead: # If the segment touches the snakeHead
## gameDisplay.fill(bground)
## snake(blockSize, snakeList)
##
## pygame.display.update
time.sleep(0.3)
gameOver = True # Game over
snake(blockSize, snakeList) ##Creates snake using function snake
score(snakeLength - 3) # Displays score (it minuses 3 because the snake starts at 3)
pygame.display.update() ##Updates to screen
## COLLISION DETECTION
if lead_x + blockSize > randAppleX and lead_x < randAppleX + appleThickness:
if lead_y + blockSize > randAppleY and lead_y < randAppleY + appleThickness:
randAppleX, randAppleY = randAppleGen()
snakeLength += 1
clock.tick(FPS)
pygame.quit()
quit()
##update screen
##
gameIntro()
gameLoop()
##Code goes above.
I have a problem where if my snake is going right, and then it turns left, my snake will crash onto itself and the game will end.
I want to design this so when my snake is going right, it cannot simply turn left, crash into itself and end the game. So when it turns right, it can only turn up, down, or keep going right. So simply, I want to make it so it cannot run backwards into itself.
I have tried coding this in myself, and I have tried many methods but nothing has worked.
Please help!!
Without altering your code too much (and without testing), an easy way to get what you want is to add another condition to your key checks. If you alter the relevant code section as follows, all should be fine:
for event in pygame.event.get(): # eventHandler for keyboard events during game
if event.type == pygame.QUIT:
gameExit = True
if event.type == pygame.KEYDOWN:
if (event.key == pygame.K_LEFT or event.key == pygame.K_a) and direction != "right": # Each of these handles either arrow keys or WASD key events.
lead_x_change = -blockSize
lead_y_change = 0
direction = "left"
elif (event.key == pygame.K_RIGHT or event.key == pygame.K_d) and direction != "left":
lead_x_change = blockSize
lead_y_change = 0
direction = "right"
elif (event.key == pygame.K_UP or event.key == pygame.K_w) and direction != "down":
lead_y_change = -blockSize
lead_x_change = 0
direction = "up"
elif (event.key == pygame.K_DOWN or event.key == pygame.K_s) and direction != "up":
lead_y_change = blockSize
lead_x_change = 0
direction = "down"
elif event.key == pygame.K_ESCAPE:
pauseGame()
Mind the parentheses around the or'd key checks!
So right now I am learning pygame and I'm using sentdex's tutorials. On I believe his 6th pygame tutorial he showed us how to generate more than just one block. I added the code, but it didin't work. I don't understand why it didn't work? Could you please tell me what I'm doing wrong and how to fix it?
Here's the code:
import pygame
import random
pygame.init()
white = (255,255,255)
black = (0,0,0)
red = (255,0,0)
window_width = 800
window_height = 600
gameDisplay = pygame.display.set_mode((window_width,window_height))
pygame.display.set_caption('MyFirstGame')
carImg = pygame.image.load("racecar.png")
clock = pygame.time.Clock()
def blocks(block_x, block_y, block_width, block_height, color):
pygame.draw.rect(gameDisplay, color, [block_x, block_y, block_width, block_height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
pygame.quit
quit()
gameExit = True
if event.key == pygame.K_c:
gameLoop()
print("User has decided to play again")
def gameLoop():
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# Defining variables to draw blocks
block_x = random.randrange(0, window_width)
block_y = -600
block_speed = 7
block_width = 100
block_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:
car_x_change += -5
if event.key == pygame.K_RIGHT:
car_x_change += 5
if event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
x_change = 0
if event.key == pygame.K_RIGHT:
x_change = 0
car_x += car_x_change
gameDisplay.fill(white)
# blocks((block_x,block_y,[block_width,block_height,black))
blocks(block_x, block_y, block_width, block_height, black)
block_y += block_speed
gameDisplay.blit(carImg, (car_x,car_y))
if car_x >= window_width:
gameExit = True
crash()
if car_x <= 0:
gameExit = True
crash()
if car_y > window_height:
block_y = 0 - block_height
block_x = random.randrange(0,window_width-block_width)
pygame.display.update()
clock.tick(30)
gameLoop()
pygame.quit
quit()
One pair block_x, block_y can't be use to draw many blocks.
You have to create list with pairs (x,y) for all blocks which you want to draw. You have to use for loops to create blocks (pairs (x,y)), to move them, and to draw them.
BTW: running gameloop() inside crash() create recursion which is not prefered method.
My version with more information in comments # changed
import pygame
import random
# changed: better organized code
# --- constants --- (UPPERCASE_NAMES)
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
WINDOW_WIDTH = 800
WINDOW_HEIGHT = 600
# --- functions --- (lowercase_names)
def blocks(points, width, height, color):
# changed: use `for` to draw all blocks
for x, y in points:
pygame.draw.rect(display, color, [x, y, width, height])
def crash():
print("YOUR GARBAGE! Press C to play again or Q to quit.")
# changed: return `True/False` insted of executing gameloop()
# because it was not good idea
while True:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_q:
return True # True = quit
if event.key == pygame.K_c:
print("User has decided to play again")
return False # false = continue
def gameloop():
# --- objects ---
car_image = pygame.image.load("racecar.png")
# Defining variables to draw and move car
car_x = 350
car_y = 400
car_x_change = 0
car_w = 100
car_h = 100
# BTW: you could use `pygame.Rect` to keep position and size
# car_rect = car_image.get_rect(x=350, y=450)
# Defining variables to draw blocks
block_speed = 7
block_width = 100
block_height = 100
# changed: create list with points x,y
pairs = []
for _ in range(10):
x = random.randrange(0, WINDOW_WIDTH)
y = -block_height
pairs.append( (x, y) )
# --- mainloop ---
clock = pygame.time.Clock()
gameExit = False
while not gameExit:
# --- events ---
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
car_x_change -= 5
elif event.key == pygame.K_RIGHT:
car_x_change += 5
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT:
car_x_change += 5 # changed: wrong variable, use +=
elif event.key == pygame.K_RIGHT:
car_x_change -= 5 # changed: wrong variable, use -=
# --- updates ---
# changed: all moves before draws
# move car
car_x += car_x_change
# changed: one `if` for both crashes (`car_x`)
if car_x < 0 or car_x >= WINDOW_WIDTH:
# changed: use value from crash to set gameExit
# and to move car to start position
gameExit = crash()
if not gameExit:
car_x = 350
car_y = 400
# changed: use `for` to move all points
# and to check if they need new random place
# move blocks
moved_pairs = []
for x, y in pairs:
y += block_speed
if y > WINDOW_HEIGHT:
y = -block_height
x = random.randrange(0, WINDOW_WIDTH - block_width)
moved_pairs.append( (x, y) )
pairs = moved_pairs
# --- draws ---
# changed: all draws after moves
display.fill(WHITE)
blocks(pairs, block_width, block_height, BLACK)
display.blit(car_image, (car_x, car_y))
pygame.display.update()
# --- FPS ---
clock.tick(30)
# --- main ---
pygame.init()
display = pygame.display.set_mode((WINDOW_WIDTH, WINDOW_HEIGHT))
pygame.display.set_caption('MyFirstGame')
gameloop()
pygame.quit() # changed: forgot ()
I'm working on the basics of a game right now, but for some reason I cannot get my sprite to move. I know that it's registering when I'm pressing the key down, but the sprite for some reason just stays still.
import pygame
import sys
from pygame.locals import *
import time
pygame.init()
black = (0, 0, 0)
white = (255, 255, 255)
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("RADICAL")
screen.fill(black)
imga = pygame.image.load('coina.png')
imgb = pygame.image.load('coinb.png')
sound = pygame.mixer.Sound('coin.mp3')
FPS = 80
imgx = 10
imgy = 10
pixMove = 10
steps = 0
x1 = 0
y1 = 0
keystate = pygame.key.get_pressed()
GameOver = False
while not GameOver:
screen.fill(white)
points = (steps)
font = pygame.font.SysFont(None, 30)
text = font.render('Score: '+str(points), True, black)
screen.blit(text, (0,0))
if steps % 2 == 0:
screen.blit(imga, (imgx, imgy))
else:
screen.blit(imgb, (imgx, imgy))
for event in pygame.event.get():
print event
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.KEYDOWN:
if keystate[pygame.K_UP]:
y1 -= pixMove
elif keystate[pygame.K_DOWN]:
y1 += pixMove
elif keystate[pygame.K_LEFT]:
x1 -= pixMove
elif keystate[pygame.K_RIGHT]:
x1 += pixMove
elif event.type == pygame.KEYUP:
if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT:
x1 = 0
if event.key == pygame.K_UP or event.key == pygame.K_DOWN:
y1 = 0
steps +=1
if event.type == K_SPACE:
sound.play()
time.sleep(1)
sound.stop()
pygame.display.update()
fpsTime.tick(FPS)
Generally you blit() images on to the screen (pygame.display.set_mode()), for the changes to to reflect on the screen we call pygame.display.update(), In your case the game never comes the statement, which is out of while loop.