AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / user-18352557

M3rtix's questions

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

我想使用 .NET MAUI MVVM 在本地设备上存储和显示 highScore 值。我可以在哪里以及使用什么代码片段来执行此操作?

  • 5

我正在使用 .NET MAUI MVVM 开发一个简单的数学练习游戏。我希望在每次玩游戏时关闭应用程序并重新输入后更新游戏主页上的高分值。什么页面以及如何执行此操作?

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

乘法PageViewModel.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));
        }
    }
}

主页.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 个回答
  • 28 Views
Martin Hope
M3rtix
Asked: 2023-08-17 16:22:29 +0800 CST

我在使用 .NET MAUI MVVM 的游戏页面上获得的分数在其他页面上不可见。如何在本地设备中保存分数数据

  • 4

我想显示我在 上获得的分数MultiplicationPage信息GameOverPage。我想我已经从中提取了数据PlayerModal,但它仍然没有显示。

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

乘法PageViewModel.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 个回答
  • 43 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

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

Explore

  • 主页
  • 问题
    • 最新
    • 热门
  • 标签
  • 帮助

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve