操场上……
“小何,接球!”小方喊道。
咻!“球要进了!“小何说。
啊!不好!被防住了!
结束后……
小方:“小何,你会编出进球游戏吗?现实踢球,太没意思。”
小何:“会啊!”
“让我看看!”
“啊,我才得五分就没了。”
“是呀,所以只能射到球门里。”
“我把代码给你,你回去玩。”
import pygame
import random
# 初始化Pygame
pygame.init()
# 设置屏幕尺寸和背景颜色
screen_width = 800
screen_height = 400
background_color = (255, 255, 255)
# 设置球的属性
ball_radius = 20
ball_color = (255, 0, 0)
ball_speed = 5
# 设置球门的属性
gate_width = 10
gate_height = 100
gate_color = (0, 0, 255)
# 创建屏幕对象
screen = pygame.display.set_mode((screen_width, screen_height))
pygame.display.set_caption("进球游戏")
clock = pygame.time.Clock()
# 初始化球和球门的位置
ball_x = ball_radius
ball_y = screen_height // 2
ball_dx = 0
ball_dy = 0
gate_x = screen_width - gate_width
gate_y = screen_height // 2 - gate_height // 2
score = 0
running = True
game_start = False
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_SPACE and not game_start:
# 发射球
ball_dx = ball_speed
game_start = True
keys = pygame.key.get_pressed()
if keys[pygame.K_UP] and not game_start:
ball_y -= ball_speed
elif keys[pygame.K_DOWN] and not game_start:
ball_y += ball_speed
if keys[pygame.K_LEFT] and game_start:
ball_dx = -ball_speed
elif keys[pygame.K_RIGHT] and game_start:
ball_dx = ball_speed
# 移动球
ball_x += ball_dx
ball_y += ball_dy
# 检测球的碰撞和边界
if ball_y < 0 or ball_y > screen_height - ball_radius:
ball_dy = 0
if ball_x < 0:
ball_x = ball_radius
if ball_x + ball_radius >= gate_x and ball_y >= gate_y and ball_y <= gate_y + gate_height:
score += 1
ball_dx = 0
ball_dy = 0
ball_x = ball_radius
game_start = False
screen.fill(background_color)
# 画球
pygame.draw.circle(screen, ball_color, (ball_x, ball_y), ball_radius)
# 画球门
pygame.draw.rect(screen, gate_color, (gate_x, gate_y, gate_width, gate_height))
# 绘制分数
font = pygame.font.Font(None, 36)
score_text = font.render("Score: " + str(score), True, (0, 0, 0))
screen.blit(score_text, (10, 10))
pygame.display.flip()
# 控制游戏速度
clock.tick(60)
pygame.quit()
“哦吼吼!耶”