import pygame, random, time
def main():
pygame.init()
size =(500,400)
surface=pygame.display.set_mode(size)
pygame.display.set_caption('Pong v1')
game = Game(surface)
game.play()
pygame.quit()
class Game():
def __init__(self,surface):
self.surface=surface
self.FPS=24
self.bg_color=pygame.Color('black')
screen_width = surface.get_width()
screen_height = surface.get_height()
ball_radius=10
ball_pos = [random.randint(ball_radius, screen_width-ball_radius),
random.randint(ball_radius, screen_height-ball_radius)]
ball_color=pygame.Color('white')
ball_velocity=[2,1]
self.ball=Ball(ball_pos,ball_radius,ball_color,ball_velocity,surface)
def draw_score(self):
font_color = pygame.Color("white")
font_bg = pygame.Color("black")
font = pygame.font.SysFont("arial", 72)
text_img = font.render("Score: (not in this version) " + str(self.score), True, font_color, font_bg)
text_pos = (0,0)
self.surface.blit(text_img, text_pos)
def draw(self):
self.surface.fill(self.bg_color)
self.ball.draw()
self.draw_score()
pygame.display.update()
def update(self):
self.ball.move()
self.score=0
def play(self):
while True:
self.draw()
self.update()
class Ball:
def __init__(self,center,radius,color,velocity,surface):
self.center=center
self.radius=radius
self.color=color
self.velocity=velocity
self.surface=surface
def move(self):
screen_width=self.surface.get_width()
screen_height=self.surface.get_height()
screen_size=(screen_width,screen_height)
for i in range(0,len(self.center)):
self.center[i]+=self.velocity[i]
if (self.center[i]<=0 + self.radius or self.center[i]>=screen_size[i] - self.radius):
self.velocity[i]=-self.velocity[i]
def draw(self):
pygame.draw.circle(self.surface,self.color,self.center,self.radius)
main()
因此,我正在尝试创建一个简单的乒乓球,球从窗口边缘弹起。我还需要在屏幕的右侧和左侧创建两个球拍,但是在此版本中,它们不需要反弹球,只有墙才可以。我不知道该怎么实现,由于某种原因,当前代码一直在给我黑屏。有人可以解释一下我将如何创建两个球拍并摆脱黑屏吗?