Advertisement
Guest User

Checkers

a guest
Oct 18th, 2019
234
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.33 KB | None | 0 0
  1. #!/usr/bin/python3
  2.  
  3. class Game:
  4.     def __init__(self, width=3, height=3, file="", p1="X", p2="O", win=3):
  5.         self.p1 = p1
  6.         self.p2 = p2
  7.         self.win = win
  8.         self.fill = '_'
  9.         self.sep = ','
  10.  
  11.         if file != "":
  12.             self.load(file)
  13.         else:
  14.             self.counter = 0
  15.             self.matrix = [[self.fill for _ in range(width)] for _ in range(height)]
  16.  
  17.     def save(self, file):
  18.         with open(file, 'w') as f:
  19.             f.write("{}\n".format(self.counter))
  20.             f.write("\n".join([self.sep.join(row) for row in self.matrix]))
  21.  
  22.     def load(self, file):
  23.         self.matrix = []
  24.         with open(file, 'r') as f:
  25.             content = f.read().splitlines()
  26.             self.counter = int(content[0])
  27.             for i in range(1, len(content)):
  28.                 self.matrix.append(list(content[i].replace(self.sep, '')))
  29.  
  30.     def place(self, x, y, char):
  31.         try:
  32.             ret = self.matrix[x][y] == self.fill
  33.             if ret:
  34.                 self.matrix[y][y] = char
  35.         except IndexError:
  36.             return False
  37.         return ret
  38.  
  39.     def check(self, char):
  40.         if char != "":
  41.             for i in range(len(self.matrix)):
  42.                 row = self.matrix[i]
  43.                 if self._consecutive(row, char):
  44.                     return True
  45.                
  46.                 col = [row[i] for row in self.matrix]
  47.                 if self._consecutive(col, char):
  48.                     return True
  49.            
  50.             dia = [row[i] for i, row in enumerate(self.matrix)]
  51.             if self._consecutive(dia, char):
  52.                 return True
  53.         return False
  54.  
  55.     def _consecutive(self, arr, char):
  56.         if len(arr) >= self.win:
  57.             occ = 0
  58.             for c in arr:
  59.                 if c == char:
  60.                     occ += 1
  61.                 else:
  62.                     occ = 0
  63.                 if occ >= self.win:
  64.                     return True
  65.         return False
  66.  
  67.     def __str__(self):
  68.         ret = " {}".format(self.fill) * len(self.matrix) + "\n"
  69.         for row in self.matrix:
  70.             ret += "|{}|\n".format("|".join(row))
  71.         return ret
  72.  
  73. def _main():
  74.     answer = input("Load board from file? (y/N) ").lower()
  75.  
  76.     if answer == "y":
  77.         answer = input("Enter file name: ")
  78.         game = Game(file=answer)
  79.     else:
  80.         (x, y) = [int(input("Enter width: ")), int(input("Enter height: "))]
  81.         game = Game(width=x, height=y)
  82.    
  83.     char = ""
  84.     while game.check(char) == False:
  85.         char = game.p2 if game.counter % 2 else game.p1
  86.  
  87.         print(game)
  88.         print("Player {}'s turn".format(char))
  89.         answer = input("Enter input: ")
  90.  
  91.         if answer == "q":
  92.             char = ""
  93.             break
  94.         elif answer == "s":
  95.             game.save(input("Enter file name: "))
  96.             print("Game saved!")
  97.         else:
  98.             try:
  99.                 (x, y) = map(lambda x: int(x), answer.split(','))
  100.             except ValueError:
  101.                 print("Bad input, try again")
  102.  
  103.             if game.place(x, y, char) == False:
  104.                 print("Unavailable position")
  105.             else:
  106.                 game.counter += 1
  107.  
  108.     print(game)
  109.     print("Good bye!" if char == "" else "{} won the game!".format(char))
  110.  
  111. if __name__ == "__main__":
  112.     _main()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement