python代码实现中式桌球游戏

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()
 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值