Python flask game not initializing - python

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()

Related

Pygame makes the game unplayable with lag

I am making a game where you just click on the circles, and i just got it working when i noticed the game really laggs out sometimes. It just would not generate new position. This is my code:
import pygame
from pygame.font import SysFont
from pygame.display import flip
from random import randint, choice
# Bools
r = True
title = True
game = False
# Floats
# Ints
points = 0
deletewhat = [True, False]
# Strings
# Lists
spots = []
pointchoice = [1,1,1,2]
# Colors
WHITE = (255,255,255)
BLACK = (0,0,0)
RED = (255,0,0)
YELLOW = (255,255,0)
GRAY = (20,20,20)
# Pygame init
pygame.init()
pygame.font.init()
# Pygame userevents
delete = pygame.USEREVENT
# Pygame timers
pygame.time.set_timer(delete, 1000)
# Pygame Fonts
titlefont = SysFont("Arial", 70)
headfont = SysFont("Arial", 20)
startfont = SysFont("Arial", 80)
pointsfont = SysFont("Arial", 25)
# Pygame font one-time render
titletext = titlefont.render("The Spot Spotter", False, BLACK)
headtext = headfont.render("Click the spots and earn points!", False, BLACK)
starttext = startfont.render("START", False, RED)
# Other Pygame things
screen = pygame.display.set_mode((900,750))
class Spot:
def __init__(self, x, y, points):
global WHITE, GRAY
self.x = x
self.y = y
self.points = points
if self.points == 1:
self.spotcolor = WHITE
else:
self.spotcolor = GRAY
def draw(self):
pygame.draw.ellipse(screen, self.spotcolor, (self.x, self.y, 50,50))
def get_pos(self):
return self.x, self.y
def get_points(self):
return self.points
spot = Spot
while r:
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == delete and game:
deleteone = choice(deletewhat)
if deleteone:
spot1 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot1ready = True
spot2 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot2ready = True
if event.type == pygame.MOUSEBUTTONDOWN:
mouse = pygame.mouse.get_pos()
if mouse[0] > 249 and mouse[0] < 801:
if mouse[1] > 299 and mouse[1] < 426:
if title:
title = False
game = True
try:
spot1.get_pos()
except NameError:
pass
else:
spot1pos = spot1.get_pos()
if mouse[0] > (spot1pos[0] - 1) and mouse[0] < (spot1pos[0] + 51):
if mouse[1] > (spot1pos[1] - 1) and mouse[1] < (spot1pos[1] + 51):
if spot1ready:
spot1ready = False
points += spot1.get_points()
try:
spot2.get_pos()
except NameError:
pass
else:
spot2pos = spot2.get_pos()
if mouse[0] > (spot2pos[0] - 1) and mouse[0] < (spot2pos[0] + 51):
if mouse[1] > (spot2pos[1] - 1) and mouse[1] < (spot2pos[1] + 51):
if spot2ready:
spot2ready = False
points += spot2.get_points()
if title:
screen.fill(WHITE)
screen.blit(titletext, (250, 0))
screen.blit(headtext, (350, 100))
pygame.draw.rect(screen, YELLOW, (200, 300, 550, 125)) # Start Button
screen.blit(starttext, (375, 315))
flip()
elif game:
pointstext = pointsfont.render(f"Points: {points}", False, BLACK)
screen.fill(BLACK)
pygame.draw.rect(screen, WHITE, (0, 600, 900, 150))
screen.blit(pointstext, (20, 610))
try:
spot1.draw()
except NameError:
pass
else:
spot1.draw()
try:
spot2.draw()
except NameError:
pass
else:
spot2.draw()
flip()
pygame.quit()
If you are wondering, the bools game and title are both for detecting which tab needs to be rendered. if game is true and title is false then the game knows hey, i need to render the game.
Also please note that i am not that good in pygame.
The problem is the line deleteone = choice(deletewhat). This may generate multiple False in a row.
Add a variable wait_delete. Decrement the variable when the delete event occurs. Set a new random value with randint if wait_delete is 0.
wait_delete = 1
spot = Spot
while r:
for event in pygame.event.get():
if event.type == pygame.QUIT:
r = False
if event.type == delete and game:
wait_delete -= 1
if wait_delete == 0:
wait_delete = randint(1, 3)
spot1 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot1ready = True
spot2 = spot(randint(20, 880), randint(20, 600), choice(pointchoice))
spot2ready = True
# [...]

Display Surface quit error when quitting

I made a pygame program what is working fine, but when I try to quit it, error occurs: pygame.error: display Surface quit, and show the code part: DS.blit(bg, (back_x - bg.get_rect().width, 0)). I use quit() command in my events and also at the end of the loop. Can't figure out where is the problem.
import pygame, os, random
pygame.init()
pygame.mixer.init()
W, H = 800,600
HW, HH = W/2,H/2
WHITE = (255,255,255)
PURPLE = (139,34,82)
FPS = 60
DS = pygame.display.set_mode((800, 600))
pygame.display.set_caption('Purpleman')
clock = pygame.time.Clock()
#Allalaadimised
bg = pygame.image.load(os.path.join('Pildid', 'Taust3.png'))
bg = pygame.transform.scale(bg, (2000, 600))
startscreen = pygame.image.load(os.path.join('Pildid', 'Start.png'))
startscreen = pygame.transform.scale(startscreen, (800, 600))
endscreen = pygame.image.load(os.path.join('Pildid', 'dead.png'))
endscreen = pygame.transform.scale(endscreen, (800, 600))
PLAYER_SHEET = pygame.image.load(os.path.join('Pildid', 'karakter.png')).convert_alpha()
menuu = pygame.mixer.Sound(os.path.join('Helid', 'Taust_laul.ogg'))
ohno = pygame.mixer.Sound(os.path.join('Helid', 'ohno.ogg'))
sad = pygame.mixer.Sound(os.path.join('Helid', 'sad.ogg'))
pygame.mixer.music.load(os.path.join('Helid', 'taustalaul.ogg'))
pygame.display.set_icon(bg)
# Sprite sheeti loikamine ja lisamine listi
PLAYER_IMAGES = []
width = PLAYER_SHEET.get_width() / 4
height = PLAYER_SHEET.get_height()
for x in range(4):
PLAYER_IMAGES.append(PLAYER_SHEET.subsurface(x*width, 0, width, height))
class Player(pygame.sprite.Sprite):
'''Mangija'''
def __init__(self, x, y, py):
super(Player,self).__init__()
self.x = x
self.y = y
self.jumping = False
self.platform_y = py
self.velocity_index = 0
self.velocity = list([(i/ 1.5)-25 for i in range (0,60)]) #huppe ulatus ja kiirus
self.frame_index = 0
self.image = PLAYER_IMAGES[self.frame_index] #kaadri valimine
self.rect = self.image.get_rect()
self.mask = pygame.mask.from_surface(self.image) #hitbox
def do_jump(self):
'''Huppemehaanika'''
if self.jumping:
self.y += self.velocity[self.velocity_index]
self.velocity_index += 2
if self.velocity_index >= len(self.velocity) - 1: #huppe aeglustus (nagu gravitatsioon)
self.velocity_index = len(self.velocity) - 1
if self.y > self.platform_y: #platvormi tagades ei huppa
self.y = self.platform_y
self.jumping = False
self.velocity_index = 0
def update(self):
'''Kaadrite vahetus ja huppamine'''
self.rect.center = self.x, self.y
self.do_jump()
# Animatsiooni kaadri uuendamine.
self.frame_index += 1
self.frame_index %= len(PLAYER_IMAGES) * 7
# Pildi vahetamine.
self.image = PLAYER_IMAGES[self.frame_index//7]
def keys(player):
'''Mangija inputi saamine'''
keys = pygame.key.get_pressed()
if keys[pygame.K_SPACE] or keys[pygame.K_UP] and player.jumping == False:
player.jumping = True
class Obstacle(pygame.sprite.Sprite):
'''Mangu takistused'''
def __init__(self, x, y):
super(Obstacle,self).__init__()
self.image = pygame.image.load(os.path.join('Pildid', 'kivi.png')).convert_alpha()
self.image = pygame.transform.scale(self.image, (90,90))
self.rect = self.image.get_rect(center=(x, y))
self.x = x
self.y = y
self.mask = pygame.mask.from_surface(self.image)
def update(self):
'''Takistuse kustutamine'''
if self.x < -64:
self.kill()
self.x += speed
self.rect.center = self.x, self.y
class Scoring():
'''Punktide lugemine ja menuud'''
def __init__(self):
with open('highscore.txt', 'w') as f: #high score salvestamine
try:
self.highscore = int(f.read())
except:
self.highscore = 0
def score(self,points):
self.font = pygame.font.Font('freesansbold.ttf',30)
self.text = self.font.render('Score: ' + str(points) , True, PURPLE)
DS.blit(self.text, (0,0))
def text_objects(self,text, font):
self.textSurface = font.render(text, True, PURPLE)
return self.textSurface, self.textSurface.get_rect()
def message_display(self,text):
self.largeText = pygame.font.Font('freesansbold.ttf',60)
self.TextSurf, self.TextRect = self.text_objects(text, self.largeText)
self.TextRect.center = ((W/2),(H/4))
DS.blit(self.TextSurf, self.TextRect)
pygame.display.update()
self.waiting = True
def startscreen(self):
'''Algusaken'''
menuu.play(-1)
DS.blit(startscreen, [0,0])
self.draw_text('Purpleman', 48, PURPLE, W/2, H/4)
self.draw_text('Space to jump', 22, PURPLE, W/2, H*3/7)
self.draw_text('Press key to play', 22, PURPLE, W/2, H*5/9)
self.draw_text('High score: ' + str(self.highscore), 22, PURPLE, W/2, 15)
self.draw_text('All made by TaaviR', 14, WHITE, W/2, 570)
pygame.display.update()
self.wait_for_key()
def pause_endscreen(self):
'''Lopuaken'''
sad.play()
DS.blit(endscreen, [0,0])
self.draw_text('GAME OVER', 48, PURPLE, W/2, H/4)
self.draw_text('You ran ' + str(points), 22, PURPLE, W/2, H/2)
self.draw_text('Press key to play again', 22, WHITE, W/2, H*5/6)
if points > self.highscore: #high score mehhanism
self.highscore = points
self.draw_text('NEW HIGH SCORE!', 22, PURPLE, W/2, H/2 + 40)
with open('highscore.txt', 'w') as f:
f.write(str(points))
else:
self.draw_text('Highscore ' + str(self.highscore), 22, PURPLE, W/2, H/2 + 40)
pygame.display.update()
self.wait_for_key()
self.waiting = True
def wait_for_key(self):
'''Mangija input menuu jaoks'''
self.waiting = True
while self.waiting:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
self.waiting = False
pygame.mixer.quit()
elif event.type == pygame.KEYUP:
self.waiting = False
menuu.stop()
pygame.mixer.music.play(-1)
sad.stop()
def draw_text(self,text, size, color, x, y):
self.font = pygame.font.Font('freesansbold.ttf', size)
self.text_surface = self.font.render(text, True, color)
self.text_rect = self.text_surface.get_rect()
self.text_rect.midtop = (x, y)
DS.blit(self.text_surface, self.text_rect)
def crash(self):
self.message_display('Purpleman got hurt')
self.waiting = True
def background():
'''Liikuv taust'''
back_x = x % bg.get_rect().width
# ---Draw everything.---
DS.blit(bg, (back_x - bg.get_rect().width, 0))
if back_x < W:
DS.blit(bg, (back_x, 0))
pygame.time.set_timer(pygame.USEREVENT+2, random.choice([2500, 3000, 1500,1000])) #valjastamaks suvaliselt takistusi
#klassid
obstacle = Obstacle(832, 412)
player = Player(190, 359, 359)
#sprite grupid
all_sprites = pygame.sprite.Group(player, obstacle)
obstacles = pygame.sprite.Group(obstacle)
#vajalikud vaartused
index = 3
points = 0
x = 0
x -= 1
speed = -5
start = Scoring()
start.startscreen()
pygame.mixer.music.play(-1)
running = True
while running:
# ---Mangumootor.---
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
pygame.mixer.quit()
pygame.quit()
elif event.type == pygame.USEREVENT+2:
r = random.randrange(0, 2)
if r == 0:
obstacle = Obstacle(832, 412)
# Lisamaks takistuse gruppidesse
obstacles.add(obstacle)
all_sprites.add(obstacle)
# ---Mangu loogika---
all_sprites.update()
collided = pygame.sprite.spritecollide(player, obstacles, True, pygame.sprite.collide_mask) #kokkupuutumine
if collided:
ohno.play()
pygame.mixer.music.stop()
start.crash()
pygame.time.delay(3000)
pygame.event.clear()
obstacles.empty()
start.pause_endscreen()
points = 0
speed = -5
else:
points += 1
#vajalikud vaartused
index += 1
x -= 2
speed += -0.008
#funktsioonid
background()
start.score(points)
all_sprites.draw(DS)
keys(player)
pygame.display.update()
clock.tick(60)
pygame.mixer.quit()
pygame.quit()
Don't call pygame.mixer.quit() and pygame.quit() in the event loop when a pygame.QUIT event occurs. When you call pygame.quit(), you can't use some pygame functions like pygame.display.update anymore because all modules have been uninitialized, and since the while loop is still running, this exception gets raised.
So just remove the pygame.quit and pygame.mixer.quit() in the event loop and call them at the end of the program (as you already do).
Actually, you don't even have to call these functions and can just let the program finish as any other program. I think pygame.quit is only needed to close the window if you run your game with the IDLE IDE (and maybe with other tkinter based applications).

What syntax am I not seeing or entering correctly via python?

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()

How to drag an image around the screen using pygame

I want to be able to grab an image by clicking on it with the mouse and then drag it to a location on the screen. when the mouse button is released it will be dropped. The image is a space ship that i want to use as a sprite and there are multiple spaceships. This is for a game of battleships and this is the part of the game where you drag your ships to a desired position on a board. I am using python 3.3.2 and pygame and windows 10. Thanks for your any help! Here is what i have so far:
def instructions_screen():
intro = True
while intro:
for event in pygame.event.get():
if event.type ==QUIT:
pygame.screen.quit()
exit()
screen.blit(background, (0, 0))
largeText = pygame.font.Font('SF Distant Galaxy.ttf',36)
TextSurf, TextRect = text_objects("Instructions:", largeText)
TextRect.center = ((display_width/2), (75))
screen.blit(instruction_text, (280, 120))
button("Back",0,670,200,50,light_grey,white,"Back_instructions")
screen.blit(TextSurf, TextRect)
pygame.display.update()
clock.tick(30)
def ship_select_screen():
top_margin = 120
left_margin = 390
intro = True
while intro:
for event in pygame.event.get():
if event.type == QUIT:
pygame.screen.quit()
exit()
screen.blit(background, (0, 0))
largeText = pygame.font.Font('SF Distant Galaxy.ttf',36)
TextSurf, TextRect = text_objects("Ship selection:", largeText)
TextRect.center = ((display_width/2), (75))
screen.blit(TextSurf, TextRect)
largeText = pygame.font.Font('SF Distant Galaxy.ttf',36)
TextSurf, TextRect = text_objects("Ships to place:", largeText)
TextRect.center = ((200), (150))
button("Back",0,670,200,50,light_grey,white,"Back_instructions")
#width and height of each grid location
WIDTH = 40
HEIGHT = 40
#margin between each cell
MARGIN = 10
#colours:
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREEN = (0, 255, 0)
RED = (255, 0, 0)
# Create a 2 dimensional array.
grid = []
for row in range(10):
# Add an empty array that will hold each cell
# in this row
grid.append([])
for column in range(10):
grid[row].append(0) # Append a cell
while True:
#draw the grid
for row in range(10):
for column in range(10):
colour = WHITE
if grid[row][column] == 1:
colour = GREEN
pygame.draw.rect(screen,
colour,
[(((MARGIN + WIDTH) * column) + left_margin),
(((MARGIN + HEIGHT) * row) + top_margin),
WIDTH,
HEIGHT])
for event in pygame.event.get():
pos = pygame.mouse.get_pos()
if event.type == QUIT:
exit()
elif event.type == pygame.MOUSEBUTTONDOWN and pos[0] > 390 and pos[0] < 890 and pos[1] > 120 and pos[1] < 620:
column = (pos[0]-left_margin) // (WIDTH + MARGIN)
row = (pos[1]-top_margin) // (HEIGHT + MARGIN)
# Set that location to zero
grid[row][column] = 1
print("Click ", pos, "Grid coordinates: ", row, column)
print(grid)
global mouse_button_down
mouse_button_down = pygame.mouse.get_pressed()
global mouse_pos
mouse_pos = pygame.mouse.get_pos()
global aircraft_x
aircraft_x = 70
global aircraft_y
aircraft_y = 185
aircraft_carrier()
screen.blit(TextSurf, TextRect)
pygame.display.update()
clock.tick(15)
button("Back",0,670,200,50,light_grey,white,"Back_game")
def aircraft_carrier():
global aircraft_x
global aircraft_y
global mouse_button_down
global mouse_pos
running = True
while running:
if mouse_button_down[0] == True and mouse_pos[0] > abs(aircraft_x - aircraft_x) + 250 and mouse_pos[1] > aircraft_y and mouse_pos[1] < aircraft_y + 40:
print("Running!")
aircraft_x = (aircraft_x + abs(aircraft_x - mouse_pos[0]))
aircraft_y = (aircraft_y + abs(aircraft_y - mouse_pos[1]))
screen.blit(aircraft_carrier_sprite, (aircraft_x, aircraft_y))
elif mouse_button_down[0] != True:
running = False
pygame.display.update()
clock.tick(30)

Pygame Screen is Black for Short Time, Then Closes

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

Categories

Resources