简体   繁体   中英

How to read data in a text file and dynamically update <div> on timed interval using JS

I am creating a web-game (text-based). One part of the game is an "arena". I have each player put in a character to fight. What I'm trying to do is get it so that when the fight starts, the payers (and anyone else) can dynamically see the results of the fight 1 action at a time.

I'm doing the fight via .php because I want to make sure that all the data is saved on the server side so that it reflects the same for everyone and I can load the final results in to a MySQLi Database . My problem is getting the information to reflect on the browser ( JS ) during each "heartbeat".

My theory is to have the .php do the entire fight at once and load the line by line in to a .txt file hidden on the server. When the fight starts, the information would be loaded from the .txt to the browser by updating the DOM . I can get the information loaded to the text and seperated:

"{Player 1} has punched {Player 2} in the face for x damage" | {p2HeadDamage=-5} <br>

I am trying to find a way to have JS split the 2 in to different variables - the first being for the display DOM and the second being for a "damage bar" which I'm working on separately.

My question - how would I pull 1 line at a time (separated by <br> ) and each variable separately?

I think you're better off using with an approach that maintains the structure of the data on the server and the client instead of dumping it into a txt file and having the client parse it out.

One way to do this would be to use a series of objects that define the interaction. For eg a "FightRecord" object that contains a list of "Action" objects which have two properties "Desc" and "Damage"... Then use JSON to serialize/deserialize the record, and the JS function setInterval to loop through the actions every X seconds with a function that uses JQuery to update the DOM.

If for some reason it isn't feasible to exchange objects using JSON, then you will want to use regex to parse the text data into structured data using a similar setInterval based mechanism.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM