Ruby - Building the Tic Tac Toe game

My first encounter with Ruby has been quite wonderful. Even with the guidance by the Flatiron curriculum and the team there, it was a really big challenge for me. However, we know have a working game! I want to share my learnings below in hope that maybe it would help others - and even more so, for myself to keep going!

Below is my first attempt to rebuild a basic game of Tic Tac Toe.

HOW THE GAME WORKS

  1. Two player starts with a blank board of 9 spaces on a 3 x 3 grid

  2. Each play takes turn to place either an “X” or “O” (a marker) on the board

  3. The game is won when one player achieve three markers in a row - horizontally, vertically, or diagonally

  4. The game is draw when the board is full and there is no winning moves

  5. The program needs to guide players along the way and announce the winner if game is won

SETTING UP THE GAME IN BIN

#!/usr/bin/env ruby

require_relative '../lib/tic_tac_toe'
puts "Welcome to Tic Tac Toe!"
board = [" ", " ", " ", " ", " ", " ", " ", " ", " "]
play(board)

SETTING UP THE BOARD & DEFINE WINNING COMBINATIONS

# -> lib/tic_tac_toe.rb

def display_board(board)
  puts " # | # | # "
  puts "-----------"
  puts " # | # | # "
  puts "-----------"
  puts " # | # | # "
end

# TROUBLESHOOTING: This was easy to get wrong because of all the spacing and number of dashes. The test specs was written quite specifically so you should pay attention to the details.

DEFINE PLAYER’S MOVES AND CONVERT THEM TO INTEGERS

def input_to_index(user_input)
  user_input.to_i - 1
end

def player_move(board, index, marker)
 board[index] = marker
end

# TROUBLESHOOTING: I was amazed at how simple it is to convert a player’s input into integer ( .to_i) Super important: the use of = (assignment) is different then == (comparison). It took me 2 hours to figure out that I got an extra =.

CONDITIONS LOGIC TO CHECK IF POSITION IS TAKEN AND IF IT’S A VALID MOVE

def position_taken? (board, index)
  if board[index] == "" || board[index] == " " || board[index] == nil
    return false
  else
    return true
  end
end

def valid_move?(board, index)
  if !position_taken?(board, index) && (index).between?(0,8)
    return true
  else 
    return false
  end
end

# TROUBLESHOOTING: The use of ! in front of !positiontaken?(board, index) reads as position is NOT taken. This is a better way to set condition vs. before I was using the positiontaken?(board, index) == false. Linking || (or) && (and) is also very helpful.

ASKING FOR PLAYERS’ INPUTS, KEEP TRACK OF THE TURNS AND PLAYER’S MARKERS

def current_player(board)
  turn_count(board) % 2 == 0? "X" : "O"
end

def turn(board)
  puts "Please enter 1-9:"
  user_input = gets.strip
  index = input_to_index(user_input)
  if valid_move?(board, index)
    player_move(board, index, current_player(board))
    display_board(board)
  else
    turn(board)
  end
end

def turn_count(board)
  counter = 0
  board.each {|space|
    if space == "X" || space == "O"
      counter += 1   
    end
  }
  counter
end

# TROUBLESHOOTING: Again I was amazed at how simple it is to write the second the last line above: Is turncount(board) is divisible by 2 -> return “X”, if not, return “O”. It’s important that the playermove includes the current_player(board) so as to display the marker “X” or “O”.

CONDITIONS LOGOC TO FIND OUT IF THE GAME IS WON, FULL, DRAW, OR OVER

WIN_COMBINATIONS = [
  [0, 1, 2],
  [3, 4, 5],
  [6, 7, 8],
  [0, 3, 6],
  [1, 4, 7],
  [2, 5, 8],
  [0, 4, 8],
  [2, 4, 6]
]

def won?(board)
  WIN_COMBINATIONS.each do |single_win_combo|
    win_index_1 = single_win_combo[0]
    win_index_2 = single_win_combo[1]
    win_index_3 = single_win_combo[2]
    
    position_1 = board[win_index_1]
    position_2 = board[win_index_2]
    position_3 = board[win_index_3]
   
    if position_1 == position_2 && position_2 == position_3 && position_taken?(board, win_index_1)
      return single_win_combo
    end
  end
  return false
end

def full?(board)
  if board.any? {|index| index == nil || index == " "}
    return false
  else
    return true
  end
end

def draw?(board)
   if !won?(board) && full?(board)
     return true
   elsif!full?(board) && !won?(board)
     return false
   else won?(board)
     return false
   end
end

def over?(board)
  if draw?(board) || won?(board) || full?(board) 
    return true
  else
    return false
  end
end

# TROUBLESHOOTING: It’s important to think of position_1, position_2, position_3 as reusable and that they will cycle through all 9 spaces on the board. The elegance of comparing them to each other also got me. In draw?(board), the appearance and sequence of won?(board) and full?(board) matter.

SET UP FOR THE ENTIRE PLAY AND WINNER ANNOUNCEMENT

def winner(board)
  if won?(board)
    return board[won?(board)[0]]
  end
end

def play(board)
  counter = 0
  until counter == 9
  turn(board)
  counter += 1
  end
end

def play(board)
  until over?(board)
    turn(board) 
  end
  if won?(board)
    winner(board) == "X" || winner(board) == "O"
    puts "Congratulations #{winner(board)}!"
  else draw?(board)
    puts "Cat\'s Game!"
  end
end

# TROUBLESHOOTING: I had a hard time (still do) associating and differentiating won?(board)[0] and single_win_combo and position_1. I think an important take away for me is the difference between being INSIDE the method vs. ability to use output OUTSIDE of the method.

Reach out if you’re learning too and want to share.

Son Doong Cave - Explore The Largest Cave in the World

Why am I writing this blog post?

It's important to state clear my intention in writing this post. I want to preserve Son Doong Cave as it is, despite all of efforts to commercialize into massive tours. Ironically, the way to preserve is through more people seeing Son doong either through small guided eco-tours or by reading about it. Hope you will see that Son Doong is a world treasure belonging to everyone, not just a person or a country. I hope the Unesco sees this cleary as well.

My second goal is to share my own experience in prepping and exploring the cave with the hope to peak your interest and prepare you for the AMAZING adventure!

What makes Son Doong Cave unique?

You might have heard that Son Doong is the largest cave in the world. What does that mean really? Son Doong Cave is 9 kilometres (5.6 mi) long, 200 metres (660 ft) high and 150 metres (490 ft) wide. That's twice the size of the next largest passage in Malaysia. To put that in perspective, you can fit the Giza pyramid inside sections of Son Doong. It is estimated to be between 2 and 5 millions years old.

Source: Oxalis Adventure Tour Co.

Source: Oxalis Adventure Tour Co.

Son Doong is also unique because it has been preserved since the Earth creation and was only explored thoroughly starting 2009. When you are in Son Doong, every rock, trees, drop of water, might not have been touch for millions of years. Just there patiently waiting and evolving.

There are two forests within Son Doong, situated at the two dolines (openings made when part of the cave collapsed) along the long cave. Multiple freshwater pools, fossils, vegetation and ecosystem made the ecosystem in Son Doong one of the most ancient and untouched in the world.

The people behind Son Doong Cave discovery:
1990 Ho Khanh
2009 British Cave Research Association led by Howard Limbert
The porters

I was fortunate to speak to both of these adventurers. Howard told me "I've been actively taking people one by one to Son Doong so that they realize how special it is. [That] it is something we need to preserve and protect. The Vietnamese should see for themselves and know what they have."

I would argue that not only the Vietnamese but the world should recognized Son Doong for the natural wonder that it is.

Can't wait to hear more? Email me.

Making a continent green - how Asia is rescuing itself from self-destruction

THE SITUATION The world depends on Asia to deliver cheap goods at lighting speed. Many of the world’s largest corporations hold production facilities in countries such as China, Vietnam, Thailand, and Myanmar. If China can build a 57-story building in 19 days[1], of course, China can produce 15 billion disposable plastic lunch boxes every year[2]. The world demands products that are cheap, fast, and of good quality, no matter the cost.

THE CHALLENGES

As a result of these forcible productions, Asia is facing issues of startling growth, rapid urbanization, and natural resource depletion. In 2016, Asia is the largest producer of carbon dioxide[3]. China, the number one country on the carbon dioxide emissions list, has the total CO2 emissions of the next four countries combined. According to the Population Reference Bureau, more than 60 percent of the increase in the world's urban population over the next three decades will occur in Asia, particularly in China and India, but also in Pakistan, Bangladesh, the Philippines, and Vietnam.[4] The growing concentrated population in cramped space threatens stable building developments, reliable transportation infrastructure, and healthy living spaces.

The rest of the world is worried. How can we help Asia cool down before the damages are spilled into other parts of the world? How can we infuse sustainable practices into some of the world's fastest growing economies while running at their exponentially growth rate?

Some say we need to apply pressure from the outside, pressure from powerful forces such as the U.S. and the European Union. However, the true answers come from within Asia, where a growing number of sustainable design advocates are bonding together, gaining governmental supports and taking initiatives on their own to ensure a better state for the continent. They are addressing Asia’s challenges in ways that only insiders with a global perspective can.

Below we’ll discuss some of the initiatives taking shape in Asia with a focus on those happening in mega cities such as Seoul, Kuala Lumpur, and Taipei (to name a few). These cities and their people are leading the charge to integrate green spaces and sustainable practice into the urban city layout and the modern consumption behaviors.

Skygarden brings green back to city center | Seoul, Korea

Seoul, South Korea’s capital and economic center, has 10.1 million residents which make up a fifth of the South Korea’s population.[5] To fight back the color of concrete and bricks, the city of Seoul is transforming the 938-meter section of an elevated highway into public space[6] and gives it a name of Seoul Skygarden. This once brick-and-mortar structure will house over 254 species of plants[7], not so foreign from the NYC’s Highline. Seoul plans to complete the Seoul Skygarden in 2017.[8]

LEDs lid up the streets | Hanoi, Vietnam

According to the Southeast Asia LED Lighting Market Scale and Trends in 2016, Vietnam has the most rapid growth in LED lighting market share among the major Southeast Asian nations, maintaining a year-over-year increase of more than 60 percent between 2013 and 2015.[9] In the capital, Hanoi, the government and the public are pushing to replace the public street light system with LED lights.[10]

Creating a cycling kingdom | Taipei, Taiwan

“How can cycling contribute to urban transportation? Can the European models for ‘cycling cities’ be adapted to Asia?” These are the throbbing questions at the Velo-city Global 2016 cycling conference in Taipei.[11] Started by the European Cyclists’ Federation in 1980, the Velo-city global conference series is designed to “plug cycling as a sustainable mode of transport for a liveable city”.[12] Previous host cities have included London, Vienna, Barcelona, Vancouver, and Adelaide. This year, the conference is hosted in Taipei, Taiwan, a city with challenges not unknown to other Asian cities: limited land, dense population, and unbelievable growth. As of 2015, Taipei has 112-kilometer riverside bike paths, 382-kilometer urban bike lanes, ten leisure bicycle rental stations, and 26,000 bicycle parking spaces across the city. [13] Besides its world class’ YouBike public bike-sharing system[14], the city plans to introduce shared cars and electric motorcycles. By 2020, commutes via green transport should account for 70% of all trips with cycling taking up 12%![15]

Building to last | Kuala Lumpur, Malaysia & Ho Chi Minh City, Vietnam

Asia is growing quickly in the green building category.  By 2020, Asia is estimated to be the fastest-growing region of the world at 7% a year[16]. In Singapore, 1,800 buildings are listed with Green Mark. In Malaysia, more than 500 are registered on the country’s Green Building Index.[17] Though these numbers seem small in comparison to those from the European cities or the United States, they mark Asia’s positive focus on green and smart buildings.

 

The recent International Construction Week Southeast Asia 2016 (April 11-15, 2016) in Kuala Lumpur[18] also shows the continent’s interest in sustainable construction. The conference attracted 100+ exhibitors and 10,000 attendees.[19] It brings together corporations and industry experts to share and learn from the cutting edge sustainable technologies in building constructions and infrastructure. The conference hosts seminars with special a focus on nuclear energy and technology. In addition, its three subsections: EcoBuild, EcoLight, and Solar Asia each deals with the latest technology and management to promote long-lasting, energy-saving and human-centric solutions in these respective fields.

Learning from this conference show positive developments in many Asian countries. According to EcoLight and LEDInside[20], Indonesia holds great LED market potential due to its government commitment to the energy saving policies[21], the fast growing economy in Vietnam will strongly stimulate demand for LED lighting products[22], and the India government plans to completely replace home-use lighting and street lamps in 100 cities by March 2019.[23] Additionally, according to research and consulting firm GlobalData, the Asia-Pacific (APAC) region will overtake Europe to become the largest contributor to global solar Photovoltaic (PV) capacity installations, increasing its cumulative installed capacity 5 times by 2025.[24]

On the architectural front, architects like Vo Trong Nghia[25] represents a new breed of talented passionate architects in Asia who care about green tech and green energy. His firm pioneers the use of bamboo as the alternative building material through projects such as the Vietnam Pavilion for Expo Milan 2015. In responding to the theme “feeding the planet, energy for life”, the temporary bamboo structure can be easily dissembled and reused after the event.[26] Bamboo, also known as green steel, is durable, inexpensive, and sustainable. Vo’s other projects such as the rooftop pavilion made entirely of bamboo and ropes[27] or plant-covered municipal building with green balconies on every level[28] explore the possibility of using sustainable local materials to achieve high aesthetic.

Upcycle in India

India is leading the charge in reusing and recycling every day’s objects. According to the Environmental Protection Agency, 15.1 million tons of textile waste was generated in 2013, of which 12.8 million tons were discarded.[29] The United States is the biggest exporter of used clothes, and the top importing countries of used clothing are India, Russia, and Pakistan.[30]

In India, a small startup named Bakeys[31] found a problem so unnerving and a solution so human, their Kickstarter campaign[32] beat the goal by 500%. Bakeys has found a market and a niche to produce edible utensils. According to the company’s claim, they can produce 100 sorghum-based spoons with the energy it takes to produce 1 plastic one[33], which makes this solution an attractive alternative to disposable plastic/wood cutlery and bamboo chopsticks.[34] The edible utensils are even made with flavors that are deeply rooted in the Indian culture: hot n spicy, onion and tomato, garlic, ginger, spicy or sweet.

MOVING FORWARD

In order to drive these initiatives forward, Asia has to rely on the governmental and private funding, support, and its young highly educated workforce, all are in abundant supply.

Asian countries and governments are stepping up to the challenge of building a more sustainable system that can support their exponential growth. The word “innovation” is repeated 71 times in the Chinese government’s next five-year plan.[35] China’s National Energy Administration (NEA) announced that 2016 starts off right with 52% increase in solar capacity[36], getting towards its promise to cut power sector emissions 60% by 2020.[37]

In addition, both private funds and governments throw money into the pot to encourage startups and expand opportunities for social enterprises in Asia. Thailand government recently launched a $570 millions venture fund to launch its startup scene.[38] Well-positioned startup funds such as 500 Startups is also pouring funds into Southeast Asia, with its most recent $10M pump into Vietnam.[39] If this is not impressive enough for you, the Chinese state-backed VCs managed about 2.2 trillion yuan ($339 billion), ready to give out to ventures.[40]

Not only is Asia well funded and has accumulated tremendous support from its governments, it also retains a highly educated work force. In 2015, 459,800 Chinese students alone went abroad to study[41]. Not to mention India, Vietnam, Korea, Thailand. Of the 4.2B people in Asia[42], we have enough people to start a green movement, and we hope you’ll join us.

[1] http://www.theguardian.com/world/2015/apr/30/chinese-construction-firm-erects-57-storey-skyscraper-in-19-days

[2] http://www.scmp.com/article/1711744/china-produces-about-third-plastic-waste-polluting-worlds-oceans-says-report

[3] http://www.statista.com/statistics/271748/the-largest-emitters-of-co2-in-the-world/

[4] http://www.prb.org/Publications/Articles/2001/UrbanizationTakesonNewDimensionsinAsiasPopulationGiants.aspx

[5] https://en.wikipedia.org/wiki/Seoul

[6] https://www.mvrdv.nl/projects/seoul-skygarden

[7] https://www.mvrdv.nl/projects/seoul-skygarden

[8] http://www.futurarc.com/index.cfm/projects/2016-jan-to-jun/2016-mar-apr-seoul-skygarden/

[9] http://www.ledinside.com/node/25219

[10] http://www.ledinside.com/news/2016/4/vietnam_capital_pushes_for_led_public_lighting_system

[11] http://www.star2.com/travel/adventure/2016/04/16/cycling-your-way-to-a-traffic-jam-free-city/

[12] http://www.star2.com/travel/adventure/2016/04/16/cycling-your-way-to-a-traffic-jam-free-city/

[13] http://www.velo-city2016.com/index.php/en/about/why-taipei-taiwan

[14] https://taipei.youbike.com.tw/en/index.php

[15] http://www.star2.com/travel/adventure/2016/04/16/cycling-your-way-to-a-traffic-jam-free-city/

[16] http://nesea.org/conversation/community-blog/southeast-asia-expanding-market-green-buildings

[17] http://sea-globe.com/whos-afraid-of-the-big-green-monster-green-architecture-vietnam-southeast-asia-globe/

[18] EcoBuild Southeast Asia Conference http://www.ecobuildsea.com/

[19] http://www.ecobuildsea.com/NEWS/Press-Release-1

[20] http://www.ledinside.com/

[21] http://www.ledinside.com/news/2016/3/indonesian_led_lighting_demands_propelled_by_increasing_electrification_ratio

[22] http://www.ledinside.com/news/2016/4/vietnam_capital_pushes_for_led_public_lighting_system

[23] http://www.ledinside.com/news/2016/3/bengaluru_gives_out_more_than_5m_led_bulbs_to_local_residents

[24] http://cms02.ubmmalaysia.com/Portals/19/SolarAsia%202016_lowres.pdf?timestamp=1450066750551

[25] http://votrongnghia.com/

[26] http://www.designboom.com/architecture/vietnam-pavilion-expo-milan-2015-vo-trong-nghia-05-04-2015/

[27] http://inhabitat.com/vo-trong-nghia-builds-a-lush-rooftop-pavilion-with-nothing-but-bamboo-pegs-and-rope/usersoonishikunikodesktop308_gallery-mapublishdwggma_sec-2/

[28] http://inhabitat.com/green-city-hall-proposal-in-vietnam-doubles-as-a-verdant-vertical-park/

[29] http://www.npr.org/2016/04/08/473513620/what-happens-when-fashion-becomes-fast-disposable-and-cheap

[30] http://www.npr.org/2016/04/08/473513620/what-happens-when-fashion-becomes-fast-disposable-and-cheap

[31] http://www.bakeys.com/

[32] https://www.kickstarter.com/projects/1240116767/edible-cutlery-the-future-of-eco-friendly-utensils?ref=nav_search

[33] https://www.kickstarter.com/projects/1240116767/edible-cutlery-the-future-of-eco-friendly-utensils/description

[34] https://www.kickstarter.com/projects/1240116767/edible-cutlery-the-future-of-eco-friendly-utensils/description

[35] http://techcrunch.com/2015/12/26/china-scaling-the-worlds-highest-innovation-peaks/

[36] https://cleantechnica.com/2016/04/26/total-cumulative-solar-capacity-china-passes-50-gw/

[37] http://www.theguardian.com/environment/2015/dec/02/china-says-it-will-cut-power-sector-emissions-60-by-2020

[38] https://www.techinasia.com/thailand-fund-startups

[39] http://500.co/vietnam/

[40] http://www.dealstreetasia.com/stories/china-government-is-bankrolling-the-boom-in-startup-fundraising-38950/

[41] http://monitor.icef.com/2015/03/number-of-chinese-outbound-students-up-by-11-in-2014/

[42] https://en.wikipedia.org/wiki/List_of_Asian_countries_by_population