import random
import pygame
# 初始化
pygame.init()
# 设置窗口大小
screen_width = 1000
screen = pygame.display.set_mode((screen_width, 600))
# 设置窗口标题
rect1_x, rect1_y = screen_width - 20, 100
rect2_x, rect2_y = 0, 100
pygame.key.set_repeat(100, 1) # 每隔1毫秒发送一个按键
ball_x, ball_y = 390, 290
direction = "right"
y_speed = random.randint(-3, 3) * random.random()
x_speed = 1
# 设置字体
font = pygame.font.Font('ziti.ttf', 30)
# 小球颜色
ball_r, ball_g, ball_b = random.randint(0, 255), random.randint(0, 255), random.randint(0, 255)
ball = pygame.image.load("ball.bmp")
# 得分
harry_score = 0
juven_score = 0
while True:
# 第14-17行:用来判断我们是否点了退出
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_UP:
rect1_y -= 10
elif event.key == pygame.K_DOWN:
rect1_y += 10
if event.key == pygame.K_w:
rect2_y -= 10
elif event.key == pygame.K_s:
rect2_y += 10
screen.fill((190, 190, 190))
if rect1_y > 550:
rect1_y = 550
elif rect1_y < -50:
rect1_y = -50
if rect2_y > 550:
rect2_y = 550
elif rect2_y < -50:
rect2_y = -50
ball_x += x_speed
ball_y += y_speed
if ball_y < 0:
y_speed = random.randint(0, 1) * random.random()
elif ball_y > 600:
y_speed = random.randint(-1, 0) * random.random()
if ball_x > screen_width:
x_speed = -1
elif ball_x < 0:
x_speed = 1
# 判断harry得分
if rect2_y < ball_y < rect2_y + 100 and 0<ball_x<20:
harry_score += 1
x_speed = 1
ball_x = 20
# 判断juven得分
if rect1_y < ball_y < rect1_y + 100 and screen_width-20<ball_x+30<screen_width:
juven_score += 1
x_speed = -1
ball_x = screen_width-100
# 设置文字
imgtext = font.render('harry分数:%d'%harry_score, True, (255, 255, 0))
screen.blit(imgtext, (0, 0))
imgtext2 = font.render('juven分数:%d'%juven_score, True, (255, 255, 0))
screen.blit(imgtext2, (700, 0))
# 画一个长方形的条条
pygame.draw.rect(screen, (0, 0, 0), (rect1_x, rect1_y, 20, 100))
pygame.draw.rect(screen, (0, 0, 0), (rect2_x, rect2_y, 20, 100))
# pygame.draw.rect(screen, (ball_r, ball_g, ball_b), c, 20, 20))
screen.blit(ball,(ball_x,ball_y))
# 循环刷新窗口
pygame.display.update()
# 退出
harry -双人对战游戏
最新推荐文章于 2023-05-30 14:34:19 发布