This is a strange problem cause I've already use the font, during the same execuction, and... in the same function !
I explain myself with a part of my program :
def text(show_text, show_size, show_color, show_x, show_y):
fontObj = pygame.font.Font('Font.ttf',show_size) # The line 43
Load_text = fontObj.render(show_text,True,show_color,None)
render_text = Load_text.get_rect()
render_text.center = (show_x,show_y)
screen.blit(Load_text,render_text)
def checkmouse(t_text,size,px,py,color1,color2,window):
global p_x, p_y
px_min = px - (int(len(str(text))/2))
px_max = px + (int(len(str(text))/2))
py_min = py - 10
py_max = py + 10
if p_x >= px_min and p_x <= px_max and p_y >= py_min and p_y <= py_max :
text(t_text,size,color1,px,py) # The line 68
pygame.display.update()
else:
text(t_text,size,color2,px,py)
pygame.display.update()
The problem is here :
if w == 'main':
sceen=pygame.display.set_mode((1920,1080), pygame.NOFRAME)
while w == 'main':
image(bg32_big,0,0)
Main = True
while Main :
checkmouse('Play',32,960,260,Dark_Blue,White,'load') # line 109
checkmouse('Quit',32,1520,740,Dark_Blue,White,'load')
And this is my 'traceback' :
Traceback (most recent call last):
File "C:\Users\Cédric\3D Objects\_TAL WIP_\TAL 1 script\newfile.py", line 143, in <module>
Window('main')
File "C:\Users\Cédric\3D Objects\_TAL WIP_\TAL 1 script\newfile.py", line 109, in Window
checkmouse('Play',32,960,260,Dark_Blue,White,'load')
File "C:\Users\Cédric\3D Objects\_TAL WIP_\TAL 1 script\newfile.py", line 68, in checkmouse
text(t_text,size,color2,px,py)
File "C:\Users\Cédric\3D Objects\_TAL WIP_\TAL 1 script\newfile.py", line 43, in text
fontObj = pygame.font.Font('Font.ttf',show_size)
pygame.error: font not initialized
But how it's possible ? In the same function, I've use text('Loading, this may take a few time...',15,Dark_Blue,240,240) before and it's worked perfectly, so why ?
PS: full code:
import time
spb = time.time()
#----+ Major Imports +----#
print('Loading pygame and other child modules :')
import pygame
import os, sys
pygame.init()
print('All modules was loaded succesfully !')
#---+ center windows +---#
os.environ['SDL_VIDEO_CENTERED'] = '1'
#-----+ ALL THE CONSTANTS FROM THE GAME +-----#
print('+*---------------*+')
print('Getting variables')
Dark_Blue = ( 0, 0, 128)
White = ( 255, 255, 255)
barPos = (40, 200)
barSize = (400, 25)
current_load = 'rien.png'
max_a = 3 # Numbur of pictures to convert
a=0
bar_percent = 0
display_percent = '0'
a_db,a_da,a_dif = 0,0,0
p_x,p_y = 0,0
show_size = 25
fontObj = pygame.font.Font('Font.ttf',show_size)
#------+ Loading window +------#
screen=pygame.display.set_mode((1,1), pygame.NOFRAME)
#-----+ ALL THE DEFINITIONS OF THE PROGRAM +-----#
print('Getting definitions')
def text(show_text, show_size, show_color, show_x, show_y):
fontObj = pygame.font.Font('Font.ttf',show_size)
Load_text = fontObj.render(show_text,True,show_color,None)
render_text = Load_text.get_rect()
render_text.center = (show_x,show_y)
screen.blit(Load_text,render_text)
def image(name,x,y):
screen.blit(name,(x,y))
def DrawBar(pos, size, borderC, barC, progress):
global screen
pygame.draw.rect(screen, borderC, (*pos, *size), 1)
innerPos = (pos[0]+3, pos[1]+3)
innerSize = ((size[0]-6) * progress, size[1] - 6)
pygame.draw.rect(screen, barC, (*innerPos, *innerSize))
# The Program draw a bar from the value that we give in 'progress'
# which is equal to a/max_a !
def checkmouse(t_text,size,px,py,color1,color2,window):
global p_x, p_y
px_min = px - (int(len(str(text))/2))
px_max = px + (int(len(str(text))/2))
py_min = py - 10
py_max = py + 10
if p_x >= px_min and p_x <= px_max and p_y >= py_min and p_y <= py_max :
text(t_text,size,color1,px,py)
pygame.display.update()
else:
text(t_text,size,color2,px,py)
pygame.display.update()
#---+ Needed for loading +---#
bg32 = pygame.image.load('sprites/bg32.png').convert_alpha()
bgbar = pygame.image.load('sprites/bgbar.png').convert_alpha()
outline = pygame.image.load('sprites/outline.png').convert_alpha()
title = pygame.image.load('sprites/loading_title.png').convert_alpha()
#---+ Program Heart +---#
def Window(w):
global screen,a,max_a,barPos,barSize,Very_Dark_Blue,borderColor,bg32,bgbar
global outline,title,current_load,a_dif,a_db,a_da,bar_percent
if w == 'first_load':
screen=pygame.display.set_mode((480,270), pygame.NOFRAME)
w = 'load'
if w == 'load':
print(current_load)
a_db = int(( a / max_a ) * 100)
a = a + 1
a_da = int(( a/max_a ) * 100)
a_dif = a_da - a_db
for i in range(0,a_dif):
image(bg32,0,0)
image(bgbar,40,200)
image(outline,0,0)
image(title,40,0)
bar_percent = bar_percent + 1
DrawBar(barPos, barSize, Dark_Blue, Dark_Blue, bar_percent/100)
display_percent = str(current_load) + ' - ' + str(bar_percent) + ' %'
text(display_percent,25,Dark_Blue,240,185)
text('Loading, this may take a few time...',15,Dark_Blue,240,240)
pygame.display.update()
if w == 'main':
sceen=pygame.display.set_mode((1920,1080), pygame.NOFRAME)
while w == 'main':
image(bg32_big,0,0)
Main = True
while Main :
checkmouse('Play',32,960,260,Dark_Blue,White,'load')
checkmouse('Quit',32,1520,740,Dark_Blue,White,'load')
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
Window(window)
pygame.quit()
print('+*---------------*+')
print('Loading window :')
#-----+ Loading window +-----#
current_load = 'Background.png'
Window('first_load')
background = pygame.image.load('sprites/Background.png').convert_alpha()
current_load = 'outline.png'
Window('load')
outline_big = pygame.image.load('sprites/outline.png').convert_alpha()
current_load = 'bg32.png'
Window('load')
bg32_big = pygame.image.load('sprites/bg32_big.png').convert_alpha()
print('All pictures was loaded succesfully !')
#---+ time debug +---#
spe = time.time()
spt = spe - spb
sptm = 0
while spt >= 60:
spt = spt - 60
sptm = sptm + 1
print('+*---------------------*+')
print('All ressources needed for the game was loaded in',sptm,'minutes and',spt,'seconds')
#-----+ and... +-----#
Window('main')
Just don't call pygame.quit() in your main loop:
while Main :
checkmouse('Play',32,960,260,Dark_Blue,White,'load')
checkmouse('Quit',32,1520,740,Dark_Blue,White,'load')
for event in pygame.event.get():
if event.type == pygame.MOUSEBUTTONDOWN:
Window(window)
pygame.quit() # <-- don't do this
It will put the font module (and other modules) in a state that's no longer useable.
Related
I have 3 python files: main.py, settings.py and classes.py
main.py:
import pygame as pg
from classes import *
from settings import *
pg.font.init()
HEALTH_FONT = pg.font.SysFont('comicsans', 20)
pg.display.set_caption("Testa Game")
ground_surface = pg.image.load('graphics/ground.png').convert()
BG_COLOR = (0, 255, 255)
BLACK = (0, 0, 0)
run = True
while run == True:
clock = pg.time.Clock()
for event in pg.event.get():
if event.type == pg.QUIT:
pg.quit()
exit()
clock.tick(FPS)
keys_pressed = pg.key.get_pressed()
health_text = HEALTH_FONT.render("Health: " + str(class_type.health), 1, BLACK)
WIN.fill(BG_COLOR)
WIN.blit(class_type.karakter_surface, (class_type.karakter.x, class_type.karakter.y))
WIN.blit(ground_surface, (0, 350))
WIN.blit(health_text, (10, 10))
karakter_moving(keys_pressed, class_type.karakter)
pg.display.flip()
settings.py:
import pygame as pg
from classes import *
WIDTH, HEIGHT = 900, 500
WIN = pg.display.set_mode((WIDTH, HEIGHT))
class_type = death_mage
FPS = 60
def karakter_moving(keys_pressed, karakter):
if keys_pressed[pg.K_w] and karakter.y - class_type.speed > 0:
karakter.y -= class_type.speed
if keys_pressed[pg.K_s] and karakter.y + class_type.speed + karakter.height < HEIGHT - 5:
karakter.y += class_type.speed
if keys_pressed[pg.K_a] and karakter.x - class_type.speed > 0: #LEFT
karakter.x -= class_type.speed
if keys_pressed[pg.K_d] and karakter.x + class_type.speed + karakter.width < WIDTH:
karakter.x += class_type.speed
classes.py:
import pygame as pg
from settings import WIN
pg.init()
def fire_ball():
fireball = []
maxFireBall = 3
manacost = 1
color = 'ORANGE'
for event in pg.event.get():
if event.type == pg.KEYDOWN:
if event.key == pg.K_SPACE and len(fireball) < maxFireBall:
dmFireBall = pg.Rect(
death_mage.karakter.x + death_mage.karakter.width, death_mage.karakter.y + death_mage.karakter.height//2 - 2, 10, 5)
fireball.append(dmFireBall)
death_mage.mana -= manacost
pg.draw.rect(WIN, color, fireball)
class death_mage:
KARAKTER_WIDTH, KARAKTER_HEIGHT = 60, 85
karakter = pg.Rect(400, 200, KARAKTER_WIDTH, KARAKTER_HEIGHT)
karakter_surface = pg.transform.scale(pg.image.load('Assets/death_mage.png'), (KARAKTER_WIDTH, KARAKTER_HEIGHT))
health = 10
mana = 5
attack = 1
speed = 2
attack_speed = 1
crit_rate = 0
crit_damage = 0
Error message:
"settings.py", line 12, in <module>
class_type = death_mage
NameError: name 'death_mage' is not defined
or if settings.py: from classes import death_mage
"settings.py", line 3, in <module>
from classes import death_mage
ImportError: cannot import name 'death_mage' from partially initialized module 'classes' (most likely due to a circular import)
How can I remedy this?
Thanks to helping me
One of your modules has got no urls.py
I'm making a game with pygame and pymunk as a physics engine. I'm trying to kill a bullet whenever it hits a player or goes past its lifetime.
When I tried to space.remove(self.shape) and the second bullet hits the player, it gives me an "AssertionError: shape not in space, already removed. I simply changed it to teleport the bullets away, and then learned of the real error.
When I have more than one bullet in the space and a bullet hits the enemy player, all the current bullets teleport away, which means that when I tried to remove one bullet, it called the remove on all the bullets and thats why I had the initial error.
However the problem still remains that one bullet is being treated as every bullet.
Why is something that should be a non-static variable being called as a static variable?
I even tried to use deepcopy to see if that fixed it, but to no avail
This is my chunk of code, apologies since I don't know what is needed to understand it.
The key parts are most likely the Bullet class, the shoot() function in the Player class, and the drawBulletCollision() function
# PyGame template.
# Import modules.
import sys, random, math, time, copy
from typing import List
import pygame
from pygame.locals import *
from pygame import mixer
import pymunk
import pymunk.pygame_util
from pymunk.shapes import Segment
from pymunk.vec2d import Vec2d
pygame.mixer.pre_init(44110, -16, 2, 512)
mixer.init()
# Set up the window.
width, height = 1440, 640
screen = pygame.display.set_mode((width, height))
bg = pygame.image.load("space.png")
def draw_bg():
screen.blit(bg, (0, 0))
#load sounds
#death_fx = pygame.mixer.Sound("")
#death_fx.set_volume(0.25)
shoot_fx = mixer.Sound("shot.wav")
shoot_fx.set_volume(0.25)
#mixer.music.load("video.mp3")
#mixer.music.play()
#time.sleep(2)
#mixer.music.stop()
#gun_mode_fx = pygame.mixer.Sound("")
#gun_mode_fx.set_volume(0.25)
#thrust_mode_fx = pygame.mixer.Sound("")
#thrust_mode_fx.set_volume(0.25)
collision_fx = mixer.Sound("thump.wav")
collision_fx.set_volume(0.25)
ship_group = pygame.sprite.Group()
space = pymunk.Space()
space.gravity = 0, 0
space.damping = 0.6
draw_options = pymunk.pygame_util.DrawOptions(screen)
bulletList = []
playerList = []
environmentList = []
arbiterList = []
b0 = space.static_body
segmentBot = pymunk.Segment(b0, (0,height), (width, height), 4)
segmentTop = pymunk.Segment(b0, (0,0), (width, 0), 4)
segmentLef = pymunk.Segment(b0, (width,0), (width, height), 4)
segmentRit = pymunk.Segment(b0, (0,0), (0, height), 4)
walls = [segmentBot,segmentLef,segmentRit,segmentTop]
for i in walls:
i.elasticity = 1
i.friction = 0.5
i.color = (255,255,255,255)
environmentList.append(i)
class Player(object):
radius = 30
def __init__(self, position, space, color):
self.body = pymunk.Body(mass=5,moment=10)
self.mode = 0 # 0 is gun, 1 is thrust, ? 2 is shield
self.body.position = position
self.shape = pymunk.Circle(self.body, radius = self.radius)
#self.image
#self.shape.friction = 0.9
self.shape.elasticity= 0.2
space.add(self.body,self.shape)
self.angleGun = 0
self.angleThrust = 0
self.health = 100
self.speed = 500
self.gearAngle = 0
self.turningSpeed = 5
self.shape.body.damping = 1000
self.cooldown = 0
self.fireRate = 30
self.shape.collision_type = 1
self.shape.color = color
playerList.append(self)
def force(self,force):
self.shape.body.apply_force_at_local_point(force,(0,0))
def rocketForce(self):
radians = self.angleThrust * math.pi/180
self.shape.body.apply_force_at_local_point((-self.speed * math.cos(radians),-self.speed * math.sin(radians)),(0,0))
def draw(self):
gear = pygame.image.load("gear.png")
gearBox = gear.get_rect(center=self.shape.body.position)
gearRotated = pygame.transform.rotate(gear, self.gearAngle)
#gearRotated.rect.center=self.shape.body.position
x,y = self.shape.body.position
radianGun = self.angleGun * math.pi/180
radianThrust = self.angleThrust * math.pi/180
radiyus = 30 *(100-self.health)/100
screen.blit(gearRotated,gearBox)
self.gearAngle += 1
if radiyus == 30:
radiyus = 32
pygame.draw.circle(screen,self.shape.color,self.shape.body.position,radiyus,0)
pygame.draw.circle(screen,(0,0,0),self.shape.body.position,radiyus,0)
pygame.draw.line(
screen,(0,255,0),
(self.radius * math.cos(radianGun) * 1.5 + x,self.radius * math.sin(radianGun) * 1.5 + y),
(x,y), 5
)
pygame.draw.line(
screen,(200,200,0),
(self.radius * math.cos(radianThrust) * 1.5 + x,self.radius * math.sin(radianThrust) * 1.5 + y),
(x,y), 5
)
#more
def targetAngleGun(self,tAngle):
tempTAngle = tAngle - self.angleGun
tempTAngle = tempTAngle % 360
if(tempTAngle < 180 and not tempTAngle == 0):
self.angleGun -= self.turningSpeed
elif(tempTAngle >= 180 and not tempTAngle == 0):
self.angleGun += self.turningSpeed
self.angleGun = self.angleGun % 360
#print(tAngle, "target Angle")
#print(self.angleGun, "selfangleGun")
#print(tempTAngle, "tempTAngle")
def targetAngleThrust(self,tAngle):
tempTAngle = tAngle - self.angleThrust
tempTAngle = tempTAngle % 360
if(tempTAngle < 180 and not tempTAngle == 0):
self.angleThrust -= self.turningSpeed
elif(tempTAngle >= 180 and not tempTAngle == 0):
self.angleThrust += self.turningSpeed
self.angleThrust = self.angleThrust % 360
#print(tAngle, "target Angle")
#print(self.angleThrust, "selfangleGun")
#print(tempTAngle, "tempTAngle")
def targetAngle(self,tAngle):
if(self.mode == 0):
self.targetAngleGun(tAngle)
elif(self.mode == 1):
self.targetAngleThrust(tAngle)
def shoot(self):
if(self.cooldown == self.fireRate):
x,y = self.shape.body.position
radianGun = self.angleGun * math.pi/180
spawnSpot = (self.radius * math.cos(radianGun) * 1.5 + x,self.radius * math.sin(radianGun)*1.5+y)
self.shape.body.apply_impulse_at_local_point((-20 * math.cos(radianGun),-20 * math.sin(radianGun)),(0,0))
print(spawnSpot)
bT = Bullet(spawnSpot, 5, 50,self.shape.color)
b = copy.deepcopy(bT)
bulletList.append(b)
space.add(b.shape,b.shape.body)
b.getShot(self.angleGun)
self.cooldown = 0
print('pew')
shoot_fx.play()
# HEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEREEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEEE
def tick(self):
self.draw()
if(self.cooldown < self.fireRate):
self.cooldown += 1
#for o in playerList:
# c = self.shape.shapes_collide(o.shape)
# if(len(c.points)>0):
# self.damage(c.points[0].distance/10)
for o in bulletList:
c = self.shape.shapes_collide(o.shape)
#print(c)
for o in walls:
c = self.shape.shapes_collide(o)
if(len(c.points)>0):
self.damage(c.points[0].distance * 3)
def damage(self, damage):
self.health -= abs(damage)
if self.health < 0:
self.health = 0
#maybe make it part of the player class
def drawWallCollision(arbiter, space, data):
for c in arbiter.contact_point_set.points:
r = max(3, abs(c.distance * 5))
r = int(r)
p = tuple(map(int, c.point_a))
pygame.draw.circle(data["surface"], pygame.Color("red"), p, r, 0)
print('magnitude', math.sqrt(arbiter.total_impulse[0]**2 + arbiter.total_impulse[1]**2))
#print('position', p)
#print(data)
print("its all arbitrary")
s1, s2 = arbiter.shapes
collision_fx.play()
def drawBulletCollision(arbiter, space, data):
s1, s2 = arbiter.shapes
for c in arbiter.contact_point_set.points:
magnitude = math.sqrt(arbiter.total_impulse[0]**2 + arbiter.total_impulse[1]**2)
for p in playerList:
avr = ((c.point_a[0] + c.point_b[0])/2, (c.point_a[1] + c.point_b[1])/2)
distance = (math.sqrt((avr[0] - p.shape.body.position[0]) **2 + (avr[1] - p.shape.body.position[1]) **2 ))
if(distance < Bullet.explosionRadius + Player.radius):
if not(s1.color == s2.color):
p.damage(magnitude)
for b in bulletList:
avr = ((c.point_a[0] + c.point_b[0])/2, (c.point_a[1] + c.point_b[1])/2)
distance = (math.sqrt((avr[0] - p.shape.body.position[0]) **2 + (avr[1] - p.shape.body.position[1]) **2 ))
if(distance < Bullet.explosionRadius + Player.radius):
if not(s1.color == s2.color):
b.damage(magnitude)
pygame.draw.circle(data["surface"], pygame.Color("red"), tuple(map(int, c.point_a)), 10, 0)
print('magnitude', magnitude)
#print('position', p)
#print(data)
print("its all arbitrary")
def drawArbitraryCollision(arbiter, space, data):
collision_fx.play()
class Ship(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("gear.png")
self.rect = self.image.get_rect()
self.rect.center = [x, y]
def rotate(self):
self.image = pygame.transform.rotate(self.image,1)
class Bullet(object):
damage = 2
explosionRadius = 5
def __init__(self, position, size, speed,color):
pts = [(-size, -size), (size, -size), (size, size), (-size, size)]
self.body = copy.deepcopy(pymunk.Body(mass=0.1,moment=1))
self.shape = copy.deepcopy(pymunk.Poly(self.body, pts))
self.shape.body.position = position
self.shape.friction = 0.5
self.shape.elasticity = 1
self.shape.color = color
self.speed = speed
self.size = size
self.shape.collision_type = 2
#space.add(self.body,self.shape)
#bulletList.append(self)
self.lifetime = 0
def getShot(self,angle):
radians = angle * math.pi/180
self.shape.body.apply_impulse_at_local_point((self.speed * math.cos(radians),self.speed * math.sin(radians)),(0,0))
def tick(self):
self.lifetime += 1
if(self.lifetime > 300):
self.shape.body.position = (10000,30)
def damage(self, damage):
self.lifetime = 300
#VELOCITY OF BULLET STARTS WITH VELOCITY OF PLAYER
#MAKE VOLUME OF SOUND DEPEND ON THE IMPULSE FOR THE IMPACTS
#error on purpose so you notice this
#INSTANCES NOT WORKING????
def runPyGame():
# Initialise PyGame.
pygame.init()
# Set up the clock. This will tick every frame and thus maintain a relatively constant framerate. Hopefully.
fps = 60.0
fpsClock = pygame.time.Clock()
running = True
font = pygame.font.SysFont("Arial", 16)
p1 = Player((240,240),space,(132, 66, 245,255))
p2 = Player((1200,400),space,(47, 247, 184,255))
space.add(segmentBot,segmentTop,segmentLef,segmentRit)
# Main game loop.
ch = space.add_collision_handler(1, 0)
ch.data["surface"] = screen
ch.post_solve = drawWallCollision
ch = space.add_collision_handler(1, 2)
ch.data["surface"] = screen
ch.post_solve = drawBulletCollision
ch = space.add_collision_handler(0, 2)
ch.data["surface"] = screen
ch.post_solve = drawArbitraryCollision
dt = 1/fps # dt is the time since last frame.
while True: # Loop forever!
keys = pygame.key.get_pressed()
for event in pygame.event.get():
# We need to handle these events. Initially the only one you'll want to care
# about is the QUIT event, because if you don't handle it, your game will crash
# whenever someone tries to exit.
if event.type == QUIT:
pygame.quit() # Opposite of pygame.init
sys.exit() # Not including this line crashes the script on Windows.
if event.type == KEYDOWN:
if event.key == pygame.K_s:
p1.mode = -(p1.mode - 0.5) + 0.5
print(p1.mode)
if (event.key == pygame.K_k and p1.mode == 0):
p1.shoot()
if event.key == pygame.K_KP_5:
p2.mode = -(p2.mode - 0.5) + 0.5
print(p2.mode)
if (event.key == pygame.K_m and p2.mode == 0):
p2.shoot()
#b = Bullet((200,200),51,51)
if(keys[K_w]):
p1.targetAngle(90)
if(keys[K_q]):
p1.targetAngle(45)
if(keys[K_a]):
p1.targetAngle(0)
if(keys[K_z]):
p1.targetAngle(315)
if(keys[K_x]):
p1.targetAngle(270)
if(keys[K_c]):
p1.targetAngle(225)
if(keys[K_d]):
p1.targetAngle(180)
if(keys[K_e]):
p1.targetAngle(135)
if(keys[K_k] and p1.mode == 1):
p1.rocketForce()
if(keys[K_KP_8]):
p2.targetAngle(90)
if(keys[K_KP_7]):
p2.targetAngle(45)
if(keys[K_KP_4]):
p2.targetAngle(0)
if(keys[K_KP_1]):
p2.targetAngle(315)
if(keys[K_KP_2]):
p2.targetAngle(270)
if(keys[K_KP_3]):
p2.targetAngle(225)
if(keys[K_KP_6]):
p2.targetAngle(180)
if(keys[K_KP_9]):
p2.targetAngle(135)
if(keys[K_m] and p2.mode == 1):
p2.rocketForce()
# Handle other events as you wish.
screen.fill((250, 250, 250)) # Fill the screen with black.
# Redraw screen here.
### Draw stuff
draw_bg()
space.debug_draw(draw_options)
for i in playerList:
i.tick()
screen.blit(
font.render("P1 Health: " + str(p1.health), True, pygame.Color("white")),
(50, 10),
)
screen.blit(
font.render("P2 Health: " + str(p2.health), True, pygame.Color("white")),
(50, 30),
)
for i in bulletList:
i.tick()
ship_group.draw(screen)
# Flip the display so that the things we drew actually show up.
pygame.display.update()
dt = fpsClock.tick(fps)
space.step(0.01)
pygame.display.update()
runPyGame()
I cant point to the exact error since the code is quite long and depends on files I dont have. But here is a general advice for troubleshooting:
Try to give a name to each shape when you create them, and then print it out. Also print out the name of each shape that you add or remove from the space. This should show which shape you are actually removing and will probably make it easy to understand whats wrong.
For example:
...
self.shape = pymunk.Circle(self.body, radius = self.radius)
self.shape.name = "circle 1"
print("Created", self.shape.name)
...
print("Adding", self.shape.name)
space.add(self.body,self.shape)
...
(Note that you need to reset the name of shapes you copy, since otherwise the copy will have the same name.)
I have the following code. Which basically gets all the images from the folder apps and the subfolders of it. My problem is that I am trying to add a click event to all of the images to do the same thing. Basically "exec("apps/" + apps[app_count] + "/app.py")"
# -*- coding: utf-8 -*-
from pygame import *
import os
import pygame
import time
import random
import sys
_image_library = {}
class SeedOS():
def home(self):
(width, height) = (240, 320)
screen = pygame.display.set_mode((width, height))
pygame.display.set_caption('Seed OS')
pygame.font.init()
Font30 = pygame.font.SysFont('Arial', 30)
WHITE = (255,255,255)
BLACK = (0,0,0)
screen.fill(WHITE)
apps = os.walk("apps").next()[1]
app_count = 0
icon_width = 15
icon_height = 0
max_width = 155
pygame.display.flip()
while True:
while app_count < len(apps):
print apps[app_count]
image = pygame.image.load("apps/" + apps[app_count] + "/app.png").convert()
screen.blit(image, (icon_width, icon_height))
icon_width+=70
if icon_width > max_width:
icon_width = 15
icon_height +=70
app_count += 1
time2 = time.strftime('%H:%M:%S')
pygame.display.flip()
pygame.draw.rect(screen,BLACK,(0,290,240,30))
clock = Font30.render(time2, False, WHITE)
screen.blit(clock,(60,288))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.quit()
phone = SeedOS()
phone.home()
This is the part of the code that checks all of the things in the folder "apps"
while app_count < len(apps):
print apps[app_count]
image = pygame.image.load("apps/" + apps[app_count] + "/app.png").convert()
screen.blit(image, (icon_width, icon_height))
icon_width+=70
if icon_width > max_width:
icon_width = 15
icon_height +=70
app_count += 1
and appends all the images from each folder. I want on every icon click , execute it's "app.py" as in every app folders there are two files: "app.png" and "app.py".
You can add the coordinates of every image in the apps list and then use these coordinates with the pygame.mouse.get_pos() method :
while True:
while app_count < len(apps):
print apps[app_count]
apps[app_count] = (apps[app_count], icon_width, icon_height) # Adding coordinates to the list
image = pygame.image.load("apps/" + apps[app_count][0] + "/app.png").convert() # Adding an index to find the image in the tuple
screen.blit(image, (icon_width, icon_height))
icon_width+=70
if icon_width > max_width:
icon_width = 15
icon_height +=70
app_count += 1
time2 = time.strftime('%H:%M:%S')
pygame.display.flip()
pygame.draw.rect(screen,BLACK,(0,290,240,30))
clock = Font30.render(time2, False, WHITE)
screen.blit(clock,(60,288))
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.quit()
if event.type == pygame.MOUSEBUTTONDOWN:
if event.button == 1: # MOUSEBUTTONLEFT
for a in apps:
if a[1] < pygame.mouse.get_pos()[0] < a[1]+IMAGEWIDTH and a[2] < pygame.mouse.get_pos()[1] < a[2] + IMAGEHEIGHT:
# Instruction to launch ("apps/" + a[0] + "/app.py")
All you have to do is to define is the width and the height from your icons (what you could do with pygame.Surface.get_size() if it's not the same for every app) and to replace the last line with the correct syntax. On windows you could use :
os.system("apps\\"+a[0]+"\\app.py") # of course you should import os first
This question already has answers here:
Why is my PyGame application not running at all?
(2 answers)
Why is nothing drawn in PyGame at all?
(2 answers)
Closed 1 year ago.
Im working on a school project on a motion projectile but my while loop breaks before it ends.
import pygame, sys
from pygame.locals import *
from math import *
def rot_center(image, center_angle):
orig_rect = image.get_rect()
rot_image = pygame.transform.rotate(image, center_angle)
rot_rect = orig_rect.copy()
rot_rect.center = rot_image.get_rect().center
rot_image = rot_image.subsurface(rot_rect).copy()
return rot_image
pygame.init()
FPS = 144
fpsClock = pygame.time.Clock()
SCENE = pygame.display.set_mode((1280, 720), 0, 32)
pygame.display.set_caption('Domača naloga')
backgroundImg = pygame.image.load('images/background.png')
cannonBaseImg = pygame.image.load('images/base.png')
cannonImg = pygame.image.load('images/cannon.png')
ballImg = pygame.image.load('images/cannonBall.png')
enemy = pygame.image.load('images/enemy.png')
cannonBasePos = (9,490)
cannonPos = (-5, 480)
ballPos = (22,510)
enemyPos = (40, 400)
cannonImg = pygame.transform.rotate(cannonImg, -15)
ang = 45
cannonMovImg = rot_center(cannonImg, ang)
# bug: backgoround image dissapears and it bugges green
SCENE.blit(backgroundImg, (0,0))
SCENE.blit(cannonMovImg, cannonPos )
SCENE.blit(ballImg, ballPos)
SCENE.blit(cannonBaseImg, cannonBasePos)
SCENE.blit(enemy, enemyPos)
t = 0
s = ballPos
v = (0, 0)
vm = 100
launched = False
while True: #<-- while starts here
dt = fpsClock.tick(FPS)
if launched:
t = t + dt/250.0 # cajt is clocka
a = (0.0, 10.0) # acceleration
v = (v0[0] + a[0]*t, v0[1] + a[1]*t) # spazz out nad 1000 !!!
vm = sqrt(v[0]*v[0] + v[1]*v[1])
s0 = ballPos # poz
s = (s0[0] + v0[0]*t + a[0]*t*t/2, s0[1] + v0[1]*t + a[1]*t*t/2)
if s[1] >= 510: # tla
launched = False
font = pygame.font.Font(None, 30)
text_ang = font.render("Kot = %d" % ang, 1, (10, 10, 10))
text_ang_pos = (1050, 50)
text_vm = font.render("Hitrost = %.1f m/s" % vm, 1, (10, 10, 10))
text_vm_pos = (1050, 80)
text_stat = font.render("Statistika:", 1, (10, 10, 10))
text_stat_pos = (1050, 20)
text_x = font.render("Dolžina = %.1f m" % s[0], 1, (10, 10, 10))
text_x_pos = (1050, 110)
text_t = font.render("Čas = %.1f s" % t, 1, (10, 10, 10))
text_t_pos = (1050, 140)
SCENE.blit(backgroundImg, (0,0))
SCENE.blit(cannonMovImg, cannonPos)
SCENE.blit(ballImg, s)
SCENE.blit(cannonBaseImg, cannonBasePos)
SCENE.blit(enemy, enemyPos) #<--- while loop breaks here
SCENE.blit(text_t, text_t_pos)
SCENE.blit(text_stat, text_stat_pos)
SCENE.blit(text_vm, text_vm_pos)
SCENE.blit(text_x, text_x_pos)
SCENE.blit(text_ang, text_ang_pos)
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
elif event.type == KEYDOWN:
if event.key == K_SPACE:
ballPos = (0,478)
s = ballPos
t = 0
launched = True
v0 = (vm*cos(radians(ang)), -vm*sin(radians(ang)))
keystate = pygame.key.get_pressed()
if keystate[K_LEFT]:
ang+=2
if ang > 90:
ang = 90
cannonMovImg = rot_center(cannonImg, ang)
if keystate[K_RIGHT]:
ang-=2
if ang < 0:
ang = 0
cannonMovImg = rot_center(cannonImg, ang)
if keystate[K_UP]:
vm+=2
if keystate[K_DOWN]:
vm-=2
pygame.display.flip() #<-- while should end here
I've tried everything but even my teacher doesnt know the anwser. He said it's a bug in Python 3.6.3. Any ideas. I've researched for the past week and im frustrated. If anyone has any ideas please let me know. Thanks for your anwsers in advance
Trying the following code with python 2.7. Basically its a circle that hangs from a bar and an apple that you can hit with an impulse by pressing the spacebar. There is also a square.
import time
import pygame
import pymunk
import pymunk.pygame_util
import sys
pygame.init()
screen = pygame.display.set_mode((800, 600))
clock = pygame.time.Clock()
space = pymunk.Space()
space.gravity = 0, -1000
ball_body = pymunk.Body(100, 100)
ball_body.position = 400.0, 300.0
ball_body.angular_velocity = 10.0
ball_shape = pymunk.Circle(ball_body, 15)
ball_shape.friction = 0.5
ball_shape.elasticity = 0.9
ball_shape.color = (0,0,0,0)
space.add(ball_body, ball_shape)
static_lines = [pymunk.Segment(space.static_body, (20,20), (780,20), 2),
pymunk.Segment(space.static_body, (20,580), (780,580), 2),
pymunk.Segment(space.static_body, (20,20), (20,580), 2),
pymunk.Segment(space.static_body, (780,20), (780,580), 2)]
for static_line in static_lines:
static_line.color = (255,255,255)
static_line.elasticity = 0.9
static_line.friction = 1
space.add(static_lines)
i = 0
prev_body = pymunk.Body(10, 10000)
prev_body.position = (300, 580)
chain_fix_point = pymunk.Body()
chain_fix_point.position = (300, prev_body.position[1])
# Another
i = 0
prev_body = pymunk.Body(10, 10000)
prev_body.position = (600, 580)
chain_fix_point = pymunk.Body()
chain_fix_point.position = (600, prev_body.position[1])
while i < 20:
# rotation_center_body = pymunk.Body()
# rotation_center_body.position = (400, prev_body.position[1] - 20)
body = pymunk.Body(1, 1)
body.position = (600, prev_body.position[1] - 10)
line = pymunk.Circle(body, 5)
line.elasticity = 0
line.friction = 1
if i == 0:
rotation_center_joint = pymunk.PinJoint(body, chain_fix_point)
else:
rotation_center_joint = pymunk.PinJoint(body, prev_body)
space.add(line, body, rotation_center_joint)
prev_body = body
i += 1
blob_body = pymunk.Body(5, 1)
blob_body.position = prev_body.position[0], prev_body.position[1] - 40
blob_shape = pymunk.Circle(blob_body, 20)
rotation_center_joint = pymunk.SlideJoint(blob_body, prev_body,(0,0),(0,0),0,40)
space.add(blob_body, blob_shape, rotation_center_joint)
appleimg = pygame.image.load('apple.png')
box_body = pymunk.Body(10,10000)
box_body.position = 600, 300
box_vertices = [(570, 270),(570, 330),(630,330),(630,270)]
box_shape = pymunk.Poly(box_body, box_vertices, offset=(0, 0), radius=1).create_box(box_body, size = (60,60))
box_shape.friction = 0.5
box_shape.elasticity = 0.9
box_shape.color = (255,0,0)
space.add(box_body, box_shape)
def main():
running = True
angle = 0;
while running == True:
print "game loop"
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
ball_body.apply_impulse(j = (100000, 100000))
screen.fill((0,0,0))
pymunk.pygame_util.draw(screen, space)
if ball_body.angle != 0:
angle += ball_body.angular_velocity
img = pygame.transform.rotate(appleimg, angle)
screen.blit(img, (ball_body.position[0] - 20, 580 - ball_body.position[1]))
pygame.display.flip()
clock.tick(60)
space.step(1/60)
pygame.quit()
quit()
main()
The gameloop runs but the position does not update.
This code worked pretty well for python 3.5. But when I switched to 2.7, its failing.
The problem is that in python 2.x you get 0 when you divide 1 by 60 when you call the step function, since / is doing integer division in 2.x.
You can fix this problem either by importing the python 3 division with
from __future__ import division
Or you can divide by a float instead 1/60.0
Check this question for mor info: In Python 2, what is the difference between '/' and '//' when used for division?