Tutorial 10: Diamond Shapes using Loops in GDScript

extends Node2D
# Draws a diamond with adjustable size

func _ready():
     # Try changing 6 with even integers from 4 to 26
     diamond_for(6)
     diamond_while(6)

func diamond_for(size: int):
     tri_for(size)  #Upside Triangle
     inv_tri_for(size) #Downside Triangle

func tri_for(size: int):
     for i in range(1, size, 2):
          var k: String = ""
          for j in range((((size - 1) - i) / 2) + i, 0, -1):
               k += "▲" if j <= i else " " # Ternary-if with increment operator
          print(k)
  
func inv_tri_for(size: int):
     for i in range(size - 1, 0, -2):
          var k: String = ""
          for j in range((((size - 1) - i) / 2) + i, 0, -1):
               k += "▼" if j <= i else " " # Ternary-if with increment operator
          print(k)

func diamond_while(size: int):
     tri_while(size)      #Upside Triangle
     inv_tri_while(size)  #Downside Triangle

func tri_while(size: int, i: int = 1):
     while i < size:
          var k: String = ""
          var j: int = (((size - 1) - i) / 2) + i
          while j > 0:
               k += "▲" if j <= i else " " # Ternary-if with increment operator
               j -= 1
          print(k)
          i += 2

func inv_tri_while(size: int):
     var i: int = size - 1
     while i > 0:
          var k: String = ""
          var j: int = (((size - 1) - i) / 2) + i
          while j > 0:
               k += "▼" if j <= i else " " # Ternary-if with increment operator
               j -= 1
          print(k)
          i -= 2

Output:

  ▲
 ▲▲▲
▲▲▲▲▲
▼▼▼▼▼
 ▼▼▼
  ▼
  ▲
 ▲▲▲
▲▲▲▲▲
▼▼▼▼▼
 ▼▼▼
  ▼

Building from the previous tutorials of using the for and while loop statements, in this tutorial, we will use them to produce diamond shapes. But with bits of challenges, like using nested loops and introducing the use of ternary-if statement to reduce code lines. You can copy the code above or download the source code here.

Equivalent of the Ternary-if in basic if-else statement of the code above:

  # k += "▲" if j <= i else " " # Ternary-if with increment operator
   if j <= i:
        k += "▲"
   else:
        k += " "

The GDScript above shows how to use for-loop or while-loop in creating the same diamond shape results. Being meticulous, for-loops has less code lines and character counts compared to while-loops for most of time.

Basically, the diamond functions calls other functions that produces upside and downside triangles. It's always good to divide them into smaller functions for easy debugging when codes gets too large.

As for your practice, use similar techniques to produce a square that is resizable based on input size.

0 comments:

Post a Comment

© 2020 by Emman Lijesta, all rights reserved. Powered by Blogger.