Question

In: Computer Science

In python please: You’re going to program a simulation of the following game. Like many probability...

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.

  • During the throwing phase, the player takes balls randomly, one at a time, from the infinite supply and tosses them at the cups creating a stack of balls in each cup. The throwing phase is over when each cup contains at least one ping-pong ball.
  • Next comes the pruning phase. During this phase the player goes through all the balls in each cup and removes any ball whose number does not match the containing cup.

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.  

Solutions

Expert Solution

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)


Related Solutions

C# PLEASE Lab7B: For this lab, you’re going to write a program that prompts the user...
C# PLEASE Lab7B: For this lab, you’re going to write a program that prompts the user for the number of GPAs to enter. The program should then prompt the user to enter the specified number of GPAs. Finally, the program should print out the graduation standing of the students based on their GPAs. Your program should behave like the sample output below. Sample #1: Enter the number of GPAs: 5 GPA #0: 3.97 GPA #1: 3.5 GPA #2: 3.499 GPA...
Write a program using Python that allows the user to play a guessing game (please provide...
Write a program using Python that allows the user to play a guessing game (please provide a picture of code so it is easier to read). The game will choose a "secret number", a positive integer less than 10000. The user has 10 tries to guess the number. Requirements: Normally, we would have the program select a random number as the "secret number". However, for the purpose of testing your program (as well as grading it), simply use an assignment...
I need to write PYTHON program which is like a guessing game using randint function which...
I need to write PYTHON program which is like a guessing game using randint function which is already done, the user has to guess a number between 1 and 1000 and the game musn't end until you guess the number, if you input a smaller number you must get hints, the same goes if your input is bigger than the wining number , also you must get notified if you repeat a number (example, you pick 1 and in the...
In this python program , you are to build a trivia game. The game should present...
In this python program , you are to build a trivia game. The game should present each question – either in order or randomly – to the player, and display up to four possible answers. The player is to input what they believe to be the correct answer.   The game will tell the player if they got it right or wrong and will display their score. If they got it right, their score will go up. If they got it...
Python 1.Suppose you were going to design an event-driven application like the famous wack-a-mole game. Do...
Python 1.Suppose you were going to design an event-driven application like the famous wack-a-mole game. Do the following: a) draw a mockup of the layout of the screen--this is usually easiest by hand. Submit a legible picture of your drawing. b) List the events your game would have to respond to (such as when certain keys are pressed). 2.Explain why you should avoid using loops to repeat actions in a GUI application. What should you do instead?
Write a python program that simulates a simple dice gambling game. The game is played as...
Write a python program that simulates a simple dice gambling game. The game is played as follows: Roll a six sided die. If you roll a 1, 2 or a 3, the game is over. If you roll a 4, 5, or 6, you win that many dollars ($4, $5, or $6), and then roll again. With each additional roll, you have the chance to win more money, or you might roll a game-ending 1, 2, or 3, at which...
Explain this python program as if you were going to present it to a class in...
Explain this python program as if you were going to present it to a class in a power point presentation. How would you explain it? I am having a hard time with this. I have my outputs and code displayed throughout 9 slides. #Guess My Number Program # Python Code is modified to discard duplicate guesses by the computer import random #function for getting the user input on what they want to do. def menu(): #print the options print("\n\n1. You...
Please use Python 21. Rock, Paper, Scissors Game Write a program that let's the user play...
Please use Python 21. Rock, Paper, Scissors Game Write a program that let's the user play the game of rock, paper, scissors against the computer. The program should work as follows: 1. When the program begins, a random number in the range of 1 through 3 is generated. If the number is 1, then the computer has chosen rock. If the number is 2, then the computer has chosen paper. If the number is 3, then the computer has chosen...
I would like the following code in PYTHON please, there was a previous submission of this...
I would like the following code in PYTHON please, there was a previous submission of this question but I am trying to have the file save as a text file and not a json. Any help would be greatly appreciated. Create an application that does the following: The user will enter product codes and product numbers from the keyboard as strings. The product code must consist of four capital letters. The product number can only consist of numeric characters, but...
Rock, Paper, Scissors Game Write a Python program rps.py that lets the user play the game...
Rock, Paper, Scissors Game Write a Python program rps.py that lets the user play the game of Rock, Paper, Scissors against the computer. The program should work as follows: You can set these constant global variables at the top outside of your main function definition: COMPUTER_WINS = 1 PLAYER_WINS = 2 TIE = 0 INVALID = 3 ROCK = 1 PAPER = 2 SCISSORS = 3 For this program 1 represents rock, 2 represents paper, and 3 represents scissors. In...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT