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
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()
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:
I have my flask file and a seperate file which contains a pygame. Both work seperately, How would i combine the flask so that when i press my link on my webpage it starts running the external file, how would I call it?
from flask import Flask, render_template
import going
app = Flask(__name__)
#app.route('/')
def index():
return render_template('index.html')
#app.route('/my-link/')
def my_link():
return going.main()
if __name__ == '__main__':
app.run(debug=True)
At the moment I am trying to run the main() method to initialize the program.
import pygame
##1100 * 800
size = [1100, 800]
score1 = 0
score2 = 0
blue = (100, 149, 237)
black = (0, 0, 0)
brown = (165,42,42)
white = (255, 255, 255)
green =(0,100,0)
red = (255,0,0)
dark_red = (200,0,0)
grey = (100,100,100)
other_grey = (0,0,100)
background = 'Mahogany.jpg'
pass_count = 0
player = 1
clock = pygame.time.Clock()
class Player(object):
def ___init__(self,id):
self.id = 1
def quitGame(self):
pygame.quit()
quit()
def pass_turn(self):
global pass_count
pass_count += 1
if pass_count == 2:
quitGame()
def score(player_text, score):
return player_text + str(score)
class Stone(object):
def __init__(self,board,position,color):
self.board = board
self.position = position
self.color = color
self.placeStone()
def placeStone(self):
coords = (self.position[0] * 50, self.position[1] * 50)
pygame.draw.circle(self.board,self.color,coords,20,0)
pygame.display.update()
class Board(object):
def draw_board(self):
for i in range(12):
for j in range(12):
rect = pygame.Rect(55 + (50 * i), 100 + (50 * j), 50, 50)
pygame.draw.rect(background, blue, rect, 1)
screen.blit(background, (0,0))
pygame.display.update()
def text_objects(self,text, font):
textSurface = font.render(text, True, black)
return textSurface, textSurface.get_rect()
def button(self,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(screen, ac,(x,y,w,h))
if click[0] == 1 and action != None:
action()
else:
pygame.draw.rect(screen, ic,(x,y,w,h))
smallText = pygame.font.Font("freesansbold.ttf",20)
textSurf, textRect = self.text_objects(msg, smallText)
textRect.center = ( (x+(w/2)), (y+(h/2)) )
screen.blit(textSurf, textRect)
def game_intro(self):
intro = True
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
screen.blit(background, (0,0))
largeText = pygame.font.SysFont("comicsansms",60)
TextSurf, TextRect = self.text_objects("GONLINE", largeText)
TextRect.center = ((1100/2),(800/2))
screen.blit(TextSurf, TextRect)
self.button("Play!",200,500,100,100,grey,other_grey,self.play_game)
self.button("Quit!",700,500,100,100,red,dark_red,Player.quitGame)
pygame.display.update()
clock.tick(15)
def play_game(self):
width = 20
height = 20
space_between = 5
global player
finish = False
self.draw_board()
while not finish:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finish = True
elif event.type == pygame.MOUSEBUTTONDOWN and player == 1:
position = pygame.mouse.get_pos()
if (event.button == 1) and (position[0] > 55 and position[0] < 710) and (position[1] > 100 and position[1] < 750):
x = int(round(((position[0]) / 50.0), 0))
y = int(round(((position[1]) / 50.0), 0))
Stone(screen,(x,y),white)
player = 2
elif event.type == pygame.MOUSEBUTTONDOWN and player == 2:
position = pygame.mouse.get_pos()
if (event.button == 1) and(position[0] > 55 and position[0] < 710) and (position[1] > 100 and position[1] < 750):
x = int(round(((position[0]) / 50.0), 0))
y = int(round(((position[1] ) / 50.0), 0))
Stone(screen,(x,y),black)
player = 1
clock.tick(60)
self.button("Pass!",750,200,100,100,grey,other_grey,Player.pass_turn)
self.button("Quit!",950,200,100,100,red,dark_red,Player.quitGame)
self.button(score("Player 1: ", score1),750,400,300,110,white,white)
self.button(score("Player 2: ",score2),750,600,300,110,white, white)
pygame.display.update()
pygame.quit()
def main():
player = Player()
board = Board()
board.game_intro()
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
main()
Here is the main game file
It seems that the two ways you try to call your game are slightly different.
The successful way, which seems to be something like
$ python going.py
runs this code
if __name__ == "__main__":
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
main()
The flask route, when triggered runs this
return going.main()
You're missing some setup. My guess is that the bottom of your going.py should look like this.
def main():
pygame.init()
screen = pygame.display.set_mode(size, 0, 32)
pygame.display.set_caption("Go_Online")
background = pygame.image.load(background).convert()
player = Player()
board = Board()
board.game_intro()
if __name__ == '__main__':
main()
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()
When trying to convert my .py script to .exe file using pyinstaller I got an error: TypeError
a bytes-like object is required not 'str'
I made a simple snake game using pygame and I'd like to convert it into .exe file.
Here is the code:
import pygame
import random
pygame.init()
black = (0, 0, 0)
red = (255, 0, 0)
green = (164, 199, 141)
blue = (0, 0, 255)
smallfont = pygame.font.SysFont(None, 25)
medfont = pygame.font.SysFont(None, 50)
largefont = pygame.font.SysFont(None, 80)
scorefont = pygame.font.SysFont(None, 30)
pygame.display.set_caption("Wąż v1.0")
clock = pygame.time.Clock()
snake_size = 10
food_size = 10
class window:
display_width = 800
display_height = 600
FPS = 15
gameDisplay = pygame.display.set_mode((window.display_width, window.display_height))
def scoreMessage(score):
text = scorefont.render("Wynik: " + str(score), True, black)
gameDisplay.blit(text, [16, 6])
def levelMessage(level):
text = scorefont.render("Poziom: " + str(level), True, black)
gameDisplay.blit(text, [116, 6])
def intro():
intro = True
cursor = 2
with open('wynik', 'r') as f:
wynik = sorted(map(int, f.readline().split(',')))
print(wynik)
while intro:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
cursor = 0
if event.key == pygame.K_DOWN:
cursor = 1
if event.key == pygame.K_RETURN and cursor == 0:
gameLoop()
if event.key == pygame.K_RETURN and cursor == 1:
pygame.quit()
quit()
if cursor == 0:
message_to_screen("Zakończ", green, 80)
message_to_screen("Zakończ", black, 80)
message_to_screen("Graj", green, 40)
message_to_screen("Graj", blue, 40)
pygame.display.update()
if cursor == 1:
message_to_screen("Graj", green, 40)
message_to_screen("Graj", black, 40)
message_to_screen("Zakończ", green, 80)
message_to_screen("Zakończ", blue, 80)
pygame.display.update()
if cursor == 2:
gameDisplay.fill(green)
message_to_screen("Wąż", red, -200, "large")
message_to_screen("Graj", black, 40)
message_to_screen("Zakończ", black, 80)
message_to_screen("Twoim celem jest zjedzenie jak największej ilości jabłek które losowo pojawiają sią na ekranie.", black, -120)
message_to_screen("Uważaj na ściany oraz swój ogon któy wydłuża się wraz ze zjedzeniem jabłka.", black, -90)
message_to_screen("Pamiętaj, że wraz z Twoim wynikiem zwiększa się prędkość węża.", black, -60)
message_to_screen("Do sterowania używaj strzałek.", black, -30)
message_to_screen("Najlepszy wynik: " + str(wynik[-1]), red, 0)
message_to_screen("_______________________________________________________________________", black, 10)
pygame.display.update()
clock.tick(15)
def outro():
game_over = True
cursor2 = 2
with open('wynik', 'r') as f:
wynik = sorted(map(int, f.readline().split(',')))
print(wynik)
while game_over:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
quit()
gameDisplay.fill(green)
if str(score) > str(wynik[-1]):
message_to_screen("Gratulacje, uzyskałeś najlepszy wynik!", red, -50, "medium")
message_to_screen("Koniec gry!", red, -100, "large")
message_to_screen("Zagraj ponownie", black, 10)
message_to_screen("Zakończ", black, 50)
pygame.display.update()
clock.tick(100)
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
cursor2 = 0
if event.key == pygame.K_DOWN:
cursor2 = 1
if event.key == pygame.K_RETURN and cursor2 == 0:
gameLoop()
if event.key == pygame.K_RETURN and cursor2 == 1:
pygame.quit()
quit()
if cursor2 == 0:
message_to_screen("Zakończ", green, 50)
message_to_screen("Zakończ", black, 50)
message_to_screen("Zagraj ponownie", green, 10)
message_to_screen("Zagraj ponownie", blue, 10)
pygame.display.update()
if cursor2 == 1:
message_to_screen("Zagraj ponownie", green, 10)
message_to_screen("Zagraj ponownie", black, 10)
message_to_screen("Zakończ", green, 50)
message_to_screen("Zakończ", blue, 50)
pygame.display.update()
def snake(snake_size, snakeList):
for XY in snakeList:
pygame.draw.rect(gameDisplay, black, [XY[0], XY[1], snake_size, snake_size])
def text_objects(text, color, size):
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="small"):
textSurf, textRect = text_objects(msg, color, size)
textRect.center = (window.display_width / 2), (window.display_height / 2) + y_displace
gameDisplay.blit(textSurf, textRect)
def gameLoop():
gameExit = False
gameOver = False
x = window.display_width / 2
y = window.display_height / 2
x_change = 0
y_change = 0
global score
score = 0
level = 0
snakeList = []
snakeLength = 1
randAppleX = round(random.randrange(15, window.display_width - food_size - 10) / 10.0) * 10.0
randAppleY = round(random.randrange(30, window.display_height - food_size - 10) / 10.0) * 10.0
while not gameExit:
if gameOver == True:
outro()
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 = -snake_size
y_change = 0
elif event.key == pygame.K_RIGHT:
x_change = snake_size
y_change = 0
elif event.key == pygame.K_UP:
y_change = -snake_size
x_change = 0
elif event.key == pygame.K_DOWN:
y_change = snake_size
x_change = 0
x += x_change
y += y_change
gameDisplay.fill(green)
pygame.draw.rect(gameDisplay, black, [0, 0, 10, 600])
pygame.draw.rect(gameDisplay, black, [10, 0, 780, 30])
pygame.draw.rect(gameDisplay, green, [10, 5, 780, 20])
pygame.draw.rect(gameDisplay, black, [790, 0, 10, 600])
pygame.draw.rect(gameDisplay, black, [10, 590, 780, 10])
scoreMessage(score)
levelMessage(level)
if x > window.display_width - 10:
gameOver = True
wynik = open('wynik', 'a')
wynik.write(',' + str(score))
elif x < 10:
gameOver = True
wynik = open('wynik', 'a')
wynik.write(',' + str(score))
elif y > window.display_height - 10:
gameOver = True
wynik = open('wynik', 'a')
wynik.write(',' + str(score))
elif y < 30:
gameOver = True
wynik = open('wynik', 'a')
wynik.write(',' + str(score))
pygame.draw.rect(gameDisplay, red, [randAppleX, randAppleY, food_size, food_size])
snakeHead = []
snakeHead.append(x)
snakeHead.append(y)
snakeList.append(snakeHead)
if len(snakeList) > snakeLength:
del snakeList[0]
for eachSegment in snakeList[:-1]:
if eachSegment == snakeHead:
gameOver = True
snake(snake_size, snakeList)
pygame.display.update()
if x == randAppleX and y == randAppleY:
randAppleX = round(random.randrange(15, window.display_width - food_size - 10) / 10.0) * 10.0
randAppleY = round(random.randrange(30, window.display_height - food_size - 10) / 10.0) * 10.0
snakeLength += 1
score += 1
if score <= 4:
clock.tick(window.FPS)
level = 1
if score > 4 and score <= 9:
clock.tick(20)
level = 2
if score > 9:
clock.tick(25)
level = 3
pygame.quit()
quit()
intro()
gameLoop()
outro()
Thanks in advance