/*
 *      XCountdown - X version of the popular Channel 4 quiz show
 *
 * This software comes with NO warranty whatsoever. I therefore take no
 * responsibility for any damages, losses or problems caused through use
 * or misuse of this program.
 *
 * I hereby grant permission for this program to be freely copied and
 * distributed by any means, provided no charge is made for it.
 *
 * Matthew Chapman, csuoq@csv.warwick.ac.uk
 *    June 1995.
 */

/* game.c -  various general purpose game functions */

#include "xcountdown.h"
#include "globals.h"

void UpdateScore(int ply,int amount);
void InitRound(void);

/* adjust score for given player, and update display */
void UpdateScore(int ply,int amount)
{
    int i;
	
    app_data.score[ply]+=amount;
    for (i=0; i<NP; i++)
	XcLcdUpdateValue(((ply==0) ? score1[i] : score2[i]),&app_data.score[ply]);
}

/* round initialization - clear inputs, and reset clock */
void InitRound()
{
    int i,j,k;
    XawTextBlock txt;
    char empty='\0';

    comp=0;
    letts_chosen=0;
    for (i=0; i<NP; i++)
	for (j=0; j<2; j++)
	    for (k=0; k<NL; k++)
		XtVaSetValues(lett[i][k][j],XtNlabel," ",SETBG(gray40),NULL);
    txt.firstPos=0;
    txt.format=FMT8BIT;
    txt.length=0;
    txt.ptr=&empty;
    for (i=0; i<NP; i++)
    {
	XawTextReplace(input1[i],0,999,&txt);
	XawTextReplace(input2[i],0,999,&txt);
	XtVaSetValues(tclock[i],XtNpercentageCompleted,0,NULL);
    }
}

/* functions to wait for given number of milliseconds, processing X events */
Boolean waiting;
void EndDelay()
{
    waiting=False;
}
void Wait(int delay)
{
    /* wait for specified time, processing X events */
    waiting=True;
    XtAppAddTimeOut(app_context,delay,(XtTimerCallbackProc)EndDelay,NULL);
    while (waiting==True)
	ProcessEvent();
}

/* advance the clock by a tick */
void Click()
{
    if (!stop_the_clock)
    {
	int i;
	
	comp += 50;
			
	for (i=0; i<NP; i++)
	    XtVaSetValues(tclock[i],XtNpercentageCompleted,comp,NULL);
	/* time up? */
	if (comp < 5000)
	    XtAppAddTimeOut(app_context,CLOCK_DELAY,(XtTimerCallbackProc)Click,NULL);
    }
}

/* process a event, if there is one pending */
void ProcessEvent()
{
    /* processes any pending events */
    if (XtAppPending(app_context)!=0)
	XtAppProcessEvent(app_context,XtIMAll);
    else
	/* sleep to greatly reduce processor load -
			   not essential but highly recommended
			*/
	usleep(10000);
}

/* action proc to redirect key presses to input box */
void KeyRedirect(Widget w, XEvent *event,String *params,Cardinal num_params)
{
    int dnum = (XtDisplay(w)==dpy[0]) ? 0 : 1;
    event->xany.window = XtWindow((dnum==0) ? input1[dnum] : input2[dnum]);
    XtDispatchEvent(event);
}

/* swap two ints */
void Swap(int *first,int *second)
{
    int tmp;
	
    tmp=*first;
    *first=*second;
    *second=tmp;		
}
