문자열로 조작하는 대화창 만들기

 

 

이 글은 대화창 만들기에서 설명을 드린 곳에 들어간

 

실행기를 만든 전체 CS파일을 복사해서 올려드린 글입니다.

 

설명은 아래에서 보실 수 있습니다.

 

 

[C#] 문자열로 조작 가능! 대화창 만들기!

안녕하십니까. 밤말팅입니다! 저번 시간에는 [은/는] 과 같이 앞 글자에 영향을 받는 조사를 변환시켜 보았는데요! [C#]은는이가 타파!! 자연스러운 문장 만들기! 안녕하십니까 밤말팅입니다! 오

game-part-factory.tistory.com

 

 

스크립트 실행기.zip
0.09MB

using System;
using System.IO;

namespace LineReader
{
    class TextContainer
    {
        public static string[] text;
    }

    class Program
    {
        public static System.Diagnostics.Stopwatch time;

        private static System.Threading.Thread threadKeyRead;

        public static ConsoleKey currentKey = 0;

        static void Main(string[] args)
        {
            time = new System.Diagnostics.Stopwatch();
            time.Start();
            
            threadKeyRead = new System.Threading.Thread(delegate () {
                while (true)
                {
                    currentKey = Console.ReadKey(true).Key;
                };
            });
            threadKeyRead.Start();

            string textFilePath = Directory.GetCurrentDirectory() + @"\CONTEXT.txt";
            if (File.Exists(textFilePath))
            {
                TextContainer.text = File.ReadAllLines(textFilePath);

                TextReader.StartRead(0);
            }
            else
            {
                File.Create(textFilePath);
                Console.WriteLine("파일이 존재하지 않았습니다. 새로 생성된 CONTEXT.txt 파일을 이용하여 새로운 스크립트를 제작해주시기 바랍니다.");
            };

            while (true)
            {
                TextReader.Update();
            };
        }

        public class TextReader
        {
            private static SelectInformation[] currentSelection = new SelectInformation[8];

            public static VariableList globalVariable = new VariableList();

            private static string talkName = "???";
            private static string showText = "";
            private static string receiptText = "";
            private static string calculatedText = "";

            private static long nextTime = 0;

            private static int currentTextIndex = 0;
            private static int currentReadIndex = 0;

            private static int currentSelectionNumber = 0;

            private static int globalReadSpeed = 10;
            private static int currentReadSpeed = 10;

            private static int currentReadPage = 0;
            private static int nextReadPage = 0;

            private static int commandStartIndex = 0;
            private static int commandDepth = 0;

            private static bool reading = false;
            private static bool skip = false;

            public static void Update()
            {
                if (reading)
                {
                    if(currentKey == ConsoleKey.Enter || currentKey == ConsoleKey.Spacebar)
                    {
                        currentKey = 0;
                        skip = true;
                    };

                    OnRead();
                }
                else
                {
                    if(currentKey == ConsoleKey.Enter || currentKey == ConsoleKey.Spacebar)
                    {
                        if(currentSelectionNumber <= 0)
                        {
                            currentKey = 0;
                            StartRead(nextReadPage);
                        };
                    }
                    else if(currentKey == ConsoleKey.A)
                    {
                        ChoiceSelection(0);
                    }
                    else if (currentKey == ConsoleKey.S)
                    {
                        ChoiceSelection(1);
                    }
                    else if (currentKey == ConsoleKey.D)
                    {
                        ChoiceSelection(2);
                    }
                    else if (currentKey == ConsoleKey.F)
                    {
                        ChoiceSelection(3);
                    }
                    else if (currentKey == ConsoleKey.Z)
                    {
                        ChoiceSelection(4);
                    }
                    else if (currentKey == ConsoleKey.X)
                    {
                        ChoiceSelection(5);
                    }
                    else if (currentKey == ConsoleKey.C)
                    {
                        ChoiceSelection(6);
                    }
                    else if (currentKey == ConsoleKey.V)
                    {
                        ChoiceSelection(7);
                    };
                };
            }

            public static void StartRead(int page)
            {
                if (reading)
                {
                    return;
                };

                reading = true;
                skip = false;

                currentReadPage = page;
                nextReadPage = page + 1;

                calculatedText = "";
                showText = "";

                nextTime = 0;

                currentTextIndex = 0;
                currentReadIndex = 0;

                commandStartIndex = 0;
                commandDepth = 0;

                currentReadSpeed = globalReadSpeed;

                if (currentReadPage < TextContainer.text.Length)
                {
                    receiptText = TextContainer.text[currentReadPage];
                }
                else
                {
                    talkName = "<System>";
                    receiptText = "스크립트가 종료되었습니다.";
                    nextReadPage = page;
                };

                string showingName = talkName;
                Console.Clear();
                Console.WriteLine(showingName);
            }

            private static void OnRead()
            {
                if (skip || nextTime <= time.ElapsedMilliseconds)
                {
                    if (currentReadIndex < calculatedText.Length)
                    {
                        showText += calculatedText[currentReadIndex];
                        Console.Write(calculatedText[currentReadIndex]);
                        ++currentReadIndex;

                        nextTime = time.ElapsedMilliseconds + currentReadSpeed;
                    }
                    else if (currentTextIndex < receiptText.Length)
                    {
                        if (receiptText[currentTextIndex] == '[')
                        {
                            commandStartIndex = currentTextIndex;
                            ++currentTextIndex;
                            commandDepth = 1;

                            while (currentTextIndex < receiptText.Length)
                            {
                                if (receiptText[currentTextIndex] == '[')
                                {
                                    ++commandDepth;
                                }
                                else if (receiptText[currentTextIndex] == ']')
                                {
                                    --commandDepth;
                                };

                                if (commandDepth <= 0)
                                {
                                    if (calculatedText.Length - 1 > 0)
                                    {
                                        calculatedText += CommandChecker(calculatedText[calculatedText.Length - 1], receiptText.Substring(commandStartIndex, currentTextIndex - commandStartIndex + 1));
                                    }
                                    else
                                    {
                                        calculatedText += CommandChecker(' ', receiptText.Substring(commandStartIndex, currentTextIndex - commandStartIndex + 1));
                                    };

                                    ++currentTextIndex;

                                    break;
                                }
                                else
                                {
                                    ++currentTextIndex;
                                };
                            };
                        }
                        else
                        {
                            calculatedText += receiptText[currentTextIndex];
                            ++currentTextIndex;
                        };
                    };

                    if (currentTextIndex >= receiptText.Length && currentReadIndex >= calculatedText.Length)
                    {
                        reading = false;
                        skip = false;

                        Console.Write('\n');

                        if (currentSelectionNumber > 0)
                        {
                            Console.WriteLine("A : " + currentSelection[0].context);
                        };
                        if (currentSelectionNumber > 1)
                        {
                            Console.WriteLine("S : " + currentSelection[1].context);
                        };
                        if (currentSelectionNumber > 2)
                        {
                            Console.WriteLine("D : " + currentSelection[2].context);
                        };
                        if (currentSelectionNumber > 3)
                        {
                            Console.WriteLine("F : " + currentSelection[3].context);
                        };
                        if (currentSelectionNumber > 4)
                        {
                            Console.WriteLine("Z : " + currentSelection[4].context);
                        };
                        if (currentSelectionNumber > 5)
                        {
                            Console.WriteLine("X : " + currentSelection[5].context);
                        };
                        if (currentSelectionNumber > 6)
                        {
                            Console.WriteLine("C : " + currentSelection[6].context);
                        };
                        if (currentSelectionNumber > 7)
                        {
                            Console.WriteLine("V : " + currentSelection[7].context);
                        };
                        return;
                    };
                };
            }

            private enum CommandType
            {
                GetVariable,
                Substitute,
                Postposition,
                Condition,
                Select
            }

            private static string CommandChecker(char preText, string targetCommand)
            {
                if (targetCommand.Length <= 2)
                {
                    return "";
                }
                else
                {
                    targetCommand = targetCommand.Substring(1, targetCommand.Length - 2);
                };

                int divideIndex = 0;
                int commandDepth = 0;
                
                CommandType currentCommand = CommandType.GetVariable;

                string returnText = "";

                for (int index = 0; index < targetCommand.Length; ++index)
                {
                    if (targetCommand[index] == '[' || targetCommand[index] == '(')
                    {
                        ++commandDepth;
                    }
                    else if (targetCommand[index] == ']' || targetCommand[index] == ')')
                    {
                        --commandDepth;
                    };

                    if (commandDepth == 0)
                    {
                        if (targetCommand[index] == '/')
                        {
                            currentCommand = CommandType.Postposition;
                            divideIndex = index;
                            break;
                        }
                        else if (targetCommand[index] == ':')
                        {
                            currentCommand = CommandType.Substitute;
                            divideIndex = index;
                            break;
                        }
                        else if (targetCommand[index] == '?')
                        {
                            divideIndex = index;
                            string leftArgument = targetCommand.Substring(0, divideIndex).Trim();
                            if (leftArgument.Length > 0 && leftArgument[0] == '(' && leftArgument[leftArgument.Length - 1] == ')')
                            {
                                currentCommand = CommandType.Select;
                                break;
                            }
                            else
                            {
                                currentCommand = CommandType.Condition;
                                break;
                            };
                        };
                    };
                };

                if (currentCommand == CommandType.Postposition)
                {
                    if (FinalConsonant(preText))
                    {
                        returnText = CommandText(targetCommand.Substring(0, divideIndex).Trim());
                    }
                    else
                    {
                        returnText = CommandText(targetCommand.Substring(divideIndex + 1, targetCommand.Length - divideIndex - 1).Trim());
                    };
                }
                else if (currentCommand == CommandType.Substitute)
                {
                    string arg0 = CommandText(targetCommand.Substring(0, divideIndex).Trim());
                    string arg1 = CommandText(targetCommand.Substring(divideIndex + 1, targetCommand.Length - divideIndex - 1).Trim());

                    if (arg0 == "Speed")
                    {
                        int checkedNumber;

                        if (arg1.Length > 0 && int.TryParse(arg1, out checkedNumber))
                        {
                            currentReadSpeed = checkedNumber;
                        }
                        else
                        {
                            currentReadSpeed = globalReadSpeed;
                        };
                    }
                    else if (arg0 == "TalkName")
                    {
                        ChangeName(arg1);
                    }
                    else if(arg0 == "Wait")
                    {
                        int checkedNumber;

                        if (arg1.Length > 0 && int.TryParse(arg1, out checkedNumber))
                        {
                            nextTime = time.ElapsedMilliseconds + checkedNumber;
                        };
                    }
                    else if(arg0 == "Next")
                    {
                        int checkedNumber;

                        if(arg1.Length > 0 && int.TryParse(arg1, out checkedNumber))
                        {
                            if(arg1[0] == '+' || arg1[0] == '-')
                            {
                                nextReadPage = currentReadPage + checkedNumber;
                            }
                            else
                            {
                                nextReadPage = checkedNumber - 1;
                            };

                            if(nextReadPage < 0)
                            {
                                nextReadPage = 0;
                            };
                        };
                    }
                    else
                    {
                        globalVariable.Set(arg0, arg1);
                    };
                }
                else if (currentCommand == CommandType.GetVariable)
                {
                    if (targetCommand == "Speed")
                    {
                        returnText = Convert.ToString(currentReadSpeed);
                    }
                    else if (targetCommand == "TalkName")
                    {
                        returnText = talkName;
                    }
                    else if(targetCommand == "Next")
                    {
                        returnText = Convert.ToString(nextReadPage);
                    }
                    else if(targetCommand == "Wait")
                    {
                        returnText = null;
                    }
                    else if(targetCommand == "Input")
                    {
                        Console.Write('\n');
                        Console.WriteLine("입력 :");
                        returnText = Console.ReadLine();
                        Console.Clear();
                        Console.WriteLine(talkName);
                        Console.Write(showText);
                    }
                    else
                    {
                        returnText = globalVariable.Get(CommandText(targetCommand));
                    };
                }
                else if(currentCommand == CommandType.Condition)
                {
                    string arg0 = targetCommand.Substring(0, divideIndex).Trim();
                    string arg1 = targetCommand.Substring(divideIndex + 1, targetCommand.Length - divideIndex - 1).Trim();

                    bool conditionCheck = false;

                    if(arg0.Length > 0)
                    {
                        int leftEnd = 0;
                        int rightStart = 0;

                        bool checkEqual = false;
                        bool checkNotEqual = false;
                        bool checkBigger = false;
                        bool checkSmaller = false;

                        for (int index = 0; index < arg0.Length; ++index)
                        {
                            if (arg0[index] == '=')
                            {
                                if(index > 0 && arg0[index - 1] == '!')
                                {
                                    checkNotEqual = true;
                                    if(leftEnd == 0)
                                    {
                                        leftEnd = index - 2;
                                    };
                                    rightStart = index + 1;
                                }
                                else if(!checkNotEqual)
                                {
                                    checkEqual = true;
                                    if (leftEnd == 0)
                                    {
                                        leftEnd = index - 1;

                                        if(leftEnd < 0)
                                        {
                                            leftEnd = 0;
                                        };
                                    };
                                    rightStart = index + 1;
                                };
                            }
                            else if(arg0[index] == '>')
                            {
                                checkBigger = true;
                                if (leftEnd == 0)
                                {
                                    leftEnd = index - 1;
                                };
                                rightStart = index + 1;
                            }
                            else if (arg0[index] == '<')
                            {
                                checkSmaller = true;
                                if (leftEnd == 0)
                                {
                                    leftEnd = index - 1;
                                };
                                rightStart = index + 1;
                            };
                        };

                        if(leftEnd == 0 && rightStart == 0)
                        {
                            if (globalVariable.Get(CommandText(arg0)) != null && globalVariable.Get(CommandText(arg0)).ToLower() != "false")
                            {
                                conditionCheck = true;
                            };
                        }
                        else
                        {
                            string leftText = CommandText(arg0.Substring(0, leftEnd).Trim());
                            string leftValue = globalVariable.Get(leftText);
                            if (leftValue == null)
                            {
                                leftValue = leftText;
                            };

                            string rightText = CommandText(arg0.Substring(rightStart, arg0.Length - rightStart).Trim());
                            string rightValue = globalVariable.Get(rightText);
                            if (rightValue == null)
                            {
                                rightValue = rightText;
                            };

                            if (checkEqual && leftValue == rightValue)
                            {
                                conditionCheck = true;
                            }
                            else if (checkNotEqual && leftValue != rightValue)
                            {
                                conditionCheck = true;
                            };
                            
                            if (checkBigger || checkSmaller)
                            {
                                int leftNumber;
                                int rightNumber;

                                if (int.TryParse(leftValue, out leftNumber) && int.TryParse(rightValue, out rightNumber))
                                {
                                    if (checkBigger && leftNumber > rightNumber)
                                    {
                                        conditionCheck = true;
                                    };

                                    if (checkSmaller && leftNumber < rightNumber)
                                    {
                                        conditionCheck = true;
                                    };
                                };
                            };
                        };
                    }
                    else
                    {
                        conditionCheck = true;
                    };

                    int resultDivideIndex = -4;
                    int rightCommandDepth = 0;
                    for(int index = 0; index < arg1.Length; ++index)
                    {
                        if(arg1[index] == '[')
                        {
                            ++rightCommandDepth;
                        }
                        else if(arg1[index] == ']')
                        {
                            --rightCommandDepth;
                        }
                        else if(arg1[index] == ':' && rightCommandDepth == 0)
                        {
                            resultDivideIndex = index;
                            break;
                        };
                    };

                    if (conditionCheck || resultDivideIndex < 0)
                    {
                        if(resultDivideIndex < 0)
                        {
                            return CommandText(arg1.Trim());
                        }
                        else
                        {
                            return CommandText(arg1.Substring(0, resultDivideIndex).Trim());
                        };
                    }
                    else
                    {
                        return CommandText(arg1.Substring(resultDivideIndex + 1, arg1.Length - resultDivideIndex - 1).Trim());
                    };
                }
                else if(currentCommand == CommandType.Select)
                {
                    string arg0 = targetCommand.Substring(0, divideIndex - 1).Trim();
                    arg0 = arg0.Substring(1, arg0.Length - 2).Trim();
                    string arg1 = targetCommand.Substring(divideIndex + 1, targetCommand.Length - divideIndex - 1).Trim();

                    int rightDivide = 0;
                    int rightCommandDepth = 0;
                    bool rightDivided = false;
                    if(arg1.Length > 0)
                    {
                        for(int index = 0; index < arg1.Length; ++index)
                        {
                            if(arg1[index] == '[')
                            {
                                ++rightCommandDepth;
                            }
                            else
                            {
                                --rightCommandDepth;
                            };

                            if(rightCommandDepth == 0 && arg1[index] == ':')
                            {
                                rightDivided = true;
                                rightDivide = index;
                                break;
                            };
                        };
                    };

                    string onSelect;
                    string notSelect;

                    if (rightDivided)
                    {
                        onSelect = arg1.Substring(0, rightDivide).Trim();
                        notSelect = arg1.Substring(rightDivide + 1, arg1.Length - rightDivide - 1).Trim();
                    }
                    else
                    {
                        onSelect = arg1;
                        notSelect = "";
                    };

                    CreateSelection(arg0, onSelect, notSelect);
                };

                if (returnText == null || returnText.Length <= 0)
                {
                    return null;
                }
                else
                {
                    return CommandText(returnText);
                };
            }

            private static string CommandText(string targetText)
            {
                string returnText = targetText;
                int commandStartIndex = 0;
                int commandDepth = 0;

                string checkedCommand;

                for (int index = 0; index < returnText.Length; ++index)
                {
                    if (returnText[index] == '[')
                    {
                        if(commandStartIndex == 0)
                        {
                            commandStartIndex = index;
                        };
                        ++commandDepth;
                    }
                    else if (returnText[index] == ']')
                    {
                        --commandDepth;
                        if (commandDepth <= 0)
                        {
                            checkedCommand = returnText.Substring(commandStartIndex, index - commandStartIndex + 1);

                            returnText = returnText.Remove(commandStartIndex, index - commandStartIndex + 1);
                            index = commandStartIndex;

                            if (checkedCommand != null)
                            {
                                if (index <= 0)
                                {
                                    index = 0;
                                    returnText = CommandChecker(' ', checkedCommand) + returnText;
                                }
                                else
                                {
                                    if (returnText != null && returnText.Length > 0)
                                    {
                                        returnText = returnText.Insert(index, CommandChecker(returnText[index - 1], checkedCommand));
                                    }
                                    else
                                    {
                                        returnText = CommandChecker(' ', checkedCommand);
                                    };
                                };
                            };
                                
                            commandDepth = 0;
                            commandStartIndex = 0;
                            --index;
                        };
                    };

                    if (returnText == null)
                    {
                        return null;
                    };
                };

                return returnText;
            }

            private static bool FinalConsonant(char wantCharacter)
            {
                if (wantCharacter < 44032 || wantCharacter > 55215)
                {
                    return false;
                };

                int checker = wantCharacter;

                checker -= 44032;

                return (checker % 28) > 0;
            }

            private static void CreateSelection(string wantContext, string wantOnSelect, string wantNotSelect)
            {
                if(currentSelectionNumber < currentSelection.Length)
                {
                    currentSelection[currentSelectionNumber] = new SelectInformation(wantContext, wantOnSelect, wantNotSelect);

                    ++currentSelectionNumber;
                };
            }

            private static void ChoiceSelection(int wantNumber)
            {
                if (!reading && wantNumber < currentSelectionNumber)
                {
                    for(int index = 0; index < currentSelectionNumber; ++index)
                    {
                        if(currentSelection[wantNumber] == null)
                        {
                            break;
                        };

                        if(index == wantNumber)
                        {
                            if(currentSelection[wantNumber].onSelectedAction != null)
                            {
                                CommandText(currentSelection[wantNumber].onSelectedAction);
                            };
                        }
                        else
                        {
                            if (currentSelection[wantNumber].notSelectedAction != null)
                            {
                                CommandText(currentSelection[wantNumber].notSelectedAction);
                            };
                        };

                        currentSelection[index] = null;
                    };

                    currentSelectionNumber = 0;

                    StartRead(nextReadPage);
                };
            }

            private static void ChangeName(string wantName)
            {
                talkName = wantName;

                Console.Clear();
                Console.WriteLine(talkName);
                Console.Write(showText);
            }
        }
    }

    public class SelectInformation
    {
        public string context;
        public string onSelectedAction;
        public string notSelectedAction;

        public SelectInformation(string wantContext, string wantOnSelectedAction, string wantNotSelectedAction)
        {
            context = wantContext;
            onSelectedAction = wantOnSelectedAction;
            notSelectedAction = wantNotSelectedAction;
        }
    }

    public class VariableList
    {
        public Variable start;
        public Variable end;

        public Variable lastContactVariable;

        public int count { get { return realCount; } }
        private int realCount;

        public VariableList()
        {
            start = null;
            end = null;
            lastContactVariable = null;
        }

        public void Set(string wantName, string wantValue)
        {
            Variable target = Find(wantName);

            if(target == null)
            {
                target = new Variable(wantName, wantValue);

                if (end != null)
                {
                    end.next = target;
                }
                else
                {
                    start = target;
                };

                end = target;
                lastContactVariable = target;

                ++realCount;
            }
            else
            {
                target.value = wantValue;
            };
        }

        public string Get(string wantName)
        {
            Variable target = Find(wantName);

            if (target != null)
            {
                return target.value;
            };

            return null;
        }

        public Variable Find(string wantName)
        {
            if (count <= 0)
            {
                return null;
            };

            if (lastContactVariable.name == wantName)
            {
                return lastContactVariable;
            };

            Variable check = start;

            for (int index = 0; index < count; ++index)
            {
                if (check != null)
                {
                    if (check.name == wantName)
                    {
                        lastContactVariable = check;
                        return check;
                    }
                    else
                    {
                        check = check.next;
                    };
                }
                else
                {
                    return null;
                };
            };

            return null;
        }
    }

    public class Variable
    {
        public string name;
        public string value;

        public Variable next;

        public Variable(string wantName, string wantValue)
        {
            name = wantName;
            value = wantValue;
            next = null;
        }
    }
}

'부품 설계도' 카테고리의 다른 글

[C#] 디아블로 스타일 인벤토리 전체 코드  (0) 2020.12.27
[C#]Bit_Builder 전체 코드  (0) 2020.11.15

 

[C#] 디아블로 스타일 인벤토리 만들기

안녕하십니까! 밤말팅입니다! 두 번째 포스팅으로 만나 뵙게 되었네요~ 오랜만에 들고 온 컨텐츠는 바로! [디아블로 스타일 인벤토리 만들기]입니다! 가방 크기는 전혀 신경 쓰지 않으셔도 되겠

game-part-factory.tistory.com

이 글은 위에서 설명하는 클래스의 전체 코드입니다!

 

내용이 궁금하시면 해당 포스팅을 참고해주시면 감사드리겠습니다~

 

using System;
using System.Collections.Generic;
public class ItemInfo
{
    public static int nextId = 0;

    public int itemID;
    public int sizeX;
    public int sizeY;
    public int stackMax;

    public ItemInfo(int wantSizeX, int wantSizeY, int wantStackMax)
    {
        itemID = nextId++;
        sizeX = wantSizeX;
        sizeY = wantSizeY;
        stackMax = wantStackMax;
    }

    public static ItemInfo sword = new ItemInfo(1, 4, 1);
    public static ItemInfo sheild = new ItemInfo(2, 4, 1);
    public static ItemInfo armor = new ItemInfo(4, 6, 1);
    public static ItemInfo shoes = new ItemInfo(3, 3, 1);
    public static ItemInfo pants = new ItemInfo(4, 5, 1);
    public static ItemInfo bread = new ItemInfo(3, 2, 16);
}
public class ItemContain
{
    private int locationX = 0;
    private int locationY = 0;
    private int stack = 0;
    private ItemInfo itemCurrent = null;

    public ItemContain(int wantLocationX, int wantLocationY, int wantStack, ItemInfo wantItem)
    {
        locationX = wantLocationX;
        locationY = wantLocationY;
        stack = wantStack;
        itemCurrent = wantItem;
    }

    public ItemContain(int wantStack, ItemInfo wantItem)
    {
        stack = wantStack;
        itemCurrent = wantItem;
    }

    public bool ItemCheck(ItemInfo wantItem)
    {
        if (itemCurrent.itemID == wantItem.itemID) 
        {
            return true;
        };
        return false;
    }

    public int ItemStack(int wantNumber)
    {
        stack += wantNumber;
        if(stack > itemCurrent.stackMax)
        {
            int retval = stack - itemCurrent.stackMax;
            stack = itemCurrent.stackMax;
            return retval;
        }
        else
        {
            return 0;
        };
    }

    public int ItemDestack(int wantNumber)
    {
        stack -= wantNumber;
        return stack;
    }

    public ItemContain ItemSplit(int wantStack)
    {
        if (stack > wantStack)
        {
            ItemDestack(wantStack);
            return new ItemContain(locationX, locationY, wantStack, itemCurrent);
        }
        else
        {
            return this;
        };
    }

    public bool ItemOverlap(int targetLocationX, int targetLocationY)
    {
        if(targetLocationX >= locationX && targetLocationX < locationX + itemCurrent.sizeX && targetLocationY >= locationY && targetLocationY < locationY + itemCurrent.sizeY)
        {
            return true;
        }
        else
        {
            return false;
        };
    }

    public bool ItemOverlap(int targetLocationX, int targetLocationY, int targetSizeX, int targetSizeY)
    {
        if(targetLocationX >= locationX + itemCurrent.sizeX || targetLocationX + targetSizeX <= locationX || targetLocationY >= locationY + itemCurrent.sizeY || targetLocationY + targetSizeY <= locationY)
        {
            return false;
        }
        else
        {
            return true;
        };
    }

    public int GetItemStack()
    {
        return stack;
    }

    public ItemInfo GetItemInfo()
    {
        return itemCurrent;
    }

    public int GetLocationX()
    {
        return locationX;
    }

    public int GetLocationY()
    {
        return locationY;
    }

    public int GetSizeX()
    {
        return itemCurrent.sizeX;
    }

    public int GetSizeY()
    {
        return itemCurrent.sizeY;
    }

    public void SetItemStack(int wantStack)
    {
        stack = wantStack;
    }

    public void SetLocation(int wantX, int wantY)
    {
        locationX = wantX;
        locationY = wantY;
    }
}
public class XFinder
{
    public int startX;
    public int lastX;

    public XFinder(int wantStartX, int wantLastX)
    {
        startX = wantStartX;
        lastX = wantLastX;
    }
}
public class InventoryBase
{
    public List<ItemContain> itemList = new List<ItemContain>();
    public int inventorySizeX;
    public int inventorySizeY;
    
    public bool ItemPlacementFinder(int wantSizeX, int wantSizeY, out int returnLocationX, out int returnLocationY)
    {
        if(itemList.Count <= 0)
        {
            returnLocationX = 0;
            returnLocationY = 0;
            return true;
        }
        else
        {
            int currentFindX;
            int ignoreIndex = 0;
            List<XFinder> finderList = new List<XFinder>();
            List<int> heightList = new List<int>();
            heightList.Add(0);

            for(int heightIndex = 0; heightIndex < heightList.Count; ++heightIndex)
            {
                if (heightList[heightIndex] + wantSizeY > inventorySizeY)
                {
                    returnLocationX = 0;
                    returnLocationY = 0;
                    return false;
                };

                currentFindX = 0;

                int targetLastY;

                for (int i = ignoreIndex; i < itemList.Count; ++i)
                {
                    if (itemList[i].GetLocationY() == heightList[heightIndex])
                    {
                        targetLastY = itemList[i].GetLocationY() + itemList[i].GetSizeY();

                        HeightSave(heightList, heightIndex, targetLastY);

                        if ((itemList[i].GetLocationX() - currentFindX) >= wantSizeX)
                        {
                            finderList.Add(new XFinder(currentFindX, itemList[i].GetLocationX()));
                        };
                        currentFindX = itemList[i].GetLocationX() + itemList[i].GetSizeX();
                        ignoreIndex = i;
                    }
                    else if (itemList[i].GetLocationY() > heightList[heightIndex])
                    {
                        HeightSave(heightList, heightIndex, itemList[i].GetLocationY());
                        break;
                    };
                };
                if ((inventorySizeX - currentFindX) >= wantSizeX)
                {
                    finderList.Add(new XFinder(currentFindX, inventorySizeX));
                };

                bool leftPass;
                bool rightPass;
                for (int i = 0; i < itemList.Count; ++i)
                {
                    if (itemList[i].GetLocationY() < heightList[heightIndex] + wantSizeY)
                    {
                        if (itemList[i].GetLocationY() + itemList[i].GetSizeY() > heightList[heightIndex])
                        {
                            for (int j = 0; j < finderList.Count; ++j)
                            {
                                if (itemList[i].GetLocationX() + itemList[i].GetSizeX() >= finderList[j].startX && itemList[i].GetLocationX() <= finderList[j].lastX)
                                {
                                    leftPass = (itemList[i].GetLocationX() - finderList[j].startX) >= wantSizeX;
                                    rightPass = (finderList[j].lastX - (itemList[i].GetLocationX() + itemList[i].GetSizeX())) >= wantSizeX;

                                    if (rightPass)
                                    {
                                        if (leftPass)
                                        {
                                            finderList.Insert(j + 1, new XFinder(itemList[i].GetLocationX() + itemList[i].GetSizeX(), finderList[j].lastX));
                                            finderList[j].lastX = itemList[i].GetLocationX();
                                        }
                                        else
                                        {
                                            finderList[j].startX = itemList[i].GetLocationX() + itemList[i].GetSizeX();
                                        };
                                    }
                                    else
                                    {
                                        if (leftPass)
                                        {
                                            finderList[j].lastX = itemList[i].GetLocationX();
                                        }
                                        else
                                        {
                                            finderList.RemoveAt(j);
                                        };
                                    };
                                };
                            };
                        };
                    }
                    else
                    {
                        break;
                    };
                };

                if (finderList.Count > 0)
                {
                    returnLocationX = finderList[0].startX;
                    returnLocationY = heightList[heightIndex];
                    return true;
                };
            };
        };
        returnLocationX = 0;
        returnLocationY = 0;
        return false;
    }
    
    public bool ItemPlacement(ItemContain wantItem, int wantX, int wantY)
    {
        int touchItemIndex;

        if (ItemCollision(wantX,wantY,wantItem.GetSizeX(),wantItem.GetSizeY(),out touchItemIndex) > 0)
        {
            ItemContain itemCheck = itemList[touchItemIndex];

            if (itemCheck != null && itemCheck.ItemCheck(wantItem.GetItemInfo()))
            {
                wantItem.SetItemStack(itemCheck.ItemStack(wantItem.GetItemStack()));
                
                if(wantItem.GetItemStack() <= 0)
                {
                    return true;
                }
                else
                {
                    return false;
                };
            }
            else
            {
                return false;
            };
        }
        else
        {
            if (wantY + wantItem.GetSizeY() > inventorySizeY || wantX + wantItem.GetSizeX() > inventorySizeX)
            {
                return false;
            }
            else
            {
                ItemInsertList(wantItem, wantX, wantY);
                wantItem.SetLocation(wantX, wantY);
                return true;
            };
        };
    }
    
    public int ItemStackCheck(ItemInfo wantItem)
    {
        int itemLeft = 0;

        for (int i = 0; i < itemList.Count; ++i)
        {
            if (itemList[i].ItemCheck(wantItem))
            {
                itemLeft += itemList[i].GetItemStack();
            };
        };

        return itemLeft;
    }
    
    public int ItemStack(ItemInfo wantItem, int wantStack)
    {
        int itemLeft = wantStack;
        for (int i = 0; i < itemList.Count; ++i)
        {
            if (itemList[i].ItemCheck(wantItem))
            {
                itemLeft = itemList[i].ItemStack(itemLeft);
                if (itemLeft <= 0)
                {
                    return 0;
                };
            };
        };

        return itemLeft;
    }
    
    public int ItemDestack(ItemInfo wantItem, int wantStack)
    {
        int itemLeft = wantStack;
        int itemNumberChecker;
        for(int i = itemList.Count -1; i >= 0; --i)
        {
            if (itemList[i].ItemCheck(wantItem))
            {
                itemNumberChecker = itemList[i].ItemDestack(itemLeft);
                if (itemNumberChecker <= 0)
                {
                    itemLeft = Math.Abs(itemNumberChecker);
                    ItemRemoveList(i);
                }
                else
                {
                    return 0;
                };

                if (itemLeft <= 0)
                {
                    return 0;
                };
            };
        };
        return itemLeft;
    }
    
    public bool ItemInsertList(ItemContain wantItem, int wantX, int wantY)
    {
        int targetIndex = 0;

        int targetLocationX;
        int targetLocationY;

        for(int i = 0; i < itemList.Count; ++i)
        {
            targetLocationY = itemList[i].GetLocationY();
            if(wantY == targetLocationY)
            {
                targetLocationX = itemList[i].GetLocationX();
                if(wantX < targetLocationX)
                {
                    targetIndex = i;
                    break;
                }
                else if(wantX > targetLocationX)
                {
                    targetIndex = i + 1;
                }
                else
                {
                    return false;
                };
            }
            else if (wantY < targetLocationY)
            {
                targetIndex = i;
                break;
            }
            else
            {
                targetIndex = i + 1;
            };
        };

        if(targetIndex >= itemList.Count)
        {
            itemList.Add(wantItem);
        }
        else
        {
            itemList.Insert(targetIndex, wantItem);
        };

        return true;
    }
    
    public ItemContain ItemRemoveList(int wantIndex)
    {
        ItemContain resultItem = itemList[wantIndex];

        itemList.RemoveAt(wantIndex);

        return resultItem;
    }

    
    public void ItemRemoveList(ItemInfo wantItem)
    {
        for (int i = 0; i < itemList.Count; ++i)
        {
            if (itemList[i].ItemCheck(wantItem))
            {
                ItemRemoveList(i);
            };
        };
    }
    
    public int ItemCollision(int wantX, int wantY, int wantSizeX, int wantSizeY, out int firstTouch)
    {
        if(wantY + wantSizeY > inventorySizeY)
        {
            firstTouch = -4;
            return -1024;
        };
        int itemTouch = 0;
        firstTouch = -4;

        for(int i = 0; i < itemList.Count; ++i)
        {
            if (itemList[i].ItemOverlap(wantX, wantY, wantSizeX, wantSizeY))
            {
                ++itemTouch;
                if(firstTouch == -4)
                {
                    firstTouch = i;
                };
            };
        };

        return itemTouch;
    }
    
    public ItemContain ItemFind(int wantX, int wantY)
    {
        for (int i = 0; i < itemList.Count; ++i)
        {
            if (itemList[i].ItemOverlap(wantX, wantY))
            {
                return itemList[i];
            };
        };

        return null;
    }
    
    public ItemContain ItemFind(int wantX, int wantY, out int returnIndex)
    {
        for (int i = 0; i < itemList.Count; ++i)
        {
            if (itemList[i].ItemOverlap(wantX, wantY))
            {
                returnIndex = i;
                return itemList[i];
            };
        };

        returnIndex = -4;
        return null;
    }

    public void HeightSave(List<int> heightList, int findStartIndex, int targetY)
    {
        for (int j = findStartIndex; j < heightList.Count; ++j)
        {
            if (targetY == heightList[j])
            {
                return;
            }
            else if (targetY < heightList[j])
            {
                heightList.Insert(j, targetY);
                return;
            };
        };

        heightList.Add(targetY);
    }
}
public class Inventory
{
    public InventoryBase currentBase = new InventoryBase();
    public ItemContain itemGrab;

    public int ItemGet(ItemInfo wantItem, int wantStack)
    {
        int itemLeft = wantStack;

        if (wantItem.stackMax > 1)
        {
            itemLeft = currentBase.ItemStack(wantItem, wantStack);
        };

        int targetLocationX;
        int targetLocationY;

        while(itemLeft > 0)
        {
            if (currentBase.ItemPlacementFinder(wantItem.sizeX, wantItem.sizeY, out targetLocationX, out targetLocationY))
            {
                currentBase.ItemPlacement(new ItemContain(Math.Min(itemLeft, wantItem.stackMax), wantItem), targetLocationX, targetLocationY);
                itemLeft -= wantItem.stackMax;
            }
            else if(itemGrab == null)
            {
                itemGrab = new ItemContain(0, wantItem);
                itemLeft = itemGrab.ItemStack(itemLeft);
            }
            else
            {
                return itemLeft;
            };
        };

        return 0;
    }

    public void ItemRemove(ItemInfo wantItem, int wantStack)
    {
        int stackLeft = wantStack;

        if (itemGrab.ItemCheck(wantItem))
        {
            itemGrab.ItemDestack(stackLeft);

            if(itemGrab.GetItemStack() < 0)
            {
                stackLeft = Math.Abs(itemGrab.GetItemStack());
                itemGrab = null;
            }
            else
            {
                return;
            };
        };

        currentBase.ItemDestack(wantItem, stackLeft);
    }

    public void ItemRemove(ItemInfo wantItem)
    {
        if (itemGrab.ItemCheck(wantItem))
        {
            itemGrab = null;
        };

        currentBase.ItemRemoveList(wantItem);
    }

    public int ItemStackCheck(ItemInfo wantItem)
    {
        int returnValue = currentBase.ItemStackCheck(wantItem);

        if (itemGrab.ItemCheck(wantItem))
        {
            returnValue += itemGrab.GetItemStack();
        };

        return returnValue;
    }

    public ItemContain ItemThrow()
    {
        ItemContain returnItem = itemGrab;
        itemGrab = null;
        return returnItem;
    }

    public void ItemUngrab()
    {
        if (itemGrab != null && currentBase.ItemPlacement(itemGrab, itemGrab.GetLocationX(), itemGrab.GetLocationY()))
        {
            itemGrab = null;
        };
    }

    public ItemContain ItemInfo(int wantX, int wantY)
    {
        return currentBase.ItemFind(wantX, wantY);
    }

    public void ItemClickLeft(int wantX, int wantY)
    {
        if (itemGrab != null)
        {
            if (currentBase.ItemPlacement(itemGrab, wantX, wantY))
            {
                itemGrab = null;
            }
            else
            {
                int touchItemIndex;
                if (currentBase.ItemCollision(wantX, wantY, itemGrab.GetSizeX(), itemGrab.GetSizeY(), out touchItemIndex) <= 1)
                {
                    if (currentBase.itemList[touchItemIndex].ItemCheck(itemGrab.GetItemInfo()))
                    {
                        if(currentBase.itemList[touchItemIndex].GetItemStack() >= itemGrab.GetItemInfo().stackMax)
                        {
                            ItemContain targetItem = currentBase.ItemRemoveList(touchItemIndex);

                            if (currentBase.ItemPlacement(itemGrab, wantX, wantY))
                            {
                                itemGrab = targetItem;
                            }
                            else
                            {
                                currentBase.ItemInsertList(targetItem, targetItem.GetLocationX(), targetItem.GetLocationY());
                            };
                        }
                        else
                        {
                            itemGrab.SetItemStack(currentBase.itemList[touchItemIndex].ItemStack(itemGrab.GetItemStack()));
                        };
                    }
                    else
                    {
                        ItemContain targetItem = currentBase.ItemRemoveList(touchItemIndex);

                        if (currentBase.ItemPlacement(itemGrab, wantX, wantY))
                        {
                            itemGrab = targetItem;
                        }
                        else
                        {
                            currentBase.ItemInsertList(targetItem, targetItem.GetLocationX(), targetItem.GetLocationY());
                        };
                    };
                };
            };
        }
        else
        {
            int targetIndex;
            ItemContain targetContain = currentBase.ItemFind(wantX, wantY, out targetIndex);

            if (targetContain != null)
            {
                itemGrab = targetContain;
                currentBase.ItemRemoveList(targetIndex);
            };
        };
    }

    public void ItemClickRight(int wantX, int wantY)
    {
        if(itemGrab != null)
        {
            if (currentBase.ItemPlacement(itemGrab.ItemSplit(1), wantX, wantY)) 
            {
                if (itemGrab.GetItemStack() <= 0)
                {
                    itemGrab = null;
                };
            }
            else
            {
                itemGrab.ItemStack(1);
            };
        }
        else
        {
            int targetIndex;
            ItemContain targetContain = currentBase.ItemFind(wantX, wantY, out targetIndex);

            if (targetContain != null)
            {
                if(targetContain.GetItemStack() > 1)
                {
                    itemGrab = targetContain.ItemSplit((int)Math.Floor(targetContain.GetItemStack() / 2.0f));
                }
                else
                {
                    itemGrab = targetContain;
                    currentBase.ItemRemoveList(targetIndex);
                };
            };
        };
    }
}

'부품 설계도' 카테고리의 다른 글

[C#] 대화창 전체 코드  (0) 2021.01.30
[C#]Bit_Builder 전체 코드  (0) 2020.11.15

 

 

[C#] Int를 비트단위로 저장해주는 클래스

안녕하십니까 밤말팅입니다. 블로그를 열고 첫 포스팅인데요, 앞으로 게임 개발에 도움이 될 여러 가지 클래스를 구상하고 제작하는 대로 포스팅 할 예정입니다. 내용이 괜찮다고 생각하시면

game-part-factory.tistory.com

 

이 글은 위에서 설명하는 클래스의 전체 코드입니다!

 

내용이 궁금하시면 해당 포스팅을 참고해주시면 감사드리겠습니다~

 

public enum Bit_Type
{
	FLOAT,
	BOOL
}

public class Bit_Builder
{
  private Bit_Type[] containTypeArray;
  private byte[] containByteArray;
  private int[] locationBitArray;

  public int Length { get { return containTypeArray.Length; } }

  public object this[int targetIndex]
  {
    get
    {
      if(targetIndex > containTypeArray.Length)
      {
          return null;
      };

      if (containTypeArray[targetIndex] == Bit_Type.BOOL)
      {
          return GetBool(targetIndex);
      }
      else if (containTypeArray[targetIndex] == Bit_Type.FLOAT)
      {
          return BitConverter.ToSingle(GetByte(targetIndex), 0);
      }
      else
      {
          return BitConverter.ToInt32(GetByte(targetIndex), 0);
      };
    }

    set
    {
      if(targetIndex > containTypeArray.Length)
      {
          return;
      };

      if (containTypeArray[targetIndex] == Bit_Type.BOOL)
      {
          SetBool(targetIndex, (bool)value);
      }
      else
      {
        Type valueType = value.GetType();
        byte[] wantByte = new byte[0];

        if (valueType == typeof(float))
        {
          wantByte = BitConverter.GetBytes((float)value);
        }
        else
        {
          wantByte = BitConverter.GetBytes((int)value);
        };

        if(wantByte.Length > 0)
        {
          SetByte(targetIndex, wantByte);
        };
      };
    }
  }

  public Bit_Builder(Bit_Type[] wantTypes)
  {
    int bitLength = 0;

    containTypeArray = wantTypes;
    locationBitArray = new int[wantTypes.Length];

    for (int i = 0; i < containTypeArray.Length; ++i)
    {
      if (containTypeArray[i] > (Bit_Type)32)
      {
      	containTypeArray[i] = (Bit_Type)32;
      };

      locationBitArray[i] = bitLength;
      bitLength += TypeLength(containTypeArray[i]);
    };
    containByteArray = new byte[(int)Math.Ceiling(bitLength / 8.0d)];
  }

  private static int TypeLength(Bit_Type wantType)
  {
    if(wantType == Bit_Type.FLOAT)
    {
    	return 32;
    }
    else
    {
    	return (int)wantType;
    };
  }

  private void SetBool(int targetIndex, bool value)
  {
    int bitLocation = locationBitArray[targetIndex] % 8;
    int byteLocation = locationBitArray[targetIndex] >> 3;

    if (value)
    {
    	containByteArray[byteLocation] |= (byte)(0x80 >> bitLocation);
    }
    else
    {
    	containByteArray[byteLocation] &= (byte)~(0x80 >> bitLocation);
    };
  }

  private bool GetBool(int targetIndex)
  {
    int bitLocation = locationBitArray[targetIndex] % 8;
    byte targetByte = containByteArray[locationBitArray[targetIndex] >> 3];

    return (targetByte & (0x80 >> bitLocation)) > 0;
  }

  private void SetByte(int targetIndex, byte[] wantByte)
  {
    int bitLocation = locationBitArray[targetIndex] % 8;
    int byteLocation = locationBitArray[targetIndex] >> 3;
    int bitEnd = bitLocation + TypeLength(containTypeArray[targetIndex]);
    int byteEnd = (locationBitArray[targetIndex] + TypeLength(containTypeArray[targetIndex])) >> 3;
    int wholeByte = TypeLength(containTypeArray[targetIndex]) >> 3;
    int leftBit = TypeLength(containTypeArray[targetIndex]) % 8;
    int lastBit = leftBit + bitLocation;

    if (byteEnd > containByteArray.Length)
    {
    	return;
    };

    if (1 < TypeLength(containTypeArray[targetIndex]) && TypeLength(containTypeArray[targetIndex]) < 8)
    {
      if (bitEnd < 9)
      {
        int bitMask = (0xff >> bitLocation) ^ (0xff >> bitEnd);

        containByteArray[byteLocation] &= (byte)~bitMask;
        containByteArray[byteLocation] |= (byte)(bitMask & (wantByte[0] << (8 - bitEnd)));
        return;
      }
      else
      {
        int bitMask = (0xff >> bitLocation);

        containByteArray[byteLocation] &= (byte)~bitMask;
        containByteArray[byteLocation] |= (byte)(bitMask & wantByte[0]);

        bitMask = ~(0xff >> (bitEnd - 8));

        containByteArray[byteLocation + 1] &= (byte)~bitMask;
        containByteArray[byteLocation + 1] |= (byte)(bitMask & (wantByte[0] << (8 - TypeLength(containTypeArray[targetIndex]))));
      };
    }
    else
    {
      if (bitLocation == 0)
      {
        for (int i = 0; i < wholeByte; ++i)
        {
          containByteArray[byteLocation + i] = wantByte[i];
        };

        if(leftBit > 0)
        {
          containByteArray[byteLocation + wholeByte] &= (byte)~(0xff >> bitEnd % 8);
          containByteArray[byteLocation + wholeByte] |= (byte)(wantByte[wholeByte] << (8 - leftBit));
        };

      return;
      }
      else
      {
        int bitMask = 0xFF >> bitLocation;

        byte firstByte = (byte)(wantByte[0] & bitMask);
        byte lastByte = (byte)(wantByte[0] & ~bitMask);

        for (int i = 1; i < wholeByte; ++i)
        {
        	containByteArray[byteLocation + i] = wantByte[i];
        };

        containByteArray[byteLocation] &= (byte)~bitMask;
        containByteArray[byteLocation] |= firstByte;

        containByteArray[byteLocation + wholeByte] &= (byte)bitMask;
        containByteArray[byteLocation + wholeByte] |= lastByte;

        if(wholeByte < 4)
        {
          if (lastBit > 8)
          {
            containByteArray[byteLocation + wholeByte] &= (byte)~bitMask;
            containByteArray[byteLocation + wholeByte] |= (byte)(wantByte[wholeByte] & bitMask);

            bitMask = ~(0xff >> lastBit % 8);
            containByteArray[byteLocation + wholeByte + 1] &= (byte)~bitMask;
            containByteArray[byteLocation + wholeByte + 1] |= (byte)((wantByte[wholeByte] << (8 - leftBit)) & bitMask);
          }
          else if (leftBit > 0)
          {
            bitMask = ~(~bitMask | (0xff >> bitLocation + leftBit));

            containByteArray[byteLocation + wholeByte] &= (byte)~bitMask;
            containByteArray[byteLocation + wholeByte] |= (byte)((wantByte[wholeByte] << (8 - lastBit)) & bitMask);
          };
      	};

      return;
      };
    };
  }

  private byte[] GetByte(int targetIndex)
  {
    int bitLocation = locationBitArray[targetIndex] % 8;
    int byteLocation = locationBitArray[targetIndex] >> 3;
    int bitEnd = bitLocation + TypeLength(containTypeArray[targetIndex]);
    int byteEnd = (locationBitArray[targetIndex] + TypeLength(containTypeArray[targetIndex])) >> 3;
    int wholeByte = TypeLength(containTypeArray[targetIndex]) >> 3;
    int leftBit = TypeLength(containTypeArray[targetIndex]) % 8;
    int lastBit = leftBit + bitLocation;

    byte[] result = new byte[4];

    if (byteEnd > containByteArray.Length)
    {
    	return result;
    };

    if (1 < TypeLength(containTypeArray[targetIndex]) && TypeLength(containTypeArray[targetIndex]) < 8)
    {
      if (bitEnd < 9)
      {
        int bitMask = (0xff >> bitLocation) ^ (0xff >> bitEnd);

        result[0] = (byte)((containByteArray[byteLocation] & bitMask) >> (8 - bitEnd));
      }
      else
      {
        int bitMask = (0xff >> bitLocation);

        result[0] = (byte)(containByteArray[byteLocation] & bitMask);

        bitMask = ~(0xff >> (bitEnd - 8));

        result[0] |= (byte)((containByteArray[byteLocation + 1] & bitMask) >> (8 - TypeLength(containTypeArray[targetIndex])));
      };
    }
    else
    {
      if (bitLocation == 0)
      {
        for (int i = 0; i < wholeByte; ++i)
        {
          result[i] = containByteArray[byteLocation + i];
        };

        if (leftBit > 0)
        {
          result[wholeByte] = (byte)(containByteArray[byteLocation + wholeByte] & ~(0xff >> bitEnd % 8));
          result[wholeByte] = (byte)(result[wholeByte] >> (8 - leftBit));
        };
      }
      else
      {
        int bitMask = 0xFF >> bitLocation;

        result[0] = (byte)(containByteArray[byteLocation] & bitMask);
        result[0] |= (byte)(containByteArray[byteLocation + wholeByte] & ~bitMask);

        for (int i = 1; i < wholeByte; ++i)
        {
          result[i] = containByteArray[byteLocation + i];
        };
        if(wholeByte != 4)
        {
          if (lastBit > 8)
          {
            result[wholeByte] = (byte)(containByteArray[byteLocation + wholeByte] & bitMask);

            bitMask = ~(0xff >> lastBit % 8);
            result[wholeByte] |= (byte)((containByteArray[byteLocation + wholeByte + 1] & bitMask) >> (8 - leftBit));
          }
          else if(leftBit > 0)
          {
            bitMask = ~(~bitMask | (0xff >> bitLocation + leftBit));
            result[wholeByte] = (byte)((containByteArray[byteLocation + wholeByte] & bitMask) >> (8 - lastBit));
          };
        };				
      };
    };

    if(TypeLength(containTypeArray[targetIndex]) % 8 == 0)
    {
      if (wholeByte <= result.Length && (result[wholeByte - 1] & (0x80)) > 0)
      {
        for (int i = 3; i>=wholeByte; --i)
        {
        	result[i] = 0xff;
        };
      };
    }
    else
    {
      if (wholeByte < result.Length && (result[wholeByte] & (0x01 << leftBit - 1)) > 0)
      {
        for (int i = 3; i > wholeByte; --i)
        {
        	result[i] = 0xff;
        };
        result[wholeByte] |= (byte)(0xff << leftBit);
      };
    };

    return result;
  }

  public bool SetByteArray(byte[] wantArray)
  {
    if (wantArray.Length == containByteArray.Length)
    {
    	containByteArray = wantArray;
    	return true;
    }
    else
    {
    	return false;
    };
  }

  public byte[] GetByteArray()
  {
  	return containByteArray;
  }
}

'부품 설계도' 카테고리의 다른 글

[C#] 대화창 전체 코드  (0) 2021.01.30
[C#] 디아블로 스타일 인벤토리 전체 코드  (0) 2020.12.27

+ Recent posts