• 八方資訊網歡迎您!
    八方資訊網>汽車>正文

    C# WPF從RIOT API獲取數據(RIOT代表作品《英雄聯盟》)

    2020-03-28 06:26:07 來源: 閱讀:

    閱讀導航

    1. 本文背景
    2. 代碼實現
    3. 本文參考

    1. 本文背景

    RIOT(拳頭)是一家美國網游開發商,成立于2006年,代表作品《英雄聯盟》。

    本文重點要講解兩個知識點:

    1. C# 使用 HttpClient 訪問 RIOT 提供的 API 接口,獲取召喚者概況信息;
    2. C# WPF界面展示召喚者信息搜索、概況信息兩個界面。

    2. 代碼實現

    站長使用 .Net CORE 3.1 創建名為 “LoLGoal” 的WPF解決方案,并添加3個Nuget包,配置如下:

    <?xml version="1.0" encoding="utf-8"?><packages>  <package id="MaterialDesignColors" version="1.1.1" targetFramework="net45" />  <package id="MaterialDesignThemes" version="2.5.0.1205" targetFramework="net45" />  <package id="Newtonsoft.Json" version="12.0.1" targetFramework="net45" /></packages>

    界面使用的MD控件,本站曾有介紹:介紹 。

    本文只簡單說明部分代碼,整體解決方案目錄結構如下,源碼文末會給出:

    2.1 引入MD控件樣式

    文件【App.xaml】

    <Application x:Class="LoLGoal.App"             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"             StartupUri="View/MainWindow.xaml">    <Application.Resources>        <ResourceDictionary>            <ResourceDictionary.MergedDictionaries>                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml" />                <ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml" />                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Primary/MaterialDesignColor.Purple.xaml" />                <ResourceDictionary Source="pack://application:,,,/MaterialDesignColors;component/Themes/Recommended/Accent/MaterialDesignColor.Blue.xaml" />            </ResourceDictionary.MergedDictionaries>        </ResourceDictionary>    </Application.Resources></Application>

    2.2 召喚者概況搜索界面

    文件【MainWindow.xaml】代碼,界面布局簡單,給人的感覺整體簡潔大方:

    <Window x:Class="LoLGoal.MainWindow"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        mc:Ignorable="d" Height="600" Width="400" WindowStartupLocation="CenterScreen"         MouseLeftButtonDown="Window_MouseLeftButtonDown"        ResizeMode="NoResize" WindowStyle="None" Background="#FF410A66">    <Grid>        <StackPanel Margin="50">            <Image Source="/Assets/logo2.png" Width="96" Height="96"/>            <Border Background="White" Margin="10 20" CornerRadius="5">                <StackPanel Margin="25">                    <ComboBox Margin="15" Style="{StaticResource MaterialDesignFloatingHintComboBox}" materialDesign:HintAssist.Hint="地區" Text="{Binding Region}">                        <ComboBoxItem Content="RU"/>                        <ComboBoxItem Content="KR"/>                        <ComboBoxItem Content="BR1"/>                        <ComboBoxItem Content="OC1"/>                        <ComboBoxItem Content="JP1"/>                        <ComboBoxItem Content="NA1"/>                        <ComboBoxItem Content="EUN1"/>                        <ComboBoxItem Content="EUW1"/>                        <ComboBoxItem Content="TR1"/>                        <ComboBoxItem Content="LA1"/>                        <ComboBoxItem Content="LA2"/>                    </ComboBox>                    <TextBox Text="{Binding SummonerName}" Margin="15" Style="{StaticResource MaterialDesignFloatingHintTextBox}" materialDesign:HintAssist.Hint="召喚者"/>                    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center">                        <Button Margin="15 50" Content="取消"/>                        <Button x:Name="ButtonSignUp" Margin="15 50" Content="搜索" Click="ButtonSignUp_Click"/>                    </StackPanel>                </StackPanel>            </Border>        </StackPanel>    </Grid></Window>

    召喚者概況搜索界面



    2.3 召喚者概況信息展示界面

    文件【WindowProfile.xaml】,布局代碼也不多,清爽:

    <Window x:Class="LoLGoal.View.WindowProfile"        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"        mc:Ignorable="d" Height="600" Width="400"         WindowStartupLocation="CenterScreen" ResizeMode="NoResize"         WindowStyle="None" Background="#FF410A66">    <Grid>        <Border Background="White" Margin="20 100 20 20" CornerRadius="15">            <StackPanel VerticalAlignment="Top" HorizontalAlignment="Stretch">                <Border Width="100" Height="100" Margin="20 20 0 10" BorderBrush="Gray" HorizontalAlignment="Left" BorderThickness="1" CornerRadius="15">                    <Border.Background>                        <ImageBrush ImageSource="{Binding Path=Icon}"/>                    </Border.Background>                </Border>                <TextBlock Margin="20 15" FontSize="30" Text="{Binding Path=SummonerName}" Foreground="DarkGray"/>                <StackPanel Orientation="Horizontal" Margin="20 0">                    <StackPanel Margin="5">                        <TextBlock Text="勝" FontSize="15" FontWeight="Bold" Foreground="Green"/>                        <TextBlock Text="{Binding Path=Wins}" FontSize="18" Foreground="Gray" HorizontalAlignment="Center"/>                    </StackPanel>                    <StackPanel Margin="5">                        <TextBlock Text="輸" FontSize="15" FontWeight="Bold" Foreground="DarkRed"/>                        <TextBlock Text="{Binding Path=Losses}" FontSize="18" Foreground="Gray" HorizontalAlignment="Center"/>                    </StackPanel>                </StackPanel>                <StackPanel Margin="30 20">                    <TextBlock Text="水平" FontSize="15" Foreground="LightGray"/>                    <TextBlock Text="{Binding Path=Level}" HorizontalAlignment="Center" FontSize="80" Foreground="Gray"/>                </StackPanel>                <Grid Margin="20 10">                    <Button x:Name="ButtonSearch" HorizontalAlignment="Left" Style="{StaticResource MaterialDesignFlatButton}" Width="100" Click="ButtonSearch_Click">                        <materialDesign:PackIcon Kind="Search" Width="24" Height="24"/>                    </Button>                    <Button HorizontalAlignment="Right" Width="100" Content="登錄"/>                </Grid>            </StackPanel>        </Border>        <StackPanel HorizontalAlignment="Right" Margin="30 10">            <Image Source="{Binding Path=Emblem}" Width="200" Height="200">                <Image.Effect>                    <DropShadowEffect BlurRadius="40" ShadowDepth="1"/>                </Image.Effect>            </Image>            <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" Margin="5">                <TextBlock FontSize="18" Foreground="Gray" Text="{Binding Path=Tier}" Margin="5" VerticalAlignment="Center"/>                <TextBlock FontSize="20" Foreground="Gray" Text="{Binding Path=Rank}" Margin="5"/>            </StackPanel>        </StackPanel>    </Grid></Window>

    概況信息展示界面



    2.4 簡單的API接口調用封裝

    直接上代碼看,Key.txt是存儲的RIOT開發者Key:

    using System;using System.Collections.Generic;using System.IO;using System.Linq;using System.Net.Http;using System.Text;using System.Threading.Tasks;namespace LoLGoal.API{    public class Api    {        private string Key { get; set; }        private string Region { get; set; }        public Api(string region)        {            Region = region;            Key = GetKey("API/Key.txt");        }        protected HttpResponseMessage GET(string URL)        {            using (HttpClient client = new HttpClient())            {                var result = client.GetAsync(URL);                result.Wait();                return result.Result;            }        }        protected string GetURI(string path)        {            return "https://" + Region + ".api.riotgames.com/lol/" + path + "?api_key=" + Key;        }        public string GetKey(string path)        {            StreamReader sr = new StreamReader(path);            return sr.ReadToEnd();        }    }}

    2.5 其他代碼

    查看源碼:get_profile_data

    2.6 以下是站長方便演示、截圖,修改的部分文件

    可參考源碼對比:

    文件【API/League_V4.cs】

    using LoLGoal.Model;using System;using System.Collections.Generic;namespace LoLGoal.API{    public class League_V4 : Api    {        public League_V4(string region) : base(region)        {        }        public List<PositionDTO> GetPositions(string summonerId)        {            //1、這是正常的API訪問            //string path = "league/v4/positions/by-summoner/" + summonerId;            //var response = GET(GetURI(path));            //string content = response.Content.ReadAsStringAsync().Result;            //if (response.StatusCode == System.Net.HttpStatusCode.OK)            //{            //    return JsonConvert.DeserializeObject<List<PositionDTO>>(content);            //}            //else            //{            //    return null;            //}            //2、這是模擬數據,正常訪問LOL服務器,需要注冊Key            string[] tiers = { "Bronze", "Challenger", "Diamond", "Gold", "Grandmaster", "Iron", "Master", "Platinum", "Silver" };            var rd = new Random(DateTime.Now.Millisecond);            var lst = new List<PositionDTO>();            for (int i = 0; i < rd.Next(5, 20); i++)            {                lst.Add(new PositionDTO                {                    Tier = tiers[rd.Next(0, tiers.Length)],                    Rank = "IV",                    Wins = rd.Next(2, 100),                    Losses = rd.Next(2, 100),                    QueueType = "RANKED_SOLO_5x5"                });            }            return lst;        }    }}

    文件【API/Summoner_V4.cs】

    using LoLGoal.Model;using System;namespace LoLGoal.API{    public class Summoner_V4 : Api    {        public Summoner_V4(string region) : base(region)        {        }        public SummonerDTO GetSummonerByName(string SummonerName)        {            //1、這是正常的API訪問            //string path = "summoner/v4/summoners/by-name/" + SummonerName;            //var response = GET(GetURI(path));            //string content = response.Content.ReadAsStringAsync().Result;            //if(response.StatusCode == System.Net.HttpStatusCode.OK)            //{            //    return JsonConvert.DeserializeObject<SummonerDTO>(content);            //}            //else            //{            //    return null;            //}            //2、這是模擬數據,正常訪問LOL服務器,需要注冊Key            return new SummonerDTO            {                ProfileIconId = DateTime.Now.Second,                Name = SummonerName,                SummonerLevel = new Random(DateTime.Now.Millisecond).Next(50, 200),                Id = DateTime.Now.Second.ToString()            };        }    }}

    3.參考

    1. 視頻一:C# WPF Design UI - #1 - Login,配套源碼:LoLGoal。
    2. 視頻二:C# WPF Design UI - #2 (1/2) - REST API Access,配套源碼:get_summoner_data。
    3. 視頻三:C# WPF Design UI - #2 (2/2) - REST API Access,配套源碼:get_summoner_data。
    4. 視頻四:C# WPF Design UI - #3 - Profile,配套源碼:summoner_profile。
    5. 視頻五:C# WPF Design UI - #4 (1/2) - Get Data From RIOT API,配套源碼:get_profile_data。
    6. 視頻六:C# WPF Design UI - #4 (2/2)- Get Data From RIOT API,配套源碼:get_profile_data。

    最終源碼:本文代碼幾乎和源碼一致(第五和第六個視頻配套Github源碼 【get_profile_data】),站長未注冊RIOT開發者Key,所以代碼中采用模擬返回數據的方式,只展示了界面效果,并將部分英文改為中文,便于向大家展示此工程。

    點擊下載源碼:get_profile_data

    除非注明,文章均由 Dotnet9 整理發布,歡迎轉載。
    轉載請注明本文地址:https://dotnet9.com/7026.html

    本文為企業推廣,本網站不做任何建議,僅提供參考,作為信息展示!

    推薦閱讀:麒麟710處理器和驍龍660哪個好

    網友評論
    請登錄后進行評論| 0條評論

    請文明發言,還可以輸入140

    您的評論已經發表成功,請等候審核

    小提示:您要為您發表的言論后果負責,請各位遵守法紀注意語言文明

    回到首頁 回到頂部
    八方資訊網 關于我們| 聯系我們| 招聘信息| 老版地圖| 網站地圖
    免責聲明:八方資訊網所有文字、圖片、視頻、音頻等資料均來自互聯網,不代表本站贊同其觀點,本站亦不為其版權負責。相關作品的原創性、文中陳述文字以及內容數據龐雜本站無法一一核實,如果您發現本網站上有侵犯您的合法權益的內容,請聯系我們,本網站將立即予以刪除!
    Copyright © 2012-2019 http://www.quan28.cn, All rights reserved.
    主站蜘蛛池模板: 免费精品视频在线| 亚洲欧美国产精品专区久久| 九九久久精品国产| 97热久久免费频精品99| 久久久精品久久久久久 | 日韩精品视频在线观看免费| 精品999在线| 久久精品亚洲精品国产色婷| 免费精品精品国产欧美在线欧美高清免费一级在线 | 美女岳肉太深了使劲国产精品亚洲专一区二区三区 | 欧美亚洲成人精品| 97精品国产97久久久久久免费| 成人精品视频99在线观看免费| 区亚洲欧美一级久久精品亚洲精品成人网久久久久 | 久久亚洲中文字幕精品一区| 国产精品久久久久久久午夜片| 国产AV国片精品一区二区| 55夜色66夜色国产精品视频| 亚洲精品国产精品国自产观看 | 国产精品99无码一区二区| 欧美精品三区| 精品国产AⅤ一区二区三区4区| 无码精品一区二区三区免费视频| 久久久久久九九99精品| 伊人 久久 精品| 日韩经典精品无码一区| 精品国产一级在线观看| 中文字幕成人精品久久不卡| 国产精品va无码一区二区| 亚洲精品国产字幕久久不卡 | 国产精品成熟老女人视频| 四虎成人精品在永久在线| 国产精品自在线拍国产手机版| 国产精品性爱| 91视频国产精品| 精品视频无码一区二区三区| 亚洲精品国产精品乱码在线观看 | 99热这里只有精品在线| 国产精品视频永久免费播放| 精品无码人妻一区二区免费蜜桃| 无码人妻精品一区二区三区夜夜嗨|