• What Do You Need Help With? V6
    7,544 replies, posted
[QUOTE=JakeAM;40529675]Ok so, I think i'm derping massively here. But over multiple classes and even within the same classes what are the protection rules for variables, etc? For example, in this piece of code, how would I make it secure but so that in the AddWeapon method I can access the list? [code]static class Player { int Health = 100; int Armor = 0; List<Weapon> Weapons = new List<Weapon>(); public static void AddWeapon(string _Name, int _Damage, int _Rate) { // access the weapons list here } }[/code][/QUOTE] Visibility is not for security.
[QUOTE=DesolateGrun;40525637]more rookie help I used a loop and a key stroke in order to fire a gun in my little game, but if you press or hold the key really fast you can fire the gun too many times, how can I make it limited to fire once every 2 seconds? >code >pic what it looks like if anyone was wondering[/QUOTE] Although I have no experience with Java, maybe when the player fires you could create a date object, set the time of it forward by 2 seconds, and at every fire trigger check if the current time > the date time.
[QUOTE=DesolateGrun;40525637]more rookie help I used a loop and a key stroke in order to fire a gun in my little game, but if you press or hold the key really fast you can fire the gun too many times, how can I make it limited to fire once every 2 seconds? Loop for firing [code] public void actionPerformed(ActionEvent e) { ArrayList ms = craft.getMissiles(); for (int i = 0; i < ms.size(); i++) { Gun1 m = (Gun1) ms.get(i); if (m.isVisible()) m.move(); else ms.remove(i); } [/code] keystroke [code] public void fire() { missiles.add(new Gun1(x + CRAFT_SIZE, y + CRAFT_SIZE/2)); } public void keyPressed(KeyEvent e) { int key = e.getKeyCode(); if (key == KeyEvent.VK_INSERT) { fire(); }[/code] [t]http://i40.tinypic.com/34e9i04.png[/t] what it looks like if anyone was wondering[/QUOTE] When you fire, get the current time with System.currentTimeMillis(), store it in a variable "lastTimeFired", and then check if System.currentTimeMillis() - lastTimeFired > 2000 (2000 ms = 2 seconds)
[QUOTE=JakeAM;40529884]Ok so I changed it from being static. But I now have the problem of not being able to access the enum from the player class. [code]using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Test { class Program { static void Main(string[] args) { Player player = new Player(); } } class Weapon { string Name; int Damage; speed Rate; public enum speed { VERY_SLOW, SLOW, FAST, VERY_FAST }; void Weapon(string _Name, int _Damage, speed _Rate) { Name = _Name; Damage = _Damage; Rate = _Rate; } } class Player { int Health = 100; int Armor = 0; List<Weapon> Weapons = new List<Weapon>(); public void AddWeapon(string _Name, int _Damage, speed _Rate) { Weapons.Add(_Name, _Damage, _Rate); } } }[/code][/QUOTE] It's because the enum is a class definition and not static, so it holds a reference to its parent instance and can only be created in an instance method of that parent class. Mark the enum definition as static and it should work.
[QUOTE=Tamschi;40535044]It's because the enum is a class definition and not static, so it holds a reference to its parent instance and can only be created in an instance method of that parent class. Mark the enum definition as static and it should work.[/QUOTE] I thought enums were always static. Is this not the case here because his enum isn't in it's own file , or is that a difference with java? I always put my enums in it's own file and haven't had any problems accessing them.
[QUOTE=mobrockers2;40536489]I thought enums were always static. Is this not the case here because his enum isn't in it's own file , or is that a difference with java? I always put my enums in it's own file and haven't had any problems accessing them.[/QUOTE] Java's enums are [b]very[/b] different from normal ones, they aren't a value type either. It's just a quick way to define a class with some constant instances really, internally they inherit from java.lang.Enum and you can do everything in an enum you can do in a class, [URL="http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html"]including using constructors with parameters[/URL]. [editline]edit[/editline] It's not static because it's an embedded class definition in another class, which implies a reference to the parent (unlike in pretty much every other language). For example, an easy way to leak memory in Java is[code]// I just use a list here because I don't remember any common classes, this also works as fake property initializer. return ArrayList<String> list = new ArrayList<String>() {{ Add("One"); Add("Two"); Add("Three"); Add("Four"); }};[/code]in an instance method. As a rule of thumb: If it's usually a value type or really convenient, chances are that the Java equivalent (similar looking code) is something completely different.
I know how the use of global variables is frowned upon save for a few exceptions. However, I'm using Box2D physics, and the World object holds all entity information such as existence, physics, etc (correct me if I'm wrong.) Would it be reasonable to have a global instance of World?
I don't know if I should make a thread for this or if a post here would work. My gaming community is looking for someone who can code for tf2. I don't know if it is simply plug-ins and such, we are not very tech savvy. We currently own 5 servers that are almost running vanilla right now and could use the help. I think we could pay some, but we recently went through a big split into two communities due to the co-leader deciding to try to take over the entire community and run it himself. Sorry if this isnt the right place to put this :(
[QUOTE=Arthamus;40538885]I know how the use of global variables is frowned upon save for a few exceptions. However, I'm using Box2D physics, and the World object holds all entity information such as existence, physics, etc (correct me if I'm wrong.) Would it be reasonable to have a global instance of World?[/QUOTE] Sure, if you know that you won't ever need more than one.
[QUOTE=Tamschi;40538973]Sure, if you know that you won't ever need more than one.[/QUOTE] Curses.
[QUOTE=Duplolas;40538923]I don't know if I should make a thread for this or if a post here would work. My gaming community is looking for someone who can code for tf2. I don't know if it is simply plug-ins and such, we are not very tech savvy. We currently own 5 servers that are almost running vanilla right now and could use the help. I think we could pay some, but we recently went through a big split into two communities due to the co-leader deciding to try to take over the entire community and run it himself. Sorry if this isnt the right place to put this :([/QUOTE] This is not the place to recruit.
[QUOTE=mobrockers2;40539082]This is not the place to recruit.[/QUOTE] Is there a specific place I can post in for that? And if so could you direct me?
On that note, why exactly ARE global variables frowned upon?
[QUOTE=Zinayzen;40540669]On that note, why exactly ARE global variables frowned upon?[/QUOTE] It's a very common sign of badly designed code. When you use global variables, you add a dependency to the global state of the program, making it less portable. It's also less robust, since any other code can modify the global variable at any time. This means your code shouldn't be making any assumptions that the global variable will stay the same. It's also very hard to track which classes/functions interact with the global variable, so maintaining larger projects becomes exponentially harder when using global variables. [url]http://stackoverflow.com/questions/484635/are-global-variables-bad[/url] [url]http://softwareengineeringexplored.blogspot.com/2009/06/introduction-global-variables-are-those.html[/url] [url]http://forums.phpfreaks.com/topic/205920-why-should-you-not-use-global-variable/[/url] The only time they're acceptable IMO are for constants or global settings for a game or something. Even for the latter, there are better, safer ways of designing it. Like you could make a Settings class and have callbacks for when any setting is changed.
Ah. I'm only vaguely familiar with the concept (I'm learning C++). From what I understand, would they just be variables you declare in the header file or something? Because honestly that sounds much easier (for small projects, anyway).
[QUOTE=Zinayzen;40541864]Ah. I'm only vaguely familiar with the concept (I'm learning C++). From what I understand, would they just be variables you declare in the header file or something? Because honestly that sounds much easier (for small projects, anyway).[/QUOTE] For a small project there may be absolutely no problem at all, but it is not a good habit to get into if you ever plan to work on larger projects with more than one person. Also, you may want to follow some coding paradigm more closely (strictly functional, strictly object oriented), and in this case you will have to be more disciplined than C++ allows you to be, because C++ doesn't enforce a specific style. [editline]5th May 2013[/editline] Along the same lines, can someone explain where singletons become useful?
[QUOTE=Rayjingstorm;40542456]Along the same lines, can someone explain where singletons become useful?[/QUOTE] They're generally just as bad as global variables, as you are introducing global state to the program and making it harder to get your code working in a multi-threaded environment. There's an example on the Wikipedia article of it's use in conjunction with the factory design pattern: [url]http://en.wikipedia.org/wiki/Singleton_pattern#Example_of_use_with_the_factory_method_pattern[/url] Additionally, it might make sense to use a singleton as opposed to a static class if you've got something that depends on global state but needs to implement an interface so it can be used as a parameter. I've never run into this situation, but some libraries like say OpenGL do have global state and someone may want to mesh that into some object-oriented code and use a singleton as the glue between the two.
[QUOTE=robmaister12;40542800]They're generally just as bad as global variables, as you are introducing global state to the program and making it harder to get your code working in a multi-threaded environment. There's an example on the Wikipedia article of it's use in conjunction with the factory design pattern: [url]http://en.wikipedia.org/wiki/Singleton_pattern#Example_of_use_with_the_factory_method_pattern[/url] Additionally, it might make sense to use a singleton as opposed to a static class if you've got something that depends on global state but needs to implement an interface so it can be used as a parameter. I've never run into this situation, but some libraries like say OpenGL do have global state and someone may want to mesh that into some object-oriented code and use a singleton as the glue between the two.[/QUOTE] So to sum up, the singleton is a glorified representation of a global state, and in any case of global state it should only be used when modeling something with global state (like a windowing kit with a specific backend dependent upon platform, or OpenGL)
[QUOTE=Rayjingstorm;40542456]For a small project there may be absolutely no problem at all, but it is not a good habit to get into if you ever plan to work on larger projects with more than one person. Also, you may want to follow some coding paradigm more closely (strictly functional, strictly object oriented), and in this case you will have to be more disciplined than C++ allows you to be, because C++ doesn't enforce a specific style. [editline]5th May 2013[/editline] Along the same lines, can someone explain where singletons become useful?[/QUOTE] Basically, singletons &#8776; global variables.
Need some quick tip on how to store data for my Android app. My app basically saves how long I've spend on my job per day, grouped into weeks. The time spend in an Integer (In seconds worked). So far, I use SharedPreferences. The week, year combinations are stored in a String like "13,2013,14,2013,15,2013" etc (Could be optimized like "13-15,2013" later. The time is stored with the key being "Work2013142" for example. (Year 2013, week 14, Wednesday) Other data, like states saved when the app is minimized is also saved with SharedPreferences. Am I good to go with using this technique, or is it worth making a database with the data?
I've been having a go at networking using SFML. I'm trying to build a simple chat program using a client and a server. I can connect the client to the server, and send messages to it, the problem is when I try to get the server to send a message to the client. [code]if (socket.receive(packet) != sf::Socket::Done)[/code] When it hits this line in the client program, the program just seems to freeze. It doesn't hit any breakpoints. I'm using SFML 2.0. Anyone have any idea? This is the full code: [U]Client[/U] [code] #include <SFML/Network.hpp> #include <iostream> // ------- Client Application ------- using namespace std; bool running = true; string name; string message; sf::Packet packet; sf::TcpSocket socket; void readConfigFile() { } void connectToServer() { cout << "Enter name: "; cin >> name; packet << name; // Create a socket and connect it to ipaddress on port 55001 sf::Socket::Status status = socket.connect("ipaddress", 55001); if (status != sf::Socket::Done) { cout << "Unable to connect to server.\n"; } else { cout << "Successfully connected to server.\n"; } if (socket.send(packet) != sf::Socket::Done) { cout << "Name not sent.\n"; } packet.clear(); } void sendMessage() { getline(cin, message); if (message != "") { packet << name << message; if (socket.send(packet) != sf::Socket::Done) { cout << "Message not sent.\n"; } packet.clear(); } } void listenForMessage() { if (socket.receive(packet) != sf::Socket::Done) { cout << "Unable to receive packet.\n"; } else { packet >> name >> message; cout << name << ": " << message << endl; } } int main() { readConfigFile(); connectToServer(); while (running) { sendMessage(); listenForMessage(); } // End while loop system("pause"); return 0; } [/code] [U]Server[/U] [code] #include <SFML/Network.hpp> #include <iostream> #include <list> // ------- Server Application -------- using namespace std; bool running = true; string name; string message; // Create a packet sf::Packet packet; // Create a selector sf::SocketSelector selector; // Create a listener to listen for new connections sf::TcpListener listener; // List of connected clients list<sf::TcpSocket*> clients; void readConfigFile() { } void distributeMessage() { packet << name << message; for (list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) { sf::TcpSocket& client = **it; if (selector.isReady(client)) { if (client.send(packet) != sf::Socket::Done) { cout << "Unable to relay message.\n"; } } } } void receiveMessage() { // Test the list of sockets. for (list<sf::TcpSocket*>::iterator it = clients.begin(); it != clients.end(); ++it) { sf::TcpSocket& client = **it; if (selector.isReady(client)) { // If the client has sent data to the server... if (client.receive(packet) == sf::Socket::Done) { // Display data from client. if (packet >> name >> message) cout << name << ": " << message << endl; packet.clear(); distributeMessage(); } } } } void tcpListenServer() { // Listen for connections on this port. listener.listen(55001); cout << "Listening for incoming connections on port 55001.\n" << endl; // Add listener to the selector selector.add(listener); // Endless loop that waits for new connections while (running) { // Make the selector wait for data on any socket if (selector.wait()) { if (selector.isReady(listener)) // Test the listener { // If the listener is ready: there is a pending connection sf::TcpSocket* client = new sf::TcpSocket; if (listener.accept(*client) == sf::Socket::Done) { clients.push_back(client); // Add the new client to the clients list // Add the new client to the selector so that we will be notified // when he sends something selector.add(*client); // Receiving packet from client. if (client->receive(packet) == sf::Socket::Done) { if (packet >> name) cout << "User: " << name << " (" << client->getRemoteAddress() << ")" << " has entered the room." << endl; } else { cout << "User connected from address: " << client->getRemoteAddress() << endl; } } else { // Error, we won't get a new connection, delete the socket delete client; } } else { // If listener is not ready // Receiving messages from clients receiveMessage(); } } } } int main() { readConfigFile(); // Start listening for new connections tcpListenServer(); system("pause"); return 0; } [/code]
Thinking about making a Roguelike RPG with SFML and C++. I've only been programming for about 3-4 months so it won't be a breeze. For turn-based combat (think Pokemon), should I use structs or classes for the framework of the battle (the player and enemy's turn)? Also, should abilities have their own separate function or should each be stored in a .txt file? The latter seems complicated taking into account some abilities' effects rely on many different factors such as the next turn's damage, enemy/player health, speed, etc. The code would be a jumble of checks, I think. But on the other hand I'd have a one-for-all function. Any ideas? Thanks in advance.
[QUOTE=Arthamus;40549512]Thinking about making a Roguelike RPG with SFML and C++. I've only been programming for about 3-4 months so it won't be a breeze. For turn-based combat (think Pokemon), should I use structs or classes for the framework of the battle (the player and enemy's turn)? Also, should abilities have their own separate function or should each be stored in a .txt file? The latter seems complicated taking into account some abilities' effects rely on many different factors such as the next turn's damage, enemy/player health, speed, etc. The code would be a jumble of checks, I think. But on the other hand I'd have a one-for-all function. Any ideas? Thanks in advance.[/QUOTE] If you want a structure to keep the callbacks in just use a class. In C++ the difference isn't even that big of a deal because you can (and should) allocate instances on the stack and can easily pass pointers around as needed. The reason structs are used so much in C# game development is that they don't generate garbage, but passing huge structs as value parameters is inefficient. If you want to make the abilities as flexible as possible, separate data and code as much as possible, like in the Pokémon games: You can put data about damage, accuracy and special effects into a .txt or whatever file, then have a dictionary with function pointers for the different kinds of abilities that execute based on the properties. Please don't make a one-for-all function, that's inviting trouble. Make small functions for similar abilities and call them as needed.
[QUOTE=Tamschi;40550075]If you want a structure to keep the callbacks in just use a class. In C++ the difference isn't even that big of a deal because you can (and should) allocate instances on the stack and can easily pass pointers around as needed. The reason structs are used so much in C# game development is that they don't generate garbage, but passing huge structs as value parameters is inefficient. If you want to make the abilities as flexible as possible, separate data and code as much as possible, like in the Pokémon games: You can put data about damage, accuracy and special effects into a .txt or whatever file, then have a dictionary with function pointers for the different kinds of abilities that execute based on the properties. Please don't make a one-for-all function, that's inviting trouble. Make small functions for similar abilities and call them as needed.[/QUOTE] Classes it is, then. Thanks for elaborating as well. Until now I always thought it was more organized to use a one-for-all function. Looks like you cleared it up. I appreciate the advice c:.
What is it called when a class can do something like the following in C#? [code] List<string> ls = new List<string>(); ls.Add("A"); ls.Add("B"); if (ls[0].Equals("A")) { } [/code] Where 'ls' can be accessed like an array even though it's a different datatype? And how would one go about implementing this in a class?
It's called an indexer and MS has a good article on them here: [URL]http://msdn.microsoft.com/en-us/library/2549tw02(v=vs.110).aspx[/URL]
Thanks, really appreciate it.
[QUOTE=Barri167;40553306]What is it called when a class can do something like the following in C#? Where 'ls' can be accessed like an array even though it's a different datatype? And how would one go about implementing this in a class?[/QUOTE] -snip- ninja
Could anyone point me out how pointers work in c++ ?
[url]http://www.cplusplus.com/doc/tutorial/pointers/[/url]
Sorry, you need to Log In to post a reply to this thread.