Hosting website on aws ec2 ubuntu server

+. Static Website, Apache2

          
#!/bin/bash

#  Config 
GIT_REPO="https://github.com/username/repo.git"
DOMAIN="s1.main.com"
PROJECT_DIR="/var/www/$DOMAIN"
CONF_FILE="/etc/apache2/sites-available/$DOMAIN.conf"

#  Step 1: Install Required Packages 
echo "=================== Installing Apache2 and Git... ==================="
sudo apt update && sudo apt install -y apache2 git

#  Step 2: Clone the Project 
echo "=================== Cloning project from GitHub... ==================="
git clone "$GIT_REPO" "$PROJECT_DIR"

#  Step 3: Set Permissions 
echo "=================== Setting permissions for $PROJECT_DIR... ==================="
sudo chown -R www-data:www-data "$PROJECT_DIR"

#  Step 4: Create Apache Config 
echo "=================== Creating Apache virtual host config... ==================="
sudo tee "$CONF_FILE" > /dev/null <<EOF

    ServerAdmin  sample.admin@gmail.com
    ServerName $DOMAIN
    DocumentRoot $PROJECT_DIR

    <Directory $PROJECT_DIR>
        Options Indexes FollowSymLinks
        AllowOverride None
        Require all granted
    </Directory>

    ErrorLog \${APACHE_LOG_DIR}/$DOMAIN-error.log
    CustomLog \${APACHE_LOG_DIR}/$DOMAIN-access.log combined

EOF

#  Step 5: Enable Site and Restart Apache 
echo "=================== Enabling site... ==================="
sudo a2ensite "$DOMAIN.conf"
sudo systemctl reload apache2

echo "Deployment complete! visit: http://$DOMAIN"
          
        

+. Node Project, Nginx

          
#!/bin/bash

# Configurable variables
APP_NAME="test1"
GIT_REPO="https://github.com/username/project.git"
DOMAIN="s2.main.com"
APP_PORT=3000
APP_DIR="/var/www/$APP_NAME" #default dr that server will search for your project
ENV_SOURCE="/user/.../env-files/${APP_NAME}.env" #This is usfull when u have muiltiple env files for multiple projects,
ENV_DEST="$APP_DIR/.env"

# Update & install system dependencies
echo "=================== Updating system & installing dependencies... ==================="
sudo apt update && sudo apt upgrade -y
curl -fsSL https://deb.nodesource.com/setup_18.x | sudo -E bash -
sudo apt install -y nodejs nginx git build-essential ...

# Install PM2
echo "=================== Installing PM2... ==================="
sudo npm install -g pm2

# Clone project
echo "=================== Cloning project from GitHub... ==================="
sudo rm -rf "$APP_DIR"
sudo git clone "$GIT_REPO" "$APP_DIR" 
sudo chown -R $USER:$USER "$APP_DIR"
cd "$APP_DIR"

# Setup environment variables
echo "=================== Setting up .env file... ==================="
if [ -f "$ENV_SOURCE" ]; then
  cp "$ENV_SOURCE" "$ENV_DEST"
  echo ".env file copied to $APP_DIR"
else
  echo ".env file not found at $ENV_SOURCE"
  exit 1
fi

# Install Node.js dependencies
echo "=================== Installing project dependencies... ==================="
npm install

# Start with PM2
echo "=================== Starting app with PM2... ==================="
pm2 start index.js --name "$APP_NAME"
pm2 save
pm2 startup systemd -u $USER --hp $HOME  # Follow the output instructions
sudo systemctl enable pm2-$USER
pm2 status

# Configure Nginx reverse proxy
echo "=================== Setting up Nginx... ==================="
NGINX_CONFIG="/etc/nginx/sites-available/$APP_NAME"
sudo tee "$NGINX_CONFIG" > /dev/null <<EOF
server {
    listen 80;
    server_name $DOMAIN;
    location / {
        proxy_pass http://localhost:$APP_PORT;
        proxy_http_version 1.1;
        proxy_set_header Upgrade \$http_upgrade;
        proxy_set_header Connection 'upgrade';
        proxy_set_header Host \$host;
        proxy_cache_bypass \$http_upgrade;
    }
}
EOF

# Enable Nginx config and reload
sudo ln -sfn "$NGINX_CONFIG" /etc/nginx/sites-enabled/
sudo nginx -t && sudo systemctl reload nginx

echo ""
echo " =================== Deployment complete! ==================="
echo " Visit: http://$DOMAIN"
          
      

=> Additional elements: Add this block into your script if you want to automate with Jenkins, but you trynna deploy project manually from server. parameters in pipeline is optional if you specified a specific programming langauge for your project.

    
# ================================= 1st ===========================
sudo apt update
sudo apt install -y openjdk-11-jdk
wget -q -O - https://pkg.jenkins.io/debian/jenkins.io.key | sudo apt-key add -
sudo sh -c 'echo deb https://pkg.jenkins.io/debian binary/ > /etc/apt/sources.list.d/jenkins.list'
sudo apt update && sudo apt install -y jenkins
sudo systemctl enable --now jenkins

    
  

Then, set up your repo webhook and set up your Jenkins environment, and add pipeline:

    
# ================================= 2nd ===========================
pipeline {
  agent any

  parameters {
    choice(
      name: 'APP_TYPE',
      choices: ['node', 'php', 'laravel'],
      description: 'Select your application stack'
    )
  }

  environment {
    APP_NAME = "${params.APP_TYPE}-app"
    DEPLOY_DIR = "/var/www/${APP_NAME}"
    SSH_CRED = 'your-ssh-credential-id'
    REMOTE_USER = 'ubuntu'
    REMOTE_HOST = 'your-ec2-ip-or-domain.com'
  }

  stages {

    stage('Pull Latest Code') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              echo "🔄 Pulling latest code into ${DEPLOY_DIR}..."
              cd ${DEPLOY_DIR}
              git reset --hard
              git pull origin main
            ENDSSH
          """
        }
      }
    }

    stage('Install Dependencies') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              cd ${DEPLOY_DIR}
              if [ "${APP_TYPE}" = "node" ]; then
                echo "📦 Installing Node packages..."
                npm install
              elif [ "${APP_TYPE}" = "laravel" ]; then
                echo "📦 Installing Composer packages..."
                composer install --no-interaction --prefer-dist
                php artisan migrate --force || true
              fi
            ENDSSH
          """
        }
      }
    }

    stage('Restart/Reload Services') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              if [ "${APP_TYPE}" = "node" ]; then
                echo "♻️ Restarting Node.js app with PM2..."
                pm2 restart ${APP_NAME}
                sudo nginx -t && sudo systemctl reload nginx
              else
                echo "♻️ Reloading Apache for PHP/Laravel..."
                sudo apache2ctl configtest && sudo systemctl reload apache2
              fi
            ENDSSH
          """
        }
      }
    }
  }

  post {
    success { echo "✅ Code updated and app redeployed for ${APP_NAME}" }
    failure { echo "❌ Deployment failed" }
  }
}
    
      

          
  # ================================= Deploy from scratch ===========================
  pipeline {
  agent any

  parameters {
    choice(
      name: 'APP_TYPE',
      choices: ['node', 'php', 'laravel'],
      description: 'Select your application stack'
    )
  }

  environment {
    APP_NAME     = "${params.APP_TYPE}-app"
    REPO_URL     = 'git@github.com:username/repo.git'
    DEPLOY_DIR   = "/var/www/${APP_NAME}"
    ENV_SOURCE   = "/home/.../env-files/${APP_NAME}.env"
    ENV_DEST     = "${DEPLOY_DIR}/.env"
    SSH_CRED     = 'your-ssh-credential-id'
    REMOTE_USER  = 'ubuntu' // or other name
    REMOTE_HOST  = 'your-ec2-ip-or-domain.com'
  }

  stages {

    stage('Mkdir') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              echo "📁 Preparing deployment directory..."
              sudo rm -rf ${DEPLOY_DIR}
              sudo mkdir -p ${DEPLOY_DIR}
              sudo chown -R \$USER:\$USER ${DEPLOY_DIR}
            ENDSSH
          """
        }
      }
    }

    stage('Clone project') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              echo "🔄 Cloning project..."
              git clone ${REPO_URL} ${DEPLOY_DIR}
            ENDSSH
          """
        }
      }
    }

    stage('Setup Env') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              if [ -f "${ENV_SOURCE}" ]; then
                echo "🔐 Copying .env..."
                cp ${ENV_SOURCE} ${ENV_DEST}
              else
                echo "⚠️ .env not found at ${ENV_SOURCE} — skipping"
              fi
            ENDSSH
          """
        }
      }
    }

    stage('Install Dependencies') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              cd ${DEPLOY_DIR}
              if [ "${APP_TYPE}" = "node" ]; then
                echo "📦 Installing Node packages..."
                npm install
              elif [ "${APP_TYPE}" = "laravel" ]; then
                echo "📦 Installing Laravel dependencies..."
                composer install --no-interaction --prefer-dist
                php artisan config:clear
                php artisan config:cache
                php artisan migrate --force || true
              elif [ "${APP_TYPE}" = "php" ]; then
                echo "📦 No dependency manager for basic PHP app — skipping"
              fi
            ENDSSH
          """
        }
      }
    }

    stage('Set Permissions') {
      when {
        expression { params.APP_TYPE == 'laravel' || params.APP_TYPE == 'php' }
      }
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              echo "🔐 Setting permissions..."
              sudo chown -R www-data:www-data ${DEPLOY_DIR}
              sudo find ${DEPLOY_DIR} -type f -exec chmod 644 {} \\;
              sudo find ${DEPLOY_DIR} -type d -exec chmod 755 {} \\;
              if [ "${APP_TYPE}" = "laravel" ]; then
                sudo chmod -R ug+rwx ${DEPLOY_DIR}/storage ${DEPLOY_DIR}/bootstrap/cache
              fi
            ENDSSH
          """
        }
      }
    }

    stage('Start App') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              if [ "${APP_TYPE}" = "node" ]; then
                echo "🚀 Starting Node.js app with PM2..."
                pm2 delete ${APP_NAME} || true
                pm2 start ${DEPLOY_DIR}/index.js --name ${APP_NAME}
                pm2 save
              else
                echo "⚙️ PHP-based app, no process manager required"
              fi
            ENDSSH
          """
        }
      }
    }

    stage('Reload Server') {
      steps {
        sshagent([env.SSH_CRED]) {
          sh """
            ssh ${REMOTE_USER}@${REMOTE_HOST} << 'ENDSSH'
              if [ "${APP_TYPE}" = "node" ]; then
                echo "🔁 Reloading Nginx..."
                sudo nginx -t && sudo systemctl reload nginx
              else
                echo "🔁 Reloading Apache..."
                sudo apache2ctl configtest && sudo systemctl reload apache2
              fi
            ENDSSH
          """
        }
      }
    }
  }

  post {
    success { echo "✅ Fresh deployment completed for ${APP_NAME}" }
    failure { echo "❌ Something went wrong. Check Jenkins logs." }
  }
}
          
        

Setup DNS on linux server
This bash script is only for setting up dns server, not complete all dns requirement like lisence, security, ...

          
#!/bin/bash

RED='\033[0;31m'
GREEN='\033[0;32m'
PURPLE='\033[35m'
RESET='\033[0m'
echo -e "${PURPLE}=========================== Clean up any existing libraries for dns =========================${RESET}"
sudo systemctl stop bind9
sudo apt-get purge bind9 -y
sudo rm -rf /etc/bind/
sudo rm -rf /var/cache/bind/
if [ $? -eq 0 ]; then
        echo -e "${GREEN}Related libs was cleaned.${RESET}"
else
        echo -e "${RED}Clean up related libs failed.${RESET}"
        exit 1
fi
echo -e "${PURPLE}=========================== Update sys libraries =========================${RESET}"
sudo apt update

echo -e "${PURPLE}=================== 1.Download bind9 and its package =======================${RESET}"
sudo apt install bind9 bind9utils bind9-doc -y
sudo apt install net-tools
echo -e "${GREEN}CHECK WAS BIND9 SUCESSFUL INSTALLED.${RESET}"
ls -l /etc/bind/
echo -e "${PURPLE}========================== 2.Start & enable bind9 ==========================${RESET}"
sudo systemctl start bind9
sudo systemctl enable bind9
if [ $? -eq 0 ]; then
        echo -e "${GREEN}Step 2 success.${RESET}"
fi

echo -e "${PURPLE}================== 3.Add prefered DNS in  named.conf.options =================${RESET}"

sed -i '/forwarders {/,/};/ s/\/\///g' /etc/bind/named.conf.options
sed -i '/forwarders {/,/};/ s/0\.0\.0\.0;/8\.8\.8\.8;\n8.8.4.4;/' /etc/bind/named.conf.options
if [ $? -eq 0 ]; then
        echo -e "${GREEN}Step 3 success.${RESET}"
else
        echo -e "${RED}Step 3 failed.${RESET}"
        exit 1
fi

echo -e "${PURPLE}============================== 4.Set domain name = ==========================${RESET}"
touch /etc/bind/db.group1.com
touch /etc/bind/db.128

echo -e ";\n;BIND data for g1.com\n;\n$"TTL"\t604800\n@\tIN\tSOA\tg1.com. admin.g1.com. (\n\t\t\t2\t;Serial\n\t\t\t604800\t;Refresh\n\t\t\t86400\t;Retry\n\t\t\t2419200\t;Expire\n\t\t\t604800 );Negative Cache TTL\n\n@\tIN\tNS\tg1.com.\n@\tIN\tA\t10.0.2.15\n@\tIN\tAAAA\t::1" > /etc/bind/db.group1.com
echo -e ";\n;BIND reverse data for g1.com\n;\n$"TTL"\t604800\n@\tIN\tSOA\tg1.com. admin.g1.com. (\n\t\t\t2\t;Serial\n\t\t\t604800\t;Refresh\n\t\t\t86400\t;Retry\n\t\t\t2419200\t;Expire\n\t\t\t604800 );Negative Cache TTL\n\n@\tIN\tNS\tg1.com.\n15\tIN\tPTR\tg1.com." > /etc/bind/db.128
echo -e 'zone "g1.com" {\n\ttype master;\n\tfile "/etc/bind/db.group1.com";\n};\n\nzone "15.2.0.10.in-addr.arpa" {\n\ttype master;\n\tfile "/etc/bind/db.128";\n};' > /etc/bind/named.conf.local

if [ $? -eq 0 ]; then
        echo -e "${GREEN}Step 4 success.${RESET}"
else
        echo -e "${RED}Step 4 failed.${RESET}"
        exit 1
fi

echo -e "${PURPLE}============================= 5.Restart bind9 ==============================${RESET}"
sudo systemctl restart bind9
if [ $? -eq 0 ]; then
        echo -e "${GREEN}Step 5 success.${RESET}"
fi

echo -e "${PURPLE}===================== 6.Enable, allow & reload  ufw ==============================${RESET}"
sudo ufw enable
sudo ufw allow bind9
sudo ufw reload
echo -e "======================= ${PURPLE}check ufw status${RESET} =============================="
sudo ufw status

echo -e "${PURPLE}========================== 7.Add Sername ====================================="
echo  "Edit nameserver in /etc/resolv.conf from 127.0.0.53 to 10.0.0.15 ${RESET}"
sed -i 's/nameserver/10.0.2.15/g' /etc/resolv.conf

echo -e "======================= ${GREEN}Completed All Step${RESET} =========================="
echo -e "${GREEN}---------------  Check nslookup g1.com -----------------${RESET}"
nslookup g1.com

          
        

Config router & terminal security on Cisco console

          
Router> enable
Router# configure terminal

! Set hostname and secret password
Router(config)# hostname R1
R1(config)# enable secret MySecurePass123

! Disable DNS lookup to prevent delays on mistyped commands
R1(config)# no ip domain-lookup

! Configure LAN interface with IP
R1(config)# interface gigabitethernet 0/0
R1(config-if)# ip address 192.168.10.1 255.255.255.0
R1(config-if)# no shutdown
R1(config-if)# exit

! Secure console (physical terminal) access
R1(config)# line console 0
R1(config-line)# password ConsolePass
R1(config-line)# login
R1(config-line)# exit

! Secure VTY (remote terminal) access
R1(config)# line vty 0 4
R1(config-line)# password VTYpass
R1(config-line)# login
R1(config-line)# exit

! Encrypt all plain-text passwords
R1(config)# service password-encryption

! Display login banner
R1(config)# banner motd #Unauthorized access is prohibited!#

! Save configuration
R1# copy running-config startup-config
          
        

Remote & maintain AWS Access Key age on linux server

I'll update when I'm free

Query data and document to excel file
This is python script.

          
    import pandas as pd
    import mysql.connector
    import json

    # connect to db 
  
    db = mysql.connector.connect( 
      host="host",
      user="username",
      passwd="pwd",
      db="dbname",
      ssl_disabled=True 
    )

    cursor = db.cursor()
    cursor = db.cursor(dictionary=True)
  
    with open("filename.json") as file:
      datas = json.load(file)

    for data in datas:
      object_name = f"""
        SELECT first_attribute, sencond_attribute, ... FROM table_name WHERE
        conditions 
      """
     # Execute query 
    
      cursor.execute(object_name)
      first_query = cursor.fetchall()

     # Select data from another table 
  
    new_object = f"""
      SELECT attributes FROM table_name WHERE conditions 
    """
  
     # Execute query 
  
    cursor.execute(new_object)
    second_query = cursor.fetchall()

     # Prepare a list to hold the decoded data 
  
    decoded_results = []

     # Loop through query results and decode
  
    for data in first_query:
      decoded_row = { 
        'name_attribute1': data['attribute_name1'],
        'name_attribute2': data'attribute_name2'],... }
    
      #This filter incase the table have one to many relation. We select
      data from single side place as title, and data from many side place
      as data of each title.
      filter_value = [value for value in second_query if value["id"] ==
      data["id"]

    for idx, filter_option in enumerate(filter_options, start=1):
      decoded_row[f'title1{idx}'] = filter_value['title1']
      decoded_row[f'title2{idx}'] = filter_value['title2']
      decoded_row[f'title3{idx}'] = filter_value['title3']
    decoded_results.append(decoded_row)

    # Convert the decoded data into an excel form
    df = pd.DataFrame(decoded_results)
    file_name = f"{name_your_file}.xlsx"
    df.to_excel(file_name, index=False)
    print(f"Done for: {file_name}")

  cursor.close()
  db.close()
  print ("Completed!!")
          
        

Hash hack
Decrypt hash with your own brain

Know which lib they are used to encrypt that hash => understand its encryption algorithm/concept => know binary value for each numeric or alphabet ... or the dataset of that lib.

Simple Grid Game
It is a simple grid game built for desktop. Using python tkinter GUI. Use arrow key to move the charater. It is my 1st year project spending last minutes like 2 days before presentation, after the first one failed 😅.

            
            
  # !=======================================constant===============================
  
  MARIO_CELL = 3
  DIAMOND_CELL=1
  BLUE_DIAMOND_CELL=2
  CION_CELL=4
  NOTHING=0
  GRID_LIN=9
  score=0
  
  # !=======================================Variable===============================
  
  grid=[
      [1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,],
      [1,0,0,4,0,0,0,1,4,4,4,1,2,0,0,0,0,0,0,0,],
      [1,0,4,4,4,0,0,1,4,4,4,1,0,0,0,0,0,0,0,0,],
      [1,0,0,4,0,0,2,4,4,4,4,1,0,0,0,0,0,0,0,0,],
      [1,1,1,1,1,0,0,1,1,1,1,1,0,0,0,0,0,0,0,0,],
      [0,0,0,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,],
      [0,0,0,0,1,0,0,1,0,0,0,0,0,0,4,4,4,4,4,0,],
      [3,0,0,0,1,0,0,1,0,0,2,0,0,0,4,1,4,1,4,0,],
      [4,1,1,1,1,0,0,4,0,0,0,0,0,0,0,4,4,4,0,0,],
      [0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,4,1,0,0,0,],
      [1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,],
  ]
  # !======================================Draw grid===============================
  
  def draw_grid():
      global move,move_up,move_down,move_left,move_right
      cell_x=0
      cell_y=10
      isWin=True
      if isWin and score<29:
          for row in grid:
              cell_y+=46
              y2=cell_y+46
              cell_x=0
              for col in range(len(row)):
                  cell_x+=46
                  x2=cell_x+46
                  if row[col]==NOTHING:
                      canvas.create_rectangle(cell_x,cell_y,x2,y2,fill='',outline='')
                  elif row[col]==DIAMOND_CELL:
                      canvas.create_rectangle(cell_x,cell_y,x2,y2,fill='purple',outline='')
                      diamond=canvas.create_image(cell_x,cell_y,image=diamond_img,anchor='nw')
                  elif row[col]==BLUE_DIAMOND_CELL:
                      canvas.create_rectangle(cell_x,cell_y,x2,y2,fill='',outline='')
                      star=canvas.create_image(cell_x,cell_y,image=star_img,anchor='nw')
                  elif row[col]==MARIO_CELL:
                      canvas.create_rectangle(cell_x,cell_y,x2,y2,fill='pink',outline='cyan')
                      mari=canvas.create_image(cell_x,cell_y,image=mario_img,anchor='nw')
                  elif row[col]==CION_CELL:
                      canvas.create_rectangle(cell_x,cell_y,x2,y2,fill='yellow',outline='')
                      cion=canvas.create_image(cell_x,cell_y,image=cion_img,anchor='nw')
      elif score==29:
          win()
  # !======================================Move mario===============================
  
      def move(direction):
          canvas.delete("all")
          winsound.PlaySound('sound/fireball.wav',winsound.SND_FILENAME|winsound.SND_ASYNC)
          global score
          isTrue=True
          for row in range(len(grid)):
              for col in range(len(grid[row])):
                  if direction=='right':
                      if (grid[row][col]==MARIO_CELL and col0 and (grid[row][col-1] != DIAMOND_CELL):
                          if grid[row][col-1]==CION_CELL:
                              winsound.PlaySound('sound/coin.wav',winsound.SND_FILENAME|winsound.SND_ASYNC)
                              score+=1
                      
                          grid[row][col]=0
                          grid[row][col-1]=MARIO_CELL
                          break
                  elif direction=='up':
                      if grid[row][col]==MARIO_CELL and row>0 and (grid[row-1][col] != DIAMOND_CELL) :
                          if grid[row-1][col]==CION_CELL:
                              winsound.PlaySound('sound/coin.wav',winsound.SND_FILENAME|winsound.SND_ASYNC)
                              score+=1
                          if grid[row][col] != DIAMOND_CELL or  grid[row][col] != BLUE_DIAMOND_CELL:
                              grid[row][col]=0
                              grid[row-1][col]=MARIO_CELL
                              break
                  elif direction=='down':
                      if grid[row][col]==MARIO_CELL and row<10 and isTrue and (grid[row+1][col] != DIAMOND_CELL) :
                          if grid[row+1][col]==CION_CELL and isTrue:
                              winsound.PlaySound('sound/coin.wav',winsound.SND_FILENAME|winsound.SND_ASYNC)
                              score+=1
                          grid[row][col]=0
                          grid[row+1][col]=MARIO_CELL
                          isTrue=False
      # !=======================================Game background==========================
          canvas.create_image(0,0,image=background,anchor='nw')
          canvas.create_text(530,600,text='Your score: '+str(score),fill='yellow',font=('',30,'bold'))
          draw_grid()
  
      def move_right(e):
          move('right')
      def move_left(e):
          move('left')
      def move_up(e):
          move('up')
      def move_down(e):
          move('down')
  # !======================================= end game feature==========================
  def win():
      global button_exit,button_replay
      canvas.create_text(500,400,text="YOU WIN !",font=("",25,"bold"),fill="white")
      canvas.create_text(500,450,text="CONGRATULATION !",font=("",25,"bold"),fill="white")
      canvas.create_window(100,500,window=button_exit)
      canvas.create_window(900,500,window=button_replay)
  def replay():
      root.destroy()
      os.system('python grid_game.py')
  def exit():
      root.destroy()
  def check_button():
      canvas.create_window(100,500,window=button_exit)
      canvas.create_window(900,500,window=button_replay)
  
  # !================================== Create window==============================    
  from tkinter import*
  import winsound
  import os
  root=Tk()       
  root.geometry('1000x700')
  frame=Frame()
  frame.master.title('project game')
  canvas=Canvas(frame)
  
  # !=======================================All images===============================
  background=PhotoImage(file='img/bg.png')
  diamond_img=PhotoImage(file='img/diamond.png')
  star_img=PhotoImage(file='img/blue_mix_purple.png')
  cion_img=PhotoImage(file='img/cion.png')
  mario_img=PhotoImage(file='img/mario.png')
  
  # !=======================================Game background==========================
  canvas.create_image(0,0,image=background,anchor='nw')
  
  # !======================================= Create button ==========================
  button_exit=Button(text="Exit",padx=10,pady=5,font=("",25,"bold"),bg="cyan",command=exit)
  button_replay=Button(text="Replay",padx=10,pady=5,font=("",25,"bold"),bg="cyan",command=replay)
  
  button_check=Button(text="Check button",padx=10,pady=5,font=("",25,"bold"),bg="cyan",command=check_button)
  canvas.create_window(200,610,window=button_check)
  
  draw_grid()
  # !=======================================All events===============================
  root.bind('',move_up)
  root.bind('',move_down)
  root.bind('',move_left)
  root.bind('',move_right)
  
  frame.pack(expand=True,fill='both')
  canvas.pack(expand=True,fill='both')
  root.mainloop()