Posted in Python onMay 02, 2022
本文实例为大家分享了用Python开发五子棋小游戏的具体代码,供大家参考,具体内容如下
# 制作一个棋盘
"""
++++++++++
++++++++++
++++++++++
++++++++++
"""
def createBoard():
board = []
for i in range(15):
board.append(["+"] * 15)
return board
def printBoard():# print(" ", end="")
for i in range(1, 16):
number = str(i).rjust(3)
print(number, end="")
print()#打印列号之后换行
for i in range(15):
number = str(i + 1).ljust(3)#注意这个函数,是将行号每个都变成左对齐,占3位,以实现棋盘对齐功能
print(number, end="")#打印行号
for j in range(15):
print(board[i][j], end=" ")
print()
def isGameOver():
count = 0
# 先判断连续
for x in range(15):
for y in range(15):
if board[x][y] != "+":
count += 1
# 向右
if y < 11:
flag = True #表示默认游戏结束
for c in range(y + 1, y + 5):
if board[x][y] != board[x][c]:
flag = False
break
if flag:
if board[x][y] == "●":
print(">>>黑方胜!")
else :
print(">>>白方胜!")
return True; # 表示游戏结束
# 向下
if x < 11:
if board[x][y] == board[x+1][y] == board[x+2][y] == board[x+3][y] == board[x+4][y]:
if board[x][y] == "●":
print(">>>黑方胜!")
else :
print(">>>白方胜!")
return True
# 向右下
if x < 11 and y < 11:
if board[x][y] == board[x+1][y+1] == board[x+2][y+2] == board[x+3][y+3] == board[x+4][y+4]:
if board[x][y] == "●":
print(">>>黑方胜!")
else :
print(">>>白方胜!")
return True
# 向右上
if x > 3 and y < 11:
if board[x][y] == board[x-1][y+1] == board[x-2][y+2] == board[x-3][y+3] == board[x-4][y+4]:
if board[x][y] == "●":
print(">>>黑方胜!")
else :
print(">>>白方胜!")
return True
# 再判断和棋
if count == 15 ** 2:
print(">>>和棋!")
return True
return False#如果以上连棋都没出现就游戏继续
def chess(c):
x, y = eval(input("请输入坐标:"))
x -= 1
y -= 1
if board[x][y] == "+":
board[x][y] = c
return True
else:
print(">>>此处已有棋子,请重新下棋!")
return False
# 程序的开始
board = createBoard();
printBoard()
player = 0
while not isGameOver():#游戏继续的操作
if player % 2 == 0:
print(">>>请黑方下棋,", end="")
if not chess("●"):
continue
else:
print(">>>请白方下棋,", end="")
if not chess("○"):
continue
printBoard()
player += 1
print(">>>游戏结束!")
五子棋胜局判断的根据所在如上图。
Python开发五子棋小游戏
- Author -
一起看日落啊- Original Sources -
声明:登载此文出于传递更多信息之目的,并不意味着赞同其观点或证实其描述。
Tags in this post...
Reply on: @reply_date@
@reply_contents@