I can’t realize the possibility of continuing the game after a collision. The snake should stop and start moving after clicking on one of the arrow buttons.
In a collision, a window appears about the loss, I need to continue the game.
I press the button and the following happens:
I don’t understand how I can save the coordinates of the snake just before the collision.
In the moveTimer_Tick method, all elements move, i.e. new coordinates have already appeared at the head and body, then there is a check for collisions with the wall and body. If they are found, a window appears about the loss.
New snake coordinates are not displayed. But after clicking the "Continue" button, an update occurs and the snake climbs to the border.
The question is: how can I save the coordinates of the snake, before the collision, and after continuing to start with them.
namespace Snake{
public partial class MainWindow : Window
{
//The field on which the snake lives
Entity field;
// snake head
Head head;
// whole snake
List<PositionedEntity> snake;
// apple
Apple apple;
//number of points
int score;
// Is movement paused
bool paused;
//time
DispatcherTimer moveTimer;
//constructor form
public MainWindow()
{
InitializeComponent();
snake = new List<PositionedEntity>();
//create field 600x600pixels
field = new Entity(600, 600, "pack://application:,,,/Resources/snake.png");
//create a timer that runs every 300 ms
moveTimer = new DispatcherTimer();
moveTimer.Interval = new TimeSpan(0, 0, 0, 0, 300);
moveTimer.Tick += new EventHandler(moveTimer_Tick);
}
//redraw screen method
private void UpdateField()
{
//update the position of the elements of the snake
foreach (var p in snake)
{
Canvas.SetTop(p.image, p.y);
Canvas.SetLeft(p.image, p.x);
}
//update the position of apple
Canvas.SetTop(apple.image, apple.y);
Canvas.SetLeft(apple.image, apple.x);
//points update
lblScore.Content = String.Format("{0}000", score);
}
//timer tick handler. All movement takes place here.
void moveTimer_Tick(object sender, EventArgs e)
{
// Do not update if movement is paused
if(paused) {
return;
}
//in the reverse order we move all the elements of the snake
foreach (var p in Enumerable.Reverse(snake))
{
p.move();
}
//we check that the head of the snake did not crash into the body
foreach (var p in snake.Where(x => x != head))
{
if (p.x == head.x && p.y == head.y)
{
//we lose
moveTimer.Stop();
GameOver.Visibility = Visibility.Visible;
btnRestart.Visibility = Visibility.Visible;
tbScore.Text = String.Format("SCORE: {0}000", score);
return;
}
}
//check that the head of the snake did not go out of the field
if (head.x < 40 || head.x >= 540 || head.y < 40 || head.y >= 540)
{
//we lose
moveTimer.Stop();
GameOver.Visibility = Visibility.Visible;
btnRestart.Visibility = Visibility.Visible;
tbScore.Text = String.Format("SCORE: {0}000", score);
return;
}
//check that the head of the snake crashed into an apple
if (head.x == apple.x && head.y == apple.y)
{
//increase the score
score++;
//move the apple to a new place
apple.move();
var part = new BodyPart(snake.Last());
canvas1.Children.Add(part.image);
snake.Add(part);
}
UpdateField();
}
private void Window_KeyDown(object sender, KeyEventArgs e)
{
// Unpause movement when any key is pressed
if(paused) {
paused = false;
}
switch (e.Key)
{
case Key.Up:
head.direction = Head.Direction.UP;
break;
case Key.Down:
head.direction = Head.Direction.DOWN;
break;
case Key.Left:
head.direction = Head.Direction.LEFT;
break;
case Key.Right:
head.direction = Head.Direction.RIGHT;
break;
}
}
// "Start"
private void button1_Click(object sender, RoutedEventArgs e)
{
btnStart.Visibility = Visibility.Hidden;
btnRestart.Visibility = Visibility.Hidden;
tBNotEnoughPoints.Visibility = Visibility.Hidden;
score = 0;
snake.Clear();
canvas1.Children.Clear();
// "Game Over"
GameOver.Visibility = Visibility.Hidden;
canvas1.Children.Add(field.image);
apple = new Apple(snake);
canvas1.Children.Add(apple.image);
head = new Head();
snake.Add(head);
canvas1.Children.Add(head.image);
moveTimer.Start();
UpdateField();
}
private void btnContinue_Click(object sender, RoutedEventArgs e)
{
if (score >= 2)
{
GameOver.Visibility = Visibility.Hidden;
btnRestart.Visibility = Visibility.Hidden;
score -= 2;
// Pause movement
paused = true;
moveTimer.Start();
UpdateField();
}
else
{
tBNotEnoughPoints.Visibility = Visibility.Visible;
}
}
public class Entity
{
protected int m_width;
protected int m_height;
Image m_image;
public Entity(int w, int h, string image)
{
m_width = w;
m_height = h;
m_image = new Image();
m_image.Source = (new ImageSourceConverter()).ConvertFromString(image) as ImageSource;
m_image.Width = w;
m_image.Height = h;
}
public Image image
{
get
{
return m_image;
}
}
}
public class PositionedEntity : Entity
{
protected int m_x;
protected int m_y;
public PositionedEntity(int x, int y, int w, int h, string image)
: base(w, h, image)
{
m_x = x;
m_y = y;
}
public virtual void move() { }
public int x
{
get
{
return m_x;
}
set
{
m_x = value;
}
}
public int y
{
get
{
return m_y;
}
set
{
m_y = value;
}
}
}
public class Apple : PositionedEntity
{
List<PositionedEntity> m_snake;
public Apple(List<PositionedEntity> s)
: base(0, 0, 40, 40, "pack://application:,,,/Resources/fruit.png")
{
m_snake = s;
move();
}
public override void move()
{
Random rand = new Random();
do
{
x = rand.Next(13) * 40 + 40 ;
y = rand.Next(13) * 40 + 40 ;
bool overlap = false;
foreach (var p in m_snake)
{
if (p.x == x && p.y == y)
{
overlap = true;
break;
}
}
if (!overlap)
break;
} while (true);
}
}
public class Head : PositionedEntity
{
public enum Direction
{
RIGHT, DOWN, LEFT, UP, NONE
};
Direction m_direction;
public Direction direction {
set
{
m_direction = value;
RotateTransform rotateTransform = new RotateTransform(90 * (int)value);
image.RenderTransform = rotateTransform;
}
}
public Head()
: base(280, 280, 40, 40, "pack://application:,,,/Resources/head.png")
{
image.RenderTransformOrigin = new Point(0.5, 0.5);
m_direction = Direction.NONE;
}
public override void move()
{
switch (m_direction)
{
case Direction.DOWN:
y += 40;
break;
case Direction.UP:
y -= 40;
break;
case Direction.LEFT:
x -= 40;
break;
case Direction.RIGHT:
x += 40;
break;
}
}
}
public class BodyPart : PositionedEntity
{
PositionedEntity m_next;
public BodyPart(PositionedEntity next)
: base(next.x, next.y, 40, 40, "pack://application:,,,/Resources/body.png")
{
m_next = next;
}
public override void move()
{
x = m_next.x;
y = m_next.y;
}
}
}
}
There is something to say about the design of your code, but if you don't care and you want a fast (and ugly) solution you can modify your PositionEntity in order to store old coordinates:
public class PositionedEntity : Entity
{
protected int m_x;
protected int m_y;
protected int m_oldX;
protected int m_oldY;
public PositionedEntity(int x, int y, int w, int h, string image)
: base(w, h, image)
{
m_x = x;
m_y = y;
m_oldX = x;
m_oldY = y;
}
public virtual void move() { }
public virtual void RestorePrevious()
{
m_x = m_oldX;
m_y = m_oldY;
}
public int x
{
get
{
return m_x;
}
set
{
m_oldX = m_x;
m_x = value;
}
}
public int y
{
get
{
return m_y;
}
set
{
m_oldY = m_y;
m_y = value;
}
}
}
When you have a collision you should call the RestorePrevious() on the head and on all the rest of the snake
Related
where should I insert Graphics it to make the game work???
I want to develop a multithreaded application that simulates the movement of billiard balls on a gaming table. The behavior of each ball (i.e. calculating new coordinates and redrawing) is programmed as a separate thread. The usual physical laws apply on the game table - balls bounce off the walls and corners of the table so that the angle of incidence is equal to the angle of reflection, the only exception for this problem is the absence of interactions between the balls (i.e., simply put, they do not collide).
When starting the simulation process, each ball receives some (random) impulse, under the influence of which it moves by inertia, gradually stopping. When the ball stops, the corresponding flow should end. The application
makes sure that there is at least one thread that has not finished its work yet. When all the threads are completed, you need to issue the appropriate message. The program should provide the user with the ability to pause/continue or interrupt the motion simulation process.
To do this, I created everything that is above, and then I don't understand where to move a little
public partial class Form1 : Form
{
private List<Circle> circles = new List<Circle>();
private List<Thread> threads = new List<Thread>();
private bool pause = false;
public Form1()
{
InitializeComponent();
}
public void AddCircle()
{
Circle circle = new Circle();
circles.Add(circle);
}
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
pause = !pause;
}
private void Form1_Paint(object sender, PaintEventArgs e)
{
Graphics g = CreateGraphics();
g.Clear(Color.White);
foreach (Circle circle in circles)
g.FillEllipse(new SolidBrush(circle.color), circle.X, circle.Y, circle.Weidth, circle.Heidth);
}
private void Form1_Click(object sender, EventArgs e)
{
Thread thread = new Thread(t =>
{
AddCircle();
Thread.Sleep(30);
})
{ IsBackground = true };
threads.Add(thread);
thread.Start();
}
}
}
this is my class circle
public class Circle
{
public float x;
public float y;
public float heidth;
public float weidth;
public float dy;
public float dx;
public Color color;
public List<Color> colors = (new Color[] { Color.Pink, Color.Red, Color.Brown, Color.Black }).ToList();
public float X
{
set { x = value; }
get { return x; }
}
public float Y
{
set { y = value; }
get { return y; }
}
public float Heidth
{
set { heidth = value; }
get { return heidth; }
}
public float Weidth
{
set { weidth = value; }
get { return weidth; }
}
public float Dy
{
set { dy = value; }
get { return dy; }
}
public float Dx
{
set { dx = value; }
get { return dx; }
}
public Color Color
{
set { color = value; }
get { return color; }
}
public Circle()
{
Random random = new Random();
x = random.Next(10, 600);
y = random.Next(10, 500);
color = colors[random.Next(colors.Count)];
weidth = 10;
heidth = 10;
dx = random.Next(-50, 50);
dy = random.Next(-50, 50);
}
}
}
I'm trying to make a snake game in WPF and I decided to use a grid to display the board.
The snake is supposed to move its x and y position changing the grid column and grid row property. To achieve this I made a SnakePlayer class, a Food class.
In the MainWindow I call the game loop every 200ms and I listen to the keyboard to set the snake direction.
The issue is, even though the snake x, y position changes correctly in the code ( I tested this ),
the snake changes in position are not visualized because it keeps staying in the initial position.
SnakePlayer Class:
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);
}
}
}
Food Class:
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);
}
}
}
MainWindow:
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;
}
}
}
MainWindow.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>
While I don't fully understand your desired UX for this game, I made a few changes that are producing more meaningful results.
The main reason why your UI isn't updating is because you are never changing your GenerateBodyPart's position. It is always equal to its initial value. Instead of passing the "tail" which never changes, you should be passing the "Head" which has the new position.
Change this:
private static Border GenerateBodyPart(int x, int y)
{
....
Grid.SetColumn(elem, tail.x);
Grid.SetRow(elem, tail.y);
return elem;
}
To be this (notice that I removed the static keyword to get to the Head):
private Border GenerateBodyPart(int x, int y)
{
....
Grid.SetColumn(elem, Head.x);
Grid.SetRow(elem, Head.y);
return elem;
}
Also, your "Directions" are incorrect for UP and DOWN. It should be this:
var DIRECTIONS = new
{
UP = (0, -1),
LEFT = (-1, 0),
DOWN = (0, 1),
RIGHT = (1, 0),
};
After making those changes, the UI was at least updating the snake position. Watch video. I don't know exactly how you want the snake to display, but that's for you to figure out later. :)
Have fun coding!
Here is my full source code for reference: Download here
Form1.cs
namespace SpaceInvadersV3
{
public partial class Form1 : Form
{
public bool isPressed;
Shooter player;
List<Missile> bullet;
List<Enemy> pirate;
Boundary bottom;
Boundary top;
Boundary left;
Boundary right;
public Form1()
{
InitializeComponent();
player = new Shooter(450,460);
bullet = new List<Missile>();
pirate = new List<Enemy>();
for (int i = 0; i < 10; i++)
{
Enemy temp = new Enemy();
pirate.Add(temp);
}
}
private void timer1_Tick(object sender, EventArgs e)
{
player.Move();
foreach (Missile b in bullet)
{
b.Move();
}
foreach (Enemy p in pirate)
{
p.Move();
}
pictureBox1.Invalidate();
if (IsColliding(player, pirate) == true)
{
gameOver();
}
}
Error in "pirate" says that it cannot convert from 'System.Collections.Generic.List<SpaceInvadersV3.Enemy>' to 'SpaceInvadersV3.Enemy' I tried changing the 'IsColliding' function below from (Enemy b) to (List<Enemy> b) but then it doesn't recognize b.Bottom and says that List<Enemy> does not contain a definition for Bottom.
// Keybinds
private void Form1_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
player.goleft = true;
}
if (e.KeyCode == Keys.D)
{
player.goright = true;
}
if (e.KeyCode == Keys.W)
{
player.goup = true;
}
if (e.KeyCode == Keys.S)
{
player.godown = true;
}
if (e.KeyCode == Keys.Space)
{
Missile temp = new Missile(player.x, player.y);
bullet.Add(temp);
}
}
private void Form1_KeyUp(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.A)
{
player.goleft = false;
}
if (e.KeyCode == Keys.D)
{
player.goright = false;
}
if (e.KeyCode == Keys.W)
{
player.goup = false;
}
if (e.KeyCode == Keys.S)
{
player.godown = false;
}
}
// keybinds
private void pictureBox1_Paint(object sender, PaintEventArgs e)
{
player.Draw(e.Graphics);
foreach (Missile b in bullet)
{
b.Draw(e.Graphics);
}
foreach (Enemy p in pirate)
{
p.Draw(e.Graphics);
}
}
private bool IsColliding(Shooter a, Enemy b)
{
bool colliding = true; // presume collision
if (a.Top() > b.Bottom())
{
colliding = false;
}
return colliding;
}
private void gameOver()
{
timer1.Stop();
MessageBox.Show("you died");
}
}
}
Box.cs where both Enemy and Shooter classes inherit from
using System.Drawing;
namespace SpaceInvadersV3
{
class Box
{
public Image pic;
public float x;
public float y;
public float speed;
public Box()
{
x = 0;
y = 0;
speed = 0;
}
// Image Resizing Code
public static Image resizeImage(Image imgToResize, Size size)
{
return (Image)(new Bitmap(imgToResize, size));
}
// image resizing code
public void Draw(Graphics g)
{
g.DrawImage(pic, x, y);
}
public float Width()
{
return pic.Width;
}
public float Height()
{
return pic.Height;
}
public float Left()
{
return x;
}
public float Right()
{
return x + Width();
}
public float Top()
{
return y;
}
public float Bottom()
{
return y + Height();
}
}
}
I Don't think if Shooter and Enemy classes are really relevant, but if you need them, I'll post them. Thanks for your help.
if (IsColliding(player, pirate) == true)
First of all, never write that. It looks amateurish to say "if it is true that these are colliding". Say "if these things are colliding":
if (IsColliding(player, pirate))
Similarly, prefer if (!whatever) to if (whatever == false).
Second, please use plural nouns for collections. That should be pirates, not pirate. You want to emphasize that there is a collection of them to the reader.
Error in "pirate" says that it cannot convert from 'List' to 'Enemy'
Your IsColliding takes a shooter and an enemy, but you are giving it a shooter and a list of enemies. IsColliding doesn't know how to deal with that.
You already know how to fix it. You wanted to move every enemy so you wrote:
foreach (Enemy p in pirate)
{
p.Move();
}
Now you want to check every enemy for collisions, so do the same thing:
foreach (Enemy p in pirate)
{
if (IsColliding(player, p)) { ... }
}
An advanced technique that you will eventually learn is to use query comprehensions on sequences:
var collisions = from p in pirate
where IsColliding(player, p)
select p;
foreach (Enemy p in collisions)
{
... handle the collision...
}
But learn to walk before you try to run.
I am using the DebugConsole script to show the debug output on screen.It works perfectly but appears at the top left corner. I want it to appear inside a panel where I have created a window and a GUI text element and the script gives this option as well. I see the gui text formed as an element in the project console, but is not visible.
I do have a GUI layer
My gui text element is the direct child of a canvas
Camera is set to screen space overlay. I tried worldspace , still not visible.
My code:
namespace OctopartApi
{
using Newtonsoft.Json;
using RestSharp;
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine;
using System.Net;
using UnityEngine.UI;
public class KeywordSearch1 : MonoBehaviour
{
public InputField mainInputField;
public Canvas can;
public Text infoText;
public float x, y;
void Start () {
mainInputField.onEndEdit.AddListener(delegate {LockInput(mainInputField); });
}
void LockInput(InputField input)
{
ExecuteSearch (input.text);
}
public void ExecuteSearch(string inp)
{
// -- your search query --
string query = inp;
string octopartUrlBase = "http://octopart.com/api/v3";
string octopartUrlEndpoint = "parts/search";
string apiKey = "57af648b";
// Create the search request
var client = new RestClient(octopartUrlBase);
var req = new RestRequest(octopartUrlEndpoint, Method.GET)
.AddParameter("apikey", apiKey)
.AddParameter("q", query)
.AddParameter("start", "0")
.AddParameter("limit", "10");
var resp = client.Execute(req);
string octojson = resp.Content;
RootOb rr = JsonUtility.FromJson<RootOb> (octojson);
string hhts = (rr.hits).ToString();
hhts = hhts + rr.user_currency;
infoText.horizontalOverflow = HorizontalWrapMode.Overflow;
infoText.verticalOverflow = VerticalWrapMode.Overflow;
infoText.text = hhts;
// sendR (inp);
// Perform the search and obtain results
/* var resp = client.Execute(req);
var search_response = JsonConvert.DeserializeObject<dynamic>(resp.Content);
Console.WriteLine (search_response);
// Print the number of hits and results
Console.WriteLine("Number of hits: " + search_response["hits"]);
Debug.Log(search_response ["hits"]+"OCTO");
foreach (var result in search_response["results"])
{
var part = result["item"];
Debug.Log(part["brand"]["name"] + "OCTO" + part["mpn"]+part["octopart_url"]);
DebugConsole.Log (part ["brand"] ["name"] + "-- " + part ["mpn"]+" " +part["octopart_url"]);
}*/
}
// -- your API key -- (https://octopart.com/api/register)
private const string APIKEY = "57af648b";
}
}
DebugConsole script :
using UnityEngine;
using System.Collections;
public class DebugConsole : MonoBehaviour
{
public GameObject DebugGui = null; // The GUI that will be duplicated
public Vector3 defaultGuiPosition = new Vector3(0.01F, 0.98F, 0F);
public Vector3 defaultGuiScale = new Vector3(0.5F, 0.5F, 1F);
public Color normal = Color.green;
public Color warning = Color.yellow;
public Color error = Color.red;
public int maxMessages = 30; // The max number of messages displayed
public float lineSpacing = 0.02F; // The amount of space between lines
public ArrayList messages = new ArrayList();
public ArrayList guis = new ArrayList();
public ArrayList colors = new ArrayList();
public bool draggable = true; // Can the output be dragged around at runtime by default?
public bool visible = true; // Does output show on screen by default or do we have to enable it with code?
public bool pixelCorrect = false; // set to be pixel Correct linespacing
public static bool isVisible
{
get
{
return DebugConsole.instance.visible;
}
set
{
DebugConsole.instance.visible = value;
if (value == true)
{
DebugConsole.instance.Display();
}
else if (value == false)
{
DebugConsole.instance.ClearScreen();
}
}
}
public static bool isDraggable
{
get
{
return DebugConsole.instance.draggable;
}
set
{
DebugConsole.instance.draggable = value;
}
}
private static DebugConsole s_Instance = null; // Our instance to allow this script to be called without a direct connection.
public static DebugConsole instance
{
get
{
if (s_Instance == null)
{
s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;
if (s_Instance == null)
{
GameObject console = new GameObject();
console.AddComponent<DebugConsole>();
console.name = "DebugConsoleController";
s_Instance = FindObjectOfType(typeof(DebugConsole)) as DebugConsole;
DebugConsole.instance.InitGuis();
}
}
return s_Instance;
}
}
void Awake()
{
s_Instance = this;
InitGuis();
}
protected bool guisCreated = false;
protected float screenHeight =-1;
public void InitGuis()
{
float usedLineSpacing = lineSpacing;
screenHeight = Screen.height;
if(pixelCorrect)
usedLineSpacing = 1.0F / screenHeight * usedLineSpacing;
if (guisCreated == false)
{
if (DebugGui == null) // If an external GUIText is not set, provide the default GUIText
{
DebugGui = new GameObject();
DebugGui.AddComponent<GUIText>();
DebugGui.name = "DebugGUI(0)";
DebugGui.transform.position = defaultGuiPosition;
DebugGui.transform.localScale = defaultGuiScale;
}
// Create our GUI objects to our maxMessages count
Vector3 position = DebugGui.transform.position;
guis.Add(DebugGui);
int x = 1;
while (x < maxMessages)
{
position.y -= usedLineSpacing;
GameObject clone = null;
clone = (GameObject)Instantiate(DebugGui, position, transform.rotation);
clone.name = string.Format("DebugGUI({0})", x);
guis.Add(clone);
position = clone.transform.position;
x += 1;
}
x = 0;
while (x < guis.Count)
{
GameObject temp = (GameObject)guis[x];
temp.transform.parent = DebugGui.transform;
x++;
}
guisCreated = true;
} else {
// we're called on a screensize change, so fiddle with sizes
Vector3 position = DebugGui.transform.position;
for(int x=0;x < guis.Count; x++)
{
position.y -= usedLineSpacing;
GameObject temp = (GameObject)guis[x];
temp.transform.position= position;
}
}
}
bool connectedToMouse = false;
void Update()
{
// If we are visible and the screenHeight has changed, reset linespacing
if (visible == true && screenHeight != Screen.height)
{
InitGuis();
}
if (draggable == true)
{
if (Input.GetMouseButtonDown(0))
{
if (connectedToMouse == false && DebugGui.GetComponent<GUIText>().HitTest((Vector3)Input.mousePosition) == true)
{
connectedToMouse = true;
}
else if (connectedToMouse == true)
{
connectedToMouse = false;
}
}
if (connectedToMouse == true)
{
float posX = DebugGui.transform.position.x;
float posY = DebugGui.transform.position.y;
posX = Input.mousePosition.x / Screen.width;
posY = Input.mousePosition.y / Screen.height;
DebugGui.transform.position = new Vector3(posX, posY, 0F);
}
}
}
//+++++++++ INTERFACE FUNCTIONS ++++++++++++++++++++++++++++++++
public static void Log(string message, string color)
{
DebugConsole.instance.AddMessage(message, color);
}
//++++ OVERLOAD ++++
public static void Log(string message)
{
DebugConsole.instance.AddMessage(message);
}
public static void Clear()
{
DebugConsole.instance.ClearMessages();
}
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
//---------- void AddMesage(string message, string color) ------
//Adds a mesage to the list
//--------------------------------------------------------------
public void AddMessage(string message, string color)
{
messages.Add(message);
colors.Add(color);
Display();
}
//++++++++++ OVERLOAD for AddMessage ++++++++++++++++++++++++++++
// Overloads AddMessage to only require one argument(message)
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
public void AddMessage(string message)
{
messages.Add(message);
colors.Add("normal");
Display();
}
//----------- void ClearMessages() ------------------------------
// Clears the messages from the screen and the lists
//---------------------------------------------------------------
public void ClearMessages()
{
messages.Clear();
colors.Clear();
ClearScreen();
}
//-------- void ClearScreen() ----------------------------------
// Clears all output from all GUI objects
//--------------------------------------------------------------
void ClearScreen()
{
if (guis.Count < maxMessages)
{
//do nothing as we haven't created our guis yet
}
else
{
int x = 0;
while (x < guis.Count)
{
GameObject gui = (GameObject)guis[x];
gui.GetComponent<GUIText>().text = "";
//increment and loop
x += 1;
}
}
}
//---------- void Prune() ---------------------------------------
// Prunes the array to fit within the maxMessages limit
//---------------------------------------------------------------
void Prune()
{
int diff;
if (messages.Count > maxMessages)
{
if (messages.Count <= 0)
{
diff = 0;
}
else
{
diff = messages.Count - maxMessages;
}
messages.RemoveRange(0, (int)diff);
colors.RemoveRange(0, (int)diff);
}
}
//---------- void Display() -------------------------------------
// Displays the list and handles coloring
//---------------------------------------------------------------
void Display()
{
//check if we are set to display
if (visible == false)
{
ClearScreen();
}
else if (visible == true)
{
if (messages.Count > maxMessages)
{
Prune();
}
// Carry on with display
int x = 0;
if (guis.Count < maxMessages)
{
//do nothing as we havent created our guis yet
}
else
{
while (x < messages.Count)
{
GameObject gui = (GameObject)guis[x];
//set our color
switch ((string)colors[x])
{
case "normal": gui.GetComponent<GUIText>().material.color = normal;
break;
case "warning": gui.GetComponent<GUIText>().material.color = warning;
break;
case "error": gui.GetComponent<GUIText>().material.color = error;
break;
}
//now set the text for this element
gui.GetComponent<GUIText>().text = (string)messages[x];
//increment and loop
x += 1;
}
}
}
}
}// End DebugConsole Class
I am only learning C# and I am trying to make a 2D game. I am at the stage where I have my Form1 set up with a 'PictureBox' for the player and the start of a player class:
class Player
{
private string _name;
private int _health;
internal Player(string name, int health = 100)
{
_name = name;
_health = health;
}
int X = 0;
internal void Draw()
{
updateInput();
Draw();
}
internal void updateInput()
{
if(Keyboard.IsKeyDown(Key.Right))
X = 1;
else if (Keyboard.IsKeyDown(Key.Left))
X = -1;
else
X = 0;
}
}
There is a PictureBox "pb_play" which contains the character's sprite on the main form. I tried setting its access modifier to public but that did not help. I want to change the position of the character by whatever the X value becomes. So I was trying to essentially access that member of the form the class.
I was attempting to do this inside the draw method, so it would update the input, then after that it would set the position, and then repeat the Draw method, looping constantly.
If there is a better way though, feel free to educate me. How can I fix this?
EDIT: Okay, I moved the methods into the UI, as mentioned by a comment. Here is what I have, but the sprite refuses to move:
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Draw();
}
int X = 0;
internal void Draw()
{
updateInput();
pb_play.Location = new Point((pb_play.Location.X + X), 0);
Draw();
}
internal void updateInput()
{
if (Keyboard.IsKeyDown(Key.Right))
X = 5;
else if (Keyboard.IsKeyDown(Key.Left))
X = -5;
else
X = 0;
}
}
I used a timer to fix the issue:
internal void Draw()
{
pb_play.Location = new Point((pb_play.Location.X + X), (pb_play.Location.Y + Y));
}
internal void updateInput()
{
if (Keyboard.IsKeyDown(Key.Right))
X = 1;
else if (Keyboard.IsKeyDown(Key.Left))
X = -1;
else
X = 0;
if (Keyboard.IsKeyDown(Key.Up))
Y = -1;
else if (Keyboard.IsKeyDown(Key.Down))
Y = 1;
else
Y = 0;
}
private void timer1_Tick(object sender, EventArgs e)
{
updateInput();
Draw();
}