""" Basic pong, with many balls using lists by Rory Solomon For Code Toolkit: Python Eugene Lang College, Fall 2020 Note: In all my while loops below I'm using len(ballX). As we discussed in class, the lists ballX, ballY, ballXDirection, and ballYDirection *should* all be the same length at all times. So really, I could use any of them inside len(). This is not ideal programming practice because if one list becomes a different length, that could introduce an "index out of bounds" error. For this example, it should be OK. But if I were to expand this game (for example, if balls were to disappear) I'd need to be careful about how I manage the lists. """ paddle1Y = 250 paddle2Y = 250 def setup (): size(600, 600) noStroke() fill(255) rectMode(CENTER) global ballX, ballY, ballXDirection, ballYDirection # initialize each as a list with just one item ballX = [300] ballY = [300] ballXDirection = [2] ballYDirection = [2] def draw(): global paddle1Y, paddle2Y, ballX, ballY, ballXDirection, ballYDirection background(0) # draw ball(s) i = 0 while i < len(ballX): ellipse( ballX[i], ballY[i], 10, 10) i = i + 1 # draw paddles rect(20, paddle1Y, 10, 50) rect(540, paddle2Y, 10, 50) # move paddles if keyPressed: if key == 'q': paddle1Y = paddle1Y - 5 elif key == 'z': paddle1Y = paddle1Y + 5 elif key == 'i': paddle2Y = paddle2Y - 5 elif key == 'm': paddle2Y = paddle2Y + 5 # check ceiling and floor collision for each ball i = 0 while i < len(ballX): if ballY[i] <= 0: ballYDirection[i] = 3 if ballY[i] >= 600: ballYDirection[i] = -3 i = i + 1 # check paddle collisions for each ball i = 0 while i < len(ballX): if ballY[i] >= paddle1Y and ballY[i] <= paddle1Y + 50 and ballX[i] <= 20: ballXDirection[i] = 1 if ballY[i] >= paddle2Y and ballY[i] <= paddle2Y + 50 and ballX[i] >= 540: ballXDirection[i] = -1 i = i + 1 # update all ball positions i = 0 while i < len(ballX): ballX[i] = ballX[i] + ballXDirection[i] ballY[i] = ballY[i] + ballYDirection[i] i = i + 1 def mousePressed(): global ballX, ballY, ballXDirection, ballYDirection ballX.append(300) ballY.append(300) ballXDirection.append( random(-3, 3) ) ballYDirection.append( random(-3, 3) )