import pygame, sys,random
# 控制球的反弹
def ball_animation():
global ball_speed_x,ball_speed_y
ball.x += ball_speed_x
ball.y += ball_speed_y
if ball.top <= 0 or ball.bottom >= screen_height:
ball_speed_y *= -1
if ball.left <= 0 or ball.right >= screen_width:
ball_restart()
if ball.colliderect(player) or ball.colliderect(opponent):
ball_speed_x *= -1
# 控制挡板不能超过屏幕
def player_animation():
player.y += player_speed
if player.top <= 0:
player.top = 0
if player.bottom >= screen_height:
player.bottom = screen_height
# 挡板的AI行动
def opponent_ai():
if opponent.top < ball.y:
opponent.top += opponent_speed
if opponent.bottom > ball.y:
opponent.bottom -= opponent_speed
if opponent.top <= 0:
opponent.top = 0
if opponent.bottom >= screen_height:
opponent.bottom = screen_height
# 游戏结束后重启
def ball_restart():
global ball_speed_x,ball_speed_y
# 如果球撞到了屏幕,那么就回到起点,再继续移动
ball.center = (screen_width/2,screen_height/2)
ball_speed_y *= random.choice((1,-1))
ball_speed_x *= random.choice((1,-1))
pygame.init()
clock = pygame.time.Clock()
screen_width = 1280
screen_height = 960
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption('Pong')
ball = pygame.Rect(screen_width / 2 - 15, screen_height / 2 - 15, 30, 30) # 创建一个矩形,前两个是他距离左边上面的位置,后面两个是宽高
player = pygame.Rect(screen_width - 20, screen_height / 2 - 70, 10, 140)
opponent = pygame.Rect(10, screen_height / 2 - 70, 10, 140)
bg_color = pygame.Color('grey12')
light_grey = (200, 200, 200)
ball_speed_x = 7 * random.choice((1,-1))
ball_speed_y = 7 * random.choice((1,-1))
player_speed = 0
opponent_speed = 7
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_DOWN:
player_speed += 7
if event.key == pygame.K_UP:
player_speed -= 7
if event.type == pygame.KEYUP:
if event.key == pygame.K_DOWN:
player_speed -= 7
if event.key == pygame.K_UP:
player_speed += 7
ball_animation()
player_animation()
opponent_ai()
screen.fill(bg_color)
# rect(Surface, color, Rect, width=0) -> Rect
# 在Surface对象上绘制一个矩形。Surface绘制在哪里
# rect代表你要绘制图像的参数,宽高和位置
# color指定颜色。
# width参数指定边框的宽度,如果设置为0则表示填充该矩形。
pygame.draw.rect(screen, light_grey, player)
pygame.draw.rect(screen, light_grey, opponent)
# ellipse 椭圆的意思
# 椭圆,参数:操作对象,颜色(RGB数组),外接矩形的左上角和右下角坐标,宽度
# 如果不填宽度,则会填充椭圆
# pygame.draw.ellipse(screen, (0, 255, 0), (0, 0, 200, 300),width=1)
pygame.draw.ellipse(screen, light_grey, ball)
# pygame.draw.aaline(Surface,color,start_pos,end_pos,blend=1)
# Surface可以理解为该直线完毕显示在哪个surface上
# color直线的颜色,为RGB三元组或RGBA四元组
# start_pos,end_pos分别为直线的起点坐标和终点坐标均为二元组
# width为直线的宽度,默认为1
# blend为是否打开直线边缘的融合效果,一般不对其设置使用其默认值
pygame.draw.aaline(screen, light_grey, (screen_width / 2, 0), (screen_width / 2, screen_height))
pygame.display.update()
clock.tick(60)
一百行代码教你用Python,pygame做个弹乒乓小游戏
最新推荐文章于 2024-07-21 23:25:11 发布