Location>code7788 >text

Hongmeng NEXT Development Case: Nine Grid Randomization

Popularity:133 ℃/2024-12-12 20:38:53

 

[Introduction]

In Hongmeng NEXT development, nine lattice lottery is a common and interesting application scenario. Through the nine lattice lottery, users can randomly get different prizes to increase interactivity and fun. In this article, we will introduce how to use the Hongmeng development framework to implement the nine lattice lottery function, and show the implementation details through code analysis.

[Environmental Preparation]

- Operating system: Windows 10

- Development Tools: DevEco Studio NEXT Beta1 Build Version: 5.0.3.806

- Target device: Huawei Mate60 Pro

- Development language: ArkTS

- Framework: ArkUI

- API version: API 12

[Thoughts]

1. Definition of the prize category

First, we define a Prize class to represent the information of each prize, including title, color and description. The prize information is initialized through the constructor to provide data support for subsequent lottery functions.

2. Structure of the lottery page

In the lottery page structure, we use Hongmeng's componentized development approach and define a LotteryPage component. This component contains the state variables required for the lottery, the lottery order array, the prize array, and the implementation methods for the lottery logic.

3. Lottery logic implementation

The logic of the Nine Grid Lottery consists of three main phases: acceleration, constant speed and deceleration. Start the lottery with startLottery method and accelerate it gradually, then go to runAtConstantSpeed method to run the lottery at a constant speed, and finally slow down with slowDown method to show the result of the lottery.

4. Building the UI interface

When building the UI interface, we used Hongmeng's layout components and style settings to display the prizes on the page in the form of nine grids. Each prize grid is clickable, and clicking the draw button will trigger the draw animation to display the draw result dialog.

[complete code]

class Prize {
  title: string // Prize title
  color: string // Prize color
  description: string // Description of the prize

  constructor(title: string, color: string, description: string = "") { // Constructor to initialize prize information
     = title // Set the prize title
     = color // Setting the prize color
     = description // Setting the prize description
  }
}

// Nine Grid Sweepstakes Chart
@Entry // Entry annotation that identifies this as a startable component
@Component // Component annotations that identify this as a component
struct LotteryPage { // Define the sweepstakes page structure
  @State selectedIndex: number = 0 // the currently selected index, initially 0
  private isAnimating: boolean = false // If or not animation is in progress, initially false.
  private selectionOrder: number[] = [0, 1, 2, 5, 8, 7, 6, 3] // Sweepstakes order array
  private cellWidth: number = 200 // Cell width
  private baseMargin: number = 10 // Cell margins
  private prizeArray: Prize[] = [ // Array of prizes
    new Prize("Red Packet", "#ff9675", "$10"), // Create the prize object
    new Prize("Calls.", "#ff9f2e", "$5").
    new Prize("Red Packet", "#8e7fff", "$50").
    new Prize("Red Packet", "#48d1ea", "$30").
    new Prize("Start \n the draw.", "#fffdfd"), // Sweepstakes button
    new Prize("Thanks for participating.", "#5f5f5f5f"), // Engagement prompts
    new Prize("Thanks for participating.", "#5f5f5f"),
    new Prize("Supermarket Bonus", "#5f5f5f", "$100").
    new Prize("Flowers.", "#75b0fe"), // Prize object
  ]
  private intervalID: number = 0 // Timer ID to control the draw speed

  startLottery(speed: number = 500) { // Start the lottery, default speed is 500 milliseconds
    setTimeout(() => { // Setting up delayed execution
      if (speed > 50) { // If the speed is greater than 50
        speed -= 50 // Speed reduction
        (speed) // Recursive call to continue acceleration
      } else {
        () // Velocity reaches threshold and enters homogenization phase
        return
      }
      ++ // Update the selected index
    }, speed) // Delay time to current speed
  }

  runAtConstantSpeed() { // Run the draw at a constant speed
    let speed = 40 + (() * ) // Random generation speed
    clearInterval() // Clear the previous timer
     = setInterval(() => { // Setting a new timer
      if ( >= speed) { // If the index is checked to reach speed
        clearInterval() // Clear the timer
        () // Entering the deceleration phase
        return
      }
      ++ // Update the selected index
    }, 50) // Updated every 50 milliseconds
  }

  slowDown(speed = 50) { // Deceleration, default speed 50 ms
    setTimeout(() => { // Setting up delayed execution
      if (speed < 500) { // If the speed is less than 500
        speed += 50 // Increased speed
        (speed) // Recursive call to continue slowing down
      } else {
         =  %  // Make sure the index is in range
        let index = [] // Get the index of the currently selected prize
         = false // End of animation, set to false
        ().showAlertDialog({ // Show results dialog
          title: 'Results', // Dialog box title
          message: `${[index].title}${[index].description}`, // Display prize information
          confirm: { // Confirm button configuration
            defaultFocus: true, // Default Focus
            value: 'I know.', // Button text
            action: () => { // Button click event
            }
          },
          alignment: , // Center the dialog box
        });
        return
      }
      ++ // Update the selected index
    }, speed) // Delay time to current speed
  }

  build() { // Build the UI
    Column() { // Use column layout
      Flex({ wrap:  }) { // Use flexible layout to allow line breaks
        ForEach(, (item: Prize, index: number) => { // Traverse the prize array
          Column() { // Use a column layout for each prize
            Text(`${}`) // Show prize title
              .fontColor([ % ] == index ?  : // Set the font color according to the selected state
              )
              .fontSize(16) // Setting the font size
            Text(`${}`) // Show prize description
              .fontColor([ % ] == index ?  : // Set the font color according to the selected state
              )
              .fontSize(20) // Setting the font size
          }
          .clickEffect({ level: , scale: 0.8 }) // Click effect
          .onClick(() => { // Click event handling
            if (index == 4) { // If the click is on a sweepstakes button
              if () { // If animation is in progress, return
                return
              }
               = true // Set to being animated
              () // Start the lottery
            }
          })
          .alignItems() // Horizontal center alignment
          .justifyContent() // Vertical center alignment
          .width(`${}lpx`) // Set the cell width
          .height(`${}lpx`) // Set the cell height
          .margin(`${}lpx`) // Set cell margins
          .backgroundColor(index == 4 ? "#ff5444" : // set the background color, the draw button is a special color
            ([ % ] == index ?  : )) // Set background color based on selected state
          .borderRadius(10) // Setting rounded corners
          .shadow({ // Setting up shadow effects
            radius: 10, // Shadow radius
            color: "#f98732", // Shadow color
            offsetX: 0, // Horizontal offset
            offsetY: 20 // Vertical offset
          })
        })
      }.width(`${ * 3 +  * 6}lpx`) // Set the overall width
      .margin({ top: 30 }) // Set the top margin
    }
    .height('100%') // Set the height to 100%
    .width('100%') // Set the width to 100%
    .backgroundColor("#ffb350") // set the background color
  }
}