Jump to content

Coding challenge


snakey

Recommended Posts

I just completed the challenge, but i use vbscript :(

*sigh*

edit: Just changed out my sorting function to embedded jscript, and i knocked a ton of chars/lines off my code (even though its still not a variation of C)

edit edit: I guess i can still post it.  i re-re-wrote it back into vb, modified it and cut out a ton of code.

Module Module1

    ' Mark's number sortabobber
    ' Language: VB
    ' Status: Single for the moment
    ' Orientation: Straight
    ' Sign: Leo

    Sub Main()

        ' Declare "the goods"
        Dim arrSort() As Integer = {12, 55, 74, 3, 65, 9, 12, 45, 6, 13}

        ' Declare random letters to do my dirty work
        Dim a As Integer
        Dim b As Integer
        Dim temp As Integer

        ' Nested loops, inner compairs current index to all other numbers and makes a decision
        For a = UBound(arrSort) - 1 To 0 Step -1
            For b = 0 To a
                If arrSort(b) < arrSort(b + 1) Then
                    temp = arrSort(b + 1)
                    arrSort(b + 1) = arrSort(b)
                    arrSort(b) = temp
                End If
            Next
        Next

        ' This cat keeps track of my index for writing
        Dim i As Integer = 0

        ' Writing
        Do Until i = 0
            Console.Write(arrSort(i) & " ")
            i += 1
        Loop
    End Sub

End Module

Link to comment
Share on other sites

  • 2 weeks later...
  • Replies 237
  • Created
  • Last Reply

Top Posters In This Topic

Top Posters In This Topic

Posted Images

stablefoxx this valid?

Me thinks so, unless someone else submits code...

Link to comment
Share on other sites

I know it's past due, but I was bored. So here it is:

/* Sorting using a linear algorithm. 
/ Programmer: hexlax
/ Language: C++ (gcc)
/ The following program takes an array of integers and sorts it from greatest to least.
*/

#include <iostream>
using namespace std;

// The following function is passed the array by reference since no changes are being made.
void print(int& array[]){
    
    for( int x = 0; x < array.length(); x++)
        cout << array[x] << " ";
}

//Our main function
int main(){

    //Our array of integers:
    int array [ 50, 25, 30, 10, 49, 23, 54, 82, 19, 28 ];

    //Used for array swapping:
    int temp =  0;

    //Initial output:
    cout << "The current array contains ";
    print(array[]);
    cout << "." << endl;


    // Sort using linear algorithm.
    // Usually I would use a log algorithm like quicksort, but since 
    // there are so few numbers in our array, linear will suffice. 
    for( int x= 0; x< array.length(); x++)
        for( int j = 0; j < array.length(); j++){
            if(array[x] < array[j]) {
                //perform the swap
                temp = array[j];
                array[j] = array[x];
                array[x] = temp;
            }
        }

    // Final output
    cout << "Now the sorted array contains ";
    print(array[]);
    cout << "." << endl;

    return 0;
}

Link to comment
Share on other sites

i dont know about you but when i try to compile it i get errors, you might want to check your code. just saying, im gonna check to see if its just my compiler. well most of it looks good but just a couple of errors. good job.

Link to comment
Share on other sites

the only problem with this is that people post there entry and leave and never come back :P

Very true, who has the next challenge  :?

-If you have a good one feel free to post it!

Link to comment
Share on other sites

Lang: C, C#, C++, Or any other c derived language

Program: Windows Start menu replacement

Must Have: Small, must have all features of normal start

Winner: Most useful

Time: 2 1/2 weeks

Is that good? For Linux, try something like it.

Link to comment
Share on other sites

  • 3 weeks later...

well if people would code something up it would run alot smoother um ok here goes

Lang: Any

Program: Alarm clock

Must Have: Must have a set able alarm clock and clock displayed aswell

Winner: best alround app

Time: 2-3 weeks

Link to comment
Share on other sites

  • 2 weeks later...

Hello! I know theres still plenty of time left, but I'm going to submit my alarm clock application early! ;)

Yeah I was a bit reluctant to do it at first because an alarm clock seemed like kind of a boring project, but I started doing it anyway because I wanted to win the challenge! :) and It actually was sorta fun to make!

It seems like the trend so far is with console app's, console apps are cool but I love making GUI's even more, so thats where I went with this challenge

Heres what it looks like:

StevesAlarmClock.png

As you can see I shaped the window like the clock image is shaped! pretty neat eh?

It surpasses both requirements, not only does it display the time, and date, it also has not 1, but 3 set able alarms... You can use the default.mp3 that comes with it as the alarm, or copy one of your favorite mp3's into the folder to use as the alarm...(just remember to turn your PC volume on full blast if you want it to wake you up!)

And I actually tested it to make sure it works! I made it yesterday... so last night, I set 1 of the alarms and turned my volume up, then went to sleep! and sure enough in the morning I was awoken to hear a song that I like playing at a loud volume! :)

You can make it start up with windows simply by checking the checkbox... (it adds it self to the registry at a key that I know of which makes programs start on startup, read over the source to learn it if you don't already know)

Once you pick an alarm time you like, or 2, or 3, then just press "Save Alarms" button, but don't forget to turn the ones you want on before pressing save, else they wont be saved as on, but they will still work...

the edit box can be used to display an mp3 song you have saved, or save a new one, press the load button to see whats currently saved... or you can press test alarm and it loads it as well, but also plays the mp3...

One thing is that an mp3 can't have any spaces in it for some reason, even though I get the full string it still wont play because of the space(s)... If anyone knows why that is or how to fix that bug, it would be cool but for now just make your mp3's with no spaces... its not case sensitive though

Has a hideme feature, Press CONTROL + ALT + A to hide/unhide the window, so no one can close it on you, and you've still got your alarm going in the background! still shows up on task manager though!

because its a GUI, the source code wont compile all on its own, you need other files with it, a bitmap and icon, window region data that defines the shape of the window, a manifest file for the xp themed buttons and other controls

so you'll have to download the full project to be able to compile it! oh and I almost forgot its coded in Microsoft Visual C++ 2008! so you'll likely need that to compile it!

Well I hope you enjoy reading my source code! and may GUI programming be with you! :)

downloads directly off my apache web server

binary:

http://www.popeax.com/downloads/StevesAlarmClock.zip

source:

http://www.popeax.com/downloads/AlarmclockSRC.zip

rapidshare downloads

binary:

http://rapidshare.com/files/122868573/Stev...mClock.zip.html

source:

http://rapidshare.com/files/122868294/AlarmclockSRC.zip.html

the main source code, you still need other data to compile though!

// AlarmClock Coded By Steve8x!
// Pure Win32 API! SCREW MFC!!!
#include <windows.h>
#include <fstream>
#include <iostream>
#include <stdio.h>
#include <time.h>
#include <string>
#include <mmsystem.h>
#include "RegionData.h" // holds binary for the window shape
#pragma comment(lib, "winmm.lib") // for mp3 playback

using namespace std;

//Prototypes
void AlarmThread(void);
HWND CreateButtonEx(char Text[64], int x, int y, int wd, int ht, int id);
HWND CreateEditEx(char Text[64], int x, int y, int wd, int ht, int id);
HWND CreateTextEx(char Text[64], int x, int y, int wd, int ht, int id);
HWND CreateCheckEx(char Text[64], int x, int y, int wd, int ht, int id);
HWND CreateDropDownEx(char Text[64], int x, int y, int wd, int ht, int id);

SYSTEMTIME st;
HINSTANCE hInst;
HRGN WndRgn;
HWND hWnd, hDate, hTime, hSet, hStartUp, hAMPM, hAMPM2, hAMPM3, hHour, hHour2, hHour3, hMinute, hMinute2, hMinute3, hCheck, hCheck2, hCheck3;
HWND hTest, hMp3, hLoad;
HKEY hk;

int ThreadRunning = 0, Stop = 0, alarm1, alarm2, alarm3;
bool AMPM = 0; // AM = 0, PM = 1

char exePath[256];
char CurrentDate[64];
char CurrentTime[32];

const char* AMorPM[] = {"AM", "PM"};
const char* HoursList[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"};
const char* MinutesList[] = {"00", "10", "20", "30", "40", "50"};

DWORD BufSize = 256;
LRESULT hourz, minutez, pmz, startwithwindows;
char HOUR[3];
char MINUTE[3];
char AMPMZ[3];
char AlarmMp3[256];

void SetBoxes(HWND h, HWND m, HWND ampm) // sets the drop down boxes values to reflect your already saved alarms
{
    for(int x = 0; x < 12; x++)
    {
        if(strcmp(HOUR, HoursList[x]) == 0)
        {
            SendMessageA(h, CB_SETCURSEL, x, 0);
            break;
        }
    }

    for(int x = 0; x < 6; x++)
    {
        if(strcmp(MINUTE, MinutesList[x]) == 0)
        {
            SendMessageA(m, CB_SETCURSEL, x, 0);
            break;
        }
    }

    if(strcmp(AMPMZ, "AM") == 0)
        SendMessageA(ampm, CB_SETCURSEL, 0, 0); // AM
    else
        SendMessageA(ampm, CB_SETCURSEL, 1, 0); // PM
}


void ReadMp3()
{
    ifstream alarms("alarms.ini");
    if(alarms.is_open())
    {
        alarms.getline(AlarmMp3, sizeof(AlarmMp3));
    }
    alarms.close();
}

void ReadAlarms()
{
    char alarmON[2];
    
    ifstream alarms("alarms.ini");
    if(alarms.is_open())
    {
        alarms.getline(AlarmMp3, sizeof(AlarmMp3));
        alarms >> HOUR >> MINUTE >> AMPMZ >> alarmON;
        SetBoxes(hHour, hMinute, hAMPM);

        if(strcmp((const char*)alarmON, "1") == 0)
        {
            alarm1 = 1;
            SendMessageA(hCheck, BM_SETCHECK, 1, 0);
            SendMessageA(hCheck, WM_SETTEXT, 0, (LPARAM)"ON");
        }
        else
        {
            alarm1 = 0;
            SendMessageA(hCheck, BM_SETCHECK, 0, 0);
            SendMessageA(hCheck, WM_SETTEXT, 0, (LPARAM)"OFF");
        }


        alarms >> HOUR >> MINUTE >> AMPMZ >> alarmON;
        SetBoxes(hHour2, hMinute2, hAMPM2);

        if(strcmp((const char*)alarmON, "1") == 0)
        {
            alarm2 = 1;
            SendMessageA(hCheck2, BM_SETCHECK, 1, 0);
            SendMessageA(hCheck2, WM_SETTEXT, 0, (LPARAM)"ON");
        }
        else
        {
            alarm2 = 0;
            SendMessageA(hCheck2, BM_SETCHECK, 0, 0);
            SendMessageA(hCheck2, WM_SETTEXT, 0, (LPARAM)"OFF");
        }

        alarms >> HOUR >> MINUTE >> AMPMZ >> alarmON;
        SetBoxes(hHour3, hMinute3, hAMPM3);

        if(strcmp((const char*)alarmON, "1") == 0)
        {
            alarm3 = 1;
            SendMessageA(hCheck3, BM_SETCHECK, 1, 0);
            SendMessageA(hCheck3, WM_SETTEXT, 0, (LPARAM)"ON");
        }
        else
        {
            alarm3 = 0;
            SendMessageA(hCheck3, BM_SETCHECK, 0, 0);
            SendMessageA(hCheck3, WM_SETTEXT, 0, (LPARAM)"OFF");
        }

    }
    alarms.close();
}
    
void SetAlarms()
{
    hourz = SendMessage(hHour, CB_GETCURSEL, 0, 0);
    minutez = SendMessage(hMinute, CB_GETCURSEL, 0, 0);
    pmz = SendMessage(hAMPM, CB_GETCURSEL, 0, 0);

    GetWindowTextA(hMp3, AlarmMp3, 256); 
    if(AlarmMp3[0] == 0) // if nothings is typed in the box read from file
    {
        ReadMp3();
        SendMessageA(hMp3, WM_SETTEXT, 0, (LPARAM)&AlarmMp3);
    }

    ofstream alarms("alarms.ini");
    if(strstr(AlarmMp3, ".mp3") == 0) // if theres no .mp3 file saved use default
        alarms << "Default.mp3" << "\n";
    else
        alarms << AlarmMp3 << "\n";

    alarms << HoursList[hourz] << "\n" << MinutesList[minutez] << "\n" << AMorPM[pmz] << "\n";
    if(alarm1 == 1)
        alarms << "1\n";
    else
        alarms << "0\n";

    hourz = SendMessage(hHour2, CB_GETCURSEL, 0, 0);
    minutez = SendMessage(hMinute2, CB_GETCURSEL, 0, 0);
    pmz = SendMessage(hAMPM2, CB_GETCURSEL, 0, 0);

    alarms << HoursList[hourz] << "\n" << MinutesList[minutez] << "\n" << AMorPM[pmz] << "\n";

    if(alarm2 == 1)
        alarms << "1\n";
    else
        alarms << "0\n";

    hourz = SendMessage(hHour3, CB_GETCURSEL, 0, 0);
    minutez = SendMessage(hMinute3, CB_GETCURSEL, 0, 0);
    pmz = SendMessage(hAMPM3, CB_GETCURSEL, 0, 0);

    alarms << HoursList[hourz] << "\n" << MinutesList[minutez] << "\n" << AMorPM[pmz] << "\n";

    if(alarm3 == 1)
        alarms << "1\n";
    else
        alarms << "0\n";

    alarms.close();
}


LRESULT CALLBACK WndProc(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam)
{
    switch(msg)
    {
        case WM_CREATE: // Sets the custom window shape
            WndRgn = ExtCreateRegion(0, sizeof(RegionData), (RGNDATA*)&RegionData);
            SetWindowRgn(hwnd, WndRgn, TRUE);
            break;

        case WM_COMMAND:
            if(wParam == 420) // user pressed "X" button to quit
                goto QUIT;

            if(wParam == 421) // user pressed "SET ALARMS" which saves alarm data + Mp3
            {
                SetAlarms();
            }

            if(wParam == 422) // "TEST ALARM" pressed loads the mp3 only and test plays it
            {
                ReadMp3();
                SendMessageA(hMp3, WM_SETTEXT, 0, (LPARAM)&AlarmMp3);

                if(Stop == 0)
                {
                    Stop = 1;
                    SendMessageA(hTest, WM_SETTEXT, 0, (LPARAM)"STOP");
                    if(ThreadRunning == 0)
                        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&AlarmThread, 0, 0, 0);
                }
                else if(Stop == 1)
                {
                    Stop = 2;
                    SendMessageA(hTest, WM_SETTEXT, 0, (LPARAM)"TEST ALARM");

                    string AlarmSound(AlarmMp3);
                    string Close = "close " + AlarmSound;
                    mciSendStringA(Close.c_str(), 0, 0, 0);
                }
            }

            // doing it when initializing the program freezes it for some reason until you click, very annoying bug
            // So we just have to press load for now (if you previously saved a custom mp3)
            // TEST ALARM button will work as well to load it...
            if(wParam == 423) // Load - Loads the Saved Mp3 into edit box
            {
                ReadMp3();
                SendMessageA(hMp3, WM_SETTEXT, 0, (LPARAM)&AlarmMp3);
            }

            if(wParam == 700) // user toggled alarm 1
            {
                _asm xor [alarm1], 1 // toggle; if alarm1 == 1, it now equals zero, or vise versa

                if(alarm1 == 1)
                    SendMessageA(hCheck, WM_SETTEXT, 0, (LPARAM)"ON");
                else
                    SendMessageA(hCheck, WM_SETTEXT, 0, (LPARAM)"OFF");
            }

            if(wParam == 701) // user toggled alarm 2
            {
                _asm xor [alarm2], 1

                if(alarm2 == 1)
                    SendMessageA(hCheck2, WM_SETTEXT, 0, (LPARAM)"ON");
                else
                    SendMessageA(hCheck2, WM_SETTEXT, 0, (LPARAM)"OFF");
            }

            if(wParam == 702) // user toggled alarm 3
            {
                _asm xor [alarm3], 1

                if(alarm3 == 1)
                    SendMessageA(hCheck3, WM_SETTEXT, 0, (LPARAM)"ON");
                else
                    SendMessageA(hCheck3, WM_SETTEXT, 0, (LPARAM)"OFF");
            }

            if(wParam == 703) // user toggled start with windows checkbox
            {
                startwithwindows = SendMessage(hStartUp, BM_GETCHECK, 0, 0);

                RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_ALL_ACCESS, &hk);

                if(startwithwindows == BST_CHECKED)
                {
                    GetModuleFileNameA(GetModuleHandle(0), exePath, sizeof(exePath));
                    int pathSize = lstrlenA(exePath);
            
                    RegSetValueExA(hk, "AlarmClock", 0, REG_SZ, (const unsigned char*)exePath, pathSize);
                }
                else
                {
                    RegDeleteValueA(hk, "AlarmClock");
                }

                RegCloseKey(hk);
            }

        case WM_LBUTTONDOWN: // so that the window is moveable
            SendMessage(hwnd, WM_NCLBUTTONDOWN, HTCAPTION, lParam);
            break;

        case WM_RBUTTONDOWN: // minimize with right click
            ShowWindow(hWnd, SW_MINIMIZE);
            break;

        case WM_CLOSE:
            DestroyWindow(hwnd);
        break;

        case WM_DESTROY:
            QUIT:
            PostQuitMessage(0);
        break;

        default:
            return DefWindowProc(hwnd, msg, wParam, lParam);
    }
    return 0;
}

void Movsb(void* dst, void* src, int bSize) // ASM movsb == Faster than memcpy
{
    _asm
    {
        pushad
        mov esi, [src]
        mov edi, [dst]
        mov ecx, [bSize]
        rep movsb
        popad
    }
}

void GetDayAndMonth(WORD day, WORD month)
{
    char WeekDay[10];
    char Month[10];
    char Day[10];

    ZeroMemory(WeekDay, 10);
    ZeroMemory(Month, 10);
    ZeroMemory(Day, 10);
    ZeroMemory(CurrentDate, sizeof(CurrentDate));

    switch(day) // wDayOfWeek
    {
        case 0:
        Movsb(&WeekDay, "Sunday,", 7);
        break;

        case 1:
        Movsb(&WeekDay, "Monday,", 7);
        break;

        case 2:
        Movsb(&WeekDay, "Tuesday,", 8);
        break;

        case 3:
        Movsb(&WeekDay, "Wednesday,", 10);
        break;

        case 4:
        Movsb(&WeekDay, "Thursday,", 9);
        break;

        case 5:
        Movsb(&WeekDay, "Friday,", 7);
        break;

        case 6:
        Movsb(&WeekDay, "Saturday,", 9);
        break;
    }

    switch(month) // wMonth
    {
        case 1:
        Movsb(&Month, "January", 7);
        break;

        case 2:
        Movsb(&Month, "February", 8);
        break;

        case 3:
        Movsb(&Month, "March", 5);
        break;

        case 4:
        Movsb(&Month, "April", 5);
        break;

        case 5:
        Movsb(&Month, "May", 3);
        break;

        case 6:
        Movsb(&Month, "June", 4);
        break;

        case 7:
        Movsb(&Month, "July", 4);
        break;

        case 8:
        Movsb(&Month, "August", 6);
        break;

        case 9:
        Movsb(&Month, "September", 9);
        break;

        case 10:
        Movsb(&Month, "October", 7);
        break;

        case 11:
        Movsb(&Month, "November", 8);
        break;

        case 12:
        Movsb(&Month, "December", 8);
        break;
    }

    sprintf_s(Day, sizeof(Day), " %u", st.wDay);

    strcat_s(CurrentDate, WeekDay);
    strcat_s(CurrentDate, " ");
    strcat_s(CurrentDate, Month);
    strcat_s(CurrentDate, Day);


    /* // LOL the way I did it first before I realized I could just strcat, silly me...
    for(int x = 0; x < sizeof(CurrentDate); x++)
    {
        if(WeekDay[x] == 0)
        {
            CurrentDate[x] = 0x20; // 0x20 = space
            theOffset = x + 1;
            x = 0;
            for(int c = theOffset; c < sizeof(CurrentDate); c++)
            {
                if(Month[x] == 0)
                {
                    theOffset = c;
                    break;
                }

                CurrentDate[c] = Month[x];
                x++;
            }
            break;
        }

        CurrentDate[x] = WeekDay[x];
    }
    

    char* dest = (char*)&CurrentDate + theOffset;

    Movsb((void*)dest, (void*)&Day, theSize);
    */
}

void AlarmThread() // plays an mp3 file
{
    ThreadRunning = 1;
    int count = 0;
    SendMessageA(hTest, WM_SETTEXT, 0, (LPARAM)"STOP");

    ReadMp3();
    SendMessageA(hMp3, WM_SETTEXT, 0, (LPARAM)&AlarmMp3);

    string AlarmSound(AlarmMp3);

    string Open = "open \"" + AlarmSound + "\" type mpegvideo alias " + AlarmSound;
    string Play = "play " + AlarmSound + " from 0";
    string Close = "close " + AlarmSound;

    mciSendStringA(Open.c_str(), 0, 0, 0);
    for(;; Sleep(10))
    {
        if(count > 0)
            count --;

        if(count == 0)
        {
            mciSendStringA(Play.c_str(), 0, 0, 0);
            count = 0x555;
        }

        if(strcmp(AlarmMp3, "Default.mp3") != 0)
        {
            count = 1337;
        }

        if(Stop == 2)
        {
            Stop = 0;
            mciSendStringA(Close.c_str(), 0, 0, 0);
            break;
        }

    }

    ThreadRunning = 0;
    ExitThread(0);
}


void MainThread() // displays time, checks for alarms
{
    // third byte is for null termination
    char hour[3];
    char minute[3];
    char second[3];

    for(;; Sleep(50))
    {
        GetLocalTime(&st);
        GetDayAndMonth(st.wDayOfWeek, st.wMonth);

        ZeroMemory(CurrentTime, sizeof(CurrentTime));
        _strtime_s(CurrentTime);

        // separate hours, minutes, and seconds from string
        // 2 chars = 2 bytes = 1 word
        // I love type casting :)
        *(WORD*)hour = *(WORD*)CurrentTime;
        *(WORD*)minute = *(WORD*)((unsigned int)CurrentTime + 3);
        *(WORD*)second = *(WORD*)((unsigned int)CurrentTime + 6);

        hour[2] = 0; // terminate those strings :)
        minute[2] = 0;
        second[2] = 0;

        int hournumber = atoi(hour); // convert hour string into number so we can check for AM or PM

        if(hournumber > 12)
        {
            AMPM = 1; // PM
            hournumber -= 12;
            sprintf_s(CurrentTime, sizeof(CurrentTime), "%u:%s:%s PM", hournumber, minute, second);
        }
        else if(hournumber == 00) // strangely 12 o' clock AM is 00 o' clock LOL, so fix it
        {
            hournumber = 12;
            sprintf_s(CurrentTime, sizeof(CurrentTime), "%u:%s:%s AM", hournumber, minute, second);
        }
        else if(hournumber == 12) // also very wierdly 12 PM shows up as AM so we must fix that too!
        {
            AMPM = 1;
            sprintf_s(CurrentTime, sizeof(CurrentTime), "%u:%s:%s PM", hournumber, minute, second);
        }
        else
        {
            AMPM = 0;
            sprintf_s(CurrentTime, sizeof(CurrentTime), "%s:%s:%s AM", hour, minute, second);
        }

        SendMessageA(hDate, WM_SETTEXT, 0, (LPARAM)&CurrentDate);
        SendMessageA(hTime, WM_SETTEXT, 0, (LPARAM)&CurrentTime);

        // convert hour number back into string so we can check if its time to set off an alarm
        char hourString[3];
        sprintf_s(hourString, sizeof(hourString), "%i", hournumber);

        if(alarm1 == 1)
        {
            hourz = SendMessage(hHour, CB_GETCURSEL, 0, 0);
            minutez = SendMessage(hMinute, CB_GETCURSEL, 0, 0);
            pmz = SendMessage(hAMPM, CB_GETCURSEL, 0, 0);
            
            if((LRESULT)AMPM == pmz)
            {
                if((strcmp(hourString, HoursList[hourz]) == 0) && (strcmp(minute, MinutesList[minutez]) == 0))
                {
                    if(ThreadRunning == 0)
                    {
                        //ReadAlarms();
                        alarm1 = 0;
                        SetAlarms();
                        ReadAlarms();
                        Stop = 1;
                        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&AlarmThread, 0, 0, 0);
                    }
                }
            }
        }
        if(alarm2 == 1)
        {
            hourz = SendMessage(hHour2, CB_GETCURSEL, 0, 0);
            minutez = SendMessage(hMinute2, CB_GETCURSEL, 0, 0);
            pmz = SendMessage(hAMPM2, CB_GETCURSEL, 0, 0);

            if((LRESULT)AMPM == pmz)
            {
                if((strcmp(hourString, HoursList[hourz]) == 0) && (strcmp(minute, MinutesList[minutez]) == 0))
                {
                    if(ThreadRunning == 0)
                    {
                        //ReadAlarms();
                        alarm2 = 0;
                        SetAlarms();
                        ReadAlarms();
                        Stop = 1;
                        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&AlarmThread, 0, 0, 0);
                    }
                }
            }
        }

        if(alarm3 == 1)
        {
            hourz = SendMessage(hHour3, CB_GETCURSEL, 0, 0);
            minutez = SendMessage(hMinute3, CB_GETCURSEL, 0, 0);
            pmz = SendMessage(hAMPM3, CB_GETCURSEL, 0, 0);

            if((LRESULT)AMPM == pmz)
            {
                if((strcmp(hourString, HoursList[hourz]) == 0) && (strcmp(minute, MinutesList[minutez]) == 0))
                {
                    if(ThreadRunning == 0)
                    {
                        //ReadAlarms();
                        alarm3 = 0;
                        SetAlarms();
                        ReadAlarms();
                        Stop = 1;
                        CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&AlarmThread, 0, 0, 0);
                    }
                }
            }
        }
    }
}

void HotkeyHandler() // hides/unhides window on CTRL + ALT + A
{
    int ShowOrHide = 1;

    for(;; Sleep(10)) // you need sleeps in indefinate loops for non 100% CPU usage
    {
        if((GetKeyState(VK_CONTROL) & 0x8000) && (GetKeyState(VK_MENU) & 0x8000) && (GetKeyState(0x41) < 0))
        {
            //SW_SHOWNORMAL = 1, SW_HIDE = 0
            _asm xor [ShowOrHide], 1 // toggle 1, 0

            ShowWindow(hWnd, ShowOrHide);
            if(ShowOrHide == 1)
                SetForegroundWindow(hWnd);

            Sleep(250); // so 1 key press wont hide and show it

        }
    }
}



int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    int ClockWidth = 331, ClockHeight = 429, ScreenPosX, ScreenPosY;
    HBITMAP ClockBMP;
    HBRUSH ClockBrush;

    hInst = hInstance;

    ClockBMP = LoadBitmap(hInstance, MAKEINTRESOURCE(102));
    ClockBrush = CreatePatternBrush(ClockBMP);

    WNDCLASSEX wc;
    MSG Msg;

    wc.cbSize        = sizeof(WNDCLASSEX);
    wc.style         = 0;
    wc.lpfnWndProc   = WndProc;
    wc.cbClsExtra    = 0;
    wc.cbWndExtra    = 0;
    wc.hInstance     = hInstance;
    wc.hIcon         = LoadIcon(hInstance, MAKEINTRESOURCE(101));
    wc.hCursor       = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground = ClockBrush;
    wc.lpszMenuName  = NULL;
    wc.lpszClassName = L"AlarmClock_Class";
    wc.hIconSm       = LoadIcon(hInstance, MAKEINTRESOURCE(101));

    RegisterClassEx(&wc);

    int ScreenWidth = GetSystemMetrics(SM_CXSCREEN);
    int ScreenHeight = GetSystemMetrics(SM_CYSCREEN);
    ScreenPosX = (ScreenWidth / 2) - ClockWidth;
    ScreenPosY = (ScreenHeight / 2) - ClockHeight;

    // Even though WS_MINIMIZEBOX doesn't get displayed it lets you minimize by clicking the tab on task bar
    hWnd = CreateWindowExA(WS_EX_LEFT, "AlarmClock_Class", "$teve's Alarm Clock", WS_POPUP | WS_MINIMIZEBOX,
        ScreenPosX, ScreenPosY, ClockWidth, ClockHeight, NULL, NULL, hInstance, NULL);

    CreateButtonEx("X", 260, 60, 20, 15, 420);
    hDate = CreateTextEx(CurrentDate, 90, 140, 150, 20, 500); 
    hTime = CreateTextEx(CurrentTime, 120, 161, 90, 20, 501);

    CreateTextEx("Alarm 1:", 35, 210, 60, 24, 502);
    CreateTextEx("Alarm 2:", 35, 240, 60, 24, 503);
    CreateTextEx("Alarm 3:", 35, 270, 60, 24, 504);

    hTest = CreateButtonEx("TEST ALARM", 55, 182, 100, 24, 422);
    hSet = CreateButtonEx("SAVE ALARMS", 165, 182, 100, 24, 421);
    
    //Alarm 1
    hHour = CreateDropDownEx(0, 100, 210, 45, 300, 600);
    hMinute = CreateDropDownEx(0, 145, 210, 45, 300, 601);
    hAMPM = CreateDropDownEx(0, 190, 210, 60, 100, 602);
    hCheck = CreateCheckEx("OFF", 250, 210, 48, 25, 700);

    //Alarm2
    hHour2 = CreateDropDownEx(0, 100, 240, 45, 300, 603);
    hMinute2 = CreateDropDownEx(0, 145, 240, 45, 300, 604);
    hAMPM2 = CreateDropDownEx(0, 190, 240, 60, 100, 605);
    hCheck2 = CreateCheckEx("OFF", 250, 240, 48, 25, 701);

    //Alarm3
    hHour3 = CreateDropDownEx(0, 100, 270, 45, 300, 606);
    hMinute3 = CreateDropDownEx(0, 145, 270, 45, 300, 607);
    hAMPM3 = CreateDropDownEx(0, 190, 270, 60, 100, 608);
    hCheck3 = CreateCheckEx("OFF", 250, 270, 48, 25, 702);

    hLoad = CreateButtonEx("Load", 215, 300, 50, 25, 423);
    hMp3 = CreateEditEx(0, 70, 300, 135, 22, 900);
    hStartUp = CreateCheckEx("Start With Windows", 90, 340, 150, 25, 703);

    // Fill List Boxes With Strings
    for(int i = 0; i < 12; i++)
    {
        SendMessageA(hHour, CB_ADDSTRING, 0, (LPARAM)HoursList[i]);
        SendMessageA(hHour2, CB_ADDSTRING, 0, (LPARAM)HoursList[i]);
        SendMessageA(hHour3, CB_ADDSTRING, 0, (LPARAM)HoursList[i]);
    }
    SendMessageA(hHour, CB_SETCURSEL, 0, 0);
    SendMessageA(hHour2, CB_SETCURSEL, 0, 0);
    SendMessageA(hHour3, CB_SETCURSEL, 0, 0);

    for(int i = 0; i < 6; i++)
    {
        SendMessageA(hMinute, CB_ADDSTRING, 0, (LPARAM)MinutesList[i]);
        SendMessageA(hMinute2, CB_ADDSTRING, 0, (LPARAM)MinutesList[i]);
        SendMessageA(hMinute3, CB_ADDSTRING, 0, (LPARAM)MinutesList[i]);
    }
    SendMessageA(hMinute, CB_SETCURSEL, 0, 0);
    SendMessageA(hMinute2, CB_SETCURSEL, 0, 0);
    SendMessageA(hMinute3, CB_SETCURSEL, 0, 0);

    SendMessageA(hAMPM, CB_ADDSTRING, 0, (LPARAM)AMorPM[0]);
    SendMessageA(hAMPM, CB_ADDSTRING, 0, (LPARAM)AMorPM[1]);
    SendMessageA(hAMPM, CB_SETCURSEL, 0, 0);

    SendMessageA(hAMPM2, CB_ADDSTRING, 0, (LPARAM)AMorPM[0]);
    SendMessageA(hAMPM2, CB_ADDSTRING, 0, (LPARAM)AMorPM[1]);
    SendMessageA(hAMPM2, CB_SETCURSEL, 0, 0);

    SendMessageA(hAMPM3, CB_ADDSTRING, 0, (LPARAM)AMorPM[0]);
    SendMessageA(hAMPM3, CB_ADDSTRING, 0, (LPARAM)AMorPM[1]);
    SendMessageA(hAMPM3, CB_SETCURSEL, 0, 0);

    ReadAlarms();

    RegOpenKeyExA(HKEY_LOCAL_MACHINE, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_READ, &hk);
    RegQueryValueExA(hk, "AlarmClock", 0, 0, (LPBYTE)exePath, &BufSize);

    if(exePath[1] == 0x3A) // 0x3A == ":" which means its been added to the registry already
    {
        SendMessage(hStartUp, BM_SETCHECK, 1, 0);
    }

    RegCloseKey(hk);

    ShowWindow(hWnd, nCmdShow);
    UpdateWindow(hWnd);

    CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&MainThread, 0, 0, 0);
    CreateThread(0, 0, (LPTHREAD_START_ROUTINE)&HotkeyHandler, 0, 0, 0);

    // Message Pump
    while(GetMessage(&Msg, NULL, 0, 0) > 0)
    {
    
        TranslateMessage(&Msg);
        DispatchMessage(&Msg);
    }
    return Msg.wParam;
}

// I like to use functions like these to make the code above more readable
HWND CreateButtonEx(char Text[64], int x, int y, int wd, int ht, int id)
{
    return CreateWindowExA(0, "BUTTON", Text, WS_CHILD | WS_VISIBLE, x, y, wd, ht, hWnd, (HMENU)id, hInst, 0);
}

HWND CreateEditEx(char Text[64], int x, int y, int wd, int ht, int id)
{
    return CreateWindowExA(WS_EX_CLIENTEDGE, "EDIT", Text, WS_CHILD | WS_VISIBLE | ES_AUTOHSCROLL | ES_NOHIDESEL | WS_TABSTOP, x, y, wd, ht, hWnd, (HMENU)id, hInst, 0);
}

HWND CreateTextEx(char Text[64], int x, int y, int wd, int ht, int id)
{
    return CreateWindowExA(WS_EX_STATICEDGE, "STATIC", Text, WS_CHILD | WS_VISIBLE | SS_LEFT, x, y, wd, ht, hWnd, (HMENU)id, hInst, 0);
}

HWND CreateCheckEx(char Text[64], int x, int y, int wd, int ht, int id)
{
    return CreateWindowExA(0, "BUTTON", Text, WS_CHILD | WS_VISIBLE | BS_AUTOCHECKBOX, x, y, wd, ht, hWnd, (HMENU)id, hInst, 0);
}

HWND CreateDropDownEx(char Text[64], int x, int y, int wd, int ht, int id)
{
    return CreateWindowExA(0, "COMBOBOX", Text, WS_CHILD | WS_VISIBLE | CBS_DROPDOWNLIST | CBS_HASSTRINGS, x, y, wd, ht, hWnd, (HMENU)id, hInst, 0);
}

Man I love c++ :P

Link to comment
Share on other sites

I was working on a new DP for MSN, when i read this challenge, so though i might as well make more outta the image than just a DP that will be used for a couple of days.

Pretty much just a simple digital clock, created in Flex 3 SDK, nothing to special.

Mad-Monkey-Alarm.png

Yerp, as you can see its 2am, and yea my system Date is wrong, so for now ill though up the source, and tomorrow ill put up the files, and PSD's that i created for the UI.

Clock.mxml

<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="250" height="250" creationComplete="onCreationComplete();">
	<mx:Script source="ActionScript.as"/>

    <mx:Style>
        @font-face{
            fontFamily:quartz;
            src:url("../assets/quartz.ttf");
            font-style:normal;
            font-weight:normal;
        }
        .quartzLarge {
            fontFamily:quartz; 
            fontSize: 77.75pt;
        }
        .quartzSmall {
            fontFamily:quartz; 
            fontSize: 21.5pt;
            color: #0b333c;
        }
        .quartzSmallred {
            fontFamily:quartz; 
            fontSize: 21.5pt;
            color: #9B0000;
        }
    </mx:Style>
    <mx:Fade id="fadeOut" duration="1000" alphaFrom="1.0" alphaTo="0.0"/>
   	<mx:Fade id="fadeIn" duration="1000" alphaFrom="0.0" alphaTo="1.0"/>
	<mx:Image x="0" y="0" id="img_backGround" source="@Embed(source='../images/Alarm-Clock-Orb.png')"/>
	<mx:Image x="18" y="19" id="img_alert" source="@Embed(source='../images/alert.png')" visible="false"/>
	<mx:Label x="35" y="60" text="88:88" id="txt_timeClock" styleName="quartzLarge" textAlign="right"/>
	<mx:Label x="110" y="140" text="88-8-8888" id="txt_timeDate" styleName="quartzSmall" textAlign="right"/>
	<mx:Label x="198" y="115" id="txt_timeSec" text="88" styleName="quartzSmall" textAlign="right"/>
	<mx:Button id="btn_alarmActive" icon="@Embed(source='../images/alarm.png')" width="0" height="0" click="showAlarm(true);" x="213" y="111" alpha="0.3"/>
	<mx:Button x="62.5" y="170" label="Deactivate" id="btn_deactivate" styleName="quartzSmall" click="alarmDeactivate();" visible="false"/>
	<mx:Image x="9" y="62" id="img_plate" source="@Embed(source='../images/plate.png')" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Label x="27" y="68" text="00" id="txt_alarmHour" styleName="quartzLarge" textAlign="right" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Label x="112" y="60" text=":" id="txt_dots" styleName="quartzLarge" textAlign="right" width="18" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Label x="135" y="68" text="00" id="txt_alarmMinute" styleName="quartzLarge" textAlign="right" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_upHour" icon="@Embed(source='../images/plus.png')" width="0" height="0" click="alarmChange('hour', 'up')" x="49" y="162" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_downHour" icon="@Embed(source='../images/negative.png')" width="0" height="0" click="alarmChange('hour', 'down')" x="88" y="162" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_upMin" icon="@Embed(source='../images/plus.png')" width="0" height="0" click="alarmChange('minute', 'up')" x="157" y="162" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_downMin" icon="@Embed(source='../images/negative.png')" width="0" height="0" click="alarmChange('minute', 'down')" x="197" y="162" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_alarmNo" icon="@Embed(source='../images/no.png')" width="0" height="0" click="alarmSetup(false);" x="123" y="151" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_alarmYes" icon="@Embed(source='../images/yes.png')" width="0" height="0" click="alarmSetup(true);" x="123" y="168" hideEffect="{fadeOut}" showEffect="{fadeIn}" visible="false"/>
	<mx:Button id="btn_copy" icon="@Embed(source='../images/copyright.png')" width="0" height="0" click="showCopy();" x="205" y="208"/>

</mx:Application>

ActionScript.as

// ActionScript file
	import mx.controls.Alert;
	import mx.core.SoundAsset;

	private var ticker:Timer;
	private var currentTime = new Date();
	public var alertActive:Boolean = false;
	public var alarmSet:Boolean = false;

	public var timeHours:Number;
	public var timeMinutes:Number;
	public var timeSeconds:Number;
	public var timeYear:Number;
	public var timeMonth:Number;
	public var timeDay:Number;

	public var alertHours:Number = 0;
	public var alertMinutes:Number = 0;

	[Embed(source="../assets/loop.mp3")]
	[Bindable]
	public var Song:Class
	public var mySong:SoundAsset = new Song() as SoundAsset;
	public var channel:SoundChannel;

	public function onCreationComplete():void
	{
		findTime()
		findDate()
		updateTime();
		updateDate();
		ticker = new Timer(1000); 
        ticker.addEventListener(TimerEvent.TIMER, onTick);
        ticker.start();


	}

	public function updateTime():void
	{
		txt_timeClock.text = doubleUp(timeHours) + ":" + doubleUp(timeMinutes);
		txt_timeSec.text = doubleUp(timeSeconds)
		if (alarmSet == true) {checkAlert();}
	}

	public function updateDate():void
	{
		txt_timeDate.text = doubleUp(timeDay) + "-" + doubleUp(timeMonth) + "-" + timeYear;
	}

	public function doubleUp(single:Number):String
	{
		if (single <= 9) 
		{ 
			var double:String = "0" + String(single);
			return String(double);
		} else {
			return String(single);
		}

	}

	public function onTick(evt:TimerEvent):void 
    {
        timeSeconds += 1;
        if (timeSeconds >= 60) {timeSeconds = 0; timeMinutes +=1;}
        if (timeMinutes >= 60) {timeMinutes = 0; timeHours +=1;}
        if (timeHours >= 24) {timeHours = 0; findDate(); updateDate();}
        if (alertActive == true) {madMonkey();}
        updateTime();

    }

    public function findDate():void
    {
    	currentTime = new Date();
		timeYear = currentTime.getFullYear();
		timeMonth = currentTime.getMonth();
		timeDay = currentTime.getDay();
    }

    public function findTime():void
    {
    	currentTime = new Date();
		timeHours = currentTime.getHours();
		timeMinutes = currentTime.getMinutes();
		timeSeconds = currentTime.getSeconds();
    }

    public function checkAlert():void
    {
    	if 	(timeHours == alertHours && timeMinutes == alertMinutes)
    		{ 
    			alertActive = true;
    			btn_deactivate.visible = true;
    		}
    }

    public function madMonkey():void
    {
    	if (channel == null) {channel = mySong.play();}
    	if (img_alert.visible == true)
    	{
    		img_alert.visible = false
    		btn_deactivate.styleName="quartzSmall";
    		btn_alarmActive.alpha=0.3;
    	} else {
    		img_alert.visible = true
    		btn_deactivate.styleName="quartzSmallred";
    		btn_alarmActive.alpha=1;
    	}
    }

    public function alarmDeactivate():void
    {	
    	channel.stop();
    	channel = null;
    	img_alert.visible = false;
    	btn_deactivate.visible = false;
    	alarmSet = false;
    	alertActive = false;
    	alertHours = 0;
		alertMinutes = 0;
		btn_alarmActive.alpha=0.3;
		txt_alarmHour.text = doubleUp(alertHours);
		txt_alarmMinute.text = doubleUp(alertMinutes);
    }


    public function alarmChange(time:String, direction:String):void
    {
		if (time == 'hour') {
			if (direction == 'up') {
				if (alertHours != 24) {
					alertHours += 1;
				} else {
					alertHours = 0;
				}
			} else {
				if (alertHours != 0) {
					alertHours -= 1;
				} else {
					alertHours = 24;
				}
			}
		} else {
			if (direction == 'up') {
				if (alertMinutes != 59) {
					alertMinutes += 1;
				} else {
					alertMinutes = 0;
				}
			} else {
				if (alertMinutes != 0) {
					alertMinutes -= 1;
				} else {
					alertMinutes = 59;
				}
			}
		} 
		txt_alarmHour.text = doubleUp(alertHours);
		txt_alarmMinute.text = doubleUp(alertMinutes);
    }
    public function alarmSetup(Setup:Boolean):void
    {
    	if (Setup == true) {
    		alarmSet = true;
    		showAlarm(false);
    		btn_alarmActive.alpha=1;
    	} else {
    		alarmSet = false;
    		showAlarm(false);
    		btn_alarmActive.alpha=0.3;
    	}
    }

    public function showAlarm(Set:Boolean):void
    {
    	img_plate.visible = Set;
    	txt_alarmHour.visible = Set;
    	txt_dots.visible = Set;
    	txt_alarmMinute.visible = Set;
    	btn_upHour.visible = Set;
    	btn_downHour.visible = Set;
    	btn_upMin.visible = Set;
    	btn_downMin.visible = Set;
    	btn_alarmNo.visible = Set;
    	btn_alarmYes.visible = Set;

    }
    public function showCopy():void
    {
		Alert.show("Auther: David Stevenson \n Version: 1.0.0 \n Release: 19-06-08 \n Ste03_aus@hotmail.com",'Mad Monkey Alarm Clock');

    }

And finaly, the link to the working file: http://img502.imageshack.us/img502/4190/clockei4.swf

Link to comment
Share on other sites

i think i've done this one before, but here we go;

/*
  Name: randum
  Copyright: Fuck That
  Author: SableFoXx
  Date: 01/02/08 12:30
  Description: Guess the random number 1 to 10
  Version: 1.0  (working)
*/

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

int main ()
{
  int i, x, y; //int vairables
  srand ( time(NULL) ); //time seed
  i = rand() % 10 + 1; //make randum number
    while(1)
    {
           printf ("Guess the number (1 to 10):");
           scanf ("%d",&x);
           if(x==i) break;
           if (i<x) puts ("Guess lower");
           else if (i>x) puts ("Guess higher"); 
    }
    while(1)
    {
        printf("+++OMGz You WiN+++\n\n 1. Play Again\n 2. Exit\n ");
        scanf ("%d",&y);
        if (y==1)
          {
             system("start .\\randum.exe"); //start over
             return 0; //exit old window
          }         
        else
        return 0; //exit
     }
}

Link to comment
Share on other sites

Can anyone help me with learning C. I did find a tutorial at howstuffworks.com but when I compiled using G++ through Cygwin it gave errors. I tried Python but realized I couldn't do what I wanted to (programs without interrupters to download). Can anyone help me learn C? Thank You

Link to comment
Share on other sites

OK guys, I had to take some time to think about it! I think I thought of a good challenge. OK here goes...

Programming Language: C++ or Java or ANYTHING! I don't care at this point! ;)

Program: CLIENT->SERVER application

Must Have: It must make use of sockets, ex. WINSOCK (which is what I'm using)

Winner: best functioning server and client

Time: 4 weeks

I recommend making two separate executables. 1 being the client, the second being the server... it just makes more sense that way I think...

For example, a chat program could be a client server app... one person runs the server, a second runs the client...

the client would have to know the server computers IP address and port the server is listening on, then they could connect and send a message to the server, the server would receive the message and be able to send a message back to the client! but it can really be anything, as long as data is transferred across the pipes of the internet through sockets, it qualifies...

If anyone thinks its too difficult, just say you want to see an example source code, and I will post my program which I'm working on currently (but ill finish soon)

But the cache is if I post my example, no one will be able to make the program I post, so if I post an example chat program (not saying that's what it is) you'll have to make something else! You can however use the example as a guide for your program, and learn from it...

If anyone has worked with sockets in linux, that would be cool if you'd post, even better would be a linux server/client which communicated with a windows server/client... there probably isn't winsock in linux but theres gotta be something similar... I'm interested in cross-platform development, but not sure how to start coding for linux as all i know up until now is WINAPI...

Also when your testing your app (over the net) be sure to port forward whatever port you make your server listen on or else the client wont be able to connect, so just keep that in mind... ;)

Challenge Starts NOW! :D

Link to comment
Share on other sites

  • 2 weeks later...

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

  • Recently Browsing   0 members

    • No registered users viewing this page.

×
×
  • Create New...