This topic is READ ONLY
stickom (8) [Avatar] Offline
#1
Hello,
this is Aleksa again... i'm now 12 years old and i've been getting back into python and been wondering if i could make a game center. It worked using the resource editor perfectly fine... all of the buttons opened up a new program, but the problem is every time i close the pygame window, it closes the whole thing as well:
from PythonCard import model

class MainWindow(model.Background):

def on_failBtn_mouseClick(self, event):
old_position = self.components.failBtn.position
old_x = old_position[0]
old_y = old_position[1]
new_x = old_x - 20
new_y = old_y - 10
new_position = [new_x, new_y]
self.components.failBtn.position = new_position

def on_annoyingBtn_mouseClick(self, event):
import pygame, sys
pygame.init()
screen = pygame.display.set_mode([640,480])
background = pygame.Surface(screen.get_size())
background.fill([255, 255, 255])
clock = pygame.time.Clock()
delay = 100
interval = 50
pygame.key.set_repeat(delay, interval)

class Ball(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed

def move(self):
if self.rect.left <= screen.get_rect().left or \r
self.rect.right >= screen.get_rect().right:
self.speed[0] = - self.speed[0]
newpos = self.rect.move(self.speed)
self.rect = newpos

my_ball = Ball('beach_ball.png', [10,0], [20, 20])
screen.blit(my_ball.image, my_ball.rect)

while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEMOTION:
my_ball.rect.center = event.pos

clock.tick(30)
screen.blit(background, (0, 0))
my_ball.move()
screen.blit(my_ball.image, my_ball.rect)
pygame.display.flip()

def on_pypngBtn_mouseClick(self, event):
import pygame, sys
global points, score_text

class MyBallClass(pygame.sprite.Sprite):
def __init__(self, image_file, speed, location = [0,0]):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image = pygame.image.load(image_file)
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
self.speed = speed

def move(self):
global points, score_text
self.rect = self.rect.move(self.speed)
# bounce off the sides of the window
if self.rect.left < 0 or self.rect.right > screen.get_width():
self.speed[0] = -self.speed[0]
if self.rect.top < screen.get_height():
hit_wall.play()

# bounce off the top of the window
if self.rect.top <= 0 :
self.speed[1] = -self.speed[1]
points = points + 10
score_text = font.render(str(points), 1, (0, 0, 0))
get_point.play()

class MyPaddleClass(pygame.sprite.Sprite):
def __init__(self, location = [0,0]):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
image_surface = pygame.surface.Surface([100, 20])
image_surface.fill([0,0,0])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.top = location
pygame.init()
pygame.mixer.init()
pygame.mixer.music.load("bg_music.mp3")
pygame.mixer.music.set_volume(0.3)
pygame.mixer.music.play(-1)
hit = pygame.mixer.Sound("hit_paddle.wav")
hit.set_volume(0.4)
new_life = pygame.mixer.Sound("new_life.wav")
new_life.set_volume(0.5)
splat = pygame.mixer.Sound("splat.wav")
splat.set_volume(0.6)
hit_wall = pygame.mixer.Sound("hit_wall.wav")
hit_wall.set_volume(0.4)
get_point = pygame.mixer.Sound("get_point.wav")
get_point.set_volume(0.2)
bye = pygame.mixer.Sound("game_over.wav")
bye.set_volume(0.6)
screen = pygame.display.set_mode([640,480])
clock = pygame.time.Clock()
myBall = MyBallClass('wackyball.bmp', [12,6], [50, 50])
ballGroup = pygame.sprite.Group(myBall)
paddle = MyPaddleClass([270, 400])
lives = 5
points = 0

# display the score
font = pygame.font.Font(None, 50)
score_text = font.render(str(points), 1, (0, 0, 0))
textpos = [10, 10]
done = False

while 1:
clock.tick(30)
screen.fill([255, 255, 255])
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEMOTION:
paddle.rect.centerx = event.pos[0]

if pygame.sprite.spritecollide(paddle, ballGroup, False):
hit.play()
myBall.speed[1] = -myBall.speed[1]

myBall.move()

if not done:
screen.blit(myBall.image, myBall.rect)
screen.blit(paddle.image, paddle.rect)
screen.blit(score_text, textpos)
for i in range (lives):
width = screen.get_width()
screen.blit(myBall.image, [width - 40 * i, 20])
pygame.display.flip()

if myBall.rect.top >= screen.get_rect().bottom:
if not done:
splat.play()
# lose a life if the ball hits the bottom
lives = lives - 1
if lives <= 0:
if not done:
pygame.time.delay(1000)
bye.play()
final_text1 = "Game Over"
final_text2 = "Your final score is: " + str(points)
ft1_font = pygame.font.Font(None, 70)
ft1_surf = font.render(final_text1, 1, (0, 0, 0))
ft2_font = pygame.font.Font(None, 50)
ft2_surf = font.render(final_text2, 1, (0, 0, 0))
screen.blit(ft1_surf, [screen.get_width()/2 - \r
ft1_surf.get_width()/2, 100])
screen.blit(ft2_surf, [screen.get_width()/2 - \r
ft2_surf.get_width()/2, 200])
pygame.display.flip()
done = True
pygame.mixer.music.fadeout(2000)
else: #wait 2 seconds, then start the next ball
pygame.time.delay(1000)
new_life.play()
myBall.rect.topleft = [50, 50]
screen.blit(myBall.image, myBall.rect)
pygame.display.flip()
pygame.time.delay(1000)

def on_skierBtn_mouseClick(self, event):
import pygame, sys, random

# different images for the skier depending on his direction
skier_images = ["skier_down.png", "skier_right1.png", "skier_right2.png",
"skier_left2.png", "skier_left1.png"]

# class for the skier sprite
class SkierClass(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("skier_down.png")
self.rect = self.image.get_rect()
self.rect.center = [320, 100]
self.angle = 0

def turn(self, direction):
# load new image and change speed when the skier turns
self.angle = self.angle + direction
if self.angle < -2: self.angle = -2
if self.angle > 2: self.angle = 2
center = self.rect.center
self.image = pygame.image.load(skier_images[self.angle])
self.rect = self.image.get_rect()
self.rect.center = center
speed = [self.angle, 6 - abs(self.angle) * 2]
return speed

def move(self, speed):
# move the skier right and left
self.rect.centerx = self.rect.centerx + speed[0]
if self.rect.centerx < 20: self.rect.centerx = 20
if self.rect.centerx > 620: self.rect.centerx = 620

# class for obstacle sprites (trees and flags)
class ObstacleClass(pygame.sprite.Sprite):
def __init__(self, image_file, location, type):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
self.image_file = image_file
self.image = pygame.image.load(image_file)
self.location = location
self.rect = self.image.get_rect()
self.rect.center = location
self.type = type
self.passed = False

def scroll(self, terrainPos):
self.rect.centery = self.location[1] - terrainPos

# create one "screen" of terrain: 640 x 640
# use "blocks" of 64 x 64 pixels, so objects aren't too close together
def create_map(start, end):
obstacles = pygame.sprite.Group()
locations = []
gates = pygame.sprite.Group()
for i in range(10): # 10 obstacles per screen
row = random.randint(start, end)
col = random.randint(0, 9)
location = [col * 64 + 20, row * 64 + 20] #center x, y for obstacle
if not (location in locations): # prevent 2 obstacles in the same place
locations.append(location)
type = random.choice(["tree", "flag"])
if type == "tree": img = "skier_tree.png"
elif type == "flag": img = "skier_flag.png"
obstacle = ObstacleClass(img, location, type)
obstacles.add(obstacle)
return obstacles

# redraw the screen, including all sprites
def animate():
screen.fill([255, 255, 255])
pygame.display.update(obstacles.draw(screen))
screen.blit(skier.image, skier.rect)
screen.blit(score_text, [10, 10])
pygame.display.flip()

def updateObstacleGroup(map0, map1):
obstacles = pygame.sprite.Group()
for ob in map0: obstacles.add(ob)
for ob in map1: obstacles.add(ob)
return obstacles

# initialize everything
pygame.init()
screen = pygame.display.set_mode([640,640])
clock = pygame.time.Clock()
skier = SkierClass()
speed = [0, 6]
map_position = 0
points = 0
map0 = create_map(20, 29)
map1 = create_map(10, 19)
activeMap = 0

# group for all obstacles to do collision detection
obstacles = updateObstacleGroup(map0, map1)

# font object for score
font = pygame.font.Font(None, 50)

# main Pygame event loop
while True:
clock.tick(30)
for event in pygame.event.get():
if event.type == pygame.QUIT: sys.exit()
if event.type == pygame.KEYDOWN: # check for key presses
if event.key == pygame.K_LEFT: # left arrow turns left
speed = skier.turn(-1)
elif event.key == pygame.K_RIGHT: #right arrow turns right
speed = skier.turn(1)
skier.move(speed)
map_position += speed[1] # scroll the terrain

# manage terrain maps, switch between them,
# and create new terrain at the bottom
if map_position >=640 and activeMap == 0:
activeMap = 1
map0 = create_map(20, 29)
obstacles = updateObstacleGroup(map0, map1)
if map_position >=1280 and activeMap == 1:
activeMap = 0
for ob in map0:
ob.location[1] = ob.location[1] - 1280 # wrap around to top
map_position = map_position - 1280 #
map1 = create_map(10, 19)
obstacles = updateObstacleGroup(map0, map1)

for obstacle in obstacles:
obstacle.scroll(map_position)

# check for hitting trees or getting flags
hit = pygame.sprite.spritecollide(skier, obstacles, False)
if hit:
if hit[0].type == "tree" and not hit[0].passed: #crashed into tree
points = points - 100
skier.image = pygame.image.load("skier_crash.png") # crash image
animate()
pygame.time.delay(1000)
skier.image = pygame.image.load("skier_down.png") # resume skiing
skier.angle = 0
speed = [0, 6]
hit[0].passed = True
elif hit[0].type == "flag" and not hit[0].passed: # got a flag
points += 10
obstacles.remove(hit[0]) # remove the flag

score_text = font.render("Score: " +str(points), 1, (0, 0, 0))
animate()

def on_lunarlndrBtn_mouseClick(self, event):
import pygame, sys
global thrust, fuel, velocity, delta_v, height, y_pos
pygame.init()
screen = pygame.display.set_mode([400,600])
screen.fill([0, 0, 0])
ship = pygame.image.load('lunarlander.png')
moon = pygame.image.load('moonsurface.png')
ground = 540 #landing pad is y = 540
start = 90
clock = pygame.time.Clock()
ship_mass = 5000.0
fuel = 5000.0
velocity = -100.0
gravity = 10
height = 2000
thrust = 0
delta_v = 0
y_pos = 90
held_down = False

# make the throttle
class ThrottleClass(pygame.sprite.Sprite):
def __init__(self, location = [0,0]):
pygame.sprite.Sprite.__init__(self) #call Sprite initializer
image_surface = pygame.surface.Surface([30, 10])
image_surface.fill([128,128,128])
self.image = image_surface.convert()
self.rect = self.image.get_rect()
self.rect.left, self.rect.centery = location

# calcualte position, motion, acceleration, fuel
def calculate_velocity():
global thrust, fuel, velocity, delta_v, height, y_pos
delta_t = 1/fps
thrust = (500 - myThrottle.rect.centery) * 5.0 # turn throttle position
# into amount of thrust
fuel -= thrust /(10 * fps) # use up fuel
if fuel < 0: fuel = 0.0
if fuel < 0.1: thrust = 0.0
delta_v = delta_t * (-gravity + 200 * thrust / (ship_mass + fuel))
velocity = velocity + delta_v
delta_h = velocity * delta_t
height = height + delta_h
y_pos = ground - (height * (ground - start) / 2000) - 90

# display the text with the speed, height, etc.
def display_stats():
v_str = "velocity: %i m/s" % velocity
h_str = "height: %.1f" % height
t_str = "thrust: %i" % thrust
a_str = "acceleration: %.1f" % (delta_v * fps)
f_str = "fuel: %i" % fuel
v_font = pygame.font.Font(None, 26)
v_surf = v_font.render(v_str, 1, (255, 255, 255))
screen.blit(v_surf, [10, 50])
a_font = pygame.font.Font(None, 26)
a_surf = a_font.render(a_str, 1, (255, 255, 255))
screen.blit(a_surf, [10, 100])
h_font = pygame.font.Font(None, 26)
h_surf = h_font.render(h_str, 1, (255, 255, 255))
screen.blit(h_surf, [10, 150])
t_font = pygame.font.Font(None, 26)
t_surf = t_font.render(t_str, 1, (255, 255, 255))
screen.blit(t_surf, [10, 200])
f_font = pygame.font.Font(None, 26)
f_surf = f_font.render(f_str, 1, (255, 255, 255))
screen.blit(f_surf, [60, 300])

# display the ship's flames - size depends on the amount of thrust
def display_flames():
flame_size = thrust / 15
for i in range (2):
startx = 252 - 10 + i * 19
starty = y_pos + 83
pygame.draw.polygon(screen, [255, 109, 14], [(startx, starty),
(startx + 4, starty + flame_size),
(startx + 8, starty)], 0)

# display final stats when the game is over
def display_final():
final1 = "Game over"
final2 = "You landed at %.1f m/s" % velocity
if velocity > -5:
final3 = "Nice landing!"
final4 = "I hear NASA is hiring!"
elif velocity > -15:
final3 = "Ouch! A bit rough, but you survived."
final4 = "You'll do better next time."
else:
final3 = "Yikes! You crashed a 30 Billion dollar ship."
final4 = "How are you getting home?"
pygame.draw.rect(screen, [0, 0, 0], [5, 5, 350, 280],0)
f1_font = pygame.font.Font(None, 70)
f1_surf = f1_font.render(final1, 1, (255, 255, 255))
screen.blit(f1_surf, [20, 50])
f2_font = pygame.font.Font(None, 40)
f2_surf = f2_font.render(final2, 1, (255, 255, 255))
screen.blit(f2_surf, [20, 110])
f3_font = pygame.font.Font(None, 26)
f3_surf = f3_font.render(final3, 1, (255, 255, 255))
screen.blit(f3_surf, [20, 150])
f4_font = pygame.font.Font(None, 26)
f4_surf = f4_font.render(final4, 1, (255, 255, 255))
screen.blit(f4_surf, [20, 180])
pygame.display.flip()

myThrottle = ThrottleClass([15, 500])

# main loop
while True:
clock.tick(30)
fps = clock.get_fps()
if fps < 1: fps = 30
if height > 0.01:
calculate_velocity()
screen.fill([0, 0, 0])
display_stats()
pygame.draw.rect(screen, [0, 0, 255], [80, 350, 24, 100], 2)
fuelbar = 96 * fuel / 5000
pygame.draw.rect(screen, [0,255,0], [84,448-fuelbar,18, fuelbar], 0)
pygame.draw.rect(screen, [255, 0, 0], [25, 300, 10, 200],0) #thrust bar
screen.blit(moon, [0, 500, 400, 100]) #moon
pygame.draw.rect(screen, [60, 60, 60], [220, 535, 70, 5],0) #landing pad
screen.blit(myThrottle.image, myThrottle.rect) #thrust handle
display_flames() #flames
screen.blit(ship, [230, y_pos, 50, 90]) #ship
instructions1 = "Land softly without running out of fuel"
instructions2 = "Good landing: < 15 m/s Great landing: < 5m/s"
inst1_font = pygame.font.Font(None, 24)
inst1_surf = inst1_font.render(instructions1, 1, (255, 255, 255))
screen.blit(inst1_surf, [50, 550])
inst2_font = pygame.font.Font(None, 24)
inst2_surf = inst1_font.render(instructions2, 1, (255, 255, 255))
screen.blit(inst2_surf, [20, 575])
pygame.display.flip()

else: #game over - print final score
display_final()

for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
held_down = True
elif event.type == pygame.MOUSEBUTTONUP:
held_down = False
elif event.type == pygame.MOUSEMOTION:
if held_down:
myThrottle.rect.centery = event.pos[1]
if myThrottle.rect.centery < 300:
myThrottle.rect.centery = 300
if myThrottle.rect.centery > 500:
myThrottle.rect.centery = 500

def on_visualsBtn_mouseClick(self, event):
from visual import *
scene.title = "Bouncing Ball"
scene.background = (1,1,1)
scene.center = (0,5,0)
scene.autoscal = False
floor = box (pos=(0,0,0), length=4, height=0.5, width=4, color=color.blue)
ball = sphere (pos=(0,6,0), radius=1, color=color.red)
ball.velocity = vector(0,-2,0)
dt = 0.01
while 1:
rate (100)
ball.pos = ball.pos + ball.velocity*dt
if ball.y < ball.radius:
ball.velocity.y = -ball.velocity.y
else:
ball.velocity.y = ball.velocity.y - 9.8*dt

def on_diaryBtn_mouseClick(self, event):
#imports
import sys
#variables
#Functions
def Clear():

f = open("log.txt", "w");
f.write("")

def Dump():
f = open("log.txt", "r");
print f.read()

def Post():
f = open("log.txt", "a");
message = raw_input("Enter Message: ");
f.write("
");
f.write(message)

def Die():
sys.exit()

def Main():
print "Hello";
print "Welcome to <(DiArY)>";
choice = raw_input("Press 1 to post, 2 to dump log, 3 to clear, or 4 to exit.""
");

if choice == "1":

Post()
Main()

elif choice == "2":

Dump()
Main()


elif choice == "3":

print "Are You Sure?"
choice2 = raw_input("Yes/No""
")
if choice2 == "Yes" or "yes" or "y":

Clear()
Main()


elif choice2 == "No" or "no" or "n":

Main()


elif choice == "4":
Die()


Main()



app = model.Application(MainWindow)
app.MainLoop()

What i don't understand is how come whenever i close the pygame window it closes the whole program... how can i fix that so that i can go back to the main screen?