使用 Corona 制作 Lua 井字游戏教程

我正在尝试完成使用 Corona SDK 制作的 Lua 井字游戏教程。 我已经通过了第一部分,但是在第二部分中,当他在一个表格中为“x”和“o”交替记录变量时,我迷失了。

他使用水龙头计数来确定轮流的次数,我尝试使用 Corona 的 touch.id 来模仿这种技术,但没有成功。

我希望有人能够解释一下如何使用 Corona 实现这一点。

下面是我目前完成的内容(来自教程的第一部分):

d = display
w20 = d.contentWidth * .2
h20 = d.contentHeight * .2
w40 = d.contentWidth * .4
h40 = d.contentHeight * .4
w60 = d.contentWidth * .6
h60 = d.contentHeight * .6
w80 = d.contentWidth * .8
h80 = d.contentHeight * .8

---- 画棋盘线
local lline = d.newLine(w40,h20,w40,h80 )
lline.strokeWidth = 5

local rline = d.newLine(w60,h20,w60,h80 )
rline.strokeWidth = 5

local bline = d.newLine(w20,h40,w80,h40 )
bline.strokeWidth = 5

local tline = d.newLine(w20,h60,w80,h60 )
tline.strokeWidth = 5

-- 将棋盘格子尺寸放入表格中
board ={

    {“tl”,1,w20,h40,w40,h20,0},
    {“tm”,2,w40,h40,w60,h20,0},
    {“tr”,3,w60,h40,w80,h20,0},

    {“ml”,4,w20,h60,w40,h40,0},
    {“mm”,5,w40,h60,w60,h40,0},
    {“mr”,6,w60,h60,w80,h40,0},

    {“bl”,7,w20,h80,w40,h60,0},
    {“bm”,8,w40,h80,w60,h60,0},
    {“br”,9,w60,h80,w80,h60,0}
  }
--

-- 点击格子添加颜色
local function fill (event)
  if event.phase == “began” then
    tap =  0

    for t = 1, 9 do
      if event.x > board[t][3] and event.x < board [t][5] then
        if event.y < board[t][4] and event.y > board[t][6] then

          r = d.newRect(board[t][3],board [t][6],w20,h20)
          r:setFillColor(1,1,0)
          r.anchorX=0
          r.anchorY=0
        end
      end
    end
  end

end
Runtime:addEventListener(“touch”,fill)
点赞
用户7026995
用户7026995

我使用了新变量 whichTurn 来确定每回合应该在棋盘上放置什么。我认为代码本身是很容易理解的。试一试吧。

...

local EMPTY, X, O = 0, 1, 2
local whichTurn = X -- X 是开始游戏的一方

...

-- 当触摸到时填充相应格子的颜色
local function fill (event)
  if event.phase == "began" then
    for t = 1, 9 do
      if event.x > board[t][3] and event.x < board [t][5] then
        if event.y < board[t][4] and event.y > board[t][6] then
          if board[t][7] == EMPTY then
             board[t][7] = whichTurn
             --[[
             AND 运算符,如果第一个参数是假的,则返回第一个参数;否则返回第二个参数。
             OR 运算符,如果第一个参数不是假的,则返回第一个参数;否则返回第二个参数。
             --]]
             whichTurn = whichTurn == X and O or X
          end
        end
      end
    end
  end

end
Runtime:addEventListener("touch", fill)

你可以在 Corona 阅读更多有关触摸事件和点击事件的区别。

同时可以查看 Corona 文档 中的以下部分:

过滤多次点击

使用 event.numTaps 属性,您可以轻松确定对象是否被多次点击,并忽略在对象上单击的情况。

2016-11-04 19:58:03