0

I am trying to make a program that couts characters in alternating colors.

#include <iostream.h>
#include <windows.h>
#include <dos.h>
#include "Random.h"


void main()
{
	randomize();
	HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
	int basecolor1=random(256), basecolor2=random(256);
	char board[4][4];
	int x, y, k;
	for(x=0; x<4; x++)
	{
		for(y=0; y<4; y++)
		{
			k=(x%2);
			k+=(y%2);
			k=k%2;
			if(k==1)
			{
				SetConsoleTextAttribute(hcon,(int)(basecolor1));
				//cout<<"l";
			}
			else
			{
				SetConsoleTextAttribute(hcon,(int)(basecolor2));
				//cout<<"k";
			}
			//Sleep(1000);
			cout<<k;
                           //cout<<endl;
			
		}
		cout<<endl;
	}
}

However, only the lines of characters actually alternate.

When you uncomment out the Sleep(1000), which waits for 1 second, the program waits for four seconds then displays the line in one color.
If you uncomment out the cout<<endl, then it displays on a different line, but alternates the colors.
How can I make the program alternate characters and not individual lines?

2
Contributors
1
Reply
2
Views
5 Years
Discussion Span
Last Post by deceptikon
0

It alternates characters just fine for me, but you can simplify the toggle just by flipping a variable instead of trying to calculate it based on the loop indexes:

#include <iostream>
#include <windows.h>

using namespace std;

int main()
{
    HANDLE hcon = GetStdHandle(STD_OUTPUT_HANDLE);
    int basecolor1 = FOREGROUND_GREEN | FOREGROUND_INTENSITY;
    int basecolor2 = FOREGROUND_RED | FOREGROUND_INTENSITY;
    int x, y, k = 1;
    
    for (x = 0; x < 4; x++)
    {
        for (y = 0; y < 4; y++)
        {
            if (k == 1)
            {
                SetConsoleTextAttribute(hcon,(int)(basecolor1));
            }
            else
            {
                SetConsoleTextAttribute(hcon,(int)(basecolor2));
            }
            
            cout << k;
            k = !k;
        }
        
        cout << endl;
    }
}

If that's not the output you want, please describe exactly what it should look like.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.