26.09.2023 Views

The C Programming Language - Pointers

This is a free tutorial about pointers from the book "The C Programming Language" by Heimo Gaicher

This is a free tutorial about pointers from the book "The C Programming Language" by Heimo Gaicher

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

1.8 <strong>Programming</strong> Example Chessboard<br />

A game is to be developed in which a piece can be moved on a chess board by keyboard<br />

input. A chessboard consists of 8x8 squares (8x8 matrix). <strong>The</strong> starting position of the<br />

piece is in the field [0][0] and the piece (the number 1) is to be moved with the keys w,<br />

a, s, d (w = up, a = left, s = down, d = right). If the edge of the playing field is crossed,<br />

the character positions itself on the opposite side. <strong>The</strong> program should end with x.<br />

1 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

0 0 0 0 0 0 0 0<br />

moving [w = up, a = left, s = down, d = right] (exit with x):<br />

/* example 136 – chessboard */<br />

#include <br />

#include <br />

// Prototypes<br />

void fieldOutput(int *field);<br />

void move(int *field, int *posX, int *posY, char moving);<br />

int main(void)<br />

{<br />

int field[8][8] = { 0 }, posX=0, posY=0;<br />

char moving;<br />

field[posY][posX] = 1;<br />

// set game piece<br />

do {<br />

fieldOutput(&field[0][0]);<br />

printf("\nmoving [w = up, a = left, s = down, d = right] (exit with x): ");<br />

scanf("%c", &moving);<br />

move(&field[0][0], &posX, &posY, moving);<br />

fflush(stdin);<br />

system("Cls");<br />

}while(moving != 'x');<br />

// clear keyboard buffer<br />

// clear screen<br />

}<br />

return 0;<br />

<strong>The</strong> C <strong>Programming</strong> <strong>Language</strong> by Heimo Gaicher – Chapter <strong>Pointers</strong> 18

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!