We introduce a new code, ECOSMOG, to run N-body simulations for a wide class of modified gravity and dynamical dark energy theories. These theories generally have one or more new dynamical degrees of freedom, the dynamics of which are governed by their (usually rather nonlinear) equations of motion. Solving these non-linear equations has been a great challenge in cosmology. Our code is based on the RAMSES code, which solves the Poisson equation on adaptively refined meshes to gain high resolutions in the high-density regions. We have added a solver for the extra degree(s) of freedom and performed numerous tests for the f(R) gravity model as an example to show its reliability. We find that much higher efficiency could be achieved compared with other existing mesh/grid-based codes thanks to two new features of the present code: (1) the efficient parallelisation and (2) the usage of the multigrid relaxation to solve the extra equation(s) on both the regular domain grid and refinements, giving much faster convergence even under much more stringent convergence criteria. This code is designed for performing high-accuracy, high-resolution and large-volume cosmological simulations for modified gravity and general dark energy theories, which can be utilised to test gravity and the dark energy hypothesis using the upcoming and future deep and high-resolution galaxy surveys.