r/cpp_questions • • 3d ago

OPEN I understand c++ syntaxes, but I still can't code

I've watched multiple yt tutorials on coding in c++, and for the syntaxes I understand it; I understand things like variables, pointers, header files, syntaxes like cin and cout.

However, I still struggle to know how to code in general. I wanted to code a game on snake, yes the one many used to play on a nokia, but I find myself confused and unfamiliar with what to write.

I don't want to use AI, not even for helping me. So can someone explain to me how you dealt with the issue

2 Upvotes

80 comments sorted by

19

u/chakani 3d ago

Start with something simple. Just sit down and write code. Compile, run, test. Try new stuff. Be patient and tenacious.

8

u/TimelyTraffic8003 3d ago

In particular, console-based applications. Once OP gets some practice (especially with the compiler), then it would be a better time to start learning how to use external libraries such as the ones useful for making games.

1

u/Xasozine 2d ago

For the snake game, I just made an array to hold all the places the player will be at, and made a struct for Vector 2D
and that's about it, I don't know where to go next

2

u/Appomatox 2d ago

If youโ€™re referring to the Snake Game where you control the snake in real time, that may be a bit ambitious, I recommend Tic-Tac-Toe for starters. Prompt the user for his/her move, go for the corners, display the board after every turn.ย 

1

u/Xasozine 2d ago

I did code tic-tac-toe previously, however I hit a road block when I tried to code the bot that'll play against the player, so I left this project temporarily to code something easier, like snake; but even that I'm having issues with.

1

u/Appomatox 1d ago

Ok, what about a simple guessing game: the program generates a number at random between 1 and 100. The player tries to guess it, the program tells him whether heโ€™s high or low.

1

u/Xasozine 1d ago

ok, I'd try that

1

u/Xasozine 1d ago

ok I did it, was easy tbh

See, I can code something like this easily because it doesn't include what I'm trying to challenge my self with

1

u/panoskj 9h ago edited 9h ago

About the tic-tac-toe, I can give you a couple of ideas.

First of all you have 9 cells, each cell can have one of 3 states (empty, X, O). This means there are 3^9 configurations (before filtering invalid, mirrored or rotated configurations). That's less than 20000 maximum configurations and if you can skip the invalid ones (constrain the number of X and O in the board) and count rotations and mirrors as duplicates, then the actual configurations are very few.

To put this in perspective, a CPU core can do BILLIONS of operations per second.

So what I'm trying to say here is you can definitely write a brute-force algorithm to solve this, to find the best possible move for every possible state. This would be a file of a few KBs or MBs in size that your game loads on startup to know every move.

Another idea I can give you on this is to try a genetic algorithm. This is like the simplest machine learning example you could probably do, I have tried this when I was in college and it worked.

To do this, first I converted the board state to a vector. Every cell corresponds to two values, let's say X, O. X and O can only be 0 or 1 and only one of them can be 1 at a time. So my vector for the board, let's call it B, looked like B = (X1, O1, X2, O2, X3, O3, ... X9, O9) - basically 18 bits.

The theory is, now that we have vector B with size 18, we can multiply it by a matrix M, sized 18x9 = 162 weights/parameters. This produces an output vector S (for solution) with size 9. Finally, you use S to find the largest value in it and say the AI wants to pick that cell. If the chosen cell is invalid move (because it is already taken), we count this as a loss (ie the AI that tries to make an illegal move loses its match immediately).

So when you have all these pieces, you would seed let's say 1000 matrixes M with random number (maybe it would help to limit these numbers to a range, let's say from -1 to 1) and set up like a tournament of those AIs playing against each other. You pick the best N AIs let's say 50 AIs (those with most wins and less losses). That is, you pick their matrixes M. You can then combine them or mutate them and run the next generation. If you do this for enough generations, eventually you will end up with a matrix M that never loses (always win or tie).

I think I trained for two matrixes M though, one for player X and another for O, so basically using 324 parameters instead of 162 as I said earlier. For each game, only one set of the parameters gets used, depending on whether it is X or O.

Well, I might have not explained everything perfectly but I'm sure if you got this far you will have your own ideas and figure it out. Both should be fun exercises if you can pull them off. Feel free to ask if you want more details.

PS: standard C++ does not really offer a way to draw GUIs, not even in a terminal. You can output lines, but you can't really clear the terminal without relying on some 3rd party code. I don't think snake can be rendered by only adding new lines. I suspect that's why you got stuck with the snake game - you need to learn about importing and using third party libraries for this. The ideas I gave you for tic-tac-toe only need standard C++ though.

7

u/the_poope 3d ago

Practice, practice, practice. Not for hours, not for days, not for months, but for years!

There's no cheat code or shortcut. You just need to put in waaaaay more time than you think.

1

u/Xasozine 2d ago

Snake here is my practice, however what I mean here is that Im hitting road blocks, with things like coding the movement logic and making the snake's tail follow.

I know and understand almost 50% of the C++ syntaxes, including how pointers work; yet Im still facing issues like this, where it feels like my time spent learning was utilizes wrongfully

2

u/the_poope 2d ago

It's ok searching for and looking at how other people solved the same problem. That's how you learn. The danger is just copying what others (including AI) do. You need to study and understand their solution.

At some point it becomes faster and more efficient to use the knowledge you already have than looking up the solution.

1

u/Xasozine 2d ago

Ok, I still fear not finding a fix for a specific issue, but good point you have

1

u/Dazzling_Music_2411 8h ago

It's important to realize that "knowing the syntax" does not help you at all in programming! This is a common misconception.

Let me put it this way: I know exactly how chess pieces move. I know this by heart, I never have to look at a book or ask chatGTP. I could show you how it works blindfolded, or even in my sleep.

Yet I could not play a game of chess to save my life. A four year old could beat me without really trying. This is because I never learnt to play chess, was never interested in it, and it's really not my game.

So there you have it: The "syntax" is how the pieces move. The "programming" is the strategies of the game. Do not confuse the two, it's a basic error.

===

How is your project going? I understand you have made a blank board, have you managed to place the snake on it and move it yet?

3

u/smozoma 3d ago

Start with text-based programs. A Snake game is jumping in too far.

Try starting with Tic-Tac-Toe. cout (or one of the newer print commands) to draw the board and alternate asking the X and O players to enter a row and a column.

Also, I don't think youtube videos are the best way to learn programming... Try reading, like https://learncpp.com.

1

u/Xasozine 2d ago

I did code Tic-Tac-Toe previously; However, I didn't know how to code the bot for the game so I kind of left the project for an easier one, like Snake.

But even that I have issues with

1

u/smozoma 1d ago

Snake is hard! You'd want to use some kind of game library, and it would have its own game loop convention you'd learn and follow, in order to get the redrawing.

I threw this into google: "how to make a portable console ascii graphics game in c++ "

The result was

To make a portable ASCII graphics game in C++, the best approach is to use a cross-platform terminal library like ncurses/PDCurses or a modern library like FTXUI, rather than relying on standard C++ alone. Standard C++ (<iostream>) has no built-in way to move the cursor, read single keypresses without pressing Enter, or color text across different operating systems.

SDL2 / SFML is also often mentioned for 2d games

1

u/Xasozine 1d ago

also learncpp.com is way to slow paced, I dont want to learn the difference between "\n" and std::endl;

1

u/smozoma 1d ago

If you know a part, skip ahead. Websites are much better for that than videos IMO. You can go at your own pace and skim over the stuff that looks familiar and find the interesting stuff.

3

u/i_am_someone_or_am_i 3d ago

You shouldn't jump from watching tutorials on youtube to write snake. Write more simple projects first

1

u/Xasozine 2d ago

I previously wrote tic tac toe, but got stuck at coding the bot for the game, so I abandoned this project.

I shifted my focus to an easier project like snake, where I won't have to code bots

but even that I'm still having issues with

1

u/i_am_someone_or_am_i 2d ago

Snake is far more complex than tic tac toe. "Bots" aren't something you should be bothered with as a starter tho.

1

u/Xasozine 2d ago

but who will the player play against,

so far, my game has you pick a No. between 1-9, and places an X depending on the No.

Now the next step is to add a rival to play against

1

u/i_am_someone_or_am_i 1d ago

Dont think too much about how good the programs you do, focus on developing yourself. You can make a simple algorithm and predictable algorithm to play against or let the other side be a human and input from the sameway the first player does.

1

u/Xasozine 1d ago

"You can make a simple algorithm and predictable algorithm to play against"

How? I don't have any idea where to begin

1

u/i_am_someone_or_am_i 1d ago

Dont think too complex, create a scheme of what you expect the algorithm to do. If it starts do this, if player does that do this etc... or just move on to the different project if this feels too tedious.

1

u/Xasozine 1d ago

I made a guessing game, where you have to guess a number between 0-10 as someone recommended.

also if I "If it starts do this, if player does that do this etc." there will be soo many if statments

1

u/i_am_someone_or_am_i 1d ago

Yeah it'll be tedious.

There are other ways to do algorithms but you should look them yourself as there are many and i am not sure which one fits best.

2

u/imradzi 1d ago

programming is not about knowing the syntax, but knowing the problem and what's the step to make it work. As for the snake game, it's knowing how it work, what kind of data you have to maintain, how it is presented on screen and the handling user input and responses.

0

u/Xasozine 1d ago

I know that, I remember someone told me that.

The main issue Im facing tho is doing the problem solving. And this doesn't just apply to snake, but my other projects in general

1

u/tyler1128 16h ago edited 16h ago

Just write code. Even if it seems like something trivial. You cannot learn to program without doing it. Write a program that takes two inputs and adds them. It doesn't have to be fancy.

Eventually, you will develop an intuition of how to solve problems, and figure out how to find information about how to solve them when you don't; understanding is more important than the answer.It has to be active, not passive.

24

u/Draynrha 3d ago

Despite looking simple, snake is a good challenge for beginners because it requires different systems to make the game. I'd say before coding, you need to have an understanding of your goal. And then you need to break it into steps.

Before doing snake, a more simple game to tackle is Guess the Number. The goal is simple: the code generates a random-ish number between 1-1000 and your goal is to guess it using the least amount of attempts. Each time you guess, the code tells you if the number is greater or smaller than your guess until you reach the correct number.

Even this smaller game requires you to keep track of multiple elements like the number to guess, the number of attempts made and it makes use of some kind of logic to determine if the user inputs are valid guesses.

2

u/drbitboy 3d ago

Start with your data model.

Tl;DR

Unless you are writing device drivers, your computer programs modify bits in memory, and those bits in memory are a model of something in the real world, or in a virtual world in the case of a game. Programs do not talk directly to hardware, measure electrical signals, or anything like that.

So the first step of writing any computer program is designing the data model I.e. where the bits are that the program will modify.

If I remember snake, it comprises a 2D Cartesian grid of discrete locations, and every location has a state: open; a piece of the snake; the next kibble to be consumed. Also, each piece of the snake needs to know where the adjacent piece(s) of the snake are, so the new head location after the next move can be added to the previous head, and the tail location can be cleared an the tail updated.

What data C++ structures or classes can be used to model that grid and the pieces of the snake in the game's "world?"

Once you have your data model, writing the code to manipulate those data is easier; in some cases it all but writes itself.

Also, keep an agile mindset, and don't be reluctant to refractor the data model (and the code) when you need to model new states or behavior you did not think of originally.

1

u/drbitboy 3d ago

P.S. make sure your "newKibbleLocation" function algorithm is not trying random grid locations until it finds one not occupied by the snake, because that would put the logic into an infinite loop if the snake has "eaten" the kibble in the last location and the snake's body takes up all the locations.

Don't ask how I know ๐Ÿคฃ.

1

u/Xasozine 2d ago

I was going to just that, thanks for pointing it out

7

u/FlailingDuck 3d ago

Coding is problem solving. Learning syntax is memorization. Entirely different things.

Often I think people struggle, because they bite off more than they can chew. If you don't know how to make snake, then you're probably biting too much.

Can you make, tic-tac-toe? How would you go about it. Think about how you play it on paper. If you had squared paper, how would you draw the tic-tac-toe board. On the lines, between the boxes (or cells).

How many cells do you need? 9.

In a particular arrangement? 3x3. What C++ things have I learnt about that can make a number of cells in a 2d grid 3 by 3.

What can be in each cell? empty, X or O. How can I denote that.

If I have that "data" of a 3x3 grid. How can I display it? On the console. Maybe I can just print it. Maybe I can clear the screen betwee each print.

How do I select the next cell? Can a cell be in 'selecting' mode. Can keyboard keys move me between cells.

How do I place my mark in that cell.

How do I check for a win condition.

....

Each question needs new code to solve it.

Snake its probably a few levels more complex than just tic-tac-toe. But starting with something smaller, and the questions and answers to snake start to become familiar.

6

u/tangerinelion 3d ago

That's because programming isn't a syntax quiz, it's literally about understanding what needs to happen to accomplish what you want. Knowing the syntax for using a member function pointer doesn't help you understand how to traverse a DAG.

6

u/neppo95 3d ago • Bravo

Unironically I just had a discussion elsewhere where people tried to convince me writing code was the main part of an engineers job, I should point them here ;)

Knowing syntax, how a language works, being able to read it and even being able to write it is just a part of creating something. The biggest part (depending on what kind of software you create) is in the work before that first line of code is created. Now we're talking snake here, not the apollo rocket, so it isn't that deep but the point stands. When you want to create something, even something relatively simple as snake, you have to ask yourself what you are making and how it works. What happens when you run your program? What do you see? What do you want it to do? If you lookup user stories, that's kind of what I'm aiming at here. Even something basic as snake has them, maybe they're in your head, on a notepad, or elsewhere, but they're somewhere. After you got that, try picking one of them and making just that one thing. To put this into an example for snake:

  • Snake grows every second
  • Snake moves in the last direction
  • Game over when snake hits edge
  • Game over when snake hits itself
  • etc

Now in this case going from basically zero, you'd probably have even simpler ones like "Draw snake". So how do you draw a snake? You need to know its position (x/y), so you need to store those somewhere. You need to know how big it is, so you need to store its size probably. Literally, building from the ground up thinking: What do I need to complete this one task.

Now you can do that as you go along in code, but like I said at the beginning, most work usually is before you write code. Take above example, you got its position, you got its size but hang on.... Why is the snake just a straight line? You stored its size, you stored its position, but you did not account for the fact that each point of the snake needs its own position stored and the size simply becomes the size of that group of elements. Were you to plan this out before you write code (which you probably wouldn't for a small project this size) then you would have probably caught that.

1

u/Toucan2000 3d ago

I know you said you don't want to use AI. If that's because you don't want it doing the work for you, I totally understand, but you can still use it to teach you. Check out this GitHub project Learn Harness

1

u/Xasozine 2d ago

I also don't want to use AI for the learning, I want to do it the old fashioned way of raw dogging documents or watching old yt tutorials to help me understand.

It's to help my brain work, even when I get the specific issues that I can't find a fix for online

2

u/alfps 3d ago

Reportedly Khan Academy has an AI specially designed as a teacher that doesn't do the student's work.

1

u/Toucan2000 1d ago

That's what I'm trying to say. I used to dig through stackoverflow posts for answers. Don't need to anymore. If there's something I learned from that labor, I'm not aware of it. I'm fine with not torturing myself, call me crazy.

1

u/ButterscotchNo670 3d ago

maybe you should watch a yt video about coding a snake

1

u/Xasozine 2d ago

I know that seems obvious, however I want to code it in my own vision or design.

What's the point of watching someone do it and copying him, that won't help me learn anything

1

u/ButterscotchNo670 2d ago

because you need to see how it works. i learned by following tutorials

1

u/dnult 3d ago

Start with a simple component of your game - perhaps a score keeper, or simple rules engine. Get it working and tested, then move on to the next thing.

It takes experience to be good, and experience comes from making mistakes. Starting simple makes it easy to recover and move on.

1

u/Xasozine 2d ago

I started with a struct to handle the pos of the snake on the x and y, then an array to render the space the snake will be on, consisting of a bunch of blank variables, kinda like: ' '.

My next step was rendering the player, no issue in that, I rendered the player as the character "W", now I want to make it move, that's where I hit a road block

1

u/SmokeMuch7356 3d ago

You learn how to write code by writing code. Programming is a skill, and like any other skill requires non-trivial amounts of practice.

Start small. Write toy programs that do one thing and one thing only - write a hardcoded greeting, compute a hardcoded output, etc.

Once you get that down, start adding inputs, play with different types.

Then add simple decisions (if/else, switch) and repetitions (for, while).

You just have to write a lot of code before it really starts to click.

1

u/Xasozine 2d ago

I get what you mean

My previous project was a game of tic tac toe, Once I got a board to properly render in the terminal, everything felt like it came automatically, I coded the ability for the player to give input and render the "X"s he gave on the board

Until, I got to the part to code the bot, where I just kind of hit a road block and I didn't know how I'll begin to code a bot that'll dynamically play depending on the player's previous decisions.

So I left the project, to code something simpler, like snake, where there's no coding of bots. but even that I have no idea how I'll code things like the snakes movement, make the snake bigger when he gains a point, and make the tail properly follow him

1

u/Dazzling_Music_2411 3d ago

What are you using for a GUI? Some graphical library like Qt or whatever, or are you using ncurses? O/S?

1

u/Xasozine 2d ago

no, I plan to make the snake a bunch of these "X" with "W" and "M" being the head and tail rendered in the terminal. I still don't really know how to render graphics, I plan to leave this be a project of its own, to render a triangle using OpenGL

1

u/Dazzling_Music_2411 2d ago

Oh. So do you plan to reprint the whole screen with every time-tick?

If so, wouldn't that be hugely messy?

Look into ncurses.

1

u/Xasozine 2d ago

its not really, the game is made ascii style in terminal, which isn't really messy

1

u/Dazzling_Music_2411 1d ago

Oh, great. So how do you update positions, if the snake moves upwards or backwards?

1

u/Dazzling_Music_2411 8h ago

Oh, I see, yes, terminals are easily fast enough these days to just keep redrawing the screen. A whole world away from what old-timers were used to! ๐Ÿ˜„
I tried it and even a pseudo-"60 fps" is achievable fairly neatly. Bit crude, but it works. You could graduate to ncurses later, when you've got the basics down pat.

How is you project going?

Have you started moving the snake around the board yet?

1

u/ButchDeanCA 3d ago

Firstly you need to understand this difference: memorizing is not understanding. You are memorizing simple syntax that is exposed as such when you try to make something.

As others have said make something simple, you certainly are not ready to make games like Snake (I did that over 20 years ago and it is a challenge).

One step at a time.

1

u/Xasozine 2d ago

I previously coded tic tac toe, for the most part. I got stuck at coding the bot that'll rival the player, but I had no idea how to begin to code it; so I kind of abandoned that project at 83% completion.

I eventually decided to code something simpler like Snake, however even that I have some issues with knowing what I'll code to get my preferred result

do you have project suggestions?

2

u/Dazzling_Music_2411 2d ago

I eventually decided to code something simpler like Snake,

Ha-ha-ha. Snake is A LOT more complicated than a tic-tac-toe playing game, with an automated opponent. Go back and finish your "83%" completed game first. You have next to no chance otherwise.

And get a decent BOOK on writing games. Yes, BOOK. Remember them? 100x more useful than random video tutorials.

1

u/Xasozine 2d ago

book from where, in my area its difficult. also yes i didn't know how to code the bot because I want it to act dynamically depending on the players previous moves

1

u/manni66 3d ago

I've watched multiple yt tutorials

That's the problem. Use learncpp.com or a book, and do the exercises.

1

u/Xasozine 2d ago

I did follow with learncpp.com, but tbh I gave up cuz it was too many lessons for something that could be summed up in like 10 lessons

1

u/Dazzling_Music_2411 2d ago

Yes, but you still don't understand anything, and now you're giving lessons to learncpp.com how to do it better! ๐Ÿ˜‚ ๐Ÿ˜‚ ๐Ÿ˜‚

Go back and do the exercises, even if it takes you 100 lessons.

1

u/Xasozine 2d ago

I agree that my lack of knowledge is due to my lack of attent, however my main issue here is not understanding a syntax, but knowing how I can use it for my situation.

1

u/serafean 3d ago

how you dealt with the issue

First I drew a block on the screen, then I made it move by itself in a single direction, then I added directional controls, then I added collision with borders, then I added generation of goodies, then eating (collision + snake grow), then collision with self.

Divide & conquer the problem, that's what programming is.

1

u/Xasozine 2d ago

yes but I often hit road blocks, like so far I made the array and struct for vec2 positions, but movement and drawing the snake, Im stuck here

and it's not just for this lil learning project, this happens to me in general when I code something

1

u/ContraryConman 3d ago

Think about learning a natural language. It is possible to know a language well enough to understand it when it is spoken, while not really being able to speak yourself. Reading and writing are similar, where some people can read a language but can't write it, and both skills have nothing to do with speaking.

Programming languages are actual languages, so a lot of the same learning rules apply. There are actually multiple skills combined here:

  1. Algorithmic thinking: the ability to decompose a solution into a series of formal steps that solves a class of problem, regardless of which language you are writing in
  2. The ability to understand the syntax of a specific language
  3. The ability to write the syntax of a specific language

If you only have the middle skill and you haven't built the other two, you're not going to be able to program in C++. As you practice, it's not good enough to be able to understand, you need to push yourself to actually write more code. Is snake is too hard to write, pick something easier and go from there

1

u/Xasozine 2d ago

I have previously made the game tic tac toe, but I gave up coding the bot to play against because I didn't know what to do here.

Snake for me is the same, I wrote the array for the grid the snake will move on, consisting of empty characters ' ', and made a Vec2 struct for int x, y;. but for the features like movement or rendering the snake, I don't know where to go to next

1

u/ContraryConman 2d ago

If you're getting stuck on knowing what to do conceptually that means it's the first part you need to practice more. You need to be able to break problems down into algorithms that solve them independent of just knowing C++ specifically.

Like, you can't tell me you don't know how to play Tic Tac Toe, right? So the issue is not that you don't understand the game, but that you can't translate from the vague, informal, plain English description of the game into rigorous steps, or program, of what playing Tic Tac Toe actually looks like.

Something like leetcode could help I think. Not for interview prep. But to focus on the easy problems to build exactly this kind of skill

1

u/StickyDeltaStrike 3d ago

Make a snake game in ascii first in a terminal maybe?

1

u/Xasozine 2d ago

I'm doing just that, however I'm finding issues in the logic side of things, like coding the movement logic or making the tail properly follow the snake

1

u/StickyDeltaStrike 2d ago

Itโ€™s the programming part โ€ฆ learning to debug and fix bugs. Then refactor/fixing

1

u/Xasozine 2d ago

no no you don't get it, you see, I didnt even code the logic things because I have no idea how or what I'm supposed to do

1

u/StickyDeltaStrike 2d ago

Ah well I get it โ€ฆ just try โ€ฆ

1

u/Xasozine 2d ago

ok, I'll start with coding the spawning of the apple for the snake for example, take on the simpler tasks and move into the more complicated

1

u/StickyDeltaStrike 1d ago

Yea just put a breakpoint, hit it, look at the variables. Step over a bit and look at what happens?

1

u/Thin_Tradition8467 2d ago

https://youtu.be/AaGK-fj-BAM?si=hUHgedDThD5FnQJm

While i was learning coding C# unity. I often watch videos like these in my spare time. It helped me a lot to understand what you are looking for.

If you ask me, good coder is the one who knows arrays well. Snake is best practice for beginners.

1

u/Xasozine 2d ago

thank you, I'll watch it in my free time

and yes I did start with making an array and struct for the 2d vector positions

1

u/tcpukl 3d ago

Practice basics.

Like print out 10 numbers.

Then write the high low game guessing game.

Then it's algorithms.

0

u/ClockMoney4525 3d ago

?????

why dont you want to use AI

just ask it the questions you seek it will be way more efficient than on reddit

if you dont want it to give you code just say so and it wont

1

u/Xasozine 2d ago

because I find it lazy and not bound to the original way of reading for hours through a document.

I want to teach my mind to take the hard way, however my problem is finding very specific issues that I cant find an answer to