In: Computer Science
In python please:
You’re going to program a simulation of the following game. Like many probability games, this one involves an infinite supply of ping-pong balls. No, this game is "not quite beer pong."
The balls are numbered 1 through N. There is also a group of N cups, labeled 1 through N, each of which can hold an unlimited number of ping-pong balls (a;ll numbered 1 through N). The game is played in rounds. A round is composed of two phases: throwing and pruning.
Every ball drawn has a uniformly random number, every ball lands in a uniformly random cup, and every throw lands in some cup. The game is over when, after a round is completed, there are no empty cups.
At the end of the simulation you will print the following:
How many rounds would you expect to need to play to finish this game?
How many balls did you draw and throw to finish this game?
Sort the cups in descending order by the number of balls they hold.
import
math
import
pygame
import
random
# Define some colors
BLACK
=
(
0
,
0
,
0
)
WHITE
=
(
255
,
255
,
255
)
# This class represents the ball
# It derives from the "Sprite" class in Pygame
class
Ball(pygame.sprite.Sprite):
# Constructor. Pass in the color of the block, and its x
and y position
def
__init__(
self
):
# Call the parent class (Sprite) constructor
super
().__init__()
# Create the image of the ball
self
.image
=
pygame.Surface([
10
,
10
])
# Color the ball
self
.image.fill(WHITE)
# Get a rectangle object that shows where our image
is
self
.rect
=
self
.image.get_rect()
# Get attributes for the height/width of the
screen
self
.screenheight
=
pygame.display.get_surface().get_height()
self
.screenwidth
=
pygame.display.get_surface().get_width()
# Speed in pixels per cycle
self
.speed
=
0
# Floating point representation of where the ball
is
self
.x
=
0
self
.y
=
0
# Direction of ball in degrees
self
.direction
=
0
# Height and width of the ball
self
.width
=
10
self
.height
=
10
# Set the initial ball speed and position
self
.reset()
def
reset(
self
):
self
.x
=
random.randrange(
50
,
750
)
self
.y
=
350.0
self
.speed
=
8.0
# Direction of ball (in degrees)
self
.direction
=
random.randrange(
-
45
,
45
)
# Flip a 'coin'
if
random.randrange(
2
)
=
=
0
:
# Reverse ball direction, let the other guy get it
first
self
.direction
+
=
180
self
.y
=
50
# This function will bounce the ball off a horizontal
surface (not a vertical one)
def
bounce(
self
,diff):
self
.direction
=
(
180
-
self
.direction)
%
360
self
.direction
-
=
diff
# Speed the ball up
self
.speed
*
=
1.1
# Update the position of the ball
def
update(
self
):
# Sine and Cosine work in degrees, so we have to convert
them
direction_radians
=
math.radians(
self
.direction)
# Change the position (x and y) according to the speed and
direction
self
.x
+
=
self
.speed
*
math.sin(direction_radians)
self
.y
-
=
self
.speed
*
math.cos(direction_radians)
if
self
.y <
0
:
self
.reset()
if
self
.y >
600
:
self
.reset()
# Move the image to where our x and y are
self
.rect.x
=
self
.x
self
.rect.y
=
self
.y
# Do we bounce off the left of the screen?
if
self
.x
<
=
0
:
self
.direction
=
(
360
-
self
.direction)
%
360
print
(
self
.direction)
#self.x=1
# Do we bounce of the right side of the screen?
if
self
.x >
self
.screenwidth
-
self
.width:
self
.direction
=
(
360
-
self
.direction)
%
360
# This class represents the bar at the bottom that the
player controls
class
Player(pygame.sprite.Sprite):
# Constructor function
def
__init__(
self
,
joystick, y_pos):
# Call the parent's constructor
super
().__init__()
self
.width
=
75
self
.height
=
15
self
.image
=
pygame.Surface([
self
.width,
self
.height])
self
.image.fill(WHITE)
self
.joystick
=
joystick
# Make our top-left corner the passed-in
location.
self
.rect
=
self
.image.get_rect()
self
.screenheight
=
pygame.display.get_surface().get_height()
self
.screenwidth
=
pygame.display.get_surface().get_width()
self
.rect.x
=
0
self
.rect.y
=
y_pos
# Update the player
def
update(
self
):
# This gets the position of the axis on the game
controller
# It returns a number between -1.0 and +1.0
horiz_axis_pos
=
self
.joystick.get_axis(
0
)
# Move x according to the axis. We multiply by 15 to speed
up the movement.
self
.rect.x
=
int
(
self
.rect.x
+
horiz_axis_pos
*
15
)
# Make sure we don't push the player paddle off the right
side of the screen
if
self
.rect.x >
self
.screenwidth
-
self
.width:
self
.rect.x
=
self
.screenwidth
-
self
.width
score1
=
0
score2
=
0
# Call this function so the Pygame library can initialize
itself
pygame.init()
# Create an 800x600 sized screen
screen
=
pygame.display.set_mode([
800
,
600
])
# Set the title of the window
pygame.display.set_caption(
'Pong'
)
# Enable this to make the mouse disappear when over our
window
pygame.mouse.set_visible(
0
)
# This is a font we use to draw text on the screen (size
36)
font
=
pygame.font.Font(
None
,
36
)
# Create a surface we can draw on
background
=
pygame.Surface(screen.get_size())
# Create the ball
ball
=
Ball()
# Create a group of 1 ball (used in checking
collisions)
balls
=
pygame.sprite.Group()
balls.add(ball)
# Count the joysticks the computer has
joystick_count
=
pygame.joystick.get_count()
if
joystick_count <
1
:
# No joysticks!
print
(
"Error, I didn't find
enough joysticks."
)
pygame.quit()
exit()
else
:
# Use joystick #0 and initialize it
joystick1
=
pygame.joystick.Joystick(
0
)
joystick1.init()
joystick2
=
pygame.joystick.Joystick(
1
)
joystick2.init()
# Create the player paddle object
player1
=
Player(joystick1,
580
)
player2
=
Player(joystick2,
25
)
movingsprites
=
pygame.sprite.Group()
movingsprites.add(player1)
movingsprites.add(player2)
movingsprites.add(ball)
clock
=
pygame.time.Clock()
done
=
False
exit_program
=
False
while
not
exit_program:
# Clear the screen
screen.fill(BLACK)
for
event
in
pygame.event.get():
if
event.
type
=
=
pygame.QUIT:
exit_program
=
True
# Stop the game if there is an imbalance of 3
points
if
abs
(score1
-
score2) >
3
:
done
=
True
if
not
done:
# Update the player and ball positions
player1.update()
player2.update()
ball.update()
# If we are done, print game over
if
done:
text
=
font.render(
"Game Over"
,
1
, (
200
,
200
,
200
))
textpos
=
text.get_rect(centerx
=
background.get_width()
/
2
)
textpos.top
=
50
screen.blit(text, textpos)
# See if the ball hits the player paddle
if
pygame.sprite.spritecollide(player1,
balls,
False
):
# The 'diff' lets you try to bounce the ball left or right
depending where on the paddle you hit it
diff
=
(player1.rect.x
+
player1.width
/
2
)
-
(ball.rect.x
+
ball.width
/
2
)
# Set the ball's y position in case we hit the ball on the
edge of the paddle
ball.y
=
570
ball.bounce(diff)
score1
+
=
1
# See if the ball hits the player paddle
if
pygame.sprite.spritecollide(player2,
balls,
False
):
# The 'diff' lets you try to bounce the ball left or right
depending where on the paddle you hit it
diff
=
(player2.rect.x
+
player2.width
/
2
)
-
(ball.rect.x
+
ball.width
/
2
)
# Set the ball's y position in case we hit the ball on the
edge of the paddle
ball.y
=
40
ball.bounce(diff)
score2
+
=
1
# Print the score
scoreprint
=
"Player 1:
"
+
str
(score1)
text
=
font.render(scoreprint,
1
,
WHITE)
textpos
=
(
0
,
0
)
screen.blit(text, textpos)
scoreprint
=
"Player 2:
"
+
str
(score2)
text
=
font.render(scoreprint,
1
,
WHITE)
textpos
=
(
300
,
0
)
screen.blit(text, textpos)
# Draw Everything
movingsprites.draw(screen)
# Update the screen
pygame.display.flip()
clock.tick(
30
)
pygame.quit()
You try this also style design
import random
import pygame, sys
from pygame.locals import *
pygame.init()
fps = pygame.time.Clock()
#colors
WHITE = (255,255,255)
RED = (255,0,0)
GREEN = (0,255,0)
BLACK = (0,0,0)
#globals
WIDTH = 600
HEIGHT = 400
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
HALF_PAD_WIDTH = PAD_WIDTH / 2
HALF_PAD_HEIGHT = PAD_HEIGHT / 2
ball_pos = [0,0]
ball_vel = [0,0]
paddle1_vel = 0
paddle2_vel = 0
l_score = 0
r_score = 0
#canvas declaration
window = pygame.display.set_mode((WIDTH, HEIGHT), 0, 32)
pygame.display.set_caption('Hello World')
# helper function that spawns a ball, returns a position
vector and a velocity vector
# if right is True, spawn to the right, else spawn to the
left
def ball_init(right):
global ball_pos, ball_vel # these are vectors stored as lists
ball_pos = [WIDTH//2,HEIGHT//2]
horz = random.randrange(2,4)
vert = random.randrange(1,3)
if right == False:
horz = - horz
ball_vel = [horz,-vert]
# define event handlers
def init():
global paddle1_pos, paddle2_pos, paddle1_vel,
paddle2_vel,l_score,r_score # these are floats
global score1, score2 # these are ints
paddle1_pos = [HALF_PAD_WIDTH - 1,HEIGHT/2]
paddle2_pos = [WIDTH +1 - HALF_PAD_WIDTH,HEIGHT/2]
l_score = 0
r_score = 0
if random.randrange(0,2) == 0:
ball_init(True)
else:
ball_init(False)
#draw function of canvas
def draw(canvas):
global paddle1_pos, paddle2_pos, ball_pos, ball_vel, l_score,
r_score
canvas.fill(BLACK)
pygame.draw.line(canvas, WHITE, [WIDTH / 2, 0],[WIDTH / 2, HEIGHT],
1)
pygame.draw.line(canvas, WHITE, [PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT],
1)
pygame.draw.line(canvas, WHITE, [WIDTH - PAD_WIDTH, 0],[WIDTH -
PAD_WIDTH, HEIGHT], 1)
pygame.draw.circle(canvas, WHITE, [WIDTH//2, HEIGHT//2], 70,
1)
# update paddle's vertical position, keep paddle on the
screen
if paddle1_pos[1] > HALF_PAD_HEIGHT and paddle1_pos[1] <
HEIGHT - HALF_PAD_HEIGHT:
paddle1_pos[1] += paddle1_vel
elif paddle1_pos[1] == HALF_PAD_HEIGHT and paddle1_vel >
0:
paddle1_pos[1] += paddle1_vel
elif paddle1_pos[1] == HEIGHT - HALF_PAD_HEIGHT and paddle1_vel
< 0:
paddle1_pos[1] += paddle1_vel
if paddle2_pos[1] > HALF_PAD_HEIGHT and paddle2_pos[1] <
HEIGHT - HALF_PAD_HEIGHT:
paddle2_pos[1] += paddle2_vel
elif paddle2_pos[1] == HALF_PAD_HEIGHT and paddle2_vel >
0:
paddle2_pos[1] += paddle2_vel
elif paddle2_pos[1] == HEIGHT - HALF_PAD_HEIGHT and paddle2_vel
< 0:
paddle2_pos[1] += paddle2_vel
#update ball
ball_pos[0] += int(ball_vel[0])
ball_pos[1] += int(ball_vel[1])
#draw paddles and ball
pygame.draw.circle(canvas, RED, ball_pos, 20, 0)
pygame.draw.polygon(canvas, GREEN, [[paddle1_pos[0] -
HALF_PAD_WIDTH, paddle1_pos[1] - HALF_PAD_HEIGHT], [paddle1_pos[0]
- HALF_PAD_WIDTH, paddle1_pos[1] + HALF_PAD_HEIGHT],
[paddle1_pos[0] + HALF_PAD_WIDTH, paddle1_pos[1] +
HALF_PAD_HEIGHT], [paddle1_pos[0] + HALF_PAD_WIDTH, paddle1_pos[1]
- HALF_PAD_HEIGHT]], 0)
pygame.draw.polygon(canvas, GREEN, [[paddle2_pos[0] -
HALF_PAD_WIDTH, paddle2_pos[1] - HALF_PAD_HEIGHT], [paddle2_pos[0]
- HALF_PAD_WIDTH, paddle2_pos[1] + HALF_PAD_HEIGHT],
[paddle2_pos[0] + HALF_PAD_WIDTH, paddle2_pos[1] +
HALF_PAD_HEIGHT], [paddle2_pos[0] + HALF_PAD_WIDTH, paddle2_pos[1]
- HALF_PAD_HEIGHT]], 0)
#ball collision check on top and bottom walls
if int(ball_pos[1]) <= BALL_RADIUS:
ball_vel[1] = - ball_vel[1]
if int(ball_pos[1]) >= HEIGHT + 1 - BALL_RADIUS:
ball_vel[1] = -ball_vel[1]
#ball collison check on gutters or paddles
if int(ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH and
int(ball_pos[1]) in range(paddle1_pos[1] -
HALF_PAD_HEIGHT,paddle1_pos[1] + HALF_PAD_HEIGHT,1):
ball_vel[0] = -ball_vel[0]
ball_vel[0] *= 1.1
ball_vel[1] *= 1.1
elif int(ball_pos[0]) <= BALL_RADIUS + PAD_WIDTH:
r_score += 1
ball_init(True)
if int(ball_pos[0]) >= WIDTH + 1 - BALL_RADIUS - PAD_WIDTH and
int(ball_pos[1]) in range(paddle2_pos[1] -
HALF_PAD_HEIGHT,paddle2_pos[1] + HALF_PAD_HEIGHT,1):
ball_vel[0] = -ball_vel[0]
ball_vel[0] *= 1.1
ball_vel[1] *= 1.1
elif int(ball_pos[0]) >= WIDTH + 1 - BALL_RADIUS -
PAD_WIDTH:
l_score += 1
ball_init(False)
#update scores
myfont1 = pygame.font.SysFont("Comic Sans MS", 20)
label1 = myfont1.render("Score "+str(l_score), 1,
(255,255,0))
canvas.blit(label1, (50,20))
myfont2 = pygame.font.SysFont("Comic Sans MS", 20)
label2 = myfont2.render("Score "+str(r_score), 1,
(255,255,0))
canvas.blit(label2, (470, 20))
#keydown handler
def keydown(event):
global paddle1_vel, paddle2_vel
if event.key == K_UP:
paddle2_vel = -8
elif event.key == K_DOWN:
paddle2_vel = 8
elif event.key == K_w:
paddle1_vel = -8
elif event.key == K_s:
paddle1_vel = 8
#keyup handler
def keyup(event):
global paddle1_vel, paddle2_vel
if event.key in (K_w, K_s):
paddle1_vel = 0
elif event.key in (K_UP, K_DOWN):
paddle2_vel = 0
init()
#game loop
while True:
draw(window)
for event in pygame.event.get():
if event.type == KEYDOWN:
keydown(event)
elif event.type == KEYUP:
keyup(event)
elif event.type == QUIT:
pygame.quit()
sys.exit()
pygame.display.update()
fps.tick(60)