2017-06-09 105 views
-1

你好,我正在嘗試做一個蛇遊戲,而不是使用一個形狀,我想用一個圖像頭和其他身體的其他圖像。 我是新來的WPF和我發現的所有教程只使用形狀。 我想在這一點上能做的是通過使用箭頭鍵移動我的圖像,並最終在我得到那個工作檢測與板上的其他圖像碰撞。 這是我的主窗口xaml代碼。它由一個簡單的圖像(DogeIcon)組成,我想像上面解釋的那樣移動,另一個圖像(貓)是一個障礙。WPF用箭頭鍵移動圖像

<Window x:Class="DogeSNake.MainWindow" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:local="clr-namespace:DogeSNake" 
    mc:Ignorable="d" 
    Title="MainWindow" Height="350" Width="525"> 
<Grid> 
    <Image Name="DogeIcon" HorizontalAlignment="Left" Height="64" Margin="33,27,0,0" VerticalAlignment="Top" Width="64" Source="media/doge.png" MouseEnter="RectangleMouseEnter" /> 
    <Image Name="CatIcon" HorizontalAlignment="Left" Height="40" Margin="445,247,0,0" VerticalAlignment="Top" Width="40" Source="media/cat.png" /> 
</Grid> 

回答

0

,你需要的不是一個網格,但在畫布...

<Window x:Class="DogeSNake.MainWindow" 
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
xmlns:local="clr-namespace:DogeSNake" 
mc:Ignorable="d" 
Title="MainWindow" Height="350" Width="525" FocusManager.FocusedElement="{Binding ElementName=MyCanvas}"> 
    <Canvas Name="MyCanvas" KeyDown="Canvas_KeyDown" Focusable="True" > 
      <Image Name="DogeIcon" Canvas.Left="10" Canvas.Top="10" HorizontalAlignment="Left" Height="64" Margin="0" VerticalAlignment="Top" Width="64" Source="media/doge.png" MouseEnter="RectangleMouseEnter"/> 
      <Image Name="CatIcon" Canvas.Left="200" Canvas.Top="200" HorizontalAlignment="Left" Height="40" Margin="0" VerticalAlignment="Top" Width="40" Source="media/cat.png"/> 
    </Canvas> 
</Window> 

在代碼bahind ...

private void Canvas_KeyDown(object sender, KeyEventArgs e) 
    { 
     if (e.Key == Key.Down) 
     { 
      Canvas.SetTop(DogeIcon, Canvas.GetTop(DogeIcon) + 10); 
     } 
     else if (e.Key == Key.Up) 
     { 
      Canvas.SetTop(DogeIcon, Canvas.GetTop(DogeIcon) - 10); 
     } 
     else if (e.Key == Key.Left) 
     { 
      Canvas.SetLeft(DogeIcon, Canvas.GetLeft(DogeIcon) - 10); 
     } 
     else if (e.Key == Key.Right) 
     { 
      Canvas.SetLeft(DogeIcon, Canvas.GetLeft(DogeIcon) + 10); 
     } 
    } 
+0

考慮,它應該成爲一個「蛇遊戲」,它可能會在網格上運行,並改變關鍵輸入的列和行索引。重要的一點是您可以定義適當數量的列和行,並且不要在圖像上設置邊距。 – Clemens