Python style questions

Rainer Deyke root at rainerdeyke.com
Sat Mar 17 12:54:42 EST 2001


"François Granger" <francois.granger at free.fr> wrote in message
news:1eqfb5l.10gfjcu1qi9xrwN%francois.granger at free.fr...
> I am currently on the following dispatch issue wich is far from corect:
>
> def game():
>     print 'Starting game.'
>     a = tictactoe() # create a new game
>     ans = raw_input('Who start (h/c) : ')
>     if  (ans[0]=='q' or ans[0]=='Q'):
>         return
>     human = userinput   # proc to handle human interaction
>     c = player('X') # create a machine player
>     computer = c.play
>     if (ans[0]=='h' or ans[0]=='H'):
>         first, second = human, computer
>     else:
>         first, second = computer, human
>     while 1:
>         if a.turn % 2:
>             move, token = second(a)
>         else:
>             move, token = first(a)
>         a.valid(move, token)
>         a.display()
>         win = a.won()
>         if win == 'tie':
>             print 'tie'
>             # call player with tie
>             # exit game
>         elif win == 'X':
>             print 'X'
>             # call player with X
>             # exit game
>         elif win == 'O':
>             print 'O'
>             # call player with O
>             # exit game
>         else:
>             continue

I would do something like this:

class Player:
  def __init__(self, game, side):
    self.game = game
    self.side = side

class HumanPlayer(Player):
  def move(self, game):
    ...

class GAPlayer(Player):
  def move(self, game):
    ...

class NNPlayer(Player):
  def move(self, game):
    ...

class Game:
  def __init__(self, player1, player2):
    self.players = [player1, player2]
    self.active_player = 0
  def run(self):
    while not self.game_over():
      self.apply_move(self.players[active_player].move(self))
      self.active_player = (self.active_player + 1) % 2

Game(HumanPlayer(), NNPlayer()).run()

--
Rainer Deyke (root at rainerdeyke.com)
Shareware computer games           -           http://rainerdeyke.com
"In ihren Reihen zu stehen heisst unter Feinden zu kaempfen" - Abigor





More information about the Python-list mailing list