Created
June 13, 2013 14:38
-
-
Save mattmawhinney/5774200 to your computer and use it in GitHub Desktop.
A paired down method for figuring out the size of a continent inspired by the game Civilization III. This is borrowed almost verbatim from "Learn to Program 2.0" by Chris Pine. It just contains a small addition that prevents the program from crashing when counting 'tiles' that are at the 'edge of the world'.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Method from Chris Pine for figuring out | |
# continent size in Civilization III | |
# with added return conditional for spots at the 'edge of the earth' | |
M = 'land' | |
o = 'water' | |
world = [[M,o,o,o,o,o,o,o,o,o,o], | |
[M,o,o,o,M,M,o,o,o,o,o], | |
[M,o,o,o,o,o,o,o,M,M,o], | |
[M,M,M,M,o,o,o,o,o,M,o], | |
[o,o,o,M,o,M,M,o,o,o,o], | |
[o,o,o,o,M,M,M,M,o,o,o], | |
[o,o,o,M,M,M,M,M,M,M,M], | |
[o,o,o,M,M,o,M,M,M,o,o], | |
[o,o,o,o,o,o,M,M,o,o,o], | |
[o,M,o,o,o,M,o,o,o,o,o], | |
[o,o,o,o,M,M,o,o,o,o,o]] | |
def continent_size world, x, y | |
# Either it's water or we already | |
# counted it, but either way, we don't | |
# want to count it now. | |
if world[x][y] != 'land' | |
return 0 | |
end | |
# My addition (at Chris Pine's suggestion) for inclduing locations | |
# At the edge of the world without having the program crash | |
if x > 9 || x < 0 || y > 9 || y < 0 | |
return 1 | |
end | |
# So first we count this tile... | |
size = 1 | |
world[x][y] = 'counted land' | |
# ...then we count all of the | |
# neighboring eight tiles (and, | |
# of course, their neighbors by | |
# way of the recursion). | |
size = size + continent_size(world, x-1, y-1) | |
size = size + continent_size(world, x , y-1) | |
size = size + continent_size(world, x+1, y-1) | |
size = size + continent_size(world, x-1, y ) | |
size = size + continent_size(world, x+1, y ) | |
size = size + continent_size(world, x-1, y+1) | |
size = size + continent_size(world, x , y+1) | |
size = size + continent_size(world, x+1, y+1) | |
size | |
end | |
puts continent_size(world, 5, 5) #32 given the current configuration of my world array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment