as part of my Pygame learning course I have to create simple helicopter game, similar to flappy bird.
It also should have a score count - so everytime you pass gap between blocks with helicopter the score should add 1.
Game logic and everything else works fine, except everytime helicopter pases thru the blocks the score is not added, so all the time score shows 0.
Below is the code, can anyone please help
import pygame
import time
from random import randint
black = (0,0,0)
white = (255,255,255)
pygame.init()
surfaceWidth = 1280
surfaceHeight = 720
imageHeight = 30
imageWidth = 60
surface = pygame.display.set_mode((surfaceWidth,surfaceHeight))
pygame.display.set_caption('EVGENY GAME')
#clock = frames per second
clock = pygame.time.Clock()
img = pygame.image.load('Helicopter.jpg')
def score(count):
font = pygame.font.Font('freesansbold.ttf', 20)
text = font.render("Score: "+str(count), True, white)
surface.blit(text, [0,0])
def blocks(x_block, y_block, block_width, block_height, gap):
pygame.draw.rect(surface, white, [x_block, y_block, block_width, block_height])
pygame.draw.rect(surface, white, [x_block, y_block+block_height+gap, block_width, surfaceHeight])
def replay_or_quit():
for event in pygame.event.get([pygame.KEYDOWN, pygame.KEYUP, pygame.QUIT]):
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
continue
return event.key
return None
def makeTextObjs(text, font):
textSurface = font.render(text, True, white)
return textSurface, textSurface.get_rect()
def msgSurface(text):
smallText = pygame.font.Font('freesansbold.ttf', 20)
largeText = pygame.font.Font('freesansbold.ttf', 150)
titleTextSurf, titleTextRect = makeTextObjs(text, largeText)
titleTextRect.center = surfaceWidth / 2, surfaceHeight / 2
surface.blit(titleTextSurf, titleTextRect)
typTextSurf, typTextRect = makeTextObjs('Press any key to continue', smallText)
typTextRect.center = surfaceWidth / 2, ((surfaceHeight / 2) + 100)
surface.blit(typTextSurf, typTextRect)
pygame.display.update()
time.sleep(1)
while replay_or_quit() == None:
clock.tick()
main()
def gameover():
msgSurface('GAME OVER')
def helicopter(x, y, image):
surface.blit(img, (x,y,))
# first constance = game over, while not true we are playing game
def main():
x = 50
y = 100
y_move = 0
x_block = surfaceWidth
y_block = 0
block_width = 100
block_height = randint(0, surfaceHeight/2)
gap = imageHeight * 8
block_move = 3
current_score = 0
game_over = False
while not game_over:#this will keep running until it hits pygame.quit
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
y_move = -10
if event.type == pygame.KEYUP:
if event.key == pygame.K_UP:
y_move = 5
y += y_move
surface.fill(black)
helicopter(x,y,img)
score(current_score)
blocks(x_block, y_block, block_width, block_height, gap)
x_block -= block_move
if y > surfaceHeight-40 or y < 0:
gameover()
if x_block < (-1*block_width):
x_block = surfaceWidth
block_height = randint(0, surfaceHeight/2)
if x + imageWidth > x_block:
if x < x_block + block_width:
if y < block_height:
if x - imageWidth < block_width + x_block:
gameover()
if x + imageWidth > x_block:
if y + imageHeight > block_height+gap:
gameover()
if x < x_block and x > x_block-block_move:
current_score += 1
pygame.display.update()#update, updates specific area on display, flip - updates whole display
clock.tick(100)#100 frames per second
main()
pygame.quit()
quit() enter code here
Your score counter never updates because your score counter condition is never reached. Change
if x < x_block and x > x_block-block_move:
to
if x_block >= x > x_block-block_move:
Related
This question already has an answer here:
How do I get the snake to grow and chain the movement of the snake's body?
(1 answer)
Closed 1 year ago.
I'm new to python and only now the basics, I'm trying to make a snake game but I can't seem to figure out how to make my snake grow 1 extra square each time it eats an apple. My reasoning is that I keep a list of all the old positions but only show the last one on the screen, and each time the snakes eats another apple it shows 1 extra old positions making the snake 1 square longer.
This is my code:
import pygame
from random import randint
WIDTH = 400
HEIGHT = 300
dis = pygame.display.set_mode((WIDTH,HEIGHT))
white = (255,255,255)
BACKGROUND = white
blue = [0,0,255]
red = [255,0,0]
class Snake:
def __init__(self):
self.image = pygame.image.load("snake.bmp")
self.rect = self.image.get_rect()
self.position = (10,10)
self.direction = [0,0]
self.positionslist = [self.position]
self.length = 1
pygame.display.set_caption('Snake ')
def draw_snake(self,screen):
screen.blit(self.image, self.position)
def update(self):
self.position = (self.position[0] + self.direction[0],self.position[1] + self.direction[1])
self.rect = (self.position[0],self.position[1],5, 5 )
self.positionslist.append(self.position)
if self.position[0]< 0 :
self.position = (WIDTH,self.position[1])
elif self.position[0] > WIDTH:
self.position = (0,self.position[1])
elif self.position[1] > HEIGHT:
self.position = (self.position[0],0)
elif self.position[1] < 0 :
self.position = (self.position[0],HEIGHT)
class Food:
def __init__(self):
self.image = pygame.image.load("appel.png")
self.rect = self.image.get_rect()
apple_width = -self.image.get_width()
apple_height = -self.image.get_height()
self.position = (randint(0,WIDTH+apple_width-50),randint(0,HEIGHT+apple_height-50))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
def draw_appel(self,screen):
screen.blit(self.image, self.position)
def eat_appel (self, snake):
if self.rect.colliderect(snake.rect) == True:
self.position = (randint(0,WIDTH),randint(0,HEIGHT))
self.rect.x = self.position[0]
self.rect.y = self.position[1]
snake.length += 1
def main():
game_over = False
while not game_over:
pygame.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()
snake = Snake()
food = Food()
while True:
screen.fill(BACKGROUND)
font = pygame.font.Font('freesansbold.ttf', 12)
text = font.render(str(snake.length), True, red, white)
textRect = text.get_rect()
textRect.center = (387, 292)
screen.blit(text,textRect)
snake.update()
#snake.update_list()
snake.draw_snake(screen)
food.draw_appel(screen)
food.eat_appel(snake)
pygame.display.flip()
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
snake.direction = [0,1]
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_RIGHT:
snake.direction = [1,0]
if event.key == pygame.K_LEFT:
snake.direction = [-1,0]
if event.key == pygame.K_UP:
snake.direction = [0,-1]
if event.key == pygame.K_DOWN:
snake.direction = [0,1]
if __name__ == "__main__":
main()
This can have multiple reasons. Firstly, I saw you tried to increase the length of the snake by typing snake.length += 1, which may work (probably won't because the module pygame allows the snake to hover around, but not like the loop or conditional statements). One of my tips would be, to increase the length of the snake by using the idea of adding the score with your present snake.length every time (because once your score is 1 by eating an apple, your snake.length would be 2. And it increases with the score). This is my code (a few modifications might be needed):
import pygame
import time
import random
pygame.init()
white = (255, 255, 255)
black = (0, 0, 0)
red = (255, 0, 0)
orange = (255, 165, 0)
width, height = 600, 400
game_display = pygame.display.set_mode((width, height))
pygame.display.set_caption("Snake Mania")
clock = pygame.time.Clock()
snake_size = 10
snake_speed = 15
message_font = pygame.font.SysFont('ubuntu', 30)
score_font = pygame.font.SysFont('ubuntu', 25)
def print_score(score):
text = score_font.render("Score: " + str(score), True, orange)
game_display.blit(text, [0,0])
def draw_snake(snake_size, snake_pixels):
for pixel in snake_pixels:
pygame.draw.rect(game_display, white, [pixel[0], pixel[1], snake_size, snake_size])
def run_game():
game_over = False
game_close = False
x = width / 2
y = height / 2
x_speed = 0
y_speed = 0
snake_pixels = []
snake_length = 1
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
while not game_over:
while game_close:
game_display.fill(black)
game_over_message = message_font.render("Game Over!", True, red)
game_display.blit(game_over_message, [width / 3, height / 3])
print_score(snake_length - 1)
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_1:
game_over = True
game_close = False
if event.key == pygame.K_2:
run_game()
if event.type == pygame.QUIT:
game_over = True
game_close = False
for event in pygame.event.get():
if event.type == pygame.QUIT:
game_over = True
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_speed = -snake_size
y_speed = 0
if event.key == pygame.K_RIGHT:
x_speed = snake_size
y_speed = 0
if event.key == pygame.K_UP:
x_speed = 0
y_speed = -snake_size
if event.key == pygame.K_DOWN:
x_speed = 0
y_speed = snake_size
if x >= width or x < 0 or y >= height or y < 0:
game_close = True
x += x_speed
y += y_speed
game_display.fill(black)
pygame.draw.rect(game_display, orange, [target_x, target_y, snake_size, snake_size])
snake_pixels.append([x, y])
if len(snake_pixels) > snake_length:
del snake_pixels[0]
for pixel in snake_pixels[:-1]:
if pixel == [x, y]:
game_close = True
draw_snake(snake_size, snake_pixels)
print_score(snake_length - 1)
pygame.display.update()
if x == target_x and y == target_y:
target_x = round(random.randrange(0, width - snake_size) / 10.0) * 10.0
target_y = round(random.randrange(0, height - snake_size) / 10.0) * 10.0
snake_length += 1
clock.tick(snake_speed)
pygame.quit()
quit()
run_game()
This question already has an answer here:
How to detect collisions between two rectangular objects or images in pygame
(1 answer)
Closed 2 years ago.
In this game I am creating one image is controlled by the players using arrows (racecar) and two images (banana) which move in a defined direction and speed (which is slowed down for now so I could see better what was happening) but their starting point is random. The goal would be for the car to avoid these blocks and to reach the finish line, only when going forward it is then impossible to pass these bananas without the crash segment to start even when there is clearly no contact. It is quit tricky because things move on the X axis. please help me.
Here is the code segment for collision between the two images:
if x + car_width >= banX:
print('ycollision')
if y + car_width >= banX and y + car_width <= banX + ban_height or ybottom + car_width >= banX and ybottom + car_width <= banX + ban_height:
print('xcollision')
crash()
Here is the whole code:
import pygame
import random
import time
pygame.init()
#Colors
black = (0,0,0)
white = (255,255,255)
grey = (96,96,96)
red = (255,0,0)
green = (0,255,0)
blue = (0,0,255)
#Setting and variables
display_width = 1570
display_height = 450
car_width = 98
car_height = 66
clock = pygame.time.Clock()
wn = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption('My own game')
#racecar
carImg = pygame.image.load('myOwnRGame.png')
Xchange = 0
Ychange = 0
y = 192
x = 10
def car(x,y):
wn.blit(carImg, (x,y))
#finish line
finish_line = pygame.image.load('myOwnFinishreal.png')
Xfin = 1480
Yfin = 0
def finish():
wn.blit(finish_line, (Xfin, Yfin))
#Crashing and wining
def textObjects(text, font):
textSurface = font.render(text, True, red)
return textSurface, textSurface.get_rect()
def displayMessage(text):
textFont1 = pygame.font.Font('freesansbold.ttf', 32)
textSurf, textRect = textObjects(text, textFont1)
textRect.center = ((display_width/2),(display_height/2))
while True:
wn.blit(textSurf, textRect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.display.quit()
pygame.quit()
if event.key == pygame.K_SPACE:
gameLoop()
pygame.display.update()
def crash():
displayMessage('You crashed!Press X to quit, _SPACE_ to restart!')
def win():
displayMessage('Bravo! You are the best car runner! Press X to quit and _SPACE_ to restart.')
#Banana widht48 height26
banImg = pygame.image.load('myOwnBanana.png')
ban_width = 48
ban_height = 26
def banana(banX, banY):
wn.blit(banImg, (banX, banY))
def banana2(banX, banY2):
wn.blit(banImg, (banX, banY2))
#Game loop
def gameLoop():
y = 192
x = 10
Xchange = 0
Ychange = 0
banX = 1600
banY = random.randrange(-5, (display_height - 21))
banY2 = random.randrange(-5, (display_height - 21))
ban_change = -3
alive = True
losing = True
while alive and losing:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.display.quit()
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_x:
pygame.display.quit()
pygame.quit()
if event.key == pygame.K_UP:
Xchange = 0
Ychange = 0
Xchange = 2.5
elif event.key == pygame.K_LEFT:
Xchange = 0
Ychange = 0
Ychange = -3
elif event.key == pygame.K_RIGHT:
Xchange = 0
Ychange = 0
Ychange = 3
elif event.key == pygame.K_DOWN:
Xchange = 0
Ychange = 0
Xchange = -3
#Borders
if y <= -15 or y >= display_height - 15:
Xchange = 0
Ychange = 0
ban_change = 2.5
crash()
if x >= display_width:
Xchange = 0
Ychange = 0
ban_change = 2.5
win()
if x <= 0:
x = 10
#Banana spon
if banX <= 0:
banY = random.randrange(-5, (display_height - 21))
banY2 = random.randrange(-5, (display_height - 21))
banX = 1540
x += Xchange
y += Ychange
ybottom = y + car_height
#Banana collision
if x + car_width >= banX:
print('ycollision')
if y + car_width >= banX and y + car_width <= banX + ban_height or ybottom + car_width >= banX and ybottom + car_width <= banX + ban_height:
print('xcollision')
crash()
wn.fill(grey)
finish()
car(x, y)
banana(banX, banY)
banana2(banX, banY2)
banX += ban_change
pygame.display.update()
clock.tick(60)
pygame.display.quit()
pygame.quit()
gameLoop()
Question summary: How could I make the bananas and car collide but still be able to dodge the collision by moving the car?
I recommend to draw the objects before invoking crash, to show the actual position of the objects when crashing. Note the objects have been moved, but not redrawn before the crash
wn.fill(grey)
finish()
car(x, y)
banana(banX, banY)
banana2(banX, banY2)
if # collision test
crash()
To evaluate if to rectangles (x1, y1, w1, h1) and _(x2, y2, w2, h2) are intersecting, you a have to evaluate if the rectangles are overlapping in both dimensions:
collide = x1 < x2+w2 and x2 < x1+w1 and y1 < y2+h2 and y2 < y1+h1
For your code that ma look as follows:
if x < banX + ban_width and banX < x + car_width:
if y < banY + ban_height and banY < y + car_height:
crash()
Anyway I recommend to pygame.Rect and colliderect() for the collision test. Get the rectangles form the pygame.Surface objects carImg and banImg by get_rect(). FOr instance:
car_rect = carImg.get_rect(topleft = (x, y))
ban_rect = banImg.get_rect(topleft = (banX, banY))
ban2_rect = banImg.get_rect(topleft = (banX, banY2))
if car_rect.colliderect(ban_rect) or car_rect.colliderect(ban2_rect):
crash()
import pygame, time, random
pygame.init()
display_width = 800
display_height = 600
white = (255,255,255)
green = (0,255,0)
black = (0,0,0)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
boy = pygame.image.load("pig.png")
fence = pygame.image.load("fence.png")
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 text_objects(text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def crash():
message_display("Game Over")
def fence1(fencex, fencey, fencew, fenceh, color):
gameDisplay.blit(fence, (fencex, fencey, fencew, fenceh))
def collision():
pig_image = pygame.image.load("pig.png")
pig_rect = pig_image.get_rect()
fence_image = pygame.image.load("fence.png")
fence_rect = fence_image.get_rect()
if pig_rect.colliderect(fence_rect):
crash()
def game_loop():
fence_startx = 900
fence_starty = gameDisplay.get_height() * 0.8
fence_speed = 15
fence_width = 50
fence_height = 50
x = gameDisplay.get_width() * 0.1
y = gameDisplay.get_height() * 0.8
y_change = 0
on_ground = True
gravity = .9
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if on_ground:
y_change = -20
on_ground = False
y_change += gravity
y += y_change
if y >= 500:
y = 500
y_change = 0
on_ground = True
gameDisplay.fill(green)
gameDisplay.blit(boy, (x, y))
fence1(fence_startx, fence_starty, fence_width, fence_height, white)
fence_startx -= fence_speed
randomx = random.randint(1,3)
if fence_startx <= -50:
if randomx == 1:
fence_startx = 1000
if randomx == 2:
fence_startx = 800
if randomx == 3:
fence_startx = 1500
collision()
pygame.display.flip()
clock.tick(60)
game_loop()
pygame.quit()
quit()
For some reason when I run this code, it spams me "Game Over". Could someone please help me on this issue. I use a collision function in this code. Is using the pygame.rect code the best way to do collision in pygame? Everything works except for my collision in the game. I would greatly appreciate some help. Thanks.
In the collision function you create two rects but leave their coordinates at the default position (0, 0) so the rects overlap. You should add rects for the player and the fence in the main game_loop function, set their x and y (or the topleft) attributes to the desired coordinates and then update them every iteration of the while loop. To check if the rects collide, pass them to the collision function and do this:
def collision(boy_rect, fence_rect):
if boy_rect.colliderect(fence_rect):
# I'm just printing it to shorten the code example.
print('crash')
Here's a minimal, complete example:
import random
import pygame
pygame.init()
green = (0,255,0)
gameDisplay = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
boy = pygame.Surface((40, 60))
boy.fill((0, 40, 100))
fence = pygame.Surface((50, 50))
fence.fill((100, 60, 30))
def collision(boy_rect, fence_rect):
if boy_rect.colliderect(fence_rect):
# I'm just printing it to shorten the code example.
print('crash')
def game_loop():
fence_speed = 15
# Create a fence and a boy rect and set their x,y or topleft coordinates.
fence_rect = fence.get_rect()
fence_rect.x = 900
fence_rect.y = gameDisplay.get_height() * 0.8
x = gameDisplay.get_width() * 0.1
y = gameDisplay.get_height() * 0.8
boy_rect = boy.get_rect(topleft=(x, y))
y_change = 0
on_ground = True
gravity = .9
gameExit = False
while not gameExit:
for event in pygame.event.get():
if event.type == pygame.QUIT:
gameExit = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
if on_ground:
y_change = -20
on_ground = False
y_change += gravity
y += y_change
if y >= 500:
y = 500
y_change = 0
on_ground = True
boy_rect.y = y # Update the rect position.
gameDisplay.fill(green)
gameDisplay.blit(boy, boy_rect)
gameDisplay.blit(fence, fence_rect)
# Update the position of the fence rect.
fence_rect.x -= fence_speed
if fence_rect.x <= -50:
# You can use random.choice to pick one of these values.
fence_rect.x = random.choice((800, 1000, 1500))
# Pass the two rects and check if they collide.
collision(boy_rect, fence_rect)
pygame.display.flip()
clock.tick(60)
game_loop()
pygame.quit()
I've been learning Python the easy (for me) way: simple video game example tutorials from sentdex on youtube. The concepts which I had not already known are made much clearer in the context of something for which I see value like a simple game. Anyway, I have come to an issue; for some reason, I cannot get a menu page to blit. I originally followed the tutorial very closely, with an eye for punctuation, capitalization and proper indentation as I see that seems to be the n00bs most consistent pitfall. However, the tutorial did not work for that section, and the program goes right into the game loop, even when game over. I have tried other methods prescribed throughout here, google, and youtube, but nothing seems to be working! I get a non-descriptive "syntax error", but as far as I can tell, the vital bits are wired up right. I'm sure I'm just being a blind noob, but some simple analysis would be much appreciated on this code!
NOTE: I know I have some danglers like how I imported Pickle but haven't used it yet, those are all just reminders for the next steps, soon to be fleshed out as soon as this menu problem is resolved.
Running python (with pygame) 2.7, since I cant get pygame to work on python 3.
I have both Eric5 and pycharm, I am running Debian Jessie with a backported Cinnamon (And I believe the kernel to, but I might be wrong)
#!/urs/bin/python2.7
import random
import pygame
import time
##import pickle
pygame.init()
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width,display_height))
pygame.display.set_caption("Zoomin' Zigs")
#Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
#asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
menuactive = True
#FUNCTIONS
##def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
##def leftclick():
##
## if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
## mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades (smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
time.sleep(3)
menuscreen()
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
pygame.Rect(gamedisplay (x, y, w, h))
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/2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
if x+w > mousecoords[0] > x and y+h > mousecoords[1] >y:
pygame.quit()
quit()
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: "+str(count), True, blue)
gamedisplay.blit(text, (30,100))
################################MENU###################################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
else:
time.sleep(3)
game_loop()
gamedisplay.blit(menuimage (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP###############################################
def game_loop():
#CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
#SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
while not menuactive:
for event in pygame.event.get():
# GAME QUIT EVENT
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
#CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
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.blit(background, (0, 0))
smbarricades (smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
#OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice ((smbarStartXA, smbarStartXB))
#DODGE COUNT
dodged += 1
#CRASHESloop
if y <= smbar_starty+smbar_height and y >= smbar_starty+smbar_height and x <= smbar_startx+car_width and x >= smbar_startx-car_width:
crash()
menuactive = True
pygame.display.update()
clock.tick(60)
########################################################################################
menuscreen()
game_loop()
pygame.quit()
quit()
Hey I saw your code and did necessary changes And Its Working now next time kindly provide us the whole details.
#!/urs/bin/python2.7
import random
import pygame
import time
# import pickle
menuactive = True
display_width = 800
display_height = 600
gamedisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Zoomin' Zigs")
# Colors
black = (0, 0, 0)
white = (255, 255, 255)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
clock = pygame.time.Clock()
# asset variables
carImg = pygame.image.load('racecar.png')
car_width = 142
car_height = 100
background = pygame.image.load('road.png')
smbarricade = pygame.image.load('barricade_166x83.png')
menuimage = pygame.image.load('menu.png')
##lgbarricade = pygame.image.load()
# FUNCTIONS
# def blocks (blockx, blocky, blockw, blockh, color):
## pygame.draw.rect(gamewindow, color, [blockx, blocky, blockw, blockh, ])
# def leftclick():
##
# if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
# mpos = pygame.mouse.get_pos() and leftclick = True
##
def smbarricades(smbar_startx, smbar_starty):
gamedisplay.blit(smbarricade, (smbar_startx, smbar_starty))
def car(x, y):
gamedisplay.blit(carImg, (x, y))
def crash():
message_display('You Crashed')
pygame.display.update()
# menuscreen()
# def button(x, y, w, h,):
# mousecoords = pygame.mouse.get_pos()
# if x+w > mousecoords[0] > x and y+h . mousecoords[1] >y:
# pygame.Rect(gamedisplay (x, y, w, h))
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 / 2))
gamedisplay.blit(TextSurf, TextRect)
def button(x, y, w, h,):
mousecoords = pygame.mouse.get_pos()
if x + w > mousecoords[0] > x and y + h > mousecoords[1] > y:
# pygame.quit()
# quit()
global menuactive
menuactive = False
def dodge_count(count):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged: " + str(count), True, blue)
gamedisplay.blit(text, (30, 100))
################################MENU######################################
def menuscreen():
##mousecoords = pygame.mouse.get_pos()
##playbX = 6
##playbY = 107
##playbutton_rect = pygame.Rect(playbx, playby, 115, 40)
##exitbX = 634
##exitbY = 514
##exitbutton = pygame.Rect(exitbx, exitby, 120, 60)
## exitb_rect = pygame.Rect(exitbx, exitby, 120, 60)
global menuactive
while menuactive:
for event in pygame.event.get():
print event
if event.type == pygame.QUIT:
menuactive = False
else:
# time.sleep(3)
game_loop()
gamedisplay.blit(menuimage, (0, 0))
pygame.display.update()
clock.tick(15)
################################GAME#LOOP#################################
def game_loop():
# CAR attributes/variables
x = (display_width * 0.3725)
y = (display_height * 0.8)
x_change = 0
# SMBARRICADE attributes/variables
smbar_starty = -83
smbar_speed = 5
smbarStartXA = 147
smbarStartXB = 444
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
smbar_width = 166
smbar_height = 83
dodged = 0
global menuactive
while menuactive:
for event in pygame.event.get():
if event.type == pygame.QUIT:
# pygame.quit()
menuactive = False
# CAR CONTROL LOOP
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
x_change = -7
elif event.key == pygame.K_RIGHT:
x_change = 7
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.blit(background, (0, 0))
smbarricades(smbar_startx, smbar_starty)
smbar_starty += smbar_speed
car(x, y)
dodge_count(dodged)
# OBSTACLE RENEWAL
if smbar_starty > display_height:
smbar_starty = -83
smbar_startx = random.choice((smbarStartXA, smbarStartXB))
# DODGE COUNT
dodged += 1
# CRASHESloop
if y <= smbar_starty + smbar_height and y >= smbar_starty + smbar_height and x <= smbar_startx + car_width and x >= smbar_startx - car_width:
crash()
menuactive = False
pygame.display.update()
clock.tick(60)
##########################################################################
if __name__ == '__main__':
pygame.init()
menuscreen()
# game_loop()
pygame.quit()
quit()
A game that I have been working on recently stopped working after converting it to .msi or .exe with cx_freeze. The first version worked perfectly fine, but now when I try to open the application, it just doesn't work.
It displays no error codes either. All it does is display a black screen and close. My code can be found below:
SpaceDodge.py
"""
Game Developer: Austin H.
Game Owner: Austin H.
Licensed Through: theoiestinapps
Build: 2
Version: 1.0.1
"""
import os
import pygame as pygame
import random
import sys
import time
pygame.init()
pygame.mixer.init()
pygame.font.init()
left = False
right = False
playerDead = False
devMode = False
musicStopped = False
game_completed = False
game_level_score = (0)
game_display_score = (0)
deaths_this_session = (0)
user_teleport_active = False
user_health_active = False
user_health_inactive = False
user_teleport_display_active = ("False")
user_health_display_active = ("False")
display_width = 1280
display_height = 650
customOrange = (210, 121, 19)
customBlue = (17, 126, 194)
black = (0, 0, 0)
blue = (0, 0, 255)
green = (0, 225, 0)
red = (250, 0, 0)
white = (255, 255, 255)
bright_red = (255,0,0)
bright_green = (0,255,0)
gameDisplay = pygame.display.set_mode((display_width, display_height))
pygame.display.set_caption("Space Dodge")
clock = pygame.time.Clock()
backgroundMusic = pygame.mixer.music.load('C:/Program Files/Space Dodge/game_background_music.mp3')
enemyImg = pygame.image.load('C:/Program Files/Space Dodge/enemy_image.png')
enemytwoImg = pygame.image.load('C:/Program Files/Space Dodge/enemy_image_two.png')
backgroundImg = pygame.image.load('C:/Program Files/Space Dodge/background_image.png')
rocketImg = pygame.image.load('C:/Program Files/Space Dodge/player_image.png')
injuredSound = pygame.mixer.Sound('C:/Program Files/Space Dodge/player_hurt_sound.wav')
errorSound = pygame.mixer.Sound('C:/Program Files/Space Dodge/game_error_sound.wav')
#Player Powerups
def teleport_powerup(user_teleport_display_active):
font = pygame.font.SysFont(None, 25)
text = font.render("Teleport Powerup: " + str(user_teleport_display_active), True, red)
gameDisplay.blit(text, (display_width - 205, 5))
def ehealth_powerup(user_health_display_active):
font = pygame.font.SysFont(None, 25)
text = font.render("Ehealth Powerup: %s" % user_health_display_active, True, red)
gameDisplay.blit(text, (display_width - 205, 25))
#Game Stats
def enemies_dodged(enemy_objects_dodged):
font = pygame.font.SysFont(None, 25)
text = font.render("Dodged UIO: " + str(enemy_objects_dodged), True, green)
gameDisplay.blit(text, (5, 5))
def game_level(game_display_score):
font = pygame.font.SysFont(None, 25)
game_display_score = game_level_score + 1
text = font.render("Game Level: " + str(game_display_score), True, green)
gameDisplay.blit(text, (5, 25))
def session_deaths(deaths_this_session):
font = pygame.font.SysFont(None, 25)
text = font.render("Session Deaths: " + str(deaths_this_session), True, green)
gameDisplay.blit(text, (display_width - 150, 630))
def bot_speed(enemy_speed):
font = pygame.font.SysFont(None, 25)
text = font.render("Bot Speed: " + str(enemy_speed), True, green)
gameDisplay.blit(text, (5, 560))
def clock_speed(clockTick):
font = pygame.font.SysFont(None, 25)
text = font.render("Clock Tick: " + str(clockTick), True, green)
gameDisplay.blit(text, (5, 630))
def clock_speed_intro(clockTick):
font = pygame.font.SysFont(None, 25)
text = font.render("Clock Tick: " + str(clockTick), True, green)
gameDisplay.blit(text, (5, 630))
#Sprite Definitions
def enemies(enemyx, enemyy):
gameDisplay.blit(enemyImg, (enemy_startx, enemy_starty))
def enemies_two(enemy_twox, enemy_twoy):
gameDisplay.blit(enemytwoImg, (enemy_two_startx, enemy_two_starty))
def rocket(x, y):
gameDisplay.blit(rocketImg, (x, y))
def background(cen1, cen2):
gameDisplay.blit(backgroundImg, (cen1, cen2))
#Message Display
def text_objects(text, font):
textSurface = font.render(text, True, blue)
return textSurface, textSurface.get_rect()
def message_display(text):
global game_completed
largeText = pygame.font.SysFont(None, 70)
TextSurf, TextRect = text_objects(text, largeText)
TextRect.center = ((display_width / 2), (display_height / 2))
gameDisplay.blit(TextSurf, TextRect)
pygame.display.update()
if game_completed == True:
time.sleep(60)
game_intro()
else:
time.sleep(5)
if game_level_score > 0:
pass
else:
pygame.mixer.music.play()
game_loop()
#User Crash
def crash():
injuredSound.play()
message_display("You Died. Game Over!")
#Button Usage
def button(msg,x,y,w,h,ic,ac,action=None):
mouse = pygame.mouse.get_pos()
click = pygame.mouse.get_pressed()
if x+w > mouse[0] > x and y+h > mouse[1] > y:
pygame.draw.rect(gameDisplay, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(gameDisplay, ic,(x,y,w,h))
smallText = pygame.font.SysFont(None,20)
textSurf, textRect = text_objects(msg, smallText)
textRect.center = ((x+(w/2)), (y+(h/2)))
gameDisplay.blit(textSurf, textRect)
#Quit
def quitgame():
pygame.quit()
sys.exit()
#Game Intro
def game_intro():
global clockTick
global game_level_score
global user_teleport_active
global user_teleport_display_active
global user_health_active
global user_health_inactive
global user_health_display_active
global enemy_speed
global enemy_two_speed
global enemies_per_level
intro = True
cen1 = (0)
cen2 = (0)
enemy_speed = (random.randrange(5, 10))
enemy_two_speed = (random.randrange(5, 10))
enemies_per_level = (5)
game_level_score = (0)
user_teleport_active = False
user_teleport_display_active = ("False")
user_health_active = False
user_health_inactive = False
user_health_display_active = ("False")
while intro:
clockTick = clock.get_fps()
for event in pygame.event.get():
if event.type == pygame.QUIT:
quitgame()
gameDisplay.fill(white)
largeText = pygame.font.Font(None, 115)
TextSurf, TextRect = text_objects("Space Dodge", largeText)
TextRect.center = ((display_width / 2),(display_height / 2))
background(cen1, cen2)
clock_speed_intro(clockTick)
gameDisplay.blit(TextSurf, TextRect)
button("Start", display_width / 2.2, 370, 100, 50, green, bright_green, game_loop)
button("Quit", display_width / 2.2, 445, 100, 50, red, bright_red, quitgame)
pygame.display.update()
clock.tick(15)
#Game Loop
def game_loop():
global left
global right
global playerDead
global musicStopped
global game_level_score
global enemy_speed
global enemy_two_speed
global game_completed
global user_teleport_active
global user_teleport_display_active
global user_health_active
global user_health_display_active
global user_health_inactive
global deaths_this_session
global enemies_per_level
global enemy_startx
global enemy_starty
global enemy_two_startx
global enemy_two_starty
x = (display_width * 0.43)
y = (display_height * 0.74)
cen1 = (0)
cen2 = (0)
x_change = 0
rocket_width = (86)
game_score = (0)
enemy_objects_dodged = (0)
enemy_startx = random.randrange(0, display_width)
enemy_starty = -600
enemy_width = 75
enemy_height = 75
enemy_two_startx = random.randrange(0, display_width)
enemy_two_starty = -600
enemy_two_width = 125
enemy_two_height = 125
while not playerDead:
clockTick = clock.get_fps()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.mixer.music.stop()
quitgame()
if devMode == True:
print(event)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_a:
left = True
if event.key == pygame.K_d:
right = True
if event.key == pygame.K_LEFT:
left = True
if event.key == pygame.K_RIGHT:
right = True
if event.key == pygame.K_KP4:
left = True
if event.key == pygame.K_KP6:
right = True
if event.key == pygame.K_ESCAPE:
game_intro()
if event.key == pygame.K_SPACE:
pass
if event.key == pygame.K_m:
if musicStopped == False:
musicStopped = True
pygame.mixer.music.stop()
elif musicStopped == True:
musicStopped = False
pygame.mixer.music.play()
if event.type == pygame.KEYUP:
if event.key == pygame.K_a or pygame.K_d:
left = False
if event.key == pygame.K_d:
right = False
if event.key == pygame.K_LEFT:
left = False
if event.key == pygame.K_RIGHT:
right = False
if event.key == pygame.K_KP4:
left = False
if event.key == pygame.K_KP6:
right = False
if event.key == pygame.K_SPACE:
pass
if left and right:
x_change *= 1
elif left and x > -86:
x_change = -10
elif right and x < (display_width - 89):
x_change = 10
else:
x_change = 0
if game_level_score > 999:
quitgame()
if enemy_objects_dodged == enemies_per_level:
enemy_speed += 0.5
enemy_two_speed + 0.5
game_level_score += 1
enemies_per_level += 3
if game_level_score == 999:
game_completed = True
message_display('Game Complete! You Win! :D')
else:
message_display('You Completed Level: ' + str(game_level_score))
if user_health_inactive == False:
if game_level_score > 9:
user_health_active = True
user_health_display_active = ("True")
if game_level_score > 4:
user_teleport_active = True
user_teleport_display_active = ("True")
if user_teleport_active == True:
if x < -0:
x = 1330
if enemy_starty > display_height:
enemy_starty = 0 - enemy_height
enemy_startx = random.randrange(0, display_width)
game_score += 1
enemy_objects_dodged += 1
if enemy_two_starty > display_height:
enemy_two_starty = 0 - enemy_two_height
enemy_two_startx = random.randrange(0, display_width)
game_score += 1
enemy_objects_dodged += 1
if y < enemy_starty + enemy_height:
if x > enemy_startx and x < enemy_startx + enemy_width or x + rocket_width > enemy_startx and x + rocket_width < enemy_startx + enemy_width:
if user_health_active:
x = (display_width * 0.43)
y = (display_height * 0.74)
user_health_active = False
user_health_display_active = False
user_health_inactive = True
else:
pygame.mixer.music.stop()
deaths_this_session += 1
crash()
if y < enemy_two_starty + enemy_two_height:
if x > enemy_two_startx and x < enemy_two_startx + enemy_two_width or x + rocket_width > enemy_two_startx and x + rocket_width < enemy_two_startx + enemy_two_width:
if user_health_active:
x = (display_width * 0.43)
y = (display_height * 0.74)
user_health_active = False
user_health_display_active = False
user_health_inactive = True
else:
pygame.mixer.music.stop()
deaths_this_session += 1
crash()
x += x_change
background(cen1, cen2)
enemies(enemy_startx, enemy_starty)
enemies_two(enemy_two_startx, enemy_two_starty)
enemy_starty += enemy_speed
enemy_two_starty += enemy_two_speed
rocket(x, y)
enemies_dodged(enemy_objects_dodged)
game_level(game_display_score)
clock_speed(clockTick)
session_deaths(deaths_this_session)
teleport_powerup(user_teleport_display_active)
ehealth_powerup(user_health_display_active)
pygame.display.update()
clock.tick(90)
if __name__ == "__main__":
pygame.mixer.music.set_volume(0.20)
pygame.mixer.music.play(-1)
game_intro()
Setup.py
from cx_Freeze import *
import sys
base = None
if sys.platform == 'win32':
base = "Win32GUI"
setup(
name = "SpaceDodge",
author = "theoiestinapps",
options = {"build_exe": {"packages": ["pygame"], "include_files": ["game_background_music.mp3", "background_image.png", "enemy_image.png",
"player_image.png", "player_hurt_sound.wav", "game_error_sound.wav"]},
"bdist_msi": {"upgrade_code": "{9d3d322e74744a1282ce1ea2c5af2676}"}},
executables = [Executable("SpaceDodge.py", shortcutName = "SpaceDodge", shortcutDir = "DesktopFolder", base = base)]
)
N.B.: I have no experience with cx_Freeze, and neither with pygame so my answer is only a "feeling" of what might be fishy, and where I'd look first if I was actually debugging the code:
at many places in your code you're changing font size by using:
font = pygame.font.SysFont(None, 25)
As you give None as parameter for the font name, the documentation says:
If a suitable system font is not found this will fallback on loading the default pygame font.
when you're packing your app to make it a self contained .exe, it's likely that cx_Freeze is trying to get the "default" font, and assumes (wrongly) that it is
freesansbold.ttf that it couldn't find or put as a resource with the .exe. And then, it might refer to that font relatively to/within the .exe, without having it copied, making the code crash.
though, when you run it with the python interpreter, the font resolution is going through the system and works appropriately, as it is supposed to.
To validate my theory, you can remove/comment all references to font changes (making your code look likely to look ugly), try to .exe it again and see if it works. You can also printout:
pygame.font.get_default_font()
in both context and see if it's showing up the same file.
That's my two cents, hope it'll help