Need A Bit Of Assistance With My First C++ Program (Simple) - c++

I've begun into C++ from a heavy C background. This is my first program, which I'm using as a learning experience. A simple Snake Game. Everything runs smoothly, the only issue is that no matter what I do, after the players score reaches 4, the next bit of food is ALWAYS spawned inside of the wall, in the bottom left corner (1 row up from the bottom.) Running into it = Game Over.
This is running on a Linux server. I've tried messing with the border parameters, but I'm having a hard time figuring out what to change, because everything looks fine to my eyes. (Clearly something is not.)
I'm pasting the entire program below. It's quite short. I just need one of you guru's to read through/run the program and take me to school on something that's probably a simple fix. Pardon the excessive comments. I use these to teach (I have a following on pastebin as odd as that is to say)
/*
Snake Game - Tragedy
My First Program In C++
I'm Using This Much As A Learning Experience For Myself
And Would Like To Help Those Reading The Code For This Goofy Game
Understand C++ A Bit Better Too
Therefore I'm Trying To Explain As Much As Possible In Real Time
*/
#include <iostream> //Standard
#include <stdlib.h> //Standard
#include <unistd.h> //For POSIX Access
#include <sys/ioctl.h> //For Display Window, TTY Window (Console Window)
#include <termios.h> //For Line Buffering - See Below
#include <stdio.h> //Old Friend
#define CLRSCR "\e[1;1H\e[2J" //Command To Clear Terminal Screen - Change Accordingly
using namespace std; /*
A NameSpace Is Used As Additional Information
To Differentiate Between Similar Functions/Variables
That Have The Same Name In Different Libraries
Using 'namespace' You Can Define The Context
In Which Names Are Defined
Withoug Using The STD NameSpace, The Computer Will Try
To Call cout Or cin As If It Weren't Defined In A NameSpace
Trying To Call Something That Doesn't Exist = Error
So, Without Using namespace std; When You Write For Example:
'cout << value;' You'd Have To Write 'std::cout << value;''
*/
//Create Boundaries
const int width = 50;
const int height = 25;
const char block = 'o';
void ClearScreen(void)
{
cout << CLRSCR;
}
//Global Arrays For Data Records
int background[height][width]; // Background
int snake[50][2]; // Max Snake Length
int food[2] = {0,0}; // Snake Food
int score = 0; // Score
int snakelen = 3; // Snake Starting Length
int snakespeedx = 1; // Horizontal Speed
int snakespeedy = 1; // Vertical Speed
int lap = 200; // Waiting Time Betweeen Frames
//Declaring Global Temporary Variables To Save Memory
int px, py, nx, ny; //Postions
char k;
int h, w;
int x, y;
int movementx = snakespeedx; //Snake Movement
int movementy = 0; //Snake Movement
//Check For Keyboard Press
/*
Reference Link:
https://www.quora.com/With-which-function-can-I-replace-kbhit-in-C++-because-the-header-conio-h-doesnt-exist-in-linux
Ubuntu Users:
sudo apt-get install libncurses5-dev libncursesw5-dev
Life Saver:
http://www.flipcode.com/archives/_kbhit_for_Linux.shtml
*/
int bytesWaiting, i;
int _kbhit()
{
static const int STDIN = 0;
static bool initialized = false; //The Boolean Data Type Is Used To Declare A Variable Whose Value Will Be Set As True (1) Or False (0)
if (! initialized)
{
//Use Termios To Turn Off Line Buffering
termios term;
tcgetattr(STDIN, &term);
term.c_lflag &= ~ICANON;
tcsetattr(STDIN, TCSANOW, &term);
setbuf(stdin, NULL);
initialized = true;
}
ioctl(STDIN, FIONREAD, &bytesWaiting);
return bytesWaiting;
}
//Initialise background borders Onto Array
void initialise_background(void)
{
//int i;
// Insert Top Border
for(i=0; i<width; i++)
{
background[0][i]=1;
}
//Insert Left Border
for(i=0; i<height; i++)
{
background[i][0]=1;
}
//Insert Right Border
for(i=0; i<height; i++)
{
background[i][width-1]=1;
}
//Insert Bottom Border
for(i=0; i<width; i++)
{
background[height-1][i]=1;
}
}
//Initialise Snake Coordinates
void initialise_snake(void)
{
snake[0][0]=3; //Coordinates X
snake[0][1]=3; //Coordinates Y
snake[1][0]=3+1; //Coordinates X
snake[1][1]=3; //Coordinates Y
snake[2][0]=3+2; //Coordinates X
snake[2][1]=3; //Coordinates Y
snake[3][0]=3+3; //Coordinates X
snake[3][1]=3; //Coordinates Y
snake[4][0]=3+4; //Coordinates X
snake[4][1]=3; //Coordinates Y
}
//Update Snake
void update_snake_coordination(void)
{
//int px,py,nx, ny;
px = snake[0][0];
py = snake[0][1];
snake[0][0] = px + movementx;
snake[0][1] = py + movementy;
nx = snake[0][0];
ny = snake[0][1];
for(i=1; i<snakelen; i++)
{
nx = snake[i][0];
ny = snake[i][1];
snake[i][0] = px;
snake[i][1] = py;
px = nx;
py = ny;
}
}
//Install Snake Coordinates Into Background Array = ( 1 To Draw And 0 To Erase)
void draw_snake_in_background(const int rev)
{
//int x, y;
for(i = 0; i<snakelen; i++)
{
x = snake[i][0];
y = snake[i][1];
if((x!=0)&&(y!=0))
{
background[y][x] = rev;
}
}
}
//Print Array Frame
void print_array_frame(void)
{
for(h=0; h<height; h++)
{
for(w=0; w<width; w++)
{
i=background[h][w];
if(i==1)
{
cout << block;
}
else if (i == 2)
{
cout << "+";
}
else
{
cout << " ";
}
}
cout << endl;
}
}
//Update Loop
void mainloop(void)
{
ClearScreen();
draw_snake_in_background(1); // Install Snake
print_array_frame(); // Print Frame
draw_snake_in_background(0); // Uninstall Snake
}
//Waiting Function
void sleepcp(int milliseconds) // Cross-Platform Sleep Function
{
clock_t time_end;
time_end = clock() + milliseconds * CLOCKS_PER_SEC/1000;
while (clock() < time_end)
{
//
}
}
//Reaction To Keyboard Press
void reaction_on_keyboard(const char k)
{
if(k=='d'||k=='6')
{
//Right Turn
movementx = snakespeedx;
movementy = 0;
}
else if(k=='a'||k=='4')
{
//Left Turn
movementx = -snakespeedx;
movementy = 0;
}
else if(k=='w'||k=='8')
{
//Turn Up
movementx = 0;
movementy = -snakespeedy;
}
else if(k=='s'||k=='2')
{
//Turn Down
movementx = 0;
movementy = snakespeedy;
}
else if(k=='q'||k=='z'||k=='c')
{
cout << "[+] Exit Safely [+]"<<endl;
exit(0);
}
}
//Create Snake Food
void cook_food(void)
{
if (food[0]==0)
{
x = rand() % width + 1;
y = rand() % height + 1;
food[0] = x;
food[1] = y;
background[y][x] = 2;
}
}
//Check Snake & Food Status
void capture_food(void)
{
x = food[0];
y = food[1];
if ((x==snake[0][0])&&(y==snake[0][1]))
{
background[y][x] = 0;
food[0] = 0;
score ++;
snakelen ++;
cook_food();
}
}
//Check Snake is Not Touching Boundary
void check_over_lapping(void)
{
//int px,py;
px = snake[0][0];
py = snake[0][1];
if((px==0)||(px==(width-1))||(py==0)||(py==(height-1)))
{
cout << "[+] Game Over [+]" << endl;
exit(0);
}
}
//Loop
void loop(void)
{
int frame = 0;
x = 0;
y = 0;
while(x<500)
{
sleepcp(lap);
if(_kbhit()) //If Keyboard Pressed
{
cin >> k; //Character
reaction_on_keyboard(k);
}
mainloop(); //RUn Main Loop FUnction
update_snake_coordination();//Update Snake Coordinates
check_over_lapping(); //Check Snake Status
cook_food(); //Make Sure Food is Available
capture_food(); //Snake Eaten Food?
cout << "[ Frame : " << frame << " | Score : " << score << " ] "<< endl; //Print Status
frame ++;
}
}
//Main Trigger Function
main()
{
initialise_background(); //Install All Variables
initialise_snake(); //Install Snake data
loop(); //Run Update Loop
}
This is what happens when running the game:
oooooooooooooooooooooooooooooooooooooooooooooooooo
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o o
o ooooooo o
o o
o o
o o
+<---Places Here Every Time o
oooooooooooooooooooooooooooooooooooooooooooooooooo
[ Frame : 169 | Score : 4 ]
Any Help or Input is greatly appreciated!

Your background array is height * width. When you place food into the array, you place it at rand() % width + 1 and rand() % height + 1, which have a range of 1 to width and 1 to height respectively. If you generate food at an x coordinate of width or a y coordinate of height, you will read outside the bounds of your background array. What is happening is that the seed your program is initialised with is generating food at an x position of width and because of the way memory is laid out that is the same array location as background[y + 1][0].
You probably want to change cook_food as follows:
void cook_food(void)
{
if (food[0]==0)
{
x = rand() % (width - 1) + 1;
y = rand() % (height - 1) + 1;
food[0] = x;
food[1] = y;
background[y][x] = 2;
}
}
I would note that this isn't really a C++ program, no matter what you're compiling it with. Your are using a very C style, storing data in a C way, and calling C standard library functions. You may want to read the isocpp C++ FAQ, which has some pointers to resources for people learning C++.
A C++ implementation would probably want to use the std::uniform_int_distribution class in the standard library, which makes it much clearer what your minimum and maximum values are for your food X and Y coordinates. You would also have 'Food' and 'Snake' objects that tracked their X and Y coordinates, rather than storing those values in arrays that you use directly.
EDIT: You've been asking some questions in the comments about collision detection for the snake. I believe this method will detect snake-on-snake collision given the code above:
bool is_snake_touching_itself() {
for (std::size_t i = 1; i < snakelen; ++i) {
if (snake[0][0] == snake[i][0] && snake[0][1] == snake[i][1]) {
return true;
}
}
return false;
}

Related

Assign TicTacToe player position to a bitboard representation

I have 2 separate boards for 2 players: X and O. Now I'd like to make sure if an entered position (int x, int y) is valid but I've got no idea of how should I convert it to bitboard representation and compare it with given board states and it's doing me head in. Also wrote a helper function to see the board states bin(). And is there a way to merge the X and O boards into one or should I keep the separate all board to check the game state?
#include <bits/stdc++.h>
using namespace std;
bool xmove = true;
const int win[] = { 0b111000000,
0b000111000,
0b000000111,
0b100100100,
0b010010010,
0b001001001,
0b100010001,
0b001010100 };
struct Board {
int b = 0b000000000;
};
int iswin(int x) {
for (size_t i = 0; i < 8; i++) {
if (win[i] == x) return 1;
}
return 0;
};
void bin(int x){
cout << "0b" + bitset<9>(x).to_string() << endl;
};
int main() {
Board x, o, all;
x.b |= 0b000000111;
o.b |= 0b000111000;
all.b = x.b | o.b;
bin(all.b);
cout << iswin(x.b);
return 0;
}
Well you can treat your bitstring as a flattened 2d array. To convert a 2d index into a 1d one you can simply do
x * width + y
So to set the matching position in the board you can do
int move = 1 << (x * 3 + y)
since a TicTacToe board is 3 wide and 3 tall. You can then check if there already is an X or O at that position with
if(x.b & move)
{
std::cout << "there already is and x at(" << x << ", " << y << ")";
}
To then add that position to the board if there is nothing there do
x.b |= move
Same thing for o.b. This is of course based on the assumption that your x and y start at 0.
Concerning your question of whether or not you can merge the two board. How would you even do that? A bit can only be 0 or 1 so there is no way to differentiate between 3 different states (nothing, X, O).

Calculating 3D cartesian coordinates inside a cone

So what I am essentially trying to do here is arranging the 3D cartesian coordinates of points inside an inverted cone (radius decreases with height). The basic approach I have taken here is to have an integrally reducing height, h, and plotting points (x,y) that fall within a circle formed at height h. Since the radius of this circle is variable, I am using a simple similarity condition to determine that at every iteration. The initial height I have taken is 1000, the radius ought to initially be 3500. Also, these circles as centred at (0,0) [the z-axis passes through the vertex of the cone, and is perpendicular to the base]. Code isn't running properly, showing me an exit status of -1. Can anyone help me figure out if my implementation is off due to some size errors or something?
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int main(){
float top[1010][9000][3];
ll i = 0;
for(ll h = 999; h >=0; h--){
float r=(h+1)*(3.5);
for (ll x = floor(r) * (-1); x <= floor(r); x++){
for (ll y = floor(r) *(-1); y <= floor(r); y++){
if(pow(x,2) + pow(y,2) <= pow(floor(r),2)){
top[h][i][0] = x;
top[h][i][1] = y;
top[h][i][2] = 9.8;
i++;
}
}
}
i=0;
}
cout << "done";
for (ll m = 0; m < 1000; m++){
for(ll n = 0; n < 7000; n++){
if(top[m][n][2] == 9.8){
cout << top[m][n][0] << top[m][n][1];
}
}
}
}
You don't need to declare ll as long long int. The indexes you are using will fit inside of int.
Here's your problem: Change the code to this to see what's going on:
for(ll h = 999; h >=0; h--){
float r=(h+1)*(3.5);
for (ll x = floor(r) * (-1); x <= floor(r); x++){
for (ll y = floor(r) *(-1); y <= floor(r); y++){
if(pow(x,2) + pow(y,2) <= pow(floor(r),2)){
/* top[h][i][0] = x;
top[h][i][1] = y;
top[h][i][2] = 9.8; //*/
i++; // this gets really big
}
}
}
cout << "max i: " << i << endl;
i=0;
}
i gets really big and is indexing into a dimension that is only 9000.
Criticism of the code...
It looks like you are scanning the entire x,y,z block and 'testing' if the point is inside. If yes, saving the x,y coordinate of the point along with 9.8 (some field value?).
Perhaps you could forgo the float buffer and just print the {x,y} coordinates directly to see how your code works before attempting to save the output. redirect the output to a file and inspect.
cout << "{" << x << "," << y <<"}," << (i % 5 == 0 ? "\n" : " ");
Also, read up on why comparing floats with == doesn't work.

Error C2678 C++ A* Pathfinding

I'm currently working on implementing the A* pathfinding algorithm in C++. I tried to run my code to see if the display grid function was working but got the C2678 error: binary '<': no operator found which takes a left-hand operand of type 'const Coord' (or there is no acceptable conversion).
I know that my program is messy and probably not efficient at all however i was trying to get a basic version working before optimising. Is the error because I'm trying to output a boolean value of a Coord structure?
Code:
#include <iostream>
#include <fstream>
#include <chrono>
#include <thread>
#include <vector>
#include <set>
using std::chrono::milliseconds;
using std::chrono::duration_cast;
using std::this_thread::sleep_for;
typedef std::chrono::steady_clock the_clock;
struct Location {
int g = 0; // Distance covered so far
int h = 0; // Estimate of distance to goal
float f = 0; // Estimated cost of the complete path
bool walkable = 0; // 0 = Walkable, 1 = Wall
};
// Structure
struct Coord {
int x;
int y;
Location location;
};
// Declare size of grid
#define WIDTH 10
#define HEIGHT 10
typedef Location Array[HEIGHT][WIDTH];
Location grid[HEIGHT][WIDTH]; // Create an array of locations
void displayGrid() {
/* Displays the Grid to the console! */
system("CLS");
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
std::cout << grid[y][x].walkable;
}
std::cout << "\n";
}
sleep_for(milliseconds(100)); // Visual delay
}
void initialiseGrid() {
/* Fills the Grid array with values */
srand((unsigned)time(0));
for (int y = 0; y < HEIGHT; y++) {
for (int x = 0; x < WIDTH; x++) {
grid[y][x].walkable = 0;
}
}
/* Test grid */
grid[4][2].walkable = 1;
grid[5][2].walkable = 1;
grid[4][3].walkable = 1;
grid[5][3].walkable = 1;
grid[4][5].walkable = 1;
grid[5][5].walkable = 1;
grid[4][6].walkable = 1;
grid[5][6].walkable = 1;
}
void Astar(Coord startPoint, Coord endPoint) {
/**/
std::set<Coord> closedSet = {}; // Nodes that do not have to be considered again
std::set<Coord> openSet = {}; // Nodes still to be considered to find the shortest path
Coord currentNode; // Current node
currentNode.x = startPoint.x;
currentNode.y = startPoint.y;
currentNode.location.g = 0; // 0 Distance from starting point
openSet.insert(currentNode); // Insert starting node
while (openSet.empty() == false) { // Loop while open list is not empty
for (std::set<Coord>::iterator it = openSet.begin(); it != openSet.end(); it++) { // Iterate through each element in the open set to find the lowest F value
if ((*it).location.f < currentNode.location.f) { // Check if iterator f value is smaller than the current value
currentNode = *it; // Update the current node
}
}
openSet.erase(currentNode); // Drop from the open set since been checked
closedSet.insert(currentNode); // Add to the closed set
}
}
int main(int argc, char *argv[]) {
// Set start and end points
Coord start;
start.x = 3;
start.y = 3;
Coord end;
end.x = 5;
end.y = 6;
initialiseGrid(); // Put -1 (empty) in
// Start timing
the_clock::time_point startTime = the_clock::now();
// Stop timing
the_clock::time_point endTime = the_clock::now();
// Compute the difference between the two times in milliseconds
auto time_taken = duration_cast<milliseconds>(endTime - startTime).count();
displayGrid();
std::cout << "That took: " << time_taken << " ms" << std::endl;
return 0;
}
The easiest way to solve the issue with std::set requiring a strict-weak-ordering and your Coord class is to provide an operator < comparing the x and y values in Coord, and returning whether one Coord is less than another Coord using these values.
You can do this with std::tie
#include <tuple>
//...
struct Coord {
int x;
int y;
Location location;
bool operator <(const Coord& c) const
// returns true if this->x and this->y < c.x and c.y, false otherwise
{ return std::tie(x,y) < std::tie(c.x,c.y); }
};
The std::tie compares the x components, then if equal, compares the y components. The result of the comparison is returned (either true if the first set of x,y components is less than the second set of x,y components, or false otherwise).
Live Example here

Using 2D-array as a workspace

I am working on a snake game and made a prototype. I have attached the code. It may not be so good but still it is messy. I could make it move but I don't know why the lower bound region is flickering. How to reduce this overall flickering, which almost makes me dizzy? Also, one more question: How to make the character move (like in the original snake game), not wait until my command? Please help me! Sorry for the language.
#include<iostream.h>
#include<stdlib.h>
#include<windows.h>
int main() {
char a[25][80]={0};
system("Color 0");
int x=40,y=15;
int m=0,n;
a[16][2]='X';
a[y][x]='O';
for(int i=0;i<25;++i) {
for(int j=0;j<80;++j) cout<<a[i][j];
}
while(m!=1000) {
Sleep(70);
if(GetAsyncKeyState(VK_LEFT)) {
a[y][x]=0;
x--;++m;a[y][x]='O';
}
if(GetAsyncKeyState(VK_RIGHT)) {
a[y][x]=0;
x++;
++m;
a[y][x]='O';
}
if(GetAsyncKeyState(VK_UP)) {
a[y][x]=0;
y--;
++m;
a[y][x]='O';
}
if(GetAsyncKeyState(VK_DOWN)) {
a[y][x]=0;
y++;
++m;
a[y][x]='O';
}
system("cls");
for(int i=0;i<25;++i) {
for(int j=0;j<80;++j) cout<<a[i][j];
}
}
}
return 0;
}
Youve chosen a graphics rendering method which nobody ever planned to be flicker-free. You need to draw graphics to a window, or learn how to use the windows console functions. Considering your tight timetable, I suggest you just ignore the flickering.
To make the snake continue to move, remember the last direction the player moved the snake; if there is no key pressed, then move that direction.
Your code doesn't compile as-is. Practice copying and pasting harder (copy it back out of stackoverflow into your compiler to make sure it works)
to overcome on flickering you have to reduce your system ("cls") time. and after one turn, your code is not giving other feed for snake. make it in loop.
and also make boundary wall of your map so that one can understand scope of map. and when you press any movement key, you have to run loop for its movement so that it move continuously .Hope that will help.
You can partially avoid flickering considering that you can draw your "screen" without clearing it before. For example, in the windows console environment (which apparently you are using), this function can be used to clear the screen instead of system("cls"):
void clear_screen ( void ) {
DWORD n; /* Number of characters written */
DWORD size; /* number of visible characters */
COORD coord = {0,0}; /* Top left screen position */
CONSOLE_SCREEN_BUFFER_INFO csbi;
/* Get a handle to the console */
HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
GetConsoleScreenBufferInfo ( h, &csbi );
/* Find the number of characters to overwrite */
size = csbi.dwSize.X * csbi.dwSize.Y;
/* Overwrite the screen buffer with whitespace */
FillConsoleOutputCharacter ( h, TEXT ( ' ' ), size, coord, &n );
GetConsoleScreenBufferInfo ( h, &csbi );
FillConsoleOutputAttribute ( h, csbi.wAttributes, size, coord, &n );
/* Reset the cursor to the top left position */
SetConsoleCursorPosition ( h, coord );
}
Reading the code, you can notice that it overwrites the screen with enough spaces and then resets the cursor position to the top left position. So, instead of blanking the screen and then drawing the strings, we can set the cursor at the origin and then write our string, which already contains spaces.
Moreover, we can use a mono dimensional null terminated array of char, big enough to represent the whole screen. You use a size of 80x25, but in Windows the console is bigger (at least mine is ~100 char wide), so I'll consider a size of 81x25 putting a \n in the extra char of every row. So I end up with this:
void update_screen ( char *buffer )
{
COORD coord = {0,0}; /* Top left screen position */
/* Get a handle to the console */
HANDLE h = GetStdHandle ( STD_OUTPUT_HANDLE );
/* Reset the cursor to the top left position */
SetConsoleCursorPosition ( h, coord );
/* Draw the screen buffer */
cout << buffer;
}
To make your character move you have to update its position every time you draw it and change direction of movement only when a key is pressed. It's better to check for bounds collision too, at least to stop the game:
#include<iostream>
#include<stdlib.h>
#include<windows.h>
#include<string>
using std::cout;
using std::string;
const int scr_rows = 25;
const int scr_cols = 80;
constexpr int buf_rows = scr_rows;
constexpr int buf_cols = scr_cols + 1;
constexpr int buf_size = scr_rows * buf_cols;
void draw( char *buf, int x, int y, char c) {
// warning, unchecked out of bounds;
buf[y * buf_cols + x] = c;
}
char value_at( char *buf, int x, int y ) {
// warning, unchecked out of bounds;
return buf[y * buf_cols + x];
}
int main() {
// initialize buffer
char screen[buf_size + 1];
for ( int i = 0, pos = 0; i < scr_rows; ++i ) {
for ( int j = 0; j < scr_cols; ++j ) {
screen[pos] = ' ';
++pos;
}
screen[pos] = '\n';
++pos;
}
screen[buf_size] = '\0';
clear_screen();
int x = 40, y = 15;
draw(screen, 2, 16,'X');
draw(screen, x, y, 'O');
int vx = -1;
int vy = 0;
bool victory = false;
while( !GetAsyncKeyState(VK_ESCAPE) ) {
Sleep(100);
if (GetAsyncKeyState(VK_LEFT)) {
vx = -1;
vy = 0;
}
if (GetAsyncKeyState(VK_RIGHT)) {
vx = 1;
vy = 0;
}
if (GetAsyncKeyState(VK_UP)) {
vx = 0;
vy = -1;
}
if (GetAsyncKeyState(VK_DOWN)) {
vx = 0;
vy = 1;
}
draw(screen, x, y, ' ');
x += vx;
y += vy;
// check bounds
if ( x < 0 || x >= scr_cols || y < 0 || y >= scr_rows )
break;
if ( 'X' == value_at(screen, x, y) ) {
victory = true;
break;
}
draw(screen, x, y, 'O');
update_screen(screen);
}
if ( victory )
cout << "\n **** You win! ****\n";
else
cout << "\n **** You loose! ****\n";
return 0;
}

How to move a piece in a checkers game

So, I am working on a in-class cooperative assignment in which I must design a partial checkerboard. This must be done using a console window and must be 8x8 board. My friend is designing the board while I design the function to move only the red piece. His part of the code will be sending me a matrix of the coordinates board[rows][columns] and the movement meaning movement = 1 is top left, movement = 2 is top right, etc.. I'm having issues understanding how the pieces are suppose to move.
Here is my code:
int movered(int movement, int board[][8])
{
int x;
int y;
int piece;
for (x=0; x == movement; x++)
{
x = movement - x;
for (y=0; y == movement; y++)
{
y = movement - y;
}
}
piece = board[x][y];
board[x][y] = 0;
DrawBoard(piece, board);
return piece;
}
I'm new to this but my shot at it would be something like this.
int moved(int xPos, int yPos, int moveSelect, int board[][8])
{
int teamCheck;
if(board[xPos][yPos] == 1)
teamCheck = 1;//else = 2
if(moveSelect == 1) // && xPos >= 0, etc... Moves can't go off board
{
board[xPos][yPos] = 0; //then set new position on board to equal a 1 or 2 depending on team chip is on
return 1;
}
//elseif - do rest of moveSelections
else
return 0; //Returning value indicates a success or failure in move
}