Programming Challenge 2.0 Reboot

Illusionz
Illusionz

Lets fucking do this.

All urls found in this thread:
https://github.com/mission712/analog-clock
haveahappyday
haveahappyday

@Illusionz

First for Ruby.

SomethingNew
SomethingNew

@haveahappyday

Oh GOOD LORD I aint doin' 07. Rolling again.

PackManBrainlure
PackManBrainlure

@SomethingNew
7 isn't actually hard, should only take you a weekend to make something decent

also rollan

Sharpcharm
Sharpcharm

I am semi-new to program development, please go easy on me

Skullbone
Skullbone

@Sharpcharm
I understand that but reloll

Burnblaze
Burnblaze

@Skullbone
I'm okay with this.

LuckyDusty
LuckyDusty

@PackManBrainlure
vigenere cipher in scheme


(define (vchar->integer c)
(- (char->integer c)
(char->integer #\a)))

(define (integer->vchar n)
(integer->char
(+ n (char->integer #\a))))

(define (table-lookup op textchar passchar)
(modulo (op (vchar->integer textchar)
(vchar->integer passchar))
26))

(define encrypt-op +)
(define decrypt-op -)

(define (string-ref-mod str n)
(string-ref str (modulo n (string-length str))))

(define (vigenere text passphrase op)
(define (iter i)
(cond
((< i (string-length text))
(if (eq? (string-ref text i) #\space)
(cons (vchar->integer #\space)
(iter (+ i 1)))

(cons (table-lookup op
(string-ref text i)
(string-ref-mod passphrase i))
(iter (+ i 1)))))

(else '())))

(list->string
(map integer->vchar
(iter 0))))

(define (encrypt text passphrase)
(vigenere text passphrase encrypt-op))

(define (decrypt text passphrase)
(vigenere text passphrase decrypt-op))

Nojokur
Nojokur

@Illusionz
Reverse a number mathematically (ie. 48572 -> 27584)
mathematically
I get the feeling whoever did this is a drooling retard, most of the challenges aren't even interesting at all.

Dreamworx
Dreamworx

Ray-Casting sounds like a breeze.

lostmypassword
lostmypassword

rolling

Poker_Star
Poker_Star

@Illusionz
Rollin'

Methnerd
Methnerd

rolling

TreeEater
TreeEater

@Nojokur

writing "mathematically" instead of "lexically" doesn't make you a drooling retard

w8t4u
w8t4u

@Illusionz
I finished this last night.

Carnalpleasure
Carnalpleasure

Rollan

Burnblaze
Burnblaze

roll

Evilember
Evilember

please dont bring roll threads to Leeky Forums

also roll

TalkBomber
TalkBomber

If you think you can do any of the challenges on that list, you shouldn't need an imageboard to generate random numbers.

SniperWish
SniperWish

@Evilember
@TalkBomber

I'm no fun and none of you must have any fun either because imageboards are SUPER serious business

RumChicken
RumChicken

For these examples, I'm guessing calling already made functions defeats the point?

New_Cliche
New_Cliche

@Illusionz
rolling in the deep

Ignoramus
Ignoramus

rolly

viagrandad
viagrandad

@Burnblaze
Aaaaaand done.

haveahappyday
haveahappyday

@viagrandad
fuk forgot link
https;//github.com/mission712/analog-clock
It ain't pretty but does the job.

SomethingNew
SomethingNew

@haveahappyday
https://github.com/mission712/analog-clock
I hate my keyboard.

lostmypassword
lostmypassword

@Evilember
Shit took me way too long


#!/usr/bin/python

date1 = "12.02.1995"
date2 = "13.03.1996"

split1 = date1.split(".")
split2 = date2.split(".")

d1 = int(split1[0])
d2 = int(split2[0])

m1 = int(split1[1])
m2 = int(split2[1])

y1 = int(split1[2])
y2 = int(split2[2])

days = 0

def getDaysInMonth(month):
if inBetweenMonth % 2 == 0:
return 30
else:
return 31

if y2 > y1:
for yearDifference in range (0, (y2 - y1)):
inBetweenYear = y1 + yearDifference
if not inBetweenYear == y2 - 1:
days += 365
else:
if not (m2 == m1 and d2 == d1):
inBetweenMonth = m1
while inBetweenMonth != m2:
if not inBetweenMonth == m2 - 1:
days += getDaysInMonth(inBetweenMonth)
if inBetweenMonth != 12:
inBetweenMonth += 1
else:
inBetweenMonth = 1
else:
if d2 > d1:
days += getDaysInMonth(inBetweenMonth)
if not d2 == d1:
inBetweenDay = d1
while not inBetweenDay == d2:
days += 1
if not inBetweenDay == getDaysInMonth(inBetweenMonth):
inBetweenDay += 1
else:
inBetweenDay = 1
break
else:
days += getDaysInMonth(inBetweenMonth)
break
days += 365

print(days)

Techpill
Techpill

@lostmypassword
if inBetweenMonth % 2 == 0:
Should me just month
Now how the fuck does this still work even though it's not called month?

Methshot
Methshot

@SomethingNew
Cool clock Ahmed

Methnerd
Methnerd

@Techpill
global variables.
Also you probably just pass the inBetweenMonth as month.

Carnalpleasure
Carnalpleasure

@Methnerd
python sure is confusing

Evilember
Evilember

@lostmypassword
Your getDaysInMonth is very incorrect. February has 28 days, and from August on, even months have 31 days and odd months 30.

Flameblow
Flameblow

@Evilember
that's the tolerance you have to calculate in

SniperGod
SniperGod

@Flameblow
5% tolerance

RavySnake
RavySnake

@Illusionz
Rollan

PurpleCharger
PurpleCharger

Roll #2 because I finished the analog clock and got nothing better to do.

BunnyJinx
BunnyJinx

@PurpleCharger
it is on.

Nojokur
Nojokur

@w8t4u
Using a library is cheating.

Raving_Cute
Raving_Cute

@Nojokur
He's including a local file, not a system file.

Boy_vs_Girl
Boy_vs_Girl

Yes, the difficulty levels are highly subjective.

@lostmypassword
You will love unix time (man 3 time).
Wanted to use time (the C functions), but Python doesn't let me use struct tm properly so I have to import program
#!/usr/bin/env python3
import datetime
from sys import argv, exit

def iso2t(s):
return datetime.datetime.strptime(s, "%Y-%m-%d")

try:
res = iso2t(argv[2]) - iso2t(argv[1])
print("%d" % res.days)
except (ValueError, IndexError):
exit("Input valid iso days fam")

Carnalpleasure
Carnalpleasure

@Boy_vs_Girl
Yes, the difficulty levels are highly subjective.
posts this

You are supposed to do it yourself. This is not programming, this is using system calls.

Snarelure
Snarelure

@Carnalpleasure

I was wondering if this thread was just about rapid prototyping or creating things from scratch. It seems like using libraries would be cheating. My task is making a string tokenizer atm, it would seem silly to just call in that exact pre-made function.

Emberburn
Emberburn

@Snarelure
I personally only code with productivity in mind if I'm workslaving or working on projects where I want the product to be done fast.

Feels weird to me to rely on things other people have coded when I want to do something for personal use. Doesn't feel like I made it.

TalkBomber
TalkBomber

@Boy_vs_Girl
it really is highly subjective, you can complete the same task in javascript if you're using datetime objects with one line of code

var daysBetween = (x, y) => (x-y)/864e5 | 0

WebTool
WebTool

@Illusionz
Rock'n'rollan

BlogWobbles
BlogWobbles

implying I have time to do this
implying I'm not working on another side project along with taking online CS courses
implying I don't have a full time job
Fuck it, rolling

LuckyDusty
LuckyDusty

@WebTool
#include <iostream>
#include <array>

int main(void)
{
std::string pre = { 32, 32, 32, 32, 32, 32, 32, 32, 34 };
char post = 34;
std::array<std::string, 18> code{
"#include <iostream>",
"#include <array>",
"",
"int main(void)",
"{",
" std::string pre = { 32, 32, 32, 32, 32, 32, 32, 32, 34 };",
" char post = 34;",
" std::array<std::string, 18> code{",
" };",
" for (unsigned i = 0; i < 8; ++i)",
" std::cout << code[i] << std::endl;",
" for (unsigned i = 0; i < code.size() - 1; ++i)",
" std::cout << pre << code[i] << post << ',' << std::endl;",
" std::cout << pre << code[code.size() - 1] << post << std::endl;",
" for (unsigned i = 8; i < code.size(); ++i)",
" std::cout << code[i] << std::endl;",
"}",
""
};
for (unsigned i = 0; i < 8; ++i)
std::cout << code[i] << std::endl;
for (unsigned i = 0; i < code.size() - 1; ++i)
std::cout << pre << code[i] << post << ',' << std::endl;
std::cout << pre << code[code.size() - 1] << post << std::endl;
for (unsigned i = 8; i < code.size(); ++i)
std::cout << code[i] << std::endl;
}

Boom, C++14 quine motherfuckers.

StonedTime
StonedTime

@Illusionz
not liking a lot of those tasks, but what's Russian Roulette withou a bullet?

DeathDog
DeathDog

@Carnalpleasure
I just wanted to show the guy unix time. Should I have reimplemented time.h? Also, "main logic" in C:
#include <time.h>
#include <stdio.h>

#define SEC2DAY(x) (x) / 60 / 60 / 24

int main()
{
struct tm t0 = {0}, t1 = {0};

// 1995-02-12
t0.tm_year = 2014;
t0.tm_mon = 2;
t0.tm_mday = 12;

// 2015-03-12
t1.tm_year = 2015;
t1.tm_mon = 3;
t1.tm_mday = 12;

time_t t0_sec = mktime(&t0);
time_t t1_sec = mktime(&t1);

printf("%lu\n", SEC2DAY(t1_sec - t0_sec));

return 0;
}

AwesomeTucker
AwesomeTucker

@StonedTime
: /\ ( n -- triangle-n ) dup 1+ * 2/ ;

5 /\ . ( outputs: 15 )

one day this will post

JunkTop
JunkTop

@TalkBomber

Kids, this is why JavaScript is bad for you.

Supergrass
Supergrass

@TalkBomber
big arrow lambda
yet var instead of let
muh ES6
muh scoping

Lunatick
Lunatick

@Supergrass

it's one line of code, there's no difference between var and let without context

Boy_vs_Girl
Boy_vs_Girl

@DeathDog
// 1995-02-12
tm_year = 2014;
Shit. Wrong comments are worse than no comments.

hairygrape
hairygrape

@Illusionz
Rolling

TurtleCat
TurtleCat

@SomethingNew
C
ty
I can't really make anything yet, but I'll roll and add it to my todo list :^)

BlogWobbles
BlogWobbles

@TurtleCat
lol fuck that
reroll

Stupidasole
Stupidasole

@Illusionz
Let's roll

whereismyname
whereismyname

@hairygrape
not me but did it anyway

var sieve = x => {
let arr = Object.keys(new Uint8Array(x + 1)).map(Number).slice(2)
let s = arr => {
let t = arr.filter(x => x % arr[0] !== 0)
let car = arr.slice(0, 1)
if (t.length === 0) {
return car
} else {
return car.concat(s(t))
}
}
return s(arr)
}

viagrandad
viagrandad

Jimmy Rawlins

TalkBomber
TalkBomber

@w8t4u
Simple but effective.
sentences.txt:

I
I love
I hate you.
I fucking hate you.
You piece of shit.
I want to fucking kill you.
I want to rip out your balls and devour.
I fucked your mother and you don't regret it.
You are now transgender cis fag. Be happy oh wait.
You are a feminazi piece of shit.
Overall you make me want to fuck buns or someshit.
Faggot.
Sincerely, OP.

StonedTime
StonedTime

@TalkBomber
Fuck that's hard, roll.

Harmless_Venom
Harmless_Venom

rawl

King_Martha
King_Martha

@Harmless_Venom
rerol noway

Methshot
Methshot

@SomethingNew
I did that when I was 15.
On a VIC-20. (3.5kB RAM)
In BASIC.
In a CAVE.

Nojokur
Nojokur

@Methshot
Yea, it should be relatively straight forward... maybe just a bit tedious to do implement everything that's needed. Not bad for practice though.

Dreamworx
Dreamworx

Pleb rolling for green

w8t4u
w8t4u

ok

Inmate
Inmate

roll

Evilember
Evilember

@Illusionz
fizzbuzz me

Spazyfool
Spazyfool

how about something that isn't a Project Euler task

Need_TLC
Need_TLC

@w8t4u
Rate my code, Leeky Forums. I hope it's not too shit tbh, I'm going to have a exam in a couple hours on C++ too, so this was good practice.
/*Two-player tic-tac-toe brudder*/
#include <iostream>
#include <string>
using namespace std;

/*Function prototypes*/
void printBoard (char xo[9]);
bool checkBoard (int, char xo[9]);
bool winCheck (char xo[9], int);

/*Main*/
int main (void) {

/*Instantiate Variables*/
char x = 'X';
char o = 'O';
bool winner = false;
bool player = 0;
bool taken = false;
int spot;
int winDetected;

/*Instantiate the arrays*/
char xo[9] = {'0', '1', '2', '3', '4', '5', '6', '7', '8'};

/*Welcome Message*/
cout << "p-please play with yourself, s-senpai > w <\n\n";
printBoard(xo);

/*Game loop until a winner is found tbh*/
while (!winner) {

/*Player must play*/
if (player == 0) {
/*X plays*/
cout << "X, pick a spot tbh: ";
cin >> spot;

/*Check if the spot is taken*/
taken = checkBoard(spot, xo);
while (taken) {
cout << "Enter another number you fuck \n";
cin >> spot;
taken = checkBoard(spot, xo);
} while(taken);

/*Update the board*/
xo[spot] = x;
printBoard (xo);

/*Check for a winner*/
winner = winCheck(xo, 0);

/*Update the player*/
player = player + 1;

} else {
/*O plays*/
cout << "O, pick a spot tbh: ";
cin >> spot;

/*Check if the spot is taken*/
taken = checkBoard(spot, xo);
while (taken) {
cout << "Enter another number you fuck \n";
cin >> spot;
taken = checkBoard(spot, xo);
} while(taken);

/*Update the board*/
xo[spot] = o;
printBoard (xo);

/*Check for a winner*/
winner = winCheck(xo, 0);

/*Update the player*/
player = player - 1;
}

} while (!winner);

/*Declare the winner*/
if (player == 1) {
cout << x << " is the winner!" << endl;
} else {
cout << o << " is the winner!" << endl;
}


return 0;
}

/*Check if the X replaced O, or vice versa. I should've put this in main
* but whatever lmao who /npm/ here amirite?*/
bool checkBoard(int number, char xo[9]){
if (xo[number] == 'X' || xo[number] == 'O') {
return true;
} else {
return false;
}
}

/*Print board*/
void printBoard (char xo[9]) {

/*Print the current board*/
cout << "\t | | \n";
cout << "\t " << xo[0] << " | " << xo[1] << " | " << xo[2] << " \n";
cout << "\t___|___|___\n" << endl;
cout << "\t | | \n";
cout << "\t " << xo[3] << " | " << xo[4] << " | " << xo[5] << " \n";
cout << "\t___|___|___\n" << endl;
cout << "\t | | \n";
cout << "\t " << xo[6] << " | " << xo[7] << " | " << xo[8] << " \n";
cout << "\t___|___|___\n" << endl;

return;
}

/*Check for a winner*/
bool winCheck (char xo[9], int winDetected) {
/*Local variables*/
char x = 'X';
char o = 'O';

for (winDetected = 0; winDetected < 9; winDetected++){
switch(winDetected) {
/*Row*/
case 1:
if ((xo[0] == o && xo[1] == o && xo[2] == o) || (xo[0] == x && xo[1] == x && xo[2] == x)) {
return true;
}
break;
case 2:
if ((xo[3] == o && xo[4] == o && xo[5] == o) || (xo[3] == x && xo[4] == x && xo[5] == x)) {
return true;
}
break;
case 3:
if ((xo[6] == o && xo[7] == o && xo[8] == o) || (xo[6] == x && xo[7] == x && xo[8] == x)) {
return true;
}
break;

/*Column*/
case 4:
if ((xo[0] == o && xo[3] == o && xo[6] == o) || (xo[0] == x && xo[3] == x && xo[6] == x)) {
return true;
}
break;
case 5:
if ((xo[1] == o && xo[4] == o && xo[7] == o) || (xo[1] == x && xo[4] == x && xo[7] == x)) {
return true;
}
break;
case 6:
if ((xo[2] == o && xo[5] == o && xo[8] == o) || (xo[2] == x && xo[5] == x && xo[8] == x)) {
return true;
}
break;

/*Diagonal*/
case 7:
if ((xo[0] == o && xo[4] == o && xo[8] == o) || (xo[0] == x && xo[4] == x && xo[8] == x)) {
return true;
}
break;
case 8:
if ((xo[2] == o && xo[4] == o && xo[6] == o) || (xo[2] == x && xo[4] == x && xo[6] == x)) {
return true;
}
break;
}
}
}

Lord_Tryzalot
Lord_Tryzalot

@Need_TLC
sorry to say, but your code is shit

King_Martha
King_Martha

@Lord_Tryzalot
I figured ;_;.
What I can improve is the switching turns part, and turn that whole part into a function instead of repeating the code twice. What else can I improve?

viagrandad
viagrandad

@King_Martha
well i hope you do realize this

for (winDetected = 0; winDetected < 9; winDetected++){
switch(winDetected) {

runs trough all the cases of the switch statement i.e. both the for and the switch are obsolete if you want to search for a winner that way
(...also why do you check for specific symbols when you can check that they are the same)
(also i'm sure there is a faster way than 8 if statements, but i don't want to think about it)

also do you even check for a draw.. or go into an endless loop when the board is filled?

cum2soon
cum2soon

@Need_TLC
Why the huge case statement? Why not do a loop at least for the loops? Better yet, why not set up something that checks recursively for lines up to 3 or something.

Inmate
Inmate

@Spazyfool
requires fpmath

fvariable fatness
fvariable tallness
0 value bmi-table

: kg ( r -- ) fatness f! ;
: pounds ( r -- ) 0.45359237e f* kg ;
: meters ( r -- ) tallness f! ;
: feet ( r -- r' ) 12e f* ;
: inches ( r r -- ) f+ 0.0254e f* meters ;

: bmi ( -- r ) fatness f@ tallness f@ fdup f* f/ ;

: bmi: ( r-from r-to "meaning" -- )
fswap f, f, here 256 allot
0 parse rot place ;

class bmi-record
fvariable low
fvariable high
256 buffer: meaning
0 buffer: next
: within ( r -- f )
low f@ 0e f< if fdrop true \ 'otherwise' case
else low f@ high f@ fwithin then ;
: wat cr low f@ f. high f@ f. meaning count type ;
end-class
: otherwise ( -- r r ) -1e -1e ;

\ superior anime BMI ranges
create japan-table here to bmi-table
0e 18.5e bmi: chibi
18.5e 25e bmi: normal person
25e 30e bmi: fat fuck
30e 35e bmi: HAES activist
35e 40e bmi: deathfat
otherwise bmi: transmountain (preferred pronouns: Mt. Mt. Mt. Mt.)

: bmi? ( -- )
bmi bmi-table begin
fdup dup USING bmi-record within if
cr ." You have a BMI of " f. ." -- meaning that you are a "
USING bmi-record meaning count type exit
then USING bmi-record next
again ;

\\
200e pounds
5e feet 9e inches
bmi?
\ outputs: You have a BMI of 29.534533 -- meaning that you are a fat fuck

likme
likme

@viagrandad
I just wanted an excuse to use switches, I've never used them until now. I'm pretty retarded.

also do you even check for a draw.. or go into an endless loop when the board is filled?
I thought about it then forgot to implement

Changes to make:
turn player switching into a function
remove case, replace with if-else statements + add a counter
This way I can also add a draw feature. If the game isn't finished by nine turns, it'll be a draw.

@cum2soon
There are only 8 possible ways to win in this game, but you're right. I could reduce it to 4 statements if I make a for loop that adds one to rows and columns using a for loop.

Poker_Star
Poker_Star

@King_Martha
In the switch(winDetected) part you have the same code over and over again with very small variations. That's always a bad sign. Design a formula so the same code handles all cases. It's ok to think about it for a while. It's maybe the single most important skill to train. The same goes for the printBoard function. Use for loops for that.

Most of your comments are completely useless. I know what function prototypes, main functions, variable instantiation and all that stuff look like. You don't need to tell me. That's not what comments are for. Comments are for when code's purpose isn't obvious. It's for fellow programmers, not people looking to learn the basic syntax of the programming language.

The purpose of your "checkBoard" function is fine. It's good to split things up in small functions. That makes your code more manageable. You could use a lot more functions. The problem with the npm fragmentation is not that there are functions for everything, but that there are packages for everything.
But you could have made the code shorter and simpler, like this:
return (xo[number] == 'X' || xo[number] == 'O');

This is something you shouldn't do, at least not inside a function:
char x = 'X';
char o = 'O';

It makes it harder to tell what's going on. If I see you're assigning a variable value to something I assume that it might change, and I have to look back to see what that value is.
But doing something like that is useful if you might want to change 'X' and 'O' to different characters at some point. But in that case you should use it consistently, and never use the literal characters anywhere. You should also make them constants that are defined outside the function definitions, so they're available everywhere. These are two ways of doing that, I don't know which one is preferred in C++:
const char x = 'X';
const char o = 'O';

#define X 'X'
#define O 'O'

The second one uses the C preprocessor.
Your goal should be to define them in a single place. That way, you only have to change two lines of code to change the characters for the entire program.

FastChef
FastChef

You can represent a tic-tac-toe board with a nine-digit number, with 0 representing an empty space, then 1 for X and 2 for O (or vice versa). The most compact representation would use a ternary numeral, but for convenience with computers you can use 4-base numerals.

For example:

: popcnt ( u -- u ) \ count set bits, from clf
DUP 1 RSHIFT $55555555 AND -
$33333333 2DUP AND >R SWAP 2 RSHIFT AND R> +
$0F0F0F0F 2DUP AND >R SWAP 4 RSHIFT AND R> +
$00FF00FF 2DUP AND >R SWAP 8 RSHIFT AND R> +
$0000FFFF 2DUP AND >R SWAP 16 RSHIFT AND R> + ;
: 3-set ( u -- f ) popcnt 3 = ;

\ Trouble in Terrorist Town (TTT)
create players bl c, char X c, char O c, ( error: ) char * c,
1 constant X
2 constant O
0 constant new-game

: .square ( t -- t' ) 4 /mod swap players + 1 type ;
: .row ( t -- t' ) cr ." |" .square .square .square ." |" ;
: --- ( -- ) cr ." -----" ;
: .board ( t -- ) --- .row .row .row drop --- ;

( t -- t' )
: match ( t1 t2 -- f *exits* | t1 )
postpone OVER postpone AND postpone 3-set postpone IF
postpone DROP postpone TRUE postpone EXIT postpone THEN ;
immediate

4 base !
: x-wins? ( t -- f )
111000000 match
000111000 match
000000111 match
100100100 match
010010010 match
001001001 match
drop false ;
: o-wins? ( t -- f )
222000000 match
000222000 match
000000222 match
200200200 match
020020020 match
002002002 match
drop false ;
decimal

: board-full? ( t -- f )
9 0 do 4 /mod swap 0= if drop false unloop exit then loop drop true ;

: play ( t t -- t | *winner* ) or dup .board cr
dup x-wins? if ." X has won!" drop exit then
dup o-wins? if ." O has won!" drop exit then
dup board-full? if ." It's a draw!" drop exit then ;
: at ( n-player n-col n-row -- t )
6 * rot swap lshift swap 2* lshift ;

Example:

new-game x 0 0 at play x 0 1 at play x 0 2 at play
-----
|X |
| |
| |
-----

-----
|X |
|X |
| |
-----

-----
|X |
|X |
|X |
-----
X has won! ok

Looking at just the board as a number, in base 4:

new-game x 0 0 at play x 0 1 at play x 0 2 at play
000000001

000001001

001001001
X has won! ok

GoogleCat
GoogleCat

Rollin'

Stark_Naked
Stark_Naked

@TreeEater
the "mathematically" probably isn't a mistake. They mean: don't just convert the number into a string and reverse the string.

still, looks like this list was put together by a thread.

Boy_vs_Girl
Boy_vs_Girl

Rolling

MPmaster
MPmaster

@FastChef
holy fuck that's v cool. Save't for future reference.

@Poker_Star
I've been making fatal mistakes the entire time. New code though:
/*Two-player tic-tac-toe brudder*/
#include <iostream>
using namespace std;

void printBoard (char xo[9]);
bool checkBoard (int, char xo[9]);
bool winCheck (char xo[9], int, bool);
bool turn (bool, char, char xo[9]);

int main (void) {

/*Instantiate Variables*/
bool winner = false;
bool player = 0;
bool draw = false;
int winDetected;
int counter;

/*Instantiate the arrays*/
char xo[9] = {'0', '1', '2', '3', '4', '5', '6', '7', '8'};

/*Welcome Message*/
cout << "Play with yourself, senpai > w < \n\n";
printBoard(xo);

/*Game loop until a winner is found*/
while (!winner) {
/*Counter to see if a draw has occured
* triggers after eight moves are played*/
for (int a = 0; a < 10; a++) {
if (a == 9) {
draw == true;
cout << "It's a draw tbg." << endl;
return 0;
}

if (player == 0) {
turn(player, 'X', xo);
player = player + 1;
} else {
turn(player, 'O', xo);
player = player - 1;
}

/*Check for a winner*/
winner = winCheck(xo, 0, draw);
}

} while (!winner);

/*Declare the winner*/
if (player == 1) {
cout << 'X' << " is the winner!" << endl;
} else {
cout << 'O' << " is the winner!" << endl;
}

return 0;
}

/*Check if the X replaced O, or vice versa.*/
bool checkBoard(int number, char xo[9]){

return (xo[number] == 'X' || xo[number] == 'O');
}

/*Print board*/
void printBoard (char xo[9]) {

/*Print the current board*/
cout << "\t | | \n";
cout << "\t " << xo[0] << " | " << xo[1] << " | " << xo[2] << " \n";
cout << "\t___|___|___\n" << endl;
cout << "\t | | \n";
cout << "\t " << xo[3] << " | " << xo[4] << " | " << xo[5] << " \n";
cout << "\t___|___|___\n" << endl;
cout << "\t | | \n";
cout << "\t " << xo[6] << " | " << xo[7] << " | " << xo[8] << " \n";
cout << "\t___|___|___\n" << endl;

return;
}

/*Check for a winner*/
bool winCheck (char xo[9], int a, bool draw) {
/*Local variables*/
char x = 'X';
char o = 'O';

/*First checks the rows, then the columns, then diagonally
* if none, returns a draw*/
for (a = 0; a < 4; a++) {
if ((xo[0+a] == o && xo[1+a] == o && xo[2+a] == o) || (xo[0+a] == x && xo[1+a] == x && xo[2+a] == x)) {
return true;
} else if ((xo[0+a] == o && xo[3+a] == o && xo[6+a] == o) || (xo[0+a] == x && xo[3+a] == x && xo[6+a] == x)){
return true;
} else if ((xo[0] == o && xo[4] == o && xo[8] == o) || (xo[0] == x && xo[4] == x && xo[8] == x)) {
return true;
} else if ((xo[2] == o && xo[4] == o && xo[6] == o) || (xo[2] == x && xo[4] == x && xo[6] == x)) {
return true;
} else {
return false;
}
}
}



/*Changing turns between x and o*/
bool turn(bool player, char who, char xo[9]) {
int spot;
bool taken = false;

cout << who << " , pick a spot tbh: ";
cin >> spot;

/*Check if the spot is taken*/
taken = checkBoard(spot, xo);
while (taken) {
cout << "This spot is taken tbh... \n";
cin >> spot;
taken = checkBoard(spot, xo);
} while(taken);

/*Update the board*/
xo[spot] = who;
printBoard (xo);

}

Disable your ad blocker to access the content

Disable your ad blocker to access the content