Piedra, papel y tijera con objetos de JavaScript

En este artículo, vamos a hacer el famoso juego de piedra papel y tijera de JavaScript. Este ejercicio es ideal para practicar los objetos que ya vimos anteriormente en el artículo: ¿Qué es un objeto en JS?.

Sin más preámbulo comenzamos.

Vamos a hacer el juego, para ello usaremos:

  • Chrome para mostrar los resultados por consola
  • JavaScript vanilla

Creando el objeto

Para ello, creamos un directorio y lo abrimos con VSC en el que añadimos:

  • main.js: será el fichero de javascript sobre el que trabajaremos.
  • index.html: en el que asociamos el script de JavaScript.

A partir de este punto, vamos a trabajar únicamente sobre nuestro JavaScript. Vamos a comenzar creando un objeto llamado game:

Añadiendo la personalización del nombre y la validación Reggex

El código será:

Vamos a añadir una funcionalidad que nos permita cambiar el nombre del jugador1. Esto lo haremos con window.prompt  y una validación con reggex ya que no vamos a permitir que nos introduzca un parámetro no valido.

Todo ello, separado por funciones unas con return y otras sin. El uso o no del return dependerá del uso que le vayamos a dar a cada función y de nuestra manera de programar. En mi caso, personalmente utilizaré un return dentro de una función principalmente cuando la utilice esos datos como parámetro en otra funcion.

window.prompt(“Mensaje”); nos permitirá añadir la ventana que nos capturará el posible nuevo nombre del player1

La validación la realizaremos con Reggex y será: ^[a-zA-Z]+

Esta validación, no dejará que se introduzca un nombre que con menos de 2 letras y que no sean letras de la A a la Z (tanto en mayúsculas como minúsculas).

Para verificar si la validación se realiza correctamente en reggex la introducimos dentro de un bloque if. Para que JavaScript entienda que nos encontramos ante una validación de reggex englobamos la validación de dos contra barras (/) una inicial y otra final (/). El resultante sería /^[a-zA-Z]+/

Finalmente utilizamos el método test() de tal manera que nos quedará /^[a-zA-Z]+/.test()

Dentro de los paréntesis del método test añadimos el nombre que almacenamos dentro del window.prompt para verificar y el resultado nos devolverá true or false.

Si ponemos un nombre correcto, podemos ver que el nombre del player1 cambia correctamente.

Os aconsejo darle zoom al navegador (con control++ o bien con control + la rueda del ratón) ya que, con ello, veremos la consola más grande y apreciaremos mejor los iconos, etc. Vamos a ver el resultado:

En cambio, si ponemos un nombre no valido, podemos ver que:

El resultado de una partida al completo será:

Si os fijáis, podemos ver que tenemos un puño arriba cuando existe un empate ambos, o cuando es un ganado el player ganador. Tenemos arrow functions, etc.

Mostrando el resultado en un documento HTML

Para ello utilizamos document.write donde utilizábamos console.log.

Una manera de realizar esto bastante rápido es seleccionar un console.log:

E ir a:

Con esto cambiaremos todos los elementos de una forma mucho más rápida por document.write:

Si volvemos a cargar la web vemos que nos sale todo apelotonado:

Esto se produce debido a que hemos cambiado el console.log por un document.write y este necesita un <BR> para hacer un salto de línea al final de cada instrucción. También debemos de cambiar el “\t” por múltiples espacios mediante a &nbsp;

Aunque nos acaban de pegar una paliza, vemos que con las últimas modificaciones ahora sí que se nos carga correctamente en el HTML:

Espero que os haya gustado. Un saludo y hasta la próxima

79 comentarios

  1. It’s impressive that you are getting ideas from this piece of
    writing as well as from our discussion made here.

  2. Hi there! Do you use Twitter? I’d like to follow you if that would be
    ok. I’m definitely enjoying your blog and look
    forward to new posts.

  3. These are in fact impressive ideas in regarding blogging.
    You have touched some pleasant factors here. Any way keep up wrinting.

  4. You’ve made some decent points there. I checked on the net for
    additional information about the issue and found most people will go along with your views on this web site.

  5. І every time used toߋ read piecе of
    writing in news pspers but now as I am a user of wеb therefore from now I am using net for cⲟntent, thanks
    to web.

    Feel free to surf to my page; funny t shirt designs

  6. What’s Going down i’m new to this, I stumbled upon this I’ve found
    It absolutely helpful and it has aided me out loads.

    I am hoping to contribute & assist other users like its helped me.
    Great job.

  7. I think the admin of this web site is in fact working hard in support of his site,
    because here every stuff is quality based information.

  8. With havin so much content and articles do you ever run into any
    problems of plagorism or copyright violation? My website has a lot of exclusive content I’ve either created myself or outsourced but it looks like a lot of it is popping it
    up all over the web without my authorization. Do you know any methods to
    help stop content from being stolen? I’d really appreciate it.

  9. Hi, I do believe this is a great blog. I stumbledupon it 😉 I will revisit yet again since I bookmarked it.
    Money and freedom is the greatest way to change, may you be rich and continue to guide others.

  10. This design is spectacular! You certainly know how to keep
    a reader entertained. Between your wit and your videos, I was almost moved to start
    my own blog (well, almost…HaHa!) Great job. I really loved what you had to say, and more than that, how
    you presented it. Too cool!

  11. Very good website you have here but I was wanting
    to know if you knew of any user discussion forums that cover the same topics talked about here?
    I’d really love to be a part of online community where I can get feed-back from other knowledgeable people that share the same interest.
    If you have any suggestions, please let me know.
    Thanks a lot!

  12. I know this web site offers quality depending posts and additional information, is
    there any other site which gives these kinds of information in quality?

  13. I was pretty pleased to discover this website. I wanted to thank you for your time
    due to this fantastic read!! I definitely enjoyed every little
    bit of it and I have you saved as a favorite to check out new things on your site.

  14. Hello there, I found your site via Google while looking for a similar matter, your web site got here up, it
    seems to be good. I’ve bookmarked it in my google bookmarks.

    Hello there, just become aware of your blog via Google,
    and found that it’s truly informative. I’m gonna watch out for brussels.
    I will appreciate when you continue this in future.
    Numerous people will probably be benefited out of
    your writing. Cheers!

  15. It’s enormous that you are getting ideas from this paragraph as well as from our discussion made at this place.

  16. Hello colleagues, fastidious piece of writing and pleasant urging commented here, I am
    actually enjoying by these.

  17. I loved as much as you will receive carried out right here.

    The sketch is tasteful, your authored subject matter stylish.
    nonetheless, you command get bought an shakiness over that you wish be delivering the following.
    unwell unquestionably come more formerly again since exactly the same
    nearly very often inside case you shield this hike.

  18. What’s up mates, fastidious post and fastidious arguments commented at this place, I am in fact enjoying
    by these.

  19. I am sure this piece of writing has touched all the internet users, its really really
    fastidious article on building up new website.

  20. This site certainly has all the information and facts I needed concerning this subject and didn’t know who to ask.

    Here is my web page Bioneo Farms Pure CBD

  21. Good post. I learn something totally new and challenging on blogs I stumbleupon on a daily basis.
    It’s always useful to read through content from other writers and practice a little something from their websites.

    Here is my web page Semzia Brain Ingredients

  22. Hey! Someone in my Myspace group shared this website with us so I came to take a
    look. I’m definitely loving the information. I’m book-marking and will be tweeting this
    to my followers! Terrific blog and amazing design.

    Also visit my site; Clinical Keto Pills

  23. Hi, I want to subscribe for this web site to obtain most up-to-date updates, therefore where can i do it
    please help.

    Look into my homepage … Cosmic Green CBD Review

  24. Thank you a lot for sharing this with all folks you actually realize what you’re speaking approximately!
    Bookmarked. Kindly additionally consult with my web site =).
    We may have a link exchange contract between us

    Feel free to visit my web page Alive CBD Oil (thaipurchase.com)

  25. Only wanna comment on few general things, The
    website style and design is perfect, the content is really
    superb :D.

    Here is my homepage – A1 Keto BHB Reviews

  26. Good article. I will be dealing with some of these issues as

    Have a look at my page Ketokor Side Effects (http://www.fles.hlc.edu.tw)

  27. Yay google is my queen helped me to find this outstanding web

    My web blog CBD XLT Review

  28. You really make it seem so easy with your presentation but I
    find this matter to be really something which I think I would never understand.
    It seems too complex and very broad for me. I’m looking forward for your next post, I’ll try to get
    the hang of it!

    Check out my blog: Semzia Keto

  29. Unquestionably believe that which you stated. Your favorite justification seemed
    to be on the internet the simplest thing to be aware of.
    I say to you, I certainly get irked while people think about
    worries that they just do not know about. You managed
    to hit the nail upon the top as well as defined out the whole thing without having side-effects ,
    people can take a signal. Will probably be back to get more.

    My blog post – Clean Cut Keto Pills

  30. You are my breathing in, I have few blogs and sometimes run out from post :).

    my web site – Primal Testo XL Pills

  31. thank you for this tremendous post, I am glad
    I found this web site on yahoo.

    Also visit my blog :: Extreme Keto Slim Reviews

  32. Hello i am kavin, its my first occasion to commenting anyplace, when i read this article i thought i could also create comment due to this good paragraph.

    My webpage: Cool Wave AC Review

  33. I do trust all of the ideas you have presented on your post.
    They are very convincing and can definitely work. Nonetheless, the posts are too short for starters.

    May you please extend them a bit from subsequent time?
    Thank you for the post.

    Also visit my homepage :: Hedofirm 360 Male Enhancement Review

  34. Pretty nice post. I simply stumbled upon your weblog and wanted to mention that I’ve really enjoyed surfing around your weblog posts.
    In any case I’ll be subscribing in your rss feed and I hope you write again soon!

    my homepage countrysidetravels.com

  35. Hi there! This post could not be written much better!
    Reading through this post reminds me of my previous roommate!
    He continually kept talking about this. I will send this
    article to him. Fairly certain he will have a great read.

    I appreciate you for sharing!

    Here is my site: Keto Lean Body Pills

  36. I am delighted that I discovered this site, exactly the right info that
    I was looking for!

    my web page; Evergold Farms CBD Reviews

  37. I have to express my passion for your kindness in support of women who really need help with the area of interest.
    Your personal commitment to getting the message along had been really insightful and have continually helped individuals just like me to get to their objectives.
    Your insightful recommendations means so much a person like me and far more to my fellow
    workers. Thanks a ton; from all of us.

    My blog post – Cool Wave Portable AC

  38. I am so happy to read this. This is the type of manual that needs to be given and not
    the accidental misinformation that is at the other blogs.

    Appreciate your sharing this greatest doc.

    Also visit my blog Cut Slim Keto Pills

  39. I believe other website owners should take this web site as an example, very clean and good user friendly layout.

    Feel free to visit my web-site; Rapid Fire Keto

  40. It’s actually a great and helpful piece of information. I’m glad that you shared this useful information with us.

    Please keep us informed like this. Thanks for sharing.

    My homepage: Level CBD Gummies

  41. You have brought up a very excellent points, thank you for the

    Look into my blog post … Wellness Xcel Keto Review

  42. Hello there! Do you know if they make any plugins to assist
    with SEO? I’m trying to get my blog to rank for
    some targeted keywords but I’m not seeing very good gains.
    If you know of any please share. Thanks!

    Take a look at my blog post :: Ignite CBD Oil

  43. Respect to op, some excellent selective information.

    my website – Rapid Fire Keto Review

  44. Aw, this was an incredibly good post. Finding the time and actual effort to generate a
    great article? but what can I say? I put things off a lot and
    don’t manage to get nearly anything done.

    Here is my web site :: Ketokor Side Effects

  45. Asking questions are actually good thing if you are
    not understanding something entirely, but this article provides
    good understanding even.

    Also visit my web blog; jpgsoft.co.kr

  46. I know this if off topic but I’m looking into starting my own blog and
    was wondering what all is needed to get set up? I’m assuming having a blog like yours would cost a pretty
    penny? I’m not very web savvy so I’m not 100% sure. Any suggestions
    or advice would be greatly appreciated. Many thanks

  47. My partner and i still cannot quite believe I could often be
    one of those reading the important tips found on your web blog.
    My family and I are truly thankful for the generosity and for
    presenting me the chance to pursue the chosen profession path.
    Many thanks for the important information I obtained from
    your web page.

    My webpage: Level CBD Gummies

  48. Hey there, You’ve performed a fantastic job.
    I’ll certainly digg it and personally suggest to my friends.
    I’m confident they’ll be benefited from this web site.

    my web site TestonoX Review

  49. Rattling nice design and wonderful subject material,
    hardly anything else we want :D.

    Also visit my web site

  50. Rattling fantastic visual appeal on this internet site, I’d value it 10.

    Here is my webpage: Keto Speed Diet Pills

  51. Joycasino порно регулярно предлагает частично вернуть потраченные деньги.
    Cashback активируют преимущественно опытные посетители.
    Cashback можно получать раз
    в месяц. Размер доступного кешбэка прописывается в
    личном кабинете.

  52. If you desire to increase your knowledge just keep visiting this site and be updated with the most up-to-date information posted here.

  53. Every weekend i used to pay a visit this site, for the reason that
    i want enjoyment, for the reason that this this site conations genuinely
    fastidious funny data too.

    Here is my homepage … Maxatin

  54. I don’t ordinarily comment but I gotta state
    regards for the post on this special one :D.

    My web blog :: Maxatin Male Enhancement

  55. Really nice style and superb articles, very little else we require :D.

    Feel free to surf to my blog post … CBD XLT Review

  56. Hiya! I know this is kinda off topic however I’d figured
    I’d ask. Would you be interested in trading links or maybe
    guest writing a blog post or vice-versa? My site goes over a lot of the same subjects as yours and
    I believe we could greatly benefit from each other. If you happen to
    be interested feel free to shoot me an e-mail.
    I look forward to hearing from you! Superb blog by the way!

    Review my webpage: http://clubriders.men/

  57. magnificent publish, very informative. I ponder why the opposite specialists of this sector do not understand this.
    You should proceed your writing. I am confident, you have
    a huge readers’ base already!

    Review my page … retrogamingrhino.com

  58. Hi there! Do you know if they make any plugins to help with Search Engine Optimization? I’m trying
    to get my blog to rank for some targeted keywords but I’m not seeing very
    good gains. If you know of any please share. Appreciate it!

    my web site; Gro Max Male Enhancement

  59. You got a very excellent website, Gladiolus I detected it through yahoo.

    Here is my homepage CoolCube AC

  60. I would like to thank you for the efforts you’ve put
    in writing this site. I’m hoping the same high-grade blog post from
    you in the upcoming as well. In fact your creative writing abilities has encouraged me to get my own blog
    now. Actually the blogging is spreading its wings quickly.
    Your write up is a great example of it.

    Feel free to visit my web-site Keto Total BHB Ingredients

  61. Of course, what a magnificent site and educative posts, I will bookmark your blog.Best Regards!

    Here is my web blog – Sound Joy Earbuds

  62. I am extremely impressed together with your writing abilities and
    also with the structure on your blog. Is that this a paid subject matter or
    did you modify it your self? Either way keep up the nice quality writing, it’s uncommon to peer
    a nice weblog like this one nowadays.

    Here is my web site Lumere Skin Serum Reviews

  63. I was curious if you ever considered changing the page layout of your blog?
    Its very well written; I love what youve got to say. But maybe you could a little more in the way
    of content so people could connect with it better. Youve got an awful lot of text for only having one or 2 pictures.
    Maybe you could space it out better?

    my web site :: MaxBHB Reviews

  64. Oh my goodness! Impressive article dude! Thank you, However
    I am having problems with your RSS. I don’t know the reason why I can’t subscribe to it.
    Is there anyone else getting the same RSS problems?
    Anyone who knows the solution will you kindly respond?

    Also visit my site; Viritenz New Formula

  65. Appreciate the recommendation. Let me try it out.

  66. Thank you for your whole work on this web page. My mother takes
    pleasure in working on investigation and it is easy to understand why.
    My spouse and i hear all about the powerful manner you
    present sensible tips and hints on your blog and even strongly encourage participation from some other
    people on that content then our favorite simple princess is now understanding so much.
    Have fun with the rest of the year. You’re carrying out a glorious
    job.[X-N-E-W-L-I-N-S-P-I-N-X]I’m extremely inspired together with your writing skills as smartly as with the
    structure for your blog. Is this a paid theme
    or did you customize it yourself? Anyway keep up the
    nice quality writing, it’s rare to look a nice blog like this one nowadays.

    Stop by my blog … Primal Testo XL Reviews

  67. Hello to all, since I am actually keen of reading this web site’s post to be
    updated on a regular basis. It contains fastidious data.

    cheap flights http://1704milesapart.tumblr.com/ cheap flights

  68. Good post. I am experiencing many of these issues as well..

  69. Howdy fantastic website! Does running a blog similar to this take a massive amount work?
    I’ve virtually no understanding of computer programming
    but I was hoping to start my own blog soon. Anyway, if
    you have any suggestions or techniques for new blog owners
    please share. I know this is off subject but I simply needed to ask.

  70. hello!,I really like your writing very so much! share we communicate
    more approximately your post on AOL? I need an expert
    on this space to solve my problem. Maybe that is you! Looking
    forward to see you.

  71. Excellent article. Keep writing such kind of info on your site.

    Im really impressed by your blog.
    Hey there, You’ve performed a fantastic job. I will certainly digg it and in my view recommend to my friends.
    I am confident they’ll be benefited from this web site.
    ps4 games https://j.mp/3nkdKIi ps4 games

  72. Now I am ready to do my breakfast, after having my breakfast coming again to read other

  73. Excellent article. Keep posting such kind of information on your blog.
    Im really impressed by it.
    Hello there, You’ve performed a great job. I will definitely
    digg it and personally suggest to my friends. I’m sure they’ll be benefited from this website.

  74. Hi, yup this piece of writing is truly nice and I have learned lot
    of things from it regarding blogging. thanks.

  75. I’d been honored to obtain a call coming from a friend when he observed the important ideas shared on your site.
    Looking at your blog write-up is a real brilliant experience.
    Thanks again for taking into consideration readers like me,
    and I hope for you the best of achievements like a professional in this arena.

    Here is my blog :: http://www.j-scripting.com

  76. Its wonderful as your other blog posts :D, thank you for posting.

    Here is my web blog Mega XL Male Enhancement Reviews

  77. This is really interesting, You are a very skilled
    blogger. I’ve joined your rss feed and look forward
    to seeking more of your excellent post. Also, I have shared your
    web site in my social networks!

    Also visit my web page – hemp benefits

  78. Definitely, what a great site and illuminating posts, I surely will bookmark your site.Best Regards!

    Here is my page … healthy eating diet plan

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

La Ley 34/2002 nos obliga a avisarte de que usamos cookies propias y de terceros con objetivos estadísticos y de sesión y para mostrarte la 'publi' que nos da de comer. Tranquilo, este mensaje solo sale una vez. Más información

Java desde 0 comunica a los usuarios, a través de este aviso, que puede utilizar cookies cuando el usuario navega por las diferentes pantallas y páginas del sitio. Durante el uso de nuestra página Web usted acepta y autoriza expresamente el uso de cookies, de acuerdo con nuestra Política de Privacidad. Este sitio web utiliza las siguientes cookies propias: - Cookies de sesión, para garantizar que los usuarios que escriban comentarios en el blog sean humanos y no aplicaciones automatizadas. De esta forma se combate el spam. Este sitio web utiliza las siguientes cookies de terceros: - Google AdManager y AdSense: Utiliza cookies para mejorar la publicidad. Entre otros fines, suelen utilizarse para segmentarla según el contenido que sea relevante para los usuarios o su ubicación, mejorar los informes de rendimiento de las campañas y evitar mostrar anuncios que los usuarios ya hayan visto. Las cookies no contienen información personal identificable. Consulta cómo utiliza Google la información de sitios web o aplicaciones. y cómo bloquear determinados anuncios. - Google Analytics: Almacena cookies para poder elaborar estadísticas sobre el tráfico y volumen de visitas de esta web. Al utilizar este sitio web está consintiendo el tratamiento de información acerca de usted por Google. Por tanto, el ejercicio de cualquier derecho en este sentido deberá hacerlo comunicando directamente con Google. - Redes sociales: Cada red social utiliza sus propias cookies para que usted pueda pinchar en botones del tipo Me gusta o Compartir.