r/badcode • u/averylazytom • Nov 20 '21
c++ Probably not my best way for checking if there are 3 equal cells in a 3 x 3 tictactoe game.
326
Upvotes
r/badcode • u/averylazytom • Nov 20 '21
28
u/averylazytom Nov 20 '21 edited Nov 20 '21
Full file: https://github.com/anythingtom/small-ncurses-games/blob/main/tic/src/tic.cpp
If you don't want to read the full file, this is the context:
'pl' is a int refering to who wins. (I can't choose booleans due to the value having 3 states).
check_winner() is a function that takes 3 characters and returns 1 if they are all equal to 'X', and 2 if they are all equal to 'O'. It returns 0 otherwise.
All help is appreciated! I am a beginner, and there MUST be a better way, but I couldn't figure it out.
6
u/GKP_light Nov 20 '21
"Probably not my best way for checking if there are 3 equal cells in a 3 x 3 tictactoe game."
no, test the 8 victory conditions is the easiest way.
mush easier than do boucles that will test only 3 things.
7
u/jzaprint Nov 20 '21
I mean that’s actually a good/best(?) way to check winners in tic tax toe haha
45
u/MurdoMaclachlan public boolean isInt(int i) { return true; } Nov 20 '21
Image Transcription: Code
[Thanks to OP for providing a link to the source in this comment. I have also placed it here for ease of access, and to highlight exactly which part of the file is shown in the image.]
I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!
35
u/aeropl3b Nov 20 '21
I mean, this is kind of verbose, but really not that bad. The biggest update I would make is to use a column or row major ordering instead of a pair of ints.
Row Major ordering is RowIndex * NumberOfColums + ColumnIndex
There are a bunch of advantages to this, mainly around minimizing memory overhead.
6
u/RedditAcc-92975 Nov 20 '21
username checks out
3
u/XPost3000 Nov 20 '21
Taking this from another comment I made:
Not sure if it's the most efficient, but the way I did it was to loop through all rows, check if each element is the same and not empty, and then return whatever element "won"
And then do this for the columns and diagonals, too
1
u/ring_dinkster Dec 02 '21
I made this monster of a code chunk in python for a tic tac toe project I did.
Context: boardValues is a 2-dimensional array that contains shapes located on each tile of the board. This can either be a cross or a circle. Shape is either a cross or a circle, depends for which shape its checking if it has won. boardwith and boardheight are the dimensions of the board that the game is played on. This means that I could make the tic tac toe board as big as I want (even though I didn't do any of that when making this)