AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 76919670
Accepted
M3rtix
M3rtix
Asked: 2023-08-17 16:22:29 +0800 CST2023-08-17 16:22:29 +0800 CST 2023-08-17 16:22:29 +0800 CST

A pontuação que ganhei na página do jogo com .NET MAUI MVVM não é visível em outras páginas. Como posso manter os dados de pontuação no dispositivo local

  • 772

Desejo exibir as informações de pontuação que ganhei MultiplicationPageno GameOverPage. Acho que extraí os dados, PlayerModalmas ainda não aparece.

GameOverPage.xaml

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:viewModels="clr-namespace:MauiApp2.ViewModels"
             xmlns:models="clr-namespace:MauiApp2.Models"
             x:Class="MauiApp2.Views.GameOverPage"
             x:DataType="viewModels:GameOverPageViewModel"
             Shell.BackButtonBehavior="{BackButtonBehavior IsVisible=False, IsEnabled=False}"
             Title="GameOverPage">
    <VerticalStackLayout Spacing="60">
        <Label Text="GAME OVER AMK!"
               VerticalOptions="Center" 
               HorizontalOptions="Center" />
        <Label Text="Score"             
               VerticalOptions="Center" 
               HorizontalOptions="Center"/>
        <Label Text="{Binding playerModal.Score}"            
               VerticalOptions="Center" 
               HorizontalOptions="Center"/>
        <Button Text="Try Again" Command="{Binding TryAgainCommand}"/>
        <Button Text="Main Menu" Command="{Binding MainMenuCommand}"/>
    </VerticalStackLayout>
</ContentPage>

GameOverPageViewModel.cs

using CommunityToolkit.Mvvm.Input;
using MauiApp2.Models;
using MauiApp2.Services;
using MauiApp2.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MauiApp2.ViewModels
{
    public partial class GameOverPageViewModel : BaseViewModel
    {
        public ObservableCollection<PlayerModal> PlayerDetails { get; set; } = new ObservableCollection<PlayerModal>();
        public PlayerModal playerModal { get; set; } = new PlayerModal();
        public GameOverPageViewModel(INavigationService navigationService) : base(navigationService)
        {

        }
        [RelayCommand]
        public void TryAgain()
        {
            NavigationService.NavigateToAsync(nameof(MultiplicationPage));
        }
        [RelayCommand]
        async Task MainMenu()
        {
            await Shell.Current.GoToAsync("../../..");
        }
    }
}

PlayerModal.cs

using CommunityToolkit.Mvvm.ComponentModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace MauiApp2.Models
{
    public partial class PlayerModal : ObservableObject
    {
        [ObservableProperty]
        int score;
        [ObservableProperty]
        int highScore;
        [ObservableProperty]
        int timeReaming;
        [ObservableProperty]
        int correctAnswer;
        [ObservableProperty]
        string answer;
        [ObservableProperty]
        string question;
    }
}

MultiplicationPageViewModel.cs

using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
using MauiApp2.Models;
using MauiApp2.Services;
using MauiApp2.Views;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;

namespace MauiApp2.ViewModels
{
    public partial class MultiplicationPageViewModel : BaseViewModel
    {
        public ObservableCollection<PlayerModal> PlayerDetails { get; set; } = new ObservableCollection<PlayerModal>();
        public PlayerModal playerModal { get; set; } = new PlayerModal();
        public ICommand SubmitAnswerCommand { get; }
        public MultiplicationPageViewModel(INavigationService navigationService) : base(navigationService)
        {
            
            playerModal.Score = 0;
            playerModal.TimeReaming= 60;
            SubmitAnswerCommand = new Command(SubmitAnswer);

            // Create a question as an example
            GenerateQuestion();
            // Start the timer
            StartTimer();
        }
        
        [RelayCommand]
        public void GenerateQuestion()
        {
            Random random = new Random();
            int number1 = random.Next(1, 11); // a random number between 1 and 10
            int number2 = random.Next(1, 11); // a random number between 1 and 10

            // playerModal.Answer = (number1 * number2).ToString(); Automatic Answer
            playerModal.Question = $"{number1} x {number2}"; 
            playerModal.CorrectAnswer = number1 * number2;
        }
        public async void StartTimer()
        {
            while (true)
            {
                await Task.Delay(1000); // wait 1 sec
                playerModal.TimeReaming--;

                if (playerModal.TimeReaming == 0)
                {
                    GameOver(); // Finish the game when time is up
                }
            }
        }

        public void SubmitAnswer()
        {
            if (int.TryParse(playerModal.Answer, out int userAnswer))
            {
                int correctAnswer = playerModal.CorrectAnswer;
                if (userAnswer == correctAnswer)
                {
                    playerModal.Score += 10;
                    playerModal.TimeReaming += 5;

                }
                else
                {
                    playerModal.Score -= 10;
                    playerModal.TimeReaming -= 55;

                    // Negative score and time control
                    if (playerModal.Score < 0)
                    {
                        playerModal.Score = 0;
                    }
                    if (playerModal.TimeReaming < 0)
                    {
                        GameOver();
                        playerModal.TimeReaming = 0;
                    }
                }

                GenerateQuestion();
            }

            playerModal.Answer = "";

        }

        public async void GameOver()
        {
            // Check earned score and update new high score
            if (playerModal.Score > playerModal.HighScore)
            {
                playerModal.HighScore = playerModal.Score;
            }
            await NavigationService.NavigateToAsync(nameof(GameOverPage));
        }
    }
}
c#
  • 1 1 respostas
  • 43 Views

1 respostas

  • Voted
  1. Best Answer
    Liyun Zhang - MSFT
    2023-08-17T16:45:19+08:002023-08-17T16:45:19+08:00

    O problema em seu projeto é a PlayerModalinstância MultiplicationPageViewModele GameOverPageViewModelsão diferentes. Então você pode declará-lo no BaseViewModel, como:

    public class BaseViewModel
    {
       public static PlayerModal playerModal { get; set; } = new();
    }
    

    E no GameOverPageViewModel:

    public partial class GameOverPageViewModel : BaseViewModel
        {
            public PlayerModal playerModal { get; set; } = BaseViewModel.playerModal;
    

    E no MultiplicationPageViewModel:

    public partial class MultiplicationPageViewModel : BaseViewModel
        {
            public PlayerModal playerModal { get; set; } = BaseViewModel.playerModal;
    

    Além disso, você também pode tentar passar o playerModal ou a pontuação para a outra página ao navegar.

    • 2

relate perguntas

  • Use a hierarquia TreeView com HierarchicalDataTemplate de dentro de um DataTemplate

  • Como posso melhorar essa interface de validação no .NET?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve