乒乓球比赛模拟python
时间: 2023-07-05 18:28:23 浏览: 44
好的,我可以帮你实现一个简单的乒乓球比赛模拟程序。你可以参考以下代码:
```python
import random
class Paddle:
def __init__(self, name):
self.name = name
self.score = 0
def win_point(self):
self.score += 1
class Ball:
def __init__(self):
self.x = 0
self.y = 0
self.vx = 1
self.vy = 1
def move(self):
self.x += self.vx
self.y += self.vy
def bounce(self):
self.vy = -self.vy
class PingPongGame:
def __init__(self, player1, player2):
self.player1 = player1
self.player2 = player2
self.ball = Ball()
def play(self):
while True:
print("Score: {} - {}".format(self.player1.score, self.player2.score))
print("Player {}'s serve...".format(random.choice([1, 2])))
while True:
self.ball.move()
print("Ball position: ({}, {})".format(self.ball.x, self.ball.y))
if self.ball.y == 0 or self.ball.y == 4:
self.ball.bounce()
elif self.ball.x == 0:
print("Player 2 wins the point!")
self.player2.win_point()
break
elif self.ball.x == 5:
print("Player 1 wins the point!")
self.player1.win_point()
break
elif self.ball.y == 1 and self.ball.x == 1:
print("Player 1 hits the ball!")
self.ball.vx = 1
self.ball.bounce()
elif self.ball.y == 2 and self.ball.x == 4:
print("Player 2 hits the ball!")
self.ball.vx = -1
self.ball.bounce()
if self.player1.score == 11 or self.player2.score == 11:
break
print("Game over! Final score: {} - {}".format(self.player1.score, self.player2.score))
player1 = Paddle("1")
player2 = Paddle("2")
game = PingPongGame(player1, player2)
game.play()
```
这个程序模拟了乒乓球比赛的过程,其中包括球的移动、反弹和击打,以及得分和比赛结束的判断。你可以根据需要进行修改和扩展。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)