import random,pygame
pygame.init()
s_w=800
s_h=600
screen=pygame.display.set_mode((s_w,s_h))
pygame.display.set_caption("乒乓球")
FPS = 60
win_score=8
clock=pygame.time.Clock()
WHITE=(255,255,255)
BLACK=(0,0,0)
ball_x=s_w//2
ball_y=s_h//2
ball_speed_x=1.5*random.choice((1,-1))
ball_speed_y=1.5*random.choice((1,-1))
ball_r=15
ball_reset_timer=0
p_h=100
p_w=25
p1_x=10
p1_y=(s_h-p_h)/2
p2_x=(s_w-p_w-10)
p2_y=(s_h-p_h)/2-10
try:
font=pygame.font.Font("simhei,ttf",74)
except:
font=pygame.font.Font(None,74)
def reset_ball(direction):
global ball_x,ball_y,ball_speed_x,ball_speed_y
ball_x=s_w//2
ball_y=s_h//2
ball_speed_x=4*direction
ball_speed_y=4*random.choice((1,-1))
ball_rese_timer=0
def check_collision():
global ball_speed_x
if (p1_x+p_w >= ball_x - ball_r and
p1_y <= ball_y <= p1_y + p_h):
ball_speed_x=abs(ball_speed_x)
if (p2_x <= ball_x + ball_r and
p2_y <= ball_y <= p2_y+p_h):
ball_speed_x=-abs(ball_speed_x)
p1_score=0
p2_score=0
game_active=True
winner=None
running=True
while running:
keys=pygame.key.get_pressed()
for evt in pygame.event.get():
if evt.type == pygame.QUIT or keys[pygame.K_ESCAPE]:
running=False
if game_active:
if ball_reset_timer<0:
ball_x+=ball_speed_x
ball_y+=ball_speed_y
else:
ball_reset_timer-=1
if ball_y <ball_r or ball_y+ball_r>s_h:
ball_speed_y *= -1
check_collision()
if keys[pygame.K_w]:
if p1_y >0:
p1_y -=5
if keys[pygame.K_s]:
if p1_y <s_h-p_h:
p1_y +=5
if keys[pygame.K_UP]:
if p2_y >0:
p2_y -=5
if keys[pygame.K_DOWN]:
if p2_y <s_h -p_h :
p2_y +=5
if ball_x<ball_r:
p2_score+=1
reset_ball(1)
if ball_x>s_w:
p1_score+=1
reset_ball(-1)
if p1_score>=win_score:
game_active=False
winner=("p1")
elif p2_score>=win_score:
game_active=False
winner=("p2")
else:
if keys[pygame.K_RETURN]:
p1_score=0
p2_score=0
game_active=True
reset_ball(random.choice((1,-1)))
screen.fill(BLACK)
pygame.draw.circle(screen,WHITE,(ball_x,ball_y),ball_r)
pygame.draw.rect(screen,WHITE,(p1_x,p1_y,p_w,p_h))
pygame.draw.rect(screen,WHITE,(p2_x,p2_y,p_w,p_h))
pygame.draw.aaline(screen,WHITE,(s_w//2,0),(s_w//2,s_h))
test=font.render(str(p1_score),True,WHITE)
screen.blit(test,(s_w//4,10))
test=font.render(str(p2_score),True,WHITE)
screen.blit(test,(3*s_w//4,10))
if not game_active:
end_text=font.render(f"(winner)获胜",True,WHITE)
restart_text=font.render("接空格重新开始",True,WHITE)
screen.blit(end_text,(s_w//2-100,s_h//2-50,))
screen.blit(restart_text,(s_w//2-150,s_h//2+50))
pygame.display.update()
clock.tick(120)
pygame.quit()