import math
import random
# 定义球的类
class Ball:
def __init__(self, x, y, radius, color):
self.x = x
self.y = y
self.radius = radius
self.color = color
self.vx = 0
self.vy = 0
def move(self):
self.x += self.vx
self.y += self.vy
def apply_friction(self):
self.vx *= 0.99
self.vy *= 0.99
def check_collision_with_walls(self, table_width, table_height):
if self.x - self.radius < 0 or self.x + self.radius > table_width:
self.vx *= -1
if self.y - self.radius < 0 or self.y + self.radius > table_height:
self.vy *= -1
def __repr__(self):
return f"Ball(x={self.x}, y={self.y}, vx={self.vx}, vy={self.vy})"
# 定义桌球游戏类
class PoolGame:
def __init__(self, width, height):
self.width = width
self.height = height
self.balls = []
self.setup_game()
def setup_game(self):
# 初始化桌球和母球
self.balls.append(Ball(self.width / 2, self.height / 2, 10, 'white'))
def update(self):
for ball in self.balls:
ball.move()
ball.apply_friction()
ball.check_collision_with_walls(self.width, self.height)
def display(self):
for ball in self.balls:
print(ball)
def add_ball(self, x, y, radius, color):
self.balls.append(Ball(x, y, radius, color))
def simulate_shot(self, power, angle):
if self.balls:
shot_ball = self.balls[0] # 假设我们只操作第一个球
shot_ball.vx = power * math.cos(angle)
shot_ball.vy = power * math.sin(angle)
# 游戏主函数
def play_game():
game = PoolGame(800, 400)
game.add_ball(200, 200, 10, 'red') # 添加额外的球作为示例
while True:
print("Enter shot power (0-10) and angle in radians (0-2π):")
try:
power = float(input("Power: "))
angle = float(input("Angle: "))
if power < 0 or power > 10 or angle < 0 or angle > 2 * math.pi:
print("Invalid input. Please enter valid power and angle.")
continue
game.simulate_shot(power, angle)
game.update()
game.display()
except ValueError:
print("Invalid input. Please enter numeric values.")
if __name__ == "__main__":
play_game()