Link to home
Start Free TrialLog in
Avatar of merijn van der leek
merijn van der leek

asked on

Writing C code to Python

Is there an easy way to rewrite c code to python?

I made the following code in C that i want to have in python:

// Implements Game of Fifteen (generalized to d x d)
// Merijn van der Leek
// 20-9-19
// fifteen

#define _XOPEN_SOURCE 500

#include <cs50.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

// Constants
#define DIM_MIN 3
#define DIM_MAX 9
#define COLOR "\033[32m"

// Board
int board[DIM_MAX][DIM_MAX];

// Dimensions
int d;

// Prototypes
void clear(void);
void greet(void);
void init(void);
void draw(void);
bool move(int tile);
bool won(void);

int main(int argc, string argv[])
{
    // Ensure proper usage
    if (argc != 2)
    {
        printf("Usage: fifteen d\n");
        return 1;
    }

    // Ensure valid dimensions
    d = atoi(argv[1]);
    if (d < DIM_MIN || d > DIM_MAX)
    {
        printf("Board must be between %i x %i and %i x %i, inclusive.\n",
            DIM_MIN, DIM_MIN, DIM_MAX, DIM_MAX);

        return 2;
    }

    // Open log
    FILE *file = fopen("log.txt", "w");
    if (file == NULL)
    {
        return 3;
    }

    // Greet user with instructions
    greet();

    // Initialize the board
    init();

    // Accept moves until game is won
    while (true)
    {
        // Clear the screen
        clear();

        // Draw the current state of the board
        draw();

        // Log the current state of the board (for testing)
        for (int i = 0; i < d; i++)
        {
            for (int j = 0; j < d; j++)
            {
                fprintf(file, "%i", board[i][j]);
                if (j < d - 1)
                {
                    fprintf(file, "|");
                }
            }
            fprintf(file, "\n");
        }
        fflush(file);

        // Check for win
        if (won())
        {
            printf("ftw!\n");

            break;
        }

        // Prompt for move
        int tile = get_int("Tile to move: ");

        // Quit if user inputs 0 (for testing)
        if (tile == 0)
        {
            break;
        }

        // Log move (for testing)
        fprintf(file, "%i\n", tile);
        fflush(file);

        // Move if possible, else report illegality
        if (!move(tile))
        {
            printf("\nIllegal move.\n");
            usleep(500000);
        }

        // Sleep thread for animation's sake
        usleep(50000);
    }

    // Close log
    fclose(file);

    // Success
    return 0;
}

// Clears screen using ANSI escape sequences
void clear(void)
{
    printf("\033[2J");
    printf("\033[%d;%dH", 0, 0);
}

// Greets player
void greet(void)
{
    clear();
    printf("WELCOME TO GAME OF FIFTEEN\n");
    usleep(2000000);
}

// Initializes the game's board with tiles numbered 1 through d*d - 1
// (i.e., fills 2D array with values but does not actually print them)
void init(void)
{
    int n = (d * d) - 1;

    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++, n--)
        {
            board[i][j] = n;
        }
    }
    if((d % 2 == 0))
    {
        board[d - 1][d - 2] = 2;
        board[d - 1][d - 3] = 1;
    }
}

// Prints the board in its current state
void draw(void)
{
    // TODO
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            if (board[i][j] == 0)
            {
                printf(" _ ");
            }
            else
            {
                printf("%2i ", board[i][j]);
            }
        }
    printf("\n");
    }
}

// If tile borders empty space, moves tile and returns true, else returns false
bool move(int tile)
{
    // TODO
    int verticaal;
    int horizontaal;
// if the white tile is found it's value is stored
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            if (board[i][j] == 0)
            {
                verticaal = i;
                horizontaal = j;
            }
        }
    }
// if the statement is true the integers get swapped
    int swap;
    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            if (tile == board[i][j])
            {
                // if the white tile is 1 above or next to the user tile they get swapped
                if ((i == verticaal && j == (horizontaal - 1)) || (i == verticaal && j == (horizontaal + 1)))
                {
                        swap = board[i][j];
                        board[i][j] = 0;
                        board[verticaal][horizontaal] = swap;
                        return true;
                }
                else if ((j == horizontaal && i == (verticaal - 1)) || (j == horizontaal && (i == verticaal + 1)))
                {
                    swap = board[i][j];
                    board[i][j] = 0;
                    board[verticaal][horizontaal] = swap;
                    return true;
                }

            }
        }

    }
    return false;
}

// Returns true if game is won (i.e., board is in winning configuration), else false
bool won(void)
{
    int teller = 0;

    for (int i = 0; i < d; i++)
    {
        for (int j = 0; j < d; j++)
        {
            // if the game of fifteen is in order from 1 to 15 the game is won
            if (board[i][j] == (teller + 1))
            {
                teller += 1;
            }
            // when the loop returned true for all the characters the last one should be equal to 0 instead of 16
            else if (i == (d - 1) && j == (d - 1))
            {
                if (board[i][j] == 0)
                {
                    return true;
                }
            }
            else
            {
                return false;
            }
        }
    }

    return true;
}

Open in new window

Avatar of Norie
Norie

What exactly do you want to do?

  • Rewrite the code in Python?
  • Convert the code 'automatically' to Python?
  • Use the code as it is in Python via some sort of link/library setup?
Avatar of merijn van der leek

ASKER

Hey i wonder if there is some tool or site that converts can convert this code to python or that u can only do this manual
If you do a Google search you'll find plenty of results for 'C to Python converter', or similar.

Whether you find anything that's useful is kind of potluck. :)
Hi merijn van der leek,

You can use the module "ctypes" in python to use your C function.

But I don't know if you can translate all your C code into python sorry.

You can see an exemple here.

Regard.
ASKER CERTIFIED SOLUTION
Avatar of David Favor
David Favor
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Thanks everyone gonna have a look :)
This code is rather simple.

If the objective is to have readable and maintainable code, then you should probably rewrite the code by hand.
Sometimes you might even change the logic a little as there is sometimes a simpler and more pythonic solution.

It all depends on your exact objectives.

If the objective is just to have some difficult to read code, that is platform independent, then tools ,ight be the reight choice.

If you want to build and enhance on this code I'd go for manual translation