python井字棋小游戏课设代码
时间: 2024-06-22 08:03:27 浏览: 118
Python实现井字棋小游戏
Python中的井字棋小游戏通常是一个很好的教学项目,用于实践循环、条件语句和用户交互。下面是一个简单的井字棋游戏的基本代码框架:
```python
# 井字棋类
class TicTacToe:
def __init__(self):
self.board = [[' ' for _ in range(3)] for _ in range(3)]
self.current_player = 'X'
def print_board(self):
for row in self.board:
print('|', end='')
for cell in row:
print(cell, '|', end=' ')
print()
print('---+' * 3)
def make_move(self, row, col):
if self.board[row][col] != ' ':
print("该位置已被占用,请重新选择")
return False
self.board[row][col] = self.current_player
self.current_player = 'O' if self.current_player == 'X' else 'X'
return True
def game_over(self):
# 判断游戏是否结束,比如检查任意一行、一列或对角线是否有三个相同的标记
# ...(此处省略具体规则实现)
# 主函数
def main():
game = TicTacToe()
while not game.game_over():
game.print_board()
row = int(input("请输入行号 (1-3): "))
col = int(input("请输入列号 (1-3): "))
if game.make_move(row - 1, col - 1):
if game.game_over():
game.print_board()
print("玩家", game.current_player, "获胜!")
break
else:
print("输入无效")
if __name__ == "__main__":
main()
```
阅读全文