Dec 23, 2013

Pong (Classic) Python implementation

Executable File/Downloadable 64bit
http://www.4shared.com/file/pnNma64G/Pong_Setup.html
Source Code
#Author : Mazhar Hussain
#National Centre of Excellence in Molecular Biology
#University of the Punjab, Lahore
#Dated : 19- 11 - 2013

#Game : Pong

import simpleguitk as simplegui
import random

# initialize globals - pos and vel encode vertical info for paddles
WIDTH = 600
HEIGHT = 400    
BALL_RADIUS = 20
PAD_WIDTH = 8
PAD_HEIGHT = 80
ball_pos = [0 , 0]
ball_vel = [0 , 0]
LEFT = False
RIGHT = True
direction = LEFT
paddle1_vel = 0
paddle2_vel = 0
paddle1_pos  = HEIGHT/2
paddle2_pos = HEIGHT/2
left_score = 0
right_score = 0

#various kinds of helper functions are defined below
#paddle1position and paddle2position controls the position of paddles
#present on both sides. These functions not only allows the legitimate motion
#of the paddles but also lock them inside canvas
def paddle1position():
    global paddle1_pos
    if (paddle1_pos  > 0) and (paddle1_pos+PAD_HEIGHT < HEIGHT):
        paddle1_pos = (paddle1_pos + paddle1_vel)
        return paddle1_pos
    elif (paddle1_pos  <= 0):
        paddle1_pos = paddle1_pos + 3
        return paddle1_pos
    elif ((paddle1_pos + PAD_HEIGHT)  >= HEIGHT):
        paddle1_pos = paddle1_pos - 3
        return paddle1_pos
 
def paddle2position():
    global paddle2_pos
    if (paddle2_pos  > 0) and (paddle2_pos+ PAD_HEIGHT < HEIGHT):
        paddle2_pos = (paddle2_pos + paddle2_vel)
        return paddle2_pos
    elif (paddle2_pos  <= 0):
        paddle2_pos = paddle2_pos + 3
        return paddle2_pos
    elif ((paddle2_pos + PAD_HEIGHT)  >= HEIGHT):
        paddle2_pos = paddle2_pos - 3
        return paddle2_pos

#ball_direction is the function which controls initial parameters about
#ball position and speed. It also contains functions for scoring after
#every failed attempt to catch ball on paddel. It contains a child function
#spawn_ball which carries the initial parametters for ball direction
#and velocity
def ball_direction():
    global direction, left_score, right_score
    if (((ball_pos[0]) - BALL_RADIUS)<= 0):
        direction = RIGHT
        left_score += 1
        spawn_ball(direction)
    elif ((ball_pos[0]+BALL_RADIUS) >= WIDTH):
        direction = LEFT
        right_score += 1
        spawn_ball(direction)

def spawn_ball(direction):
    global ball_pos, ball_vel
    if (direction == RIGHT):
        ball_vel[0] = random.randrange(120 , 240)
        ball_vel[1] = random.randrange(60 , 180)
        ball_vel = [ball_vel[0] , ball_vel[1]]
        ball_pos = [WIDTH/2 , HEIGHT/2]
        return ball_pos, ball_vel
    elif (direction == LEFT):
        ball_vel[0] = random.randrange(-240 , -120)
        ball_vel[1] = random.randrange(60 , 180)
        ball_vel = [ball_vel[0] , ball_vel[1]]
        ball_pos = [WIDTH/2 , HEIGHT/2]
        return ball_pos, ball_vel  

# paddle1_detector() and paddle2_detector() are collision functions.
# they describes the event when ball touches the paddel. They tell
# how the ball rebounds and at what velocity. Ball increase by 10% speed
# after every stroke by paddel
def paddle1_detector():
    global ball_vel, left_score
    if ((ball_pos[0] + 30) >= WIDTH) and ((ball_pos[1]) > paddle1_pos) and ((ball_pos[1] < (paddle1_pos + PAD_HEIGHT))):
        ball_vel[0] = -((ball_vel[0])*1.1)
        ball_vel = [ball_vel[0], ball_vel[1]]
        return ball_vel
    else:
        ball_vel[0] = ball_vel[0]
        ball_direction()
 
def paddle2_detector():
    global ball_vel, right_score
    if ((ball_pos[0] - 30) <= 0) and ((ball_pos[1]) > paddle2_pos) and ((ball_pos[1] < (paddle2_pos + PAD_HEIGHT))):
        ball_vel[0] = -((ball_vel[0])*1.1)
        ball_vel = [ball_vel[0], ball_vel[1]]
        return ball_vel
    else:
        ball_vel[0] = ball_vel[0]
        ball_direction()

# new_game() is an event handler which resets the game, once the button is triggered
def new_game():
    global paddle1_pos, paddle2_pos, left_score, right_score  # these are numbers
    global score1, score2  # these are ints
    spawn_ball(direction)
    left_score = 0
    right_score = 0
    paddle1_pos = HEIGHT/2
    paddle2_pos = HEIGHT/2

# draw(c) is event handler for drawing function. It is about everything we see on
# screen... it is about printing the ball position... it directly calls
# the paddel detector function
def draw(c):
    global score1, score2, paddle1_pos, paddle2_pos, ball_pos, ball_vel
    c.draw_line([WIDTH / 2, 0],[WIDTH / 2, HEIGHT], 1, "White")
    c.draw_line([PAD_WIDTH, 0],[PAD_WIDTH, HEIGHT], 1, "White")
    c.draw_line([WIDTH - PAD_WIDTH, 0],[WIDTH - PAD_WIDTH, HEIGHT], 1, "White")
    c.draw_text(str(right_score), (100, 100), 60, 'Green')
    c.draw_text(str(left_score), (450, 100), 60, 'Yellow')
    if (((ball_pos[1])-BALL_RADIUS) <= 0):
        ball_vel[1] = -(ball_vel[1])
        ball_pos[0] += (ball_vel[0])/60
        ball_pos[1] += (ball_vel[1])/60
        ball_pos = [(ball_pos[0]) , (ball_pos[1])]
        c.draw_circle(ball_pos, BALL_RADIUS, 3, 'White', 'White')
    elif ((ball_pos[1])+(BALL_RADIUS) >= (HEIGHT)):
        ball_vel[1] = -(ball_vel[1])
        ball_pos[0] += (ball_vel[0])/60
        ball_pos[1] += (ball_vel[1])/60
        ball_pos = [(ball_pos[0]) , (ball_pos[1])]
        c.draw_circle(ball_pos, BALL_RADIUS, 3, 'White', 'White')
    else:
        ball_pos[0] += (ball_vel[0])/60
        ball_pos[1] += (ball_vel[1])/60
        ball_pos = [(ball_pos[0]) , (ball_pos[1])]
        c.draw_circle(ball_pos, BALL_RADIUS, 3, 'White', 'White')
    c.draw_line([(PAD_WIDTH), (paddle2position())],[PAD_WIDTH, (paddle2position()+PAD_HEIGHT)], 10, "White")
    c.draw_line([WIDTH - PAD_WIDTH, (paddle1position())],[WIDTH - PAD_WIDTH, (paddle1position()+PAD_HEIGHT)], 10, "White")
    paddle1_detector()
    paddle2_detector()  

 
# keydown and keyup handlers which are triggered once a key is pressed
def keydown(key):
    global paddle1_vel, paddle2_vel
    if key == simplegui.KEY_MAP["down"]:
        paddle1_vel= 3
    elif key == simplegui.KEY_MAP["up"]:
        paddle1_vel = -3
    elif key == simplegui.KEY_MAP["s"]:
        paddle2_vel = 3
    elif key == simplegui.KEY_MAP["w"]:
        paddle2_vel = -3
     
def keyup(key):
    global paddle1_vel, paddle2_vel
    if key == simplegui.KEY_MAP["down"]:
        paddle1_vel= 0
    elif key == simplegui.KEY_MAP["up"]:
        paddle1_vel = 0
    elif key == simplegui.KEY_MAP["s"]:
        paddle2_vel =  0
    elif key == simplegui.KEY_MAP["w"]:
        paddle2_vel = 0

frame = simplegui.create_frame("Pong", WIDTH, HEIGHT)
frame.set_draw_handler(draw)
frame.set_keydown_handler(keydown)
frame.set_keyup_handler(keyup)
frame.add_button("RESTART GAME", new_game, 120)
def about_me():
 
    top = "************************************************************************"
    top1= "--------------------------------ABOUT ME--------------------------------"
 
    x1 = "| This game is developed by me, Mazhar Hussain, on the |"
    x2 =  "| top of PYTHON. I have completed my MPhil in Molecular |"
    x3 =  "| Biology from National Centre of Excellence in Molecular |"
    x4 = "| Biology. My BS(Hons) is in Microbiology and Molecular |"
    x5 = "| Genetics from University of the Punjab, Lahore. This |"
    x6 =  "| game is 1972 version of PONG, which is infact very |"
    x7 = "| famous among teens of developing countries. |"
    x8 =  "| |"
    x9 =  "| I have implemented various concepts in its development, |"
    x10 =  "| which include functions, conditionals, graphic-user-interface |"
    x11 =  "| and random number generator. This game simply demonstrate |"
    x12 =  "| the visualization of graphics and control of objects using |"
    x13 = "| KEYBOARD. |"
    print str(top)+"\n"+str(top1)+"\n"+str(top)+"\n"+str(x1)+"\n"+ str(x2)+"\n"+str(x3)+"\n"+ str(x4)+"\n" +str(x5)+"\n"+ str(x6)+"\n"+str(x7)+"\n"+ str(x8)+"\n"+str(x9)+"\n"+ str(x10)+"\n" +str(x11)+"\n"+ str(x12)+"\n"+ str(x13)


def how_to_play():
 
    top = "************************************************************************"
    top1= "----------------------------How To Play---------------------------------"
 
    x1 = "| Rules are pretty simple. Game is controlled by two paddles |"
    x2 =  "| left and right. Left paddle up and down motion is |"
    x3 =  "| controlled by 'w' and 's', respectively while the |"
    x4 = "| paddle on right is controlled by up and down arrow keys. |"
    x5 = "| As long as ball stays on table, it gains speed by 10% increment.|"
    x6 =  "| When ball misses the paddle and go in gutter, opposite player |"
    x7 = "| will gain the points. |"
    x8 =  "| |"
 
    print str(top)+"\n"+str(top1)+"\n"+str(top)+"\n"+str(x1)+"\n"+ str(x2)+"\n"+str(x3)+"\n"+ str(x4)+"\n" +str(x5)+"\n"+ str(x6)+"\n"+str(x7)+"\n"+ str(x8)+"\n"

frame.add_button("Play Instructions", how_to_play, 120)  
frame.add_button("About Me", about_me, 120)

new_game()
spawn_ball(direction)

frame.start()

Guess the Number

Executable File/Downloadable 64bit

Source Code

#Author : Mazhar Hussain
#Centre of Excellence in Molecular Biology,
#University of the Punjab Lahore
#Dated : 01 - 11 - 2013
#Game : Guess the Number

import random 
"""Calls Module random which generates a random number in
given range
"""

import simpleguitk as simplegui
"""Calls Module simplegui which produces the input fields
and interactive graphic-user-interface
"""

# initialize global variables used in your code

computer_number = 0 # carries random number from random module
attempts_left = 0 # contains value of remaining number of attempts
default_attempts = 0 # it directly takes value from initial trigger
                    # and preserve value for next playing session
set_value_from = 0 # provides initial value to randrange function in random
set_value_to = 100 # provides final value to randrange function in random

# helper function to start and restart the game

"""can trigger new_game by taking values from the previous game
regarding number of attempts left but generates new value from
random module using random_generator function in game
"""
def new_game():
    global attempts_left
    random_generator(set_value_from , set_value_to)
    attempts_left = default_attempts
"""
random_generator() is function in the heart of game
it directly generates random number in given range
and then preserves the 
"""
    
def random_generator (set_value_from, set_value_to):
    global computer_number
    computer_number = random.randrange (set_value_from, set_value_to)
    return computer_number
"""
attempts_remaining() is helping function and it counts down
the attempts to zero and ultimately using conditionals
assissts in terminating game, if correct number was not guessed
"""
def attempts_remaining():
    global attempts_left
    attempts_left = attempts_left - 1
    return attempts_left
"""
Helper function, Which Prints Current State of Game in fanciful way.
It is called from range100() and range1000() event handlers
"""
def state_of_game(set_value_from, set_value_to, attempts_left):
    print "===================================\n",
    print "Guess the Number Between "+ str(set_value_from) + " to " + str(set_value_to) + "\n",
    print "and you have only "+str(attempts_left) +" attempts. :D"
    print "==================================="   

# define event handlers for control panel
"""
Handle of "Guess Number from 0-100" button. When button is pressed
it sets the variables so that "State of Guess the Number in 0 to 100"
becomes active. Declares global variables which are vital for not only
current game but also for subsequent game on same settings
"""

def range100():
    global set_value_from, set_value_to
    global attempts_left, default_attempts
    set_value_from = 0
    set_value_to = 100
    attempts_left = 7
    default_attempts = 7
    computer_number = random_generator(set_value_from , set_value_to)
    state_of_game(set_value_from, set_value_to, attempts_left)
   
    # button that changes range to range [0,100) and restart
"""
Handle of "Guess Number from 0-1000" button. Other details are same as
discussed for "Guess Number from 0-100) button.
"""

def range1000():
    global set_value_from, set_value_to
    global attempts_left, default_attempts
    set_value_from = 0
    set_value_to = 1000
    attempts_left = 10
    default_attempts = 10
    computer_number = random_generator(set_value_from , set_value_to)
    state_of_game(set_value_from, set_value_to, attempts_left)
    
"""
Core of game, which compares Computer's generated number and player's guess.
It suggests player to GUESS HIGHER or LOWER NUMBER. It counts on the number of attempts
left. It contains rules for declaring win or lose. It immeditely triggers the next
game as soon as current game is ended.
"""
    
    
def input_guess(player_number):
    if (attempts_remaining() == 0) and (computer_number == int(player_number)):
        print "-----------------------------------------------------------------------------"
        print "You Guessed the Number "+str(player_number)+" and Your all attempts are over,"
        print "----------------------But You Guessed the Correct Number---------------------"
        print "--------------------------Congratulations! You Won---------------------------"
        print "----------------Wishing You Awesome Performane in Next Game Too--------------"
        print "-----------------------------------------------------------------------------"
        print "----------------------------Triggered New Game------------------------------"
        new_game()
    elif (attempts_left == 0) and (computer_number != int(player_number)):
        print "------------------------------------------------------"
        print "You Guessed the Number "+str(player_number)+" and Your all attempts are over,"
        print "----------------The correct number was "+str(computer_number)+"-------------"
        print "------------Better Luck in the Next Game--------------"
        print "------------------------------------------------------"
        print "--------------------Triggered New Game---------------"
        new_game()
    else:
        if (computer_number == int(player_number)):
            print "------------------------------------------------------"
            print "You Guessed the Number "+str(player_number)+", which is Correct"
            print ">>>>>>>>>>>Congratualations You Did it!!!<<<<<<<<<<<<<<<"
            print "---------Wishing You Best of Luck For Next Game--------"
            print "------------------------------------------------------"
            print "------------------Triggered New Game------------------"
            new_game()
        elif (computer_number > int(player_number)):
            print"----------------------------------------------"
            print "You guessed the number "+str(player_number)+" and left "+str(attempts_left)+" attempts"
            print ">>>>>>>>>>>>>>>>Guess Higher<<<<<<<<<<<<<<<<"
        else:
            print"----------------------------------------------"
            print "You guessed the number "+str(player_number)+" and left "+str(attempts_left)+" attempts"
            print ">>>>>>>>>>>>>>>>Guess Lower<<<<<<<<<<<<<<<<"

# create frame

frame = simplegui.create_frame("Guess the Number", 200, 200)

# register event handlers for control elements
frame.add_button ("Guess Number from 0 - 100", range100)
frame.add_button ("Guess Number from 0 - 1000", range1000)
frame.add_input ("Put Your Guess Here (Integers Only)", input_guess , 200)

range100()
# call new_game and start frame

frame.start()