Crossin的编程教室

标题: 求助!初学python,这个代码怎么在pygame里面运行不起来呢? [打印本页]

作者: pickle    时间: 2019-7-7 22:48
标题: 求助!初学python,这个代码怎么在pygame里面运行不起来呢?
代码如下:
这是《与孩子一起学编程》这本书里面的17-2代码清单,在SPE里面运行就显示黑框,是为什么呀?
import sys, pygame
from random import *

class MyBallClass(pygame.sprite.Sprite):
    def __init__(self, image_file, location, speed):
        pygame.sprite.Sprite.__init__(self)
        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):
        self.rect = self.rect.move(self.speed)
        if self.rect.left < 0 or self.rect.right > width:
            self.speed[0] = - self.speed[0]

        if self.rect.top < 0 or self.rect.bottom > height:
            self.speed[1] = -self.speed[1]

size = width, height = 640, 480
screen = pygame.display.set_mode(size)
screen.fill([255,255,255])
img_file = "beach_ball.png"
balls = []
for row in range (0, 3):
    for column in range (0, 3):
        location = [column*180 + 10, row*180 + 10]
        speed = [choice([-2, 2]), choice([-2, 2])]
        ball = MyBallClass(img_file, location, speed)
        balls.append(ball)

while True:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            sys.exit()
pygame.time.delay(20)
screen.fill([255,255,255])
for ball in balls:
    ball.move()
    screen.blit(ball.image, ball.rect)
pygame.display.flip()





2019-07-07.png (273.71 KB, 下载次数: 459)

截屏

截屏


作者: crossin先生    时间: 2019-7-8 23:16
pygame.time.delay(20)
screen.fill([255,255,255])
for ball in balls:
    ball.move()
    screen.blit(ball.image, ball.rect)
pygame.display.flip()

这一段的缩进不对,他应该是在主循环里的。放外面肯定不显示咯,主循环里啥都没有
但我不知道你是不是贴上来时候错了

然后出问题后两个建议:
1,可以控制台下直接运行试试
2,可以换几张图片试试




欢迎光临 Crossin的编程教室 (https://bbs.crossincode.com/) Powered by Discuz! X2.5