• Announcements

    • khawk

      Download the Game Design and Indie Game Marketing Freebook   07/19/17

      GameDev.net and CRC Press have teamed up to bring a free ebook of content curated from top titles published by CRC Press. The freebook, Practices of Game Design & Indie Game Marketing, includes chapters from The Art of Game Design: A Book of Lenses, A Practical Guide to Indie Game Marketing, and An Architectural Approach to Level Design. The GameDev.net FreeBook is relevant to game designers, developers, and those interested in learning more about the challenges in game development. We know game development can be a tough discipline and business, so we picked several chapters from CRC Press titles that we thought would be of interest to you, the GameDev.net audience, in your journey to design, develop, and market your next game. The free ebook is available through CRC Press by clicking here. The Curated Books The Art of Game Design: A Book of Lenses, Second Edition, by Jesse Schell Presents 100+ sets of questions, or different lenses, for viewing a game’s design, encompassing diverse fields such as psychology, architecture, music, film, software engineering, theme park design, mathematics, anthropology, and more. Written by one of the world's top game designers, this book describes the deepest and most fundamental principles of game design, demonstrating how tactics used in board, card, and athletic games also work in video games. It provides practical instruction on creating world-class games that will be played again and again. View it here. A Practical Guide to Indie Game Marketing, by Joel Dreskin Marketing is an essential but too frequently overlooked or minimized component of the release plan for indie games. A Practical Guide to Indie Game Marketing provides you with the tools needed to build visibility and sell your indie games. With special focus on those developers with small budgets and limited staff and resources, this book is packed with tangible recommendations and techniques that you can put to use immediately. As a seasoned professional of the indie game arena, author Joel Dreskin gives you insight into practical, real-world experiences of marketing numerous successful games and also provides stories of the failures. View it here. An Architectural Approach to Level Design This is one of the first books to integrate architectural and spatial design theory with the field of level design. The book presents architectural techniques and theories for level designers to use in their own work. It connects architecture and level design in different ways that address the practical elements of how designers construct space and the experiential elements of how and why humans interact with this space. Throughout the text, readers learn skills for spatial layout, evoking emotion through gamespaces, and creating better levels through architectural theory. View it here. Learn more and download the ebook by clicking here. Did you know? GameDev.net and CRC Press also recently teamed up to bring GDNet+ Members up to a 20% discount on all CRC Press books. Learn more about this and other benefits here.
Sign in to follow this  
Followers 0
Askr

Custom GUI - Assigning functions to buttons

15 posts in this topic

Hey there,

so I've been trying to come up with a GUI (using SFML2.0 and C#) and while it's not really a problem to draw stuff onto the screen (or even checking if the mouse is above a button or if the button is clicked), I can't come up with an idea of how to make the buttons functional.

I want to have a class called "Button" with a Property "ButtonFunction". So when I create a button I can also associate an action to be triggered, when I click the button.

Can anyone give me a kickstart here? I'd also appreciate any other information regarding creating a useful custom GUI.
Thanks in advance!
0

Share this post


Link to post
Share on other sites
Use a delegate that should be set on the buttonFunction property or passed as a construction parameter to the button class. This way you can provide completely new actions but use the same button class for all of your buttons.
0

Share this post


Link to post
Share on other sites
Thanks for your fast reply. Although I don't quite understand how I can achieve the wanted functionality using delegates. :|
Would you mind elaborating your solution some more?
0

Share this post


Link to post
Share on other sites
Yeah basically you do this
[code]
delegate void ButtonDelegate(); //This can return a value and take parameters and is only the definition of how the function should look

class Button
{
public Button(ButtonDelegate delegate)
{
m_delegate = delegate;
}

public onButtonClick()
{
m_delegate();
}

private ButtonDelegate m_delegate;
}

static class Wrapper
{
public static void printHelloWorld()
{
Console.WriteLn("Hello World! From delegate call"):
}
}

Button button = new Button(Wrapper.printHelloWorld);
button.onButtonClick();
}

[/code]

See http://msdn.microsoft.com/en-us/library/900fyy8e%28v=vs.80%29.aspx for more information on delegates. A delegate is effictivly a function pointer and it is a way for you to give a function to something else and call that particular function from that something else, this is how callbacks in C/C++ are usually implemented. Edited by NightCreature83
2

Share this post


Link to post
Share on other sites
To build on what NightCreature said, you might try looking into C# events. They may not be necessary for what you're intending, but I didn't quite understand delegates until I started working with events. Here are [url="http://www.dotnetperls.com/event"]two[/url] [url="http://www.switchonthecode.com/tutorials/csharp-snippet-tutorial-custom-event-handlers"]links[/url] that give a decent intro to events in practice.

I've put together a GUI using SFML 2.0 and C#, so if you'd like more information on what I did (which is functional, if inelegant) let me know.
0

Share this post


Link to post
Share on other sites
Parameterless events:

[code]
public event Action Click; // add this as a member of the button class

protected virtual void OnClick() // Add this function as a member of the button class
{
if (Click != null)
Click(); // This causes all of the attached delegates to be called.
}


// elsewhere, you hook the event using any of the following forms:

// Lambda expression form
button.Click += () => Trace.WriteLine("button clicked!");

// Lambda statement form
button.Click += () =>
{
// Inline code here
};

// Anonymous method form
button.Click += delegate
{
// Inline code here
};


// Standard form
button.Click += FunctionName; // Note: Visual studio will auto-complete this for you if you press TAB twice after typing the +=

and:

void FunctionName()
{
// Stuff here.
}
[/code]

Events with parameters:

[code]
public event Action<MouseButton> Click; // add this as a member of the button class

protected virtual void OnClick(MouseButton mb) // Add this function as a member of the button class
{
if (Click != null)
Click(mb); // This causes all of the attached delegates to be called.
}


// elsewhere, you hook the event using any of the following forms:

// Lambda expression form
button.Click += (mb) => Trace.WriteLine("button clicked: " + mb);

// Lambda statement form
button.Click += (mb) =>
{
// Inline code here
Trace.WriteLine("A button was clicked.");
Trace.WriteLine("It was: "+mb);
};

// Anonymous method form when you don't need the parameter list
button.Click += delegate
{
// Inline code here
};


// Standard form
button.Click += FunctionName; // Note: Visual studio will auto-complete this for you if you press TAB twice after typing the +=

and:

void FunctionName(MouseButton mb)
{
// Stuff here.
}
[/code]


Edited by Nypyren
2

Share this post


Link to post
Share on other sites
[quote name='Askr' timestamp='1354004748' post='5004445']
I'd also appreciate any other information regarding creating a useful custom GUI.
[/quote]

Sure. Search for Gtk#, a C# application for making GUIs.

MonoDevelop
[url="http://monodevelop.com/"]http://monodevelop.com/[/url]
Mono
[url="http://www.mono-project.com/Main_Page"]http://www.mono-project.com/Main_Page[/url]

Gtk# - Can be used to make GUIs in C# targeting Mono and/ or .Net Framework.
[url="http://www.mono-project.com/GtkSharp"]http://www.mono-project.com/GtkSharp[/url]



Clinton
0

Share this post


Link to post
Share on other sites
Wow, thanks guys! That's certainly some interesting stuff to work through.

@NightCreature83
Thanks for explaining, I think I got it now! If I understood correctly delegates might be exactly what I've been looking for.

@Khaiy
[quote]I've put together a GUI using SFML 2.0 and C#, so if you'd like more information on what I did (which is functional, if inelegant) let me know.[/quote]
Sure thing, hit me up with anything you got. I'd love to see how you did it. [img]http://public.gamedev.net//public/style_emoticons/default/biggrin.png[/img]

@Nypyren
[quote]// Standard form
button.Click += FunctionName;[/quote]
I always did stuff like this. The first time I heard of lambda expressions was from your post and although I read the msdn article about lambda expressions by now I'm still a bit lost. You say I could use any of those forms, but do the prior ones do anything [i]better[/i] than the standard form?

@3Ddreamer
Thanks for those links, but I was referring to GUIs in games. Although Gtk# looks promising I don't think I could find a use for it within my current project. [img]http://public.gamedev.net//public/style_emoticons/default/smile.png[/img]
0

Share this post


Link to post
Share on other sites
[quote]Gtk# is being used in games as well as other programs.[/quote]
Is that so? I figured from a quick overview that it was not. Then I shall look into it some more. :)
0

Share this post


Link to post
Share on other sites
[quote name='Askr' timestamp='1354088075' post='5004877']
I always did stuff like this. The first time I heard of lambda expressions was from your post and although I read the msdn article about lambda expressions by now I'm still a bit lost. You say I could use any of those forms, but do the prior ones do anything [i]better[/i] than the standard form?
[/quote]

Yes. The Lambda and anonymous methods are allowed to "capture" or "close over" variables in scope, which isn't available with a standard function.

This is most often used when you're using lambdas in LINQ:

[code]
Console.WriteLine("Please enter a search word:");

string word = Console.ReadLine();

List<Record> matches = allRecords.Where(record => record.Keywords.Contains(word)).ToList(); // "word" is being captured by the lambda
[/code]

In the above example, it's not immediately apparent how powerful capturing variables is. The variables are captured EVEN AFTER they go out of scope of the function that declared them!

This means you can do things like this:

[code]
Button[] buttons = new Button[10];

for (int i=0; i<buttons.Length; ++i)
{
int buttonID = i; // NOTE: If you capture a variable incremented by a loop, bad things happen! You must assign a separate variable, otherwise all lambdas will capture a single variable.
buttons[i] = new Button();
buttons[i].Click += delegate
{
MessageBox.Show("Button " + buttonID + " was clicked!"); // If I use "i" here instead of "buttonID", all buttons would print "Button 10 was clicked!".
};
}
[/code]

And the button handlers will still work even after the function which contained this code exits. Edited by Nypyren
1

Share this post


Link to post
Share on other sites
Sorry for being absent from this topic so long, but I came around testing all your input just now. :]

Everything compiles well enough and I'm almost positive I didn't write anything too stupid, but somehow it just doesn't work. Let me paste some code and tell you what it does (and more importantly, what it does not):

This is from my Program.cs - I spared out the parts I don't consider interesting (FillColor and the like).
[CODE]
Window myWindow = new Window(50, 50, 400, 200);
Button myButton = new Button(0, 0, 150, 25);
myButton.setFillColor(new Color(255, 0, 0));
myButton.Click += new Action(myButton_Click);
myWindow.Add(myButton);

myWindow.Draw();
while (MainWindow.IsOpen())
{
MainWindow.DispatchEvents();
MainWindow.Display();
}

[...]

static void myButton_Click()
{
Console.Write("foo");
}
[/CODE]

This is my button class
[code]
public event Action Click;
protected virtual void OnClick()
{
if (Click != null)
Click();
}

public Button(int x, int y, int w, int h)
{
this.X = x;
this.Y = y;
this.Width = w;
this.Height = h;
}
[/code]

When I run the program the window with a button inside of it pops up, but wherever I click, the corresponding method just isn't called. It came to me that I don't have anything defined yet that does any mouse handling, so I figured I have to do this first. Here however I'm at a loss again. :/ Right now I have this Class called "GuiItem" from which "Button" and "Window" inheret. Should I add MouseEventHandlers for keeping track of the mouse in there, or rather create something new?
0

Share this post


Link to post
Share on other sites
Try replacing
[CODE]myButton.Click += new Action(myButton_Click);[/CODE]
with
[CODE]myButton.Click += myButton_Click;[/CODE]
or
[CODE]myButton.Click += () => {Console.Write("foo");};[/CODE]

From what I can tell in the MSDN article, the constructor format of Action doesn't do what you're thinking it does. I'll gladly take some correction on that if I didn't search deep enough though. Edited by BCullis
0

Share this post


Link to post
Share on other sites
Your syntax looks right for subscribing to the event. When are you calling the OnClick() method from the Button class? If that method isn't being called, then the Click event isn't being raised.

I would track the mouse position and whether or not it's been clicked in the Window class, and then if the position of the cursor is inside of myButton when a click is dispatched call myButton.OnClick(). Edited by Khaiy
0

Share this post


Link to post
Share on other sites
[quote name='BCullis' timestamp='1355495228' post='5010616']
Try replacing
[CODE]myButton.Click += new Action(myButton_Click);[/CODE]
with
[CODE]myButton.Click += myButton_Click;[/CODE]
or
[CODE]myButton.Click += () => {Console.Write("foo");};[/CODE]

From what I can tell in the MSDN article, the constructor format of Action doesn't do what you're thinking it does. I'll gladly take some correction on that if I didn't search deep enough though.
[/quote]
Sorry, this doesn't work. It doesn't even compile due to syntax errors.

[quote name='Khaiy' timestamp='1355538855' post='5010820']
I would track the mouse position and whether or not it's been clicked in the Window class, and then if the position of the cursor is inside of myButton when a click is dispatched call myButton.OnClick().
[/quote]
That was my thought as well. Since you already made a GUI: How did you listen for the mouse? Did you add an own class for this or where did you put it? :) Edited by Askr
0

Share this post


Link to post
Share on other sites
SFML already has a mouse class, so you probably won't need to make one.

The way that mine is set up is in my abstract Screen class I have a method called OnMouseClick. In the main program, after creating the window but before the game loop I register the OnMouseClick event with the Window.MouseButtonPressed event:

[CODE]

RenderWindow myWindow = new RenderWindow(new VideoMode(800, 600), "My Window");

myWindow.Closed += new EventHandler(OnClose);
myWindow.MouseButtonPressed += new EventHandler<MouseButtonEventArgs>(currentGameScreen.OnMouseClick);

[/CODE]

So for every screen that needs to accept mouse input, I have code parsing any input events that are passed to them. The event handler above accepts MouseButtonEventArgs which is descended from EventArgs:

[CODE]

public override void OnMouseClick(object sender, EventArgs e)
{
// Since it comes from a mouse click event, EventArgs argument e carries an enum indicating which mouse input was dispatched with that
// event. So we check what it is:
if (e.Code == SFML.Window.Mouse.Button.Left)
{
// Check if cursor is within the button's clickable region
if (SFML.Mouse.GetPosition(myWindowsName) == // Within myButton's borders)
{
// Execute myButton's left mouse click function
}
}
}

[/CODE]

The thing to remember is that the SFML Window class is set up to receive keyboard and mouse input, so the window is where the listening happens. In my game screen's base class I have a public virtual method OnMouseClick, which is empty. That way any descendant can ignore mouse input by default but still pass it along to child elements. If an object gets the mouse button event argument and uses that particular input, it does whatever it's supposed to do. Edited by Khaiy
0

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!


Register a new account

Sign in

Already have an account? Sign in here.


Sign In Now
Sign in to follow this  
Followers 0