Hi, Im doing this memory game where im supposed to randomize 18 words from a file, duplicate them and shuffle and then place in a matrix 6 x 6. Ive gotten quite far, but im not sure what the best way is to place the words in the matrix, and been searching for ways a couple of days but cant find much info about this.

The "player" is supposed to pick 2 words and then i need to compare them, but right now i cant get passed the matrix bit. One of my friends thought we could make a list with a fixed size like list = [6][6], but then i get errors... can i do it in the way i intended or should i just go about it a totally different way?? Kind regards / Suzy

import random


class Ruta:
        def __init__(self, ord ): 
                self.ord = ord
                self.hidden = True
        def turn(self):
                if self.hidden == True:
                        self.hidden = False
                else:
                        self.hidden = True
            
        def __str__(self):
                if self.hidden:
                                return "---"
                else:
                                return self.ord



def main():

    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    index = 0

    while index < 18:
        valdaord.append(words[index].rstrip('\n'))
        valdaord.append(words[index].rstrip('\n'))
        index += 1   
    random.shuffle(valdaord)

    print len(valdaord)



   liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)


    matobj = [6][6]

    a = 0
    for i in range(0,5):
        matobj[0][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(6,11):
        matobj[1][a] = liobj[i]
        a = a + 1
    a = 0 
    for i in range(12,17):
        matobj[2][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(18,23):
        matobj[3][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(24,29):
        matobj[4][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(30,35):
        matobj[5][a] = liobj[i]
        a = a + 1



bokstav = ['', 'A', 'B', 'C', 'D', 'E', 'F']
sifferlista = ['','1','2','3','4','5','6',]

for i in range (0,6):
        for j in range(0,6):
                if j==0:
                        print bokstav[i]
                elif i==0:
                        print sifferlista[j]
                print li_bredd[i,j]


main()

gameover = False
while !gameover:
    gissning = 0.0

    bok = raw_input('Vilken rad? (A-F)').lower()
    bok = strIn[0]
    siffra = input('Vilken kolumn? (1-6)')
    siffra = strIn[1]

        if bok =='A';
            index = 0
        elif bok == 'B';
            index = 1
        elif bok == 'C';
            index = 2
        elif bok == 'D';
            index = 3
        elif bok == 'E';
            index = 4
        elif bok == 'F';
            index = 5
        gissning = gissning + 0.5

    if all is turned
        gameover = True

and some more code...

You would use a [6][6] list of lists.

list_6x6=[]     ## outer 'matrix'
   junk = []
   for k in range(0, 6):                   ## inner list with length=6
      junk.append(j*6 + k)
   list_6x6.append(junk)

for single_list in list_6x6:
   print single_list

Also, you can use a dictionary instead of those if/elif.

if bok =='A';
            index = 0
        elif bok == 'B';
            index = 1
        elif bok == 'C';
            index = 2
        elif bok == 'D';
            index = 3
        elif bok == 'E';
            index = 4
        elif bok == 'F';
            index = 5
#
##   replace with
bok_dic = { "A":0, "B":1, "C":2, "D":3, "E":4, "F":5 }
if bok in bok_dic:
   index = bok_dic[bok]
else:
   index = -1

Finally, the following code uses the same value for "a" over and over. Instead, use two for() loops (adding 6 to the value of i). Post back if you can't get it and look at the first example I posted.

for i in range(0,5):
                    |-----this would be "i" = 0 --> 5
        matobj[0][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(6,11):
        matobj[1][a] = liobj[i]
        a = a + 1
    a = 0 
    for i in range(12,17):
        matobj[2][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(18,23):
        matobj[3][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(24,29):
        matobj[4][a] = liobj[i]
        a = a + 1
    a = 0
    for i in range(30,35):
        matobj[5][a] = liobj[i]
        a = a + 1

Optionally, unless the requirements specifically require that you use a 6 by 6 matrix internally, the program could continue to store the grid in a single list. The internal program structure of your data does not need to be the same as the external representation. Use the internal structure that makes the most sense and makes the implementation the easiest.

You just have to be able to display it as a grid and reference the list like it was a grid.

For the list, elements 0-5 would be row 1, 6-11 row 2, etc.

So if row is 0-5 and col is 0-5 the index would be (row * 5 + col) .

If row is 1-6 and col is 1-6 adapt by subtracting one when doing the calculation. ((row - 1) * 5 + (col - 1)) I would be tempted to implement a 'board' or 'table' class that supported displaying the matrix to the player and allow the rest of the program to reference elements in the list like it was a 6 x 6 matrix. The class could optionally also support using letters as the row index if that would help.

Optionally, unless the requirements specifically require that you use a 6 by 6 matrix

I found that odd as well. Perhaps you should re-read the problem and make sure that it requires a 6x6. The 6X6=36 evidently comes from 18 words X2 = unscrambled and scrambled, in which case there would be 2 lists, one for the unscrambled and one for the scrambled. Anyway, if you haven't solved it yet, post back with a little more info.

Hi there, and thanks for your interest in my problem. I don't specificly need to place them in a 6x6 list, but they do need to be displayed as a 6x6 matrix when you play the program, so the player can choose which row/col. One of my teachers helped me out and his solution was to put it in a list like that, but he didnt know the last code to actually make it work, and then the lesson ended, so now im quite lost since i was following his idea, and now im not sure it will work at all :/ and this program is due on thursday..

It doesnt have to be 2 lists, one scrambled and one not scrambled. I just have to randomize 18 word and duplicate them, then place them a list. Then place them in a grid/matrix so a person can choose...

Hope it makes it clearer..Anyone got some new ideas?

Ive also posted in another forum... and so far ive gotten 4 different ways of how to do it.. how do I choose and why does it differ so much? Thanks // Susanna

This is the easiest way to understand that I can think of for printing 6 across. One while loop, no multiple for loops. You should decide how the user will pick the column and row that they want, unless I missed it in your code (obviously, a 6x6 matrix will be easier to determine row and column).

words = [ "one", "two", "three", "four", "five", "six", "seven", \
          "eight", "nine", "ten", "eleven", "twelve", "thirteen", \
          "fourteen", "fifteen", "sixteen", "seventeen", "eighteen" ]
ctr = 0
while ctr < 18:
   print "%-11s" % (words[ctr]),     ## note the comma
   ctr += 1
   if ctr % 6 == 0:
      print     ## newline

Have you done anything with your program in the last couple of days?

Did you like any of the suggestions?

Normally, we like to give you advice and don't like to write your code for you. The help you receive tends to vary directly with the amount of effort you appear to be putting in. We (ok I) feel that putting in effort to contribute to the solution (even if you got the idea from someone else) helps you to learn more from the process.

If you like an idea, but are having trouble implementing it, show us your work (-- this shows your effort --) and we will help you correct what isn't working.

If you've been working on the code and making changes, please post the updated code. If you're having problems with the updated code, describe what it is doing and what you wanted it to be doing and we'll make suggestions on how to get the two closer together.

Hi!! Yes ive been workin a lot with it, but i kinda struggle since we didnt have many good lessons, and not a lot of scheduled lessons with teacher assistance.. And the book we are learning from or should i say .pdf is "Starting out with Python" and its very basic. I chose memory game coz i thought it would be fun and maybe if i had the time i would do a graphic version so i could get an A. But since we were 88 students and only around 4 assistants per lesson i dont feel ive gotten the help i was promised. Anywhoo..

I first started out with one .py-document, but now im workin in 3 different ones testing them out...

One problem is right now that i need to first write the letters (ABCDEF) in front of the row, so thats what im trying to do now...probably very easy but im struggling..

this is one of them, trying to implement what you guys been saying.

import random


class Ruta:
    def __init__(self, ord ): 
        self.ord = ord
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
            
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord


def main():

    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    index = 0

    while index < 19:
        valdaord.append(words[index].rstrip('\n'))
        valdaord.append(words[index].rstrip('\n'))
        index += 1   
    random.shuffle(valdaord)
  # print valdaord
  # print len(valdaord)

#def skapa_plan(rad,kol):
    liobj = []
    for ord in valdaord:
        #R = Ruta(ord)
        R = ord
        liobj.append(R)

    row1 = '     1      2      3      4      5      6'         
    print row1
    row2 = liobj[0:6]
    print 'A', row2
    row3 = liobj[6:12]
    print 'B', row3
    row4 = liobj[12:18]
    print 'C', row4
    row5 = liobj[18:24]
    print 'D', row5
    row6 = liobj[24:30]
    print 'E', row6
    row7 = liobj[31:37]
    print 'F', row7

    print '     1      2      3      4      5      6'         
    bokstav = ['', 'A', 'B', 'C', 'D', 'E', 'F']
    words = liobj[0:36]
    ctr = 0
    while ctr < 36:
        print "%-5s" % (words[ctr]),     ## note the comma
        ctr += 1
        if ctr % 6 == 0:
            bo = 0
            while bo in bokstav:
                print bokstav[bo],
                bo += 1
                print     ## newline


"""
    print '     1      2      3      4      5      6'         
    if liobj[0:6]:
        print 'A', valdaord[0:6]
    if liobj[6:12]:
        print 'B', valdaord[6:12]
    if liobj[12:18]:
        print 'C', liobj[12:18]
    if liobj[18:24]:
        print 'D', liobj[18:24]
    if liobj[24:30]:
        print 'E', liobj[24:30]
    if liobj[31:37]:
        print 'F', liobj[31:37]
"""

"""  
    bokstav = ['', 'A', 'B', 'C', 'D', 'E', 'F']
    sifferlista = ['','1','2','3','4','5','6',]

    for i in range (0,6):
        for j in range(0,6):
            if j==0:
                print bokstav[i]
            elif i==0:
                print sifferlista[j]
            print li_bredd[i,j]


    i=0
    li_rad = []
    while i < 6:
        j=0
        li_kol = []
        while j < 6:
            li_kol.append(Ruta())
            j = j+1
        li_rad.append(li_hojd)
        i = i+1
        return spelplan
    print spelplan

    list_6x6=[]
    for j in range(0,6):
        junk = []
        for k in range(0,6):
            junk.append(j*6 + k)
            list_6x6.append(Ruta())

    for single_list in list_6x6:
        print single_list

def visa_spelplan(minor):
    for n in minor:
        print minor[n]
        for m in minor[n]:
            #print li_hojd[n]
            if spelplan[n][m].min_status == 1:
                print "x"
            else:
                print "[]"
"""
main()

A lot of crap code in the other one... but i was trying out different ways of doing it.. the last but about minor is from a game called minesweeper..

Im not supposed to show the words in the matrix unless the player turn the position with the word around. Its supposed to show as "---" when its face-down.

Now i atleast have them in line which is good, but need to add the A B C D E F and also make them "secret"

:( Im wondering if this is gonna take to much time and i should choose another program to do, since my classmates who picked the easy ones only have around 50 lines of code :/ But im not sure i can change my assignment now since its due on thursday anyway. Gosh..

Thanks a bunch for your interest in helping out with Python, how come you all are so helpful? :)

//Susanna

import random


class Ruta:
    def __init__(self, ord ): 
        self.ord = ord
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
            
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord


def main():

    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    index = 0

    while index < 19:
        valdaord.append(words[index].rstrip('\n'))
        valdaord.append(words[index].rstrip('\n'))
        index += 1   
    random.shuffle(valdaord)
  # print valdaord
  # print len(valdaord)

#def skapa_plan(rad,kol):
    liobj = []
    for ord in valdaord:
        #R = Ruta(ord)
        R = ord
        liobj.append(R)

    row1 = '     1      2      3      4      5      6'         
    print row1
    row2 = liobj[0:6]
    print 'A', row2
    row3 = liobj[6:12]
    print 'B', row3
    row4 = liobj[12:18]
    print 'C', row4
    row5 = liobj[18:24]
    print 'D', row5
    row6 = liobj[24:30]
    print 'E', row6
    row7 = liobj[31:37]
    print 'F', row7

    print '     1      2      3      4      5      6'         
    words = liobj[0:36]
    ctr = 0
    while ctr < 36:
        print "%-5s" % (words[ctr]),     ## note the comma
        ctr += 1
        if ctr % 6 == 0:
            print     ## newline

Now Ive made it a bit cleaner.. but still no Letter index on each row.

Ive managed to apply the "Ruta-class" so it only shows '---' right now..

import random


class Ruta:
    def __init__(self, ord ): 
        self.ord = ord
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
            
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord


def main():

    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    index = 0

    while index < 19:
        valdaord.append(words[index].rstrip('\n'))
        valdaord.append(words[index].rstrip('\n'))
        index += 1   
    random.shuffle(valdaord)


#def gameboard(row,col):
    liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)


   
    print ' 1     2     3     4     5     6'         
    words = liobj[0:36]
    ctr = 0
    while ctr < 36:
        print "%-5s" % (words[ctr]),     
        ctr += 1
        if ctr % 6 == 0:
            print

Try this for the display:

print
    #      # ####### ####### ####### ####### ####### #######
    print '     1       2       3       4       5       6'
    for row in range(6):
        print chr(65 + row),
        for col in range(6):
            print "%7s" % liobj[row * 6 + col],
        print

In my sample code, I expanded the space for a word to 7 letters (my list had a couple of 6 letter words on it.)

I modified Ruta to use 7 dashes instead of 3 and I also modified it to 'center' the word in 7 spaces so I could skip the forced left or forced right alignment.

It was a bit brute force, but I used:

def spacepad( inword, padlen):
    if len(inword) < padlen:
        nspace = padlen - len(inword)
        nlead = nspace / 2
        ntail = nspace - nlead
        return ' ' * nlead + inword + ' ' * ntail
    return inword

Hi!
Have you all left me to my own misery now ? ;)

This is where im at right now..

Have you got any ideas? I dont quite get how im supposed to end the game. Im playing about with the "while not gameover"..

How am I supposed to store the user input to make the '---' turn over to a word. And how do i make sure it doesnt turn back until the second choice from the user. And then if they are a match keep them turned up for the rest of the game. And how to i match them?

Oh, and is it better to use the "def gameboard():" than to have the code straight under main():? and if so, does that mean i can call for the printout of the gameboard with a simple line?

import random

class Ruta:
    def __init__(self, ord ): 
        self.ord = ord
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
            
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord


    
""" 
    bok_dic = { "A":0, "B":1, "C":2, "D":3, "E":4, "F":5 }
    if bok in bok_dic:
            index = bok_dic[bok]
    else:
    index = -1
"""


def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    index = 0
    while index < 19:
        valdaord.append(words[index].rstrip('\n'))
        valdaord.append(words[index].rstrip('\n'))
        index += 1   
    random.shuffle(valdaord)

#def gameboard():
    liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)

    print ' 1     2     3     4     5     6'         
    words = liobj[0:36]
    ctr = 0
    while ctr < 36:
        print "%-5s" % (words[ctr]),     
        ctr += 1
        if ctr % 6 == 0:
            print     

#gameover = False
#while not gameover:
    guess = 0.0

    letter = raw_input('Which row? (A-F)').lower()
   # letter = strIn[0]
    number = input('Which column? (1-6)')
    #number = strIn[1]
    guess = guess + 0.5
    if letter =='A':
        choice = liobj[number-1]
    elif letter == 'B':
        choice = liobj[5+number]
    elif letter == 'C':
        choice = liobj[11+number]
    elif letter == 'D':
        choice = liobj[17+number]
    elif letter == 'E':
        choice = liobj[23+number]
    elif letter == 'F':
        choice = liobj[29+number]

    choice.turn()         

"""
    R = Ruta()
    R.turn();  
    choice1 = choice2

    if all is turned up
       gameover = True

    print gameboard

    if self.hidden == False
        gameover = True
"""

    print 'You guessed', guess, ' times'

main()

Hi! Oh i missed your reply! I've been waiting all day, but now when i posted i realised it had ended up on "page 2"........

The first bit of code, for the print out worked excellent, but i dont understand the second code part, and not sure where i should implement it?

//Susanna

I called that second part from the Ruta __init__:

wordsize = 7

    def __init__(self, ord ):
        self.ord = spacepad(ord, wordsize)
        self.hidden = True

I actually declared a main function

def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

Inside main, the game loop starts like this:

nmatch = 0    
    nguess = 0
    while nmatch < 18:
        drawBoard(liobj)

drawBoard displays all of the words in the grid. Note that I pass it the liobj list with all of the Ruta in it. The liobj list is local to my main so I have to pass it to the functions that help.

My input validation routines allow the user to select a card, but before they accept the card, they confirm that it is hidden. They also test to make sure the selection is in range and properly formatted. (I have the user select a card like 'B3' or 'C4')

I ask for the first card (validate it) flip it and drawBoard again.
I ask for second card (validate it) flip it and drawBoard again.
Then I compare the first card to the second card, if the cards match, I increment nmatch. If they don't match I flip both cards back.

Unless the game is over, the loop in main goes back and draws the board again.

Hi again.
So what is "inword" ? And when i try to run my program, it said NameError: global name 'liobj' is not defined
And whats spacepad? :/:/:/

import random

wordsize = 7
class Ruta:

    def __init__(self, ord ):
        self.ord = spacepad(ord, wordsize)
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
    def __str__(self):
        if self.hidden:
            return "-----"
        else:
            return self.ord    


def spacepad(inword, padlen):
    if len(inword) < padlen:
        nspace = padlen - len(inword)
        nlead = nspace / 2
        ntail = nspace - nlead
        return ' ' * nlead + inword + ' ' * ntail
    return inword

def drawBoard():
    liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)
        
    print

    print '      1       2       3       4       5       6'
    for row in range(6):
        print chr(65 + row),
        for col in range(6):
            print "%7s" % liobj[row * 6 + col],
        print

    
def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    nmatch = 0    
    nguess = 0
    while nmatch < 18:
        drawBoard(liobj)


#gameover = False
#while not gameover:
    #guess = 0.0
"""
    letter = raw_input('Which row? (A-F)').lower()
   # letter = strIn[0]
    number = input('Which column? (1-6)')
    #number = strIn[1]
    guess = guess + 0.5
    if letter =='A':
        choice = liobj[number-1]
    elif letter == 'B':
        choice = liobj[5+number]
    elif letter == 'C':
        choice = liobj[11+number]
    elif letter == 'D':
        choice = liobj[17+number]
    elif letter == 'E':
        choice = liobj[23+number]
    elif letter == 'F':
        choice = liobj[29+number]

    choice.turn()         


    R = Ruta()
    R.turn();  
    choice1 = choice2

    if all is turned up
       gameover = True

    print gameboard

    if self.hidden == False
        gameover = True
"""

#print 'You guessed', guess, ' times'

main()
drawBoard()
spacepad()

When posting python code, please use python code tags
[code=python] # Your code here

[/code]

You didn't get everything that was supposed to be in main indented.

Here's the outline of how my code is organized...you don't have to match all of my code, this is just how I have it implemented.

import random

wordsize = 7

def spacepad( inword, padlen):
## This is the function that takes the input word (inword)
## and a size (padlen) and 'centers' the word by adding
## spaces around it until it is at least padlen characters long

class Ruta:
## This is the class that holds the word and whether or not
## the card is face up.

def drawBoard(wlist):
## This function draws the board (from the list of Ruta objects in wlist)

def decode(loc):
## I wrote this function to translate from 'A2' or 'B4' to the array index
## it returns -1 if the location is not valid

def doflip(wlist, loc):
## This function calls decode on the loc and then turns the card face up
## It will return false if the card is already face up, or if the location
## specified is invalid.

def docompare(wlist, loc1, loc2):
## This function compares the two cards (which must be face up)
## If the cards match it returns True
## If the cards do not match it turns the cards face down
## and returns False

# this is my entire main function
def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)

    for index in range(18):
        tword = words[index].strip()
        valdaord.append(tword)
        valdaord.append(tword)

    random.shuffle(valdaord)
    
    liobj = []
    for row in range(6):
        for col in range(6):
            liobj.append(Ruta(valdaord[row * 6 + col]))

    nmatch = 0    
    nguess = 0
    while nmatch < 18:
        drawBoard(liobj)
        
        while True:
            loc1 = raw_input("Select first card: ")
            if doflip(liobj, loc1):
                drawBoard(liobj)
                break

        while True:
            loc2 = raw_input("Select second card: ")
            if doflip(liobj, loc2):
                drawBoard(liobj)
                break
            
        if docompare(liobj, loc1, loc2):
            nmatch += 1
        nguess += 1
        
    print "You finished!"
    print "It took you", nguess, "guesses"
    
# This is first line in the file since wordsize=7
# that is not defining a function or class
main()

Oh ok, i get it now, that was a lot more def than i had expected! My teachers told me that i could do most of it in main... but guess they were up to no good :&

I will give it another shot since its due on friday! ( i had almost given up coz i could always show the program later, but then i will get the lowest grade)

thanks Murtan you gave some energy back to me!

Just because you 'could' do most of it in main doesn't mean you 'should'.

Start simple, write and test a simple function, make sure to give it both valid and invalid inputs. Make sure that it handles everything that it might expect to see.

For example, when I was testing the decode function, I gave it several valid values: 'A1', 'B5', 'f2', 'c4' but I gave it invalid values as well: 'c0', 'g3', 'a 4', '3c', 'd34', 'bug', 'dd'. I used my decode to help validate the user input. My version of the decode function actually displays the error messages using print. (This part will need to be reworked a little if I decide to make a GUI for the progam, but so will a lot of other code.)

Yeah, its just that as a beginner one tend to do what the teachers tell you.. but thats life!

Where does the wlist come from?

For the decoding part, should i use def decode (loc1, loc2) or is it enough with (loc) ?
I just put something together and it goes like:

def decode(loc1,loc2):

    loc1 = loc1.split()
    letter = loc1[0]
    number = loc1[1]
    
    if letter =='A':
        choice = liobj[number-1]
    elif letter == 'B':
        choice = liobj[5+number]
    elif letter == 'C':
        choice = liobj[11+number]
    elif letter == 'D':
        choice = liobj[17+number]
    elif letter == 'E':
        choice = liobj[23+number]
    elif letter == 'F':
        choice = liobj[29+number]

        if choice <= 35:
                return choice1
        else:
                return -1
        
    loc2 = loc2.split()
    letter = loc1[0]
    number = loc1[1]


    if letter =='A':
        choice = liobj[number-1]
    elif letter == 'B':
        choice = liobj[5+number]
    elif letter == 'C':
        choice = liobj[11+number]
    elif letter == 'D':
        choice = liobj[17+number]
    elif letter == 'E':
        choice = liobj[23+number]
    elif letter == 'F':
        choice = liobj[29+number]

        if choice <= 35:
                return choice2
        else:
                return -1

Is this way off?

I corrected a small thing i noticed.. the loc =loc1.split() should be l1=loc1.split() if im not mistaking.. :&

def decode(loc1,loc2):

    l1 = loc1.split()
    letter = l1[0]
    number = l1[1]
    
    if letter =='A':
        choice = liobj[number-1]
    elif letter == 'B':
        choice = liobj[5+number]
    elif letter == 'C':
        choice = liobj[11+number]
    elif letter == 'D':
        choice = liobj[17+number]
    elif letter == 'E':
        choice = liobj[23+number]
    elif letter == 'F':
        choice = liobj[29+number]

        if choice <= 35:
                return choice1
        else:
                return -1
        
    l2 = loc2.split()
    letter = l2[0]
    number = l2[1]


    if letter =='A':
        choice = liobj[number-1]
    elif letter == 'B':
        choice = liobj[5+number]
    elif letter == 'C':
        choice = liobj[11+number]
    elif letter == 'D':
        choice = liobj[17+number]
    elif letter == 'E':
        choice = liobj[23+number]
    elif letter == 'F':
        choice = liobj[29+number]

        if choice <= 35:
                return choice2
        else:
                return -1

The 'funny' part is, that you don't really have to split the loc at all and the decode prototype (with only one loc) was how I used it. All decode does is translate from 'a1' to 0, 'a2' to 1, 'a3' to 2, 'b1' to 6, ...

If there was anything wrong with the loc, it would complain and return -1.

My decode used if not loc[0].upper() in rowltr where rowltr was "ABCDEF" to decide to complain about an invalid row letter. I used a similar test against the string colnum ("123456") for validating the column. Once it was determined that the loc[0] and loc[1] were valid, I used rowltr.index(loc[0].upper()) to get the row index (0-5) and colnum.index(loc[1]) to get the column index (0-5) and then calculated the return value as row * 6 + col.

Your set of 'ifs' would have worked, except that the number in your examples is still a string, but you try to use it in math. (Didn't you try to test your function?)

my doFlip(wlist, loc) would call idx = decode(loc) , if the idx was < 0 then loc was invalid. Otherwise, it would look to see if the card at idx was already face up. If it was already face up, it would complain and return False. If it was face down, it would turn it face up and return True.

my doCompare(wlist, loc1, loc2) would call decode() twice, once for each loc. It didn't really do much additional testing as the loc's came from previously successful calls to doFlip(). It would then compare the string stored in each of the Ruta objects to see if they matched. If they matched, it returned True. If it didn't match, it turned both cards back to face down and returned False.

The wlist you see in drawboard, doflip and docompare is passed to those functions from the main. The main 'owns' the list of Ruta objects. In main it is called liobj. Inside the functions, they call it wlist.

Hi!
I wrote this before i saw your latest answer.. this is where im at now...

And im at school waiting for a tutor to help me! the assignment is due tomorrow.. but we are a few students here for the last lines... :)

import random
 
wordsize = 7

# En funktion som tar inword och en storlek (padlen) och centrerar ordet genom
# att lägga till mellanrum tills det är minst padlen-storlek lång så det ser snyggt ut.

def spacepad(inword, padlen):
    if len(inword) < padlen:
        nspace = padlen - len(inword)
        nlead = nspace / 2
        ntail = nspace - nlead
        return ' ' * nlead + inword + ' ' * ntail
    return inword

# Detta är klassen som håller ordet och om det är uppåt eller nedåt.
class Ruta:
    def __init__(self, ord ):
        self.ord = spacepad(ord, wordsize)
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord 
    

# Denna funktion ritar upp spelplanen(från listan av Rutaobjekt i wlist)
def drawBoard(wlist, valdaord):
    liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)
        
    print

    print '      1       2       3       4       5       6'
    for row in range(6):
        print chr(65 + row),
        for col in range(6):
            print "%7s" % liobj[row * 6 + col],
        print
    return drawBoard
    
 
def decode(loc):
## Funktion för att översätta user input från A4 till listindex.
## den skall returnera -1 om platsen inte är giltig.

    l1 = loc.split()
    letter = l1[0]
    number = int(l1[1])
    
    if letter =='A':
        choice = number-1
    elif letter == 'B':
        choice = 5+number
    elif letter == 'C':
        choice = 11+number
    elif letter == 'D':
        choice = 17+number
    elif letter == 'E':
        choice = 23+number
    elif letter == 'F':
        choice = 29+number

    if choice <= 35:
        return choice
    else:
        return -1
        
 
def doflip(wlist, loc):
    wlist[loc].turn()
#Denna funktion skall kalla på decode för loc och sen vända kortet faceup.
# Skall returnera False om kortet redan är faceup eller om platsen är fel.

 
def docompare(wlist, loc1, loc2):
# Denna funktion skall jämföra de 2 korten, som måste vara faceup.
# Om korten matchar så returneras True
# Om korten inte matchar så vänds korten nedåt och returnerar False
    if wlist(loc1).hidden == False and wlist(loc2).hidden == False:
       if wlist[loc1].ord == wlist[loc2].ord:
           return True
       else:
           return False

def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)
 
    for index in range(18):
        tword = words[index].strip()
        valdaord.append(tword)
        valdaord.append(tword)
 
    random.shuffle(valdaord)
 
    liobj = []
    for row in range(6):
        for col in range(6):
            liobj.append(Ruta(valdaord[row * 6 + col]))
 
    nmatch = 0    
    nguess = 0
    while nmatch < 18:
        drawBoard(liobj,valdaord)
 
        while True:
            loc1 = raw_input("Select first card between A-F and 1-6: ")
            l1 = decode(loc1)
            if choice<=-1:
                print 'You have chosen an invalid card'
            else:
                doflip(liobj, l1)
                drawBoard(liobj, valdaord)
                break
 
        while True:
            loc2 = raw_input("Select second card between A-F and 1-6: ")
            l2 = decode(loc2)
            if choice<=-1:
                print 'You have chosen an invalid card'
            else:
                doflip(liobj, l2)
                drawBoard(liobj, valdaord)
                break
 
        if docompare(liobj, loc1, loc2):
            nmatch += 1
        nguess += 1
 
    print "You are done!"
    print "You made", nguess, "guesses."
 
main()

Lines 109-112 fill the list liobj with a Ruta created from the words in valdaord. This should only happen once.

When you call drawBoard, you should only pass liobj: drawBoard(liobj) drawBoard should NOT attempt to fill the wlist, it is already full. The corrected drawBoard is:

def drawBoard(wlist):
    print '      1       2       3       4       5       6'
    for row in range(6):
        print chr(65 + row),
        for col in range(6):
            print "%7s" % wlist[row * 6 + col],
        print

Your current decode function does not validate the number part of the coordinate. (It would accept A9 for example.) It also has a problem with coordinates that do not have a number as the second digit, 5C for example (which is invalid, but shouldn't cause your program to exit).

In my version, doFlip called decode, I didn't call decode from the main, but either implementation works. One of the locations (either doFlip or main) needs to confirm that the card they select is face down. It would be bad form to let them pick the same card twice.

hi! Now it finally works!!!!!
Havent sorted out the invalid inputs yet.. So for now the player have to write like 'A 1', what and where could i fix it so the user can write both a and A, aswell as A1 without the space.. I know its supposed to be like .upper() but where exactly should i put it without messing it all up.. and the spacething..I know how to put .split(' ') but what should i write when i dont want anything in between since it doesnt work with .split('')... :/ wow cant believe im almost done! I was waiting for 1.5 hours for the assistant but he didnt show up.. then he did, then he was gone again and hasnt helped anyone for an hour.. so whilst in queue i wrote something here and there.. and TADA it was done!! Im finally getting a hang of this :)

import random
 
wordsize = 7

# En funktion som tar inword och en storlek (padlen) och centrerar ordet genom
# att lägga till mellanrum tills det är minst padlen-storlek lång så det ser snyggt ut.

def spacepad(inword, padlen):
    if len(inword) < padlen:
        nspace = padlen - len(inword)
        nlead = nspace / 2
        ntail = nspace - nlead
        return ' ' * nlead + inword + ' ' * ntail
    return inword

# Detta är klassen som håller ordet och om det är uppåt eller nedåt.
class Ruta:
    def __init__(self, ord ):
        self.ord = spacepad(ord, wordsize)
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord 
    
def createboard(valdaord):
    liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)
    return liobj

# Denna funktion ritar upp spelplanen(från listan av Rutaobjekt i wlist)
def drawBoard(liobj):
#    liobj = []
#    for ord in valdaord:
#       R = Ruta(ord)
#       liobj.append(R)
        
    print

    print '      1       2       3       4       5       6'
    for row in range(6):
        print chr(65 + row),
        for col in range(6):
            print "%7s" % liobj[row * 6 + col],
        print
    return drawBoard
    
 
def decode(loc):
## Funktion för att översätta user input från A4 till listindex.
## den skall returnera -1 om platsen inte är giltig.

    l1 = loc.split(' ')
    letter = l1[0]
    number = int(l1[1])

    if letter =='A':
        choice = number-1
    elif letter == 'B':
        choice = 5+number
    elif letter == 'C':
        choice = 11+number
    elif letter == 'D':
        choice = 17+number
    elif letter == 'E':
        choice = 23+number
    elif letter == 'F':
        choice = 29+number

    if choice <= 35:
        return choice
    else:
        return -1
    
        
 
def doflip(wlist, loc):
    wlist[loc].turn()
#Denna funktion skall kalla på decode för loc och sen vända kortet faceup.
# Skall returnera False om kortet redan är faceup eller om platsen är fel.

 
def docompare(wlist, l1, l2):
# Denna funktion skall jämföra de 2 korten, som måste vara faceup.
# Om korten matchar så returneras True
# Om korten inte matchar så vänds korten nedåt och returnerar False
    if wlist[l1].hidden == False and wlist[l2].hidden == False:
       if wlist[l1].ord == wlist[l2].ord:
           print 'Congratulations you found a pair!!!'
           return True
       else:
           wlist[l1].turn()
           wlist[l2].turn()
           print
           print
           print 'Tough luck, please try again!'
           print '_____________________________________________________'
           return False


def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)
 
    for index in range(18):
        tword = words[index].strip()
        valdaord.append(tword)
        valdaord.append(tword)
 
    random.shuffle(valdaord)
 
    liobj = createboard(valdaord)
    for row in range(6):
        for col in range(6):
            liobj.append(Ruta(valdaord[row * 6 + col]))
 
    nmatch = 0    
    nguess = 0
    while nmatch < 18:
        drawBoard(liobj)
 
        while True:
            print
            loc1 = raw_input("Select your first card between A-F and 1-6 i.e. A 1: ")
            l1 = decode(loc1)
            if l1<=-1:
                print 'You have chosen an invalid card'
            else:
                doflip(liobj, l1)
                drawBoard(liobj)
                break
 
        while True:
            print    
            loc2 = raw_input("Select second card between A-F and 1-6: ")
            l2 = decode(loc2)
            if l2<=-1:
                print 'You have chosen an invalid card'
            else:
                doflip(liobj, l2)
                drawBoard(liobj)
                break
 
        if docompare(liobj, l1, l2):
            nmatch += 1
        nguess += 1
 
    print "You are done!"
    print "You made", nguess, "guesses."
 
main()

What if we changed decode?

def decode(loc):
## Funktion för att översätta user input från A4 till listindex.
## den skall returnera -1 om platsen inte är giltig.
    letter = loc[0].upper()
    numchar = loc[1]
    if numchar.isspace():
        numchar = loc[2]
    number = int(numchar)
    # the rest of decode still goes here...

or we could try to use the length as a clue:

def decode(loc):
## Funktion för att översätta user input från A4 till listindex.
## den skall returnera -1 om platsen inte är giltig.
    if len(loc) == 2:
        letter = loc[0].upper()
        number = int(loc[1])
    elif len(loc) == 3:
        letter = loc[0].upper()
        number = int(loc[2])
    # the rest of decode still goes here...

Python has a feature where if we say loc[-1] we get the last character of loc. If we use that:

def decode(loc):
## Funktion för att översätta user input från A4 till listindex.
## den skall returnera -1 om platsen inte är giltig.
    letter = loc[0].upper()
    number = int(loc[-1])
    # the rest of decode still goes here...

Hi there!
Just wanted to let you know that I'm finished with the program!! Think i got it all right for now. Got to show my program at 2pm, which is in 2 hrs time.. and if the teacher doesnt have any objections i should get a B, the only way to get an A is to do the test with graphics.. I might do that later, but i am well happy with a B or C!

To get a B i have to be able to have words with different lengths, and if im not mistaken thats exactly what i can do!

Thanks a bunch for all your interest in my programming.

Kind regards
Suzy

import random

print 'Hi, welcome to my game of Memory' 
wordsize = 3

# En funktion som tar inword och en storlek (padlen) och centrerar ordet genom
# att lägga till mellanrum tills det är minst padlen-storlek lång så det ser snyggt ut.
def spacepad(inword, padlen):
    if len(inword) < padlen:
        nspace = padlen - len(inword)
        nlead = nspace / 2
        ntail = nspace - nlead
        return ' ' * nlead + inword + ' ' * ntail
    return inword

# Detta är klassen som håller ordet och om det är uppåt eller nedåt.
class Ruta:
    def __init__(self, ord ):
        self.ord = spacepad(ord, wordsize)
        self.hidden = True
    def turn(self):
        if self.hidden == True:
            self.hidden = False
        else:
            self.hidden = True
    def __str__(self):
        if self.hidden:
            return "---"
        else:
            return self.ord 

# Funktion för att göra själva listan.    
def createboard(valdaord):
    liobj = []
    for ord in valdaord:
        R = Ruta(ord)
        liobj.append(R)
    return liobj

# Denna funktion ritar upp spelplanen(från listan av Rutaobjekt i wlist)
def drawBoard(liobj):
      
    print
    print '      1       2       3       4       5       6'
    for row in range(6):
        print chr(65 + row),
        for col in range(6):
            print "%7s" % liobj[row * 6 + col],
        print
    return drawBoard
    
 

## Funktion för att översätta user input från A4 till listindex.
## den skall returnera -1 om platsen inte är giltig.
def decode(loc):
    letter = loc[0].upper()
    numchar = loc[1]
    if numchar.isspace():
        numchar = loc[2]
    number = int(numchar)
    if number >= 7:
        return -1

    if letter =='A':
       choice = number-1
    elif letter == 'B':
       choice = 5+number
    elif letter == 'C':
        choice = 11+number
    elif letter == 'D':
        choice = 17+number
    elif letter == 'E':
        choice = 23+number
    elif letter == 'F':
         choice = 29+number
    else:
        choice = -1

    if choice <= 35:
        return choice
    return -1

        
# Denna funktion skall kalla på decode för loc och sen vända kortet faceup.
# Skall returnera False om kortet redan är faceup eller om platsen är fel.
def doflip(wlist, loc):
    if wlist[loc].hidden == True:
        wlist[loc].turn()
        return True
    else:
        return False
 #  wlist[loc].turn()
    

 
def docompare(wlist, l1, l2):
# Denna funktion skall jämföra de 2 korten, som måste vara faceup.
# Om korten matchar så returneras True
# Om korten inte matchar så vänds korten nedåt och returnerar False
    if wlist[l1].hidden == False and wlist[l2].hidden == False:
       if wlist[l1].ord == wlist[l2].ord:
           print 'Congratulations you found a pair!!!'
           return True
       else:
           wlist[l1].turn()
           wlist[l2].turn()
           print
           print
           print 'Tough luck, please try again!'
           print '_____________________________________________________'
           return False


def main():
    infile = open("memo.txt", "r")
    words = []
    valdaord = []
    words = infile.readlines()
    infile.close()
    random.shuffle(words)
 
    for index in range(18):
        tword = words[index].strip()
        valdaord.append(tword)
        valdaord.append(tword)
 
    random.shuffle(valdaord)
 
    liobj = createboard(valdaord)
    for row in range(6):
        for col in range(6):
            liobj.append(Ruta(valdaord[row * 6 + col]))
 
    nmatch = 0    
    nguess = 0
    while nmatch < 18:
        drawBoard(liobj)
 
        while True:
            print
            loc1 = raw_input("Select your first card between A-F and 1-6: ")
            l1 = decode(loc1)
            if l1==-1:
               print '**You have chosen an invalid card. Please try again**'

            else:
               doflip(liobj, l1)
               drawBoard(liobj)
               break
 
        while True:
            print    
            loc2 = raw_input("Select second card between A-F and 1-6: ")
            l2 = decode(loc2)
            if l2==-1:
                print '**You have chosen an invalid card. Please try again**'
            else:
                if doflip(liobj, l2) == True:
                    drawBoard(liobj)
                    break
                else:
                    print
                    print '**Thats the same card, stupid!**'
 
        if docompare(liobj, l1, l2):
            nmatch += 1
        nguess += 1
 
    print "You are done!"
    print "You made", nguess, "guesses."
 
main()
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.