Something is wrong on line 54... I don't know how to fix this...
(builtins.AttributeError: 'Game' object has no attribute 'center')
Help______________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________________
import pygame
def main():
pygame.init()
pygame.display.set_mode((500, 400))
pygame.display.set_caption('Pong')
w_surface = pygame.display.get_surface()
game = Game(w_surface)
game.play()
pygame.quit()
class Game:
def __init__(self, surface):
self.surface = surface
self.bg_color = pygame.Color('black')
self.fg_color = pygame.Color('white')
self.FPS = 60
self.game_Clock = pygame.time.Clock()
self.close_clicked = False
self.continue_game = True
self.small_dot = Dot('white', 10, [10, 10], [2, 2], self.surface)
self.rect1 = pygame.Rect([50,150], [10, 100])
self.rect2 = pygame.Rect([450,150], [10, 100])
self.max_frames = 100000
self.frame_counter = 0
self.score1 = 0
self.score2 = 0
def play(self):
while not self.close_clicked:
self.handle_events()
self.draw()
if self.continue_game:
self.update()
self.decide_continue()
self.game_Clock.tick(self.FPS)
def handle_events(self):
events = pygame.event.get()
for event in events:
if event.type == pygame.QUIT:
self.close_clicked = True
def draw(self):
self.surface.fill(self.bg_color)
self.small_dot.draw()
self.draw_score1()
self.draw_score2()
pygame.draw.rect(self.surface, self.fg_color, self.rect1)
pygame.draw.rect(self.surface, self.fg_color, self.rect2)
pygame.display.update()
def update(self):
self.small_dot.move()
if self.center[0] > 490:
self.score1 += self.score1
self.frame_counter = self.frame_counter + 1
def decide_continue(self):
if self.frame_counter > self.max_frames:
self.continue_game = False
def draw_score1(self):
score_string = 'Score: '+str(self.score1)
score_fg_color = pygame.Color('white')
score_font = pygame.font.SysFont('', 35)
score_image = score_font.render(score_string, True, score_fg_color)
self.surface.blit(score_image, (0, 0))
def draw_score2(self):
score_string = 'Score: '+str(self.score2)
score_fg_color = pygame.Color('white')
score_font = pygame.font.SysFont('', 35)
score_image = score_font.render(score_string, True, score_fg_color)
self.surface.blit(score_image, (400, 0))
class Dot:
def __init__(self, dot_color, dot_radius, dot_center, dot_velocity, surface):
self.color = pygame.Color(dot_color)
self.radius = dot_radius
self.center = dot_center
self.velocity = dot_velocity
self.surface = surface
def move(self):
self.center[0] += self.velocity[0]
self.center[1] += self.velocity[1]
if self.center[0] < 10:
self.velocity[0] = -self.velocity[0]
if self.center[1] < 10:
self.velocity[1] = -self.velocity[1]
if self.center[0] > 490:
self.velocity[0] = -self.velocity[0]
if self.center[1] > 390:
self.velocity[1] = -self.velocity[1]
def draw(self):
pygame.draw.circle(self.surface, self.color, self.center, self.radius)
main()
Indeed your Game class does not have a center. Your Dot does.
Add a center to your Game class in the __init__ function.
Or
Maybe you meant to call self.small_dot.center instead (in line 54)
Related
I would like to use the RubberBand to zoom in and out relative to the size of the box I would like to zoom in the view to fit whatever is inside the block to the full view.
Can anyone help?
The zoom in and out with the mouse works as expected.
You can see in the code the rubberband works but I don't know how to make the zoom relative to the size of the box.
code:
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
import sys
from math import sqrt
class Point(QGraphicsItem):
def __init__(self, x, y):
super(Point, self).__init__()
self.setFlag(QGraphicsItem.ItemIsSelectable, True)
self.rectF = QRectF(0, 0, 30, 30)
self.x=x
self.y=y
self._brush = QBrush(Qt.black)
def setBrush(self, brush):
self._brush = brush
self.update()
def boundingRect(self):
return self.rectF
def paint(self, painter=None, style=None, widget=None):
painter.fillRect(self.rectF, self._brush)
def hoverMoveEvent(self, event):
point = event.pos().toPoint()
print(point)
QGraphicsItem.hoverMoveEvent(self, event)
class Viewer(QGraphicsView):
photoClicked = pyqtSignal(QPoint)
rectChanged = pyqtSignal(QRect)
def __init__(self, parent):
super(Viewer, self).__init__(parent)
self.rubberBand = QRubberBand(QRubberBand.Rectangle, self)
self.setMouseTracking(True)
self.origin = QPoint()
self.changeRubberBand = False
self._zoom = 0
self._empty = True
self._scene = QGraphicsScene(self)
self.setTransformationAnchor(QGraphicsView.AnchorUnderMouse)
self.setResizeAnchor(QGraphicsView.AnchorUnderMouse)
self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
self.setFrameShape(QFrame.NoFrame)
self.area = float()
self.setPoints()
def setItems(self):
self.data = {'x': [-2414943.8686, -2417160.6592, -2417160.6592, -2417856.1783, -2417054.7618, -2416009.9966, -2416012.5232, -2418160.8952, -2418160.8952, -2416012.5232, -2417094.7694, -2417094.7694], 'y': [10454269.7008,
10454147.2672, 10454147.2672, 10453285.2456, 10452556.8132, 10453240.2808, 10455255.8752, 10455183.1912, 10455183.1912, 10455255.8752, 10456212.5959, 10456212.5959]}
maxX = max(self.data['x'])
minX = min(self.data['x'])
maxY = max(self.data['y'])
minY = min(self.data['y'])
distance = sqrt((maxX-minX)**2+(maxY-minY)**2)
self.area = QRectF(minX, minY, distance, distance)
for i,x in enumerate(self.data['x']):
x = self.data['x'][i]
y = self.data['y'][i]
p = Point(x,y)
p.setPos(x,y)
self._scene.addItem(p)
self.setScene(self._scene)
def fitInView(self, scale=True):
rect = QRectF(self.area)
if not rect.isNull():
self.setSceneRect(rect)
unity = self.transform().mapRect(QRectF(0, 0, 1, 1))
self.scale(1 / unity.width(), 1 / unity.height())
viewrect = self.viewport().rect()
scenerect = self.transform().mapRect(rect)
factor = min(viewrect.width() / scenerect.width(),
viewrect.height() / scenerect.height())
self.scale(factor, factor)
self._zoom = 0
def setPoints(self):
self._zoom = 0
self.setItems()
self.setDragMode(True)
self.fitInView()
def wheelEvent(self, event):
if event.angleDelta().y() > 0:
factor = 1.25
self._zoom += 1
else:
factor = 0.8
self._zoom -= 1
if self._zoom > 0:
self.scale(factor, factor)
elif self._zoom == 0:
self.fitInView()
else:
self._zoom = 0
def mousePressEvent(self, event):
if event.button() == Qt.LeftButton:
self.origin = event.pos()
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.rectChanged.emit(self.rubberBand.geometry())
self.rubberBand.show()
self.changeRubberBand = True
return
#QGraphicsView.mousePressEvent(self,event)
elif event.button() == Qt.MidButton:
self.viewport().setCursor(Qt.ClosedHandCursor)
self.original_event = event
handmade_event = QMouseEvent(QEvent.MouseButtonPress,QPointF(event.pos()),Qt.LeftButton,event.buttons(),Qt.KeyboardModifiers())
QGraphicsView.mousePressEvent(self,handmade_event)
super(Viewer, self).mousePressEvent(event)
def mouseReleaseEvent(self, event):
if event.button() == Qt.LeftButton:
self.origin = event.pos()
self.rubberBand.setGeometry(QRect(self.origin, QSize()))
self.changeRubberBand = False
QGraphicsView.mouseReleaseEvent(self,event)
elif event.button() == Qt.MidButton:
self.viewport().setCursor(Qt.OpenHandCursor)
handmade_event = QMouseEvent(QEvent.MouseButtonRelease,QPointF(event.pos()),Qt.LeftButton,event.buttons(),Qt.KeyboardModifiers())
QGraphicsView.mouseReleaseEvent(self,handmade_event)
super(Viewer, self).mouseReleaseEvent(event)
def mouseMoveEvent(self, event):
if self.changeRubberBand:
self.rubberBand.setGeometry(QRect(self.origin, event.pos()).normalized())
self.rectChanged.emit(self.rubberBand.geometry())
QGraphicsView.mouseMoveEvent(self,event)
super(Viewer, self).mouseMoveEvent(event)
class Window(QWidget):
def __init__(self):
super(Window, self).__init__()
self.viewer = Viewer(self)
self.btnLoad = QToolButton(self)
self.btnLoad.setText('Load Points')
self.btnLoad.clicked.connect(self.loadPoints)
VBlayout = QVBoxLayout(self)
VBlayout.addWidget(self.viewer)
HBlayout = QHBoxLayout()
HBlayout.setAlignment(Qt.AlignLeft)
HBlayout.addWidget(self.btnLoad)
VBlayout.addLayout(HBlayout)
def loadPoints(self):
self.viewer.setPoints()
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
window = Window()
window.setGeometry(500, 300, 800, 600)
window.show()
sys.exit(app.exec_())
from tkinter import *
import random
import time
tk = Tk()
tk.title("Game")
tk.resizable(0, 0)
tk.wm_attributes("-topmost", 1)
canvas = Canvas(tk, width=500, height=400, bd=0, highlightthickness=0)
canvas.pack()
tk.update()
class Ball:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
starts = [-3, -2, -1, 1, 2, 3]
random.shuffle(starts)
self.x = starts[0]
self.y = -3
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
def hit_paddle(self, pos):
paddle_pos = self.canvas.coords(self.paddle.id)
if pos[2] >= paddle_pos[0] and pos[0] <= paddle_pos[2]:
if pos[3] >= paddle_pos[1] and pos[3] <= paddle_pos[3]:
return True
return False
def draw(self):
self.canvas.move(self.id, self.x, self.y)
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.y = 3
if pos[3] >= self.canvas_height:
self.y = -3
if self.hit_paddle(pos) == True:
self.y = -3
if pos[0] <= 0:
self.x = 3
if pos[2] >= self.canvas_width:
self.x = -3
class Paddle:
def __init__(self, canvas, paddle, color):
self.canvas = canvas
self.paddle = paddle
self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
self.canvas.move(self.id, 200, 300)
self.x = 0
self.canvas_width = self.canvas.winfo_width()
self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
def draw(self):
self.canvas.move(self.id, self.x, 0)
pos = self.canvas.coords(self.id)
if pos[1] <= 0:
self.x = 0
elif pos[2] >= self.canvas_width:
self.x = 0
def turn_left(self, evt):
self.x = -2
def turn_right(self, evt):
self.x = +2
paddle = Paddle(canvas, 'blue') - line 70 is here
ball = Ball(canvas, paddle, 'red')
while 1:
ball.draw()
paddle.draw()
tk.update_idletasks()
tk.update()
time.sleep(0.015)
I get an error that looks like this:
line 70, in paddle = Paddle(canvas, 'blue') TypeError:
init() missing 1 required positional argument: 'color'
I tried to fix my Paddle class code but it looks fine for me.
Even though I have a color argument in there it still gives me an error
I think you mixed up the constructors for Ball and Paddle. It should be like this.
class Ball:
def __init__(self, canvas, paddle, color):
self.canvas = canvas
self.paddle = paddle
self.id = canvas.create_oval(10, 10, 25, 25, fill=color)
self.canvas.move(self.id, 245, 100)
starts = [-3, -2, -1, 1, 2, 3]
random.shuffle(starts)
self.x = starts[0]
self.y = -3
self.canvas_height = self.canvas.winfo_height()
self.canvas_width = self.canvas.winfo_width()
And
class Paddle:
def __init__(self, canvas, color):
self.canvas = canvas
self.id = canvas.create_rectangle(0, 0, 100, 10, fill=color)
self.canvas.move(self.id, 200, 300)
self.x = 0
self.canvas_width = self.canvas.winfo_width()
self.canvas.bind_all('<KeyPress-Left>', self.turn_left)
self.canvas.bind_all('<KeyPress-Right>', self.turn_right)
And now this will work
paddle = Paddle(canvas, 'blue')
ball = Ball(canvas, paddle, 'red')
i didnt involved my settings here because thats just basic information and stuff my problem in this code is at the threading. the game just lagges extremly when i involve my threads T4 and T5 and i dont know why because i thought threads are like an side code with no efFect on the main code . hope you can help me here thanks!
from settings import *
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH,HEIGHT))
pygame.display.set_caption('Space shoter!')
pygame.display.set_icon(icon)
clock = pygame.time.Clock()
def draw_score(surf, text, size, x, y):
def checkscore():
bossinvinc = False
def draw_healthbar(surf, x, y, pct,maxhp):
def playermovement():
class Player(pygame.sprite.Sprite):
class Mob(pygame.sprite.Sprite):
class Laser(pygame.sprite.Sprite):
class Spawnmeteroits(Thread):
def run(*args):
global spawnthebig
while running:
if meterorfallactv:
for _ in range(random.randint(2, 4)):
m = Mob(tinymeteroit, tinyspeed , tinyHP, tinypoints)
mobs.add(m)
all_sprites.add(m)
time.sleep(1)
if spawnthebig:
spawnthebig = False
m = Mob(bigmeteroit, bigspeed , bigHP, bigpoints)
mobs.add(m)
all_sprites.add(m)
time.sleep(1)
class Spawnmeteroitsmedium(Thread):
def run(*args):
while running:
if meterorfallactv:
time.sleep(3)
for _ in range(random.randint(1, 2)):
m = Mob(mediummeteroit, mediumspeed , mediumHP, mediumpoints)
mobs.add(m)
all_sprites.add(m)
class Shotlaser(Thread):
def run(*args):
while running:
pulscannonXleft = shipcenter - 23
pulscannonXright = shipcenter + 14
pulscannonY = shipbottom - 52
Lleft = Laser(pulscannonXleft,pulscannonY)
Lright = Laser(pulscannonXright,pulscannonY)
lasershotsR.add(Lright)
lasershotsL.add(Lleft)
all_sprites.add(Lleft,Lright)
time.sleep(attackspeed)
heres one of these threads
bossfightstart = False
lethtebosscome = False
class Bossfight(Thread):
def run(*args):
global bossfightstart, lethtebosscome, bossinvinc
while running:
if lethtebosscome:
print('yeye')
bossinvinc = True
boss = Endboss(bosshealth)
all_sprites.add(boss)
stagebossfight.add(boss)
while boss.rect.x > 70:
pass
lethtebosscome = False
bossfightstart = True
bossinvinc = False
Laserabilityoff = False
class Boss_laser(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = laserstart
self.rect = self.image.get_rect()
self.rect.centerx = random.randint(150, 600)
self.mask = pygame.sprite.from_surface(self.image)
if self.rect.centerx <= 170:
self.rect.centery = 170
else:
self.rect.centery = 190
def update(self):
self.rect.y += 10
self.rect = self.image.get_rect()
self.mask = pygame.sprite.from_surface(self.image)
if self.rect.top > HEIGHT:
self.kill()
if Laserabilityoff:
self.kill()
heres one of these threads
class firebosslaser(Thread):
def run(*args):
while running:
if bossfightstart:
global Laserabilityoff
time.sleep(random.randint(4, 7))
for _ in range(random.randint(3, 6)):
BL = Boss_laser()
all_sprites.add(BL)
stagebossfight.add(BL)
time.sleep(3.5) # durating of existence
Laserabilityoff = True
def playergetshit():
global Playerhealth
meterorhits = pygame.sprite.spritecollide(player,mobs,False)
if meterorhits:
truemeterorhits = pygame.sprite.spritecollide(player,mobs,True,pygame.sprite.collide_mask)
for _ in truemeterorhits:
player.HP -= 1
Playerhealth -= 1
def meteroitsgethit():
LaserhitsR = pygame.sprite.groupcollide(mobs, lasershotsR, False, False)
if LaserhitsR:
truelaserhitsR = pygame.sprite.groupcollide(mobs, lasershotsR, False, True,pygame.sprite.collide_mask)
for hit in truelaserhitsR:
hit.health -= LaserDMG
LaserhitsL = pygame.sprite.groupcollide(mobs, lasershotsL, False, False)
if LaserhitsL:
truelaserhitsL = pygame.sprite.groupcollide(mobs, lasershotsL, False, True,pygame.sprite.collide_mask)
for hit in truelaserhitsL:
hit.health -= LaserDMG
class Endboss(pygame.sprite.Sprite):
def __init__(self,bosshp):
global meterorspeed
pygame.sprite.Sprite.__init__(self)
self.image = finalboss
self.rect = self.image.get_rect()
self.HP = bosshp
self.rect.y = 0
self.rect.x = 810
self.mask = pygame.sprite.Sprite(self.image)
meterorspeed = 0
def update(self):
# movement to middle of the screen noch invincible
if self.rect.x > 70:
self.rect.x -= 3.5
self.mask = pygame.sprite.from_surface(self.image)
player = Player(Playerhealth)
healthbarX = player.rect.x - 18
healthbarY = player.rect.y + 69
all_sprites.add(player)
# game loop
running = True
meterorfallactv = True
# thread start
T1 = Spawnmeteroits(daemon = True)
T1.start()
T2 = Shotlaser(daemon = True)
T2.start()
T3 = Spawnmeteroitsmedium(daemon = True)
T3.start()
T4 = Bossfight(daemon = True)
T4.start()
T5 = firebosslaser(daemon = True)
T5.start()
while running:
clock.tick(fps)
screen.fill((40, 40, 40))
screen.blit(background,background_rect)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
playermovement()
all_sprites.update()
playergetshit()
meteroitsgethit()
all_sprites.draw(screen)
draw_healthbar(screen, healthbarX, healthbarY, Playerhealth,PlayerMaxHealth)
checkscore()
pygame.display.flip()
pygame.quit()
i had to disable some of my code because im not allowed to post this much code but its not important the problem is with the threads
In Bossfight, you have this:
while boss.rect.x > 70:
pass
That's a "busy loop"; the interpreter will basically stop there, but will continuously check boss.rect.x > 70. Replace pass with a short sleep to keep it from eating too much CPU.
firebosslaser has a similar problem: If bossfightstart is False, it will loop forever. Add else: time.sleep(5) after that loop and you should be OK.
import pygame
import random
from os import path
img_dir = path.join(path.dirname(__file__), 'img')
snd_dir = path.join(path.dirname(__file__), 'sound')
WIDTH = 800
HEIGHT = 600
FPS = 50
WHITE=(255, 255, 255)
BLACK=(0, 0, 0)
RED=(255, 0, 0)
GREEN=(0, 255, 0)
BLUE=(0, 0, 255)
YELLOW=(255, 255, 0)
pygame.init()
pygame.mixer.init()
screen = pygame.display.set_mode((WIDTH, HEIGHT))
pygame.display.set_caption("My Game")
clock = pygame.time.Clock()
font_name = pygame.font.match_font('arial')
end = True
def start_screen():
draw_text(screen, "SPACE SHOOTING", 70, WIDTH/2, HEIGHT/4)
draw_text(screen, "INSTRUCTIONS", 25, WIDTH/2, HEIGHT/2)
draw_text(screen, "Press Left arrow key to move left", 20, WIDTH/2, HEIGHT*2/3.5)
draw_text(screen, "Press Right arrow key to move right", 20, WIDTH/2, HEIGHT*2/3.3)
draw_text(screen, "Spacebar to shoot", 20, WIDTH/2, HEIGHT*2/3.1)
draw_text(screen, "Press a key to begin", 20, WIDTH/2, HEIGHT*3/4)
pygame.display.flip()
wait = True
while wait:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYUP:
if event.key == pygame.K_SPACE:
wait = False
def draw_text(surf, text, size, x, y):
font = pygame.font.Font(font_name, size)
text_surface = font.render(text, True, WHITE)
text_rect = text_surface.get_rect()
text_rect.midtop = (x, y)
surf.blit(text_surface, text_rect)
class Player(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.transform.scale(player_img, (50, 38))
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = 20
self.rect.centerx = WIDTH/2
self.rect.bottom = HEIGHT - 10
self.speedx = 0
def update(self):
self.speedx = 0
keystate = pygame.key.get_pressed()
if keystate[pygame.K_LEFT]:
self.speedx = -5
if keystate[pygame.K_RIGHT]:
self.speedx = 5
self.rect.x += self.speedx
if self.rect.right > WIDTH:
self.rect.right = WIDTH
if self.rect.left < 0:
self.rect.left = 0
def shoot(self):
bullet = Bullets(self.rect.centerx, self.rect.top)
all_sprites.add(bullet)
bullets.add(bullet)
class Aliens(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = aliens_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width*.85/2)
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
def update(self):
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
class SuperAliens(pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.__init__(self)
self.image = superaliens_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.radius = int(self.rect.width*.85/2)
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
self.speedx = random.randrange(-3, 3)
def update(self):
self.rect.x += self.speedx
self.rect.y += self.speedy
if self.rect.top > HEIGHT + 10 or self.rect.left < -25 or self.rect.right > WIDTH + 20:
self.rect.x = random.randrange(WIDTH - self.rect.width)
self.rect.y = random.randrange(-100, -40)
self.speedy = random.randrange(1, 8)
def shoot1(self):
sbullet = SBullets(self.rect.centerx, self.rect.bottom)
all_sprites.add(sbullet)
bullets.add(sbullet)
class SBullets(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = sbullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = +10
def update(self):
self.rect.y += self.speedy
if self.rect.top < 0:
self.kill()
class Bullets(pygame.sprite.Sprite):
def __init__(self, x, y):
pygame.sprite.Sprite.__init__(self)
self.image = bullet_img
self.image.set_colorkey(BLACK)
self.rect = self.image.get_rect()
self.rect.bottom = y
self.rect.centerx = x
self.speedy = -10
def update(self):
self.rect.y += self.speedy
if self.rect.bottom < 0:
self.kill()
class Explode(pygame.sprite.Sprite):
def __init__(self, center, size):
pygame.sprite.Sprite.__init__(self)
self.size = size
self.image = explode[self.size][0]
self.rect = self.image.get_rect()
self.rect.center = center
self.frame = 0
self.last_update = pygame.time.get_ticks()
self.frame_rate = 2
def update(self):
now = pygame.time.get_ticks()
if now - self.last_update > self.frame_rate:
self.last_update = now
self.frame += 1
if self.frame == len(explode[self.size]):
self.kill()
else:
center = self.rect.center
self.image = explode[self.size][self.frame]
self.rect = self.image.get_rect()
self.rect.center = center
background = pygame.image.load(path.join(img_dir, "back.png")).convert()
background_rect = background.get_rect()
player_img = pygame.image.load(path.join(img_dir, "playerShip2_blue.png")).convert()
superaliens_img = pygame.image.load(path.join(img_dir, "enemyBlack4.png")).convert()
aliens_img = pygame.image.load(path.join(img_dir, "enemyBlack1.png")).convert()
bullet_img = pygame.image.load(path.join(img_dir, "laserRed16.png")).convert()
sbullet_img = pygame.image.load(path.join(img_dir, "laserRed11.png")).convert()
explode = {}
explode['super']=[]
explode['small']=[]
for i in range(9):
filename = 'regularExplosion02.png'.format(1)
img = pygame.image.load(path.join(img_dir, filename)).convert()
img.set_colorkey(BLACK)
img_super = pygame.transform.scale(img, (75, 75))
explode ['super'].append(img_super)
img_small = pygame.transform.scale(img, (32, 32))
explode ['small'].append(img_small)
#pygame.mixer.music.load(path.join(snd_dir, 'Orbital.mp3'))
#pygame.mixer.music.set_volume(0.4)
#pygame.mixer.music.play(loops=-1)
end_game = True
running = True
while running:
if end_game:
start_screen()
end_game = False
all_sprites = pygame.sprite.Group()
aliens = pygame.sprite.Group()
superaliens = pygame.sprite.Group()
bullets = pygame.sprite.Group()
sbullets = pygame.sprite.Group()
player = Player()
all_sprites.add(player)
for i in range(5):
m = Aliens()
all_sprites.add(m)
aliens.add(m)
for j in range(1):
n = SuperAliens()
all_sprites.add(n)
superaliens.add(n)
score = 0
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE:
player.shoot()
all_sprites.update()
hits = pygame.sprite.groupcollide(aliens, bullets, True, True)
for hit in hits:
score += 1
m = Aliens()
expl = Explode(hit.rect.center, 'small')
all_sprites.add(expl)
all_sprites.add(m)
aliens.add(m)
hits = pygame.sprite.groupcollide(superaliens, bullets, True, True)
for hitt in hits:
score += 5
n = SuperAliens()
expl1 = Explode(hitt.rect.center, 'super')
all_sprites.add(expl1)
all_sprites.add(n)
superaliens.add(n)
hits = pygame.sprite.spritecollide(player, aliens, True)
for hit in hits:
expl = Explode(hit.rect.center, 'small')
all_sprites.add(expl)
if hits:
end_game = True
hits = pygame.sprite.spritecollide(player, superaliens, True)
for hitt in hits:
expl1 = Explode(hitt.rect.center, 'super')
all_sprites.add(expl1)
if hits:
end_game = True
screen.fill(BLACK)
screen.blit(background, background_rect)
all_sprites.draw(screen)
draw_text(screen,"SCORE" +str(score), 22, WIDTH/2, 10)
#after drwing everything flip the display
pygame.display.flip()
pygame.quit()
Sorry for the bad formatting but couldn't upload it with the proper formatting. Its my first pygame, so im not good in it. The program is working good, but every time when i close the window, its is showing me this error.
Traceback (most recent call last):
File "/Users/Documents/game.py", line 221, in
start_screen()
File "/Users/Documents/game.py", line 41, in start_screen
for event in pygame.event.get():
pygame.error: video system not initialized
I was also trying to make the super aliens shoot randomly towards the player, and that thing is not working as well.A little help would be appreciated. Thanks
After the line:
pygame.quit()
put:
exit()
Basically, pygame.quit() tells pygame that you are done with it. After you call it in your event loop, pygame no longer can draw things to the screen, but you still try to make it do so later in your program. Calling exit() makes python exit so that pygame is not told to draw anything.
I created a rectangle in the middle of the window, and used key 'w', 's', 'a', 'd', to move it. My problem is every time the rectangle hits the edge of the window is becomes stuck and cannot move any more.
import pygame, sys, time
from pygame.locals import *
class Tile:
bcolor = pygame.Color('black')
rcolor = pygame.Color('white')
def __init__(self, surface):
self.surface = surface
self.size = 30
self.x = self.surface.get_width()//2 - self.size//2
self.y = self.surface.get_height()//2 - self.size//2
self.rect = pygame.Rect(self.x, self.y, self.size, self.size)
self.speed = 10
self.rcolor = Tile.rcolor
self.bcolor = Tile.bcolor
def draw(self):
pygame.draw.rect(self.surface, self.rcolor, self.rect)
def moveup(self):
if self.rect.top < self.speed:
self.speed = self.rect.top
self.rect.move_ip(0, -self.speed)
def movedown(self):
maxbottom = self.surface.get_height()
if maxbottom - self.rect.bottom < self.speed:
self.speed = maxbottom - self.rect.bottom
self.rect.move_ip(0,self.speed)
def moveleft(self):
if self.rect.left < self.speed:
self.speed = self.rect.left
self.rect.move_ip(-self.speed, 0)
def moveright(self):
maxright = self.surface.get_width()
if maxright - self.rect.right < self.speed:
self.speed = maxright - self.rect.right
self.rect.move_ip(self.speed, 0)
def handlekeydown(self, key):
if key == K_w:
self.moveup()
if key == K_s:
self.movedown()
if key == K_a:
self.moveleft()
if key == K_d:
self.moveright()
def update(self):
self.surface.fill(self.bcolor)
self.draw()
def main():
pygame.init()
pygame.key.set_repeat(20, 20)
surfacesize = (500,400)
title = 'Practice'
framedelay = 0.02
surface = pygame.display.set_mode(surfacesize, 0, 0)
pygame.display.set_caption(title)
tile = Tile(surface)
gameover = False
tile.draw()
pygame.display.update()
while True:
for event in pygame.event.get():
if event.type == QUIT:
pygame.quit()
sys.exit()
if event.type == KEYDOWN and not gameover:
tile.handlekeydown(event.key)
tile.update()
pygame.display.update()
time.sleep(framedelay)
main()
Just look at this piece of code:
def moveup(self):
if self.rect.top < self.speed:
self.speed = self.rect.top
self.rect.move_ip(0, -self.speed)
Once you move to the top of the screen, self.rect.top becomes 0, which is smaller than self.speed, so the condition of the if statement is True and in the next line you set self.speed to 0, hence all your move_ip calls won't move the Rect (because self.speed is now 0).
If you want to prevent the Rect from leaving the screen, better just use clamp_ip:
...
def moveup(self):
self.rect.move_ip(0, -self.speed)
def movedown(self):
self.rect.move_ip(0,self.speed)
def moveleft(self):
self.rect.move_ip(-self.speed, 0)
def moveright(self):
self.rect.move_ip(self.speed, 0)
def handlekeydown(self, key):
if key == K_w:
self.moveup()
if key == K_s:
self.movedown()
if key == K_a:
self.moveleft()
if key == K_d:
self.moveright()
self.rect.clamp_ip(pygame.display.get_surface().get_rect())
...
(There are some other issues with your code, but that's another topic.)