Quantcast
Channel: Programming Forums
Viewing all 51036 articles
Browse latest View live

PyPy - anyone had a look?

$
0
0
I am a Python noob for the time being and trying to improve in this area. By browsing the net, from time to time i come across PyPy. I still don't know where PyPy fits in but there is a bit of hype over it. People saying that PyPy will replace Python etc and encouraging others to give it a go. So my question is whether anyone tried it and what feedback can you give on the technology.

making a 2D bullet fire towards the X and Y position of the mouse?

$
0
0
Hi guys,
I need some help with a particular part of a C++ DirectX game. My course has tasked me with creating a game similar in look and function to the old missile command arcade game (something like this), however I have hit a bit of a wall in terms of getting the missile to fire in the direction I want it to. I'll preface this by saying I am more of a designer than a mathmatician/programmer... but I would like to improve my design skills by getting an understanding of what happens from a programming standpoint in order to make my game designs more feasable, so please forgive me in the likely event of me making a fundamentally rookie mistake >_</>. With that out of the way here is what I have done so far.

I have created a missile class that has an instance in the game state. When the game state calls it in, depending on the key press it creates a missile at the X and Y position of the silo the missile is being fired from. That part I have got to work exactly how I want it to.

What I struggle with is the syntax regarding how to define the missile's trajectory. I have created a vector made up of the cursor's X and Y position

D3DXVECTOR2 newPos;
//The above bit is declared within the missile class
newPos = InputManager::Get().GetMousePos();
// that code is called within the constructor. 



I have also done something similar for the missile's starting position and as far as I know, the declarations do their job as intended. Now for the part that stumps me... I'm not quite sure how to utilise this data to do what I want it to do.

In the update function of the missile class I have inserted a piece of code just to see if the vector actually works.

playerMissiles[1].pos.x -= (((newPos.x))*0.02);
playerMissiles[1].pos.y += (((newPos.y))*0.02);



I know that pice of code is incorrectt however at least I know that it does actually move across the screen with it's direction affected by the position of the cursor, so I suppose the question is:

Using the x and y position of the mouse, how can I create a translation that updates pos.x and pos.y to always follow the mouse position?

I know the answer lies in something along the lines of pos.x+= (/something to calculate the x tracectory/) and pos.y+= (/something to calculate the y position/) but I just don't know what it is.

I have created a short animation below to demonstrate the effect I am after.Click here to see it just to get the jist of what I'm talking about.

I have checked through numerous website and forums for people with similar problems to me but I have not found any good results. I have considered using angles as well but I thought that would simply be over complicating the problem.

I would be so grateful if anyone can provide any sort of assistance :)/>

Barcode scanner for ios and android

$
0
0
My requirement is to develop a barcode scanner for both android and ios mobile OS.
When I googled, I found corona SDK multiplatform, but I am not sure whether I can develop barcode scanner because I could not find an example for barcode scanner. Below are my doubts

1. Is corona SDK is good to make multiplatform application?
2. Is it possible develop barcode scanner sc they are mainly concentrating on gaming application?
3. If possible, whether I should use any third party control to access the camera functionality or to access any device functionality?
4. If not, suggest me a good mobile development SDK

Advertisement Plugin for Yourls Shorten Url Script?

$
0
0
Hi,
Just registered here and hope gurus will help me in my issue as I'm totally a newbie in php/javascript.
I installed Yourls (Url Shorterning Script yourls.org), its working fine. But I want to add a feature which can show an Advertisement page for 5-10 seconds before redirecting user to the destination page.
I have read on their (Yourls) site that plugins are best way to add any feature. But unfortunately, my knowledge of php is zero.
I will be very grateful if any one can help me..
Any suggestions or advices are warmly welcome.
This is their latest version of Yourls script:
http://code.google.com/p/yourls/downloads/detail?name=yourls-1.5.1.zip&can=2&q=

At my wits end. Adding to Access Database.

$
0
0
Ok so I have this code. And I keep getting 'Syntax Error in INSERT INTO statement'. I've thrice checked it and I cant see any problem ;[


Dim sql As String
        Dim carsDa As OleDb.OleDbDataAdapter
        Dim carsDs As New DataSet

        con.Open()

        sql = "SELECT * FROM cars"
        carsDa = New OleDb.OleDbDataAdapter(sql, con)
        carsDa.Fill(carsDs, "Cars2")


        Dim cb As New OleDb.OleDbCommandBuilder(carsDa)
        Dim dsNewRow As DataRow
        dsNewRow = carsDs.Tables("Cars2").NewRow()
        dsNewRow.Item("customerID") = txtID.Text
        dsNewRow.Item("make") = txtMake.Text
        dsNewRow.Item("model") = txtModel.Text
        dsNewRow.Item("reg") = txtReg.Text
        dsNewRow.Item("year") = txtYear.Text
        dsNewRow.Item("enginesize") = txtEngine.Text
        carsDs.Tables("Cars2").Rows.Add(dsNewRow)

        carsDa.Update(carsDs, "Cars2")

        con.Close()

    End Sub



Any help would be fantastic!

Thanks

Why am I getting an error

$
0
0
We are practicing friend functions this week. It seemed pretty easy when we were studying this but when I tried to compile it, it gave me an error and I have tried tweaking it but I am still at a lost.


//Lynette Wilkins
//Week 11
//Program that transers a guest from one room to another room

//Lynette Wilkins
//Week 8
#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

class HotelRoom
{
	friend int Transfer(HotelRoom&, HotelRoom&);
private:
	char room_num[3]; //Character array that stores a 3-character room number
	char transroom_num;
	char* guest; //Character pointer,which stores the name of the guest occupying the room
	int room_cap;
	int occup_stat;
	double daily_rt;
	int tranfer_room;

public:
	HotelRoom(char room[], char* g_p, int roomcap, int occup, double rate = 89.00);
	~HotelRoom();
	void Display_Number();  //Displays room number and add the method Display_Guest()
	int Get_Capacity();
	int Get_Status();
	double Get_Rate();
	int Change_Status(int);
	double Change_Rate(double);
	void Display_Guest();

};

HotelRoom::HotelRoom(char room[], char* g_p, int roomcap,int occup, double rate )
{
	strcpy(room_num, room); //copy first argument into room_num[]
	guest = new char[strlen(g_p) + 1]; //reserve space for the guest name
	strcpy(guest, g_p); //copy fourth argument into new space
    room_cap = roomcap;
	daily_rt = rate;
	occup_stat = occup;

}

HotelRoom::~HotelRoom()
{
	cout << endl<<endl;
	cout << "Guest in room "<<room_num << " has checked out." <<endl;
	delete [] guest;
}

 void HotelRoom::Display_Number()
{
	cout << room_num;
}

int HotelRoom::Get_Capacity()
{
	return room_cap;
}

int HotelRoom::Get_Status()
{
	
	return occup_stat;
}



int HotelRoom::Change_Status(int occup)
{
	occup_stat = occup;

	if (occup > room_cap)
	{
		return -1;
	}
	else
	
	return occup_stat;
	
}

double HotelRoom::Get_Rate()
{
	return daily_rt;
}

double HotelRoom::Change_Rate(double rate)
{
	daily_rt = rate;
		return daily_rt;
}

int Transfer(char room, char transroom)

{
	

	room = transroom;
	return room;
}

void HotelRoom::Display_Guest()
{
	cout<< guest;
}
int main()
{
	cout<< setprecision(2)
		<<setiosflags(ios::fixed)
		<<setiosflags(ios::showpoint);
	
char room[4]; 
char buffer[100]; //temporarily stores guest name
int roomcap = 4;
char transroom[4];
int occup;
double rate = 89.00;


cout<<"\nEnter the room number: "<<endl;
cin.getline(room, 5);

cout<<"\nEnter the amount of guest to occupy this room: "<<endl;
cin>>occup;


cout<<"\nEnter the primary guest name: "<<endl;
cin.ignore();
cin.getline(buffer, 100);

cout<<"\nThe guest has decided to transfer rooms"<<endl;
cout<<"\nEnter the room to transfer the guest to"<<endl;
cin.getline(transroom,5);

HotelRoom room1(room, buffer, roomcap, occup, rate); //initialize the object

if (room1.Change_Status(occup) == -1)
{
	cout<<"You have exceeded the room capacity"<<endl;
}
else
{

cout <<"\nThe room number is ";
room1.Display_Number();
cout<<"."<<endl;
cout<<"\nThe name of the primary guest is ";
room1.Display_Guest();
cout <<"."<<endl;
cout<<"\nThe number of guest in the room is "<<room1.Change_Status(occup)<<"."<<endl;
cout<<"\nThe daily rate for room "<<room<< " is "<<room1.Get_Rate()<<"."<<endl<<endl;

cout<<"\nYou have tranferred the guest from room"<<room1.Display_Number()<<"to"<<Transfer(room, transroom)<<endl;
}





cout<<"\nRoom ";
room1.Display_Number();
cout<<" is vacant."<<endl;





system("PAUSE");

	
	return 0;
}




The error is saying

"(159): error C2679: binary '<<' : no operator found which takes a right-hand operand of type 'void' (or there is no acceptable conversion)"

Any help would be greatly appreciated.

Thanks in advance!!

struggling to debug code problem

$
0
0
hi all

so here is my challeneg to debug this code i will first give u what i was given then i will show what i managed to do and what error i get

public class Pal {

    public static void Main() {
        Console.WriteLine("How many chars? ");
        int size =int.Parse(Console.ReadLine());
            char [] a = new char[size];
        for (int i = 0; i < a.Length; i++) {
            Console.WriteLine(" Enter Next Character");
            
                a[i] = int.Parse(Console.ReadLine());
        }
        Console.Write(" the word is ");
        for (int i = 0; i < a.Length; i++)
            
            Console.Write(a[i]);

        for (int i = 1;  i < a.Length/2; i++)
            if (a[i] != a[a.Length-i]){
                Console.WriteLine(" is not a palidrome");
                Environment.Exit(0);
            }
        Console.WriteLine(" is a palindrome");
        Console.ReadLine();
    }
}




here is what i managed to get to

public class Pal {

    public static void Main() {
        Console.WriteLine("How many chars? ");
        int size =int.Parse(Console.ReadLine());
            char [] a = new char[size];
        for (int i = 0; i < a.Length; i++) {
            Console.WriteLine(" Enter Next Character");
            
                a[i] = char.Parse(Console.ReadLine());
        }
        Console.Write(" the word is ");
        for (int i = 0; i < a.Length; i++)
            
            Console.Write(a[i]);

        for (int i = 1;  i < a.Length; i++)
            if (a[i] != a[a.Length-i]){
                Console.WriteLine(" is not a palidrome");
                Environment.Exit(0);
            }
        Console.WriteLine(" is a palindrome");
        Console.ReadLine();
    }
}



now i am using the example with this as 4 letters o,t,t,o hoping for it to work but i am getting it display "IS not a palindrome" when it should be?

thanks

Tic-Tac-Toe - play of the computer

$
0
0
I wanted to know how to improve play of the computer . Because when I raise the level of play on the computer instead it should play your best, which does not occur. I put the move on a list of tree increasing it each interaction according to the current board and the level of difficulty. For example, if the level increases it generates more occurrences to measure.



* MelhorJogada (): Estimates the best move to be made following

* Arguments: tab (input) - the board that represents the root of the game tree
* Current
* profundidade (input) - the depth of the game tree
*jogador (input) - the player whose turn
* NovoTab (output) - original board changed to contain the best play




* ConstroiArvore (): Returns a pointer to a game tree

* Arguments: tab (input) - the board that represents the root of the tree depth (input) - the depth of the tree

* Return: pointer to the root of the tree created

* Expands (): Expands a node of the game tree, creating all positions that can be obtained from the board of the node received as argument. The generated we become children of the node received as argument. So, this function is called recursively generated using the nodes as arguments until the desired depth is reached.

* Arguments: p (input / output) - Pointer to the node to be expanded
* Level (entry) - node level
* profundidae (in) - depth expansion


* GeraFilhos (): Returns a pointer to a list of nodes that are children of the node whose board is passed as argument.

* Arguments: tab (input) - the board of which will be generated nodes
* Return: pointer to the list of nodes generated



* AcrescentaNaLista (): Adds a node to the list we received as an argument and returns a pointer to the list plus
* Arguments: list (input / output) - Pointer to the beginning of the list of nodes
* Tab (input) - the board before the move
* Row, column (input) - the row and column where the play will be
* Move (input) - the move to be made (X or O)
*
* Return: pointer to the list node resulting from increased play

* ProcuraMelhorLance (): Looking for the best move in the tree whose root is
Received as argument
* Arguments: tree (input) - pointer to the game tree
* Player (inlet) - the player (X or W) having the
* Better (output) - Pointer to the node that represents the best play
* Value (output) - the value of the best node


* Evaluate (): Evaluates statically board position for the given player.
* The result of the evaluation is the number of rows, columns and diagonals that can be filled by the player minus the number of these that can be filled by your opponent.

* Arguments: tab (input) - the board that will be evaluated
* Player (input) - the player whose turn it is

* Return: The value of the evaluation
#include <stdio.h>
#include <stdlib.h>


typedef enum {VAZIO = ' ', O = 'O', X = 'X'} tConteudo;
typedef enum {MIN, MAX} tTipoDeNo;
typedef enum {FAIL, SUCESS} tValida;
typedef enum {EASY = 1, MEDIUM = 2, HARD = 3} tDificult;


typedef  struct  no
{
    tConteudo tabuleiro[3][3];
    tTipoDeNo tipoDeNo;
    struct  no  *filhoEsquerda;
    struct  no  *proximoIrmao;
} tNo, *tArvore;


tArvore AcrescentaNaLista( tArvore *lista, tConteudo tab[][3],
                           unsigned linha, unsigned coluna, tConteudo jogada )
{
    tArvore   aux;
    unsigned  i, j;
    aux = (tArvore)malloc(sizeof(tNo));

    for (i = 0; i < 3; ++i)
        for (j = 0; j < 3; ++j)
            aux->tabuleiro[i][j] = tab[i][j];
    aux->tabuleiro[linha][coluna] = jogada;
    aux->proximoIrmao = *lista;
    aux->filhoEsquerda = NULL;
    *lista = aux;
    return aux;
}



tArvore GeraFilhos(tConteudo tab[][3])
{
    tArvore   listaDeNos = NULL;
    tConteudo quemJoga;
    unsigned  i, j;
    quemJoga =  O ;
    for (i = 0; i < 3; ++i)
        for (j = 0; j < 3; ++j)
            if (tab [i][j] == VAZIO)
                listaDeNos = AcrescentaNaLista(&listaDeNos, tab, i, j, quemJoga);
    return listaDeNos;
}

void Expande(tArvore p, unsigned nivel, unsigned profundidade)
{
    tArvore filhos ;
    if (nivel <= profundidade)
    {
        filhos = GeraFilhos(p->tabuleiro);
        p->filhoEsquerda = filhos;

        while(filhos)
        {
            if (p->tipoDeNo == MAX)
                filhos->tipoDeNo = MIN;
            else
                filhos->tipoDeNo = MAX;

            filhos->filhoEsquerda = NULL;

            Expande(filhos, nivel + 1, profundidade);
            filhos = filhos->proximoIrmao;
        }
    }
}


tArvore ConstroiArvore(tConteudo tab[][3], unsigned profundidade)
{
    tArvore  arvore;
    unsigned i, j;
    arvore = malloc(sizeof(tNo));

    for (i = 0; i < 3; ++i)
        for (j = 0; j < 3; ++j)
            arvore->tabuleiro[i][j] = tab[i][j];
    arvore->tipoDeNo = MAX;
    arvore->filhoEsquerda = NULL;
    arvore->proximoIrmao = NULL;
    Expande(arvore,  1, profundidade);
    return arvore;
}

int Avalia(tConteudo tab[][3], tConteudo jogador)
{
    unsigned  i, j;
    tConteudo oponente;
    int valor = 0, valorOponente = 0;

    for (i = 0; i < 3; ++i)
        if ( ((tab[i][0] == jogador) || (tab[i][0] == VAZIO)) &&
                ((tab[i][1] == jogador) || (tab[i][1] == VAZIO)) &&
                ((tab[i][2] == jogador) || (tab[i][2] == VAZIO)) )
            valor++;
    /* Verifica quantas colunas o jogador pode preencher */
    for (j = 0; j < 3; ++j)
        if ( ((tab[0][j] == jogador) || (tab[0][j] == VAZIO)) &&
                ((tab[1][j] == jogador) || (tab[1][j] == VAZIO)) &&
                ((tab[2][j] == jogador) || (tab[2][j] == VAZIO)) )
            valor++;
    /* Verifica quantas diagonais o jogador pode preencher */
    if ( ((tab[0][0] == jogador) || (tab[0][0] == VAZIO)) &&
            ((tab[1][1] == jogador) || (tab[1][1] == VAZIO)) &&
            ((tab[2][2] == jogador) || (tab[2][2] == VAZIO)) )
        valor++;
    if ( ((tab[0][2] == jogador) || (tab[0][2] == VAZIO)) &&
            ((tab[1][1] == jogador) || (tab[1][1] == VAZIO)) &&
            ((tab[2][0] == jogador) || (tab[2][0] == VAZIO)) )
        valor++;
    oponente =  X;

    for (i = 0; i < 3; ++i)
        if ( ((tab[i][0] == oponente) || (tab[i][0] == VAZIO)) &&
                ((tab[i][1] == oponente) || (tab[i][1] == VAZIO)) &&
                ((tab[i][2] == oponente) || (tab[i][2] == VAZIO)) )
            valorOponente++;

    for (j = 0; j < 3; ++j)
        if ( ((tab[0][j] == oponente) || (tab[0][j] == VAZIO)) &&
                ((tab[1][j] == oponente) || (tab[1][j] == VAZIO)) &&
                ((tab[2][j] == oponente) || (tab[2][j] == VAZIO)) )
            valorOponente++;

    if ( ((tab[0][0] == oponente) || (tab[0][0] == VAZIO)) &&
            ((tab[1][1] == oponente) || (tab[1][1] == VAZIO)) &&
            ((tab[2][2] == oponente) || (tab[2][2] == VAZIO)) )
        valorOponente++;
    if ( ((tab[0][2] == oponente) || (tab[0][2] == VAZIO)) &&
            ((tab[1][1] == oponente) || (tab[1][1] == VAZIO)) &&
            ((tab[2][0] == oponente) || (tab[2][0] == VAZIO)) )
        valorOponente++;
    return (valor - valorOponente);
}

void ProcuraMelhorLance(tArvore arvore, tConteudo jogador, tArvore *melhor,
                        int *valor)
{
    tArvore  p, melhor2;
    int      valor2;
    if (!arvore->filhoEsquerda)
    {
        *valor = Avalia(arvore->tabuleiro,jogador);
        *melhor = arvore;
    }
    else
    {
        p = arvore->filhoEsquerda;
        ProcuraMelhorLance(p, jogador, melhor, valor);
        *melhor = p;

        if (arvore->tipoDeNo == MIN)
            *valor = (-1)*(*valor);
        p = p->proximoIrmao;
        while (p)
        {
            ProcuraMelhorLance(p, jogador, &melhor2, &valor2);
            if (arvore->tipoDeNo == MIN)
                valor2 = (-1)*valor2;
            if (valor2 > *valor)
            {
                *valor = valor2;
                *melhor = p;
            }
            p = p->proximoIrmao;
        }
        if (arvore->tipoDeNo == MIN)
            *valor = (-1)*(*valor);
    }
}

void DestroiArvore(tArvore* raiz){

     if(*raiz != NULL){
             if((*raiz)->filhoEsquerda != NULL)
                DestroiArvore(&((*raiz)->filhoEsquerda));
             if((*raiz)->proximoIrmao != NULL)
                DestroiArvore(&((*raiz)->proximoIrmao));
             free(*raiz);
             *raiz = NULL;
     }
}



void MelhorJogada( tConteudo tab[][3], unsigned profundidade, tConteudo jogador,
                   tConteudo novoTab[][3] )
{
    tArvore  arvore, melhorLance;
    unsigned i, j;
    int      valor;

    arvore = ConstroiArvore(tab, profundidade);

    ProcuraMelhorLance(arvore, jogador, &melhorLance, &valor);
    for (i = 0; i < 3; ++i)
        for (j = 0; j < 3; ++j)
            novoTab[i][j] = melhorLance->tabuleiro[i][j];
    DestroiArvore(&arvore);
}

void Apresentacao(void)
{

    char enter;

    printf("Bem-vindo ao Jogo da Velha:\n");
    printf("O jogador comeca!!! \nEscolha se quer ser 'X' ou 'O'\nPronto p/comecar...");
    printf("Aperte ENTER p/ iniciar...");
    scanf("%c", &enter);
    if(enter == '\n')
    {
        system("cls");
    }

}
void InicializaTabuleiro(tConteudo tabuleiro[][3])
{

    unsigned  i, j, nOs = 0, nXs = 0;
    printf("\t\t\t\tTABULEIRO INICIALIZADO\n\n");
    for (i = 0; i < 3; ++i)
    {

        if(i == 1 || i ==2 )
        {
            printf("--- --- ---\n");
        }

        for (j = 0; j < 3; ++j)
        {
            tabuleiro[i][j] = VAZIO;
            if( j ==1)
                printf("| %c |", tabuleiro[i][j]);
            else
                printf(" %c ", tabuleiro[i][j]);
        }

        printf("\n");
    }

}

void ApresentaJogo(tConteudo tabuleiro[][3])
{

    unsigned  i, j;

    for (i = 0; i < 3; ++i)
    {

        if(i == 1 || i ==2 )
        {
            printf("--- --- ---\n");
        }

        for (j = 0; j < 3; ++j)
        {

            if( j ==1)
                printf("| %c |", tabuleiro[i][j]);
            else
                printf(" %c ", tabuleiro[i][j]);
        }

        printf("\n");
    }

}


void EscolheJogada(tConteudo tabuleiro[][3], tConteudo  jogador)
{

    tValida cond = FAIL;
    int opcao;


    do{

            printf("Escolha a jogada 1 a 9:\n");
            scanf("%d", &opcao);


            switch(opcao)
            {
            case 1:
                if(tabuleiro[0][0] == VAZIO)
                {
                    tabuleiro[0][0] = jogador;
                    cond = SUCESS;
                }
                break;
                 case 2:
                if(tabuleiro[0][1] == VAZIO)
                {

                    tabuleiro[0][1] = jogador;
                    cond = SUCESS;
                }
                break;
            case 3:
                if(tabuleiro[0][2] == VAZIO){
                    tabuleiro[0][2] = jogador;
                    cond = SUCESS;
                }
                break;
            case 4:
                if(tabuleiro[1][0] == VAZIO){
                    tabuleiro[1][0] = jogador;
                    cond = SUCESS;
                }
                break;
            case 5:
                if(tabuleiro[1][1] == VAZIO)
                {

                    tabuleiro[1][1] = jogador;
                    cond = SUCESS;
                }
                break;
            case 6:
                if(tabuleiro[1][2] == VAZIO)
                {
                    tabuleiro[1][2] = jogador;
                    cond = SUCESS;
                }
                break;
            case 7:
                if(tabuleiro[2][0] == VAZIO)
                {

                    tabuleiro[2][0] = jogador;
                    cond = SUCESS;
                }
                break;
            case 8:
                if(tabuleiro[2][1] == VAZIO)
                {

                    tabuleiro[2][1] = jogador;
                    cond = SUCESS;
                }
                break;
            case 9:
                if(tabuleiro[2][2] == VAZIO)
                {
                    tabuleiro[2][2] = jogador;
                    cond = SUCESS;
                }
                break;
            }
        }while (cond!= SUCESS);


}

unsigned JogoTerminado(tConteudo  tabuleiro[][3])
    {

        unsigned  i, j;
        tConteudo cont = VAZIO;

        unsigned jogadas =0;
        for (i = 0; i < 3; ++i)
            for (j = 0; j < 3; ++j)
                if (tabuleiro[i][j] == VAZIO)
                {
                    jogadas++;
                }

        return jogadas;
    }


tConteudo EhVencedor(tConteudo Matriz[][3])
{
    int linha, coluna;
    tConteudo vez = X;
    int ct=0;
    while (ct < 2){

     for (linha = 0; linha < 3; linha++){
     if ((Matriz[linha][0] == vez) && (Matriz[linha][1] == vez) && (Matriz[linha][2] == vez))
     return vez;

  for (coluna = 0; coluna < 3; coluna++){
    if ((Matriz[0][coluna] == vez) && (Matriz[1][coluna] == vez) && (Matriz[2][coluna] == vez))
      return vez;
  }
  if ((Matriz[0][0] == vez) && (Matriz[1][1] == vez) && (Matriz[2][2] == vez)){
	 return vez;
    }
  if ((Matriz[0][2] == vez) && (Matriz[1][1] == vez) && (Matriz[2][0] == vez)){
	return vez;
}
     }
	vez = O;
	ct++;

}
   return VAZIO;
}



void AtualizaTabuleiro(tConteudo tabuleiro[][3], tConteudo novoTabuleiro[][3]){

        unsigned  i, j;

        for (i = 0; i < 3; ++i)
            for (j = 0; j < 3; ++j)
            tabuleiro[i][j] = novoTabuleiro[i][j];

}




    int main (void)
    {

        tConteudo tabuleiro[3][3];
        tConteudo novoTabuleiro[3][3];
        tConteudo jogador = X;
        tConteudo oponente = O;
        tConteudo campeao = VAZIO;
        tDificult prof = HARD;
        int opcao;
        int flag =  0;

        //Apresentacao();
            //printf("%d", (int)prof);
        InicializaTabuleiro(tabuleiro);
        //InicializaTabuleiro(novoTabuleiro);

        /*
        printf("\nEscolha a Dificuldade:\n 1 - FACIL\n2 - MEDIO\n3 - DIFICIL \n");
        scanf("%d", &prof);*/

        printf("%d", JogoTerminado(tabuleiro));
        printf("\nVc quer Iniciar?:\n 1 - SIM\n0 - NAO \n");
        scanf("%d", &flag);



        while( JogoTerminado(tabuleiro) > 0)
        {
            printf("Quantidade de jogadas= %d\n", JogoTerminado(tabuleiro));
            if (flag == 1)
            {
                EscolheJogada(tabuleiro, jogador);
                flag = 0;
                //ApresentaJogo(tabuleiro);
            }
            else
            {
                MelhorJogada( tabuleiro, (int)prof,oponente,novoTabuleiro);
                //EscolheJogada(tabuleiro, oponente);
                //
                //ApresentaJogo(novoTabuleiro);
                AtualizaTabuleiro(tabuleiro, novoTabuleiro);

                flag = 1;
            }

            ApresentaJogo(tabuleiro);
            campeao = EhVencedor(tabuleiro);

            if(campeao == O ){
            printf("COMPUTER WIN");
            break;
            }else if(campeao == X){
            printf("YOU WIN!");
            break;
            }


        }


if(campeao == VAZIO){
    printf("DRAW!!!");
}



        system("PAUSE");
        return 0;
}


Apply Named Template to every Control on UserControl

$
0
0
I have named Styles and Templates in my App.xaml file. I can apply these to each control throughout my project. I have a UserControl with X number of Buttons. Instead of specifying each Button's style, I was able to use BasedOn:
<UserControl ...>
   <UserControl.Resources>
      <Style TargetType={x:Type Button}" BasedOn="{StaticResource styBigButtons}">
         <Setter Property="Margin" Value="10" />
      </Style>
   </UserControl.Resources>
<Grid>
   ///This is a very condensed example so we can get to the point
   <Button Name="btn1" Content="1" Template="{StaticResource ctRedButton}" />
   ...
   <Button Name="btn9" Content="9" Template="{StaticResource ctRedButton}" />
</Grid>
</UserControl>


This has saved a lot of typing to specify which style to use on this page. Is there a way to set all Buttons' Templates on this page using a named Template I already have? It would make sense for this to be possible.

Winsock

$
0
0
Hello.

How do I send special characters through winsock?
Here's my code:

WSADATA wsaData;
WSAStartup(MAKEWORD(2, 2), &wsaData);

SOCKET Socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
SOCKADDR_IN server_info;
server_info.sin_family = AF_INET;
hostent* host = gethostbyname("myhost.com");
if (host != NULL)
{
	server_info.sin_addr.s_addr = *((DWORD*)host->h_addr);
}
server_info.sin_port = htons(12345);

connect(Socket, (SOCKADDR*)&server_info, sizeof(SOCKADDR_IN));



Until here, everything good, but when I try to send a special character like "ç" or "á", instead it displays this symbol: "�".

CHAR buffer[1024];
strcpy_s(buffer, 1024, "rándom");
send(Socket, buffer, strlen(buffer), NULL);



The receiver would then read "r�ndom".

What am I doing wrong?

Finding child Nodes of a node in a tree

$
0
0
Hello all I need to find the child nodes of a node in a binary tree.I was just wondering if this will return the number of child nodes thanks.
        public int FindChildNodes()
        {
            if (RightNode == null && LeftNode == null)
            {
                return 1;
            }
            else
            {
                return RightNode.FindChildNodes() + LeftNode.FindChildNodes();
            }
        }

Serious problem with Hangman.java

$
0
0
[import java.util.Scanner;
import java.util.Random;

public class HangmanMy {
  public static void main (String[] args){
    System.out.println("Welcome to the game Hangman :)/>/>/>/>");
    Scanner input = new Scanner(System.in);
    boolean done = false;
    String guess;
    String guesses = "";
    char letter;
    int wrongGuess = 0;
    StringBuffer dashes;
    System.out.println("Choose a category -> places / games / animals / subjects ");
    String words = WordsToChoose(input.nextLine());
    dashes = makeDashes(words);
    while (! done)
    {
      System.out.println("Here is your word: " + dashes);
      System.out.println("Guesses so far: " + guesses);
      System.out.print("enter a guess (letter or word): ");
      guess = input.next().replaceAll("\\W", "");
      // process the guess
      
      if (guess.length() > 1)
      {
        if (guess.equalsIgnoreCase(words))
          System.out.println("you win!");
        else 
          System.out.println("Thats the wrong guess");
        done=true;
      }
      else // process single letter guess
      {
        letter = guess.charAt(0);
        guesses += letter;
        if (words.indexOf(letter) < 0)  // not there
        {
          wrongGuess++;
          if(wrongGuess < 6)
            System.out.print("Bad guess: ");
          else if(wrongGuess >= 6)System.out.println("Too many Guesses,The real word was: " + words);
        }
        else // letter is in the words
        {
          // put it in dashes where it belongs
          matchLetter(words, dashes, letter); 
        }
        if(words.equalsIgnoreCase(dashes.toString())){ 
          System.out.print("\nyou win!");
          done = false;
        }
      }
    }
  } 
  public static void matchLetter(String words, StringBuffer dashes, char letter)
  {
    for (int index = 0; index < words.length(); index++)
      if (words.charAt(index) == letter)
      dashes.setCharAt(index, letter);
          words = words.replaceAll("\\W","");
    System.out.print("Good guess: ");
  }
  public static StringBuffer makeDashes(String s)
  {
    StringBuffer dashes = new StringBuffer(s.length());
    for (int count=0; count < s.length(); count++)
      dashes.append('-');
    return dashes;
  }
  
  public static String WordsToChoose(String category)
  {
    Random generator = new Random();
    String name = "";
    if (category.equalsIgnoreCase("places"))
    {
      String places[] = {"Barc elona", "Lond on", "Par is", "Los Angeles", "Miami Beach", "San Diego", "Sydney", "Puerto Rico"};
      name = places[generator.nextInt(8)];
    }
    else if (category.equalsIgnoreCase("games"))
    {
      String games[] = {"Call of duty", "Halo", "FIFA", "Gta", "AssassinsCreed", "Need for speed", "AngryBirds", "FruitNinja"};
      name = games[generator.nextInt(8)];
    }
    else if (category.equalsIgnoreCase("animals"))
    {
      String animals[] = {"eagle", "tiger", "lion", "Jaguar", "rhinoceros", "sharks", "dolphin", "whale"};
      name = animals[generator.nextInt(8)];
    }
    else if (category.equalsIgnoreCase("subjects"))
    {
      String subjects[] = {"physics", "Computer Science", "chemistry", "gym", "english", "religion", "computer tech", "accounting"};
      name = subjects[generator.nextInt(8)];
    }
    return name.toLowerCase();
  }  
} 


My program will not end and also the when there is too many guesses the right word shows on top of everything not on the bottom and also it dosent end after it keeps on going
Could you tell me what i did wrong??

Also the program creates a dash for the space fix that also

JScrollPane's JScrollBar position error

$
0
0
Here's the problem code (there's more of it, but I figure this illustrates enough of the problem):
JMenuItem contentsItem = new JMenuItem("Contents");
contentsItem.setMnemonic(KeyEvent.VK_C);
contentsItem.setAccelerator(
		KeyStroke.getKeyStroke(
				KeyEvent.VK_F1, 0));

contentsItem.addActionListener(new ActionListener(){
	
	public void actionPerformed(ActionEvent ev){
		
		Container container = (Container)ev.getSource();
		
		do{
			if(container instanceof JPopupMenu){
				container = (Container)((JPopupMenu)container).getInvoker();
			}else if (container instanceof JMenuBar){
				container = ((JMenuBar)container).getTopLevelAncestor();
			}else {
				container = container.getParent();
			}
		}while(!(container instanceof JFrame));
		
		JTextPane helpContents = new JTextPane();
		helpContents.setEditable(false);
		helpContents.setEditorKit(new HTMLEditorKit());
		helpContents.setText("<html><body>" +
				"<h2>General Information</h2>" +
				"<p>" + APPLICATION_TITLE + " is an application coded in pure Java that is designed to enable the user to take screenshots of their desktop and save them to the local filesystem.</p>" +
				"<p>Upon pressing the <strong>Snap</strong> button, the application will hide itself from user view and take a screenshot. Dependent on the user options selected, the application will reappear once it has captured and written the screenshot to the local filesystem.</p>" +
				"<h2>Capture Area</h2>" +
				"<p>In the area titled <strong>Region</strong> there are two buttons that control the program's area capture behavior:</p>" +
				"<ul>" +
				"<li>Redefine</li>" +
				"<li>Fullscreen</li>" +
				"</ul>" +
				"<p><strong>Redefine</strong> brings up a dialog that allows the user to define a specific area of the screen to be captured. The area that the dialog window takes up on the user's screen is indicative of the region that the application will capture.</p>" +
				"<p><strong>Fullscreen</strong> ensures that the area to be captured is the entire screen width and height.</p>" +
				"<h2>Capture Timing</h2>" +
				"<p>In the area titled <strong>Timing</strong> there three radio buttons and two spinners that work in tandem with the <strong>Snap</strong> button to control the program's timed capture behavior:</p>" +
				"<ul>" +
				"<li>Immediate</li>" +
				"<li>Delay</li>" +
				"<li>Repeat</li>" +
				"</ul>" +
				"<ul>" +
				"<li>Frequency</li>" +
				"<li>Period</li>" +
				"</ul>" +
				"<p><strong>Immediate</strong> is selected when the user wishes to take a screenshot upon immediate pressing of the <strong>Snap</strong> button.</p>" +
				"<p><strong>Delay</strong> is selected when the user wishes to capture a screenshot after a preset amount of time has passed. The amount of time is controlled by the <strong>Frequency</strong> spinner.</p>" +
				"<p><strong>Repeat</strong> is selected when the user wishes to capture a series of screenshots for a given length of time. The total time that the application will capture screenshots is controlled by the <strong>Period</strong> spinner. The delay between each successive screenshot is controlled by the <strong>Frequency</strong> spinner.</p>" +
				"<h2>Saving Screenshots</h2>" +
				"<p>By default, screenshots are saved to the directory where the application resides. Users can modify this by using the <em><span style=\"text-decoration:underline;\">F</span>ile</em> menu's <em><span style=\"text-decoration:underline;\">S</span>ave To</em> option.</p>" +
				"<p>Screenshot filenames are automatically generated and saved as PNG images. The structure of the filename is a sequence of numbers (appended with the .png extension) which represent the following:</p>" +
				"<p>The smallest unit of time used for capturing screenshots is the millisecond. The user's machine, however, may not have the resources available to capture successive screenshots at such a pace. The application's performance will vary according to the user's machine setup.</p>" +
				"<ul>" +
				"<li>{1,4} Year screenshot was captured</li>" +
				"<li>{5,6} Month screenshot was captured</li>" +
				"<li>{7,8} Day screenshot was captured</li>" +
				"<li>{9,10} Hour screenshot was captured</li>" +
				"<li>{11,12} Minute screenshot was captured</li>" +
				"<li>{13,14} Second screenshot was captured</li>" +
				"<li>{15,18} Millisecond screenshot was captured</li>" +
				"</ul>" +
				"<h2>Warning</h2>" +
				"<p>Screenshot filename generation makes use of the local system time. There is no prompt for overwrite should two files share the same name. A user must take care when capturing screenshots between sessions, or in already populated directories, because the possibility of overwriting files does exist.</p>" + 
				"</body></html>");
		JScrollPane helpPane = new JScrollPane(helpContents);
		helpPane.setPreferredSize(new Dimension(400, 200));
		
		JOptionPane.showMessageDialog((JFrame)container, helpPane, "Help", JOptionPane.PLAIN_MESSAGE, null);
	}
});
So I'm creating a "Contents" menu item within my "Help" menu. Give it a shortcut of C and an accelerator of F1. I add to it a listener for when it is pressed. Within the listener I determine the frame that is its parent. Now I create a JTextPane, make it non-editable, set it to be text/html and include a bunch of HTML markup text. Then I create a JScrollPane to encapsulate it, and give it a size. Finally, I create a dialog that outputs the info to the user.

While testing this, the problem I encounter is that the vertical scrollbar's position is set to the bottom of the text within its viewport. By default I imagine the behavior should be at the top. Indeed this is confirmed by looking at the JScrollBar's getValue method (retrieved using getVerticalScrollBar from the scroll pane). The value is 0, but 0 shouldn't be at the bottom it should be at the top. I surmise that the issue has something to do with how I've constructed the objects, some sort of gotcha with regards to the behavior during construction and display. What that issue is I have no idea. Suggestions for a fix? Keep in mind I've already tried the various methods of scrolling like setValue, scrollRectToVisible, etc. and they did not work.

Does WindowBuilder make acceptable code?

$
0
0
I have found this new GUI builder, and I was wondering if it makes acceptable code. I am well aware that NetBeans makes terrible code, and you shouldn't use it's GUI builder. Here is the link to WindowBuilder: http://www.eclipse.org/windowbuilder/

The Term 'Expansion'?

$
0
0
I'm not sure where this should be posted as it can apply to any programming language as far as I can see.
I'm currently reading about Makefiles and there is a term used called 'Wildcard Expansion'. Also 'Link Library Expansion' etc. Any clues what is meant by expansion?

Here's a link to 'Wildcard Expansion' Wildcard Expansion. I'm really just trying to understand what 'Expansion' means?

Thanks

Java webstart: jnlp file not quite calling JAR as desired

$
0
0
Hi dreamincode! I've been making a simple program in Java using JMonkey (which is pretty much like NetBeans), and plan to put it up on y site, http://www.gfcf14greendream.com/ . The thing is, I'm not too happy with giving away JARS, so I made the project into a webstart and uploaded both the JAR and JNLP files using FileZilla (of course the webstart was set up so that an instance of the jnlp file calls the jar from my site). I download the JNLP and run it, and it calls the JAR properly, but I've noticed that it only happens when the JAR's permissions are "Read". Meaning that anyone could download it, which I would not prefer. Is there any way to set up the JNLP to call the JAR, but ONLY from there, so that no one who knows/learns the address of it online can download it? If I just remove reading privileges on the jar, I get this, while running the JNLP:

java.io.IOException: Server returned HTTP response code: 403 for URL: http://www.gfcf14greendream.com/...


And I've noticed that I'm unable to save/overwrite a txt file with FileReader. As I try it reading the JAR from my site, I get this:

java.security.AccessControlException: access denied ("java.io.FilePermission" "applications.txt" "write")


I'm guessing both problems are similar, but in any case. Is there a way to save such txt file to the address from where the downloaded JNLP is called? Say if the JNLP is at C:/Users/anuser/Downloads , then the text file would be saved to that address, is that possible? I could always warn that the saved files would be saved to a folder in C:/ , but can this actually be done? And how would I be able to change the JNLP file's name, so that it doesn't just say launch? Any help for any of these questions is greatly appreciated. I hope everyone has a happy New Year!!

Really long repeating list of errors in eclipse java?

$
0
0
I've been making a quiz in java, and everything seems fine, but when i tested it, it gave me a long list of errors. This is the whole code:
Main class:
public class Main {
	public static void main(String args[]){
		Methods me = new Methods();
		me.menu();
	}
}


Methods class:
import java.util.Scanner;
import java.util.Random;

public class Methods {
	//Attributes
//-------------------------------------------------------------------
	private int correctq = 0;
	private int incorrectq = 0;
	private int totalq = 0;
	private Questions qe = new Questions();
	private Scanner sc = new Scanner(System.in);
	private Random ra = new Random();
	
	//Methods
//-------------------------------------------------------------------
	public void menu(){
		cls();
		
		System.out.println("This is a quiz that will generate a\nrandom question for you to answer!");
		System.out.println();
		System.out.println("Do you want to continue? Y/N");
		
		char YN = sc.nextLine().charAt(0);
		
		if(YN == 'Y' || YN == 'y'){
			randomq();
		}
		if(YN == 'N' || YN == 'n'){
			System.exit(0);
		}
	}
	
	public void correct(){
		cls();
		correctq++;
		totalq++;
		System.out.println("Correct!\nDo you want another question? Y/N");
		
		char YN = sc.nextLine().charAt(0);
		if(YN == 'Y' || YN == 'y'){
			randomq();
		}
		if(YN == 'N' || YN == 'n'){
			end();
		}
	}
	
	public void incorrect(){
		cls();
		incorrectq++;
		totalq++;
		System.out.println("Incorrect!\nDo you want another question? Y/N");
		
		char YN = sc.nextLine().charAt(0);
		if(YN == 'Y' || YN == 'y'){
			randomq();
		}
		if(YN == 'N' || YN == 'n'){
			end();
		}
	}
	
	public void end(){
		cls();
		System.out.println("Game finished!\nYou got " + correctq + "/" + totalq + " correct questions");
		System.out.println("You got " + incorrectq + "/" + totalq + " incorrect questions");
		System.out.println("Total questions answered: " + totalq);
		System.out.println("Do you want to go back to menu? Y/N");
		
		char YN = sc.nextLine().charAt(0);
		if(YN == 'Y' || YN == 'y'){
			menu();
		}
		if(YN == 'N' || YN == 'n'){
			System.exit(0);
		}
	}
	
	public void randomq(){
		int rand = 1+ra.nextInt(5);
		if(rand == 1){
			qe.q1();
		}
		if(rand == 2){
			qe.q2();
		}
		if(rand == 3){
			qe.q3();
		}
		if(rand == 4){
			qe.q4();
		}
		if(rand == 5){
			qe.q5();
		}
	}
	
	public void cls(){
		for(int counter = 0; counter <= 10; counter++){
			System.out.println();
		}
	}
	
}


Questions class:
import java.util.Scanner;

public class Questions {
	private Scanner sc = new Scanner(System.in);
	private Methods me = new Methods();
	//I haven't created the questions themselves yet
	public void q1(){}
	
	public void q2(){}
	
	public void q3(){}
	
	public void q4(){}
	
	public void q5(){}
}


But when i run it i get a really long list of errors, at the top it says
Exception in thread "main" java.lang.StackOverflowError
at java.lang.StringBuffer.setLength(Unknown Source)
at java.text.DecimalFormat.expandAffix(Unknown Source)
at java.text.DecimalFormat.expandAffixes(Unknown Source)
at java.text.DecimalFormat.applyPattern(Unknown Source)
at java.text.DecimalFormat.<init>(Unknown Source)
at java.text.NumberFormat.getInstance(Unknown Source)
at java.text.NumberFormat.getNumberInstance(Unknown Source)
at java.util.Scanner.useLocale(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
at java.util.Scanner.<init>(Unknown Source)
And then it keeps saying
at Questions.<init>(Questions.java:4)
at Methods.<init>(Methods.java:9)
over and over and over again.
The problem is that i have no idea why I'm getting all these errors! I'm using Eclipse Juno.

Parameter Invalid: Uploading Picture in MS SQL

$
0
0
So I have a class for connecting to db and for the execution of queries there. This class is called "DBHelper". I won't spoil this class much 'cause I don't have a problem there. The problem with my code is that I can upload the picture successfully to the database, but when it comes to VB .Net, There is an error saying "Parameter Invalid".

This code is for my store procedure:
USE [testing]
GO
/****** Object:  StoredProcedure [dbo].[insertImage]    Script Date: 01/01/2013 10:17:57 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[insertImage]

@pic image
AS
BEGIN
	-- SET NOCOUNT ON added to prevent extra result sets from
	-- interfering with SELECT statements.
	SET NOCOUNT ON;

  insert into ImageTable(SImage) values (@pic)
END





This is my code for uploading picture:
Imports System.Windows.Forms
Imports System.IO
Public Class Form1
    Public cs, command As String
    Private mImageFile As Image
    Private mImageFilePath As String
    Public DBConhelper As DBHelper = Nothing
    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Try
            cs = "Data Source = NINJANINA\SQLEXPRESS; Initial Catalog = testing; Persist Security Info = False; User ID = sa; Password= sa"
            Me.DBConhelper = New DBHelper(cs)
            Me.DBConhelper.ConnectToDatabase()
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub
    Private Sub btnBrowse_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnBrowse.Click
        ' My Resource:  http://devpod.wordpress.com/2011/12/04/viewing-saving-an-image-to-ms-sql-server-in-vb-net/
        Dim fdlg As OpenFileDialog = New OpenFileDialog
        fdlg.Title = "Set Photo"
        fdlg.InitialDirectory = "C:\Users\Niña\Pictures"
        fdlg.Filter = "All Files|*.*|Bitmap Files (*)|*.bmp;*.gif;*.jpg"
        fdlg.FilterIndex = 4
        fdlg.FileName = ""
        fdlg.RestoreDirectory = True
        If fdlg.ShowDialog() = Windows.Forms.DialogResult.OK Then
            tbImagePath.Text = fdlg.FileName
        Else
            Exit Sub
        End If
        Dim sFilePath As String
        sFilePath = fdlg.FileName
        If sFilePath = "" Then
            Exit Sub
        End If
        If System.IO.File.Exists(sFilePath) = False Then
            Exit Sub
        Else
            tbImagePath.Text = sFilePath
            mImageFilePath = sFilePath
        End If
        pbImage.Image = Image.FromFile(tbImagePath.Text)

    End Sub
    Private Function uploadFile()
       
        pbImage.Image.Dispose()
        Dim ok As Boolean = False
        Try
            If Me.tbImagePath.Text = String.Empty Then
                ok = False
                Return ok
                Exit Function
            End If

        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
        Dim fs As FileStream = New FileStream(mImageFilePath.ToString(), IO.FileMode.Open)
        Dim img As Byte() = New Byte(fs.Length) {}
        fs.Read(img, 0, fs.Length)
        fs.Close()

        mImageFile = Image.FromFile(mImageFilePath.ToString())
        Dim imgType As String = Path.GetExtension(mImageFilePath)
        mImageFile = Nothing
        command = "insertImage"
        Dim pic As New System.Data.SqlClient.SqlParameter("@pic", SqlDbType.Image)
        pic.Value = img
        Try
            Me.DBConhelper.ExecuteSPNonQuery(command, pic)
            ok = True
        Catch ex As Exception
            MsgBox(ex.Message)
            ok = False
            Return ok
            Exit Function
        End Try

        Return ok
    End Function

    Private Sub btnUpload_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpload.Click
        uploadFile()
      
    End Sub

End Class




As you can see in my code, there includes my source. Thank you for any further help.

Question: Developing Terminal Programs on Jailbroken Iphone

$
0
0
I jail broke my iphone using Cydia. I wish to develop a simple client socket program for the terminal in c++ or c. Now I have some questions:
*If I just write the program on my mac(or other unix based system), and simply FTP it to my phone will it work? This is more of a question about compatibility than anything else.

*Of course I have to link some libraries to use sockets. Will that cause a problem when I put it on my iphone?


Thanks, I hope I posted in the right location because the iphone forum is all about C# and I did not feel that my questions are related to C#.

How to install Allegro in Mingw

$
0
0
i wanted to install Allegro in Mingw gcc compiler on Window7 32-bit i have downloaded allegro.zip file but don't know how to install it in C:\Mingw.
Viewing all 51036 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>