Program Tip

Corona SDK의 타일을 한 단어로 결합하여 Breakout 게임 그리드를 만드시겠습니까?

programtip 2020. 10. 17. 12:06
반응형

Corona SDK의 타일을 한 단어로 결합하여 Breakout 게임 그리드를 만드시겠습니까?


Breakout 을 다시 구현할 게임 프로젝트가 있습니다. 한 줄에 각 단어를 두 단어로 표시하고 싶습니다. 그들은 벽돌 블록으로 연결됩니다. 내부에서 맨 윗줄은 왼쪽에 정렬 된 이름입니다. 맨 아래 줄은 오른쪽으로 정렬 된 성입니다. 텍스트 상자에서 입력되며 다음과 같이 렌더링됩니다.

위에서 설명한대로

1 초가 지나면 화면은 두 단어가 완성 된 것처럼 보일 때까지 구성 가능한 수의 브릭을 그리드에 추가합니다 (예 : 초당 5 개 브릭). 행렬 (0,1)에서 만든 알파벳 문자를 표시했습니다.

...하지만 나는 그것들을 한 단어로 결합하는 방법을 모릅니다. 이 편지에 어떻게 가입 할 수 있습니까?

이것이 내가 지금까지 얻은 것입니다.

Bricks.lua

local Bricks = display.newGroup() -- static object
local Events = require("Events")
local Levels = require("Levels")
local sound = require("Sound")
local physics = require("physics")
local Sprites = require("Sprites")
local Func = require("Func")


local brickSpriteData = 
{
    {
        name = "brick",
        frames = {Sprites.brick}
    },

    {
        name = "brick2",
        frames = {Sprites.brick2}
    },

    {
        name = "brick3",
        frames = {Sprites.brick3}
    },

}

-- animation table
local brickAnimations = {}

Sprites:CreateAnimationTable
{
    spriteData = brickSpriteData,
    animationTable = brickAnimations
}

-- get size from temp object for later use
local tempBrick = display.newImage('red_apple_20.png',300,500)
--local tempBrick = display.newImage('cheryGreen2.png',300,500)
local brickSize =
{
    width = tempBrick.width, 
    height = tempBrick.height
}
--tempBrick:removeSelf( )


----------------
-- Rubble -- needs to be moved to its own file
----------------

local rubbleSpriteData =
{
    {
        name = "rubble1",
        frames = {Sprites.rubble1}
    },

    {
        name = "rubble2",
        frames = {Sprites.rubble2}
    },

    {
        name = "rubble3",
        frames = {Sprites.rubble3}
    },

    {
        name = "rubble4",
        frames = {Sprites.rubble4}
    },

    {
        name = "rubble5",
        frames = {Sprites.rubble5}
    },

}

local rubbleAnimations = {}
Sprites:CreateAnimationTable
{
    spriteData = rubbleSpriteData,
    animationTable = rubbleAnimations
}

local totalBricksBroken = 0 -- used to track when level is complete
local totalBricksAtStart = 0

-- contains all brick objects
local bricks = {}


local function CreateBrick(data)

    -- random brick sprite
    local obj = display.newImage('red_apple_20.png')
    local objGreen = display.newImage('cheryGreen2.png')
    obj.name = "brick"
    obj.x = data.x --or display.contentCenterX
    obj.y = data.y --or 1000
    obj.brickType = data.brickType or 1
    obj.index = data.index

    function obj:Break()

        totalBricksBroken =  totalBricksBroken + 1
        bricks[self.index] = nil
        obj:removeSelf( )
        sound.play(sound.breakBrick)

    end

    function obj:Update()
        if(self == nil) then
            return
        end 

        if(self.y > display.contentHeight - 20) then
            obj:Break()
        end 
    end 
    if(obj.brickType ==1) then
        physics.addBody( obj, "static", {friction=0.5, bounce=0.5 } )
    elseif(obj.brickType == 2) then
        physics.addBody( objGreen,"static",{friction=0.2, bounce=0.5, density = 1 } )
    end 

    return obj
end

local currentLevel = testLevel
-- create level from bricks defined in an object
-- this allows for levels to be designed
local function CreateBricksFromTable(level)

    totalBricksAtStart = 0
    local activeBricksCount = 0
    for yi=1, #level.bricks do
        for xi=1, #level.bricks[yi] do
            -- create brick?
            if(level.bricks[yi][xi] > 0) then
                local xPos
                local yPos
                if(level.align == "center") then
                    --1100-((99*16)*0.5)
                    xPos = display.contentCenterX- ((level.columns * brickSize.width) * 0.5/3) + ((xi-1) * level.xSpace)--display.contentCenterX 
                    --xPos = 300 +(xi * level.xSpace)
                    yPos = 100 + (yi * level.ySpace)--100
                else
                    xPos = level.xStart + (xi * level.xSpace)
                    yPos = level.yStart + (yi * level.ySpace)
                end

                local brickData = 
                {
                    x = xPos,
                    y = yPos,
                    brickType = level.bricks[yi][xi],
                    index = activeBricksCount+1
                }
                bricks[activeBricksCount+1] = CreateBrick(brickData)

                activeBricksCount = activeBricksCount + 1

            end

        end 

    end

    totalBricks = activeBricksCount
    totalBricksAtStart = activeBricksCount


end

-- create bricks for level --> set from above functions, change function to change brick build type
local CreateAllBricks = CreateBricksFromTable
-- called by a timer so I can pass arguments to CreateAllBricks
local function CreateAllBricksTimerCall()
    CreateAllBricks(Levels.currentLevel)
end 
-- remove all brick objects from memory
local function ClearBricks()

    for i=1, #bricks do
        bricks[i] = nil
    end

end
-- stuff run on enterFrame event
function Bricks:Update()

-- update individual bricks
    if(totalBricksAtStart > 0) then
        for i=1, totalBricksAtStart do
            -- brick exists?
            if(bricks[i]) then
                bricks[i]:Update()
            end 
        end 
    end
    -- is level over?
    if(totalBricksBroken == totalBricks) then
        Events.allBricksBroken:Dispatch()
    end

end
----------------
-- Events
----------------
function Bricks:allBricksBroken(event)
    -- cleanup bricks
    ClearBricks()
    local t = timer.performWithDelay( 1000, CreateAllBricksTimerCall)
    --CreateAllBricks()
    totalBricksBroken = 0       

    -- play happy sound for player to enjoy
    sound.play(sound.win)

    print("You Win!")
end
Events.allBricksBroken:AddObject(Bricks)
CreateAllBricks(Levels.currentLevel)
return Bricks

Levels.lua

local Events = require("Events")
local Levels = {}
local function MakeLevel(data)
    local level = {}
    level.xStart = data.xStart or 100
    level.yStart = data.yStart or 100
    level.xSpace = data.xSpace or 23
    level.ySpace = data.ySpace or 23
    level.align = data.align or "center"
    level.columns = data.columns or #data.bricks[1]
    level.bricks = data.bricks --> required
    return level
end
Levels.test4 = MakeLevel
{
    bricks =
    {
        {0,2,0,0,2,0,0,2,0},
        {0,0,2,0,2,0,2,0,0},
        {0,0,0,0,2,0,0,0,0},
        {1,1,2,1,1,1,2,1,1},
        {0,0,0,0,1,0,0,0,0},
        {0,0,0,0,1,0,0,0,0},
        {0,0,0,0,1,0,0,0,0},
    }
}

Levels.test5 = MakeLevel
{
    bricks =
    {       
                    {0,0,0,1,0,0,0,0},
                     {0,0,1,0,1,0,0,0},
                     {0,0,1,0,1,0,0,0},
                     {0,1,0,0,0,1,0,0},
                     {0,1,1,1,1,1,0,0},
                     {1,0,0,0,0,0,1,0},
                     {1,0,0,0,0,0,1,0},
                     {1,0,0,0,0,0,1,0},
                     {1,0,0,0,0,0,1,0}
    }
}
-- Levels.test6 = MakeLevel2
-- {
--  bricks =
--  {
----A         "a" = {{0,0,0,1,0,0,0,0},
--                   {0,0,1,0,1,0,0,0},
--                   {0,0,1,0,1,0,0,0},
--                   {0,1,0,0,0,1,0,0},
--                   {0,1,1,1,1,1,0,0},
--                   {1,0,0,0,0,0,1,0},
--                   {1,0,0,0,0,0,1,0},
--                   {1,0,0,0,0,0,1,0},
--                   {1,0,0,0,0,0,1,0}},
----B
--            "b" = {{1,1,1,1,0,0,0},
--                   {1,0,0,0,1,0,0},
--                   {1,0,0,0,1,0,0},
--                   {1,0,0,0,1,0,0},
--                   {1,1,1,1,0,0,0},
--                   {1,0,0,0,1,0,0},
--                   {1,0,0,0,0,1,0},
--                   {1,0,0,0,0,1,0},
--                   {1,1,1,1,1,0,0}},
--...........
--.......
--...
-- --Z
--             "z"= {{1,1,1,1,1,1,1,0},
--                   {0,0,0,0,0,1,0,0},
--                   {0,0,0,0,1,0,0,0},
--                   {0,0,0,0,1,0,0,0},
--                   {0,0,0,1,0,0,0,0},
--                   {0,0,1,0,0,0,0,0},
--                   {0,0,1,0,0,0,0,0},
--                   {0,1,0,0,0,0,0,0},
--                   {1,1,1,1,1,1,1,0}} 
--  }
-- }
-- stores all levels in ordered table so that one can be selected randomly by index
Levels.levels = 
{
    --Levels.test4,
     Levels.test5
    -- Levels.test6,
}
function Levels:GetRandomLevel()
    return self.levels[math.random(#Levels.levels)]
end
Levels.notPlayedYet = {}
Levels.currentLevel = Levels:GetRandomLevel()
-- Events
function Levels:allBricksBroken(event)
    self.currentLevel = Levels:GetRandomLevel()
end
Events.allBricksBroken:AddObject(Levels)
return Levels

지금까지 수행 한 작업 (위와 동일)을 외부 다운로드 : http://www.mediafire.com/download/1t89ftkbznkn184/Breakout2.rar


실제로 질문에 답하기 위해 :

"어떻게이 편지에 가입 할 수 있니?"라는 말이 무슨 뜻인지 100 % 확신 할 수는 없지만 코드를 훑어 보면 추측이 나왔으니 그것이 정확한지 아니면 내가 원하는 것이 틀렸는 지 명확히 해주세요.

시나리오 1

스크린 샷에 표시된 이미지를 성공적으로 얻지 못했습니다. 한 글자를 그릴 수 있었지만 여러 글자를 그릴 수 없었습니다.

이 경우 코드가 수행하는 작업을 더 잘 이해해야합니다. CreateBricksFromTable함수는 열이있는 행을 나타내는 테이블 테이블 인 속성이 MakeLevel있는 테이블 에서 함수에 의해 생성 된 Level 객체 bricks를 가져와 각 위치에 있어야하는 벽돌 유형을 보여줍니다. 주석 처리 된 수준에서 bricks필드에 각 문자에 대한 필드가 포함 된 테이블을 만들었지 만 MakeLevel함수는 여전히 bricks블록 그리드를 직접 포함 하는 필드를 예상합니다 . 시도한 것처럼- MakeWordLevel이 문자 목록과 각 줄에 대한 단어를 사용하는 함수 (또는 이와 유사한 것)를 만들고 적절한 문자를 복사하여 더 큰 격자를 구성해야합니다.

StackOverflow는 프로그래밍 튜터가 아니며 SO 질문은 사람들이 코드를 작성하도록하거나이 작업을 수행하는 방법에 대한 단계별 세부 정보를 입력하는 데 적합한 포럼이 아닙니다.하지만 기본적인 개요를 남겨 드리겠습니다. 함수는 다음과 같습니다.

local function MakeWordLevel(data, line1, line2)
    local level = {}
    ...
    return level
end

그리고 다음을 수행해야합니다.

  • 동일한 속성의 모든 웁니다 MakeLevel수행을
  • level.columns모든 문자가있는 레벨의 너비 ( )를 계산합니다.
  • bricks속성 과 동일한 형식으로 모든 문자를 담을 수있을만큼 큰 테이블을 만듭니다.
  • 입력 문자열 ( line1line2)을 살펴보고 현재 test6배열 에서 올바른 문자 데이터를 찾은 다음 해당 데이터를 큰 테이블에 복사합니다.
  • 해당 테이블을 다음과 같이 지정하십시오. level.bricks

This question already is a bit outside of what StackOverflow is intended for in that it asks about how to implement a feature rather than achieve a small, specific programming task, so any further followup should take place in a chatroom - perhaps the Hello World room would be helpful.

Scenario 2:

This was my original guess, but after considering and reading past edits, I doubt this is answering the right question

You may want a solid "background" of, say, red blocks, surrounding your letters and making the field into a solid "wall", with the name in a different color. And you may want these bricks to slowly show up a few at a time.

In that case, the main thing you need to do is keep track of what spaces are "taken" by the name bricks. There are many ways to do this, but I would start with a matrix to keep track of that - as big as the final playing field - full of 0's. Then, as you add the bricks for the name, set a 1 at the x,y location in that matrix according to that block's coordinate.

When you want to fill in the background, each time you go to add a block at a coordinate, check that "taken" matrix before trying to add a block - if it's taken (1), then just skip it and move onto the next coordinate.

This works if you're filling in the background blocks sequentially (say, left to right, top to bottom), or if you want to add them randomly. With random, you'd also want to keep updating the "taken" matrix so you don't try to add a block twice.

The random fill-in, however, presents its own problem - it will keep taking longer to fill in as it goes, because it'll find more and more "taken" blocks and have to pick a new one. There are solutions to this, of course, but I won't go too far down that road when I don't know if that's even what you want.


I don't really understand (or read, for that matter) your code but from what I see joining them into complete words is easy. You have two possibilities.

레벨 / 디스플레이 데이터로 직접 "렌더링"할 수 있습니다. 다음과 같이 적절한 위치에 복사하면됩니다.

-- The level data.
local level = {}

-- Create the level data.
for row = 1, 25, 1 do
    local rowData = {}

    for column = 1, 80, 1 do
        rowData[column] = "."
    end

    level[row] = rowData
end

-- Now let us setup the letters.
local letters = {
    A = {
        {".",".",".","#",".",".",".","."},
        {".",".","#",".","#",".",".","."},
        {".",".","#",".","#",".",".","."},
        {".","#",".",".",".","#",".","."},
        {".","#","#","#","#","#",".","."},
        {"#",".",".",".",".",".","#","."},
        {"#",".",".",".",".",".","#","."},
        {"#",".",".",".",".",".","#","."},
        {"#",".",".",".",".",".","#","."}
    },
    B = {
        {"#","#","#","#",".",".","."},
        {"#",".",".",".","#",".","."},
        {"#",".",".",".","#",".","."},
        {"#",".",".",".","#",".","."},
        {"#","#","#","#",".",".","."},
        {"#",".",".",".","#",".","."},
        {"#",".",".",".",".","#","."},
        {"#",".",".",".",".","#","."},
        {"#","#","#","#","#",".","."}
    }
}

-- The string to print.
local text = "ABBA"

-- Let us insert the data into the level data.
for index = 1, #text, 1 do
    local char = string.sub(text, index, index)
    local charData = letters[char]

    local offset = index * 7

    for row = 1, 9, 1 do
        local rowData = charData[row]

        for column = 1, 7, 1 do
            level[row][offset + column] = rowData[column]
        end
    end
end

-- Print everything
for row = 1, 25, 1 do
    local rowData = level[row]

    for column = 1, 80, 1 do
        io.write(rowData[column])
    end
    print()

end

룩업 테이블에 문자를 저장 한 다음 레벨 데이터에 하나씩 복사합니다. 여기서는 숫자를 점과 숫자 기호로 대체하여 명령 줄에서 더 예쁘게 만들었습니다.

또는 준비된 버퍼에 단어를 "렌더링"한 다음 동일한 논리를 사용하여 레벨 데이터에 삽입 할 수도 있습니다.

참고 URL : https://stackoverflow.com/questions/38484433/join-tiles-in-corona-sdk-into-one-word-for-a-breakout-game-grid

반응형