Can I write up code and sell my game with my code in it legally.Without being sued for accidentlly coping somebodies code,
If your code is your own, and you’ve not copied it from anywhere, then yes.
Short answer
You won’t be sued for accidentally duplicating code if you write it independently. You will be in trouble if you set out to deliberately reproduce someone else’s game. Or if your code is written by decompiling another game and rebuilding the code.
Long answer
Copy right is typically for creative assets. You can’t rip somebody else’s graphics and throw them in your game and expect to get away with it. You can independently create your own graphics and use them. You can’t set out to create a duplicate of another game. Titles, logos and so forth are other no go areas.
Technical inventions, such as code, are covered by patents rather then copyright. Many countries do no allow code to be patented, unless it is part of a machine. So you have free reign to build whatever you like. Again setting out to duplicate another game is a bad idea. Blatant copying of other peoples code is a bad idea.
And of course none of this is legal advice. If you actually make enough money off a game that someone actually considers suing you then you can hire a lawyer to worry about it.