TransWikia.com

How to check for errors in list? [problem not solved]

Stack Overflow Asked by hatten on January 22, 2021

Hi I have a program that allows the user to choose coordinates, and I’m having problem with error checking when a the user writes a coordinate that does not exist or a coordinate that is already taken. My program is a Memory tile game, and the coordinates and game board is built in a class called Board.

class Board:
    def __init__(self, A):
        self.A = A 
        self.list_gameboard, self.word_size = words(A) #self.list_gameboard is a list of (A ** 2 / 2) words witch is (* 2) to get pairs 
        self.matched = [] 
        self.reset()

    def convert_coords(self, coord):
        alphabet = list("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
        c1 = alphabet.index(coord[0])
        c2 = int(coord[1]) - 1
        return c1, c2

    def turn(self, coord): 
        c1, c2 = self.convert_coords(coord)
        self.hidden_gameboard[c1][c2] = self.list_gameboard[c1][c2]
        return self.list_gameboard[c1][c2]

…and it continues

until…

def main():
    done = False
    board = Board(A)

    board.show() 
    print("=", "====" * A, sep = "")

    while not done: 
        try:
            coord1 = input("Choose first coord: ").capitalize()
        except(IndexError, ValueError):
            print("You did not write a correct coordinate")
        if coord1 not in board.list_gameboard[]:
            print("You did not choose a coordinate that exists")
        if coord1 in board.matched[]:
            print("You chose a coordinate that is already taken")

        word1 = board.turn(coord1)
        board.show()
        print("=", "====" * A, sep = "")

The try-except part is my attempt on solving this problem.

To clarify: A is the matrix size of the board (nxn) and looks for example like this:

Choose gameboard size (only even numbers): 4
   1   2   3   4   
A --- --- --- ---
B --- --- --- ---
C --- --- --- ---
D --- --- --- ---
=================

I’m currently receiving this error:

if coord1 not in board.list_gameboard[]:
                                      ^

SyntaxError: invalid syntax

One Answer

The problem is that you are trying something that will not cause exception (or at least, not the ones you are interested in!): what you want to check for exception is the part in which you use a coordinate already taken or nonexistant.

The simplest way to rewrite that part is probably as:

coord = input("Choose first coord: ").capitalize()
if coord1 not in board.list_gameboard:
    print("You did not choose a coordinate that exists")
if coord1 in board.matched:
    print("You chose a coordinate that is already taken")

But you should really think about what you want to achieve here. For instance, I think it makes more sense to add this sanity check as an internal method of the class (i.e. I would perform the internal check when the user call the method board.turn), letting the external code to eventually catch the exception and deal with that.

For instance, the class might look like:

class Board:
    ...
    def _sanity_check(self, coord):
        if coord not in self.list_gameboard:
             raise ValueError("Coordinates {} do not exists".format(coord))
        if coord in self.matched:
             raise ValueError("Coordinates {} already taken".format(coord))

    def turn(self, coord):
        self._sanity_check(coord)
        c1, c2 = self.convert_coords(coord)
        self.hidden_gameboard[c1][c2] = self.list_gameboard[c1][c2]
        return self.list_gameboard[c1][c2]

and then call the turn method with something similar to

while True:
   try:
       board.turn(input("Choose first coord: ").capitalize())
   except ValueError as e:
       print(e)
   else:
       break

Which uses a while loop to wrap the input method which is broken as soon as the user insert valid coordinates.

Actually, having a more clear picture of how this game works I think you could come up of a better way to handle this, this is most probably not the smartest one (and for sure you could define better exceptions for your particular case).

Answered by jschiavon on January 22, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP