Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Field():
- def __init__(self):
- self.data = [0,0,0,
- 0,0,0,
- 0,0,0]
- self.win = -1
- def step(self, who, pos):
- if not self.check_step_possible(pos):
- return False
- self.data[pos] = who
- return True
- def step_x(self, pos):
- if not self.check_step_possible(pos):
- return False
- self.data[pos] = 1
- return True
- def step_o(self, pos):
- if not self.check_step_possible(pos):
- return False
- self.data[pos] = 2
- return True
- def check_step_possible(self, pos):
- return self.data[pos] == 0
- def check_win(self):
- win_combinations = [
- [1,2,3],
- [4,5,6],
- [7,8,9],
- [1,4,7],
- [2,5,8],
- [3,6,9],
- [1,5,9],
- [3,5,7]
- ]
- # combinations to indexes
- for ar in range(0, len(win_combinations)):
- for it in range(0, len(win_combinations[ar])):
- win_combinations[ar][it] = win_combinations[ar][it] - 1
- # print(win_combinations)
- for win_indexes in win_combinations:
- win = True
- letter = self.data[win_indexes[0]]
- # print(win_indexes)
- if letter == 0:
- continue
- for i in win_indexes:
- if self.data[i] != letter:
- win = False
- if (win):
- self.win = letter
- if self.win > 0:
- return self.win
- else:
- return False
- def print_state(self):
- msg = "----------------\n"
- msg += "| %s | %s | %s |\n"
- msg += "| %s | %s | %s |\n"
- msg += "| %s | %s | %s |\n"
- msg += "----------------\n"
- tpl = ()
- for item in self.data:
- tpl = tpl + (item,)
- print(msg % tpl)
- if __name__ == "__main__":
- f = Field()
- cur_player = 1
- f.print_state()
- win = False
- while not win:
- print("Player %s step: " % cur_player)
- step = int(input())
- while not f.step(cur_player, step - 1):
- print("Cant go there! Input another position, Player %s:" % cur_player)
- step = int(input())
- f.print_state()
- cur_player = 3 - cur_player
- win = f.check_win()
- # print(win)
- print("Player %s win!" % f.win)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement