Array = {row=0,col=0}
Chess={ipos=0,jpos=0,chessturn=0}
local array={}
local isWin=false
local isWhite=false
local isBlack=true
print("五子棋游戏开始:请输入你需要的棋盘的行数")
local maxRow =io.read()
print("你设定的行数为",maxRow)
print("五子棋游戏开始:请输入你需要的棋盘的列数")
local maxCol =io.read()
print("你设定的列数为",maxCol)
print("成功生成并打印五子棋棋盘")
--棋牌类基础方法new
function Array:new (o,row,col)
o = o or {}
setmetatable(o, self)
self.__index = self
row=row or 0
col=col or 0
self.row=row
self.col=col
return o
end
--棋子类基础方法new
function Chess:new (o,ipos,jpos,chessturn)
o = o or {}
setmetatable(o, self)
self.__index = self
ipos=ipos or 0
jpos=jpos or 0
chessturn=chessturn or 0
self.ipos=ipos
self.jpos=jpos
self.chessturn=chessturn
return o
end
--棋盘基础类方法 初始化棋盘
function Array:initArray()
--初始化棋盘
for row=1,self.row do
array[row]={}
for col=1,self.col do
array[row][col]=0
print("i:"..row..",J:"..col.." arr:"..array[row][col])
end
end
end
--棋子类基础方法 下棋
function Chess:changeArray(functionWin)
array[self.ipos][self.jpos]=self.chessturn
for row=1,Array.row do
for col=1,Array.col do
print("i:"..row..",J:"..col.." arr:"..array[row][col])
end
end
functionWin(self.ipos,self.jpos,self.chessturn)
end
function initChess()
print("轮到黑子,请输入要走的行数")
newIpos =tonumber(io.read())
print("轮到黑子,请输入要走的列数")
newJpos =tonumber(io.read())
if(isWhite) then
newchessturn=2
isWhite=false
isBlack=true
end
if(isBlack) then
newchessturn=1
isWhite=true
isBlack=false
end
mychess= Chess:new(nil,newIpos,newJpos,newchessturn)
mychess:changeArra1y(Win)
end
--判断胜利逻辑方法 ipos是这次落子的X坐标 jpos是这次落子的y坐标 chessturn是这次落子的颜色 1是黑色 2是白色 返回值0是无人获胜 返回值1是黑色胜利 2是白色胜利
Win=function (ipos,jpos,chessturn)
idir={0,0,1,-1,1,-1,1,-1}
jdir={1,-1,0,0,1,-1,-1,1}
for i=1,8 do
count=0
x=ipos
y=jpos
while(x>0 and y>0 and array[x][y]==chessturn) do
count=count+1
if(count==5) then
isWin=true
return chessturn
end
x=x+idir[i]
y=y+jdir[i]
end
i=i+1
if(i>8) then
break
end
x=ipos+idir[i]
y=jpos+jdir[i]
while(x>0 and y>0 and array[x][y]==chessturn) do
count=count+1
if(count==5) then
isWin=true
if(chessturn==1) then
isWhite=false
print("黑色胜利")
elseif (chessturn==2) then
isBlack=false
print("白色胜利")
end
return chessturn
end
x=x+idir[i]
y=y+jdir[i]
if(x<1 or y<1) then
break
end
end
end
print("无人胜利")
return 0
end
--主循环方法
function main()
while(isWin==false) do
if(isWhite) then
initChess()
end
if(isBlack) then
initChess()
end
end
end
--创建对象
myarray = Array:new(nil,maxRow,maxCol)
--调用初始和打印方法
myarray:initArray()
--没得出结果之前循环落子
main()