[英]Bug using pygame where my sprite won't appear on screen
I'm at the very beginning of a chess program and want to print the board on the screen. 我刚开始国际象棋程序,想在屏幕上打印棋盘。 However, I am having trouble at the first hurdle and cannot even get it to print the squares of the board.
但是,我遇到了第一个障碍,甚至无法用它来印刷木板的正方形。 It just comes up with a black screen and doesn't put the sprite on it.
它只是带有一个黑屏,没有在其上放置精灵。
I've tried looking at some code from a previous project where it worked, but I can't find any differences in this part of the program. 我曾尝试查看先前项目在其中起作用的一些代码,但在程序的这一部分中找不到任何区别。
import pygame
import os
import time
pygame.init()
WHITE = (0, 30, 0)
BLACK = (200, 200, 200)
screen_width = 1400
screen_height = 800
square_size = screen_height/10
screen = pygame.display.set_mode([screen_width, screen_height])
os.environ['SDL_VIDEO_WINDOWS_POS'] = '10,10'
class square(pygame.sprite.Sprite):
def __init__(self, colour, x, y):
super().__init__()
self.image = pygame.Surface([square_size, square_size])
pygame.draw.rect(self.image, colour, [0, 0, square_size, square_size])
self.colour = colour
self.rect = self.image.get_rect()
squares = pygame.sprite.Group()
s = square(WHITE, 20, 20)
squares.add(s)
squares.draw(screen)
time.sleep(3)
I would expect this to output one white square in the top left hand corner of the screen, but only a black screen appears. 我希望这会在屏幕的左上角输出一个白色的正方形,但是只会出现一个黑色的屏幕。
最有可能的问题是,您没有翻转/更新屏幕。
You need an event.get
loop, and to update your display using pygame.display.update()
after the squares.draw(screen)
: 您需要一个
event.get
循环,并在squares.draw(screen)
之后使用pygame.display.update()
更新显示内容:
import pygame
import os
import time
pygame.init()
WHITE = (0, 30, 0)
BLACK = (200, 200, 200)
screen_width = 1400
screen_height = 800
square_size = screen_height/10
screen = pygame.display.set_mode([screen_width, screen_height])
os.environ['SDL_VIDEO_WINDOWS_POS'] = '10,10'
class square(pygame.sprite.Sprite):
def __init__(self, colour, x, y):
super().__init__()
self.image = pygame.Surface([square_size, square_size])
pygame.draw.rect(self.image, colour, [0, 0, square_size, square_size])
self.colour = colour
self.rect = self.image.get_rect()
for event in pygame.event.get():
pass
squares = pygame.sprite.Group()
s = square(WHITE, 20, 20)
squares.add(s)
squares.draw(screen)
pygame.display.update()
time.sleep(3)
Also note, an RGB value of (0, 30, 0)
is not white, it's a dark green, if you want bright white try (255, 255, 255)
. 还要注意,如果您要尝试明亮的白色尝试
(255, 255, 255)
,则RGB值(0, 30, 0)
不是白色,而是深绿色。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.