Popular Posts

Showing posts with label Python. Show all posts
Showing posts with label Python. Show all posts

Saturday, July 6, 2013

Simple Peg Solitaire Game in Python



Description:

   It is a Simple Peg Solitaire command line game in python. It has two classes Board and Play.
When create Object for Board class it initialize game board like the above picture. Board class contain methods to display board and check any valid move have in this board.

        Player Class methods get the move positions from the user and validate positions, play with the game with user entered date it valid.

Main function plays the game with the Board and Player classes.

 




 """Pige Solatire  Game"""

PEG = 'O'
BLANK = '#'
HOLE = ' '

class Board:
    """ This class is responsible to create board and checking board status"""

    def __init__(self):
        """ Initialize Board and it's attributes"""

        self.move = 0
        self.max_row = 7
        self.max_col = 7
        self.max_move = 31
        self.board = []
        self.board.append([BLANK, BLANK, PEG, PEG, PEG, BLANK, BLANK])
        self.board.append([BLANK, BLANK, PEG, PEG, PEG, BLANK, BLANK])
        self.board.append([PEG, PEG, PEG, PEG, PEG, PEG, PEG])
        self.board.append([PEG, PEG, PEG, HOLE, PEG, PEG, PEG])
        self.board.append([PEG, PEG, PEG, PEG, PEG, PEG, PEG])
        self.board.append([BLANK, BLANK, PEG, PEG, PEG, BLANK, BLANK])
        self.board.append([BLANK, BLANK , PEG, PEG, PEG, BLANK, BLANK])
      
    def print_board(self):
        """ Display current status of board """

        print '\nBoard:\n'
        print "  0 1 2 3 4 5 6"
        print "---------------"
        count = 0
        for row in self.board:
            print ("%d") % (count),
            count += 1
            for position in row:
                print position,
            print ''
  
    def check_move_possible(self):
        """ Check for further valid move in the board"""

        for i in range(self.max_row):
            if(i < 2 or i > 4):
                ret = self.three_row_check(i)
            else:
                ret = self.seven_row_check(i)
            if(ret == True):
                return True

        for i in range(self.max_col):
            if(i < 2 or i > 4):
                ret = self.three_col_check(i)
            else:
                ret = self.seven_col_check(i)
                if(ret == True):
                    return True
        return False
                          
    def three_row_check(self, row):
        """ Checking valid move in three column rows"""
      
        if(self.board[row][2] == PEG and self.board[row][3] == PEG
           and self.board[row][4] == HOLE):
            return True

        if(self.board[row][2] == HOLE and self.board[row][3] == PEG
           and self.board[row][4] == PEG):
            return True
        return False

    def seven_row_check(self, row):
        """ Checking valid move in seven column rows"""
      
        for i in range(self.max_col):
            if(i == 0):
                if(self.board[row][0] == PEG and self.board[row][1] == PEG \
                       and self.board[row][2] == HOLE):
                    return True
            elif(i == 6 or i == 5):  
                if(self.board[row][6] == PEG and self.board[row][5] == PEG \
                       and self.board[row][4] == HOLE):
                    return True
            else:
                if(self.board[row][i] == PEG and self.board[row][i + 1] == PEG):
                    if(self.board[row][i - 1] == HOLE or \
                           self.board[row][i + 2] == HOLE):
                        return True
        return False

    def three_col_check(self, col):
        """ Checking valid move in three row cols"""
      
        if(self.board[2][col] == PEG and self.board[3][col] == PEG \
               and self.board[4][col] == HOLE):
            return True

        if(self.board[2][col] == HOLE and self.board[3][col] == PEG \
               and self.board[4][col] == PEG):
            return True
        return False

    def seven_col_check(self, col):
        """ Checking valied move in seven row cols"""
      
        for i in range(self.max_row):
            if(i == 0):
                if(self.board[0][col] == PEG and self.board[1][col] == PEG \
                       and self.board[2][col] == HOLE):
                    return True
            elif(i == 6 or i == 5):  
                if(self.board[6][col] == PEG and self.board[5][col] == PEG \
                       and self.board[4][col] == HOLE):
                    return True
            else:
                if(self.board[i][col] == PEG and self.board[i + 1][col] == PEG):
                    if(self.board[i - 1][col] == HOLE or \
                           self.board[i + 2][col] == HOLE):
                        return True
        return False
  

  
class Play:
    """ This class is responsible to get move info \
    from player and play peg solitaire game."""

    def __init__(self):

        "initialize instance variables"
        self.get_row = 0
        self.get_col = 0
        self.put_row = 0
        self.put_col = 0
        self.midr = 0
        self.midc = 0

    def get_pos(self):
        """ Get move position from user"""

        self.get_row = int (raw_input("Enter row no to get peg : "))
        self.get_col = int (raw_input("Enter col no to get peg : "))
        self.put_row = int (raw_input("Enter row no to put peg : "))
        self.put_col = int (raw_input("Enter col no to put peg : "))
      
    def validate_pos_board(self):
        """ Validate user entered position inputs with board layout"""

        if(self.get_row < 0 or self.get_row > 6):
            return False

        if(self.get_col < 0 or self.get_col > 6):
            return False

        if(self.put_row < 0 or self.put_row > 6):
            return False
      
        if(self.put_col < 0 or self.put_col > 6):
            return False
        return True

    def validate_valied_pos(self):
        """ validate user entered positions """

        if(self.get_row == self.put_row):
            val = self.get_col - self.put_col
            if(val == -2 or val == 2):
                self.midr = self.get_row
                self.midc = (self.get_col + self.put_col) / 2
                return True
        if(self.get_col == self.put_col):
            val = self.get_row - self.put_row
            if(val == -2 or val == 2):
                self.midr = (self.get_row + self.put_row) / 2
                self.midc = self.get_col
                return True
        return False
          
    def validate_pos_with_peg_and_play(self, board):
        """ Valid date user entered position with valid move"""

        if(board.board[self.get_row][self.get_col] == PEG):
            if(board.board[self.put_row][self.put_col] == HOLE):
                if(board.board[self.midr][self.midc] == PEG):
                    board.board[self.get_row][self.get_col] = HOLE
                    board.board[self.put_row][self.put_col] = PEG
                    board.board[self.midr][self.midc] = HOLE
                    board.move += 1
                    return True
                return False
            return False

def main():
    """ Function for playing Peg Solitaire """
    play_board = Board()
    player = Play()
  
    while(True):
        play_board.print_board()
        player.get_pos()
      
        ret = player.validate_pos_board()
        if(ret == False):
            print "Wrong Position"
            continue
      
        ret = player.validate_valied_pos()
        if(ret == False):
            print "Wrong Position"
            continue
      
        ret = player.validate_pos_with_peg_and_play(play_board)
        if(ret == False):
            print "Wrong Position"
            continue
      
        ret = play_board.check_move_possible()
        if(ret == False):
            print "No more legal Moves"
            play_board.print_board()
            break
      
        if(play_board.move == play_board.max_move):
            print "Congratulations!! you have solved the puzzle!"
            play_board.print_board()
            break

if __name__ == '__main__':
    main()
  

Thursday, December 15, 2011

GETTING BUS TIMING UPDATE THROUGH SMS(USING PYTHON)


    In this modernized world SMS is one thing  which is useful in getting regular updates and information easily.
This simple project is used to get update of  bus timing through SMS.

GSM Modem (Global System for Mobile communication):
     GSM modem is a device in mobile communication for data transfer(SMS, Cal). Many GSM Modems available in  market, for our project, We use GSM Modem with serial port for sending and receiving SMS in PC using AT commands.

Requirements:

Hardware:
 *  A GSM Modem with serial port cable.
 *  PC.
 *  A Valied SIM card for communication.

Software:
 * Python 2.7,  Pyserial module for serial communication, MySQLdb module for (MYSQL data base   connectivity)
 * MySQL Database


Sample Testing:
 * Create a database(DB) named 'bus' in MySQL and in that DB create a table names 'route'
     with unnecessary fields route, time1, time2, time3 as varchar type.
 * insert values into table 'route'.
 * insert SIM card in modem and connect to the PC.
 * Run the below python code in our PC.
 * Send SMS in format, TIME<space> <route> from another mobile to the SIM which you insert in
    GSM   Modem.
  *  If you send correct route the code fetch data from the 'route' table those match from the received route
     and send back to you.
 * In case the format is wrong or wrong route it send info accordingly.

Code:
import serial
import MySQLdb


def send_sms(ser,no,sms):
    ser.write("AT+CMGS="+no+"\r")
    ch = ser.readline()
    ch = ch.strip()
    while ch != ">":
        ch = ser.readline()
        ch = ch.strip()
    ser.write(sms+"\x1A")
    ser.readline()
    sucess = ser.readline()
    if sucess == "OK":
        print "SMS send:" + sms
    else:
        print "Failed to send"
              
def delete_sms(ser,loc):
    ser.write("AT+CMGD="+str(loc)+",4\r")
    ser.readline()
    while True:
        if ser.readline() == "OK":
            break

    print "SMS Deleted sucessfully"

def open_db(dbname):
    conn = MySQLdb.Connection( host="localhost", user="root", passwd="password", db=dbname)
    print "connection object ready"
    mysql = conn.cursor()
    print "cursor object ready"
    return mysql

def modem_init():
    ser = open_serial("/dev/ttyUSB0")
    while True:
        ser.write("AT+CMGF=1\r")
        ser.readline()
        if ser.readline() == "OK":
            break
    while True:    
        ser.write("AT+CNMI=1,1,0,0,0\r")
        ser.readline()
        if ser.readline() == "OK":
            break
       
    print "modem ready for communication"
    return ser

def open_serial(port):
    ser = serial.Serial(port,9600,timeout=2)
    print "serial port opend"
    return ser

   
try:
    ser = modem_init()
    mysql = open_db("bus")
    while True:
        ms = ser.readline()
        m = ms.split(":")       
        if m[0] == "+CMTI":
            print "SMS received"
            m = ms.split(",")
            ser.write("AT+CMGR="+m[1]+"\r")
            ser.readline()
            ms = ser.readline()
            content = ser.readline()
            ser.readline()
            m = ms.split(",")
            no = m[1]
            print "Mobile NO:"+ no
            content = content.upper()
            content = content.strip()
            print "Content:"+ content
            time = content.split(" ")
            if time[0] == "TIME":
                if time[1] != " ":
                    query = "select * from route where route = '"+ time[1] +"'"
                    mysql.execute(query)
                    resultset = mysql.fetchall()
                    if resultset == ():
                        sms = "wrong route"
                        send_sms(ser, no, sms)
                        delete_sms(ser, 1)
                       
                    else:
                        sms = "%s %s %s %s"% resultset[0]
                        print sms
                        send_sms(ser, no, sms)
                        delete_sms(ser, 1)
                else:
                    sms = "Wrong format TIME<space>ROUTE no route"
                    send_sms(ser, no, sms)
                    delete_sms(ser, 1)
                   
            else:
                sms = "Wrong format TIME<space>ROUTE"
                send_sms(ser, no, sms)
                delete_sms(ser, 1)
finally:
    ser.close()