Jump to content
  • Advertisement
    1. Past hour
    2. An alternative is to swap "lane" and "toLane", although that changes the "current lane", which may not be desirable.
    3. I propose a slightly different approach: 1. Start by making one object (of any kind, eg. a cube) that exists in the world, can be displayed, and can react to user input in some way. 2. Think of a game, or a type of game, which you would like your engine to support. 3. Think of the most important feature of that game that your engine does not have. 4. Implement that feature. 5. GOTO 3 until you end up making that game using your engine. 6. GOTO 2 until you end up with a general-purpose engine. I think this order makes the most sense. It focuses on questions that you can easily answer ("What do I want to do? What do i need to do it? What do I not have from the things I need?") and you will end up with a logical order of features and a better sense of progress than trying to order features in a vacuum.
    4. You need to type commands in the console terminal (you need to run the console terminal as administrator): pip install GLFW pip install PyOpenGL pip install Pyrr pip install NumPy Pyrr - for trigonometry and linear algebra NumPy - for special arrays for OpenGL functions You will see how to use these libraries in video tutorial below. Now you are ready to create simple games in Python and OpenGL. See this video tutorial about basics of OpenGL. You can start from the second lesson: Modern OpenGL programming in Python - part 02 - creating a GLFW window After studying of this tutorial you can rewrite a prototype of the Snake 2D Tutorial: Python Snake Game from deprecated/legacy OpenGL 1 to modern OpenGL 3 and make it 3D with textures and lighting. And you will be able to load 3D models from Blender because the video tutorial above covers loading 3D models from Blender. How to create an empty window using GLFW: Copy the file below ("main.py") Place glfw3.dll (glfw3.dll.zip) with "main.py" Run the application. For this run the command in the console terminal: python main.py main.py import glfw def main(): # Initialize glfw if not glfw.init(): return window = glfw.create_window(800, 600, "My OpenGL Window", None, None) if not window: glfw.terminate() return glfw.make_context_current(window) while not glfw.window_should_close(window): glfw.poll_events() glfw.swap_buffers(window) glfw.terminate() if __name__ == "__main__": main()
    5. Yeah I know but so far, with my luck, they're the only company that responded back. Yeah you know my last in person interview was with appliedVR for an Android developer position. In that interview, I did an outstanding job showing them my stuff and know how. What happened was that it turns out that I didn't get the job because I didn't have sufficient actual work experience. If I did they would have hired me on the spot. That's also why I'm not be so picky about jobs.
    6. 1024

      Alternative names for fantasy classes

      Sometimes it is good to use standard names for things. Using standard names for classes makes it easier for players to learn what each class does. Using new names makes the learning curve longer (for the same standard classes), and all you get in return is some originality (but not much, if the classes are still standard in everything except their names). You should think about if that trade-off is worth it.
    7. There is also a (at least one) multiplayer AI-writing RTS: Screeps Interestingly, they are making money by selling CPU time for your AI.
    8. Today
    9. Julie.chan

      Pygame - alternatives?

      You mention vsync, which would suggest you're talking about tearing. But the problem you describe sounds more like the problem of using float positions, which is a different issue. That would be avoided by using only integer positions. If you're talking about actual tearing though (when the top and bottom halves of the screen are in different positions), apparently Pyglet is better for preventing that. It's true that mimicking the refresh display can minimize tearing, but it's not possible to time everything exactly as you propose. Plus, it's very possible for someone to have a different refresh rate, e.g. 59 Hz is one I've seen in some computers I've used, so it's not a 100% reliable solution anyway.
    10. Here's a fairly simple approach I would use: 1) at all times, the player belongs to a "lane". This can be a separate object, and index or just a vector you store in the player object. 2) the player also has a property called "toLane", which is nothing more than a reference another lane. Most of the time this can be some invalid/null value to denote that the player is staying in the current lane 3) when a lane change needs to happen, set the "toLane" to the target lane and start a timer (you may also want to set the speed of the transition)* 4) while the transition is in progress (eg while the timer is less than the desired transition time), lerp the position from "lane" to "toLane" (keep the transition relative to ensure the player can keep moving along the road in the interim) 5) once the lane change finishes, set "lane" to "toLane" and "toLane" to invalid/null * I'm not sure what code you're working with. 'Starting a timer' in this case might be something as simple as adding the player to a list of animated objects where the lane change is applied automatically. This list is then processed every tick until the animation completes and the objects are removed. If you wish to allow the player to be able to undo the lane change by letting them navigate back mid-transition, simply set "toLane" to "lane", set the "lane" property to invalid/null, and treat the player's world position as the source point. Based on your example this seems to have the chance of becoming complicated quickly, however. Unless you provide additional metadata along with the level. Eg what do you do if the player wants to change lanes while in the middle of an intersection?
    11. Yes, you're right! But it's one of problems in my settings. Thanks for your reply and I will learn more about SampleMask!. (PS. I don't know how to make a reply of your post and click the "Report Post", Writing my reply and submitting. Sorry if it will bother you) Yes, I use it(after updating my windows and visual studio) and find out that there's something wrong with my blend setting. It seem's there's a variable in the D3D12_BLEND_DESC structure which is one of the variable of D3D12_GRAPHICS_PIPELINE_STATE_DESC structure. In D3D12_BLEND_DESC, we need to set each render target's writeMask. In my code, I use ={} to initialize the D3D12_BLEND_DESC. And then, each writeMask is set to 0. So, nothing can be writted into the render target and pixel shader never be invocated. ={} DOESN'T GIVE YOU DEFAULTS BUT THE TRAP Thanks for your reply and suggestions
    12. Olivier Girardot

      My Footsteps Sound Effects !

      That sounds awesome ! Contact me any time. And the offer for a discount on my sound effects on ogsoundfx.com still stands. Maybe next time
    13. ProjectTaival

      Dev Diary #007 - Indie Inc.

      Hi, and welcome to this weeks Dev Diary! This last week was entirely on video editing, as I spent all my time on creating the first release version of the Intro Video for Project Taival. Secondly, I have spent time on researching about building a Indie Game company around my first game. You would think that you can't have a Game Company while being an Indie Game developer, but I found a method how that can still be true, while at the same time being more organized with other Indie game developers. More on that down below. Intro Video (Picture: Preview of the latest iteration of the 9th iteration of the Intro Video) During all this time editing the intro video, despite being 10 seconds long (600 frames, at 60fps), I have constant problems with my PC's capability to handle the workload, as many time After Effects freezes due to low amount of RAM (8Gb). This can be mitigated largely by urging the caches often, but when ever I forgot to do so multiple times when previewing the footage, some work has been lost and needed to be done again. Secondly, my 9 years old, 6 core CPU (AMD Phenom 2 1060T) isn't up for the task anymore. Luckily I decided back then to go for a 6 core CPU, even though many review sites touted that it was a waste of money back then (2010), as almost all games only used 1 or 2 cores. If I didn't have 6 cores now, I can only dread at how slow my PC would be now. Due to the age of my PC, the preview speed in After Effects is only a fraction of a frame per second, approximately 1 frame every 3 seconds, when the text layer is enabled . This slows down even the most simple workflow considerably, which is why making a simple 10 second Intro #Video has taken so long. As I'm still just learning how to use After Effects properly, I do many small changes and like to see how they affected the end result, which takes time to see properly. The odd thing is, that the GPU acceleration is enabled, but somehow my PC processes the preview extremely slowly, which is odd to say the least. I have a Geforce GTX 1080 Ti GPU, so it shouldn't be because of a slow card for the job. Ideas for a Games Company Since simple research into company structures is so easy these days, I see no harm in sharing the rudimentary concepts of the ideas I came across for anyone interested. Considering how bad the situation has become in the games industry, as all the largest game companies seem to be headed in to a quantity before quality approach in their games. Most visible example being EA having predatory and borderline predatory micro-transactions in their games and other games companies, like Bethesda following on their tracks with Fallout 76. I have come to believe that a Co-Op model would be the best practice for a games company, as that makes corporate takeovers by behemoths like EA much less likely to happen and keeps the company responsible for their customers in a healthy manner. Thus, those who want to enter the gaming industry to create something remarkable, something that speaks to players in a whole different level than the mass produced husks of ideas of past glory, have a place to do so. As for the Indie developers, a Co-Op can function as a umbrella company for individual game developers, where independent developers do their own games the way they are used to do them. The Co-Op can provide the following benefits; For Developers; - Various Tax benefits (Potential savings in the first 5 years measured in a range of or more than 1k - 20k USD per year). - Security in numbers, which helps all participants to protect their IP's - The developer owns the IP, if the Co-Op has agreed so. For Gamers; - Much better likelihood for quality games, with more creative or experimental core concepts. - Much more incentives for customers (gamers) to build and upkeep a healthy community around the company and it's philosophy. (if the co-op decides to implement such factors). Remember that a regular corporation model can do the same things, but since a Co-Op is much more resilient towards corporate takeovers, a Co-Op harbors more trust and gives a notion of longevity and sincerity of the company. A Co-Op can include customers in the company ecosystem in a more integral way, thus encouraging customer loyalty. Taking care of the company bottom line by keeping the source of your revenue - the customers - happy, in a win-win fashion, is a healthy business decision by any measure. I won't go into details on how to achieve all this, as that is between me and those who would like to build something like this with me. In Finland, it is possible to found a Co-Op by my self also, which I might do before finding partners, as it is a good idea to think hard on who you want to partner up with. This is it for this weeks Dev Diary, thank you for tuning in and welcome again next week!
    14. Uttam Kushwah

      undefined behavior of bullet objects.

      I guess than i have to do it by hard way😵 as Alberth suggested, So thanks for both of your replies and help😄.
    15. lawnjelly

      undefined behavior of bullet objects.

      If you are sure you can confirm it is not tunneling (you've tried continuous collision detection, you are sure of your stepping etc), then you will probably need to use detective work as Alberth suggests, I agree with the advice on using simple tests.
    16. jbadams

      That's it

      Nice one!
    17. ito123456789

      Improbable's SpatialOS GDK for Unity

      Maybe when there is some more direct and simple explanation about what this really is, and there is pricing info people will start using this. I see ads everywhere but I still haven't found a good and simple explanation of what SpatialOS is. And I don't want them to contact me just to try the thing.
    18. 8Observer8

      c# console snake game

      Let's structure the code a little bit. I think it is more convenient to separate drawing and action. This code is just for example. The code below is bad because the snake changes a move direction with changing a food position. Could you explain how do you want to control the snake? By mouse click? Or the snake must move yourself with simple AI (path finding)? int food_x = 0; int food_y = 0; private void timer2_Tick(object sender, EventArgs e) { move = rnd.Next(1, 5); food_x = rnd.Next(0, 200); food_y = rnd.Next(0, 200); } private void Form1_Paint(object sender, PaintEventArgs e) { Graphics g = this.CreateGraphics(); SolidBrush greenBrush = new SolidBrush(Color.Green); SolidBrush blackBrush = new SolidBrush(Color.Black); SolidBrush redBrush = new SolidBrush(Color.Red); //Rectangle rect_green = new Rectangle(340 + x, 280 + y, 10, 10); //Rectangle rect_black = new Rectangle(330 + x, 280 + y, 10, 10); Rectangle rect_green = new Rectangle(150 + x, 150 + y, 10, 10); Rectangle rect_black = new Rectangle(140 + x, 150 + y, 10, 10); Rectangle rect_red = new Rectangle(food_x, food_y, 10, 10); g.FillRectangle(greenBrush, rect_green); g.FillRectangle(blackBrush, rect_black); g.FillRectangle(redBrush, rect_red); redBrush.Dispose(); blackBrush.Dispose(); greenBrush.Dispose(); g.Dispose(); }
    19. Uttam Kushwah

      undefined behavior of bullet objects.

      i tried decreasing down the ball's velocity it is not working.
    20. @ajmiles will be right, I also bumped into this.
    21. james340

      Game concept and tools required question

      Thanks Lorenzo - I've downloaded Unity and am going through a load of tutorials and such to get my head around the engine. Looks pretty in-depth, so will likely take a while to truly get to grips with it, but looking forward to the challenge! Thanks again for your help
    22. LorenzoGatti

      Game concept and tools required question

      Technically, your needs are generic (point and click interaction, probably keyboard, rendering layers of assorted animated stuff) and not very demanding (2D, not realtime), so generic tools like Unity and other popular engines should be fine. Regarding selection of the best one, the only obvious thing that could require an in-depth analysis is how to implement modding with that engine. Everything else you mention is strictly a game design challenge and you won't need special tools to start thinking about them.
    23. hello, finally i have success, all is displayed exactly as expected 😀 Thank you MJP your questions lead me to check SV_Depth use in pixelshader. This is a directx API specific system value. I have now a bit reduced performance: - (45 - 50) fps with 5 million spheres fully shaded, animated - all spheres are visible in the camera The bottleneck i assume is the (depth check/override ) When not all speres are visible in the camera the fps gets higher. Just a information for other co-readers. Typical use case normally: Rendertarget: -we attach a depth buffer with a depth stencil rule that only the pixel neares to the viewport are drawn VertexShader: - we tranform our vertecies by world-view-projection matrix. - then, internally, automatically the depth is computed as position.Z / position.W PixelShader: - the vertecie position remains untouched - the position.Z / position.W value is used to calculate the depth, an used to check if the pixel is drawn or is behind another pixel special use case: depth value shall be manipulated in pixelShader VertexShader: - in my situation the depth of the sprite center is calculated ( like above ) PixelShader - a delta depth of the virtual sphere has to be added the sprite center depth - because we want to manipulate the depth manually we have to declare this in the pixelshader e.g. in the definition of the output pixelshader struc ( see SV_Depth system value) comment: according to my study there comes a performance hit because vertecies that normally could be discarded earlier now "overlive" longer and are processed in the pixelshader struct PixelShaderOutput_sprite { float4 Color : SV_Target0; float4 Normal : SV_Target1; float4 Depth : SV_Target2; float system_depth : SV_Depth; }; - the depth has now to be calculated two times a. depth calculation for the gbuffer rendertarget in my case this is done in viewspace as linear depth b. system pixel depth value, that acually is used for the depth comparison if this pixel is drawn or not a). Out.Depth = input.Depth + delta_depth_view / FarClip;; b). Out.system_depth = a_surface_Position_proj.z / a_surface_Position_proj.w; The b). line was missing in my shader code, I hope i have explained right. Maby others will correct it, no problem
    24. In the attached picture an intersection block is shown. My goal is to have the player switch lanes and (within the red bounding box) turn direction on a different road while always keeping a forward movement. Therefor the only input is left and right. The changing of the lanes has to happen quick and snappy (dependant on the player's overall speed) as visualized by the black squigly line. However I'm not sure how to implement this. I tried moving left and right with coroutines but got stuck at going back to the lane one came from mid-changing. I added those nodes at the ends with the intention to lerp/move towards depending on the lane and road the player changes to but that won't work with the aforementioned quick snappy movement. Another thought that passed was creating a bit of a node graph and dynamically make a spline when switching lanes but this seems a bit overkill for what it really is (?). Finally I figured creating an object that the player controls but doesn't see that the actual player objects follows that's slightly infront of the object but haven't gotten to that yet due to too much doubts of implementation. The player should not be constrained. If they whish to change back to a lane halfways through changing lanes that should be possible. Would like to hear some suggestions no mather how out there they might seem. Thanks!
    25. I also wanted to add: what is happening in the video before (when there were white dots inside the triangles) I explain as a mistake of "Float Point Error" when interpolating in the Rasterizer.
    26. GVA1994

      Game audio production milestones

      Thanks for the reply. I wasn't entirely clear with my question. I'd like to know what major deadlines are there in audio production? What major deadlines do pre-production, production and post-production have, and what tasks belong to each of these major deadlines? Thank you.
    27. Your method works fine. And I even checked it now. Everything is normal, but there is a problem that you compare not with the actual coordinates of the pixel, but with some abstract value, which is not quite correct. It looks like a bit of a crutch, but most likely I would have done the same in the end if I had not found another solution. I wanted to first find the settings for disabling this interpolation and thought that it could not be that they are not there. It is good that I did not give up on this and finally decided to ask on the forum. Even, before the question here, I discovered earlier that, for example, DirectX 12 (HLSL 5.1) has more features when accessing the settings of the Rasterizer. Thus, the version of the API also depends, and not what Irusan, son of Arusan (my thanks to him again!) wrote, that there is no difference. I also checked that changing the settings of the Rasterizer: rasterDesc.FrontCounterClockwise = true; rasterDesc.CullMode = D3D11_CULL_BACK; // or rasterDesc.FrontCounterClockwise = false; rasterDesc.CullMode = D3D11_CULL_FRONT; does not change the order in which it interpolates the values. Thank.
    28. Heroku is a free hosting. Let's deploy the application from this instruction: Emit and Broadcast JSON You need to register on https://heroku.com/ and complete this official instruction: Getting Started on Heroku with Node.js Go here: https://dashboard.heroku.com/apps and create a new application. For this you need to press "New" button in right top corner. Select "create new app". I created a new application with the name: red-game. In this case, my application will be available from this domain: https://red-game.herokuapp.com/ When you create your application at first time you will see this web page: Go to your work folder using the console terminal. You need to have the file "app.js" and "client" folder in your work folder. Indeside "client" folder you need to have "index.html" from the instruction above. But we will change a few lines in "app.js". We will change a port number. Replace this line of code: var port = 8080; On this line: var port = process.env.PORT || 3000; Note. If you do not want to read the previous instruction you can just copy-past this files and install packages using this commands: app.js var express = require("express"); var app = express(); var server = require("http").Server(app); app.get("/", function(req, res) { res.sendFile(__dirname + "/client/index.html"); }); app.use("/client", express.static(__dirname + "/client")); var port = process.env.PORT || 3000; server.listen(port); console.log("Server started. Port = " + port); var io = require("socket.io")(server, {}); var shortid = require('shortid'); io.sockets.on("connection", function(socket) { var clientName = shortid.generate(); console.log("client was connected, name = " + clientName); socket.on("getMyName", function() { socket.emit("onGetMyName", { name: clientName }); }); socket.on("sendMyNameToAllClients", function() { socket.broadcast.emit("onSendMyNameToAllClients", { name: clientName }); console.log(clientName); }); }); index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.2.0/socket.io.js"></script> <title>Multiplayer Snake</title> </head> <body> <button onclick="getMyName();">Get My Name</button> <button onclick="sendMyNameToAllClients();">Send my Name to all Clients</button> <script> var socket = io(); socket.emit("hello", { message: "hello from client!" }); socket.on("onGetMyName", function(data) { console.log("My Name: " + data.name); }); socket.on("onSendMyNameToAllClients", function(data) { console.log("Name of another client: " + data.name); }); function getMyName() { socket.emit("getMyName"); } function sendMyNameToAllClients() { socket.emit("sendMyNameToAllClients"); } </script> </body> </html> Add a new file: .gitignore (pay attention, "." is a part of the name) The file ".gitignore" should have this content: Add the start script command in package.json here: "scripts": { "start": "app.js", "test": "echo \"Error: no test specified\" && exit 1" }, Enter these commands in the command terminal. Pay attention: you need to write your application name instead of "red-game": Now we can to add new files, commit them and push/deploy our application on Heroku. Enter these commands: Go to your application in the browser. For example, in my case: https://red-game.herokuapp.com/ Open the browser console, for example in Chrome: "Ctrl+Shift+J". Click on buttons and you will see messages in the browser console. Open two tabs and press "Send my Name to all Clients" button. You will see a messages in the console in the second client tab. P.S. You need to empty cache when you change your client side scripts of files: RMB on "Reload" button and select "Empty Cache and Hard Reload"
    29. Zemlaynin

      DevBlog #34

      Thanks In fact, this scale in the game will not. With this removal of the camera, the map will switch to strategic 2D mode. Therefore, there is no sense in Imposters.
    30. Uttam Kushwah

      undefined behavior of bullet objects.

      Thanks lawnjelly, I have gone through the post you mentioned. But I am not sure that this is the problem with my simulation because that particular sphere also fails the raytest. As I know raytest don't need time stamp to calculate the collision between the object and ray cause bullet and other physics engine checks collision when all the object are static at any instant. And also the size too is big. Although i will try to make it clear by reducing the velocity of the balls and then check it again and let you know
    31. duke_meister

      That's it

      Still some rough edges and lots more that could be done, but it's essentially finished. You can restart a game, see the score and the snake can get much longer (a trivial change). This hasn't really been a blog, but somewhere to drop this code. Maybe I'll make another one that goes through it step by step (because although console is obviously not for gaming, a lot of the basics can be learned from a project like this). Another idea would be to make a blog about turning this exact code into a graphics (e.g. GDI) version with a minimum of changes... That would be geared more towards beginner C# programmers. If anyone's interested using System; using System.Linq; using System.Threading.Tasks; namespace ConsoleSnake { /// <summary> /// All code written by duke_meister (Valentino Rossi) /// except keyboard reading technique /// </summary> class Program { // our unchanging values: // playfield height & width const int PlayfieldWidth = 80; const int PlayfieldHeight = 40; // game pieces const string EmptyCell = " "; const string SnakeHeadCell = "@"; const string SnakeBodyCell = "o"; const string FoodCell = "."; // timeout to adjust speed of snake static int MillisecondsTimeout = 50; // our playfield; stores FieldVals instead of ints so we don't have to remember them static readonly FieldVals[,] PlayField = new FieldVals[PlayfieldWidth, PlayfieldHeight]; static int _snakeBodyLen; // not including head // which direction (SnakdDirs enum) the snake is currently moving static SnakeDirs _snakeDir; // position of the one-and-only piece of food; use our own coordinate class, Pos static readonly Pos FoodPos = new Pos(0, 0); static readonly Pos EraserPos = new Pos(0, 0); // defines the snake; each element tells us which coordinates each snake piece is at static int _maxSnakeLen = 30; static Pos[] _snakeCells = new Pos[_maxSnakeLen]; // guess static int _score = 0; // for randomizing things like food placement static Random _rnd; // how many body pieces the snake will increase by when it eats food static int SnakeSizeIncrease = 2; // could've used something existing, but made a simple screen coordinate class public class Pos { public int X { get; set; } public int Y { get; set; } public Pos(int x, int y) { X = x; Y = y; } } // these make it easy (for the human) to know what each cell contains enum FieldVals { DontDraw, Empty, SnakeHead, SnakeBody, SnakeFood } // these make it easy (for the human) to read snake the direction enum SnakeDirs { Up, Right, Down, Left } static void Main(string[] args) { _rnd = new Random(); RunGame(); } private static void RunGame() { Console.Clear(); _score = 0; for (var i = 0; i < PlayfieldWidth; i++) { for (var j = 0; j < PlayfieldHeight; j++) { PlayField[i, j] = FieldVals.DontDraw; } } // create the initial snake cell coords (place it on playfield) SetUpSnake(); // start with an initial piece of food MakeNewFood(); // draw the border, once DrawBorder(); // game loop; this was the easiest but might switch to Timer, etc. // function names should explain purpose for (;/* ever */; ) { CheckForKeyboardCommand(); AdjustGameSpeed(); UpdatePlayfield(); CheckForSnakeOutOfBounds(); CheckForSnakeCollisionWithSelf(); UpdateSnakeBodyPosition(); CheckSnakeHasEatenFood(); } } private static void CheckForSnakeCollisionWithSelf() { if( _snakeCells.Skip(1).Any(pos => pos.X == _snakeCells.First().X && pos.Y == _snakeCells.First().Y)) { EndGame(false); } } /// <summary> /// Work out the initial coordinates of the snake's body parts /// </summary> private static void SetUpSnake() { _snakeBodyLen = 4; // create the empty snake array cells for (var i = 0; i < _snakeCells.Length; i++) { _snakeCells[i] = new Pos(0, 0); } // randomly choose snake's initial direction _snakeDir = (SnakeDirs)_rnd.Next((int)SnakeDirs.Up, (int)SnakeDirs.Left + 1); int[] xOffsets = { 0, _snakeBodyLen * -1, 0, _snakeBodyLen}; int[] yOffsets = { _snakeBodyLen, 0, _snakeBodyLen * -1, 0}; int xOffset = xOffsets[(int) _snakeDir]; int yOffset = yOffsets[(int) _snakeDir]; // First randomly choose the position of the snake's head // We'll work out the rest of the snake body coords based on which // direction it's initially facing. _snakeCells.First().X = _rnd.Next( xOffset * _snakeBodyLen * -1, PlayfieldWidth + xOffset * _snakeBodyLen + 1); _snakeCells.First().Y = _rnd.Next( yOffset * _snakeBodyLen * -1, PlayfieldHeight + yOffset * _snakeBodyLen + 1); switch (_snakeDir) { case SnakeDirs.Up: // make the snake's body go below the head, as it's moving up for (int i = 1; i < _snakeBodyLen; i++) { _snakeCells[i].X = _snakeCells.First().X; _snakeCells[i].Y = _snakeCells[i - 1].Y + 1; } break; case SnakeDirs.Right: // make the snake's body go left of the head, as it's moving right for (int i = 1; i < _snakeBodyLen; i++) { _snakeCells[i].X = _snakeCells.First().X - 1; _snakeCells[i].Y = _snakeCells.First().Y; } break; case SnakeDirs.Down: // make the snake's body go above of the head, as it's moving down for (int i = 1; i < _snakeBodyLen; i++) { _snakeCells[i].X = _snakeCells.First().X; _snakeCells[i].Y = _snakeCells[i - 1].Y - 1; } break; case SnakeDirs.Left: // make the snake's body go right of the head, as it's moving left for (int i = 1; i < _snakeBodyLen; i++) { _snakeCells[i].X = _snakeCells.First().X + 1; _snakeCells[i].Y = _snakeCells.First().Y; } break; } } private static void AdjustGameSpeed() { // delay so the game isn't too fast. Halve the delay (to go faster) when going left or right // as it appears that going up/down is faster Task.Delay( _snakeDir == SnakeDirs.Up || _snakeDir == SnakeDirs.Right ? MillisecondsTimeout / 2 : MillisecondsTimeout).Wait(); } /// <summary> /// Check the keyboard for arrow keys /// I got the code off the net (see bottom of code); no point re-creating this /// </summary> private static void CheckForKeyboardCommand() { if (NativeKeyboard.IsKeyDown(KeyCode.Down)) // player hit Down arrow { // can't hit down while going up; game over if (_snakeDir == SnakeDirs.Up) EndGame(false); // change snake direction to down _snakeDir = SnakeDirs.Down; } else if (NativeKeyboard.IsKeyDown(KeyCode.Up)) { // can't hit up while going down; game over if (_snakeDir == SnakeDirs.Down) EndGame(false); // change snake direction to up _snakeDir = SnakeDirs.Up; } else if (NativeKeyboard.IsKeyDown(KeyCode.Left)) { // can't hit left while going right; game over if (_snakeDir == SnakeDirs.Right) EndGame(false); // change snake direction to left _snakeDir = SnakeDirs.Left; } else if (NativeKeyboard.IsKeyDown(KeyCode.Right)) { // can't hit right while going left; game over if (_snakeDir == SnakeDirs.Left) EndGame(false); // change snake direction to right _snakeDir = SnakeDirs.Right; } } /// <summary> /// See if snake has eaten the food /// </summary> private static void CheckSnakeHasEatenFood() { // if snake head is in the same x,y position as the food // NB: First() is a Linq function; it gives me the first element in the array if (_snakeCells.First().X == FoodPos.X && _snakeCells.First().Y == FoodPos.Y) { IncrementScore(); MakeNewFood(); IncreaseSnakeSize(); } } private static void IncreaseSnakeSize() { if (_snakeBodyLen + SnakeSizeIncrease <= _maxSnakeLen) { _snakeBodyLen += SnakeSizeIncrease; UpdateScore(); } } private static void UpdateScore() { WriteAt($"Score: {_score} Snake Size: {_snakeBodyLen}", 0, 0); } private static void IncrementScore() { ++_score; UpdateScore(); } /// <summary> /// Put food item at random location /// </summary> private static void MakeNewFood() { int x, y; do { // this ensures we're not putting the food on top of the snake, or the border x = _rnd.Next(1, PlayfieldWidth - 1); y = _rnd.Next(1, PlayfieldHeight - 1); } while (_snakeCells.Any(pos => pos.X == x || pos.Y == y)); // set the food coords FoodPos.X = x; FoodPos.Y = y; // update the playfield position with the food value PlayField[FoodPos.X, FoodPos.Y] = FieldVals.SnakeFood; } static void CheckForSnakeOutOfBounds() { // snake mustn't be on any border cell, or game over if (_snakeCells.First().Y < 1 || _snakeCells.First().X > PlayfieldWidth - 2 || _snakeCells.First().Y > PlayfieldHeight - 2 || _snakeCells.First().X < 1) { EndGame(false); } } /// <summary> /// Move the snake pieces appropriately. I just did the simplest thing that I thought of. /// </summary> static void UpdateSnakeBodyPosition() { // remember the position of the snake's last piece so that later, // after drawing the snake, we can set it to the 'don't draw' value EraserPos.X = _snakeCells[_snakeBodyLen].X; EraserPos.Y = _snakeCells[_snakeBodyLen].Y; // Last piece of snake's tail will always become empty as the snake moves // NB: Last() is a Linq function; it gives me the last element in the array (end of snake tail) PlayField[_snakeCells[_snakeBodyLen].X, _snakeCells[_snakeBodyLen].Y] = FieldVals.Empty; // move the 'middle' section of the snake one cell along for (int i = _snakeCells.Length - 1; i > 0; i--) { _snakeCells[i].X = _snakeCells[i - 1].X; _snakeCells[i].Y = _snakeCells[i - 1].Y; } // move the snake's head, depending on direction moving // the body was already moved above switch (_snakeDir) { case SnakeDirs.Up: // moved the snake head up 1 (-ve Y direction) --_snakeCells.First().Y; break; case SnakeDirs.Right: // moved the snake head right 1 (+ve X direction) ++_snakeCells.First().X; break; case SnakeDirs.Down: // moved the snake head up 1 (+ve Y direction) ++_snakeCells.First().Y; break; case SnakeDirs.Left: // moved the snake head left 1 (-ve X direction) --_snakeCells.First().X; break; } // Set the playfield position at the head of the snake, to be... the snake head! PlayField[_snakeCells.First().X, _snakeCells.First().Y] = FieldVals.SnakeHead; // Set the positions on the playfield for the snake body cells // so we know to draw them // NB: Skip(1).Take(4) is Linq; it gives me the array left after // skipping the first item, then grabbing the next 4 (so in this // case misses the first and last). foreach (var cell in _snakeCells.Skip(1).Take(4)) { PlayField[cell.X, cell.Y] = FieldVals.SnakeBody; } } /// <summary> /// Just show a message and exit (can only lose right now) /// </summary> /// <param name="win"></param> static void EndGame(bool win) { Console.Clear(); Console.WriteLine($"YOU DIED. Score: {_score} Snake Length: {_snakeBodyLen}"); Console.ReadKey(); Console.WriteLine("P to play again, Q to quit."); var consoleKeyInfo = Console.ReadKey(); if (consoleKeyInfo.Key == ConsoleKey.Q) { Environment.Exit(0); } RunGame(); } /// <summary> /// Set the console size appropriately & draw the border, leaving room for the score /// </summary> static void DrawBorder() { Console.SetWindowSize(PlayfieldWidth, PlayfieldHeight + 2); WriteAt("╔", 0, 1); WriteAt("╗", PlayfieldWidth - 1, 1); WriteAt("╚", 0, PlayfieldHeight); WriteAt("╝", PlayfieldWidth - 1, PlayfieldHeight); for (var i = 1; i < PlayfieldWidth - 1; i++) { WriteAt("═", i, 1); WriteAt("═", i, PlayfieldHeight); } for (var i = 2; i < PlayfieldHeight; i++) { WriteAt("║", 0, i); WriteAt("║", PlayfieldWidth - 1, i); } } /// <summary> /// Go through every element of the 2d array, only drawing a cell /// if it has a value (other than 0). This way we only draw the /// cells that need to be updated. A bit like Invalidate() in GDO. /// Pretty self-explanatory; if a cell has a value, draw the character /// appropriate for it. The space is only used to overwrite the last /// piece of the snake's tail. /// </summary> static void UpdatePlayfield() { for (var i = 1; i < PlayfieldWidth - 1; i++) { for (var j = 1; j < PlayfieldHeight - 1; j++) { switch (PlayField[i, j]) { case FieldVals.Empty: WriteAt( EmptyCell, i, j + 1); break; case FieldVals.SnakeHead: WriteAt(SnakeHeadCell, i, j + 1); break; case FieldVals.SnakeBody: WriteAt(SnakeBodyCell, i, j + 1); break; case FieldVals.SnakeFood: WriteAt(FoodCell, i, j + 1); PlayField[FoodPos.X, FoodPos.Y] = FieldVals.DontDraw; break; } } } PlayField[EraserPos.X, EraserPos.Y] = FieldVals.DontDraw; } // From Microsoft sample protected static void WriteAt(string s, int x, int y) { try { Console.SetCursorPosition(x, y); Console.Write(s); } catch (ArgumentOutOfRangeException e) { Console.Clear(); Console.WriteLine(e.Message); } } } /// <summary> /// Codes representing keyboard keys. /// </summary> /// <remarks> /// Key code documentation: /// http://msdn.microsoft.com/en-us/library/dd375731%28v=VS.85%29.aspx /// </remarks> internal enum KeyCode { Left = 0x25, Up, Right, Down } /// <summary> /// Provides keyboard access. /// </summary> internal static class NativeKeyboard { /// <summary> /// A positional bit flag indicating the part of a key state denoting /// key pressed. /// </summary> const int KeyPressed = 0x8000; /// <summary> /// Returns a value indicating if a given key is pressed. /// </summary> /// <param name="key">The key to check.</param> /// <returns> /// <c>true</c> if the key is pressed, otherwise <c>false</c>. /// </returns> public static bool IsKeyDown(KeyCode key) { return (GetKeyState((int)key) & KeyPressed) != 0; } /// <summary> /// Gets the key state of a key. /// </summary> /// <param name="key">Virtual-key code for key.</param> /// <returns>The state of the key.</returns> [System.Runtime.InteropServices.DllImport("user32.dll")] static extern short GetKeyState(int key); } }
    32. This my example how to use GUI WinForms and OpenTK.GLControl Source for Visual Studio (including DLLs): EditedTriangle_WinFormsOpenGL31CSharp.zip EXE: EditedTrianlge_WinFormsOpenGL31CSharp_EXE.zip Separated DLL's for references: OpenTK.zip, OpenTK.GLControl.zip Standard WinForms Color Dialog:
    33. Esteban5XG

      Some reviews for your game!

      Hi there! We are looking for people to play our game prototype Project BlockchainZ. Right now, we are available on itch.io for free and we really appreciate if you could give it a try! So, this is the link: https://projectblockchainz.itch.io/projectbcz Feel free to play the game and so to participate in our Discord Server. We are reaching a group of people to discuss about the game in order to create together an amazing video game! Thanks in advance
    34. Rutin

      My Footsteps Sound Effects !

      Very nice work. I see your music is being used to promote different industries which is really cool. I wasn't able to use any of your packs for my challenge game on GameDev.net here, as I didn't have enough time to finish... My commercial game will be needing assets at some point either way and I'll note down that you do music as well as I might need a composer if I don't do it in house.
    35. TeaTreeTim

      Point light

      mvVertexPosition = vec3(modelViewMatrix * vec4(positions, 1.0)); . . . vec4 lightResult = calculateLight(pointLight, material, mvVertexPosition, mvVertexNormal); You are applying the view matrix to the position of the vertices, so as the view matrix changes, the light will change... I think.
    36. Someone did for C# something similar that was inspired by Unreal Engine name Netprints I think someone with some time would be able to port this into Unity and write some kind of C# code generator for it
    37. Shaarigan

      A Low requeriments Engine?

      I had running a Unity installation on my old XP System for a long time. ATI 2600 HD Graphics, AMD APU, 2 GB RAM so everything is possible if you are willing to deal with huge load times
    38. lawnjelly

      undefined behavior of bullet objects.

      The problem is probably 'bullet tunneling'. Or in this case, if you are using bullet physics, you could call it 'bullet bullet tunneling'. :) https://www.aorensoftware.com/blog/2011/06/01/when-bullets-move-too-fast/
    39. This is probably the hardest of all the entries I've played! I was able to find the Ban Hammer!!! I found it a bit difficult because it was so easy to get knocked off, and sometimes you would jump on a platform but still die, ect... After playing for over 2 hours 😮 I just did my "speed run approach" instead of attacking, gathering, and marking my spots. I grabbed the yellow crystal for vision, nothing else... Then jumped like a mad man through the whole level searching out everything. I found all the glasses locations so I equipped it and dumped the yellow crystal as I had full vision now. Then I found the ban hammer and returned back home. Took under 5 minutes with a clean run once I knew where to go. Great job!
    40. drwuro

      Pygame - alternatives?

      Well the thing is, even if I use the "clock" functionality and try to make my code run at a stable 60 FPS, it sometimes has 59 FPS or 62 FPS or something like that. Apparently it's not possible to use VSync at all, neither on Linux nor on Windows. The code of the game itself is fast enough (without limitation it runs at 180 FPS or something like that), so that's not the reason here. Now the problem is, when there is a sprite moving smoothly from one side of the screen to the other (imagine a simple arcade-like game, nothing 3D or so), you will sometimes see it jitter around instead of floating smoothly one pixel at a time. And as far as I've read so far, there is no way to fix this when using Pygame, it simply has to be accepted.
    41. Webellion

      Five Nations

      Five Nations is a real-time sci-fi strategy game for PC platforms, Switch, and mobile. Encompassing tactical combat in space in real-time mixed with micromanagement of economy, construction, and production, it will play both in single player and multiplayer modes. The RTS mechanics being custom-made to deliver action-packed gameplay. Gameplay You are a commander of one of the five greatest galactic empires in the far future Develop your space facilities, mining stations, factories, power plants, and research centers. Produce a gigantic armada of spacecraft to confront and destroy your rivals by applying shrewd strategies to outmaneuver their fleets. All this in real-time, by micromanaging your spaceships and structures through conventional RTS mechanics tailored to modern action-packed gameplay. Story In the near future, countries of the Earth are clustered in an international organization to create co-operation between states and prevent future wars. Aligning mankind under a common flag helped the economic and technological progress that paved the way for space conquest. During the colonization of the solar system, a group of pioneers discovered a wormhole that led to an unknown corner of the galaxy. Although the first attempt to enter the wormhole was deemed a complete success, the second expedition never returned... Join our Discord server and get Super Early Access https://discord.gg/uSSzUKs Social Media Facebook fan page: https://www.facebook.com/fivenationsthegame Instagram: https://instagram.com/fivenationsthegame GameJolt: https://gamejolt.com/games/fivenations/389358 Itch.io: https://webellionlimited.itch.io/five-nations Twitter: https://twitter.com/webellion
    42. Zemlaynin

      DevBlog #34

      Hello dears! It's been more than a month since the last diary. Frankly, it was a hard month for me in terms of development. Most of the time was devoted to the construction of the structure of society, the interaction of the population, the transition from one stratum to another. It took a lot of time to build economic ties. At one point, I decided to throw some scheme of our project, which allowed a little systematize all my thoughts and see the degree of implementation of certain tasks. Who is interested to assess the scale, you can see the resulting scheme: https://mm.tt/1209438933?t=mBE5c38pFT In between work on the gameplay part of the thing with the mountains, and returned them again to the ice caps: Alexey made new optimized palm trees-270-350 triangles on one subtile Great result with such a landfill! I also managed to experiment with the user interface and made this sketch: And more or less brought him to mind: I prefer this interface concept. Before the interface was very heavy and it looked as if looking into the tube. But now clearly lacks any curls Then I experimented with transparent objects, we had an idea to implement such fields initially: But, in the end, we decided to focus on such an option: In a long box I had the task of building walls around our settlements. Alexey made models, already as half a year ago, but his hands did not reach them. I had to dust them off.: The problem was not trivial, it was necessary to carry out a lot of calculations to determine the need for a wall with an entrance, here is an example of such a case: And here is masterpiece deciduous trees on 800 triangles on subtil: Then I broke everything.: There came a ten-day period of optimization and rethinking of everything that was done on the render. And all this is due to the fact that I came up with one idea, how else to optimize our render. Unfortunately, I was not able to implement all my ideas, so to speak, theoretical calculations went against the practical results. But the result was still impressive. The first thing I want to mention — we now have 16 subtiles on the tile, and was 9. Before mesh subflow was 3x3, 4x4 now. 484 tops against 1089 now. The number of vertices per tile has increased 2.25 times, and the performance has remained at the same level and the map generation is now faster, as the most time-consuming process of normals calculation is now faster. This happened due to the fact that I removed from the calculations all the numbers with a period after the decimal point, such as 1\3 and 2\3. Now all calculations on both CPU side so GPU are faster. This is especially noticeable on large and huge worlds: The increase in the number of vertices and subflow allowed to implement more realistic mountains: Now our render takes out 32 million polygons!!! True to my GTX660 IS only 10FPS Alteration of the whole world on the structure of 4x4 sub-tails resulted in alteration of generation of mountains, hills, rivers, scaling of all models. Which together took those 10 days. - Also, the following points have been implemented about which I would like to briefly tell: - Normalmaps for the whole of terrane. - An error with the calculation of normalmap. - Corrected an interface error on the containers voznikayuschaya when the MouseEntered MouseExited events. - Go to / from full screen mode by pressing F11. A lot of time I took one bug: 5 hours I killed on his the search Thank you for your attention!
    43. Zemlaynin

      The Great Tribes

      Game project, a global strategy simulator of civilization development - The Great Tribes
    44. Tomtheseadog

      OpenGL Point light

      Hey guys, I'm having a little trouble with my point light. My light is working but the light source moves when I move my camera. I've been trying all week to fix it but at my wits end. Maybe I haven't converted it to the proper space. **VERTEX SHADER** in vec3 positions; in vec2 texCoords; in vec3 normals; out vec2 pass_texCoords; out vec3 mvVertexNormal; out vec3 mvVertexPosition; uniform mat4 projectionMatrix; uniform mat4 modelViewMatrix; uniform mat4 normalMatrix; void main() { pass_texCoords = texCoords; vec4 mvPos = modelViewMatrix * vec4(positions, 1.0); mvVertexNormal = mat3(normalMatrix) * normals; mvVertexPosition = vec3(modelViewMatrix * vec4(positions, 1.0)); gl_Position = projectionMatrix * mvPos; } **FRAGMENT SHADER** in vec2 pass_texCoords; in vec3 mvVertexPosition; in vec3 mvVertexNormal; out vec4 out_colour; struct Material { int hasNormalMap; int hasTexture; vec3 diffuse; vec3 ambient; vec3 specular; float reflectivity; }; struct PointLight { vec3 position; vec3 colour; float intensity; }; uniform sampler2D our_texture; uniform Material material; uniform vec3 ambientLight; uniform float specularPower; uniform PointLight pointLight; uniform vec3 viewer_position; vec4 calculateLight(PointLight light, Material material, vec3 position, vec3 normal) { // AMBIENT vec3 ambient = ambientLight * light.colour; // DIFFUSE vec3 norm = normalize(normal); vec3 lightDir = normalize(light.position - position); float diff = max(dot(norm, lightDir), 0.0); vec3 diffuse = diff * light.colour; // SPECULAR vec3 viewDir = normalize(viewer_position - position); vec3 reflectDir = reflect(-lightDir, norm); float spec = pow(max(dot(viewDir, reflectDir), 0.0), 32); vec3 specular = specularPower * spec * light.colour; vec3 result = (ambient + diffuse + specular); return vec4(result, 1.0); } void main() { vec4 lightResult = calculateLight(pointLight, material, mvVertexPosition, mvVertexNormal); out_colour = texture(our_texture, pass_texCoords) * lightResult; } The light source is coming from the cube in the red circle. Even the first picture the light isnt directly under the cube. If I don't move my camera and have the cube light source move around automatically the the light will stay with it. It's only if I move the camera that I get problems. The second picture i've moved my camera to the left and the light is moving with me and moving away from the cube light source.
    45. I'm adding shadow volume support into my engine (graphics backend written in OpenGL 4.5). Depth Pass was working fine and to deal with shadows when the camera placed inside a shadow volume - I've decided to use Carmack's Reverse (Depth Fail). I'm getting weird errors and I wanted to make sure I'm working with a good model (I'm using the Stanford Bunny / Dragon) before I continue to debug my algorithm. Depth Pass (working fine): Depth Fail (artifacts): I then positioned the camera inside the bunny and realized that the artifacts are actually triangles that aren't being culled (they facing the camera and the light source so they shouldn't be culled): Note: The bunny in this picture is the 2nd bunny behind the one in the previous picture - the camera is inside the first bunny in the picture above! I added a simple geom shader to paint front faces in green and back faces in blue. As you can see, This "patch" looks weird as some of the triangles facing the camera and some facing away from it - which might explain the artifact... Maybe the model is incorrect? I'm adding here the gltf I'm using (Bunny.gltf). Bunny.gltf I'm using silhouette extrusion to calculate the shadow volumes. I calculate the silhouette by using adjacency triangle toplogy (I'm calculating it once when loading the model) - and find edges that go around the light facing triangles (I'm using face normals for this calculation - I found it to yield better results then interpolated model normals). Would love to hear your thoughts about this method. Thank you for your help!
    46. Rutin

      Psy - Dungeon Challenge

      Wow really good take on this concept. I was able to get it on my 2nd try as I didn't know how to use potions (H).
    47. This is gonna be a heavy programming post. TL;DR: I made a Unity debug tool that can call functions from MonoBehaviours directly! On the edge of starting a new project, I stopped myself and thought about testing debug behaviors. I thought, "Gee, I sure don't like hooking up a bunch of random debug keys to update loops that I'll delete anyway. Wouldn't it be nice to have a debug system that you can type in a gameObject, component, and function name with arguments and just call it?" Sounds simple... right? :)))))))))))) Well obviously not really. The first step was to see what unity already had in terms of N E A R E F F O R T L E S S F U N C T I O N C A L L I N G . They have a couple options. There's the MonoBehaviour Invoke. You just find a MonoBehaviour, and pass in a string what function you want. It takes in NO arguments, so it's not 100% ideal. monoBehaviour.Invoke("Foo", 0); // This calls "Foo()" with a 0 second delay The next best thing is BroadcastMessage. We actually get an argument to pass in, but only one... and there's a second caveat -- If the gameObject has two of the same MonoBehaviour, or the same MonoBehaviour in its children, it will call this on ALL of them. Not ideal for testing! monoBehaviour.BroadcastMessage("Foo", 1); // Gettin' there... This calls Foo(int i) and passes in one argument... BUT ONLY ONE So, what else is there? Well, there is the System.Reflection namespace! Reflection is a program's ability to observe itself at runtime. It's what Unity and Unreal Engine do to allow your classes' fields to be shown in the editor. We can use the API in this namespace to get information about our own classes, and call methods from them! Here's what we need: using System.Reflection; // Gives us the "Info" classes MethodInfo method = monoBehaviour.GetType().GetMethod("Foo"); // Gets a "MethodInfo" from this mb's type with the name "Foo" ParameterInfo[] ParameterInfos = method.GetParameters(); // Returns an array of "ParameterInfo"s -- this includes their types. object[] parameters = new object[ParameterInfos.Length]; // We don't know *what* we'll be passing in yet, but we do know how many things we'll want. // If we have parameters to pass in, we call this: method.Invoke(monoBehaviour, parameters); // It doesn't like being passed in an empty object array if there's no parameters, so in this case we use the standard invoke instead. monoBehaviour.Invoke(method.Name, 0); To implement this, I got a list of the Scene's MonoBehaviours, and for each one that had the GameObject's name, I searched for a matching component. Parameterizing was tricky -- for now I just stuck with intrinsic types. Passing in classes is going to be a whole other rabbit hole. Using this, I was able to create a debug tool that can call functions off of MonoBehaviours! Despite its current limitations to intrinsic types, I am very happy with it so far. The Caller in action: Calling from GameObject1: Testing again: Calling from GameObject2 with parameters: Next Steps: Overloading Functions This is a tricky one... You would have to get all of the methods with the name you are querying, and then be able to check if the string arguments you passed in can be cast to any of the possibilities... Its a much longer one. Class Types Not sure how to start with this one... Perhaps it could be easy to pass in a newly constructed object in the case of things like Vector3... but what about Transforms? They don't have a name and are attached to gameObjects. I would have to, ideally, parse the gameObject's name and its component... determining which component exactly that is ... that doesn't sound fun. Parented Objects My system currently looks for the first GameObject that contains the given MonoBehaviour, meaning child objects that share similar names are not distinct from each other. A solution would be to have the user type something like "ParentObject.ChildObject", recognize that there is a child to search for, and continue that way. Private Functions Soooo I know being able to access anything private kind of defeats the point of it being private ... but what if I could? Is it even possible? I don't know, I need to look more into it. What I do know is that this is a debugging tool that uses reflection so I would not feel so bad if it touches something private (probably not so nice words, however.)
    48. Rutin

      Dawn - Dungeon Challenge

      Great job! I really enjoyed this entry. Brought me back to the good ole' days!
    49. duke_meister

      c# console snake game

      Paint gets called all the time. And you randomize the placement. That's why you get many all over the place. Also use e.Graphics
    50. CrazyCdn

      c# console snake game

      Because you're randomly drawing it all over the screen... Well technically in the ranges of 330 - 340 + 0 - 770 and 280 + 0 - 550. What were you expecting random to do? Don't call the randomize function Form1_Paint() each frame and you won't get a new food items each frame.
    51. hplus0603

      Some questions about UDP in C++

      A few things, small and big: 1) You should initialize listenAddress to 0 before filling out fields; either by using memset(), or by declaring it as sockaddr_in listenAddress = {}; 2) Because you don't do anything on a timer, you might do better not turning on non-blocking mode; as it is, your server will be burning a full CPU doing nothing but polling the socket. 3) NULL is not the "error socket value" in either Unix or Windows. Use the constant INVALID_SOCKET which I think aliases to 0xffffffff (which, when read as a signed 32-bit int, equals -1 which is the Unix error value.) 4) You need to assign sizeof(sockaddr_in) to listenAddressSize before the call to recvfrom(), each time. You have no idea what that value will become after the first call to the function. Similarly, you should use listenAddressSize, not sizeof(sockaddr_in), when sending the response, although this only really matters once you build a dual-stack IP4/IP6 implementation. 5) sendtoAddress also needs to be initialized to 0 before filling out fields. 6) inet_pton() is a simple wrapper on sscanf(), it doesn't "resolve" anything. The error messages are thus misleading. 7) you practically never bind() the client socket. You're probably better off removing the call to bind() in the client code.The socket will be assigned a random-ish, unused port number the first time it sends a datagram, automatically, and that port will be in the address the server sees to return the packet to. 😎 recvAddressSize should have the value sizeof(sockaddr_in) each time you call recvfrom(). 9) You should check errors for sendto() for both clients and servers. 10) What does Ethereal say when you capture UDP packets on port 8000 on the client and server when it doesn't work?
  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!