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 / user-18352557

M3rtix's questions

Martin Hope
M3rtix
Asked: 2023-08-18 04:06:25 +0800 CST

Desejo armazenar e exibir o valor highScore no dispositivo local com .NET MAUI MVVM. Onde e com qual trecho de código posso fazer isso?

  • 5

Estou desenvolvendo um jogo simples de prática matemática com .NET MAUI MVVM. Eu quero que o valor highScore na página principal do jogo seja atualizado depois que eu fechar o aplicativo e inseri-lo novamente toda vez que eu jogar. Qual página e como posso fazer isso?

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; } = BaseViewModel.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
                    playerModal.TimeReaming = 60;
                }
            }
        }

        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 = 60;
                    }
                }

                GenerateQuestion();
            }

            playerModal.Answer = "";

        }

        public void GameOver()
        {
            // Check earned score and update new high score
            if (playerModal.Score > playerModal.HighScore)
            {
                playerModal.HighScore = playerModal.Score;

                // Save the high score to preferences
                Preferences.Default.Set("HighScore", playerModal.HighScore);

            }

            NavigationService.NavigateToAsync(nameof(GameOverPage));
        }
    }
}

HomePageViewModel.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 HomePageViewModel : BaseViewModel
    {
        public ObservableCollection<PlayerModal> PlayerDetails { get; set; } = new ObservableCollection<PlayerModal>();
        public PlayerModal playerModal { get; set; } = BaseViewModel.PlayerModal;
        public HomePageViewModel(INavigationService navigationService) : base(navigationService)
        {
            // Load the high score from preferences
            int highScore = Preferences.Default.Get("HighScore", 0);

            // Set the high score on the view model
            playerModal.HighScore = highScore;
        }

        [RelayCommand]
        public void Play()
        {
            NavigationService.NavigateToAsync(nameof(SelectionPage));
        }
    }
}

HomePage.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.HomePage"
             x:DataType="viewModels:HomePageViewModel"
             Title="Home">
    <VerticalStackLayout VerticalOptions="Center">
        <Label 
            Text="MATH GAME"
            VerticalOptions="Center" 
            HorizontalOptions="Center" 
            FontAttributes="Bold"
            FontSize="50"/>
        <Label 
            Text="High Score"
            Margin="0,15,0,0"
            VerticalOptions="Center" 
            HorizontalOptions="Center" 
            FontAttributes="None"
            FontSize="40"/>
        <Label 
            Text="{Binding playerModal.HighScore}"
            VerticalOptions="Center" 
            HorizontalOptions="Center" 
            FontAttributes="Bold"
            FontSize="30"/>
        <Button Text="Play"
                FontAttributes="Bold"
                FontSize="20"
                Margin="90,30,90,0"
                Command="{Binding PlayCommand}"/>
    </VerticalStackLayout>
</ContentPage>
c#
  • 1 respostas
  • 28 Views
Martin Hope
M3rtix
Asked: 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

  • 4

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 respostas
  • 43 Views

Sidebar

Stats

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

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +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