'Sprites don't blit onto surface PyGame
I'm making chess in pygame, but the pieces don't blit onto the surface for them. How could I fix this?
import pygame
pygame.init()
size = (600,600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("chess")
clock = pygame.time.Clock()
chessboard = pygame.image.load("chess_board.png")
whitepawn = pygame.image.load("whitepawn.png")
blackpawn = pygame.image.load("blackpawn.png")
class pawn(pygame.sprite.Sprite):
def __init__(self,colour,x,y):
self.x = x
self.y = y
moved = False
self.colour = colour
pygame.sprite.Sprite.__init__(self)
self.im = pygame.surface.Surface((75,75))
def showpiece(self):
if self.colour == "white":
pygame.Surface.blit(self.im,whitepawn,(self.x,self.y))
elif self.colour == "black":
pygame.Surface.blit(self.im,blackpawn,(self.x,self.y))
num1 = 0
pawns = []
for i in range (8):
pawns.append(pawn("black",0+num1,75))
pawns.append(pawn("white",0+num1,450))
num1 += 75
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
screen.blit(chessboard,[0,0])
for n in range (len(pawns)):
pawns[n].showpiece()
pygame.display.flip()
clock.tick(60)
Also what is the point in clock.tick? I know it controls fps, but why does that need limiting?
Solution 1:[1]
You have to blit the Sprites on the display Surface (screen):
class pawn(pygame.sprite.Sprite):
# [...]
def showpiece(self):
if self.colour == "white":
screen.blit(whitepawn, (self.x,self.y))
elif self.colour == "black":
ecreen.blit(blackpawn, (self.x,self.y))
I suggest to use pygame.Rect to store the positions of the pieces:
import pygame
pygame.init()
size = (600,600)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("chess")
clock = pygame.time.Clock()
chessboard = pygame.image.load("chess_board.png")
whitepawn = pygame.image.load("whitepawn.png")
blackpawn = pygame.image.load("blackpawn.png")
class pawn(pygame.sprite.Sprite):
def __init__(self, colour, image, x, y):
pygame.sprite.Sprite.__init__(self)
self.colour = colour
self.image = image
self.rect = self.image.get_rect(topleft = (x, y))
def showpiece(self, surf):
surf.blit(self.image, self.rect)
pawns = []
for i in range(8):
pawns.append(pawn("black", blackpawn, i*75, 75))
pawns.append(pawn("white", whitepawn, i*75, 450))
run = True
while run :
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
screen.blit(chessboard, (0, 0))
for p in pawns:
p.showpiece(screen)
pygame.display.flip()
clock.tick(60)
pygame.quit()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
