mexicanhat.py

Created by rr-inyo

Created on September 01, 2025

1.45 KB

Draws a Mexican hat.


# Mexican hat for Numworks Python
# (c) 2024 RR_Inyo

import math
import kandinsky
import time

def mexhat():
  # Get timer
  t0 = time.monotonic()
  
  # Define variables
  d = [221] * 320
  dr = math.pi / 180
  
  # Draw black background
  c = kandinsky.color(0, 0, 0)
  kandinsky.fill_rect(0, 0, 320, 222, c)
  
  for y in range(-180, 180, 6):
    for x in range(-180, 180, 4):
      # Calculate
      r = dr * math.sqrt(x**2 + y**2)
      z = 100 * math.cos(r) - 30 * math.cos(3 * r)
      sx = int(160 + x / 1.5 - y / 2)
      sy = int(110 - y / 4 - z / 2)

      # Check drawing area
      if (sx < 0):
        continue
      if (sx > 319):
        continue
      if (d[sx] <= sy):
        continue
      
      # Decide a color
      zz = int((z + 100) * 0.035) + 1
      col_r = 0
      col_g = 0
      col_b = 0
      if zz == 1:
        col_b = 255
      if zz == 3:
        col_b = 255
      if zz == 5:
        col_b = 255
      if zz == 7:
        col_b = 255
      if zz == 2:
        col_r = 255
      if zz >= 6:
        col_r = 255
      if zz >= 4:
        col_g = 255
      c = kandinsky.color(col_r, col_g, col_b)
      
      # Make a pixel
      kandinsky.set_pixel(sx, sy, c)
      d[sx] = sy
  
  # Draw text
  c = kandinsky.color(255, 255, 255)
  cb = kandinsky.color(0, 0, 0)
  kandinsky.draw_string('Mexican Hat', 100, 20, c, cb)
  # Get timer again
  t1 = time.monotonic()
  print('Time to draw: {:.2f} ms'.format((t1 - t0) * 1000))

During your visit to our site, NumWorks needs to install "cookies" or use other technologies to collect data about you in order to:

With the exception of Cookies essential to the operation of the site, NumWorks leaves you the choice: you can accept Cookies for audience measurement by clicking on the "Accept and continue" button, or refuse these Cookies by clicking on the "Continue without accepting" button or by continuing your browsing. You can update your choice at any time by clicking on the link "Manage my cookies" at the bottom of the page. For more information, please consult our cookies policy.