用lua写了个在consle上运行的2048,这里简单说下是如何实现的。(源代码地址:http://download.youkuaiyun.com/detail/c_boy_lu/9393255)
1.实现一个简单的游戏循环
游戏循环实际上是一个死循环,只有在退出游戏的时候,终止循环。
- 初始化
- 更新
逻辑更新
显示更新
- sleep
代码:
print("=========2048=========")
--main loop
print("Direction:Up = 1")
print("Direction:Down = 2")
print("Direction:Left = 3")
print("Direction:Right = 4")
--init 初始化
createNewCell()
show()
while (true)
do
--control
print("Please enter a direction:")
local direc = tonumber(io.read())
local isUpdata = printInpuInfo(direc)
if isUpdata then
--logic
updataLogic(direc)
--show
show()
end
--reset clean times
local max = width * height
for i = 1,max do
cell_clean_times[i] = 0
end
--sleep
sleep(0.5)
end
2.游戏中的逻辑
a. 玩法:游戏开始的时候,会在棋盘上随机产生一个可消除的元素,每次操作后,如果,棋盘上有空余的位置,则产生一个新的可消除的元素。消除的规则是,玩家进行上下左右的操作,棋盘中的元素根据玩家的操作上下左右移动,同时,同一方向上相同的元素消除,组成一个新的元素。
b.逻辑:游戏的逻辑分为三部分:
1)得到玩家发出的指令(上,下,左,右)
2)根据指令进行移动和消除
3)显示当前棋盘的状态
1)读取玩家的输入,得到玩家的操作:
local direc = tonumber(io.read()):读取玩家输入的数字
local isUpdata = printInpuInfo(direc):输出玩家的操作信息,判断是否进行更新(如果,玩家输入的信息是有效信息,则进行操作,否则不进行操作)
2)这里就是游戏所有的逻辑了:根据方向进行移动,消除,创建新的元素:
3)显示棋盘当前的状态
--逻辑更新
function updataLogic(direction)
print("updata logic")
--clean cell
if direction == UP then
moveUp()
cleanUp()
moveUp()
elseif direction == DOWN then
moveDown()
cleanDown()
moveDown()
elseif direction == LEFT then
moveLeft()
cleanLeft()
moveLeft()
elseif direction == RIGHT then
moveRight()
cleanRight()
moveRight()
end
--create new cell
createNewCell()
end
3)显示棋盘当前的状态
--显示更新
function show()
print("updata show")
showChessBoard()
end
源代码地址:http://download.youkuaiyun.com/detail/c_boy_lu/9393255
本文介绍如何利用Lua语言实现经典的2048小游戏。从初始化游戏板到设计更新规则,再到实现游戏流程中的暂停功能,详细解析每个步骤。
934

被折叠的 条评论
为什么被折叠?



