HIT暑假python作业2《五子棋(控制台版)》
使用之前记得安装一下库colorama
不会安装的话,可以直接删除前两行代码(前两行的作用是保证将该代码编译成exe文件的时候能够保证颜色属性被识别)
本地运行效果
编译成可执行文件后的效果
import os
from colorama import init
init(autoreset=True)
chess = {'A': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'B': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'C': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'D': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'E': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'F': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'G': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'H': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'I': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-'],
'J': ['-', '-', '-', '-', '-', '-', '-', '-', '-', '-']}
def printchess():
FOREGROUND_DARKRED = 0x04 # dark red.
print("\033[1;37;41m------简易五子棋游戏(控制台版)-----\033[0m\n\033[1;46m--------------------------------\033[0m\n\033[1;46m 1 2 3 4 5 6 7 8 9 10\033[0m")
for i in chess.items():
all_line = ''
for count in range(0,10):
all_line += ' '+str(i[1][count])
print('\033[1;46m'+i[0]+all_line+' \033[0m')
print('\033[1;46m--------------------------------\033[0m')
def ifwin(x):
for i in range(65,65+6):
for j in range(0,6):
if chess[chr(i)][j] == x:
if chess[chr(i+1)][j] == chess[chr(i+2)][j] == chess [chr(i+3)][j] == chess[chr(i+4)][j] == x:
return 1
if chess[chr(i)][j+1] == chess[chr(i)][j+2] == chess [chr(i)][j+3] == chess[chr(i)][j+4] == x:
return 1
if chess[chr(i+1)][j+1] == chess[chr(i+2)][j+2] == chess [chr(i+3)][j+3] == chess[chr(i+4)][j+4] == x:
return 1
for i in range(65+4,65+10):
for j in range(0,6):
if chess[chr(i)][j] == x:
if chess[chr(i-1)][j+1] == chess[chr(i-2)][j+2] == chess [chr(i-3)][j+3] == chess[chr(i-4)][j+4] == x:
return 1
return 0
def deal(location):
y = '0'
try:#防止什么都不输入,或者中间报错(说明格式不对)
if 'A'<=location[0]<='J':
x = location[0]
else:
x = 0
location = location[1:]
y = int(location)
if y<1 or y>10:
x = 0
except:
x = 0#如果格式有误用x = 0表示
return x,y
def clean():
os.system('cls')
count = 1
data = [['J5','A1'],['o','*'],['\033[1;42m','\033[1;43m']]
printchess()
while(True):
init(autoreset=True)
print('%s请%s输入棋子坐标(例如%s): \033[0m'%(data[2][count%2],data[1][count%2],data[0][count%2]),end='')
location = input()
x,y = deal(location.strip())#顺便去除空格干扰
if x == 0 :
print('\033[0;31m***您输入的坐标有误,请重新输入!***\033[0m')
continue
if chess[x][int(y)-1] in ['*','o']:
print('\033[0;31m您输入的位置已经有其他棋子,请重新输入!\033[0m')
continue
chess[x][int(y)-1] = data[1][count%2]
if ifwin(data[1][count%2]):
printchess()
print('\033[0;31m\'%s\'棋子胜利***\033[0m'%data[1][count%2])
break
count += 1
clean()
printchess()