• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0

How to improve this pong game?

0 posts in this topic

I made this simple pong game in Python using Pygame. It consists of two files, one which contains the main game code and the other contains the code for the classes. I'd like some advice on how to improve this code.


# classes.py
# 3/19/2013

import pygame
import random

# Paddle properties
PADDLE_COLOR = (0, 0, 0)

# Ball properties
BALL_COLOR = (0, 0, 0)

# Base object class
class Object:
	# Initializes the object with coordinates, size and color
	def __init__(self, x, y, w, h, color):
		self.x = x
		self.y = y
		self.w = w
		self.h = h
		self.vx = 0
		self.vy = 0
		self.color = color
	# Updates object by moving it and checking if it's in screen range
	def update(self, screenWidth, screenHeight):
		self.x += self.vx
		self.y += self.vy
		if self.x < 0: self.x = 0
		if self.y < 0: self.y = 0
		if self.x > screenWidth - self.w: self.x = screenWidth - self.w
		if self.y > screenHeight - self.h: self.y = screenHeight - self.h

	# Must be implemented by child classes
	def draw(self, surface):
	# Returns whether object collides with another object (rectangular collision detection)
	def collides(self, obj):
		return self.y < obj.y + obj.h and self.y + self.h > obj.y and self.x < obj.x + obj.w and self.x + self.w > obj.x
	# Called when object collides with anoher object, must be implemented by child classes
	def onCollide(self, obj):
# Paddle class	
class Paddle(Object):
	# Initializes Paddle object
	def __init__(self, x, y):
		super(Paddle, self).__init__(x, y, PADDLE_WIDTH, PADDLE_HEIGHT, PADDLE_COLOR)
	# Draws paddle with a rectangle
	def draw(self, surface):
		pygame.draw.rect(surface, self.color, (self.x, self.y, self.w, self.h))
	# Moves paddle up
	def moveUp(self):
		self.vy -= PADDLE_SPEED
	# Moves paddle down
	def moveDown(self):
		self.vy = PADDLE_SPEED
	# Stops moving the paddle
	def stopMoving(self):
		self.vy = 0

# ComputerPaddle class
class ComputerPaddle(Paddle):
	# Initializes ComputerPaddle object
	def __init__(self, x, y):
		super(ComputerPaddle, self).__init__(x, y)
	# Adjust Y-velocity based on speed and direction of ball
	def update(self, ball, screenWidth, screenHeight):
		super(ComputerPaddle, self).update(screenWidth, screenHeight)
		if ball.vx < 0: 
		ballX = ball.x
		ballY = ball.y
		ballVX = ball.vx
		ballVY = ball.vy
		while ballX + ball.w < self.x:
			ballX += ballVX
			ballY += ballVY
			if ballY < 0 or ballY > screenHeight - ball.h: ballVY = -ballVY
		if ballY > self.y + self.h: self.moveDown()
		elif ballY + ball.h < self.y: self.moveUp()
		else: self.stopMoving()

# Ball class
class Ball(Object):

	# Initializes the Ball object along with initial velocities
	def __init__(self, x, y):
		super(Ball, self).__init__(x, y, BALL_RADIUS, BALL_RADIUS, BALL_COLOR)
		self.startX = x
		self.startY = y
		self.vx = BALL_INITIAL_VX
		self.vy = BALL_INITIAL_VY
	# Updates the ball object, if it hits screen edge then negate velocity
	def update(self, screenWidth, screenHeight):
		super(Ball, self).update(screenWidth, screenHeight)
		if self.x == 0 or self.x == screenWidth - self.w: self.vx = -self.vx
		if self.y == 0 or self.y == screenHeight - self.h: self.vy = -self.vy
	# Resets the ball back to its initial coordinates
	def reset(self):
		self.x = self.startX
		self.y = self.startY
		self.vx = BALL_INITIAL_VX
		self.vy = BALL_INITIAL_VY
	# Draws a circle onto screen to represent the ball
	def draw(self, surface):
		pygame.draw.circle(surface, self.color, (self.x, self.y), self.w)
	# If ball collides with another object, then negate both velocities by a random amount
	def onCollide(self, obj): 
		# If ball is "inside" of paddle, then reposition it so it's just outside the paddle
		if self.x < obj.x + obj.w: self.x = obj.x + obj.w
		elif self.x + self.w > obj.x: self.x = obj.x - self.w
		if self.y < obj.y + obj.h: self.y = obj.y + obj.h
		elif self.y + self.h > obj.y: self.y = obj.y - self.h
		rx = int(random.uniform(-3, 5))
		ry = int(random.uniform(-2, 4))
		self.vx = -self.vx + rx
		self.vy = -self.vy + ry


# game.py
# 3/19/2013

import pygame, sys, os
from pygame.locals import *
from classes import *

# Basic constants
FPS = 60
SCREEN_BACKGROUND = (255, 255, 255)

# Game states

# Some global variables
gameState = GSTATE_START
playerScore = 0
computerScore = 0

# Handle all inputs to application
def input(events, obj): 
	global gameState
	for event in events:
		if event.type == QUIT:
			return False
		elif event.type == KEYDOWN:
			if event.key == K_w:
			elif event.key == K_s:
		elif event.type == KEYUP:
			if event.key == K_w or event.key == K_s:
			elif event.key == K_SPACE and (gameState == GSTATE_START or gameState == GSTATE_VICTORY):
				gameState = GSTATE_PLAYING
	return True
# Main drawing function
def draw(screen, font, gameObjects):
	global gameState
	global playerScore
	global computerScore
	if gameState != GSTATE_PLAYING:
		if gameState == GSTATE_START: message = "Press Space to start playing"
		elif gameState == GSTATE_VICTORY: message = "Round complete, press Space to continue"
		screen.blit(font.render(message, 1, (0, 0, 0)), ((SCREEN_WIDTH / 2) - 200, SCREEN_HEIGHT / 2))

	screen.blit(font.render("Player: %d" % playerScore, 1, (0, 0, 0)), (int(SCREEN_WIDTH / 4), 20))
	screen.blit(font.render("Computer: %d" % computerScore, 1, (0, 0, 0)), (int(SCREEN_WIDTH * 3 / 4), 20)) 
	for obj in gameObjects: 
# Main update function
def update(p1, p2, ball):
	global gameState
	global playerScore
	global computerScore
	# Do not update if game hasn't started yet
	if gameState != GSTATE_PLAYING: return
	# Update game objects
	# Check if the ball collides with either of the two paddles
	if ball.collides(p1): ball.onCollide(p1)
	elif ball.collides(p2): ball.onCollide(p2)
	# Check for victory conditions
	if ball.x == 0: 
		computerScore += 1
		gameState = GSTATE_VICTORY
	elif ball.x == SCREEN_WIDTH - ball.w:
		playerScore += 1
		gameState = GSTATE_VICTORY
# Main function, entry point of application
def main():
	# Initialize pygame
	pygame.display.set_caption('Pygame Pong (RL)')

	# Setup window, screen, clock and fonts
	window = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
	screen = pygame.display.get_surface()
	clock = pygame.time.Clock()
	font = pygame.font.Font('freesansbold.ttf', 20)

	# Initialize game objects
	paddlePlayer = Paddle(0, int((SCREEN_HEIGHT - PADDLE_HEIGHT) / 2))
	paddleComputer = ComputerPaddle(int(SCREEN_WIDTH - PADDLE_WIDTH), int((SCREEN_HEIGHT - PADDLE_HEIGHT) / 2))
	ball = Ball(int((SCREEN_WIDTH - BALL_RADIUS) / 2), int((SCREEN_HEIGHT - BALL_RADIUS) / 2))

	# Game loop
	while input(pygame.event.get(), paddlePlayer):
		update(paddlePlayer, paddleComputer, ball)
		draw(screen, font, [ paddlePlayer, paddleComputer, ball ])
	# Exit game
# Start program
if __name__ == "__main__":


Also there is a bug in the game where when the ball gets to the right end of the screen, it always counts as a computer victory even if it touches the computer paddle. Any idea how to fix it?

Edited by rlink

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
Sign in to follow this  
Followers 0