Card Matching Game on Python - python

I am current building a simple card matching game in python, with a 5x4 (row*column) grid, in which two players try to match a deck of twenty cards (2,10 of only suit Hearts) * 2.
The problem I am running into is in iterating through the deck, printing the cards out in a grid fashion so it would look like this:
----- ----- ----- -----
- - - - - - - -
4-H 6-H 7-H 8-H
- - - - - - - -
----- ----- ----- -----
The code I currently have is below:
#needed import for shuffle function
from random import shuffle
#class for my deck
class Deck:
#constructor starts off with no cards
def __init__( self ):
self._deck = []
#populate the deck with every combination of suits and values
def Populate( self ):
#Heart, Diamond, Spades, Clubs
for suit in 'HDSC':
#Jack = 11, Queen = 12, King = 13, Ace = 14
for value in range(2, 15):
if value == 11:
value = 'J'
elif value == 12:
value = 'Q'
elif value == 13:
value = 'K'
elif value == 14:
value = 'A'
#add to deck list
self._deck.append(str(value) + '-' + suit)
#populate the deck with only hears hearts and all cards except face cards and aces (2, 3, 4, 5, 6, 7, 8, 9, 10) twice
def gamePop( self ):
suit = 'H'
for x in range(2):
for value in range(2, 11):
self._deck.append(str(value) + '-' + suit)
#shuffle the deck with the random import
def Shuffle( self ):
shuffle( self._deck )
#length of the deck
def len( self ):
return len( self._deck )
def stringIt( self ):
#Returns the string representation of a deck
result = ''
for c in self._deck:
result = result + str(c) + '\n'
return result
#class for a single card
class Card:
#constructor for what type of card it is
def __init__( self, value, suit ):
self._value = value
self._suit = suit
self._card = self._value + self._suit
#print the type of card
def Description( self ):
return ( self._card )
#overloaded ==
def __eq__( self, another ):
if ( self._card == another.Description() ):
return True
else:
return False
#main function which plays the game
def main():
#sets player counters to zero,
pOneCount = 0
pTwoCount = 0
#creates the deck to be put on the board
gameDeck = Deck()
gameDeck.gamePop()
gameDeck.Shuffle()
print(gameDeck._deck)
currentCard = 0
for row in range(5):
for card in range(0,4+i):
mystring =
print ('------- ' * 4)
print ('| | ' * 4)
for x in range(4):
print ('| ' +gameDeck._deck[currentCard]+'|'),
currentCard += 1
print ('| | ' * 4)
print ('------- ' * 4)
Edit: I cleared up the code which I've tried.
The current output is this:
------- ------- ------- -------
| | | | | | | |
| 7-H|
| 5-H|
| 7-H|
| 9-H|
| | | | | | | |
------- ------- ------- -------

the problem is in the def main():
def main():
print ('------- ' * 4)
print ('| | ' * 4)
for x in range(4):
print ('| ' +gameDeck._deck[currentCard]+'|'),
currentCard += 1
print ('| | ' * 4)
print ('------- ' * 4)
the * 4 just mean that this:
print ('------- ' * 4)
will become this:
print ('------- ' + '------- ' + '------- ' + '------- ' )
it can also be type as:
print ('------- ------- ------- ------- ' )
so. your problem is here:
for x in range(4):
print ('| ' +gameDeck._deck[currentCard]+'|'),
currentCard += 1
this would print as:
| 7-H|
| 5-H|
| 7-H|
| 9-H|
you need to put it as something like this:
print ('| ' +gameDeck._deck[currentCard]+'|'+'| ' +gameDeck._deck[currentCard+1]+'|'+'| ' +gameDeck._deck[currentCard+2]+'|'+'| ' +gameDeck._deck[currentCard+3]+'|')
so it would print in one line like how you want it:
| 7-H| | 5-H| | 7-H| | 9-H|
here is the code that i clean up a little. if it work like it should, it should work:
def main():
#sets player counters to zero,
pOneCount = 0
pTwoCount = 0
#creates the deck to be put on the board
gameDeck = Deck()
gameDeck.gamePop()
gameDeck.Shuffle()
print(gameDeck._deck)
currentCard = 0
for row in range(5):
for card in range(0,4+i):
print (' ------- ' * 4)
print (' | | ' * 4)
print (' | ' +gameDeck._deck[currentCard]+' | '+' | ' +gameDeck._deck[currentCard+1]+' | '+' | ' +gameDeck._deck[currentCard+2]+' | '+' | ' +gameDeck._deck[currentCard+3]+' | ')
print (' | | ' * 4)
print (' ------- ' * 4)
oh, and like John Y say (copy and paste):
The main function has a dangling mystring =, which is a blatant syntax error
here what i use to test, because the whole code don't work for me, i just tested the print part:
print (' ------- ' * 4)
print (' | | ' * 4)
print (' | ' +"1-H"+' | '+' | ' +"2-H"+' | '+' | ' +"3-H"+' | '+' | ' +"4-H"+' | ')
print (' | | ' * 4)
print (' ------- ' * 4)
that got me:
------- ------- ------- -------
| | | | | | | |
| 1-H | | 2-H | | 3-H | | 4-H |
| | | | | | | |
------- ------- ------- -------
>>>

Related

Outputting tictactoe board

I'm trying to print my tictactoe board so it looks like
| |
-+-+-
| |
-+-+-
| |
This is my code:
def __str__(self):
result = ""
for i in range(self.nrows):
for j in range(self.ncols):
cell = str(self.gameboard[i][j])
result += cell + "|"
result += "\n"
result += "-+"
result += '\n'
return result
The result looks like
| | |
-+
| | |
-+
| | |
-+
How should I change the code so it looks like the first board? self.nrows is the number of rows, self.ncols is the number of columns, and self.gameboard is the 2d array.
That's not the most pythonic way, and you probably should diverge the code into some functions, but it's working:
def __str__(self):
result = ""
for i in range(self.nrows):
for j in range(self.ncols-1):
cell = str(self.gameboard[i][j])
result += cell + "|"
result += "\n"
if i == self.nrows - 1:
break # added the last line, which is just |
for j in range(self.ncols-1):
result += "-+"
result += '-'
result += '\n'
return result
Output for self.nrows = self.ncols = 3 and self.gameboard[i][j] = ' ' for each i,j:
| |
-+-+-
| |
-+-+-
| |
You need to change the row result += "-+" to result += "-+" * self.ncols + "-". Reason is that you print "-+" symbol only once, but need to do that as many time as your number of columns. Also, in the end you need to add one more "-" symbol to make it look symmetric. In the end just remove the last row that have 2*ncols+2 symbols.
The complete code would be:
def __str__(self):
result = ""
for i in range(self.nrows):
for j in range(self.ncols):
cell = str(self.gameboard[i][j])
result += cell + "|"
result += "\n"
result += "-+" * self.ncols + "-"
result += '\n'
# Remove the last row
result = result[:-2*ncols-2]
result += "\n"
return result

Python Drawing a tic tac toe board

I am trying to draw a fake 3x3 tic tac toe board. I am new to python and I don't understand why this does not work. Help would be appreciated. Thanks!
def draw():
for i in range(4):
board = (" ___ " * 3)
for i in board:
("| " * 4).join(board)
print(board)
draw()
EDIT:
Final code:
def draw():
board = ''
for i in range(-1,6):
if i%2==0:
board += '| ' * 4
board += '\n| | | |'
else:
board += ' _____ ' * 3
board += '\n'
print (board)
draw()
output:
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
Double Edit:
Another way:
def drawsmall():
a = (' ___' * 3 )
b = ' '.join('||||')
print('\n'.join((a, b, a, b, a, b, a, )))
drawsmall()
output:
___ ___ ___
| | | |
___ ___ ___
| | | |
___ ___ ___
| | | |
___ ___ ___
I found it easier to do this in one loop, printing a row of the board each iteration. You can alternate between vertical and horizontal bars by checking if the current iteration is an even or odd number using the % operator.
With strings you don't need to use join -- it can be more clear to append with the += operator.
def draw():
# initialize an empty board
board = ""
# there are 5 rows in a standard tic-tac-toe board
for i in range(5):
# switch between printing vertical and horizontal bars
if i%2 == 0:
board += "| " * 4
else:
board += " --- " * 3
# don't forget to start a new line after each row using "\n"
board += "\n"
print(board)
draw()
Output:
| | | |
--- --- ---
| | | |
--- --- ---
| | | |
If you don't want to use variables/functions/loops and want a simple one-liner solution based on Print command:
print("__|__|__", "__|__|__", " | | ", sep='\n')
Try this code instead:
def draw():
a=('\n _____ _____ _____ ')
b= ('\n| | | |')
print(a,b,b,a,b,b,a,b,b,a)
draw()
Output:
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
| | | |
| | | |
_____ _____ _____
for Better view use:
def print_tic_tac_toe():
print("\n")
print("\t | |")
print("\t | | ")
print('\t_____|_____|_____')
print("\t | |")
print("\t | | ")
print('\t_____|_____|_____')
print("\t | |")
print("\t | | ")
print("\t | |")
print("\n")
print_tic_tac_toe()
Output :
| |
| |
_____|_____|_____
| |
| |
_____|_____|_____
| |
| |
| |
​
Look up how the join function works. First, it takes the given string and uses that for the "glue", the string that connects the others. Second, it returns the constructed string; your join operation fails to save the result.
Try doing this first with nested loops: print a row of boxes, then the horizontal divider, etc. Then, bit by bit, convert that to the single-string output you want.
You can try this:
def draw():
return [["__" for b in range(3)] for i in range(3)]
Now you have a list of lists which contains your board. To print it out, you can do this:
the_board = draw()
for i in the_board:
for b in i:
print('|'.join(i), end="")
print()
print(" | | ")
I thought I'd simplify things so that I could understand it myself. This code produces the same output as above:
def draw_board():
v = '| | | |'
h = ' ____ ____ ____ '
for i in range(0,10):
if i%3==0:
print(h)
else:
print(v)
draw_board()
Output:
____ ____ ____
| | | |
| | | |
____ ____ ____
| | | |
| | | |
____ ____ ____
| | | |
| | | |
____ ____ ____
You can try this:
find below python code for end-to-end interactive Tic-Tac-Toe board game.
Code looks lengthy which can be optimized, but it works perfect as interactive Tic-Tac-Toe board game.
#Function code to clear the output space (screen)
from IPython.display import clear_output
#code to display just board-
def ttt_borad(board):
cl = clear_output()
print('Your Tic-Tac-Toe board now:\n')
print(board[1] + "|" + board[2] + "|" + board[3])
print("________")
print(board[4] + "|" + board[5] + "|" + board[6])
print("________")
print(board[7] + "|" + board[8] + "|" + board[9])
#function code to accept player key choices-
def player_key():
player_choice = ''
play1 = ''
play2 = ''
while player_choice not in ('Y', 'N'):
player_choice = input("Player-1 would like to go first ? Enter Y/N: ")
player_choice = player_choice.upper()
if player_choice not in ('Y', 'N'):
print("Invalid Key")
else:
pass
if player_choice == 'Y':
while play1 not in ('X', 'O'):
play1 = input("Select your Key for Player-1 X or O: ")
play1 = play1.upper()
if play1 not in ('X', 'O'):
print("Invalid Key")
else:
pass
else:
while play2 not in ('X', 'O'):
play2 = input("Select your Key for Player-2 X or O: ")
play2 = play2.upper()
if play2 not in ('X', 'O'):
print("Invalid Key")
else:
pass
if play1 == 'X':
play2 = 'O'
elif play1 == 'O':
play2 = 'X'
elif play2 == 'X':
play1 = 'O'
elif play2 == 'O':
play1 = 'X'
print(f'Key for Player-1 is: {play1} and Key for Player-2 is: {play2}')
return play1, play2
#function code to accept key strokes to play game
def enter_key(key, bp):
play1, play2 = key
ind = ['1', '2', '3', '4', '5', '6', '7', '8', '9']
i = 1
while i < 10:
j = 0
k = 0
print(f'Game Move: {i}')
while j not in ind:
j = input("Player-1: Select position (1-9) for your Move: ")
if j not in ind:
print("Invalid Key or Position already marked")
else:
pass
x = ind.index(j)
ind.pop(x)
j = int(j)
bp[j] = play1
ttt_borad(bp)
i = i + 1
tf = game_winner(key, bp)
if tf == 1:
print("The Winner is: Player-1 !!")
break
print(f'Game Move: {i}')
if i == 10:
break
while k not in ind:
k = input("Player-2: Select position (1-9) for your Move: ")
if k not in ind:
print("Invalid Key or Position already marked")
else:
pass
y = ind.index(k)
ind.pop(y)
k = int(k)
bp[k] = play2
ttt_borad(bp)
i = i + 1
ft = game_winner(key, bp)
if ft == 2:
print("The Winner is: Player-2 !!")
break
return bp
#function code to calculate and display winner of the game-
def game_winner(key, game):
p1, p2 = key
p = 0
if game[1] == game[2] == game[3] == p1:
p = 1
return p
elif game[1] == game[4] == game[7] == p1:
p = 1
return p
elif game[1] == game[5] == game[9] == p1:
p = 1
return p
elif game[2] == game[5] == game[8] == p1:
p = 1
return p
elif game[3] == game[6] == game[9] == p1:
p = 1
return p
elif game[4] == game[5] == game[6] == p1:
p = 1
return p
elif game[3] == game[5] == game[7] == p1:
p = 1
return p
elif game[1] == game[2] == game[3] == p2:
p = 2
return p
elif game[1] == game[4] == game[7] == p2:
p = 2
return p
elif game[1] == game[5] == game[9] == p2:
p = 2
return p
elif game[2] == game[5] == game[8] == p2:
p = 2
return p
elif game[3] == game[6] == game[9] == p2:
p = 2
return p
elif game[4] == game[5] == game[6] == p2:
p = 2
return p
elif game[3] == game[5] == game[7] == p2:
p = 2
return p
else:
p = 3
return p
#Function code to call all functions in order to start and play game-
def game_play():
clear_output()
entry = ['M', '1', '2', '3', '4', '5', '6', '7', '8', '9']
ttt_borad(entry)
plk = player_key()
new_board = enter_key(plk, entry)
tie = game_winner(plk, new_board)
if tie == 3:
print("Game Tie !!! :-( ")
print('Would you like to play again? ')
pa = input("Enter Y to continue OR Enter any other key to exit game: ")
pa = pa.upper()
if pa == 'Y':
game_play()
else:
pass
game_play()
#Try this entire code in any Python3 editor and let me know your feedback.
I have attached sample board how code displays.Sample Tic-Tac-Toe board by code
Thanks
def create_board():
board_size = int(input("What size game board they want to draw? "))
horizontal = " ---"
vertical = "| "
for i in range(board_size):
print(horizontal * board_size)
print(vertical * (board_size + 1))
return print(horizontal * board_size)
create_board()

B-ship game follow up: How to have the computer randomnize their ships?

Follow up from this:
I want to now randomnize the AI boat's locations. Also, can we try to do two boats?
Here's the code if you dont want to click the above link:
def drawboard(hitboard):
print('| | | |')
print('| ' + hitboard[7] + ' | ' + hitboard[8] + ' | ' + hitboard[9] + ' |')
print('| | | |')
print('-------------')
print('| | | |')
print('| ' + hitboard[4] + ' | ' + hitboard[5] + ' | ' + hitboard[6] + ' |')
print('| | | |')
print('-------------')
print('| | | |')
print('| ' + hitboard[1] + ' | ' + hitboard[2] + ' | ' + hitboard[3] + ' |')
print('| | | |')
def aicorners(hitboard,spot_hit):
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def aiedges(hitboard,spot_hit):
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def aimiddle(hitboard,spot_hit):
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def hitplayer():
pass
def main():
gameisplaying = True
while gameisplaying:
hitboard = [' ' for i in range(10)]
userready = input('Place your ships. Type done when you finished placing it.')
while not userready == 'done':
userready = input('Type done when you locate your ship. ')
shipissunk = False
while shipissunk == False:
spot_hit = input('Where\'s the hit?: 1-9 ')
while not (spot_hit in '1 2 3 4 5 6 7 8 9'.split()):
spot_hit = input ('Please tell me where the hit is: 1-9 ')
spot_hit = int(spot_hit)
if (spot_hit in [1,3,7,9]):
aicorners(hitboard,spot_hit)
elif (spot_hit in [2,4,6,8]):
aiedges(hitboard,spot_hit)
else:
aimiddle(hitboard,spot_hit)
main()
Notice how I only have one boat, and it's set position of [1,2,3]. I want to change the location every time the user plays it.
Parts of code updated below: (should i replace the original code?)
def aicorners(hitboard,spot_hit,ship_spots,ship_spots2):
if spot_hit in ship_spots or spot_hit in ship_spots2:
hitboard[spot_hit] = 'x'
else:
hitboard[spot_hit] = 'o'
print(drawboard(hitboard))
def main():
import random
possible_spots = [[1,2,3], [4,5,6], [7,8,9], [7,4,1], [8,5,2], [9,6,3]]
possible_spots2 = [[1,2],[2,3],[4,5],[5,6],[7,8],[8,9],[1,4],[4,7],[2,5],[5,8],[3,6],[6,9]]
ship_spots = random.choice(possible_spots)
ship_spots2 = random.choice(possible_spots2)
gameisplaying = True
while gameisplaying:
hitboard = [' ' for i in range(10)]
userready = input('Place your ships. Type done when you finished placing it.')
while not userready == 'done':
userready = input('Type done when you locate your ship. ')
shipissunk = False
while shipissunk == False:
spot_hit = input('Where\'s the hit?: 1-9 ')
while not (spot_hit in '1 2 3 4 5 6 7 8 9'.split()):
spot_hit = input ('Please tell me where the hit is: 1-9 ')
spot_hit = int(spot_hit)
aicorners(hitboard,spot_hit,ship_spots,ship_spots2)
main()
Help is greatly appreciated!
Right now you're hard-coding the check (in three identical functions with different names -- a mysterious approach!) as:
if spot_hit == 1 or spot_hit == 2 or spot_hit == 3:
this needs to become something like
if spot_hit in ship_spots:
where ship_spots is a global variable you randomly set at the start to one of the possible set of positions for the ship.
I have no idea what sets of positions you want to choose among (never played battleship on a 3 by 3 board!-) but for example:
import random
possible_spots = [[1,2,3], [4,5,6], [7,8,9]]
ship_spots = random.choice(possible_spots)
would give you one of the three horizontal possibilities.
Place this in main just before gameisplaying = True (the import random should more elegantly moved to the top of the module) and there you are.
Of course you would extend possible_spots if ships need not be horizontal, e.g
possible_spots = [[1,2,3], [4,5,6], [7,8,9],
[7,4,1], [8,5,2], [9,6,3]]
would allow the three vertical placements as well as the three horizontal ones.

B-ship game follow up 2: AI and User IDK how to do alternating turns

From this
I have been making a b-ship game but I have run into a problem. It is 3x3, so it's a scaled down version of the actual game. We're using one ship for now.
I currently have the user hitting the AI section done, but how can i make it switch to the Ai's turn after one hit?
The AI, when it is his turn, knows that the user has part of a ship at [4] and that will stay that way for now. then He tries to hit [7], but if that doesn't work, try [1], or if that doesn't work, try [5]. And How can I do this for any edge??
import random
def drawboard(hitboard,hitboard2):
print(' Opponent\'s Your')
print(' Ships Ships')
print('| | | | | | | |')
print('| ' + hitboard[7] + ' | ' + hitboard[8] + ' | ' + hitboard[9] + ' | | ' + hitboard2[7] + ' | ' + hitboard2[8] + ' | ' + hitboard2[9] + ' |')
print('| | | | | | | |')
print('------------- -------------')
print('| | | | | | | |')
print('| ' + hitboard[4] + ' | ' + hitboard[5] + ' | ' + hitboard[6] + ' | | ' + hitboard2[4] + ' | ' + hitboard2[5] + ' | ' + hitboard2[6] + ' |')
print('| | | | | | | |')
print('------------- -------------')
print('| | | | | | | |')
print('| ' + hitboard[1] + ' | ' + hitboard[2] + ' | ' + hitboard[3] + ' | | ' + hitboard2[1] + ' | ' + hitboard2[2] + ' | ' + hitboard2[4] + ' |')
print('| | | | | | | |')
def aiships(hitboard,spot_hit,shipspots,hitboard2):
if spot_hit in shipspots:
hitboard[1] = 'x'
else:
hitboard[7] = 'o'
drawboard(hitboard,hitboard2)
def playerships(hitboard,hitboard2, spot_hit, usershipspots):
hitboard2[7] = 'x'
print("\nComputer's turn.\n")
spot_hit = random.choice(usershipspots)
hitboard2[spot_hit] = 'x'
if spot_hit not in usershipspots:
hitboard2[spot_hit] = 'o'
drawboard(hitboard,hitboard2)
def main():
possiblespots = [[1,2],[2,3],[4,5],[5,6],[7,8],[8,9],[1,4],[4,7],[2,5],[5,8],[3,6],[6,9]]
shipspots = random.choice(possiblespots)
userspots = [[4,7],[4,1],[4,5]]
usershipspots = random.choice(userspots)
gameisplaying = True
ai_spots = [4, 7, 1, 5]
ai_index = 0
while gameisplaying:
hitboard = [' ' for i in range(10)]
hitboard2 = [' ' for i in range(10)]
hitboard2[usershipspots[0]] = 's'
hitboard2[usershipspots[1]] = 's'
userready = input('Place your ships. Type done when you finished placing it.')
while not userready == 'done':
userready = input('Type done when you locate your ship. ')
spot_hit = input('Where\'s the hit?: 1-9 ')
while not (spot_hit in '1 2 3 4 5 6 7 8 9'.split()):
spot_hit = input ('Please tell me where the hit is: 1-9 ')
spot_hit = int(spot_hit)
aiships(hitboard, spot_hit, shipspots, hitboard2)
playerships(hitboard, hitboard2, ai_spots[ai_index], shipspots)
ai_index += 1
main()
But wait, there's more! (billy mays reference)
No matter what number I put in, there will always be an O in the 7 space. Unless I put in the ship coordinates of the playerships (which is quite odd) which will create an X in the 1 space. Also there will always be an 's' in the 3 space on the 'your ships' board. (using numpad for numbers)
So between the two current statements
aiships(hitboard,spot_hit,shipspots,hitboard2)
playerships(hitboard, hitboard2,spot_hit,shipspots)
you need to recompute spot_hit so it's 4 the first time, then 7, then 1, then 5 (we'll worry about "any hedge" in some other future Q, OK?-).
For the purpose, it's simplest to initialize, just before the while:
ai_spots = [4, 7, 1, 5]
ai_index = 0
and then transform those two statements into:
aiships(hitboard, spot_hit, shipspots, hitboard2)
playerships(hitboard, hitboard2, ai_spots[ai_index], shipspots)
ai_index += 1
I hope it's clear how it works here. BTW, a side note, the randomly different order of arguments in the two functions is confusing to no good purpose -- reorder things so that they're the same in both cases!
For the "all hedges" presumably you need a longer list for ai_spots and the ability to increment ai_index by more than one if an attempt was not successful -- which in turn requires playerships to give you a boolean return telling you if the attempt was successful or not, so you can use it to determine how much to change ai_index by.
However that's very premature as you still have many bigger bugs to think about right now. For example, consider the snippet:
spot_hit = random.choice(usershipspots)
if spot_hit in usershipspots:
random.choice always returns one of the items in its argument -- so the check of whether its return value is indeed one of those items is completely redundant -- it will always be True and the body of the if clause will always execute.
No doubt you want to remove that recomputation of spot_hit as a random choice and accept the argument you're passed instead!
The if can remain of course and at the end of the function you can return spot_hit in usershipspots which is exactly the boolean telling you if the hit was successful or not.

Python: functions in class's methods return None instead bool (aka sloppy pathfinding)

I'm trying to somehow rectify why I cannot get any satisfying results calling one method after another.
at start I have a 2-dim table [7x9] with cards that create a maze.
for instance:
, A. , B. , C. , D. , E. , F. , G. ,
+-----+-----+-----+--#--+-----+-----+-----+
0. | | | :#####: | | |
+-----+-----+-----+--#--+-----+-----+-----+
1. | | | | # | | | |
+-----+-----+-----+--#--+-----+-----+-----+
2. | | | | #########: | |
+-----+-----+-----+--#--+--#--+-----+-----+
3. | | | | | # | | |
+-----+-----+-----+-----+--#--+-----+-----+
4. | | | | | #########: |
+-----+-----+-----+-----+--#--+-----+-----+
5. | | | | | # | | |
+-----+-----+-----+-----+--#--+-----+-----+
6. | | | :#################: |
+-----+-----+-----+-----+--#--+--#--+-----+
7. | | | | | | # | |
+-----+-----+-----+-----+-----+--#--+-----+
8. | | | | | :#####: |
+-----+-----+-----+-----+-----+--#--+-----+
starting with point D0 I want to check if the path made of cards reached point F8
I don't need shortest way or anything, just to know, that the path exists.
I successfully coded a couple simple functions that are checking that within a class, but the main class method is not returning the True / False to the place where it was called from.
You can judge me by my way of coding, but I never wrote anything that big in Python ;P
Classes:
Board
class Board(object):
board = []
def __init__(self):
for y in range(0,9):
#...
def print_board(self):
# implemented
def getBoard(self):
return self.board
GameBoard
class short idea:
class GameBoard(Board):
def __init__(self, cardsInHand):
def gameView(self):
def checkPath(self):
def right(poz, pa):
def left(poz, pa):
def down(poz, pa):
def up(poz, pa):
def doNext(poz, pa):
def pushCard(self, pos, newCard , force = False):
and the important methods:
def __init__(self, cardsInHand):
Board.__init__(self)
self.cards = cardsInHand
def checkPath(self):
poz = [0,3] # Starting position
conns = [] # skip this
tPath = [] # temporary path
ret = False
test = 0
def right(poz, pa):
if len(self.board[0]) - 1 > poz[1]: # can be checked right
if 1 in self.board[poz[0]][poz[1]].entries: # has route to the right
if 3 in self.board[poz[0]][poz[1] + 1].entries: #the next has matching route
nl = [poz[0], poz[1] + 1]
if nl not in pa:
pa.append(nl)
doNext(nl , pa)
else :
pa = []
def left(poz, pa):
if poz[1] > 0:
if 3 in self.board[poz[0]][poz[1]].entries:
if 1 in self.board[poz[0]][poz[1] - 1].entries:
nl = [poz[0], poz[1] - 1]
if nl not in pa:
pa.append(nl)
doNext(nl, pa)
else:
pa = []
def down(poz, pa):
if len(self.board) - 1 > poz[0]:
if 2 in self.board[poz[0]][poz[1]].entries:
if 0 in self.board[poz[0] + 1][poz[1]].entries:
nl = [poz[0] +1, poz[1]]
if nl not in pa:
pa.append(nl)
doNext(nl , pa)
else :
pa = []
def up(poz, pa):
if poz[0] > 0:
if 2 in self.board[poz[0]][poz[1]].entries:
if 0 in self.board[poz[0] - 1][poz[1]].entries:
nl = [poz[0] - 1, poz[1]]
if nl not in pa:
pa.append(nl)
doNext(nl , pa)
else :
pa = []
def doNext(poz, pa):
ways = []
output = None
if poz == [8, 5]: # the point '**F8**'
ways.append(pa)
output = True
else:
if 1 in self.board[poz[0]][poz[1]].entries:
right(poz, pa)
if 2 in self.board[poz[0]][poz[1]].entries:
down(poz, pa)
if 3 in self.board[poz[0]][poz[1]].entries:
left(poz, pa)
if 0 in self.board[poz[0]][poz[1]].entries:
up(poz, pa)
output = False
return output
#print 'Expect False or True: ', str(doNext(poz, tPath))
return str(doNext(poz, tPath))
As the last checkPath() print eventually should return (print) True at some point but it never does.
further in this class I have method:
def pushCard(self, pos, newCard, force = False):
...
...
win = False
...
# unimportant code
...
if force == True:
allow = True
if allow == True:
self.board[pY][pX] = newCard
if self.checkPath():
print "The path exists"
win = True
else:
#cannot put card here
win = False
return wynik
Following, I cannot also get right result during gameplay:
for num in range(0, 12):
input = str(raw_input( str(num + 1) + ". Card position and identity: 'An T' "))
inPar = input.split(" ")
if len(inPar) == 2:
if gra.pushCard(inPar[0], Karta(inPar[1])):
print ("end of the game")
break
else:
print ("try again")
gra.gameView()
else:
print("bad input")
The function doNext() never returns True, but during testing I got many times a feedback, that the path has been found.
I'm using Python 2.6.6, not able to upgrade.
Any help would be appreciated.

Categories

Resources