题目: 用Python实现四连环游戏
代码实现:
#-*-encoding:utf-8-*-
import sys
import random
random_=random.randint(1000,9999)
filename = '四连环Log-'+str(random_)+'.txt'
#日志记录
class Logger(object):
def __init__(self, filename="Default.log"):
self.terminal = sys.stdout
self.log = open(filename, 'a')
def write(self, message):
self.terminal.write(message)
self.log.write(message)
def flush(self):
pass
sys.stdout = Logger(filename)
import random,time,math
map_ = [[0 for x in range(8)] for y in range(6)]
list_8 = [0,0,0,0,0,0,0,0]
#打印地图
def print_map(map_):
print(' 1 2 3 4 5 6 7 8')
for i in range(5, -1, -1):
for j in range(8):
qz = map_[i][j]
if qz == 0 :
qz = ' '
print('|' + qz, end='')
print('|')
print('------------------')
#判断是否胜利
def IsWin(map_,row,col,piece):
countH=1
countS=1
countP=1
countN=1
# /*计算countH*/
# /*左边*/
i=col-1
row = row-1
while(i>=0):
if(map_[row][i]==piece):
countH+=1
else:
break
i-=1
# /*右边*/
i=col+1
while(i<=7):
if(map_[row][i]==piece):
countH+=1
else:
break
i+=1
# /*计算countS*/
# /*上边*/
i=row-1
while(i>=0):
if(map_[i][col]==piece):
countS+=1
else:
break
i-=1
# /*下边*/
i=row+1
while(i<=5):
if(map_[i][col]==piece):
countS+=1
else:
break
i++1
# /*计算countN*/
# /*左上*/
i=row-1
j=col-1
while(i>=0 and j>=0):
if(map_[i][j]==piece):
countN+=1
else:
break
i-=1
j-=1
i=row+1
j=col+1
while(i<=5 and j<=7):
if(map_[i][j]==piece):
countN+=1
else:
break
i+=1
j+=1
# /*计算countP*/
# /*右上*/
i=row-1
j=col+1
while(i>=0 and j<=7):
if(map_[i][j]==piece):
countP+=1
else:
break
i-=1
j+=1
# /*左下*/
i=row+1
j=col-1
while(i<=5 and j>=0):
if(map_[i][j]==piece):
countP+=1
else:
break
i+=1
j-=1
if(countH>=4 or countS>=4 or countP>=4 or countN>=4):
return piece
else:
return 0
#主函数
if __name__ == '__main__':
print("Hi,我是劳拉,我们来玩一局四连环。我用O型棋子,你用X型棋子。")
print("游戏规则:双方轮流选择棋盘的列号放进自己的棋子,")
print("若棋盘上有四颗相同型号的棋子在一行、一列或一条斜线上连接起来,")
print("则使用该型号棋子的玩家就赢了!")
print()
print("开始了!这是棋盘的初始状态:")
print_map(map_)
flag = ""
while(flag != "a"):
while True:
luraChess = random.randint(0,7)
if list_8[luraChess] < 6:
break
if math.fsum(list_8)==48:
print('地图已填满,你们是平局!')
flag = "a"
break
if(flag=="a"):
break
list_8[luraChess] += 1
for i in range(6):
if map_[i][luraChess] == 0:
map_[i][luraChess] = '0'
break
print('>>>轮到我了,我把O棋子放在第%d列' %(luraChess+1))
print_map(map_)
if(IsWin(map_,list_8[luraChess],luraChess,"0")):
print("劳拉胜利!")
break
print(">>>轮到你了,你放X棋子,请选择列号(1-8):")
yourChess = eval(input())
if(yourChess < 1 or yourChess > 8):
print(">>>输入错误,你放X棋子,请选择列号(1-8):")
yourChess = eval(input())
print()
yourChess -= 1
for i in range(6):
if map_[i][yourChess] == 0:
map_[i][yourChess] = 'X'
break
list_8[yourChess] += 1
print_map(map_)
if(IsWin(map_,list_8[yourChess],yourChess,"X")):
print("******* 好吧,你赢了!^_*")
break
time.sleep(1)