זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/python/lessons/tictactoe-lab
זה נושא דיון מלווה לערך המקורי ב- https://www.tocode.co.il/bundles/python/lessons/tictactoe-lab
איך עושים מערך דו מימדי בפייתון - אני לא מצליח - רוצה לעשות מערך של הלוח
מה ניסית לכתוב בינתיים?
זה המוודול של המשחק עצמו
"""
This modol incluse the game of X O
"""
#Exeptions
class TypePlayerExeption(Exception):
def __init__(self):
self.message="Error Type Player is only X or O only "
class NamePlayerInvalidExeption(Exception):
def __init__(self):
self.message="Error: Name Player is Requerd! "
class PlayerMustToBeDefranceExeption(Exception):
def __init__(self):
self.message="Error: The Player must be diffrance (not by equle name or type) "
class PlayNotLigalExeption(Exception):
def __init__(self):
self.message="Error:the play is not legal becouse the row,colomn is not in the board or the cell is not empty "
class GameOverExeption(Exception):
def __init__(self):
self.message="Error:the play is not legal becouse the the game is over "
#Player class
class Player(object):
#typePlayer: X or O
def __init__(self,namePlayer,typePlayer):
#Raise Exption
if not typePlayer is str and not typePlayer.upper() in ["X","O"]: raise TypePlayerExeption
if not name is str and name=="": raise NamePlayerInvalidExeption
self._typePlayer = typePlayer.upper()
self._name = namePlayer
def __str__(self):
print "player name: %s (%s)" % (self._name,self._typePlayer)
def __eq__(self, other):
if not type(other) is Player:return NotImplemented
return self._name==other._name and self._typePlayer==other._typePlayer
#Game class
class Game(object):
#starts a new game with players p1 and p2
def start(self,p1,p2):
#Raise exption
if not p1 is Player or not p2 is Player: raise ValueError("must to get 2 player with difrance type(O\X)")
if p1 == p2 or p1._name == p2._name or p1._typePlayer == p2._typePlayer: raise PlayerMustToBeDefranceExeption
#set the curre3nt value to the game
self._player_1=p1
self._player_2=p2
self._current_player=p1
self._winner=None
#new board
self._board = _get_new_board()
def _get_new_board(self):
return [[None for j in range(3)] for i in range(3)]
#current player picked a square. If the square was free mark it as X or O and switch turns to the other player.
#If square was taken or not in the board, or game is over, raise an exception.
def play(self,row,column):
#Exeption
if self.winner() != None: raise GameOverExeption
if val(row,column) != None:raise PlayNotLigalExeption
self._board[row-1][column-1]=self._current_player._typePlayer
if winner():
self._winner=self._current_player
return True
_set_current_player
return False
def get_current_player(self):
return self._current_player
def _set_current_player(self):
if self._current_player._typePlayer==self._player_1._typePlayer:
self._current_player.self._player_2
else:
self._current_player.self._player_1
#If game is over return the winning player, else return None
def winner(self):
if self._winner != None: return self._winner
#rows
if self._board[0][0] != None and self._board[0][0]==self._board[0][1] and self._board[0][0]==self._board[0][2]: return True
if self._board[1][0] != None and self._board[1][0]==self._board[1][1] and self._board[1][0]==self._board[1][2]: return True
if self._board[2][0] != None and self._board[2][0]==self._board[2][1] and self._board[2][0]==self._board[2][2]: return True
#Column
if self._board[0][0] != None and self._board[0][0]==self._board[1][0] and self._board[0][0]==self._board[2][0]: return True
if self._board[0][1] != None and self._board[0][1]==self._board[1][1] and self._board[0][1]==self._board[2][1]: return True
if self._board[0][2] != None and self._board[0][2]==self._board[1][2] and self._board[0][2]==self._board[2][2]: return True
if self._board[0][0] != None and self._board[0][0]==self._board[1][1] and self._board[0][0]==self._board[2][2]: return True
if self._board[0][2] != None and self._board[0][2]==self._board[1][1] and self._board[0][2]==self._board[2][0]: return True
return False
#return current value for square (X, O or empty)
def val(self,row, column):
#Exeption
if not row-1 in range(3) or not column-1 in range(3): raise PlayNotLigalExeption
return self._board[row-1][column-1]
def print_board(self):
for i in rang(3):
for j in range(3):
print "%*s" % (4,self._board[i][j]),
print
זה הקובץ הראשי
"""
main flie of run the oxGames
"""
import sys
import oxGame as G
if __name__ == "__name__": sys.exit()
print "Hello , Welcome to the game of X \ O"
while True:
print "To start please set S else set exit."
cmd = sys.stdin.readline()
if cmd == "exit" : sys.exit()
if cmd != "S":continue
#Get the name and type the player
try:
print "set the name and the type X\O for the player 1"
[name_p,type_p] = sys.stdin.readline().split()
p1 = G.Player(name_p,type_p)
print "set the name and the type X\O for the player 2"
[name_p,type_p] = sys.stdin.readline().split()
p2 = G.Player(name_p,type_p)
except TypePlayerExeption as e:
print "Must to set the X\O type to the player, try again from begginng "
continue
except NamePlayerInvalidExeption as e:
print "Must to set the name of the player, try again from begginng "
continue
except Exception as e:
print e.message
continue
#Create new gmae
try:
game = G.Game()
game.start(p1,p2)
except ValueError as e:
print "to start game must set two players"
continue
except PlayerMustToBeDefranceExeption as e:
print "to start game must set two players with name or type difrance"
continue
#start the game
while True:
try:
print "Now player the %s , plase select cell " % (game.get_current_player())
[row,column]=sys.stdin.readline().split()
is_game_over=game.play(row,column)
game.print_board()
if is_game_over: break
print
print "The winer is:", game.winner()
except GameOverExeption as e:
print "The game is over!!!!"
break
except PlayNotLigalExeption as e:
print "The play is not legal , plase try again"
continue
מתקבלת לי שגיאה - אני לא מבין מדוע - הרי זה כן מוגדר במודול כמו שלמדנו
NameError: name 'TypePlayerExeption' is not defined
זה הכל באותו קובץ או מספר קבצים? אם מספר קבצים אולי תעלה אותם לאיזה Repository מסודר (למשל בגיטהאב) שיהיה קל לראות?