用python 写一个 五子棋游戏
时间: 2023-02-19 14:39:26 浏览: 64
我可以给你一个简单的示例:
```python
# 五子棋游戏
import random
# 创建棋盘
board = [[0 for i in range(15)] for i in range(15)]
# 打印棋盘
def print_board():
for i in range(15):
for j in range(15):
if board[i][j] == 0:
print('-', end=' ')
elif board[i][j] == 1:
print('X', end=' ')
elif board[i][j] == 2:
print('O', end=' ')
print()
# 落子
def put_chess(x, y, chess):
board[x][y] = chess
# 判断是否赢了
def judge_win(x, y, chess):
win_count = 1
# 判断横向
for i in range(1, 5):
if x + i < 15 and board[x + i][y] == chess:
win_count += 1
else:
break
for i in range(1, 5):
if x - i >= 0 and board[x - i][y] == chess:
win_count += 1
else:
break
if win_count >= 5:
return True
# 判断纵向
win_count = 1
for i in range(1, 5):
if y + i < 15 and board[x][y + i] == chess:
win_count += 1
else:
break
for i in range(1, 5):
if y - i >= 0 and board[x][y - i] == chess:
win_count += 1
else:
break
if win_count >= 5:
return True
# 判断左斜
win_count = 1
for i in range(1, 5):
if x + i < 15 and y + i < 15 and board[x + i][y + i] == chess:
win_count += 1
else:
break
for i in range(1, 5):
if x - i >= 0 and y - i >= 0 and board[x - i][y - i] == chess:
win_count += 1
else:
break
if win_count >= 5:
return True
# 判断右斜
win_count = 1
for i in range(1, 5):
if x + i < 15 and y - i >= 0 and board[x + i][y - i] == chess:
win_count += 1
else:
break
for i in range(1, 5):
if x - i >= 0 and y + i < 15 and board[x - i][y + i] == chess:
win_count += 1
else:
break
if win_count >= 5:
return True
return False
# 游戏开始
print('欢迎来到五子棋游戏!')
while True:
# 玩家落子
x, y = input('请输入您要落子的位置:').split()
x = int(x)
y = int(y)
put_chess(x, y, 1)
print_board()
if judge_win(x, y, 1):
print('恭喜你,你赢了!')
break
# 电脑落子
while True:
x = random.randint(0, 14)
y = random.randint(0, 14)
if board[x][y] == 0:
break
put_chess(x, y, 2)
print_board()
if judge_win(x, y, 2):
print('很遗憾,你输了!')
break
```
阅读全文