Go to do with a List

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Avatar19
    New Member
    • Apr 2010
    • 43

    Go to do with a List

    My question is:
    I have written a program to take input in the format e.g.

    0 0 0
    X 0 X
    X X 0


    the program is supposed to simulate "noughts and crosses" or "Tic Tac Toe" ,depending where you are from, and decide who is the winner i.e. "X" or "0" or if there is no winner, "draw". I am at the point where i can output for each 8 possibilities either "True" if X won or "False" if 0 won in the form of a list. What i don't know how to do is iterate over the elements in the list and get the program
    to evaluate if there are both True and False in list to output "draw", if there is only True, to output "X is the winner", or if there is only False, 0 is the winner.
    This is my code

    Code:
    def EvalC(A,B,C,V,K):
        #Evaluates each row or column to determine True or False
        if A== V:
            i = 1
            if B == V:
                i = 2
                if C == V:
                    i = 3
                    return True
        elif A == K:
            n = 1
            if B == K:
                n = 2
                if C ==K:
                    n = 3
                    return False
    Matrix = []
    while True:
        Input = raw_input()
        if Input:
            Input = Matrix.append(Input.split())
        else:
            break
    #takes the input an put it into a list
    #e.g.[['X', '0', '0'], ['X', '-', '-'], ['X', '0', '0']]
    TRow = Matrix[0][0] + Matrix[0][1] + Matrix[0][2]
    MRow = Matrix[1][0] + Matrix[1][1] + Matrix[1][2]
    BRow = Matrix[2][0] + Matrix[2][1] + Matrix[2][2]
    LCol = TRow[0] + MRow[0] + BRow[0]
    MCol = TRow[1] + MRow[1] + BRow[1]
    RCol = TRow[2] + MRow[2] + BRow[2]
    VertR = TRow[0] + MRow[1] + BRow[2]
    VertL = TRow[2] + MRow[1] + BRow[0]
    #above are all the possible combos for wins
    List1 =[(EvalC(TRow[0],MRow[0],BRow[0],"X","0")),(EvalC(TRow[1],MRow[1],BRow[1],"X","0")),(EvalC(TRow[2],MRow[2],BRow[2],"X","0")),
    (EvalC(TRow[0],MRow[1],BRow[2],"X","0")),(EvalC(TRow[2],MRow[1],BRow[0],"X","0")),
    (EvalC(Matrix[0][0],Matrix[0][1],Matrix[0][2],"X","0")),(EvalC(Matrix[1][0],Matrix[1][1],Matrix[1][2],"X","0")),
    (EvalC(Matrix[2][0],Matrix[2][1],Matrix[2][2],"X","0"))]
    #the function applied to each possible win combo
    A possible output at this level would be:
    List1=[True, None, None, None, None, None, None, None]
    Thanks you for any help and also please suggest ways to neaten and shorten my code with more productive functions. Thank you!!!
    Last edited by Avatar19; Apr 16 '10, 04:00 PM. Reason: made a mistake
  • Glenton
    Recognized Expert Contributor
    • Nov 2008
    • 391

    #2
    Hi

    Good job on the coding! A couple of points on simplifying the code. A class structure can be very helpful in organising the data.

    Also the 8 possible straight lines can be put into a list of some sort, so that you can go through them with a for structure. Personally I tend to use a for structure if there's >=2 items in the list, so I might be a bit extreme! But it is easier to understand and debug. Eg create a blank list (List1 = []), and then cycle through the possibilities appending the result to that. But since you've done the typing anyway, you might as well run with it!

    Now as I understand it, the central problem for you is that you've got a list of eight items, each of which can be True, False, or None, and you want to return something sensible.

    Add this to bottom of your code!
    Code:
    List1=[True,None,None,None]
    
    #Start with both players having lost
    Awon=False
    Bwon=False
    
    #Go through all the events and update the winner
    for i in List1:
        if i==True: Awon=True
        elif i==False: Bwon=True
    
    #Check if A won:
    if Awon:
        #Check if B also won
        if Bwon:
            print "both won!"
        else:
            print "A won!"
    else:
        if Bwon:
            print "B won!"
        else:
            print "Neither won!"
    Good luck, and post back to let us know how it goes!
    Last edited by Glenton; Apr 19 '10, 11:32 AM. Reason: typo

    Comment

    • Avatar19
      New Member
      • Apr 2010
      • 43

      #3
      Thanks so much for the input Glenton.. if its not too much trouble could i ask you to demonstrate what you would do with this?, When u talked about class structure and for loops?

      Comment

      • Glenton
        Recognized Expert Contributor
        • Nov 2008
        • 391

        #4
        Originally posted by Avatar19
        Thanks so much for the input Glenton.. if its not too much trouble could i ask you to demonstrate what you would do with this?, When u talked about class structure and for loops?
        Have you got the thing working overall? I'll try to have a look next week - since it's for a fellow saffa!

        Comment

        • Avatar19
          New Member
          • Apr 2010
          • 43

          #5
          Yah i did get it working i used a very similar if statement like you suggested in your first response so the program does work, but I am very interested to see different ways of doing this.. thanks any help is greatly appreciated

          Comment

          • Glenton
            Recognized Expert Contributor
            • Nov 2008
            • 391

            #6
            Originally posted by Avatar19
            Thanks so much for the input Glenton.. if its not too much trouble could i ask you to demonstrate what you would do with this?, When u talked about class structure and for loops?
            Okay, so this is not terribly sophisticated at this point. Object orientation takes a bit of getting used to. It doesn't do anything differently, it's just a way of structuring everything that's ultimately more convenient.

            You could then import this code to another script and use the class there, wrap it in a simple GUI or just into a game loop, include some logic for the computer to play some of the moves, alternate the tokens automatically etc.

            But I've just put in the basic code here to give you a feel for how it works. If you're not used to class structures it may take a while to get the feel for it. Please try to understand it quite hard before questions. But after bona fide effort, questions welcome!

            Code:
            class OX:
                """Class for noughts and crosses"""
                def __init__(self,startPos=None):
                    """Optional parameter of startPos (blank board if omitted)"""
                    
                    if startPos==None:  #create startPos with blank position
                        startPos = [['-','-','-'],['-','-','-'],['-','-','-']]
                    self.pos = startPos #self.pos is variable holding board structure
                
                def move(self,row,col,token):
                    "Add token (O or X) to (row,col) position (if allowed)"
                    if token in "oO0": token = "O"
                    if token in "xX": token = "X"
                    if token not in ['O','X']:
                        print "Token must be an 'O' or an 'X'"
                        return
                    if self.pos[row][col]=='-':
                        self.pos[row][col]=token
                    else:
                        print "Must move onto a blank space"
                
                def __repr__(self):
                    "Used for printing the position"
                    out=""
                    for i in range(3):
                        for j in range(3):
                            out+=self.pos[i][j]+'\t'
                        out+='\n'
                    return out
                
                def _lines(self):
                    "Generates a list of all 8 lines"
                    p=self.pos
                    l=[]
                    d1=[]
                    d2=[]
                    for i in range(3):
                        l.append([p[i][0],p[i][1],p[i][2]])
                        l.append([p[0][i],p[1][i],p[2][i]])
                        d1.append(p[i][i])
                        d2.append(p[i][2-i])
                    l.append(d1)
                    l.append(d2)
                    return l
                
                def testwinner(self):
                    "returns result of game so far"
                    l=self._lines()
                    xwin = (['X','X','X'] in l)
                    owin = (['O','O','O'] in l)
                    if xwin and owin:
                        return "Oops. Both win!"
                    if xwin:
                        return "X wins!"
                    if owin:
                        return "O wins!"
                    return "No winner"
                        
            
            def main():
                "Shows basic class functionality"
                game=OX()
                print "blank game created"
                print game  #This prints the output from __repr__ function
                print
                
                print "second game with pre-defined position created"
                game1=OX([['X', 'O', 'O'], ['X', '-', '-'], ['X', 'O', 'O']])
                print game1
                print
                
                print "Test who's won in second game"
                print game1.testwinner()
                print
                
                print "Move made in second game with invalid token"
                game1.move(1,1,'b')
                print
                
                print "Move made in second game on occupied square"
                game1.move(0,0,'O')
                print
                
                print "Valid move made in second game"
                game1.move(1,1,'O')
                print
                
                print "Second game position"
                print game1
                print "Test who's won in second game"
                print game1.testwinner()
                print
                
                print "First game is still blank"
                print game
                print
                
                print "Make move in first game"
                game.move(1,1,"x")
                print game
                print
                
                print "Test who's won first game"
                print game.testwinner()
                
            
            
            if __name__=="__main__": main()
            Helpful hint: Just copy paste and run at first. Then go through main function and you should be able to follow what it's doing!
            Last edited by Glenton; Apr 26 '10, 01:55 AM. Reason: helpful hint added at end

            Comment

            • Avatar19
              New Member
              • Apr 2010
              • 43

              #7
              Cool thanks a lot, I am going to give it a good look tomorrow and I'll let you know once I get to grips with it!!

              Comment

              Working...