- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试在 WPF 中制作贪吃蛇游戏,因此我决定使用网格来显示棋盘。蛇应该移动它的 x 和 y 位置来改变网格列和网格行属性。为此,我创建了一个 SnakePlayer
类,一个 Food
类。在 MainWindow
中,我每 200 毫秒调用一次游戏循环,然后听键盘设置蛇的方向。问题是,即使蛇的 x, y 位置在代码中正确更改(我对此进行了测试),蛇的位置变化没有可视化,因为它一直保持在初始位置。
贪吃蛇类:
namespace Snake
{
internal class SnakePlayer
{
// keeps track of the current direction and makes the snake keep moving
public (int x, int y) Acceleration = (x: 0, y: 1);
//rappresents the coordinate of each snake part
private readonly List<(int x, int y)> Body = new();
public (int x, int y) Head;
public SnakePlayer(int NUMBER_OF_ROWS, int NUMBER_OF_COLUMNS)
{
int x = Convert.ToInt32((NUMBER_OF_ROWS - 1) / 2);
int y = Convert.ToInt32((NUMBER_OF_COLUMNS - 1) / 2);
Body.Add((x, y));
Head = Body.ElementAt(0);
}
public void UpdatePosition()
{
for (int i = Body.Count - 2; i >= 0; i--)
{
(int x, int y) = Body.ElementAt(i);
Body[i + 1] = (x, y);
}
MoveHead();
}
private void MoveHead()
{
// for example if acceleration is (1,0) the head keeps going to the right each time the method is called
Head.x += Acceleration.x;
Head.y += Acceleration.y;
}
public void Show(Grid gameGrid)
{
/*
* i basically erase all the previous snake parts and
* then draw new elements at the new positions
*/
gameGrid.Children.Clear();
Body.ForEach(tail =>
{
Border element = GenerateBodyPart(tail.x, tail.y);
gameGrid.Children.Add(element);
});
}
private static Border GenerateBodyPart(int x, int y)
{
static void AddStyles(Border elem)
{
elem.HorizontalAlignment = HorizontalAlignment.Stretch;
elem.VerticalAlignment = VerticalAlignment.Stretch;
elem.CornerRadius = new CornerRadius(5);
elem.Background = Brushes.Green;
}
Border elem = new();
AddStyles(elem);
Grid.SetColumn(elem, x);
Grid.SetRow(elem, y);
return elem;
}
public void Grow()
{
var prevHead = (Head.x,Head.y);
AddFromBottomOfList(Body,prevHead);
}
public bool Eats((int x, int y) position)
{
return Head.x == position.x && Head.y == position.y;
}
public void SetAcceleration(int x, int y)
{
Acceleration.x = x;
Acceleration.y = y;
UpdatePosition();
}
public bool Dies(Grid gameGrid)
{
bool IsOutOfBounds(List<(int x, int y)> Body)
{
int mapWidth = gameGrid.ColumnDefinitions.Count;
int mapHeight = gameGrid.RowDefinitions.Count;
return Body.Any(tail => tail.x > mapWidth || tail.y > mapHeight || tail.x < 0 || tail.y < 0);
}
bool HitsItsSelf(List<(int x, int y)> Body)
{
return Body.Any((tail) =>
{
bool isHead = Body.IndexOf(tail) == 0;
if (isHead) return false;
return Head.x == tail.x && Head.y == tail.y;
});
}
return IsOutOfBounds(Body) || HitsItsSelf(Body);
}
public bool HasElementAt(int x, int y)
{
return Body.Any(tail => tail.x == x && tail.y == y);
}
private static void AddFromBottomOfList<T>(List<T> List,T Element)
{
List<T> ListCopy = new();
ListCopy.Add(Element);
ListCopy.AddRange(List);
List.Clear();
List.AddRange(ListCopy);
}
}
}
食品类:
namespace Snake
{
internal class Food
{
public readonly SnakePlayer snake;
public (int x, int y) Position { get; private set; }
public Food(SnakePlayer snake, Grid gameGrid)
{
this.snake = snake;
Position = GetInitialPosition(gameGrid);
Show(gameGrid);
}
private (int x, int y) GetInitialPosition(Grid gameGrid)
{
(int x, int y) getRandomPosition()
{
static int RandomPositionBetween(int min, int max)
{
Random random = new();
return random.Next(min, max);
}
int cols = gameGrid.ColumnDefinitions.Count;
int rows = gameGrid.RowDefinitions.Count;
int x = RandomPositionBetween(0, cols);
int y = RandomPositionBetween(0, rows);
return (x, y);
}
var position = getRandomPosition();
if (snake.HasElementAt(position.x, position.y)) return GetInitialPosition(gameGrid);
return position;
}
public void Show(Grid gameGrid)
{
static void AddStyles(Border elem)
{
elem.HorizontalAlignment = HorizontalAlignment.Stretch;
elem.VerticalAlignment = VerticalAlignment.Stretch;
elem.CornerRadius = new CornerRadius(500);
elem.Background = Brushes.Red;
}
Border elem = new();
AddStyles(elem);
Grid.SetColumn(elem, Position.x);
Grid.SetRow(elem, Position.y);
gameGrid.Children.Add(elem);
}
}
}
主窗口:
namespace Snake
{
public partial class MainWindow : Window
{
const int NUMBER_OF_ROWS = 15, NUMBER_OF_COLUMNS = 15;
private readonly SnakePlayer snake;
private Food food;
private readonly DispatcherTimer Loop;
public MainWindow()
{
InitializeComponent();
CreateBoard();
snake = new SnakePlayer(NUMBER_OF_ROWS, NUMBER_OF_COLUMNS);
food = new Food(snake, GameGrid);
GameGrid.Focus();
GameGrid.KeyDown += (sender, e) => OnKeySelection(e);
Loop = SetInterval(GameLoop, 200);
}
private void GameLoop()
{
snake.UpdatePosition();
snake.Show(GameGrid);
food.Show(GameGrid);
if (snake.Eats(food.Position))
{
food = new Food(snake, GameGrid);
snake.Grow();
}
else if (snake.Dies(GameGrid))
{
Loop.Stop();
snake.UpdatePosition();
ResetMap();
ShowEndGameMessage("You Died");
}
}
private void OnKeySelection(KeyEventArgs e)
{
if(e.Key == Key.Escape)
{
Close();
return;
}
var DIRECTIONS = new
{
UP = (0, 1),
LEFT = (-1, 0),
DOWN = (0, -1),
RIGHT = (1, 0),
};
Dictionary<string, (int x, int y)> acceptableKeys = new()
{
{ "W", DIRECTIONS.UP },
{ "UP", DIRECTIONS.UP },
{ "A", DIRECTIONS.LEFT },
{ "LEFT", DIRECTIONS.LEFT },
{ "S", DIRECTIONS.DOWN },
{ "DOWN", DIRECTIONS.DOWN },
{ "D", DIRECTIONS.RIGHT },
{ "RIGHT", DIRECTIONS.RIGHT }
};
string key = e.Key.ToString().ToUpper().Trim();
if (!acceptableKeys.ContainsKey(key)) return;
(int x, int y) = acceptableKeys[key];
snake.SetAcceleration(x, y);
}
private void CreateBoard()
{
for (int i = 0; i < NUMBER_OF_ROWS; i++)
GameGrid.RowDefinitions.Add(new RowDefinition());
for (int i = 0; i < NUMBER_OF_COLUMNS; i++)
GameGrid.ColumnDefinitions.Add(new ColumnDefinition());
}
private void ResetMap()
{
GameGrid.Children.Clear();
GameGrid.RowDefinitions.Clear();
GameGrid.ColumnDefinitions.Clear();
}
private void ShowEndGameMessage(string message)
{
TextBlock endGameMessage = new();
endGameMessage.Text = message;
endGameMessage.HorizontalAlignment = HorizontalAlignment.Center;
endGameMessage.VerticalAlignment = VerticalAlignment.Center;
endGameMessage.Foreground = Brushes.White;
GameGrid.Children.Clear();
GameGrid.Children.Add(endGameMessage);
}
private static DispatcherTimer SetInterval(Action cb, int ms)
{
DispatcherTimer dispatcherTimer = new();
dispatcherTimer.Interval = TimeSpan.FromMilliseconds(ms);
dispatcherTimer.Tick += (sender, e) => cb();
dispatcherTimer.Start();
return dispatcherTimer;
}
}
}
主窗口.xaml:
<Window x:Class="Snake.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:Snake"
mc:Ignorable="d"
WindowStyle="None"
Background="Transparent"
WindowStartupLocation="CenterScreen"
Title="MainWindow" Height="600" Width="600" ResizeMode="NoResize" AllowsTransparency="True">
<Border CornerRadius="20" Height="600" Width="600" Background="#FF0D1922">
<Grid x:Name="GameGrid" Focusable="True" ShowGridLines="False"/>
</Border>
</Window>
最佳答案
虽然我不完全理解您希望这款游戏的用户体验,但我进行了一些更改以产生更有意义的结果。
您的 UI 未更新的主要原因是您从未更改 GenerateBodyPart 的位置。它始终等于其初始值。您不应传递永远不变的“尾部”,而应传递具有新位置的“头部”。
改变这个:
private static Border GenerateBodyPart(int x, int y)
{
....
Grid.SetColumn(elem, tail.x);
Grid.SetRow(elem, tail.y);
return elem;
}
要这样(注意我删除了 static
关键字以到达 Head):
private Border GenerateBodyPart(int x, int y)
{
....
Grid.SetColumn(elem, Head.x);
Grid.SetRow(elem, Head.y);
return elem;
}
此外,您的“方向”对于向上和向下都不正确。应该是这样的:
var DIRECTIONS = new
{
UP = (0, -1),
LEFT = (-1, 0),
DOWN = (0, 1),
RIGHT = (1, 0),
};
进行这些更改后,UI 至少更新了蛇的位置。 Watch video .我不确切知道你希望蛇如何显示,但那是你以后要弄清楚的。 :)
祝您编码愉快!
这是我的完整源代码以供引用:Download here
关于c# - 如何修复网格行和列在 wpf 中不更新?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71690908/
您能否建议如何在 Bootstrap 或 IE 兼容的 CSS 网格中,在没有 CSS 网格的情况下进行以下布局。 在大屏幕中 头部,左侧堆叠的 body 和右侧覆盖头部和 body 高度的图像。 [
我想在 Objective-C 中绘制一个 15*15 的网格。格子颜色是蓝色的,就像在诺基亚制作“贪吃蛇”游戏的棋盘一样。 我试过使用 for 循环来创建 subview ,但它似乎不起作用,我查看
我正在尝试将 CSS 网格与 grid-template-columns: repeat(auto-fill, auto) 一起使用,单元格被设置为最大宽度,导致每行一个元素。 p> 是否可以让元素宽
我正在努力在网格的自定义列上添加一个指向网站的简单、简单的链接。我用了 Inchoo blog为列添加自定义渲染器,它可以工作。我认为只需修改渲染并添加标签就足够了。但我的希望破灭了,行不通。 如何做
使用 Gnuplot 我绘制了下图 - 现在,正如您在图像中看到的那样,很难在线条之间识别出其末端的块。所以我想用不同的颜色或样式交替着色网格。 我现在用来给网格着色的代码是 - set style
假设我有一个非常简单的 WPF 网格(6 行 x 6 列),定义如下:
我有一个希望绑定(bind)到 WPF 网格的集合。 我面临的问题是列数是动态的并且取决于集合。这是一个简单的模型: public interface IRows { string Messa
我正在使用 Vaadin 8,我想制作某种混淆矩阵。我想知道是否可以根据单元格位置而不是数据提供者手动填充表格/网格的值。 referenceTable.addColumn(reference ->
我在 http://jsfiddle.net/TsRJy/ 上创建了一个带有 div 框的网格. 问题 我不知道如何使 a:hover 工作。 信息 重写 HTML 代码,因为表格不适合我。 http
银光处女在这里。如何使网格周围的用户控件自动调整大小以适应内部网格宽度?目前,当浏览器窗口更宽时,用户控件的显示尺寸约为 300 或 400 像素。它在数据网格周围呈现垂直和水平滚动条,这很丑陋。我想
这个问题已经有答案了: Equal width columns in CSS Grid (11 个回答) 已关闭 2 年前。 使用 CSS Grid,当您不知道会有多少个子项时,如何将所有子项保留在一
我想使用 CSS Grid 的 grid-template-areas。 但问题是我正在使用的 CMS 添加了大量额外的包装器。有没有办法忽略额外的包装?因为它弄乱了漂亮的网格区域...... 我正在
在我的Grid中,当我单击“操作”按钮(下面的代码中显示的“删除和编辑”按钮)时,我需要弹出一个窗口,而不用警告消息提醒用户; 在下面的代码中,我正在使用HANDLER handler: button
这个问题已经有答案了: Equal width columns in CSS Grid (11 个回答) 已关闭 2 年前。 使用 CSS Grid,当您不知道会有多少个子项时,如何将所有子项保留在一
我需要模拟一个仓库,其中有几辆自动驾驶车辆在给定的布局上移动,并具有简单的优先级规则。根据我的理解,这个问题可以通过离散事件模拟(DES)轻松解决,我会使用 SimPy为了这。 我看到的问题是,我似乎
在 ASP.NET 中,我可以让用户控件在页面上的表格中占据多个单元格: 用户控件1: foo bar 第1页: 并且自动调整列宽以适应最大的用户控件。 这也可以在 WPF
我正在寻找一种方法来实时搜索我的网格+要过滤的复选框。我有一个包含学生的网格(照片和姓名)。我想要的是有一个复选框,可以过滤学生所在的不同类(class)。还有一个搜索栏,我可以在其中输入学生姓名。
我正在使用 jQuery 和 jQuery UI 构建一个 Web 应用程序。我陷入了僵局。我需要的是一个 jQuery 网格,它具有可编辑字段,并以某种方式在这些可编辑单元格之一上合并一个自动完成字
我想知道是否有其他 JavaScript 组件可以提供具有多个分组的网格表示。下面是jqGrid的截图我扩展了允许该功能,但它需要获取所有数据。我希望在扩展分组时加载数据。 另一个修改后的 jqGri
我一直在为我将在此处描述的 CSS 问题而烦恼: 在下面的示例 ( https://codesandbox.io/s/jjq4km89y5 ) 中,您可以看到一个可滚动的内容(紫色背景)和一个被左侧面
我是一名优秀的程序员,十分优秀!