1

#PlatziCodingChallenge - Escalando nuestro piedra papel o tijera

Escalando nuestro piedra papel o tijera
Agrega 2 jugadores a tu juego de piedra papel o tijera, cómo lo harías de la forma más eficiente?

Escribe tu comentario
+ 2
Ordenar por:
1
7689Puntos
letjuegos = 0
  function juego() {
    if (juegos === 0){
      alert('Bienvenido a Piedra papel o tijeras mejorado, este juego consiste de 2 jugadores')
    }
    letjugador1 = parseInt(prompt('Ingrese la opción del jugador 1  |0 -> piedra|1 -> papel|2-> tijera|'))
    letjugador2 = 0if (jugador1 === 0 || jugador1 === 1 || jugador1 === 2){
      jugador2 = parseInt(prompt('Ingrese la opción del jugador 2  |0 -> piedra|1 -> papel|2-> tijera|'))
      if (jugador2 === 0 || jugador2 === 1 || jugador2 === 2){
        if ((jugador1 === 0 && jugador2 === 2) || (jugador1 === 2 && jugador2 === 1) || (jugador1 === 1 && jugador2 === 0)) {
          alert('Gano el jugador 1')
          letdecision = parseInt(prompt('Deseas volver a jugar? |0 -> SI|1 -> NO|'))
          if (decision === 0){
            juegos++
            juego()
          }
        } elseif ((jugador1 === 0 && jugador2 === 1) || (jugador1 === 2 && jugador2 === 0) || (jugador1 === 1 && jugador2 === 2)) {
          alert('Gano el jugador 2')
          letdecision = parseInt(prompt('Deseas volver a jugar? |0 -> SI|1 -> NO|'))
          if (decision === 0){
            juegos++
            juego()
          }
        }
      } else {
        alert('Error en ingreso de datos...')
        juego()
      }
    } else {
      alert('Error en ingreso de datos...')
      juego()
    }
  }

  juego()
1
7689Puntos

Concuerdo con mis compañeros, no entiendo cual es el objetivo de este reto

1
28285Puntos

Este challenge necesita más documentación

1
28285Puntos

import getpass

scores = {‘pa-pi’,‘pi-ti’, ‘ti-pa’}

def who_won(player1, player2, player1_id, player2_id ):
if f’{player1}-{player2}‘in scores:
return player1_id
if f’{player2}-{player1}'in scores:
return player2_id
return “tie”

def to_int(val, msg):
try:
return int(val)
except:
print(msg)

def get_selection(player):
result = getpass.getpass(f"Player {player} select an option:\n"
“1. Stone\n”
“2. Paper\n”
"3. Scissors\n: ").strip()
if result == ‘1’:
return "pi"
if result == ‘2’:
return "pa"
if result == ‘3’:
return "ti"
return None

def to_value(code):
if code == ‘pi’:
return "Stone"
if code == ‘pa’:
return "Paper"
return “Scissors”

def game(multiplayer):
def_msg = “No players today. It’s OK!“
print(“Welcome to Stone - Paper - Scissors!”)
players = 2
if multiplayer:
print(””“This is a multiplayer game.”"")
players = to_int(input(“Number of Players? “), def_msg)
if players == 0:
print(def_msg)
return None
if players == 1:
print(“Player 1 won by default”)
return None
p1 = 1
p2 = 2
matches = players - 1
while True:
if matches == 0:
break
print(f"Player {p1} vs {p2}”)
p1_value = get_selection(p1)
if p1_value == None:
print(f"Player {p2} win”)
p1 = 2
p2 += 1 #next player
matches -= 1
continue
p2_value = get_selection(p2)
if p2_value == None:
print(f"Player {p1} win")
p2 += 1 #next player
matches -= 1
continue
match_winner = who_won(p1_value, p2_value, p1, p2)
if match_winner == ‘tie’:
print(f"{to_value(p1_value)} vs {to_value(p2_value)} we have a tie lets go to a rematch")
continue
p1 = match_winner
p2 += 1
matches -= 1
print(f"{to_value(p1_value)} vs {to_value(p2_value)} the winner is Player {p1}")

if name == “main”:
game(False)

1
28285Puntos
import getpass

scores = {'pa-pi','pi-ti', 'ti-pa'}

defwho_won(player1, player2, player1_id, player2_id ):if f'{player1}-{player2}'in scores:
        return player1_id
    if f'{player2}-{player1}'in scores:
        return player2_id
    return"tie"defto_int(val, msg):try:
        return int(val)
    except:
        print(msg)

defget_selection(player):    
    result = getpass.getpass(f"Player {player} select an option:\n" \
        "1. Stone\n" \
        "2. Paper\n" \
        "3. Scissors\n: ").strip()
    if result == '1':
        return"pi"if result == '2':
        return"pa"if result == '3':
        return"ti"returnNonedefto_value(code):if code == 'pi':
        return"Stone"if code == 'pa':
        return"Paper"return"Scissors"defgame(multiplayer):
    def_msg = "No players today. It's OK!"    
    print("Welcome to Stone - Paper - Scissors!")
    players = 2if multiplayer:
        print("""This is a multiplayer game.""")
        players = to_int(input("Number of Players? "), def_msg)
    if players == 0:
        print(def_msg)
        returnNoneif players == 1:
        print("Player 1 won by default")
        returnNone
    p1 = 1
    p2 = 2
    matches = players - 1whileTrue:
        if matches == 0:
            break
        print(f"Player {p1} vs {p2}")
        p1_value = get_selection(p1)
        if p1_value == None:
            print(f"Player {p2} win")
            p1 = 2
            p2 += 1#next player
            matches -= 1continue        
        p2_value = get_selection(p2)
        if p2_value == None:
            print(f"Player {p1} win")
            p2 += 1#next player
            matches -= 1continue        
        match_winner = who_won(p1_value, p2_value, p1, p2)
        if match_winner == 'tie':
            print(f"{to_value(p1_value)} vs {to_value(p2_value)} we have a tie lets go to a rematch")        
            continue
        p1 = match_winner
        p2 += 1
        matches -= 1
    print(f"{to_value(p1_value)} vs {to_value(p2_value)} the winner is Player {p1}")
        
if __name__ == "__main__":
    game(False)
1
19943Puntos

No entiendo el reto, al final se deben contar 4 jugadores o como?

1
28285Puntos

Le hice una mejora para soportar color

import getpass

scores = {'pa-pi','pi-ti', 'ti-pa'}

defwho_won(player1, player2, player1_id, player2_id ):if f'{player1}-{player2}'in scores:
        return player1_id
    if f'{player2}-{player1}'in scores:
        return player2_id
    return"tie"defto_int(val, msg):try:
        return int(val)
    except:
        print(msg)

defget_selection(player):    
    result = getpass.getpass(f"Player {player} select an option:\n" \
        "1. Stone\n" \
        "2. Paper\n" \
        "3. Scissors\n: ").strip()
    if result == '1':
        return"pi"if result == '2':
        return"pa"if result == '3':
        return"ti"returnNonedefto_value(code):if code == 'pi':
        return"Stone"if code == 'pa':
        return"Paper"return"Scissors"defgame(multiplayer):
    def_msg = "No players today. It's OK!"    
    print("Welcome to Stone - Paper - Scissors!")
    players = 2if multiplayer:
        print("""This is a multiplayer game.""")
        players = to_int(input("Number of Players? "), def_msg)
    if players == 0:
        print(def_msg)
        returnNoneif players == 1:
        print("\u001b[32mPlayer 1 won by default\u001b[0m")
        returnNone
    p1 = 1
    p2 = 2
    matches = players - 1whileTrue:
        if matches == 0:
            break
        print(f"Player {p1} vs {p2}")
        p1_value = get_selection(p1)
        if p1_value == None:
            print(f"\u001b[32mPlayer {p2} win\u001b[0m")
            p1 = 2
            p2 += 1#next player
            matches -= 1continue        
        p2_value = get_selection(p2)
        if p2_value == None:
            print(f"\u001b[32mPlayer {p1} win\u001b[0m")
            p2 += 1#next player
            matches -= 1continue        
        match_winner = who_won(p1_value, p2_value, p1, p2)
        if match_winner == 'tie':
            print(f"\u001b[33m{to_value(p1_value)} vs {to_value(p2_value)} we have a tie lets go to a rematch\u001b[0m")        
            continue
        p1 = match_winner
        p2 += 1
        matches -= 1
        print(f"\u001b[32m{to_value(p1_value)} vs {to_value(p2_value)} the winner is Player {p1}\u001b[0m")
        
if __name__ == "__main__":
    game(False)
Capture.PNG
1
19943Puntos

Reto 59 en JavaScript

// Escalando nuestro piedra papel o tijera en JavaScriptclassPPT{
  constructor(games) {
    this.player1 = { score: 0 }
    this.player2 = { score: 0 }
    for (let g = 0; g < games; g++) {
      this.newGame(g)
    }
    this.printResults()
  }
  newGame(g) {
    alert('Juego ' + (g + 1))
    this.player1.choice = prompt('Jugador 1: ¿Piedra, papel o tijeras?').toLowerCase()
    this.player2.choice = prompt('Jugador 2: ¿Piedra, papel o tijeras?').toLowerCase()
    const winner = this.getWinner(this.player1.choice, this.player2.choice)
    if (winner !== 0) {
      alert(`${this.player1.choice} vs ${this.player2.choice}: Gana Jugador ${winner}`)
      this[`player${winner}`].score++
    } else {
      alert(`${this.player1.choice} vs ${this.player2.choice}: No hay ganador`)
    }
  }
  getWinner(choice1, choice2) {
    switch (choice1) {
      case'piedra':
        switch (choice2) {
          case'piedra': return0case'papel': return2case'tijeras': return1default: return0
        }
      case'papel':
        switch (choice2) {
          case'piedra': return1case'papel': return0case'tijeras': return2default: return0
        }
      case'tijeras':
        switch (choice2) {
          case'piedra': return2case'papel': return1case'tijeras': return0default: return0
        }
      default: return0
    }
  }
  printResults() {
    let message = `Jugador 1: ${this.player1.score} puntos\nJugador 2: ${this.player2.score} puntos\n`if (this.player1.score > this.player2.score) {
      message += 'Gana Jugador 1'
    } elseif (this.player1.score < this.player2.score) {
      message += 'Gana Jugador 2'
    } else {
      message += 'Empate'
    }
    alert(message)
  }
}

try {
  const numJuegos = parseInt(prompt('¿Cuántas veces van a jugar?'))
  if (numJuegos > 0) {
    const Juego = new PPT(numJuegos)
  } else {
    alert('Debes introducir un número mayor que 0')
  }
} catch (error) {
  alert('Debes introducir un número mayor que 0')
}
1
import random

defmain():
    juegos=[]
    resp='si'
    cont1=0
    cont2=0while resp=='si':
        juego=[]
        jug1=input('Ingresa tu arma jugador 1: ')
        jug2=input('Ingresa tu arma jugador 2: ')
        juego.append(jug1)
        juego.append(jug2)
        juegos.append(juego)

        if jug1==jug2:
            passelif jug1=='pi'and jug2== 'pa':
            cont2=cont2+1elif jug1=='pi'and jug2== 'ti':
            cont1=cont1+1elif jug1=='pa'and jug2== 'ti':
            cont2=cont2+1elif jug1=='pa'and jug2== 'pi':
            cont1=cont1+1elif jug1=='ti'and jug2== 'pa':
            cont1=cont1+1elif jug1=='ti'and jug2== 'pi':
            cont2=cont2+1
        resp=input('Desea jugar otra partida:')

    if cont1<cont2:
        print('El ganador es el jugador 2')
    elif cont2<cont1:
        print('El ganador es el jugador 1')
    else:
        print('Hubo empate en ambos jugadores')
    print(juegos)
if __name__ == '__main__':
    menu='''Escoge tu arma:
            si escoges piedra escribe -> pi
            si escoges papel escribe -> pa
            si escoges tijera escribe -> ti'''
    print(menu)
    main()