Snippets Collections
/* eslint-disable max-lines */
import { useDashboardData } from "api/hooks/dashboard/useDashboardData";
import { useEffect, useState } from "react";
import { isAdminSite } from "utils/appUtils";
import { getColumnTotal } from "utils/helper";

import { rowsPerPageOptions } from "constants/data";
import { SubHeading } from "constants/enums";
import { images } from "constants/images";
import { paymentHistoryColumns } from "pages/bookings/paymentHistoryTable";
import { Box, Card, Loader, IconButton, Image } from "uiCore";
import { DetailsCard } from "uiCore/detailsCard/DetailsCard";

import { excelDownload } from "../downloadList";
import { BookingFilter } from "../Filter";
import { PaymentDetailsDialog } from "../PaymentDetailsModel";
import { BookingTable } from "../Table";
import { useStyle } from "./style";

export interface FilterProps {
  gameId?: string;
  courtId?: string;
  startDate?: string;
  endDate?: string;
  createdEndDate?: string;
  createdStartDate?: string;
}

export interface Props {
  isUpcomingBooking?: boolean;
}

export const ManageBookings = ({ isUpcomingBooking = false }: Props) => {
  const [upcomingLimit, setUpcomingLimit] = useState(10);
  const [bookingHistoryLimit, setBookingHistoryLimit] = useState(10);
  const initialFilterData = {
    page: 1,
    limit: upcomingLimit,
    gameId: "",
    courtId: "",
    startDate: "",
    endDate: "",
    createdEndDate: "",
    createdStartDate: "",
    isClear: false,
    isUpcoming: isUpcomingBooking,
  };

  const [filterData, setFilterData] = useState(initialFilterData);
  const [totalAmount, setTotalAmount] = useState(0);

  const [filterOpen, setFilterOpen] = useState(false);
  const classes = useStyle({ filterOpen });
  const [queryData, setQueryData] = useState(filterData);
  const [openPaymentDetailModal, setOpenPaymentDetailModal] = useState(false);
  const [isFilterApplied, setIsFilterApplied] = useState(false);
  const [selectedOrderId, setSelectedOrderId] = useState("");
  const [isExcelDataLoading, setIsExcelDataLoading] = useState(false);

  const { dashboardData, isDashboardLoading, isDashboardSuccess } =
    useDashboardData(queryData);

  useEffect(() => {
    if (dashboardData?.data?.paymentLogs?.length) {
      const amount = getColumnTotal(dashboardData.data.paymentLogs, "amount");
      setTotalAmount(amount);
    }
  }, [dashboardData]);

  useEffect(() => {
    if (filterData.isClear) {
      isFilterApplied && setQueryData({ ...filterData });
      setFilterData({ ...filterData, isClear: false });
      setIsFilterApplied(false);
    }
  }, [filterData]);

  useEffect(() => {
    setQueryData({
      ...initialFilterData,
      limit: isUpcomingBooking ? upcomingLimit : bookingHistoryLimit,
      isUpcoming: isUpcomingBooking,
    });
    setFilterData(initialFilterData);
  }, [isUpcomingBooking]);

  const handleFilter = () => {
    setFilterOpen(!filterOpen);
  };

  const handleSetFilterData = (filterProps: FilterProps) => {
    setFilterData((prev) => ({
      ...prev,
      ...filterProps,
    }));
  };

  const handleFilterSubmit = () => {
    let dateData = {};
    if (filterData.startDate && !filterData.endDate) {
      dateData = { endDate: filterData.startDate };
    }

    if (filterData.createdStartDate && !filterData.createdEndDate) {
      dateData = { createdEndDate: filterData.createdStartDate };
    }
    setQueryData((prev) => ({
      ...prev,
      ...filterData,
      isUpcoming: isUpcomingBooking,
      ...dateData,
    }));
    setFilterOpen(false);
    setIsFilterApplied(true);
  };
  const handleFilterClear = () => {
    setFilterData({
      ...initialFilterData,
      isClear: true,
      isUpcoming: isUpcomingBooking,
    });
  };

  const handlePageChange = (newPage: number) => {
    setQueryData({ ...queryData, page: newPage + 1 });
  };
  const handlePageSizeChange = (limit: number) => {
    if (queryData.isUpcoming) {
      setUpcomingLimit(limit);
    } else {
      setBookingHistoryLimit(limit);
    }
    setQueryData({ ...queryData, page: 1, limit });
  };

  const closePaymentDetailsDialog = () => {
    setOpenPaymentDetailModal(false);
  };

  const handleExport = async () => {
    const totalCount = isUpcomingBooking
      ? dashboardData?.data?.totalUpcomingBookings
      : dashboardData?.data?.totalBooking;
    if (totalCount && dashboardData?.data?.paymentLogs?.length) {
      try {
        await excelDownload({
          totalCount,
          queryData,
          setIsExcelDataLoading,
        });
      } finally {
        setIsExcelDataLoading(false);
      }
    }
  };

  const {
    courtId,
    createdEndDate,
    createdStartDate,
    endDate,
    gameId,
    startDate,
  } = filterData;

  const buttonDisable =
    !gameId &&
    !courtId &&
    !startDate &&
    !endDate &&
    !createdStartDate &&
    !createdEndDate;

  return (
    <>
      <Box className={classes.topCardsGroup}>
        {!isUpcomingBooking && (
          <>
            <DetailsCard
              label={isAdminSite ? "Total Earnings" : "Total Paid"}
              isLoading={isDashboardLoading}
              data={dashboardData?.data?.totalEarning}
              rupeesIcon
              decimal={2}
              icon={images.totalAmount.default}
            />
            <DetailsCard
              label="Total Bookings"
              isLoading={isDashboardLoading}
              data={dashboardData?.data?.totalBooking}
              icon={images.booking.default}
              isTotalBooking
            />
          </>
        )}
        <DetailsCard
          label="Total Amount"
          isLoading={isDashboardLoading}
          rupeesIcon
          data={
            dashboardData?.data?.paymentLogs.length > 0
              ? Number(totalAmount)
              : 0
          }
          icon={images.totalAmount.default}
          decimal={2}
        />
      </Box>
      <Card
        title={
          isUpcomingBooking
            ? SubHeading.upcomingBookings
            : SubHeading.bookingHistory
        }
        headerActionClassName={classes.DashboardHeaderAction}
        sx={{ boxShadow: 5 }}
        action={
          <Box
            sx={{
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <IconButton
              onClick={handleExport}
              id="export-image"
              title="Export"
              color="primary"
              disabled={dashboardData?.data?.paymentLogs?.length === 0}
            >
              {isExcelDataLoading ? (
                <Loader size={22} />
              ) : (
                <Image src={images.download.default} />
              )}
            </IconButton>
            {(dashboardData?.data?.paymentLogs?.length > 0 ||
              !buttonDisable) && (
              <IconButton onClick={handleFilter} color="primary" title="Filter">
                <Image
                  src={images.filter.default}
                  className={classes.dashboardFilterIcon}
                />
              </IconButton>
            )}
          </Box>
        }
      >
        <Box className={classes.dashboardMain}>
          <Box className={classes.dashboardCard}>
            <Box className={classes.top}>
              <Box className={classes.dashboardFilter}>
                <Box className={classes.dashboardFilterIconMain}>
                  {filterOpen && (
                    <BookingFilter
                      gameId={filterData.gameId}
                      courtId={filterData.courtId}
                      endDate={filterData.endDate}
                      startDate={filterData.startDate}
                      createdEndDate={filterData.createdEndDate}
                      createdStartDate={filterData.createdStartDate}
                      handleFilterSubmit={handleFilterSubmit}
                      handleFilterClear={handleFilterClear}
                      handleSetFilterData={handleSetFilterData}
                    />
                  )}
                </Box>
              </Box>
            </Box>
            <Box className={classes.bottom}>
              <Box className={classes.tablesection}>
                <BookingTable
                  rowData={dashboardData?.data?.paymentLogs}
                  columns={paymentHistoryColumns(
                    setOpenPaymentDetailModal,
                    setSelectedOrderId,
                    isUpcomingBooking
                  )}
                  page={queryData.page - 1}
                  rowCount={
                    queryData.isUpcoming
                      ? dashboardData?.data?.totalUpcomingBookings
                      : dashboardData?.data?.totalBooking
                  }
                  pageSize={queryData.limit}
                  onPageSizeChange={handlePageSizeChange}
                  onPageChange={handlePageChange}
                  rowsPerPageOptions={rowsPerPageOptions}
                  loading={isDashboardLoading || !isDashboardSuccess}
                />
              </Box>
            </Box>
          </Box>
        </Box>
      </Card>
      <PaymentDetailsDialog
        closePaymentDetailsDialog={closePaymentDetailsDialog}
        openPaymentDetailModal={openPaymentDetailModal}
        selectedOrderId={selectedOrderId}
      />
    </>
  );
};
export const images = {
  confirmationImage: require("assets/images/confirmation/confirmation.gif"),
  excelIcon: require("assets/images/excel/excelIcon.png"),
  error: require("assets/images/error/error.png"),
  emptyImage: require("assets/images/emptyImage/emptyImage.png"),
  success: require("assets/icons/success.png"),
  inProgress: require("assets/icons/inProgress.gif"),
  fail: require("assets/icons/fail.png"),
  totalEarning: require("assets/icons/totalEarning.png"),
  totalAmount: require("assets/icons/Paid.svg"),
  wallet: require("assets/icons/Wallet.svg"),
  booking: require("assets/icons/Bookings.svg"),
  totalBooking: require("assets/icons/totalBooking.png"),
  totalPaid: require("assets/icons/totalPaid.png"),
  lastPayout: require("assets/icons/lastPayout.png"),
  lastPayoutTime: require("assets/icons/lastPayoutTime.png"),
  noImage: require("assets/images/emptyImage/initialImage.jpg"),
  uploadImage: require("assets/icons/upload.png"),
  download: require("assets/icons/download.svg"),
  filter: require("assets/icons/Filter.svg"),
};
def mathOp(line, tline, i, rowNum):
    op = []
    num_of_operations = 0
    num_of_AN = 0

    while i < len(line):
        if line[i] == "SUM OF":
            op.append("+")
            i += 1
            num_of_operations += 1
        elif line[i] == "DIFF OF":
            op.append("-")
            i += 1
            num_of_operations += 1
        elif line[i] == "PRODUKT OF":
            op.append("*")
            i += 1
            num_of_operations += 1
        elif line[i] == "QUOSHUNT OF":
            op.append("/")
            i += 1
            num_of_operations += 1
        elif line[i] == "MOD OF":
            op.append("%")
            i += 1
            num_of_operations += 1
        elif line[i] == "BIGGR OF":
            op.append("max")
            i += 1
            num_of_operations += 1
        elif line[i] == "SMALLR OF":
            op.append("min")
            i += 1
            num_of_operations += 1
        else:
            if tline[i] == "NUMBR":
                op.append(int(line[i]))
                i += 1
            elif tline[i] == "NUMBAR":
                op.append(float(line[i]))
                i += 1
            elif tline[i] == "VARIABLE":
                value, _ = searchVarValue(line[i])
                op.append(value)
                i += 1
            elif tline[i] == "YARN":
                value = typeCasting(line[i], tline[i], "NUMBAR", rowNum)
                op.append(value)
                i += 1
            elif tline[i] == "AN":
                i += 1
                num_of_AN += 1
            else:
                raise RuntimeError("Unexpected %r at line %d" % (line[i], rowNum))
            i += 1

    expected_operands = num_of_operations + 1
    actual_operands = len(op) - (num_of_AN + num_of_operations)
    if expected_operands != actual_operands:
        raise RuntimeError(
            "Expected %d operands, but found %d at line %d"
            % (expected_operands, actual_operands, rowNum)
        )
    else:
        return parse(deque(op))
WITH user_to_user_txn AS (
    SELECT 
        receiveruser,
        senderuserid,
        LOWER(sendernameonbankaccount) AS lower_sendername,
        COUNT(DISTINCT transaction_id) AS total_send_txns,
        SPLIT(Lower(sendernameonbankaccount), " ") AS array3,
        SUM(totaltransactionamount) AS total_send_amt
    FROM 
        fraud.transaction_details_v3
    WHERE 
        updated_date BETWEEN DATE_SUB('2023-10-02', 32) AND DATE_SUB('2023-10-02', 2)
        AND pay_transaction_status = 'COMPLETED'
        AND sendertype = 'INTERNAL_USER'
        AND workflowtype IN ('CONSUMER_TO_CONSUMER', 'CONSUMER_TO_CONSUMER_V2')
        AND transfermode IN ('PEER_TO_PEER')
        AND receiveruser <> senderuserid
    GROUP BY receiveruser, senderuserid, LOWER(sendernameonbankaccount)
),

receiver_txn AS (
    SELECT 
        receiver_identity, 
        LOWER(account_holder_name) AS lower_account_holder_name,
        SPLIT(LOWER(account_holder_name), " ") AS array1
    FROM  
        payment.transaction_receiver_instruments 
    WHERE 
        year = 2023 AND month = 09
    GROUP BY receiver_identity, LOWER(account_holder_name)
),

user_txn AS (
    SELECT 
        receiveruser,
        LOWER(receiver_name) AS lower_receiver_name,
        COUNT(DISTINCT transaction_id) AS user_txns_all_30d,
        SUM(totaltransactionamount) AS user_received_amt_all_30d
    FROM 
        fraud.transaction_details_v3
    WHERE 
        updated_date BETWEEN DATE_SUB('2023-10-02', 32) AND DATE_SUB('2023-10-02', 2)
        AND pay_transaction_status = 'COMPLETED'
        AND transfermode IN ('PEER_TO_PEER')
        AND workflowtype IN ('CONSUMER_TO_CONSUMER', 'CONSUMER_TO_CONSUMER_V2')
    GROUP BY receiveruser, LOWER(receiver_name)
),

sub_tb1 AS (
    SELECT 
        a.senderuserid,
        a.receiveruser,
        total_send_txns,
        b.user_txns_all_30d,
        b.user_received_amt_all_30d,
        a.total_send_amt,
        c.receiver_identity,
        a.array3,
        c.array1,
        ARRAY_CONTAINS(a.array3, c.array1[0]) OR
        ARRAY_CONTAINS(a.array3, c.array1[1]) OR
        ARRAY_CONTAINS(a.array3, c.array1[2]) OR
        ARRAY_CONTAINS(a.array3, c.array1[3]) AS true_falsecol2
    FROM 
        user_to_user_txn a
    LEFT JOIN 
        user_txn b ON a.receiveruser = b.receiveruser
    LEFT JOIN 
        receiver_txn c ON b.receiveruser = c.receiver_identity -- Add missing alias 'c'
    WHERE 
        total_send_txns > 200 AND total_send_txns / b.user_txns_all_30d > 0.7 and c.array1 IS NOT NULL
),

final_tb1 AS (
    SELECT *
    FROM sub_tb1
    WHERE true_falsecol2 = false -- Fix column name in WHERE clause
)

SELECT *
FROM final_tb1;
SELECT DATE_SUB('2023-12-02',32) starting_date
,DATE_SUB('2023-12-02',2) ending_date
,receiveruser AS identifier
,'NA' as active_days
,total_send_amt AS value
,'Offline-FIU-13-C2M-Large value of transactions from a single customer' AS red_flag
,'monthly' as date_range
,'AML' `group`
,'FRA' `type`
,'Alerts' as type_fra
,'User' as issue_type
,'UPI' as sub_issue_type
,concat ('total_send_txns :', total_send_txns, ',merchant_txns_all_30d:' , merchant_txns_all_30d,'senderuserid:' , senderuserid) AS comment
from final_tb1 ;
import re
from Variable import Variable
from collections import deque

vars = []


class SyntaxAnalyzer:
    def program(self, tokens, lexeme, row):
        i = 0

        while tokens[i] == "COMMENT":
            i += 1

        if tokens[i] == "START":  # encountered start of program
            print("==== PROGRAM START! === \n")
            i += 1
            while tokens[i] != "END" and i < len(tokens):
                if tokens[i] == "COMMENT":
                    i += 1
                    continue

                if tokens[i] == "WAZZUP":
                    i += 1
                    i = isVarDec(tokens, lexeme, row, i)

                i = statement(tokens, lexeme, row, i)

                if i >= len(tokens):
                    break
            if i == len(tokens):
                raise RuntimeError("End of program not found")
            # printVariables()
        else:
            raise RuntimeError("Start of program not found")


def isVarDec(tokens, lexeme, row, i):
    maxlen = len(tokens)
    while tokens[i] != "BUHBYE":
        if tokens[i] == "COMMENT":  # aka BTW (single line comment)
            # comments are stored all in one, if it's a multiline is when we iterate thru so this is fine
            i += 1
            continue
        elif tokens[i] == "VAR_DEC":
            # build line
            rowNum = row[i]
            line = []
            tline = []
            while rowNum == row[i]:
                line.append(lexeme[i])
                tline.append(tokens[i])
                i += 1
            storeVariable(tline, line, rowNum)
        else:
            raise RuntimeError(
                "Unexpected %r on line %d, Only variable declarations are allowed in this section"
                % (lexeme[i], row[i])
            )

        if i >= maxlen:
            raise RuntimeError("Encountered end of file")
    return i


def storeVariable(tline, line, rowNum):
    global vars

    i = 1
    maxlength = len(tline)
    if tline[i] == "VARIABLE":
        varName = line[i][:-1]
        i += 1
    else:
        raise RuntimeError("Expected VARIABLE NAME on line %d" % (rowNum))

    if i >= maxlength:
        vars.append(Variable(varName, "NOOB", None))
        return

    if tline[i] == "ITZ":
        i += 1
    else:
        raise RuntimeError("Expected 'ITZ' on line %d" % (rowNum))

    if i >= maxlength:
        raise RuntimeError("Encountered end of file!")

    if (
        tline[i] == "NOOB"
        or tline[i] == "YARN"
        or tline[i] == "TROOF"
        or tline[i] == "NUMBAR"
        or tline[i] == "NUMBR"
        or tline[i] == "VARIABLE"
    ):
        type = tline[i]
        value = line[i]
        vars.append(Variable(varName, type, value))
        return
    else:
        raise RuntimeError(
            "Variable declaration can only be to a YARN, TROOF, NOOB etch"
        )
    vars.append(Variable("IT", "NOOB", ""))


def statement(tokens, lexeme, row, i):
    tline = []
    line = []
    rowNum = row[i]
    # print(rowNum)
    while rowNum == row[i]:
        tline.append(tokens[i])
        line.append(lexeme[i])
        i += 1

    if tline[0] == "PRINT":
        printLine(line, tline)
    elif tline[0] == "VAR_DEC":
        raise RuntimeError("Unexpected variable declaration at line %d" % (rowNum))
    elif tline[0] == "BOOL_OPER":
        print(boolOpRegion(line, tline, 0, rowNum))
    elif tline[0] == "COMPARISON":
        print(comparison(line, tline, 0, rowNum))
    elif tline[0] == "MATH":
        print(mathOp(line, tline, 0, rowNum))
    return i


def comparison(line, tline, i, rowNum):
    compQ = []
    # print(line)
    if line[i] == "BOTH SAEM":
        i += 1
        if tline[i] == "NUMBR" or tline[i] == "NUMBAR":
            compQ.append([tline[i], line[i]])
            i += 1
        elif tline[i] == "VARIABLE":
            value, type = searchVarValue(line[i])
            compQ.append([type, value])
            i += 1
        else:
            raise RuntimeError(
                "Expected NUMBR, NUMBAR, or VARIABLE at line %d" % (rowNum)
            )
        if tline[i] != "AN":
            raise RuntimeError("Expected AN at line %d" % (rowNum))
        i += 1
        if line[i] == "BIGGR OF" or line[i] == "SMALLR OF":
            compQ.append(line[i])
            i += 1
            if tline[i] == "NUMBR" or tline[i] == "NUMBAR":
                compQ.append([tline[i], line[i]])
                i += 1
            elif tline[i] == "VARIABLE":
                value, type = searchVarValue(line[i])
                compQ.append([type, value])
                i += 1
            else:
                raise RuntimeError(
                    "Expected NUMBR, NUMBAR, or VARIABLE at line %d" % (rowNum)
                )
            if compQ[0][1] != compQ[2][1]:
                raise RuntimeError(
                    "Value mismatch - operand 1 and 2 (%r and %r) must be same"
                    % (compQ[0][1], compQ[2][1])
                )
            if tline[i] != "AN":
                raise RuntimeError("Expected AN at line %d" % (rowNum))
            i += 1
            if tline[i] == "NUMBR" or tline[i] == "NUMBAR":
                compQ.append([tline[i], line[i]])
                i += 1
            elif tline[i] == "VARIABLE":
                value, type = searchVarValue(line[i])
                compQ.append([type, value])
                i += 1
            else:
                raise RuntimeError(
                    "Expected NUMBR, NUMBAR, or VARIABLE at line %d" % (rowNum)
                )
        elif tline[i] == "NUMBR" or tline[i] == "NUMBAR":
            compQ.append([tline[i], line[i]])
            i += 1
        elif tline[i] == "VARIABLE":
            value, type = searchVarValue(line[i])
            compQ.append([type, value])
            i += 1
        else:
            raise RuntimeError(
                "Expected NUMBR, NUMBAR, VARIABLE, BIGGR OF, or SMALLR OF at line %d"
                % (rowNum)
            )

        # print(compQ)
        if compQ[1] == "BIGGR OF":
            if compQ[2][0] != compQ[3][0]:
                raise RuntimeError(
                    "Type mismatch - cannot compare %r and %r"
                    % (compQ[0][0], compQ[1][0])
                )
            if compQ[2][0] == "NUMBR":
                if int(compQ[2][1]) >= int(compQ[3][1]):
                    return "WIN"
                else:
                    return "FAIL"
            elif compQ[2][0] == "NUMBAR":
                if float(compQ[2][1]) >= float(compQ[3][1]):
                    return "WIN"
                else:
                    return "FAIL"
            else:
                raise RuntimeError("Unexpected type %r" % (compQ[2][0]))
        elif compQ[1] == "SMALLR OF":
            if compQ[2][0] != compQ[3][0]:
                raise RuntimeError(
                    "Type mismatch - cannot compare %r and %r"
                    % (compQ[0][0], compQ[1][0])
                )
            if compQ[2][0] == "NUMBR":
                if int(compQ[2][1]) <= int(compQ[3][1]):
                    return "WIN"
                else:
                    return "FAIL"
            elif compQ[2][0] == "NUMBAR":
                if float(compQ[2][1]) <= float(compQ[3][1]):
                    return "WIN"
                else:
                    return "FAIL"
            else:
                raise RuntimeError("Unexpected type %r" % (compQ[2][0]))
        else:
            if compQ[0][0] != compQ[1][0]:
                raise RuntimeError(
                    "Type mismatch - cannot compare %r and %r"
                    % (compQ[0][0], compQ[1][0])
                )
            if compQ[0][1] == compQ[1][1]:
                return "WIN"
            else:
                return "FAIL"
    elif line[i] == "DIFFRINT":
        i += 1
        if tline[i] == "NUMBR" or tline[i] == "NUMBAR":
            compQ.append([tline[i], line[i]])
            i += 1
        elif tline[i] == "VARIABLE":
            value, type = searchVarValue(line[i])
            compQ.append([type, value])
            i += 1
        else:
            raise RuntimeError(
                "Expected NUMBR, NUMBAR, or VARIABLE at line %d" % (rowNum)
            )
        if tline[i] != "AN":
            raise RuntimeError("Expected AN at line %d" % (rowNum))
        i += 1
        if line[i] == "BIGGR OF" or line[i] == "SMALLR OF":
            compQ.append(line[i])
            i += 1
            if tline[i] == "NUMBR" or tline[i] == "NUMBAR":
                compQ.append([tline[i], line[i]])
                i += 1
            elif tline[i] == "VARIABLE":
                value, type = searchVarValue(line[i])
                compQ.append([type, value])
                i += 1
            else:
                raise RuntimeError(
                    "Expected NUMBR, NUMBAR, or VARIABLE at line %d" % (rowNum)
                )
            if compQ[0][1] != compQ[2][1]:
                raise RuntimeError(
                    "Value mismatch on line %d (%r and %r) must be same"
                    % (rowNum, compQ[0][1], compQ[2][1])
                )
            if tline[i] != "AN":
                raise RuntimeError("Expected AN at line %d" % (rowNum))
            i += 1
            if tline[i] == "NUMBR" or tline[i] == "NUMBAR":
                compQ.append([tline[i], line[i]])
                i += 1
            elif tline[i] == "VARIABLE":
                value, type = searchVarValue(line[i])
                compQ.append([type, value])
                i += 1
            else:
                raise RuntimeError(
                    "Expected NUMBR, NUMBAR, or VARIABLE at line %d" % (rowNum)
                )
        elif tline[i] == "NUMBR" or tline[i] == "NUMBAR":
            compQ.append([tline[i], line[i]])
            i += 1
        elif tline[i] == "VARIABLE":
            value, type = searchVarValue(line[i])
            compQ.append([type, value])
            i += 1
        else:
            raise RuntimeError(
                "Expected NUMBR, NUMBAR, VARIABLE, BIGGR OF, or SMALLR OF at line %d"
                % (rowNum)
            )

        # print(compQ)
        if compQ[1] == "BIGGR OF":
            if compQ[2][0] != compQ[3][0]:
                raise RuntimeError(
                    "Type mismatch - cannot compare %r and %r"
                    % (compQ[0][0], compQ[1][0])
                )
            if compQ[2][0] == "NUMBR":
                if int(compQ[3][1]) >= int(compQ[2][1]):
                    return "WIN"
                else:
                    return "FAIL"
            elif compQ[2][0] == "NUMBAR":
                if float(compQ[3][1]) >= float(compQ[2][1]):
                    return "WIN"
                else:
                    return "FAIL"
            else:
                raise RuntimeError("Unexpected type %r" % (compQ[2][0]))
        elif compQ[1] == "SMALLR OF":
            if compQ[2][0] != compQ[3][0]:
                raise RuntimeError(
                    "Type mismatch - cannot compare %r and %r"
                    % (compQ[0][0], compQ[1][0])
                )
            if compQ[2][0] == "NUMBR":
                if int(compQ[3][1]) <= int(compQ[2][1]):
                    return "WIN"
                else:
                    return "FAIL"
            elif compQ[2][0] == "NUMBAR":
                if float(compQ[3][1]) <= float(compQ[2][1]):
                    return "WIN"
                else:
                    return "FAIL"
            else:
                raise RuntimeError("Unexpected type %r" % (compQ[2][0]))
        else:
            if compQ[0][0] != compQ[1][0]:
                raise RuntimeError(
                    "Type mismatch - cannot compare %r and %r"
                    % (compQ[0][0], compQ[1][0])
                )
            if compQ[0][1] != compQ[1][1]:
                return "WIN"
            else:
                return "FAIL"


# function for parsing prefix notation math operations
def parse(tokens):
    if not tokens:
        raise RuntimeError("Unexpected end of statement.")
    else:
        token = tokens.popleft()
        if token == "+":
            return parse(tokens) + parse(tokens)
        elif token == "-":
            return parse(tokens) - parse(tokens)
        elif token == "/":
            return parse(tokens) / parse(tokens)
        elif token == "*":
            return parse(tokens) * parse(tokens)
        elif token == "%":
            return parse(tokens) % parse(tokens)
        elif token == "max":
            return max(parse(tokens), parse(tokens))
        elif token == "min":
            return min(parse(tokens), parse(tokens))
        else:
            return token


def mathOp(line, tline, i, rowNum):
    op = []

    while i < len(line):
        if line[i] == "SUM OF":
            op.append("+")
            i += 1
        elif line[i] == "DIFF OF":
            op.append("-")
            i += 1
        elif line[i] == "PRODUKT OF":
            op.append("*")
            i += 1
        elif line[i] == "QUOSHUNT OF":
            op.append("/")
            i += 1
        elif line[i] == "MOD OF":
            op.append("%")
            i += 1
        elif line[i] == "BIGGR OF":
            op.append("max")
            i += 1
        elif line[i] == "SMALLR OF":
            op.append("min")
            i += 1
        else:
            if tline[i] == "NUMBR":
                op.append(int(line[i]))
                i += 1
            elif tline[i] == "NUMBAR":
                op.append(float(line[i]))
                i += 1
            elif tline[i] == "VARIABLE":
                value, type = searchVarValue(line[i])
                op.append([type, value])
                i += 1
            elif tline[i] == "YARN":
                value = typeCasting(line[i], tline[i], "NUMBAR", rowNum)
                op.append(value)
                i += 1
            elif tline[i] == "AN":
                i += 1
            else:
                raise RuntimeError("Unexpected %r at line %d" % (line[i], rowNum))
            i += 1

    return parse(deque(op))


def boolOp(line, tline, i, rowNum):
    if tline[i] == "BOOL_OPER":
        opAddress = i
        boolQ = []
        i += 1
        i, boolQ0 = boolOp(line, tline, i, rowNum)
        boolQ.append(boolQ0)
        if line[opAddress] == "NOT":
            if boolQ[0] == "WIN":
                return i, "FAIL"
            else:
                return i, "WIN"
        i += 1
        if tline[i] != "AN":
            raise RuntimeError("Expected AN at line %d" % (rowNum))
        i += 1
        i, boolQ1 = boolOp(line, tline, i, rowNum)
        boolQ.append(boolQ1)
        # print(boolQ)
        if line[opAddress] == "BOTH OF":
            if boolQ[0] == "WIN" and boolQ[1] == "WIN":
                return i, "WIN"
            else:
                return i, "FAIL"
        elif line[opAddress] == "EITHER OF":
            if boolQ[0] == "WIN" or boolQ[1] == "WIN":
                return i, "WIN"
            else:
                return i, "FAIL"
        elif line[opAddress] == "WON OF":
            if boolQ[0] != boolQ[1] and (boolQ[0] == "WIN" or boolQ[1] == "WIN"):
                return i, "WIN"
            else:
                return i, "FAIL"
    elif tline[i] == "VARIABLE":
        if i < len(line) - 1:
            line[i] = line[i][:-1]
        value, type = searchVarValue(line[i])
        if type != "TROOF":
            value = typeCasting(value, type, "TROOF", rowNum)
        return i, value
    elif tline[i] == "TROOF":
        return i, line[i]
    else:
        raise RuntimeError("Unexpected %r at line %d" % (line[i], rowNum))


def boolOpRegion(line, tline, i, rowNum):
    # print(line)
    if line[i] == "ALL OF" or line[i] == "ANY OF":
        if line[i] == "ALL OF":
            initCond = "WIN"
            terminateCond = "WIN"
        elif line[i] == "ANY OF":
            terminateCond = "FAIL"
            initCond = "FAIL"
        i += 1
        while i < len(line) and initCond == terminateCond:
            initCond = boolOp(line, tline, i, rowNum)[1]
            # print(initCond, terminateCond)
            i += 1
            if line[i] == "AN":
                i += 1
            else:
                raise RuntimeError("Expected AN at line %d" % (rowNum))
            if line[i] == "MKAY":
                break
        return initCond
    else:
        return boolOp(line, tline, i, rowNum)[1]


def printLine(line, tline):
    # assume muna na YARN lang ung priniprint
    string = ""
    for i in range(0, len(line)):
        if tline[i] != "PRINT" and tline[i] != "COMMENT":
            if tline[i] == "YARN":
                string = string + line[i][1:-1]
            elif tline[i] == "VARIABLE":
                value, type = searchVarValue(line[i])
                if type != "YARN":
                    value = typeCasting(value, type, "YARN", i)
                else:
                    value = value[1:-1]
                string = string + value
            elif tline[i] == "NUMBR" or tline[i] == "NUMBAR":
                value = typeCasting(line[i], tline[i], "YARN", i)
                string = string + value
            elif tline[i] == "TROOF":
                value = line[i]
                string = string + value
            else:
                raise RuntimeError("Type %r cannot be printed" % (tline[i]))
    print(string)


def searchVarValue(name):
    global vars
    for variable in vars:
        if variable.name == name:
            return variable.value, variable.dataType
    raise RuntimeError("Variable %r does not exist" % (name))


def typeCasting(value, type1, type2, rowNum):
    if type1 == "NOOB":
        if type2 == "TROOF":
            return False
        else:
            raise RuntimeError(
                "Encountered error in line %d, cannot typecast NOOB to %r"
                % (rowNum, type2)
            )
    elif type1 == "NUMBR" or type1 == "NUMBAR":
        match type2:
            case "NUMBAR":
                return float(value)
            case "NUMBR":
                return int(value)
            case "YARN":
                return str(value)
            case "TROOF":
                if value == 0:
                    return "FAIL"
                else:
                    return "WIN"
            case _:
                raise RuntimeError(
                    "Encountered error in line %d, cannot typecast NUMBR to %r"
                    % (rowNum, type2)
                )
    elif type1 == "TROOF":
        match type2:
            case "NUMBAR":
                if value == "WIN":
                    return 1.0
                else:
                    return 0
            case "NUMBR":
                if value == "WIN":
                    return 1
                else:
                    return 0
            case "YARN":
                return value
            case _:
                raise RuntimeError(
                    "Encoutnered error in line %d, cannot typecast TROOF to %r"
                    % (rowNum, type2)
                )
    elif type1 == "YARN":
        value = value[1:-1]
        match type2:
            case "NUMBR":
                if bool(re.search(r"-?\d(\d)*", value)):
                    return int(value)
                else:
                    raise RuntimeError(
                        "Encountered error in line %d, cannot typecast YARN to %r"
                        % (rowNum, type2)
                    )
            case "NUMBAR":
                if bool(re.search(r"-?\d(\d)*\.\d(\d)*", value)):
                    return float(value)
                else:
                    raise RuntimeError(
                        "Encountered error in line %d, cannot typecast YARN to %r"
                        % (rowNum, type2)
                    )
            case "TROOF":
                if value == "":
                    return "FAIL"
                else:
                    return "WIN"
            case _:
                raise RuntimeError(
                    "Encountered error in line %d, cannot typecast YARN to %r"
                    % (rowNum, type2)
                )


def printVariables():
    global vars
    for variable in vars:
        print(variable.name)
        print(variable.dataType)
        print(variable.value)
        print("")
//set pin numbers
//const   won't change
const int ledPin = 12;   //the number of the LED pin
const int   ldrPin = A0;  //the number of the LDR pin


void setup() {

  Serial.begin(9600);
   pinMode(ledPin, OUTPUT);  //initialize the LED pin as an output
  pinMode(ldrPin,   INPUT);   //initialize the LDR pin as an input
}

void loop() {
  int   ldrStatus = analogRead(ldrPin);   //read the status of the LDR value

  //check   if the LDR status is <= 500
  //if it is, the LED is HIGH
Serial.println(ldrStatus);

   if (ldrStatus <=80) {

    digitalWrite(ledPin,   HIGH);               //turn LED on

   }
  else {

    digitalWrite(ledPin,   LOW);          //turn LED off
  }
}
<script>
    jQuery(document).ready(function($){
        $('#filter-btn').on('click',function(){
             $('.filter-window').slideToggle(300);
       }); 
    });
</script>
if (score >= 120) {
        sf::Text gameOverText;
        gameOverText.setFont(font);
        gameOverText.setCharacterSize(48);
        gameOverText.setFillColor(sf::Color::Red);
        gameOverText.setPosition(200, 300);
        gameOverText.setString("GAME OVER");
        window.draw(gameOverText);
        window.display();

        // Wait for a few seconds before closing the window
        sf::sleep(sf::seconds(3));
        window.close();
    } else {
        // Display the updated window
        window.display();
    }
}
{"count":60,"next":"https://swapi.dev/api/planets/?page=2&format=json","previous":null,"results":[{"name":"Tatooine","rotation_period":"23","orbital_period":"304","diameter":"10465","climate":"arid","gravity":"1 standard","terrain":"desert","surface_water":"1","population":"200000","residents":["https://swapi.dev/api/people/1/","https://swapi.dev/api/people/2/","https://swapi.dev/api/people/4/","https://swapi.dev/api/people/6/","https://swapi.dev/api/people/7/","https://swapi.dev/api/people/8/","https://swapi.dev/api/people/9/","https://swapi.dev/api/people/11/","https://swapi.dev/api/people/43/","https://swapi.dev/api/people/62/"],"films":["https://swapi.dev/api/films/1/","https://swapi.dev/api/films/3/","https://swapi.dev/api/films/4/","https://swapi.dev/api/films/5/","https://swapi.dev/api/films/6/"],"created":"2014-12-09T13:50:49.641000Z","edited":"2014-12-20T20:58:18.411000Z","url":"https://swapi.dev/api/planets/1/"},{"name":"Alderaan","rotation_period":"24","orbital_period":"364","diameter":"12500","climate":"temperate","gravity":"1 standard","terrain":"grasslands, mountains","surface_water":"40","population":"2000000000","residents":["https://swapi.dev/api/people/5/","https://swapi.dev/api/people/68/","https://swapi.dev/api/people/81/"],"films":["https://swapi.dev/api/films/1/","https://swapi.dev/api/films/6/"],"created":"2014-12-10T11:35:48.479000Z","edited":"2014-12-20T20:58:18.420000Z","url":"https://swapi.dev/api/planets/2/"},{"name":"Yavin IV","rotation_period":"24","orbital_period":"4818","diameter":"10200","climate":"temperate, tropical","gravity":"1 standard","terrain":"jungle, rainforests","surface_water":"8","population":"1000","residents":[],"films":["https://swapi.dev/api/films/1/"],"created":"2014-12-10T11:37:19.144000Z","edited":"2014-12-20T20:58:18.421000Z","url":"https://swapi.dev/api/planets/3/"},{"name":"Hoth","rotation_period":"23","orbital_period":"549","diameter":"7200","climate":"frozen","gravity":"1.1 standard","terrain":"tundra, ice caves, mountain ranges","surface_water":"100","population":"unknown","residents":[],"films":["https://swapi.dev/api/films/2/"],"created":"2014-12-10T11:39:13.934000Z","edited":"2014-12-20T20:58:18.423000Z","url":"https://swapi.dev/api/planets/4/"},{"name":"Dagobah","rotation_period":"23","orbital_period":"341","diameter":"8900","climate":"murky","gravity":"N/A","terrain":"swamp, jungles","surface_water":"8","population":"unknown","residents":[],"films":["https://swapi.dev/api/films/2/","https://swapi.dev/api/films/3/","https://swapi.dev/api/films/6/"],"created":"2014-12-10T11:42:22.590000Z","edited":"2014-12-20T20:58:18.425000Z","url":"https://swapi.dev/api/planets/5/"},{"name":"Bespin","rotation_period":"12","orbital_period":"5110","diameter":"118000","climate":"temperate","gravity":"1.5 (surface), 1 standard (Cloud City)","terrain":"gas giant","surface_water":"0","population":"6000000","residents":["https://swapi.dev/api/people/26/"],"films":["https://swapi.dev/api/films/2/"],"created":"2014-12-10T11:43:55.240000Z","edited":"2014-12-20T20:58:18.427000Z","url":"https://swapi.dev/api/planets/6/"},{"name":"Endor","rotation_period":"18","orbital_period":"402","diameter":"4900","climate":"temperate","gravity":"0.85 standard","terrain":"forests, mountains, lakes","surface_water":"8","population":"30000000","residents":["https://swapi.dev/api/people/30/"],"films":["https://swapi.dev/api/films/3/"],"created":"2014-12-10T11:50:29.349000Z","edited":"2014-12-20T20:58:18.429000Z","url":"https://swapi.dev/api/planets/7/"},{"name":"Naboo","rotation_period":"26","orbital_period":"312","diameter":"12120","climate":"temperate","gravity":"1 standard","terrain":"grassy hills, swamps, forests, mountains","surface_water":"12","population":"4500000000","residents":["https://swapi.dev/api/people/3/","https://swapi.dev/api/people/21/","https://swapi.dev/api/people/35/","https://swapi.dev/api/people/36/","https://swapi.dev/api/people/37/","https://swapi.dev/api/people/38/","https://swapi.dev/api/people/39/","https://swapi.dev/api/people/42/","https://swapi.dev/api/people/60/","https://swapi.dev/api/people/61/","https://swapi.dev/api/people/66/"],"films":["https://swapi.dev/api/films/3/","https://swapi.dev/api/films/4/","https://swapi.dev/api/films/5/","https://swapi.dev/api/films/6/"],"created":"2014-12-10T11:52:31.066000Z","edited":"2014-12-20T20:58:18.430000Z","url":"https://swapi.dev/api/planets/8/"},{"name":"Coruscant","rotation_period":"24","orbital_period":"368","diameter":"12240","climate":"temperate","gravity":"1 standard","terrain":"cityscape, mountains","surface_water":"unknown","population":"1000000000000","residents":["https://swapi.dev/api/people/34/","https://swapi.dev/api/people/55/","https://swapi.dev/api/people/74/"],"films":["https://swapi.dev/api/films/3/","https://swapi.dev/api/films/4/","https://swapi.dev/api/films/5/","https://swapi.dev/api/films/6/"],"created":"2014-12-10T11:54:13.921000Z","edited":"2014-12-20T20:58:18.432000Z","url":"https://swapi.dev/api/planets/9/"},{"name":"Kamino","rotation_period":"27","orbital_period":"463","diameter":"19720","climate":"temperate","gravity":"1 standard","terrain":"ocean","surface_water":"100","population":"1000000000","residents":["https://swapi.dev/api/people/22/","https://swapi.dev/api/people/72/","https://swapi.dev/api/people/73/"],"films":["https://swapi.dev/api/films/5/"],"created":"2014-12-10T12:45:06.577000Z","edited":"2014-12-20T20:58:18.434000Z","url":"https://swapi.dev/api/planets/10/"}]}
    #include <iostream>
    #include <SFML/Graphics.hpp>
    #include <SFML/Audio.hpp>
     
    using namespace std;
     
    // Initializing Dimensions.
    // resolutionX and resolutionY determine the rendering resolution.
    // Don't edit unless required. Use functions on lines 43, 44, 45 for resizing the game window.
    const int resolutionX = 960;
    const int resolutionY = 960;
    const int boxPixelsX = 32;
    const int boxPixelsY = 32;
    const int gameRows = resolutionX / boxPixelsX; // Total rows on grid
    const int gameColumns = resolutionY / boxPixelsY; // Total columns on grid
     
    // Initializing GameGrid.
    int gameGrid[gameRows][gameColumns] = {};
     
    // The following exist purely for readability.
    const int x = 0;
    const int y = 1;
    const int exists = 2;                                    //bool exists;//                       
    const int direction = 3;
    /////////////////////////////////////////////////////////////////////////////
    //                                                                         //
    // Write your functions declarations here. Some have been written for you. //
    //                                                                         //
    /////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite);
    void movePlayer(float player[],float bullet[],float shroom[][4], int maxShrooms);
    void moveBullet(float bullet[], sf::Clock& bulletClock);
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite);
    void drawShrooms(sf::RenderWindow& window, float shroom[][4], sf::Sprite& shroomSprite,int maxShrooms);
    void initializeShrooms(float shroom[][4],int maxShrooms);
    void initialize_centipede(float centipede[][4],int totalSegments);
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments); 
    void move_centipede(float centipede[][4], sf::Clock& bulletClock, int maxShrooms,float shroom[][4]);   //remove from sf::render..          ////,int maxShrooms,float shroom[][2] //
    void bullet_shroom(float bullet[],float shroom[][4]);
    void shroom_centipede_collision(float centipede[][4],float shroom[][4],int totalSegments,int maxShrooms);
    void splitCentipede(float centipede[][4], int totalSegments, int segmentHit);
    void player_shroom_collision(float player[],float shroom[][4] ); 
    int main()
    {
    	srand(time(0));
      /*
      //centipede stuff:
      const int totalSegments = 12;
    float centipede[totalSegments][2]; // 2D array to store x and y positions of each segment
     
    // Initialize centipede positions (for example, starting from the top left)
    const int startX = 100; // Adjust as needed
    const int startY = 100; // Adjust as needed
    const int segmentGap = 20; // Gap between segments
     
    for (int i = 0; i < totalSegments; ++i) {
        centipede[i][0] = startX + i * segmentGap; // x position
        centipede[i][1] = startY; // y position (same for all segments in this example)
        
    }
                         */
     
           
     
     
     
    	// Declaring RenderWindow.
    	sf::RenderWindow window(sf::VideoMode(resolutionX, resolutionY), "Centipede", sf::Style::Close | sf::Style::Titlebar);
     
    	// Used to resize your window if it's too big or too small. Use according to your needs.
    	window.setSize(sf::Vector2u(640, 640)); // Recommended for 1366x768 (768p) displays.
    	//window.setSize(sf::Vector2u(1280, 1280)); // Recommended for 2560x1440 (1440p) displays.
    	// window.setSize(sf::Vector2u(1920, 1920)); // Recommended for 3840x2160 (4k) displays.
    	
    	// Used to position your window on every launch. Use according to your needs.
    	window.setPosition(sf::Vector2i(100, 0));
     
    	// Initializing Background Music.
    	sf::Music bgMusic;
    	bgMusic.openFromFile("Centipede_Skeleton/Music/field_of_hopes.ogg");
    	bgMusic.play();
    	bgMusic.setVolume(50);
     
    	// Initializing Background.
    	sf::Texture backgroundTexture;
    	sf::Sprite backgroundSprite;
    	backgroundTexture.loadFromFile("Centipede_Skeleton/Textures/Untitled 2.jpeg");
    	backgroundSprite.setTexture(backgroundTexture);
    	backgroundSprite.setColor(sf::Color(255, 255, 255, 200)); // Reduces Opacity to 25%
            
    	// Initializing Player and Player Sprites.
    	float player[2] = {};
    	player[x] = (gameColumns / 2) * boxPixelsX;
    	player[y] = (gameColumns * 3 / 4) * boxPixelsY;
    	sf::Texture playerTexture;
    	sf::Sprite playerSprite;
    	playerTexture.loadFromFile("Centipede_Skeleton/Textures/player.png");
    	playerSprite.setTexture(playerTexture);
    	playerSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock playerClock;
     
    	// Initializing Bullet and Bullet Sprites.
    	float bullet[3] = {};                              
    	                                  //bool bullet1[3];
    	bool request = false;
    	bullet[x] = player[x];
    	bullet[y] = player[y] - boxPixelsY;
    	bullet[exists] = false;
    	sf::Clock bulletClock;
    	sf::Texture bulletTexture;
    	sf::Sprite bulletSprite;
    	bulletTexture.loadFromFile("Centipede_Skeleton/Textures/bullet.png");          
    	bulletSprite.setTexture(bulletTexture);
    	bulletSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	//initializing centipede
    	const int totalSegments = 12;
    	float centipede[100][4];
    	int segmentStrike = -1;
    	//centipede[x] = (gameColumns / 2) * boxPixelsX;           //the position from where centipede will start its journey x-co-ordinate//
    	//centipede[y] = (gameColumns * 3 / 4) * boxPixelsY;         //the position from where centipede will start its journey y-co-ordinate//
    	//centipede[1][exists] = false;
    	for(int i=0;i<totalSegments;i++){
     
    	centipede[i][exists] = true;
    	
    	
    	                                 }
    	               
    	sf::Texture centipedeTexture;
    	sf::Sprite centipedeSprite;
    	centipedeTexture.loadFromFile("Centipede_Skeleton/Textures/c_body_left_walk.png");
    	centipedeSprite.setTexture(centipedeTexture);
    	centipedeSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));                     //int rect(0,0,32,32)
    	
    	sf::Clock centipedeClock;
    	initialize_centipede(centipede,totalSegments);
    	
    	
    	//initializing shrooms:
    	const int maxShrooms = 18;
    	float shroom[25][4] = {};
            
    	sf::Texture shroomTexture;
    	sf::Sprite shroomSprite;
    	shroomTexture.loadFromFile("Centipede_Skeleton/Textures/mushroom.png");
    	shroomSprite.setTexture(shroomTexture);
    	shroomSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	for(int i=0;i<maxShrooms;i++){
    	shroom[i][exists] = true;
    	
    	                               }  
    	
    	
          
           initializeShrooms(shroom,maxShrooms);           //calling shroom's function to initialize position;    
           // int segmentHit = -1;   
            float strike_range = 15.0f;                                         // shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    	while(window.isOpen()) {
     
    		///////////////////////////////////////////////////////////////
    		//                                                           //
    		// Call Your Functions Here. Some have been written for you. //
    		// Be vary of the order you call them, SFML draws in order.  //
    		//                                                           //
    		///////////////////////////////////////////////////////////////
     
          
          
    		window.draw(backgroundSprite);
    		
    		drawPlayer(window, player, playerSprite);
    	        movePlayer(player,bullet,shroom,maxShrooms);                                               //movePlayer(player,bullet);
    		/*shootBullet(bullet,request);
    		if(request){
    		bullet[exists] = true;
    		request = false;          
    		    }                       */  
    		
    		//if (bullet[exists] == true) {
              // Initialize segmentHit to -1 indicating no segment was hit initially
 
 
    // ... (existing code for game loop)
 
    if (bullet[exists]) {
      
        moveBullet(bullet, bulletClock);
    			
    	drawBullet(window, bullet, bulletSprite);
      
        bullet_shroom(bullet,shroom);
        // Check for collision with centipede segments
        for (int j = 0; j < totalSegments; j++) {
            // ... (existing code for collision detection)
 
            // Check if bullet hits the centipede segment
            if (bullet[x] >= centipede[j][x] - strike_range &&
                bullet[x] <= centipede[j][x] + strike_range &&
                bullet[y] >= centipede[j][y] - strike_range &&
                bullet[y] <= centipede[j][y] + strike_range &&
                centipede[j][exists]) {
 
                // Store the index of the hit segment
                segmentStrike = j;
                // Split the centipede at the hit segment
                splitCentipede(centipede, totalSegments, segmentStrike);
                bullet[exists] = false;
                break; // Exit the loop after handling collision with one segment
            }
        }
    }
 
    // ... (rest of your game loop)
 
              
              
              
    			
    			
    		//}
          
    		
    		
    		
    		drawShrooms(window,shroom,shroomSprite,maxShrooms);
    		
    		
    		
    		drawCentipede(window, centipede, centipedeSprite,totalSegments);
    		move_centipede(centipede,centipedeClock,maxShrooms,shroom);                         //,maxShrooms,shroom//
    		
    		shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    		
                sf::Event e;
    		while (window.pollEvent(e)) {
    			if (e.type == sf::Event::Closed) {
    				return 0;
    			}
    		
    		}		
    		window.display();
    		window.clear();
    	}
    	 
    	
    	
     }
     
    ////////////////////////////////////////////////////////////////////////////
    //                                                                        //
    // Write your functions definitions here. Some have been written for you. //
    //                                                                        //
    ////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite) {
    	playerSprite.setPosition(player[x], player[y]); 
    	window.draw(playerSprite);
    }
     
     
     
     
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite) {
     
     if(bullet[exists] == true){
    	bulletSprite.setPosition(bullet[x], bullet[y]);
    	window.draw(bulletSprite);
    	
        }
     
     }
     
     
     
                     
                           
     
     
     
    void moveBullet(float bullet[], sf::Clock& bulletClock) {
     float bullet_speed = 10.0f;
            
        
     	if (bulletClock.getElapsedTime().asMilliseconds() < 10)
    		return;
            
    	bulletClock.restart(); 
    	bullet[y] += -32;	 
    	if (bullet[y] < -32)    
           {  bullet[exists] = false; }
    		
                                                   }  
                                                   
     
     
           
                                                   
                                                   
     
     
    void drawShrooms(sf::RenderWindow& window, float shroom[][4], sf::Sprite& shroomSprite,int maxShrooms){
         
         for(int i=0;i<maxShrooms;i++){
             if(shroom[i][exists]){                    
                              
                              
                              shroomSprite.setPosition(shroom[i][x],shroom[i][y]);
                              window.draw(shroomSprite);                            
                                                                                      } 
                                                          }                                 
                      } 
     
    void initializeShrooms(float shroom[][4],int maxShrooms){
                                                                                                    
                                                                                                   
         for(int i=0;i<maxShrooms;i++){
                              shroom[i][x] =     rand()%gameRows * boxPixelsX; 
                              shroom[i][y] =     rand()%gameColumns * boxPixelsY;            
                              //shroom[i][exists] = true;                                      }
                              shroom[i][3] = 0;       
                                                                            } 
                                                                              }
                                                                               
                                                                                                                                                                   
    void movePlayer(float player[],float bullet[],float shroom[][4], int maxShrooms) {
        float movementSpeed = 5.0f;
        int bottomLimit = resolutionY - (6 * boxPixelsY); // Calculate the bottom limit
   
    bool collisionUp = false;
    bool collisionDown = false;
    bool collisionLeft = false;
    bool collisionRight = false;
 
    // Check for collision with mushrooms in each direction
    for (int i = 0; i < maxShrooms; i++) {
        if (shroom[i][exists]) {
            // Check collision with each mushroom
            // Define collision range around the mushrooms
            float strike_range = 15.0f;
 
            // Check collision in each direction
            if (player[x] + boxPixelsX > shroom[i][x] - strike_range &&
                player[x] < shroom[i][x] + boxPixelsX + strike_range &&
                player[y] + boxPixelsY > shroom[i][y] - strike_range &&
                player[y] < shroom[i][y] + boxPixelsY + strike_range) {
                // Collision occurred, set collision flags based on direction
                if (player[y] > shroom[i][y]) {
                    collisionUp = true;
                }
                if (player[y] < shroom[i][y]) {
                    collisionDown = true;
                }
                if (player[x] > shroom[i][x]) {
                    collisionLeft = true;
                }
                if (player[x] < shroom[i][x]) {
                    collisionRight = true;
                }
            }
        }
    }
        
        
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player[y] > bottomLimit && !collisionUp) {
            player[y] -= movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player[y] < resolutionY - boxPixelsY && !collisionDown) {
            player[y] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player[x] < resolutionX - boxPixelsX && !collisionRight) {
            player[x] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player[x] > 0 && !collisionLeft) {
            player[x] -= movementSpeed + 3;
        }
        
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && bullet[exists]==false){
        
        bullet[exists] = true;
        bullet[x] = player[x];
        bullet[y] = player[y] - boxPixelsY;
        
    }
        }
     
    void initialize_centipede(float centipede[][4],int totalSegments){
         
        
             for(int j=0;j<totalSegments;j++){
         centipede[j][x] = boxPixelsX*j;
          centipede[j][y] = boxPixelsY; 
         centipede[j][exists] = true;
         centipede[j][direction] = 1;              //1 for right and 0 for left;
         
         
     
                                                 }
                                              
                 
                                                           }   
     
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments) {
        const int segmentWidth = boxPixelsX; // Width of each centipede segment
        const int segmentHeight = boxPixelsY; // Height of each centipede segment
     
        for (int i = 0; i < totalSegments; ++i) {
            if(centipede[i][exists]){
            centipedeSprite.setPosition(centipede[i][x], centipede[i][y]);
            window.draw(centipedeSprite);
            }
        }
    }
     
 
 
   void move_centipede(float centipede[][4], sf::Clock& centipedeClock, int maxShrooms,float shroom[][4] ) {                        //, int maxShrooms,float shroom[][2] //
    int totalSegments = 12;
 
    if (centipedeClock.getElapsedTime().asMilliseconds() < 100)
        return;
 
    centipedeClock.restart();
 
    bool reachedBottomRight = true;
    bool reachedBottomLeft = true;
    shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
 
    for (int j = 0;j < totalSegments ; j++) {
        if (centipede[j][direction] == 1 ) { // Moving right                     ////
            if (centipede[j][x] < 928) {
                centipede[j][x] += 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 0; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        } else { // Moving left
            if (centipede[j][x] > 0) {
                centipede[j][x] -= 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 1; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        }
    }
    
    for (int j = 0; j < totalSegments; j++){
 if (centipede[j][y] == 928 && centipede[j][x] == 928){
 reachedBottomRight = true;}
 else{reachedBottomRight = false;}
 
 if(centipede[j][y] == 928 && centipede[j][x] < 0){
  reachedBottomLeft = true; }
  else{reachedBottomLeft = false;} 
 
    if (reachedBottomRight || reachedBottomLeft) {
        // Move to the 6th row above the bottom
         {
            centipede[j][y] = 928 - (7 * boxPixelsY);
        }
    }
}
/*mushroom_centipede collsion:
 
initializeShrooms(shroom,maxShrooms);
for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 
if(shroom[i][x] == centipede[j][x] && shroom[i][y] == centipede[j][y]){
centipede[j][y] += 32;}
                             */
  
   }  
 
 
 
 
                                                                
 
 
 
 
 
void bullet_shroom(float bullet[], float shroom[][4]) {
    float bulletX = bullet[x];
    float bulletY = bullet[y];
 
    for (int i = 0; i < 18; i++) {
        float shroomX = shroom[i][x];
        float shroomY = shroom[i][y];
 
        // Define a range around the mushroom position for collision detection
        float strike_range = 15.0f; // Adjust this value as needed
 
        // Check if bullet position is within the range of a mushroom
        if (bulletX >= shroomX - strike_range && bulletX <= shroomX + strike_range &&
            bulletY >= shroomY - strike_range && bulletY <= shroomY + strike_range) {
             if(shroom[i][exists] ){ 
            shroom[i][exists] = false;
             bullet[exists] = false;
            break; // Exit loop after handling collision with one mushroom//
   
    }
        
                                    
    }
      }
        }                     
     
void shroom_centipede_collision(float centipede[][4],float shroom[][4],int totalSegments,int maxShrooms){
 
//initialize_centipede(centipede,totalSegments);
            //initializeShrooms(shroom,maxShrooms);
for(int i=0;i<totalSegments;i++){                                                         //still requiares changes
 
   for(int j=0;j<maxShrooms;j++){
   
     if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] != 928 && shroom[i][x] != 0){
     centipede[i][y] += 32;
     centipede[i][direction] = !centipede[i][direction];
     if(centipede[i][direction] == 0){
     centipede[i][x] -= 32;  }
     else{centipede[i][x] += 32;}
                                                          
                                     }
     else if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] == 928 ){
    centipede[i][y] -= 32;  
      centipede[i][direction] = centipede[i][direction];
     //centipede[i][x] +=32;  
    
                                       }
    
    
                                     
                                       }
                                         } 
                                           }
                                           
                                           
                                           
                               

 
/*for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 if(centipede[j][x] == shroom[i][x] && centipede[j][y] == shroom[j][y] ){
 centipede[j][y] += 32;
                                 } 
                                     }
                                        }   */
 
 
void splitCentipede(float centipede[][4], int totalSegments, int segmentHit) {
    // Split the centipede at the hit segment
    for (int k = segmentHit; k < totalSegments - 1; k++) {
        centipede[k][x] = centipede[k + 1][x];
        centipede[k][y] = centipede[k + 1][y];
        centipede[k][exists] = centipede[k + 1][exists];
        centipede[k][direction] = centipede[k + 1][direction];
    }
    // Mark the last segment as not existing
    centipede[totalSegments - 1][exists] = false;
}


//TO DO: BULLET_SHROOM MODIFICATION , CENTIPEDE HEAD , DEAL WITH COMMENTS INCLDUING THIS ONE//


<script>
document.querySelectorAll("input, textarea").forEach(function(element) {
  element.addEventListener("focus", function() {
    this.closest(".form-group").classList.add("focused");
  });
  element.addEventListener("blur", function() {
    var inputValue = this.value;
    if (inputValue === "") {
      this.closest(".form-group").classList.remove("focused");
    }
  });
});
</script>
<script>
document.querySelectorAll("input, textarea").forEach(function(element) {
  element.addEventListener("focus", function() {
    this.closest(".ff-el-group").classList.add("focused");
  });
  element.addEventListener("blur", function() {
    var inputValue = this.value;
    if (inputValue === "") {
      this.closest(".ff-el-group").classList.remove("focused");
    }
  });
});
</script>
#include <bits/stdc++.h>
using namespace std;

int main() {
	double p,r,t;
	cin>>p>>r>>t;
	double in=(p*r*t)/100;
	cout<<fixed<<setprecision(6)<<in;
	return 0;
}
// Remove first item in breadcrumb
add_filter('woocommerce_get_breadcrumb', 'remove_first_item_in_breadcrumbs', 10, 2);

function remove_first_item_in_breadcrumbs($crumbs, $breadcrumb) {
    // Check if WooCommerce is active and it's a product page
    if (class_exists('WooCommerce') && is_product()) {
        // Remove the first item in the breadcrumbs
        array_shift($crumbs);
    }

    return $crumbs;
}


// Remove last item in breadcrumb
add_filter( 'woocommerce_get_breadcrumb', 'bbloomer_single_product_edit_prod_name_breadcrumbs', 9999, 2 );
 
function bbloomer_single_product_edit_prod_name_breadcrumbs( $crumbs, $breadcrumb ) {
    
   if ( is_product() ) {
      global $product;
      $index = count( $crumbs ) - 1; // product name is always last item
      $value = $crumbs[$index];
      $crumbs[$index][0] = null;
   }
    
   return $crumbs;
}


// Remove separatot in last item
add_filter( 'woocommerce_breadcrumb_defaults', 'wcc_change_breadcrumb_delimiter' );
function wcc_change_breadcrumb_delimiter( $defaults ) {
	// Change the breadcrumb delimeter from '/' to null
	$defaults['delimiter'] = null;
	return $defaults;
}
int countLeaves(Node* root)
{
   if(!root)
   return 0;
   if(root->left==NULL and root->right==NULL)
   {
       return 1;
   }
   return (countLeaves(root->left)+countLeaves(root->right));
}
#include <bits/stdc++.h>
using namespace std;

struct StackNode {
    int data;
    StackNode *next;
    StackNode(int a) {
        data = a;
        next = NULL;
    }
};

class MyStack {
  private:
    StackNode *top;

  public:
    void push(int);
    int pop();
    MyStack() { top = NULL; }
};
//Function to push an integer into the stack.
void MyStack ::push(int x) 
{
   StackNode* newnode=new StackNode(x);
   newnode->next=top;
   top=newnode;
  
}

//Function to remove an item from top of the stack.
int MyStack ::pop() 
{
    int ddata;
    if(top==NULL)
    {
        return -1;
    }
     ddata=top->data;
    top=top->next;
    return ddata;
}

    #include <iostream>
    #include <SFML/Graphics.hpp>
    #include <SFML/Audio.hpp>
     
    using namespace std;
     
    // Initializing Dimensions.
    // resolutionX and resolutionY determine the rendering resolution.
    // Don't edit unless required. Use functions on lines 43, 44, 45 for resizing the game window.
    const int resolutionX = 960;
    const int resolutionY = 960;
    const int boxPixelsX = 32;
    const int boxPixelsY = 32;
    const int gameRows = resolutionX / boxPixelsX; // Total rows on grid
    const int gameColumns = resolutionY / boxPixelsY; // Total columns on grid
     
    // Initializing GameGrid.
    int gameGrid[gameRows][gameColumns] = {};
     
    // The following exist purely for readability.
    const int x = 0;
    const int y = 1;
    const int exists = 2;                                    //bool exists;//                       
    const int direction = 3;
    /////////////////////////////////////////////////////////////////////////////
    //                                                                         //
    // Write your functions declarations here. Some have been written for you. //
    //                                                                         //
    /////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite);
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms);
    void moveBullet(float bullet[], sf::Clock& bulletClock);
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite);
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms);
    void initializeShrooms(float shroom[][2],int maxShrooms);
    void initialize_centipede(float centipede[][4],int totalSegments);
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments); 
    void move_centipede(float centipede[][4], sf::Clock& bulletClock, int maxShrooms,float shroom[][2]);   //remove from sf::render..          ////,int maxShrooms,float shroom[][2] //
    void bullet_shroom(float bullet[],float shroom[][2]);
    void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms);
    void splitCentipede(float centipede[][4], int totalSegments, int segmentHit);
    void player_shroom_collision(float player[],float shroom[][2] ); 
    int main()
    {
    	srand(time(0));
      /*
      //centipede stuff:
      const int totalSegments = 12;
    float centipede[totalSegments][2]; // 2D array to store x and y positions of each segment
     
    // Initialize centipede positions (for example, starting from the top left)
    const int startX = 100; // Adjust as needed
    const int startY = 100; // Adjust as needed
    const int segmentGap = 20; // Gap between segments
     
    for (int i = 0; i < totalSegments; ++i) {
        centipede[i][0] = startX + i * segmentGap; // x position
        centipede[i][1] = startY; // y position (same for all segments in this example)
        
    }
                         */
     
           
     
     
     
    	// Declaring RenderWindow.
    	sf::RenderWindow window(sf::VideoMode(resolutionX, resolutionY), "Centipede", sf::Style::Close | sf::Style::Titlebar);
     
    	// Used to resize your window if it's too big or too small. Use according to your needs.
    	window.setSize(sf::Vector2u(640, 640)); // Recommended for 1366x768 (768p) displays.
    	//window.setSize(sf::Vector2u(1280, 1280)); // Recommended for 2560x1440 (1440p) displays.
    	// window.setSize(sf::Vector2u(1920, 1920)); // Recommended for 3840x2160 (4k) displays.
    	
    	// Used to position your window on every launch. Use according to your needs.
    	window.setPosition(sf::Vector2i(100, 0));
     
    	// Initializing Background Music.
    	sf::Music bgMusic;
    	bgMusic.openFromFile("Centipede_Skeleton/Music/field_of_hopes.ogg");
    	bgMusic.play();
    	bgMusic.setVolume(50);
     
    	// Initializing Background.
    	sf::Texture backgroundTexture;
    	sf::Sprite backgroundSprite;
    	backgroundTexture.loadFromFile("Centipede_Skeleton/Textures/background.png");
    	backgroundSprite.setTexture(backgroundTexture);
    	backgroundSprite.setColor(sf::Color(255, 255, 255, 200)); // Reduces Opacity to 25%
            
    	// Initializing Player and Player Sprites.
    	float player[2] = {};
    	player[x] = (gameColumns / 2) * boxPixelsX;
    	player[y] = (gameColumns * 3 / 4) * boxPixelsY;
    	sf::Texture playerTexture;
    	sf::Sprite playerSprite;
    	playerTexture.loadFromFile("Centipede_Skeleton/Textures/player.png");
    	playerSprite.setTexture(playerTexture);
    	playerSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock playerClock;
     
    	// Initializing Bullet and Bullet Sprites.
    	float bullet[3] = {};                              
    	                                  //bool bullet1[3];
    	bool request = false;
    	bullet[x] = player[x];
    	bullet[y] = player[y] - boxPixelsY;
    	bullet[exists] = false;
    	sf::Clock bulletClock;
    	sf::Texture bulletTexture;
    	sf::Sprite bulletSprite;
    	bulletTexture.loadFromFile("Centipede_Skeleton/Textures/bullet.png");
    	bulletSprite.setTexture(bulletTexture);
    	bulletSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	//initializing centipede
    	const int totalSegments = 12;
    	float centipede[100][4];
    	int segmentStrike = -1;
    	//centipede[x] = (gameColumns / 2) * boxPixelsX;           //the position from where centipede will start its journey x-co-ordinate//
    	//centipede[y] = (gameColumns * 3 / 4) * boxPixelsY;         //the position from where centipede will start its journey y-co-ordinate//
    	//centipede[1][exists] = false;
    	for(int i=0;i<totalSegments;i++){
     
    	centipede[i][exists] = true;
    	
    	
    	                                 }
    	               
    	sf::Texture centipedeTexture;
    	sf::Sprite centipedeSprite;
    	centipedeTexture.loadFromFile("Centipede_Skeleton/Textures/c_body_left_walk.png");
    	centipedeSprite.setTexture(centipedeTexture);
    	centipedeSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock centipedeClock;
    	initialize_centipede(centipede,totalSegments);
    	
    	
    	//initializing shrooms:
    	const int maxShrooms = 18;
    	float shroom[25][2] = {};
            
    	sf::Texture shroomTexture;
    	sf::Sprite shroomSprite;
    	shroomTexture.loadFromFile("Centipede_Skeleton/Textures/mushroom.png");
    	shroomSprite.setTexture(shroomTexture);
    	shroomSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	for(int i=0;i<maxShrooms;i++){
    	shroom[i][exists] = true;
    	
    	                               }  
    	
    	
          
           initializeShrooms(shroom,maxShrooms);           //calling shroom's function to initialize position;    
            int segmentHit = -1;   
            float centipedeCollisionRange = 16.0f;                                         // shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    	while(window.isOpen()) {
     
    		///////////////////////////////////////////////////////////////
    		//                                                           //
    		// Call Your Functions Here. Some have been written for you. //
    		// Be vary of the order you call them, SFML draws in order.  //
    		//                                                           //
    		///////////////////////////////////////////////////////////////
     
          
          
    		window.draw(backgroundSprite);
    		
    		drawPlayer(window, player, playerSprite);
    	        movePlayer(player,bullet,shroom,maxShrooms);                                               //movePlayer(player,bullet);
    		/*shootBullet(bullet,request);
    		if(request){
    		bullet[exists] = true;
    		request = false;          
    		    }                       */  
    		
    		if (bullet[exists] == true) {
              // Initialize segmentHit to -1 indicating no segment was hit initially
 
 
    // ... (existing code for game loop)
 
    if (bullet[exists]) {
      
        moveBullet(bullet, bulletClock);
    			
    	drawBullet(window, bullet, bulletSprite);
      
        bullet_shroom(bullet,shroom);
        // Check for collision with centipede segments
        for (int j = 0; j < totalSegments; j++) {
            // ... (existing code for collision detection)
 
            // Check if bullet hits the centipede segment
            if (bullet[x] >= centipede[j][x] - centipedeCollisionRange &&
                bullet[x] <= centipede[j][x] + centipedeCollisionRange &&
                bullet[y] >= centipede[j][y] - centipedeCollisionRange &&
                bullet[y] <= centipede[j][y] + centipedeCollisionRange &&
                centipede[j][exists]) {
 
                // Store the index of the hit segment
                segmentHit = j;
                // Split the centipede at the hit segment
                splitCentipede(centipede, totalSegments, segmentHit);
                bullet[exists] = false;
                break; // Exit the loop after handling collision with one segment
            }
        }
    }
 
    // ... (rest of your game loop)
 
              
              
              
    			
    			
    		}
          
    		
    		
    		
    		drawShrooms(window,shroom,shroomSprite,maxShrooms);
    		
    		
    		
    		drawCentipede(window, centipede, centipedeSprite,totalSegments);
    		move_centipede(centipede,centipedeClock,maxShrooms,shroom);                         //,maxShrooms,shroom//
    		
    		shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    		
                sf::Event e;
    		while (window.pollEvent(e)) {
    			if (e.type == sf::Event::Closed) {
    				return 0;
    			}
    		
    		}		
    		window.display();
    		window.clear();
    	}
    	 
    	
    	
     }
     
    ////////////////////////////////////////////////////////////////////////////
    //                                                                        //
    // Write your functions definitions here. Some have been written for you. //
    //                                                                        //
    ////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite) {
    	playerSprite.setPosition(player[x], player[y]); 
    	window.draw(playerSprite);
    }
     
     
     
     
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite) {
     
     if(bullet[exists] == true){
    	bulletSprite.setPosition(bullet[x], bullet[y]);
    	window.draw(bulletSprite);
    	
        }
     
     }
     
     
     
                     
                           
     
     
     
    void moveBullet(float bullet[], sf::Clock& bulletClock) {
     float bullet_speed = 10.0f;
            
        
     	if (bulletClock.getElapsedTime().asMilliseconds() < 10)
    		return;
            
    	bulletClock.restart(); 
    	bullet[y] += -32;	 
    	if (bullet[y] < -32)    
           {  bullet[exists] = false; }
    		
                                                   }  
                                                   
     
     
           
                                                   
                                                   
     
     
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms){
         
         for(int i=0;i<maxShrooms;i++){
             if(shroom[i][exists]){                    
                              
                              
                              shroomSprite.setPosition(shroom[i][x],shroom[i][y]);
                              window.draw(shroomSprite);                            
                                                                                      } 
                                                          }                                 
                      } 
     
    void initializeShrooms(float shroom[][2],int maxShrooms){
                                                                                                    
                                                                                                   
         for(int i=0;i<maxShrooms;i++){
                              shroom[i][x] =     rand()%gameRows * boxPixelsX; 
                              shroom[i][y] =     rand()%gameColumns * boxPixelsY;            
                             // shroom[i][exists] = true;                                      }
                                                                            } 
                                                                              }
                                                                               
                                                                                                                                                                   
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms) {
        float movementSpeed = 5.0f;
        int bottomLimit = resolutionY - (6 * boxPixelsY); // Calculate the bottom limit
   
    bool collisionUp = false;
    bool collisionDown = false;
    bool collisionLeft = false;
    bool collisionRight = false;
 
    // Check for collision with mushrooms in each direction
    for (int i = 0; i < maxShrooms; i++) {
        if (shroom[i][exists]) {
            // Check collision with each mushroom
            // Define collision range around the mushrooms
            float strike_range = 15.0f;
 
            // Check collision in each direction
            if (player[x] + boxPixelsX > shroom[i][x] - strike_range &&
                player[x] < shroom[i][x] + boxPixelsX + strike_range &&
                player[y] + boxPixelsY > shroom[i][y] - strike_range &&
                player[y] < shroom[i][y] + boxPixelsY + strike_range) {
                // Collision occurred, set collision flags based on direction
                if (player[y] > shroom[i][y]) {
                    collisionUp = true;
                }
                if (player[y] < shroom[i][y]) {
                    collisionDown = true;
                }
                if (player[x] > shroom[i][x]) {
                    collisionLeft = true;
                }
                if (player[x] < shroom[i][x]) {
                    collisionRight = true;
                }
            }
        }
    }
        
        
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player[y] > bottomLimit && !collisionUp) {
            player[y] -= movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player[y] < resolutionY - boxPixelsY && !collisionDown) {
            player[y] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player[x] < resolutionX - boxPixelsX && !collisionRight) {
            player[x] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player[x] > 0 && !collisionLeft) {
            player[x] -= movementSpeed + 3;
        }
        
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && bullet[exists]==false){
        
        bullet[exists] = true;
        bullet[x] = player[x];
        bullet[y] = player[y] - boxPixelsY;
        
    }
        }
     
    void initialize_centipede(float centipede[][4],int totalSegments){
         
        
             for(int j=0;j<totalSegments;j++){
         centipede[j][x] = boxPixelsX*j;
          centipede[j][y] = boxPixelsY; 
         centipede[j][exists] = true;
         centipede[j][direction] = 1;              //1 for right and 0 for left;
         
         
     
                                                 }
                                              
                 
                                                           }   
     
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments) {
        const int segmentWidth = boxPixelsX; // Width of each centipede segment
        const int segmentHeight = boxPixelsY; // Height of each centipede segment
     
        for (int i = 0; i < totalSegments; ++i) {
            if(centipede[i][exists]){
            centipedeSprite.setPosition(centipede[i][x], centipede[i][y]);
            window.draw(centipedeSprite);
            }
        }
    }
     
 
 
   void move_centipede(float centipede[][4], sf::Clock& centipedeClock, int maxShrooms,float shroom[][2] ) {                        //, int maxShrooms,float shroom[][2] //
    int totalSegments = 12;
 
    if (centipedeClock.getElapsedTime().asMilliseconds() < 100)
        return;
 
    centipedeClock.restart();
 
    bool reachedBottomRight = true;
    bool reachedBottomLeft = true;
    shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
 
    for (int j = 0;j < totalSegments ; j++) {
        if (centipede[j][direction] == 1 ) { // Moving right                     ////
            if (centipede[j][x] < 928) {
                centipede[j][x] += 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 0; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        } else { // Moving left
            if (centipede[j][x] > 0) {
                centipede[j][x] -= 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 1; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        }
    }
    
    for (int j = 0; j < totalSegments; j++){
 if (centipede[j][y] == 928 && centipede[j][x] == 928){
 reachedBottomRight = true;}
 else{reachedBottomRight = false;}
 
 if(centipede[j][y] == 928 && centipede[j][x] < 0){
  reachedBottomLeft = true; }
  else{reachedBottomLeft = false;} 
 
    if (reachedBottomRight || reachedBottomLeft) {
        // Move to the 6th row above the bottom
         {
            centipede[j][y] = 928 - (7 * boxPixelsY);
        }
    }
}
/*mushroom_centipede collsion:
 
initializeShrooms(shroom,maxShrooms);
for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 
if(shroom[i][x] == centipede[j][x] && shroom[i][y] == centipede[j][y]){
centipede[j][y] += 32;}
                             */
  
   }  
 
 
 
 
                                                                
 
 
 
 
 
void bullet_shroom(float bullet[], float shroom[][2]) {
    float bulletX = bullet[x];
    float bulletY = bullet[y];
 
    for (int i = 0; i < 18; i++) {
        float shroomX = shroom[i][x];
        float shroomY = shroom[i][y];
 
        // Define a range around the mushroom position for collision detection
        float strike_range = 15.0f; // Adjust this value as needed
 
        // Check if bullet position is within the range of a mushroom
        if (bulletX >= shroomX - strike_range && bulletX <= shroomX + strike_range &&
            bulletY >= shroomY - strike_range && bulletY <= shroomY + strike_range) {
             if(shroom[i][exists] ){ 
            shroom[i][exists] = false;
             bullet[exists] = false;
            break; // Exit loop after handling collision with one mushroom//
   
    }
        
                                    
    }
      }
        }                     
     
void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms){
 
//initialize_centipede(centipede,totalSegments);
            //initializeShrooms(shroom,maxShrooms);
for(int i=0;i<totalSegments;i++){                                                         //still requiares changes
 
   for(int j=0;j<maxShrooms;j++){
   
     if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] != 928 && shroom[i][x] != 0){
     centipede[i][y] += 32;
     centipede[i][direction] = !centipede[i][direction];
     //centipede[i][x] += 16;  
                                                          
                                     }
     else if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] == 928 ){
    centipede[i][y] -= 32;  
      centipede[i][direction] = centipede[i][direction];
     //centipede[i][x] +=32;  
    
                                       }
    
    
                                     
                                       }
                                         } 
                                           }
                                           
                                           
                                           
                               

 
/*for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 if(centipede[j][x] == shroom[i][x] && centipede[j][y] == shroom[j][y] ){
 centipede[j][y] += 32;
                                 } 
                                     }
                                        }   */
 
 
void splitCentipede(float centipede[][4], int totalSegments, int segmentHit) {
    // Split the centipede at the hit segment
    for (int k = segmentHit; k < totalSegments - 1; k++) {
        centipede[k][x] = centipede[k + 1][x];
        centipede[k][y] = centipede[k + 1][y];
        centipede[k][exists] = centipede[k + 1][exists];
        centipede[k][direction] = centipede[k + 1][direction];
    }
    // Mark the last segment as not existing
    centipede[totalSegments - 1][exists] = false;
}


//TO DO: BULLET_SHROOM MODIFICATION , CENTIPEDE HEAD , DEAL WITH COMMENTS INCLDUING THIS ONE//


    #include <iostream>
    #include <SFML/Graphics.hpp>
    #include <SFML/Audio.hpp>
     
    using namespace std;
     
    // Initializing Dimensions.
    // resolutionX and resolutionY determine the rendering resolution.
    // Don't edit unless required. Use functions on lines 43, 44, 45 for resizing the game window.
    const int resolutionX = 960;
    const int resolutionY = 960;
    const int boxPixelsX = 32;
    const int boxPixelsY = 32;
    const int gameRows = resolutionX / boxPixelsX; // Total rows on grid
    const int gameColumns = resolutionY / boxPixelsY; // Total columns on grid
     
    // Initializing GameGrid.
    int gameGrid[gameRows][gameColumns] = {};
     
    // The following exist purely for readability.
    const int x = 0;
    const int y = 1;
    const int exists = 2;                                    //bool exists;//                       
    const int direction = 3;
    /////////////////////////////////////////////////////////////////////////////
    //                                                                         //
    // Write your functions declarations here. Some have been written for you. //
    //                                                                         //
    /////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite);
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms);
    void moveBullet(float bullet[], sf::Clock& bulletClock);
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite);
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms);
    void initializeShrooms(float shroom[][2],int maxShrooms);
    void initialize_centipede(float centipede[][4],int totalSegments);
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments); 
    void move_centipede(float centipede[][4], sf::Clock& bulletClock, int maxShrooms,float shroom[][2]);   //remove from sf::render..          ////,int maxShrooms,float shroom[][2] //
    void bullet_shroom(float bullet[],float shroom[][2]);
    void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms);
    void centipede_bullet_collision(float centipede[][4],float bullet[],int totalSegments);
   // void player_shroom_collision(float player[];float shroom[][2] ); 
    int main()
    {
    	srand(time(0));
      /*
      //centipede stuff:
      const int totalSegments = 12;
    float centipede[totalSegments][2]; // 2D array to store x and y positions of each segment
     
    // Initialize centipede positions (for example, starting from the top left)
    const int startX = 100; // Adjust as needed
    const int startY = 100; // Adjust as needed
    const int segmentGap = 20; // Gap between segments
     
    for (int i = 0; i < totalSegments; ++i) {
        centipede[i][0] = startX + i * segmentGap; // x position
        centipede[i][1] = startY; // y position (same for all segments in this example)
        
    }
                         */
     
           
     
     
     
    	// Declaring RenderWindow.
    	sf::RenderWindow window(sf::VideoMode(resolutionX, resolutionY), "Centipede", sf::Style::Close | sf::Style::Titlebar);
     
    	// Used to resize your window if it's too big or too small. Use according to your needs.
    	window.setSize(sf::Vector2u(640, 640)); // Recommended for 1366x768 (768p) displays.
    	//window.setSize(sf::Vector2u(1280, 1280)); // Recommended for 2560x1440 (1440p) displays.
    	// window.setSize(sf::Vector2u(1920, 1920)); // Recommended for 3840x2160 (4k) displays.
    	
    	// Used to position your window on every launch. Use according to your needs.
    	window.setPosition(sf::Vector2i(100, 0));
     
    	// Initializing Background Music.
    	sf::Music bgMusic;
    	bgMusic.openFromFile("Centipede_Skeleton/Music/field_of_hopes.ogg");
    	bgMusic.play();
    	bgMusic.setVolume(50);
     
    	// Initializing Background.
    	sf::Texture backgroundTexture;
    	sf::Sprite backgroundSprite;
    	backgroundTexture.loadFromFile("Centipede_Skeleton/Textures/background.png");
    	backgroundSprite.setTexture(backgroundTexture);
    	backgroundSprite.setColor(sf::Color(255, 255, 255, 200)); // Reduces Opacity to 25%
            
    	// Initializing Player and Player Sprites.
    	float player[2] = {};
    	player[x] = (gameColumns / 2) * boxPixelsX;
    	player[y] = (gameColumns * 3 / 4) * boxPixelsY;
    	sf::Texture playerTexture;
    	sf::Sprite playerSprite;
    	playerTexture.loadFromFile("Centipede_Skeleton/Textures/player.png");
    	playerSprite.setTexture(playerTexture);
    	playerSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock playerClock;
     
    	// Initializing Bullet and Bullet Sprites.
    	float bullet[3] = {};                              
    	                                  //bool bullet1[3];
    	bool request = false;
    	bullet[x] = player[x];
    	bullet[y] = player[y] - boxPixelsY;
    	bullet[exists] = false;
    	sf::Clock bulletClock;
    	sf::Texture bulletTexture;
    	sf::Sprite bulletSprite;
    	bulletTexture.loadFromFile("Centipede_Skeleton/Textures/bullet.png");
    	bulletSprite.setTexture(bulletTexture);
    	bulletSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	//initializing centipede
    	const int totalSegments = 12;
    	float centipede[100][4];
    	int segmentStrike = -1;
    	//centipede[x] = (gameColumns / 2) * boxPixelsX;           //the position from where centipede will start its journey x-co-ordinate//
    	//centipede[y] = (gameColumns * 3 / 4) * boxPixelsY;         //the position from where centipede will start its journey y-co-ordinate//
    	//centipede[1][exists] = false;
    	for(int i=0;i<totalSegments;i++){
     
    	centipede[i][exists] = true;
    	
    	
    	                                 }
    	               
    	sf::Texture centipedeTexture;
    	sf::Sprite centipedeSprite;
    	centipedeTexture.loadFromFile("Centipede_Skeleton/Textures/c_body_left_walk.png");
    	centipedeSprite.setTexture(centipedeTexture);
    	centipedeSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock centipedeClock;
    	initialize_centipede(centipede,totalSegments);
    	
    	
    	//initializing shrooms:
    	const int maxShrooms = 18;
    	float shroom[25][2] = {};
            
    	sf::Texture shroomTexture;
    	sf::Sprite shroomSprite;
    	shroomTexture.loadFromFile("Centipede_Skeleton/Textures/mushroom.png");
    	shroomSprite.setTexture(shroomTexture);
    	shroomSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	for(int i=0;i<maxShrooms;i++){
    	shroom[i][exists] = true;
    	                               }  
    	
    	
          
           initializeShrooms(shroom,maxShrooms);           //calling shroom's function to initialize position;
                                                        // shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    	while(window.isOpen()) {
     
    		///////////////////////////////////////////////////////////////
    		//                                                           //
    		// Call Your Functions Here. Some have been written for you. //
    		// Be vary of the order you call them, SFML draws in order.  //
    		//                                                           //
    		///////////////////////////////////////////////////////////////
     
    		window.draw(backgroundSprite);
    		
    		drawPlayer(window, player, playerSprite);
    	        movePlayer(player,bullet,shroom,maxShrooms);                                               //movePlayer(player,bullet);
    		/*shootBullet(bullet,request);
    		if(request){
    		bullet[exists] = true;
    		request = false;          
    		    }                       */  
    		
    		if (bullet[exists] == true) {
    			moveBullet(bullet, bulletClock);
    			
    			drawBullet(window, bullet, bulletSprite);
    			
    		}
    		bullet_shroom(bullet,shroom);
    		
    		
    		drawShrooms(window,shroom,shroomSprite,maxShrooms);
    		
    		
    		
    		drawCentipede(window, centipede, centipedeSprite,totalSegments);
    		move_centipede(centipede,centipedeClock,maxShrooms,shroom);                         //,maxShrooms,shroom//
    		
    		
    		shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    		centipede_bullet_collision(centipede,bullet,totalSegments);
    		
               sf::Event e;
    		while (window.pollEvent(e)) {
    			if (e.type == sf::Event::Closed) {
    				return 0;
    			}
    		
    		}		
    		window.display();
    		window.clear();
    	}
    	 
    	
    	
     }
     
    ////////////////////////////////////////////////////////////////////////////
    //                                                                        //
    // Write your functions definitions here. Some have been written for you. //
    //                                                                        //
    ////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite) {
    	playerSprite.setPosition(player[x], player[y]); 
    	window.draw(playerSprite);
    }
     
     
     
     
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite) {
     
     if(bullet[exists] == true){
    	bulletSprite.setPosition(bullet[x], bullet[y]);
    	window.draw(bulletSprite);
    	
        }
     
     }
     
     
     
                     
                           
     
     
     
    void moveBullet(float bullet[], sf::Clock& bulletClock) {
     float bullet_speed = 10.0f;
            
        
     	if (bulletClock.getElapsedTime().asMilliseconds() < 10)
    		return;
            
    	bulletClock.restart(); 
    	bullet[y] += -32;	 
    	if (bullet[y] < -32)    
           {  bullet[exists] = false; }
    		
                                                   }  
                                                   
     
     
           
                                                   
                                                   
     
     
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms){
         
         for(int i=0;i<maxShrooms;i++){
             if(shroom[i][exists]){                    
                              
                              
                              shroomSprite.setPosition(shroom[i][x],shroom[i][y]);
                              window.draw(shroomSprite);                            
                                                                                      } 
                                                          }                                 
                      } 
     
    void initializeShrooms(float shroom[][2],int maxShrooms){
                                                                                                    
                                                                                                   
         for(int i=0;i<maxShrooms;i++){
                              shroom[i][x] =     rand()%gameRows * boxPixelsX; 
                              shroom[i][y] =     rand()%gameColumns * boxPixelsY;            
                             // shroom[i][exists] = true;                                      }
                                                                            } 
                                                                              }
                                                                               
                                                                                                                                                                   
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms) {
        float movementSpeed = 5.0f;
        int bottomLimit = resolutionY - (6 * boxPixelsY); // Calculate the bottom limit
   
    bool collisionUp = false;
    bool collisionDown = false;
    bool collisionLeft = false;
    bool collisionRight = false;
 
    // Check for collision with mushrooms in each direction
    for (int i = 0; i < maxShrooms; i++) {
        if (shroom[i][exists]) {
            // Check collision with each mushroom
            // Define collision range around the mushrooms
            float collisionRange = 16.0f; // Adjust this value as needed
 
            // Check collision in each direction
            if (player[x] + boxPixelsX > shroom[i][x] - collisionRange &&
                player[x] < shroom[i][x] + boxPixelsX + collisionRange &&
                player[y] + boxPixelsY > shroom[i][y] - collisionRange &&
                player[y] < shroom[i][y] + boxPixelsY + collisionRange) {
                // Collision occurred, set collision flags based on direction
                if (player[y] > shroom[i][y]) {
                    collisionUp = true;
                }
                if (player[y] < shroom[i][y]) {
                    collisionDown = true;
                }
                if (player[x] > shroom[i][x]) {
                    collisionLeft = true;
                }
                if (player[x] < shroom[i][x]) {
                    collisionRight = true;
                }
            }
        }
    }
        
        
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player[y] > bottomLimit && !collisionUp) {
            player[y] -= movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player[y] < resolutionY - boxPixelsY && !collisionDown) {
            player[y] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player[x] < resolutionX - boxPixelsX && !collisionRight) {
            player[x] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player[x] > 0 && !collisionLeft) {
            player[x] -= movementSpeed + 3;
        }
        
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && bullet[exists]==false){
        
        bullet[exists] = true;
        bullet[x] = player[x];
        bullet[y] = player[y] - boxPixelsY;
        
    }
        }
     
    void initialize_centipede(float centipede[][4],int totalSegments){
         
        
             for(int j=0;j<totalSegments;j++){
         centipede[j][x] = boxPixelsX*j;
          centipede[j][y] = boxPixelsY; 
         centipede[j][exists] = true;
         centipede[j][direction] = 1;              //1 for right and 0 for left;
         
         
     
                                                 }
                                              
                 
                                                           }   
     
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments) {
        const int segmentWidth = boxPixelsX; // Width of each centipede segment
        const int segmentHeight = boxPixelsY; // Height of each centipede segment
     
        for (int i = 0; i < totalSegments; ++i) {
            if(centipede[i][exists]){
            centipedeSprite.setPosition(centipede[i][x], centipede[i][y]);
            window.draw(centipedeSprite);
            }
        }
    }
     

 
   void move_centipede(float centipede[][4], sf::Clock& centipedeClock, int maxShrooms,float shroom[][2] ) {                        //, int maxShrooms,float shroom[][2] //
    int totalSegments = 12;
 
    if (centipedeClock.getElapsedTime().asMilliseconds() < 100)
        return;
 
    centipedeClock.restart();
 
    bool reachedBottomRight = true;
    bool reachedBottomLeft = true;
    shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
 
    for (int j = 0;j < totalSegments ; j++) {
        if (centipede[j][direction] == 1 ) { // Moving right                     ////
            if (centipede[j][x] < 928) {
                centipede[j][x] += 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 0; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        } else { // Moving left
            if (centipede[j][x] > 0) {
                centipede[j][x] -= 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 1; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        }
    }
    
    for (int j = 0; j < totalSegments; j++){
 if (centipede[j][y] == 928 && centipede[j][x] == 928){
 reachedBottomRight = true;}
 else{reachedBottomRight = false;}
 
 if(centipede[j][y] == 928 && centipede[j][x] < 0){
  reachedBottomLeft = true; }
  else{reachedBottomLeft = false;} 
 
    if (reachedBottomRight || reachedBottomLeft) {
        // Move to the 6th row above the bottom
         {
            centipede[j][y] = 928 - (7 * boxPixelsY);
        }
    }
}
/*mushroom_centipede collsion:

initializeShrooms(shroom,maxShrooms);
for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){

if(shroom[i][x] == centipede[j][x] && shroom[i][y] == centipede[j][y]){
centipede[j][y] += 32;}
                             */
  
   }  










void bullet_shroom(float bullet[], float shroom[][2]) {
    float bulletX = bullet[x];
    float bulletY = bullet[y];
 
    for (int i = 0; i < 18; i++) {
        float shroomX = shroom[i][x];
        float shroomY = shroom[i][y];
 
        // Define a range around the mushroom position for collision detection
        float collisionRange = 16.0f; // Adjust this value as needed
 
        // Check if bullet position is within the range of a mushroom
        if (bulletX >= shroomX - collisionRange && bulletX <= shroomX + collisionRange &&
            bulletY >= shroomY - collisionRange && bulletY <= shroomY + collisionRange) {
          
            shroom[i][exists] = false;
             bullet[exists] = false;
           // break; // Exit loop after handling collision with one mushroom//
        }
        /* if(shroom[i][exists] == false){
         bullet[exists] == true;  }   */
                                    
    }
}                     

void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms){

//initialize_centipede(centipede,totalSegments);
            //initializeShrooms(shroom,maxShrooms);
for(int i=0;i<totalSegments;i++){                                                         //still requiares changes

   for(int j=0;j<maxShrooms;j++){
   
     if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] != 928 && shroom[i][x] != 0){
     centipede[i][y] += 32;
     centipede[i][direction] = !centipede[i][direction];
     centipede[i][x] -=32;  
                                                          
                                     }
     else if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] == 928 ){
    centipede[i][y] -= 32;  
      centipede[i][direction] = centipede[i][direction];
     //centipede[i][x] +=32;  
    
                                       }
    
    
                                     
                                       }
                                         } 
                                           }
                                           
                                           
                                           
                               
/*void player_shroom_collision(float player[];float shroom[][2] ){

for(int i=0,i<maxShrooms;i++){
   if(player[x] == shroom[i][x] && player[y] == shroom[i][y] ){
   
   player[x



     }                               */                 


/*for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 if(centipede[j][x] == shroom[i][x] && centipede[j][y] == shroom[j][y] ){
 centipede[j][y] += 32;
                                 } 
                                     }
                                        }   */


void centipede_bullet_collision(float centipede[][4],float bullet[],int totalSegments){
   
   int hitted_segment = -1;        
   float centipedeCollisionRange = 16.0f;
      if (bullet[exists]) {
        // Check for collision with centipede segments
        for (int j = 0; j < totalSegments; j++) {
            // ... (existing code for collision detection)
 
            // Check if bullet hits the centipede segment
            if (bullet[x] >= centipede[j][x] - centipedeCollisionRange &&
                bullet[x] <= centipede[j][x] + centipedeCollisionRange &&
                bullet[y] >= centipede[j][y] - centipedeCollisionRange &&
                bullet[y] <= centipede[j][y] + centipedeCollisionRange &&
                centipede[j][exists]) {
 
                // Store the index of the hit segment
                hitted_segment = j;
                // Split the centipede at the hit segment
               
                bullet[exists] = false;
                break;    }
                              }
                
                for (int k = hitted_segment; k < totalSegments - 1; k++) {
        centipede[k][x] = centipede[k + 1][x];
        centipede[k][y] = centipede[k + 1][y];
        centipede[k][exists] = centipede[k + 1][exists];
        centipede[k][direction] = centipede[k + 1][direction];
    }
    // Mark the last segment as not existing
    centipede[totalSegments - 1][exists] = false;  }
                                                            }
       
   
             

    #include <iostream>
    #include <SFML/Graphics.hpp>
    #include <SFML/Audio.hpp>
     
    using namespace std;
     
    // Initializing Dimensions.
    // resolutionX and resolutionY determine the rendering resolution.
    // Don't edit unless required. Use functions on lines 43, 44, 45 for resizing the game window.
    const int resolutionX = 960;
    const int resolutionY = 960;
    const int boxPixelsX = 32;
    const int boxPixelsY = 32;
    const int gameRows = resolutionX / boxPixelsX; // Total rows on grid
    const int gameColumns = resolutionY / boxPixelsY; // Total columns on grid
     
    // Initializing GameGrid.
    int gameGrid[gameRows][gameColumns] = {};
     
    // The following exist purely for readability.
    const int x = 0;
    const int y = 1;
    const int exists = 2;                                    //bool exists;//                       
    const int direction = 3;
    /////////////////////////////////////////////////////////////////////////////
    //                                                                         //
    // Write your functions declarations here. Some have been written for you. //
    //                                                                         //
    /////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite);
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms);
    void moveBullet(float bullet[], sf::Clock& bulletClock);
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite);
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms);
    void initializeShrooms(float shroom[][2],int maxShrooms);
    void initialize_centipede(float centipede[][4],int totalSegments);
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments); 
    void move_centipede(float centipede[][4], sf::Clock& bulletClock, int maxShrooms,float shroom[][2]);   //remove from sf::render..          ////,int maxShrooms,float shroom[][2] //
    void bullet_shroom(float bullet[],float shroom[][2]);
    void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms);
   void splitCentipede(float centipede[][4], int totalSegments, int segmentHit);
   // void player_shroom_collision(float player[];float shroom[][2] ); 
    int main()
    {
    	srand(time(0));
      /*
      //centipede stuff:
      const int totalSegments = 12;
    float centipede[totalSegments][2]; // 2D array to store x and y positions of each segment
     
    // Initialize centipede positions (for example, starting from the top left)
    const int startX = 100; // Adjust as needed
    const int startY = 100; // Adjust as needed
    const int segmentGap = 20; // Gap between segments
     
    for (int i = 0; i < totalSegments; ++i) {
        centipede[i][0] = startX + i * segmentGap; // x position
        centipede[i][1] = startY; // y position (same for all segments in this example)
        
    }
                         */
     
           
     
     
     
    	// Declaring RenderWindow.
    	sf::RenderWindow window(sf::VideoMode(resolutionX, resolutionY), "Centipede", sf::Style::Close | sf::Style::Titlebar);
     
    	// Used to resize your window if it's too big or too small. Use according to your needs.
    	window.setSize(sf::Vector2u(640, 640)); // Recommended for 1366x768 (768p) displays.
    	//window.setSize(sf::Vector2u(1280, 1280)); // Recommended for 2560x1440 (1440p) displays.
    	// window.setSize(sf::Vector2u(1920, 1920)); // Recommended for 3840x2160 (4k) displays.
    	
    	// Used to position your window on every launch. Use according to your needs.
    	window.setPosition(sf::Vector2i(100, 0));
     
    	// Initializing Background Music.
    	sf::Music bgMusic;
    	bgMusic.openFromFile("Centipede_Skeleton/Music/field_of_hopes.ogg");
    	bgMusic.play();
    	bgMusic.setVolume(50);
     
    	// Initializing Background.
    	sf::Texture backgroundTexture;
    	sf::Sprite backgroundSprite;
    	backgroundTexture.loadFromFile("Centipede_Skeleton/Textures/background.png");
    	backgroundSprite.setTexture(backgroundTexture);
    	backgroundSprite.setColor(sf::Color(255, 255, 255, 200)); // Reduces Opacity to 25%
            
    	// Initializing Player and Player Sprites.
    	float player[2] = {};
    	player[x] = (gameColumns / 2) * boxPixelsX;
    	player[y] = (gameColumns * 3 / 4) * boxPixelsY;
    	sf::Texture playerTexture;
    	sf::Sprite playerSprite;
    	playerTexture.loadFromFile("Centipede_Skeleton/Textures/player.png");
    	playerSprite.setTexture(playerTexture);
    	playerSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock playerClock;
     
    	// Initializing Bullet and Bullet Sprites.
    	float bullet[3] = {};                              
    	                                  //bool bullet1[3];
    	bool request = false;
    	bullet[x] = player[x];
    	bullet[y] = player[y] - boxPixelsY;
    	bullet[exists] = false;
    	sf::Clock bulletClock;
    	sf::Texture bulletTexture;
    	sf::Sprite bulletSprite;
    	bulletTexture.loadFromFile("Centipede_Skeleton/Textures/bullet.png");
    	bulletSprite.setTexture(bulletTexture);
    	bulletSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	//initializing centipede
    	const int totalSegments = 12;
    	float centipede[100][4];
    	int segmentStrike = -1;
    	//centipede[x] = (gameColumns / 2) * boxPixelsX;           //the position from where centipede will start its journey x-co-ordinate//
    	//centipede[y] = (gameColumns * 3 / 4) * boxPixelsY;         //the position from where centipede will start its journey y-co-ordinate//
    	//centipede[1][exists] = false;
    	for(int i=0;i<totalSegments;i++){
     
    	centipede[i][exists] = true;
    	
    	
    	                                 }
    	               
    	sf::Texture centipedeTexture;
    	sf::Sprite centipedeSprite;
    	centipedeTexture.loadFromFile("Centipede_Skeleton/Textures/c_body_left_walk.png");
    	centipedeSprite.setTexture(centipedeTexture);
    	centipedeSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock centipedeClock;
    	initialize_centipede(centipede,totalSegments);
    	
    	
    	//initializing shrooms:
    	const int maxShrooms = 18;
    	float shroom[25][2] = {};
            
    	sf::Texture shroomTexture;
    	sf::Sprite shroomSprite;
    	shroomTexture.loadFromFile("Centipede_Skeleton/Textures/mushroom.png");
    	shroomSprite.setTexture(shroomTexture);
    	shroomSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	for(int i=0;i<maxShrooms;i++){
    	shroom[i][exists] = true;
    	                               }  
    	
    	
          
           initializeShrooms(shroom,maxShrooms);           //calling shroom's function to initialize position;    
            int segmentHit = -1;                                            // shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    	while(window.isOpen()) {
     
    		///////////////////////////////////////////////////////////////
    		//                                                           //
    		// Call Your Functions Here. Some have been written for you. //
    		// Be vary of the order you call them, SFML draws in order.  //
    		//                                                           //
    		///////////////////////////////////////////////////////////////
     
          
          
    		window.draw(backgroundSprite);
    		
    		drawPlayer(window, player, playerSprite);
    	        movePlayer(player,bullet,shroom,maxShrooms);                                               //movePlayer(player,bullet);
    		/*shootBullet(bullet,request);
    		if(request){
    		bullet[exists] = true;
    		request = false;          
    		    }                       */  
    		
    		if (bullet[exists] == true) {
              // Initialize segmentHit to -1 indicating no segment was hit initially


    // ... (existing code for game loop)

    if (bullet[exists]) {
      
        moveBullet(bullet, bulletClock);
    			
    	drawBullet(window, bullet, bulletSprite);
      
        bullet_shroom(bullet,shroom);
        // Check for collision with centipede segments
        for (int j = 0; j < totalSegments; j++) {
            // ... (existing code for collision detection)

            // Check if bullet hits the centipede segment
            if (bulletX >= centipede[j][x] - centipedeCollisionRange &&
                bulletX <= centipede[j][x] + centipedeCollisionRange &&
                bulletY >= centipede[j][y] - centipedeCollisionRange &&
                bulletY <= centipede[j][y] + centipedeCollisionRange &&
                centipede[j][exists]) {

                // Store the index of the hit segment
                segmentHit = j;
                // Split the centipede at the hit segment
                splitCentipede(centipede, totalSegments, segmentHit);
                bullet[exists] = false;
                break; // Exit the loop after handling collision with one segment
            }
        }
    }

    // ... (rest of your game loop)

              
              
              
    			
    			
    		}
          
    		
    		
    		centipede_bullet_collision(centipede,bullet,totalSegments);
    		drawShrooms(window,shroom,shroomSprite,maxShrooms);
    		
    		
    		
    		drawCentipede(window, centipede, centipedeSprite,totalSegments);
    		move_centipede(centipede,centipedeClock,maxShrooms,shroom);                         //,maxShrooms,shroom//
    		
    		shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    		
               sf::Event e;
    		while (window.pollEvent(e)) {
    			if (e.type == sf::Event::Closed) {
    				return 0;
    			}
    		
    		}		
    		window.display();
    		window.clear();
    	}
    	 
    	
    	
     }
     
    ////////////////////////////////////////////////////////////////////////////
    //                                                                        //
    // Write your functions definitions here. Some have been written for you. //
    //                                                                        //
    ////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite) {
    	playerSprite.setPosition(player[x], player[y]); 
    	window.draw(playerSprite);
    }
     
     
     
     
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite) {
     
     if(bullet[exists] == true){
    	bulletSprite.setPosition(bullet[x], bullet[y]);
    	window.draw(bulletSprite);
    	
        }
     
     }
     
     
     
                     
                           
     
     
     
    void moveBullet(float bullet[], sf::Clock& bulletClock) {
     float bullet_speed = 10.0f;
            
        
     	if (bulletClock.getElapsedTime().asMilliseconds() < 10)
    		return;
            
    	bulletClock.restart(); 
    	bullet[y] += -32;	 
    	if (bullet[y] < -32)    
           {  bullet[exists] = false; }
    		
                                                   }  
                                                   
     
     
           
                                                   
                                                   
     
     
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms){
         
         for(int i=0;i<maxShrooms;i++){
             if(shroom[i][exists]){                    
                              
                              
                              shroomSprite.setPosition(shroom[i][x],shroom[i][y]);
                              window.draw(shroomSprite);                            
                                                                                      } 
                                                          }                                 
                      } 
     
    void initializeShrooms(float shroom[][2],int maxShrooms){
                                                                                                    
                                                                                                   
         for(int i=0;i<maxShrooms;i++){
                              shroom[i][x] =     rand()%gameRows * boxPixelsX; 
                              shroom[i][y] =     rand()%gameColumns * boxPixelsY;            
                             // shroom[i][exists] = true;                                      }
                                                                            } 
                                                                              }
                                                                               
                                                                                                                                                                   
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms) {
        float movementSpeed = 5.0f;
        int bottomLimit = resolutionY - (6 * boxPixelsY); // Calculate the bottom limit
   
    bool collisionUp = false;
    bool collisionDown = false;
    bool collisionLeft = false;
    bool collisionRight = false;
 
    // Check for collision with mushrooms in each direction
    for (int i = 0; i < maxShrooms; i++) {
        if (shroom[i][exists]) {
            // Check collision with each mushroom
            // Define collision range around the mushrooms
            float collisionRange = 16.0f; // Adjust this value as needed
 
            // Check collision in each direction
            if (player[x] + boxPixelsX > shroom[i][x] - collisionRange &&
                player[x] < shroom[i][x] + boxPixelsX + collisionRange &&
                player[y] + boxPixelsY > shroom[i][y] - collisionRange &&
                player[y] < shroom[i][y] + boxPixelsY + collisionRange) {
                // Collision occurred, set collision flags based on direction
                if (player[y] > shroom[i][y]) {
                    collisionUp = true;
                }
                if (player[y] < shroom[i][y]) {
                    collisionDown = true;
                }
                if (player[x] > shroom[i][x]) {
                    collisionLeft = true;
                }
                if (player[x] < shroom[i][x]) {
                    collisionRight = true;
                }
            }
        }
    }
        
        
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player[y] > bottomLimit && !collisionUp) {
            player[y] -= movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player[y] < resolutionY - boxPixelsY && !collisionDown) {
            player[y] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player[x] < resolutionX - boxPixelsX && !collisionRight) {
            player[x] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player[x] > 0 && !collisionLeft) {
            player[x] -= movementSpeed + 3;
        }
        
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && bullet[exists]==false){
        
        bullet[exists] = true;
        bullet[x] = player[x];
        bullet[y] = player[y] - boxPixelsY;
        
    }
        }
     
    void initialize_centipede(float centipede[][4],int totalSegments){
         
        
             for(int j=0;j<totalSegments;j++){
         centipede[j][x] = boxPixelsX*j;
          centipede[j][y] = boxPixelsY; 
         centipede[j][exists] = true;
         centipede[j][direction] = 1;              //1 for right and 0 for left;
         
         
     
                                                 }
                                              
                 
                                                           }   
     
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments) {
        const int segmentWidth = boxPixelsX; // Width of each centipede segment
        const int segmentHeight = boxPixelsY; // Height of each centipede segment
     
        for (int i = 0; i < totalSegments; ++i) {
            if(centipede[i][exists]){
            centipedeSprite.setPosition(centipede[i][x], centipede[i][y]);
            window.draw(centipedeSprite);
            }
        }
    }
     

 
   void move_centipede(float centipede[][4], sf::Clock& centipedeClock, int maxShrooms,float shroom[][2] ) {                        //, int maxShrooms,float shroom[][2] //
    int totalSegments = 12;
 
    if (centipedeClock.getElapsedTime().asMilliseconds() < 100)
        return;
 
    centipedeClock.restart();
 
    bool reachedBottomRight = true;
    bool reachedBottomLeft = true;
    shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
 
    for (int j = 0;j < totalSegments ; j++) {
        if (centipede[j][direction] == 1 ) { // Moving right                     ////
            if (centipede[j][x] < 928) {
                centipede[j][x] += 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 0; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        } else { // Moving left
            if (centipede[j][x] > 0) {
                centipede[j][x] -= 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 1; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        }
    }
    
    for (int j = 0; j < totalSegments; j++){
 if (centipede[j][y] == 928 && centipede[j][x] == 928){
 reachedBottomRight = true;}
 else{reachedBottomRight = false;}
 
 if(centipede[j][y] == 928 && centipede[j][x] < 0){
  reachedBottomLeft = true; }
  else{reachedBottomLeft = false;} 
 
    if (reachedBottomRight || reachedBottomLeft) {
        // Move to the 6th row above the bottom
         {
            centipede[j][y] = 928 - (7 * boxPixelsY);
        }
    }
}
/*mushroom_centipede collsion:

initializeShrooms(shroom,maxShrooms);
for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){

if(shroom[i][x] == centipede[j][x] && shroom[i][y] == centipede[j][y]){
centipede[j][y] += 32;}
                             */
  
   }  










void bullet_shroom(float bullet[], float shroom[][2]) {
    float bulletX = bullet[x];
    float bulletY = bullet[y];
 
    for (int i = 0; i < 18; i++) {
        float shroomX = shroom[i][x];
        float shroomY = shroom[i][y];
 
        // Define a range around the mushroom position for collision detection
        float collisionRange = 16.0f; // Adjust this value as needed
 
        // Check if bullet position is within the range of a mushroom
        if (bulletX >= shroomX - collisionRange && bulletX <= shroomX + collisionRange &&
            bulletY >= shroomY - collisionRange && bulletY <= shroomY + collisionRange) {
          
            shroom[i][exists] = false;
             bullet[exists] = false;
           // break; // Exit loop after handling collision with one mushroom//
        }
        /* if(shroom[i][exists] == false){
         bullet[exists] == true;  }   */
                                    
    }
}                     

void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms){

//initialize_centipede(centipede,totalSegments);
            //initializeShrooms(shroom,maxShrooms);
for(int i=0;i<totalSegments;i++){                                                         //still requiares changes

   for(int j=0;j<maxShrooms;j++){
   
     if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] != 928 && shroom[i][x] != 0){
     centipede[i][y] += 32;
     centipede[i][direction] = !centipede[i][direction];
     centipede[i][x] -=32;  
                                                          
                                     }
     else if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] == 928 ){
    centipede[i][y] -= 32;  
      centipede[i][direction] = centipede[i][direction];
     //centipede[i][x] +=32;  
    
                                       }
    
    
                                     
                                       }
                                         } 
                                           }
                                           
                                           
                                           
                               
/*void player_shroom_collision(float player[];float shroom[][2] ){

for(int i=0,i<maxShrooms;i++){
   if(player[x] == shroom[i][x] && player[y] == shroom[i][y] ){
   
   player[x



     }                               */                 


/*for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 if(centipede[j][x] == shroom[i][x] && centipede[j][y] == shroom[j][y] ){
 centipede[j][y] += 32;
                                 } 
                                     }
                                        }   */


void splitCentipede(float centipede[][4], int totalSegments, int segmentHit) {
    // Split the centipede at the hit segment
    for (int k = segmentHit; k < totalSegments - 1; k++) {
        centipede[k][x] = centipede[k + 1][x];
        centipede[k][y] = centipede[k + 1][y];
        centipede[k][exists] = centipede[k + 1][exists];
        centipede[k][direction] = centipede[k + 1][direction];
    }
    // Mark the last segment as not existing
    centipede[totalSegments - 1][exists] = false;
}
       
   
             

//int segmentHit = -1;  // Initialize segmentHit to -1 indicating no segment was hit initially
for (int k = segmentHit; k < totalSegments - 1; k++) {
        centipede[k][x] = centipede[k + 1][x];
        centipede[k][y] = centipede[k + 1][y];
        centipede[k][exists] = centipede[k + 1][exists];
        centipede[k][direction] = centipede[k + 1][direction];
    }
    // Mark the last segment as not existing
    centipede[totalSegments - 1][exists] = false;
   



if (bullet[exists]) {
        // Check for collision with centipede segments
        for (int j = 0; j < totalSegments; j++) {
            // ... (existing code for collision detection)

            // Check if bullet hits the centipede segment
            if (bulletX >= centipede[j][x] - centipedeCollisionRange &&
                bulletX <= centipede[j][x] + centipedeCollisionRange &&
                bulletY >= centipede[j][y] - centipedeCollisionRange &&
                bulletY <= centipede[j][y] + centipedeCollisionRange &&
                centipede[j][exists]) {

                // Store the index of the hit segment
                segmentHit = j;
                // Split the centipede at the hit segment
               
                bullet[exists] = false;
                break; // Exit the loop after handling collision with one segment
            }
        }
    }
import holidays
from datetime import datetime, timedelta


# Get current date/time
tday = datetime.now()
testday = datetime(2023,12,1,13,13,0)    # for debug only

tday = testday    # for debug only
aims_rec_date = tday.strftime('%Y-%m-%d')
aims_time = tday.strftime('%H:%M:%S')
same_day_despatch_cut_off_time = datetime.strptime(aims_rec_date + " 13:00:00", "%Y-%m-%d %H:%M:%S")
add_days = 0

print(f"*******************************\nReceipt: {aims_rec_date} @ {aims_time}")

# Early enough for same-day despatch?
wk_day = int(tday.strftime('%w'))
if wk_day in range(1,5+1):
    despatch_today = tday < same_day_despatch_cut_off_time
    print(f"Despatch today: {despatch_today}")
    if not despatch_today:
        add_days = 1
else:
    print("Weekend...")

# Set provisional despatch date
aims_despatch_date = (tday + timedelta(days=add_days))

# Only interested in these public holidays
occasions = [
    "New Year's Day",
    "Good Friday",
    "Easter Monday [England/Wales/Northern Ireland]",
    "May Day",
    "Spring Bank Holiday",
    "Late Summer Bank Holiday [England/Wales/Northern Ireland]",
    "Christmas Day",
    "Boxing Day",
]
uk_holidays = holidays.UnitedKingdom()

print(f"UK Holiday: {aims_despatch_date in uk_holidays}")

# Amend provisional despatch date if not working day
while aims_despatch_date in uk_holidays or int(aims_despatch_date.strftime('%w')) in [0,6]:
    print("****skip-a-day****")
    try:    # amend for public holiday
        occasion = uk_holidays[aims_despatch_date]
        if occasion in occasions:
            aims_despatch_date = (aims_despatch_date + timedelta(days=1))
            wk_day = aims_despatch_date.strftime('%w')
        else:
            break
    except Exception as e:    # amend for weekend
        aims_despatch_date = (aims_despatch_date + timedelta(days=1))
        wk_day = aims_despatch_date.strftime('%w')


print(f"Despatch: {aims_despatch_date.strftime('%Y-%m-%d')}\n*******************************\n")
    #include <iostream>
    #include <SFML/Graphics.hpp>
    #include <SFML/Audio.hpp>
     
    using namespace std;
     
    // Initializing Dimensions.
    // resolutionX and resolutionY determine the rendering resolution.
    // Don't edit unless required. Use functions on lines 43, 44, 45 for resizing the game window.
    const int resolutionX = 960;
    const int resolutionY = 960;
    const int boxPixelsX = 32;
    const int boxPixelsY = 32;
    const int gameRows = resolutionX / boxPixelsX; // Total rows on grid
    const int gameColumns = resolutionY / boxPixelsY; // Total columns on grid
     
    // Initializing GameGrid.
    int gameGrid[gameRows][gameColumns] = {};
     
    // The following exist purely for readability.
    const int x = 0;
    const int y = 1;
    const int exists = 2;                                    //bool exists;//                       
    const int direction = 3;
    /////////////////////////////////////////////////////////////////////////////
    //                                                                         //
    // Write your functions declarations here. Some have been written for you. //
    //                                                                         //
    /////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite);
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms);
    void moveBullet(float bullet[], sf::Clock& bulletClock);
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite);
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms);
    void initializeShrooms(float shroom[][2],int maxShrooms);
    void initialize_centipede(float centipede[][4],int totalSegments);
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments); 
    void move_centipede(float centipede[][4], sf::Clock& bulletClock, int maxShrooms,float shroom[][2]);   //remove from sf::render..          ////,int maxShrooms,float shroom[][2] //
    void bullet_shroom(float bullet[],float shroom[][2]);
    void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms);
   // void centipede_bullet_collision(float centipede[][4],float bullet[],int totalSegments);
   // void player_shroom_collision(float player[];float shroom[][2] ); 
    int main()
    {
    	srand(time(0));
      /*
      //centipede stuff:
      const int totalSegments = 12;
    float centipede[totalSegments][2]; // 2D array to store x and y positions of each segment
     
    // Initialize centipede positions (for example, starting from the top left)
    const int startX = 100; // Adjust as needed
    const int startY = 100; // Adjust as needed
    const int segmentGap = 20; // Gap between segments
     
    for (int i = 0; i < totalSegments; ++i) {
        centipede[i][0] = startX + i * segmentGap; // x position
        centipede[i][1] = startY; // y position (same for all segments in this example)
        
    }
                         */
     
           
     
     
     
    	// Declaring RenderWindow.
    	sf::RenderWindow window(sf::VideoMode(resolutionX, resolutionY), "Centipede", sf::Style::Close | sf::Style::Titlebar);
     
    	// Used to resize your window if it's too big or too small. Use according to your needs.
    	window.setSize(sf::Vector2u(640, 640)); // Recommended for 1366x768 (768p) displays.
    	//window.setSize(sf::Vector2u(1280, 1280)); // Recommended for 2560x1440 (1440p) displays.
    	// window.setSize(sf::Vector2u(1920, 1920)); // Recommended for 3840x2160 (4k) displays.
    	
    	// Used to position your window on every launch. Use according to your needs.
    	window.setPosition(sf::Vector2i(100, 0));
     
    	// Initializing Background Music.
    	sf::Music bgMusic;
    	bgMusic.openFromFile("Centipede_Skeleton/Music/field_of_hopes.ogg");
    	bgMusic.play();
    	bgMusic.setVolume(50);
     
    	// Initializing Background.
    	sf::Texture backgroundTexture;
    	sf::Sprite backgroundSprite;
    	backgroundTexture.loadFromFile("Centipede_Skeleton/Textures/background.png");
    	backgroundSprite.setTexture(backgroundTexture);
    	backgroundSprite.setColor(sf::Color(255, 255, 255, 200)); // Reduces Opacity to 25%
            
    	// Initializing Player and Player Sprites.
    	float player[2] = {};
    	player[x] = (gameColumns / 2) * boxPixelsX;
    	player[y] = (gameColumns * 3 / 4) * boxPixelsY;
    	sf::Texture playerTexture;
    	sf::Sprite playerSprite;
    	playerTexture.loadFromFile("Centipede_Skeleton/Textures/player.png");
    	playerSprite.setTexture(playerTexture);
    	playerSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock playerClock;
     
    	// Initializing Bullet and Bullet Sprites.
    	float bullet[3] = {};                              
    	                                  //bool bullet1[3];
    	bool request = false;
    	bullet[x] = player[x];
    	bullet[y] = player[y] - boxPixelsY;
    	bullet[exists] = false;
    	sf::Clock bulletClock;
    	sf::Texture bulletTexture;
    	sf::Sprite bulletSprite;
    	bulletTexture.loadFromFile("Centipede_Skeleton/Textures/bullet.png");
    	bulletSprite.setTexture(bulletTexture);
    	bulletSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	//initializing centipede
    	const int totalSegments = 12;
    	float centipede[100][4];
    	
    	//centipede[x] = (gameColumns / 2) * boxPixelsX;           //the position from where centipede will start its journey x-co-ordinate//
    	//centipede[y] = (gameColumns * 3 / 4) * boxPixelsY;         //the position from where centipede will start its journey y-co-ordinate//
    	//centipede[1][exists] = false;
    	for(int i=0;i<totalSegments;i++){
     
    	centipede[i][exists] = true;
    	
    	
    	                                 }
    	               
    	sf::Texture centipedeTexture;
    	sf::Sprite centipedeSprite;
    	centipedeTexture.loadFromFile("Centipede_Skeleton/Textures/c_body_left_walk.png");
    	centipedeSprite.setTexture(centipedeTexture);
    	centipedeSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	
    	sf::Clock centipedeClock;
    	initialize_centipede(centipede,totalSegments);
    	
    	
    	//initializing shrooms:
    	const int maxShrooms = 18;
    	float shroom[25][2] = {};
            
    	sf::Texture shroomTexture;
    	sf::Sprite shroomSprite;
    	shroomTexture.loadFromFile("Centipede_Skeleton/Textures/mushroom.png");
    	shroomSprite.setTexture(shroomTexture);
    	shroomSprite.setTextureRect(sf::IntRect(0, 0, boxPixelsX, boxPixelsY));
    	for(int i=0;i<maxShrooms;i++){
    	shroom[i][exists] = true;
    	                               }  
    	
    	
          
           initializeShrooms(shroom,maxShrooms);           //calling shroom's function to initialize position;
                                                        // shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    	while(window.isOpen()) {
     
    		///////////////////////////////////////////////////////////////
    		//                                                           //
    		// Call Your Functions Here. Some have been written for you. //
    		// Be vary of the order you call them, SFML draws in order.  //
    		//                                                           //
    		///////////////////////////////////////////////////////////////
     
    		window.draw(backgroundSprite);
    		
    		drawPlayer(window, player, playerSprite);
    	        movePlayer(player,bullet,shroom,maxShrooms);                                               //movePlayer(player,bullet);
    		/*shootBullet(bullet,request);
    		if(request){
    		bullet[exists] = true;
    		request = false;          
    		    }                       */  
    		
    		if (bullet[exists] == true) {
    			moveBullet(bullet, bulletClock);
    			
    			drawBullet(window, bullet, bulletSprite);
    			
    		}
    		bullet_shroom(bullet,shroom);
    		
    		drawShrooms(window,shroom,shroomSprite,maxShrooms);
    		
    		
    		
    		drawCentipede(window, centipede, centipedeSprite,totalSegments);
    		move_centipede(centipede,centipedeClock,maxShrooms,shroom);                         //,maxShrooms,shroom//
    		
    		shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
    		
               sf::Event e;
    		while (window.pollEvent(e)) {
    			if (e.type == sf::Event::Closed) {
    				return 0;
    			}
    		
    		}		
    		window.display();
    		window.clear();
    	}
    	 
    	
    	
     }
     
    ////////////////////////////////////////////////////////////////////////////
    //                                                                        //
    // Write your functions definitions here. Some have been written for you. //
    //                                                                        //
    ////////////////////////////////////////////////////////////////////////////
     
    void drawPlayer(sf::RenderWindow& window, float player[], sf::Sprite& playerSprite) {
    	playerSprite.setPosition(player[x], player[y]); 
    	window.draw(playerSprite);
    }
     
     
     
     
    void drawBullet(sf::RenderWindow& window, float bullet[], sf::Sprite& bulletSprite) {
     
     if(bullet[exists] == true){
    	bulletSprite.setPosition(bullet[x], bullet[y]);
    	window.draw(bulletSprite);
    	
        }
     
     }
     
     
     
                     
                           
     
     
     
    void moveBullet(float bullet[], sf::Clock& bulletClock) {
     float bullet_speed = 10.0f;
            
        
     	if (bulletClock.getElapsedTime().asMilliseconds() < 10)
    		return;
            
    	bulletClock.restart(); 
    	bullet[y] += -32;	 
    	if (bullet[y] < -32)    
           {  bullet[exists] = false; }
    		
                                                   }  
                                                   
     
     
           
                                                   
                                                   
     
     
    void drawShrooms(sf::RenderWindow& window, float shroom[][2], sf::Sprite& shroomSprite,int maxShrooms){
         
         for(int i=0;i<maxShrooms;i++){
             if(shroom[i][exists]){                    
                              
                              
                              shroomSprite.setPosition(shroom[i][x],shroom[i][y]);
                              window.draw(shroomSprite);                            
                                                                                      } 
                                                          }                                 
                      } 
     
    void initializeShrooms(float shroom[][2],int maxShrooms){
                                                                                                    
                                                                                                   
         for(int i=0;i<maxShrooms;i++){
                              shroom[i][x] =     rand()%gameRows * boxPixelsX; 
                              shroom[i][y] =     rand()%gameColumns * boxPixelsY;            
                             // shroom[i][exists] = true;                                      }
                                                                            } 
                                                                              }
                                                                               
                                                                                                                                                                   
    void movePlayer(float player[],float bullet[],float shroom[][2], int maxShrooms) {
        float movementSpeed = 5.0f;
        int bottomLimit = resolutionY - (6 * boxPixelsY); // Calculate the bottom limit
   
    bool collisionUp = false;
    bool collisionDown = false;
    bool collisionLeft = false;
    bool collisionRight = false;
 
    // Check for collision with mushrooms in each direction
    for (int i = 0; i < maxShrooms; i++) {
        if (shroom[i][exists]) {
            // Check collision with each mushroom
            // Define collision range around the mushrooms
            float collisionRange = 16.0f; // Adjust this value as needed
 
            // Check collision in each direction
            if (player[x] + boxPixelsX > shroom[i][x] - collisionRange &&
                player[x] < shroom[i][x] + boxPixelsX + collisionRange &&
                player[y] + boxPixelsY > shroom[i][y] - collisionRange &&
                player[y] < shroom[i][y] + boxPixelsY + collisionRange) {
                // Collision occurred, set collision flags based on direction
                if (player[y] > shroom[i][y]) {
                    collisionUp = true;
                }
                if (player[y] < shroom[i][y]) {
                    collisionDown = true;
                }
                if (player[x] > shroom[i][x]) {
                    collisionLeft = true;
                }
                if (player[x] < shroom[i][x]) {
                    collisionRight = true;
                }
            }
        }
    }
        
        
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::W) && player[y] > bottomLimit && !collisionUp) {
            player[y] -= movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::S) && player[y] < resolutionY - boxPixelsY && !collisionDown) {
            player[y] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::D) && player[x] < resolutionX - boxPixelsX && !collisionRight) {
            player[x] += movementSpeed + 3;
        }
        if (sf::Keyboard::isKeyPressed(sf::Keyboard::A) && player[x] > 0 && !collisionLeft) {
            player[x] -= movementSpeed + 3;
        }
        
        if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space) && bullet[exists]==false){
        
        bullet[exists] = true;
        bullet[x] = player[x];
        bullet[y] = player[y] - boxPixelsY;
        
    }
        }
     
    void initialize_centipede(float centipede[][4],int totalSegments){
         
        
             for(int j=0;j<totalSegments;j++){
         centipede[j][x] = boxPixelsX*j;
          centipede[j][y] = boxPixelsY; 
         centipede[j][exists] = true;
         centipede[j][direction] = 1;              //1 for right and 0 for left;
         
         
     
                                                 }
                                              
                 
                                                           }   
     
    void drawCentipede(sf::RenderWindow& window, float centipede[12][4], sf::Sprite& centipedeSprite,const int totalSegments) {
        const int segmentWidth = boxPixelsX; // Width of each centipede segment
        const int segmentHeight = boxPixelsY; // Height of each centipede segment
     
        for (int i = 0; i < totalSegments; ++i) {
            if(centipede[i][exists]){
            centipedeSprite.setPosition(centipede[i][x], centipede[i][y]);
            window.draw(centipedeSprite);
            }
        }
    }
     

 
   void move_centipede(float centipede[][4], sf::Clock& centipedeClock, int maxShrooms,float shroom[][2] ) {                        //, int maxShrooms,float shroom[][2] //
    int totalSegments = 12;
 
    if (centipedeClock.getElapsedTime().asMilliseconds() < 100)
        return;
 
    centipedeClock.restart();
 
    bool reachedBottomRight = true;
    bool reachedBottomLeft = true;
    shroom_centipede_collision(centipede,shroom,totalSegments,maxShrooms);
 
    for (int j = 0;j < totalSegments ; j++) {
        if (centipede[j][direction] == 1 ) { // Moving right                     ////
            if (centipede[j][x] < 928) {
                centipede[j][x] += 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 0; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        } else { // Moving left
            if (centipede[j][x] > 0) {
                centipede[j][x] -= 32;
                if (centipede[j][y] != 928) {
                    reachedBottomRight = false;
                    reachedBottomLeft = false;
                }
            } else {
                centipede[j][direction] = 1; // Change direction to down
                centipede[j][y] += 32;      // Move down a row
            }
        }
    }
    
    for (int j = 0; j < totalSegments; j++){
 if (centipede[j][y] == 928 && centipede[j][x] == 928){
 reachedBottomRight = true;}
 else{reachedBottomRight = false;}
 
 if(centipede[j][y] == 928 && centipede[j][x] < 0){
  reachedBottomLeft = true; }
  else{reachedBottomLeft = false;} 
 
    if (reachedBottomRight || reachedBottomLeft) {
        // Move to the 6th row above the bottom
         {
            centipede[j][y] = 928 - (7 * boxPixelsY);
        }
    }
}
/*mushroom_centipede collsion:

initializeShrooms(shroom,maxShrooms);
for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){

if(shroom[i][x] == centipede[j][x] && shroom[i][y] == centipede[j][y]){
centipede[j][y] += 32;}
                             */
  
   }  










void bullet_shroom(float bullet[], float shroom[][2]) {
    float bulletX = bullet[x];
    float bulletY = bullet[y];
 
    for (int i = 0; i < 18; i++) {
        float shroomX = shroom[i][x];
        float shroomY = shroom[i][y];
 
        // Define a range around the mushroom position for collision detection
        float collisionRange = 16.0f; // Adjust this value as needed
 
        // Check if bullet position is within the range of a mushroom
        if (bulletX >= shroomX - collisionRange && bulletX <= shroomX + collisionRange &&
            bulletY >= shroomY - collisionRange && bulletY <= shroomY + collisionRange) {
          
            shroom[i][exists] = false;
             bullet[exists] = false;
           // break; // Exit loop after handling collision with one mushroom//
        }
        /* if(shroom[i][exists] == false){
         bullet[exists] == true;  }   */
                                    
    }
}                     

void shroom_centipede_collision(float centipede[][4],float shroom[][2],int totalSegments,int maxShrooms){

//initialize_centipede(centipede,totalSegments);
            //initializeShrooms(shroom,maxShrooms);
for(int i=0;i<totalSegments;i++){                                                         //still requiares changes

   for(int j=0;j<maxShrooms;j++){
   
     if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] != 928 && shroom[i][x] != 0){
     centipede[i][y] += 32;
     centipede[i][direction] = !centipede[i][direction];
     centipede[i][x] -=32;  
                                                          
                                     }
     else if(centipede[i][x] == shroom[j][x] && centipede[i][y] == shroom[j][y] && centipede[i][y] == 928 ){
    centipede[i][y] -= 32;  
      centipede[i][direction] = centipede[i][direction];
     //centipede[i][x] +=32;  
    
                                       }
    
    
                                     
                                       }
                                         } 
                                           }
                                           
                                           
                                           
                               
/*void player_shroom_collision(float player[];float shroom[][2] ){

for(int i=0,i<maxShrooms;i++){
   if(player[x] == shroom[i][x] && player[y] == shroom[i][y] ){
   
   player[x



     }                               */                 


/*for(int i=0,j=0;i<maxShrooms && j<totalSegments;i++,j++){
 if(centipede[j][x] == shroom[i][x] && centipede[j][y] == shroom[j][y] ){
 centipede[j][y] += 32;
                                 } 
                                     }
                                        }   */


/*void centipede_bullet_collision(float centipede[][4],float bullet[],int totalSegments){
   
   if(centipede[        */
   
             

let vertical = random() < 0.5;
function tosave(name) {
  let docName =
    "rect_comp_" +
    year() +
    "_" +
    month() +
    "_" +
    day() +
    "-" +
    hour() +
    "_" +
    minute() +
    "_" +
    second();
  save(docName + ".png");
}
void movePlayer(float player[], float bullet[], float shroom[][2], int maxShrooms) {
    float movementSpeed = 5.0f;
    int bottomLimit = resolutionY - (6 * boxPixelsY); // Calculate the bottom limit

    bool collisionUp = false;
    bool collisionDown = false;
    bool collisionLeft = false;
    bool collisionRight = false;

    // Check for collision with mushrooms in each direction
    for (int i = 0; i < maxShrooms; i++) {
        if (shroom[i][exists]) {
            // Check collision with each mushroom
            // Define collision range around the mushrooms
            float collisionRange = 16.0f; // Adjust this value as needed

            // Check collision in each direction
            if (player[x] + boxPixelsX > shroom[i][x] - collisionRange &&
                player[x] < shroom[i][x] + boxPixelsX + collisionRange &&
                player[y] + boxPixelsY > shroom[i][y] - collisionRange &&
                player[y] < shroom[i][y] + boxPixelsY + collisionRange) {
                // Collision occurred, set collision flags based on direction
                if (player[y] > shroom[i][y]) {
                    collisionUp = true;
                }
                if (player[y] < shroom[i][y]) {
                    collisionDown = true;
                }
                if (player[x] > shroom[i][x]) {
                    collisionLeft = true;
                }
                if (player[x] < shroom[i][x]) {
                    collisionRight = true;
                }
            }
        }
    }
import { createDirectus, rest, readFiles } from "@directus/sdk";

interface Example {
    id: string;
    related: number[] | Relational[];
}

interface Relational {
    id: number;
}

interface Schema {
    example: Example[];
    relational: Relational[];
//  For some unexplained reason this fixes it
//    directus_non_existent: string;
}

const directus = createDirectus<Schema>("http://0.0.0.0:8055").with(rest());

const result = await directus.request(
    readFiles({
        fields: ["non-existing", "count(non-existing)"],
    })
);

console.log(result[0]);
(function() {

  var a = b = 5;

})();



console.log(b);
What will the following JavaScript code output?


(function() {

  var a = b = 5;

})();



console.log(b);
Which of the following is not a valid JavaScript variable name?
Where is the correct place to insert a JavaScript?
To display a less than sign in an HTML document we must write
Which is the correct way to write a JavaScript array?
<script type="text/javascript">

var x = 4 + "4";

console.log(x);

</script>
Whats is the output of the following code snippet?


<script type="text/javascript">

var x = 4 + "4";

console.log(x);

</script>
Which of the following is the default positioning elements with CSS?
The variables Numb1 and numb1, are interchangeable in JavaScript
What kind of oppurtunity are you looking now ?
Do you have a job offer after you complete your graduation?
How many hours you can spend maximum in a day during internship ?
Would your college provide NOC certificate to work with companies during final semester(If you are a 2024 passed out student)?
Where is the correct place to insert a JavaScript?
What will the following JavaScript code output?


(function() {

  var a = b = 5;

})();



console.log(b);
What will the following JavaScript code output?


for (var i = 0; i < 3; i++) {

  setTimeout(function() { alert(i); }, 1000 + i);

}
USE [master]
GO
/****** Object:  Database [Hikvision]    Script Date: 3/30/2021 8:55:15 AM ******/
CREATE DATABASE [Hikvision] ON  PRIMARY 
( NAME = N'Hikvision', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\Hikvision.mdf' , SIZE = 8192KB , MAXSIZE = UNLIMITED, FILEGROWTH = 65536KB )
 LOG ON 
( NAME = N'Hikvision_log', FILENAME = N'C:\Program Files\Microsoft SQL Server\MSSQL15.MSSQLSERVER\MSSQL\DATA\Hikvision_log.ldf' , SIZE = 8192KB , MAXSIZE = 2048GB , FILEGROWTH = 65536KB )
GO
IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))
begin
EXEC [Hikvision].[dbo].[sp_fulltext_database] @action = 'enable'
end
GO
ALTER DATABASE [Hikvision] SET ANSI_NULL_DEFAULT OFF 
GO
ALTER DATABASE [Hikvision] SET ANSI_NULLS OFF 
GO
ALTER DATABASE [Hikvision] SET ANSI_PADDING OFF 
GO
ALTER DATABASE [Hikvision] SET ANSI_WARNINGS OFF 
GO
ALTER DATABASE [Hikvision] SET ARITHABORT OFF 
GO
ALTER DATABASE [Hikvision] SET AUTO_CLOSE OFF 
GO
ALTER DATABASE [Hikvision] SET AUTO_SHRINK OFF 
GO
ALTER DATABASE [Hikvision] SET AUTO_UPDATE_STATISTICS ON 
GO
ALTER DATABASE [Hikvision] SET CURSOR_CLOSE_ON_COMMIT OFF 
GO
ALTER DATABASE [Hikvision] SET CURSOR_DEFAULT  GLOBAL 
GO
ALTER DATABASE [Hikvision] SET CONCAT_NULL_YIELDS_NULL OFF 
GO
ALTER DATABASE [Hikvision] SET NUMERIC_ROUNDABORT OFF 
GO
ALTER DATABASE [Hikvision] SET QUOTED_IDENTIFIER OFF 
GO
ALTER DATABASE [Hikvision] SET RECURSIVE_TRIGGERS OFF 
GO
ALTER DATABASE [Hikvision] SET  DISABLE_BROKER 
GO
ALTER DATABASE [Hikvision] SET AUTO_UPDATE_STATISTICS_ASYNC OFF 
GO
ALTER DATABASE [Hikvision] SET DATE_CORRELATION_OPTIMIZATION OFF 
GO
ALTER DATABASE [Hikvision] SET TRUSTWORTHY OFF 
GO
ALTER DATABASE [Hikvision] SET ALLOW_SNAPSHOT_ISOLATION OFF 
GO
ALTER DATABASE [Hikvision] SET PARAMETERIZATION SIMPLE 
GO
ALTER DATABASE [Hikvision] SET READ_COMMITTED_SNAPSHOT OFF 
GO
ALTER DATABASE [Hikvision] SET HONOR_BROKER_PRIORITY OFF 
GO
ALTER DATABASE [Hikvision] SET RECOVERY FULL 
GO
ALTER DATABASE [Hikvision] SET  MULTI_USER 
GO
ALTER DATABASE [Hikvision] SET PAGE_VERIFY CHECKSUM  
GO
ALTER DATABASE [Hikvision] SET DB_CHAINING OFF 
GO
EXEC sys.sp_db_vardecimal_storage_format N'Hikvision', N'ON'
GO
USE [Hikvision]
GO
/****** Object:  User [hik]    Script Date: 3/30/2021 8:55:15 AM ******/
CREATE USER [hik] FOR LOGIN [hik] WITH DEFAULT_SCHEMA=[dbo]
GO
sys.sp_addrolemember @rolename = N'db_owner', @membername = N'hik'
GO
sys.sp_addrolemember @rolename = N'db_accessadmin', @membername = N'hik'
GO
sys.sp_addrolemember @rolename = N'db_securityadmin', @membername = N'hik'
GO
sys.sp_addrolemember @rolename = N'db_ddladmin', @membername = N'hik'
GO
sys.sp_addrolemember @rolename = N'db_backupoperator', @membername = N'hik'
GO
sys.sp_addrolemember @rolename = N'db_datareader', @membername = N'hik'
GO
sys.sp_addrolemember @rolename = N'db_datawriter', @membername = N'hik'
GO
/****** Object:  Table [dbo].[attlog]    Script Date: 3/30/2021 8:55:15 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[attlog](
	[employeeID] [nvarchar](50) NULL,
	[authDateTime] [datetime] NULL,
	[authDate] [date] NULL,
	[authTime] [time](7) NULL,
	[direction] [nvarchar](50) NULL,
	[deviceName] [nvarchar](50) NULL,
	[deviceSN] [nvarchar](50) NULL,
	[personName] [nvarchar](50) NULL,
	[cardNo] [nvarchar](50) NULL,
	[serialNo] [int] IDENTITY(1,1) NOT NULL
) ON [PRIMARY]
GO
USE [master]
GO
ALTER DATABASE [Hikvision] SET  READ_WRITE 
GO
Note-
#react ko single page application bolte h kyuki pure project mai ek hi html file hoti h or sara kaam ussi ke ander hota h.
#entry point -index.js
#React DOM implementation h react ka web app pr.DOM ek tree structure h.react khud ka virtual DOM bnata h.

function Chai()
{
    return(
        <>
        {/* fragment */}
        <h2>I am Nistha</h2>
        <h3>btech</h3>
        </>
       
    )
}
export default Chai;
//@version=4
strategy("YSPS Buy/Sell and Custom Incremental Partial Sell Strategy", overlay=true)
length = input(20, title="BB Length")
mult = input(2.0, title="BB MultFactor")
lengthKC = input(20, title="KC Length")
multKC = input(1.5, title="KC MultFactor")
useTrueRange = input(true, title="Use TrueRange (KC)")
thresholdType = input("Percentage", title="Sell Threshold Type", options=["Percentage", "Dollars", "Cents"])
sellThresholdValue = input(1.0, title="Sell Threshold Value")
incrementalSellPercent = input(1, title="Incremental Sell Percentage (%)")

// Calculate BB
source = close
basis = sma(source, length)
dev = mult * stdev(source, length)
upperBB = basis + dev
lowerBB = basis - dev

// Calculate KC
ma = sma(source, lengthKC)
range = useTrueRange ? tr : (high - low)
rangema = sma(range, lengthKC)
upperKC = ma + rangema * multKC
lowerKC = ma - rangema * multKC

// Buy and Sell conditions
val = linreg(source - avg(highest(high, lengthKC), lowest(low, lengthKC)), lengthKC, 0)
buySignal = crossover(val, 0)
sellSignal = crossunder(val, 0)

// Entry and exit strategy
strategy.entry("Buy", strategy.long, when = buySignal)

// Exit strategy, only if profitable
if (sellSignal and close > strategy.position_avg_price)
    strategy.close("Buy", when = sellSignal)

// Incremental selling when profitable
var float sellThreshold = na
if (strategy.position_size > 0)
    if (thresholdType == "Percentage")
        sellThreshold := strategy.position_avg_price * (1 + sellThresholdValue / 100)
    else if (thresholdType == "Dollars")
        sellThreshold := strategy.position_avg_price + sellThresholdValue
    else
        sellThreshold := strategy.position_avg_price + sellThresholdValue / 100

incrementalSellCondition = strategy.position_size > 0 and close > sellThreshold

if (incrementalSellCondition)
    strategy.close("Buy", qty_percent=incrementalSellPercent, when = incrementalSellCondition)

// Plot signals for manual alert setting
plotshape(series=buySignal, title="Buy Signal", location=location.belowbar, color=color.green, style=shape.labelup, text="Buy")
plotshape(series=sellSignal, title="Sell Signal", location=location.abovebar, color=color.red, style=shape.labeldown, text="Sell")
plotshape(series=incrementalSellCondition, title="Incremental Sell Signal", location=location.abovebar, color=color.purple, style=shape.labeldown, text="Incremental Sell")
star

Mon Dec 04 2023 12:24:47 GMT+0000 (Coordinated Universal Time)

@chiragwebelight #reactj

star

Mon Dec 04 2023 12:24:15 GMT+0000 (Coordinated Universal Time)

@chiragwebelight #reactj

star

Mon Dec 04 2023 11:49:20 GMT+0000 (Coordinated Universal Time)

@lawlaw #r

star

Mon Dec 04 2023 10:05:00 GMT+0000 (Coordinated Universal Time)

@saumyatiwari

star

Mon Dec 04 2023 08:26:22 GMT+0000 (Coordinated Universal Time)

@lawlaw #r

star

Mon Dec 04 2023 01:12:54 GMT+0000 (Coordinated Universal Time)

@iliavial

star

Sun Dec 03 2023 12:26:19 GMT+0000 (Coordinated Universal Time)

@jtkcjtkc

star

Sun Dec 03 2023 12:02:43 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sun Dec 03 2023 11:04:46 GMT+0000 (Coordinated Universal Time) https://swapi.dev/api/planets/?format

@jtkcjtkc

star

Sun Dec 03 2023 08:49:02 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sun Dec 03 2023 08:17:33 GMT+0000 (Coordinated Universal Time) https://codepen.io/dixie0704/pen/jOVxGXL

@AlexP #alpinejs #select #tailwind

star

Sun Dec 03 2023 07:43:50 GMT+0000 (Coordinated Universal Time)

@Shesek

star

Sun Dec 03 2023 07:34:59 GMT+0000 (Coordinated Universal Time)

@Shesek

star

Sun Dec 03 2023 06:45:00 GMT+0000 (Coordinated Universal Time) https://workat.tech/problem-solving/practice/simple-interest

@nistha_jnn #c++

star

Sat Dec 02 2023 20:42:06 GMT+0000 (Coordinated Universal Time)

@mastaklance

star

Sat Dec 02 2023 18:26:25 GMT+0000 (Coordinated Universal Time)

@nistha_jnn #c++

star

Sat Dec 02 2023 18:17:00 GMT+0000 (Coordinated Universal Time)

@nistha_jnn #c++

star

Sat Dec 02 2023 17:30:28 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sat Dec 02 2023 17:05:45 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sat Dec 02 2023 14:36:29 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sat Dec 02 2023 14:16:34 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sat Dec 02 2023 13:47:00 GMT+0000 (Coordinated Universal Time)

@yusufalao #python

star

Sat Dec 02 2023 13:28:41 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sat Dec 02 2023 11:53:02 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sat Dec 02 2023 11:52:18 GMT+0000 (Coordinated Universal Time)

@seb_prjcts_be

star

Sat Dec 02 2023 11:21:08 GMT+0000 (Coordinated Universal Time) https://digops.azurewebsites.net/wp-admin/post.php?post

@jtkcjtkc

star

Sat Dec 02 2023 10:55:57 GMT+0000 (Coordinated Universal Time)

@yolobotoffender

star

Sat Dec 02 2023 10:14:35 GMT+0000 (Coordinated Universal Time)

@Vexel_CM

star

Sat Dec 02 2023 09:25:24 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:22 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:19 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:16 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:13 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:10 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:06 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:25:02 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:24:58 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:24:52 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:24:49 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:24:45 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:24:42 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:24:40 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:19:03 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:15:51 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:15:49 GMT+0000 (Coordinated Universal Time) https://coderbyte.com/candidate-assessment#submitted_code_solution

@yash89

star

Sat Dec 02 2023 09:04:06 GMT+0000 (Coordinated Universal Time) undefined

@jianxiaoyu

star

Sat Dec 02 2023 09:03:23 GMT+0000 (Coordinated Universal Time)

@Taimoor

star

Sat Dec 02 2023 07:33:21 GMT+0000 (Coordinated Universal Time)

@nistha_jnn #c++

star

Fri Dec 01 2023 23:37:41 GMT+0000 (Coordinated Universal Time)

@Tonyfingh

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension