62개의 풀이가 있습니다.
import random
while True:
user=input("가위바위보를 하세요:")
if user=='가위':
if random.choice(["가위","바위","보"])=="가위":
print("무승부")
elif random.choice(["가위","바위","보"])=="바위":
print("패")
else:
print("승")
if user=='바위':
if random.choice(["가위","바위","보"])=="가위":
print("승")
elif random.choice(["가위","바위","보"])=="바위":
print("무승부")
else:
print("패")
if user=='보':
if random.choice(["가위","바위","보"])=="가위":
print("패")
elif random.choice(["가위","바위","보"])=="바위":
print("승")
else:
print("무승부")
static void Main(string[] args)
{
string 나, 상대방;
int 계속=1;
while (계속 > 0)
{
Console.WriteLine("가위, 바위, 보를 입력하세요");
나 = Console.ReadLine();
Random r = new Random();
switch (r.Next(0, 3))
{
case 0:
상대방 = "가위";
switch (나)
{
case "가위":
Console.WriteLine("비김");
break;
case "바위":
Console.WriteLine("이김");
break;
case "보":
Console.WriteLine("짐");
break;
}
break;
case 1:
상대방 = "바위";
switch (나)
{
case "가위":
Console.WriteLine("짐");
break;
case "바위":
Console.WriteLine("비김");
break;
case "보":
Console.WriteLine("이김");
break;
}
break;
default:
상대방 = "보";
switch (나)
{
case "가위":
Console.WriteLine("이김");
break;
case "바위":
Console.WriteLine("짐");
break;
case "보":
Console.WriteLine("비김");
break;
}
break;
}
Console.WriteLine("상대방 입력결과:" + 상대방);
Console.Write("한판더? yes:1 , no:0 \r\n 입력:");
계속 = Convert.ToInt16(Console.ReadLine());
}
}
C#입니다.
자바 입니다 package RockScissorPaper;
public class RockSP {
public static void main(String[] args) {
RockSPCom rc = new RockSPCom();
RSPuse ru = new RSPuse();
System.out.print("가위바위보: ");
ru.user();
rc.com();
String a0 = ru.b;
String y0 = rc.y;
if(y0.equals(a0)) {
System.out.println("무승부");
}else if((y0.equals("바위")&a0.equals("보")) | (y0.equals("가위")&a0.equals("바위"))
| (y0.equals("보")&a0.equals("가위"))) {
System.out.println("승리");
}else {
System.out.println("패배");
}
}
}
package RockScissorPaper;
import java.util.*;
public class RockSPCom {
String y;
int x = (int) (Math.random()*3);
public String com() {
switch(x) {
case 0:
y="바위";
System.out.println("com: "+y);
break;
case 1:
y="가위";
System.out.println("com: "+y);
break;
default:
y="보";
System.out.println("com: "+y);
}
return y;
}
}
package RockScissorPaper;
import java.util.Scanner;
public class RSPuse {
String b;
public String user() {
Scanner scan = new Scanner(System.in);
String a = scan.nextLine();
switch(a) {
case "바위" :
b="바위";
break;
case "가위" :
b="가위";
break;
case "보" :
b="보";
break;
default:
System.out.println("다시 입력");
}
return b;
}
}
import java.util.Scanner;
enum Rsp { 가위, 바위, 보}
enum Winner { 사람, 컴퓨터}
public class Rockscissorpaper {
public static void main(String[] args) { //input computer judge print
Rockscissorpaper rsp = new Rockscissorpaper();
int human = rsp.humanInput();
int computer = rsp.computerCalc();
int winner = rsp.judgeWinner(human, computer);
rsp.printWinner(winner);
}
private int humanInput() {
Scanner input = new Scanner(System.in);
while(true) {
try {
System.out.println("컴퓨터와 가위바위보를 시작합니다.");
System.out.println("가위, 바위, 보 셋 중 하나를 입력하세요.");
String rspinput = input.nextLine();
Rsp rsp0 = Rsp.valueOf(rspinput);
int rsp = rsp0.ordinal();
return rsp;
}
catch (Exception e) {
System.out.print("입력이 잘못되었습니다.다시 ");
}
}
}
private int computerCalc() {
int rsp = (int)(Math.random()*3);
Rsp com[] = Rsp.values();
System.out.println(com[rsp].name());
return rsp;
}
private int judgeWinner(int human, int computer) {
int judge;
if (human == computer) {
judge = 2;
}
else if((human + 1 == computer)||(computer +2 == human)) {
judge = 1;
}
else {
judge = 0;
}
return judge;
}
private void printWinner(int winner) { //사람이 이겼다면 0을 받고 컴퓨터가 이겼다면 1을 받는다.그외의 숫자(2는 비김을 표시함)는 예외로 처리하여 비김을 출력한다.
Winner who[] = Winner.values();
try {
System.out.printf("승자는 %s 입니다",who[winner].name());
}
catch(Exception e) {
System.out.printf("비겼습니다");
}
}
}
decision_tbl = [
['scissors', 'rock', 'paper'],
['rock', 'even', 'paper'],
['scissors', 'paper', 'even'],
]
kind = ['scissors', 'rock', 'paper']
res = ''
while True:
comp_in = random.randint(0, 2)
print(comp_in, sel)
res = decision_tbl[comp_in][sel]
if 'even' != res:
break
user_in = input('input one of [scissors, rock, paper] >> ')
sel = 0 if user_in == 'scissors' else 1 if user_in == 'rock' else 2
print('{} vs {} --> '.format(kind[comp_in], kind[sel]), end ='')
print('usre {}'.format('win' if user_in == res else 'even' if res == 'even' else 'lose'))
import random
gbb_list = ['가위', '바위', '보']
while True:
gbb_in = input("가위(1)/바위(2)/보(3) 해당 번호를 선택하십시오.\n종료하려면 엔터키.:")
try:
input_num = int(gbb_in)
print('')
print('%s :' % gbb_list[input_num - 1], end = ' ')
pc_num = random.randint(-3, -1)
print('%s(PC)' % gbb_list[pc_num*(-1) - 1])
rslt = input_num + pc_num
if abs(rslt) > 1:
rslt *= (-1)
if rslt > 0:
print('이기셨습니다.\n')
elif rslt < 0:
print('지셨습니다.\n')
else:
print('비기셨네요, 다시 입력하세요.\n')
except:
break
import random
choice = ["가위","바위","보"]
while True:
winner = "사용자"
comp_num = random.randint(0,2)
comp_choice = choice[comp_num]
user_choice = input("골라주세요(가위, 바위, 보): ")
if user_choice not in choice:
print("다시 입력해주세요")
continue
user_num = choice.index(user_choice)
if comp_num == 0 and user_num == 2:
winner = "컴퓨터"
elif comp_num == 2 and user_num == 0:
pass
else:
if comp_num > user_num:
winner = "컴퓨터"
print("컴퓨터: %s, 사용자: %s" % (comp_choice, user_choice))
if comp_num == user_num:
print("비겼습니다.")
else:
print("%s가 이겼습니다." % winner)
파이썬으로 작성했습니다~
from random import randint
rock_scissor_paper = {0: '가위', 1: '바위', 2: '보', 3: '가위', 4: '바위'}
user = input("가위, 바위, 보 중 하나를 입력 :")
def check_win(user, computer):
if user < computer:
return 'Lose'
elif user > computer:
return "Win"
else:
return "Draw"
if user == '가위':
computer = randint(2, 4)
print(check_win(3, computer))
elif user == '바위':
computer = randint(0, 2)
print(check_win(1, computer))
else:
computer = randint(1, 3)
print(check_win(2, computer))
C#
194번 문제와 중복입니다. 해당 문제 풀이에 대해 문자열 입력부 수정과 주석을 추가하여 아래와 같이 첨부합니다.
using System;
namespace CD213
{
class Program
{
static void Main()
{
while (true)
{
Console.Write("'가위', '바위', '보' 또는 엔터(종료): ");
string input = Console.ReadLine().Trim();
if (input == "") { break; }
if (input == "가위" || input == "바위" || input == "보")
{
var userSelection = (RSP)Enum.Parse(typeof(RSP), input);
Game(userSelection);
}
else { continue; }
}
}
enum RSP { 가위, 바위, 보 } // [0, 1, 2]
static Random rnd = new Random();
static void Game(RSP userSelection)
{
int comSelection = rnd.Next(0, 3); // 컴퓨터 선택 [0, 1, 2]
// 승자 판단:
// 가위(0), 바위(1), 보(2) 순환 판단을 위해 3으로 나눈 나머지로 접급
// 예>
// - 사용자: 보(2) / 컴퓨터: 가위(0) 의 경우
// - 사용자[(보 + 1) % 3 = 0] == 컴퓨터[0] 조건에 의해 컴퓨터 승
string result = string.Empty;
if ((comSelection + 1) % 3 == (int)userSelection)
{
result = "유저 승";
}
else if (((int)userSelection + 1) % 3 == comSelection)
{
result = "컴퓨터 승";
}
else { result = "비김"; }
Console.WriteLine($"유저: {userSelection} vs 컴퓨터: {(RSP)comSelection} => {result}");
}
}
}
import random
rsp = input("가위바위보 게임을 시작합니다. \n가위, 바위, 보 중 하나를 고르세요. ")
com = random.randrange(1, 3) # 1은 가위, 2는 바위, 3은 보
if (rsp=='가위' and com == 3 ) or (rsp=='바위' and com ==1) or (rsp== '보' and com ==2) :
print("너님이 승리하셨습니다.")
elif (rsp=='가위' and com==1) or (rsp=='바위' and com==2) or (rsp=='보' and com==3) :
print("비겼습니다.")
else :
print("너님이 졋어요.")
while(true) {
let user = prompt('가위바위보')
let com
switch(Math.floor(Math.random() * 3) + 1) {
case 1:
com = '가위'
break
case 2:
com = '바위'
break
case 3:
com = '보'
break
}
if(user == com) alert('무승부')
else if ((user == '가위' && com == '바위') || (user=='바위' && com == '보') || (user == '보' && com == '가위')) alert('패')
else alert('승')
}
import java.util.*;
class Ready{
String[] Rps = {"","Rock","Paper","Scissors"};
int usernum = 0;
int comnum =0;
void Computer() { // 컴퓨터 랜덤값
comnum= (int)(Math.random()*3)+1;
System.out.println("Computer : "+Rps[comnum]);
}
void User() { // 유저 입력값
Scanner in =new Scanner(System.in);
do {
System.out.println("Rock.Paper.Scissors 입력 : ");
String userin = in.next();
System.out.println("User : "+userin);
switch (userin) { // 비교를 위해 user입력값 숫자로 입력
case "Rock":case "rock": usernum=1; break;
case "Paper":case "paper": usernum=2; break;
case "Scissors":case"scissors": usernum=3; break;
default : usernum=4;break;
}
}while(usernum == 4); // 잘못 입력한경우 다시 입력
}
void compare() { // 비교 승리 혹은 패배시 게임 종료
if(usernum==1 &&comnum==3||usernum==2 && comnum ==1 || usernum ==3 && comnum ==2 ) {
System.out.println("승리!!");
System.exit(0); //종료
}else if(usernum==comnum) {
System.out.println("비겼네!! 한번더");
}else {
System.out.println("패배!!");
System.exit(0);
}
}
}
public class RockPaperScissors {
public static void main(String[] args) {
Ready R = new Ready();
while(true) {
R.User();
R.Computer();
R.compare();
}
}
}
R로 작성하였습니다
rsp = function(user){
if(user %in% c("가위", "바위", "보") == FALSE){
return("error")
}
table = data.frame(c("무", "승", "패"),
c("패", "무", "승"),
c("승", "패", "무"), stringsAsFactors = F)
rownames(table) = colnames(table) = c("가위", "바위", "보")
computer = sample(c("가위", "바위", "보"), size = 1)
for(i in 1:nrow(table)){
for(j in 1:ncol(table)){
if(user == colnames(table)[i] && computer == rownames(table)[j]){
return(c(user, computer, table[i,j]))
}
}
}
}
Python
import random
x = ['Rock', 'Paper', 'Scissor']
computer_choice = random.choice(x)
userenter = input('Please enter Rock, Paper, or Scissor')
print(computer_choice, '\n')
if computer_choice == userenter:
print('Draw')
elif computer_choice != userenter:
if computer_choice == 'Rock' and userenter == 'Paper':
print('User wins')
elif computer_choice == 'Rock' and userenter == 'Scissor':
print('Computer wins')
elif computer_choice == 'Paper' and userenter == 'Scissor':
print('User wins')
elif computer_choice == 'Paper' and userenter == 'Rock':
print('Computer wins')
elif computer_choice == 'Scissor' and userenter == 'Rock':
print('User wins')
elif computer_choice == 'Scissor' and userenter == 'Paper':
print('Computer wins')
else:
print('What are you doing?')
import random
class RoPaSciss:
def __init__(self):
self.items=['가위','바위','보']
self.win = {'가위':'바위','바위':'보','보':'가위'}
self.choice_item={}
def game_start(self):
self.choice_item = self.choice()
self.victory()
def choice(self):
itemindex = random.randint(0,2)
comcho = self.items[itemindex]
usercho = input("가위,바위,보 중하나(문자)를 입력하세요:")
return {'user':usercho,'computer':comcho}
def victory(self):
print('유저는:',self.choice_item['user'])
print('컴퓨터는:',self.choice_item['computer'])
if self.choice_item['user'] == self.choice_item['computer']:
print('무승부 입니다.')
elif self.win[self.choice_item['user']] == self.choice_item['computer']:
print('Computer가 이겼습니다.')
else:
print('User가 이겼습니다.')
g = RoPaSciss()
g.game_start()
import random
while True:
comp=random.choice(["가위","바위","보"])
user=input("Input 가위, 바위 or 보: ")
if comp=="가위":
if user=="가위": print("비기셨습니다.")
elif user=="바위": print("승리하셨습니다.")
elif user=="보": print("패배하셨습니다.")
else: print("Invalid input.")
if comp=="바위":
if user=="가위": print("패배하셨습니다.")
elif user=="바위": print("비기셨습니다.")
elif user=="보": print("승리하셨습니다.")
else: print("Invalid input.")
if comp=="보":
if user=="가위": print("승리하셨습니다.")
elif user=="바위": print("패배하셨습니다.")
elif user=="보": print("비기셨습니다.")
else: print("Invalid input.")
if user in ["가위","바위","보"]:
print("컴퓨터: {0}".format(comp))
k=0
a=0
import random
while True:
a=int(input("1.rock 2.scissor 3.paper"))
k=random.randrange(1,4)
if a==1:
if k==1:
print("draw")
elif k==2:
print("win")
elif k==3:
print("lose")
elif a==2:
if k==1:
print("lose")
elif k==2:
print("draw")
elif k==3:
print("win")
elif a==3:
if k==1:
print("win")
elif k==2:
print("lose")
elif k==3:
print("draw")
else:
break
비쥬얼 스튜디오로 작성했습니다. 문자열로 입력을 받아서 처리하는건 도무지 방법이 안떠올라서 정수로 입력받아서 처리했습니다.```{.cpp}
using namespace std;
void main() {
int user, com, count = 0, win = 0, draw = 0, lose=0;
srand(time(NULL));
for (int i = 0; i < 100; i++) {
printf("가위(1), 바위(2), 보(3), 그만할래요(0) 입력하세요 : ");
scanf_s("%d", &user);
com = rand() % 3 + 1;
count++;
if (user == 1)
{
if (com == 2)
{
printf("졌습니다. ㅠㅠ\n");
lose++;
break;
}
else if (com == 3)
{
printf("이겼닭! \n");
win++;
}
else {
printf("비겼습니다.\n");
draw++;
}
}
else if (user == 2)
{
if (com == 3)
{
printf("졌습니다. ㅠㅠ\n");
lose++;
break;
}
else if (com == 1)
{
printf("이겼닭! \n");
win++;
}
else {
printf("비겼습니다.\n");
draw++;
}
}
else if (user == 3)
{
if (com == 1)
{
printf("졌습니다. ㅠㅠ\n");
lose++;
break;
}
else if (com == 2)
{
printf("이겼닭! \n");
win++;
}
else {
printf("비겼습니다.\n");
draw++;
}
}
if (user == 0) {
count--;
break;
}
}
printf("당신은 총 %d번 게임하였으며, %d승 %d무 %d패입니다.", count, win, draw, lose);
} ```
import random
Dkbb={'가위':'보','바위':'가위','보':'바위'} #딕셔너리
rkbb=['가위','바위','보']
Mkbb=input('가위,바위,보 입력 :')
while Mkbb == rkbb[0] or Mkbb == rkbb[1] or Mkbb == rkbb[2]:
Ckbb=random.choice(rkbb) #컴퓨터가 결정
print('나:',Mkbb,' PC:',Ckbb)
if Mkbb == Ckbb:
print('비겼습니다.')
else:
if Ckbb == Dkbb[Mkbb]:
print('우와 승리.')
else:
print('에구 졌다.')
print()
Mkbb=input('가위,바위,보 입력 :')
딕셔너리로 간단하게 처리
어렵네용!
import random
# 가위=0, 바위=1, 보=2
Choice = ['가위','바위','보']
list = {'가위':'무패승', '바위':'승무패', '보':'패승무'}
play = True
while play:
input_value = input("\n가위-바위-보 :")
A_Status = random.randrange(3)
if input_value not in list:
continue
print("\n입력 값 : %s\n컴퓨터 값 : %s\n승부결과 : 사용자 %s " % (input_value, Choice[A_Status] , list[input_value][A_Status]))
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand((unsigned)time(NULL));
while (1)
{
char me;
char you = rand() % 3;
printf(" r, s, p 중 하나를 입력하세요. 0을 누르면 종료.\n");
scanf(" %c" , &me);
if (me == '0')
break;
if (you == 0)
you = 'r';
else if (you == 1)
you = 's';
else
you = 'p';
if (me == you)
printf(" ----- 비겼습니다. -----\n");
else if (me == 'r')
printf(" ----- %s -----\n", you == 's' ? "이겼습니다." : "졌습니다.");
else if (me == 's')
printf(" ----- %s -----\n", you == 'p' ? "이겼습니다." : "졌습니다.");
else if (me == 'p')
printf(" ----- %s -----\n", you == 'r' ? "이겼습니다." : "졌습니다.");
else
printf(" 잘못된 입력입니다.\n");
printf(" 나 : %c\n 상대 : %c\n\n", me, you);
}
return 0;
}
# RockScissorsPaper.py
import random
# 1. 메세지 출력 클래스 정의
class MessagePrinter:
@staticmethod
def win():
print("승리하였습니다.")
@staticmethod
def lose():
print("패배하였습니다.")
@staticmethod
def draw():
print("비겼습니다.")
# 1. 상수 정의
CONST_ROCK = 0
CONST_SCISSORS = 1
CONST_PARER = 2
# 2. 사용자의 입력을 받고 컴퓨터의 랜덤값 생성
user_input = input("입력: ")
computer_input = random.randint(0, 2)
# 3. 값을 통해 결과 출력
if computer_input == CONST_ROCK:
print("컴퓨터: 바위")
if user_input == "바위":
MessagePrinter.draw()
if user_input == "가위":
MessagePrinter.lose()
if user_input == "보":
MessagePrinter.win()
elif computer_input == CONST_SCISSORS:
print("컴퓨터: 가위")
if user_input == "바위":
MessagePrinter.win()
if user_input == "가위":
MessagePrinter.draw()
if user_input == "보":
MessagePrinter.lose()
elif computer_input == CONST_PARER:
print("컴퓨터: 보")
if user_input == "바위":
MessagePrinter.lose()
if user_input == "가위":
MessagePrinter.win()
if user_input == "보":
MessagePrinter.draw()
import random
sample = {'01' : 'lose', '02' : 'win', '12' : 'lose', '10' : 'win', '20' : 'lose',
'21' : 'win', '00' : 'draw', '11' : 'draw', '22' : 'draw'}
hw = input()
if hw == '가위':
hw = '0'
elif hw == '바위':
hw = '1'
elif hw == '보':
hw = '2'
else:
raise Exception("가위바위보 하자며")
com = str(random.randint(0,2))
R_S_P = hw + com
print(sample.get(R_S_P))
# Python
import random
choice = {'가위': 0, '바위': 1, '보': 2}
while True:
try:
user = choice[input('가위~ 바위~ 보!: ')]
computer = random.randint(1, 3)-1
if user == computer:
print("무승부!")
elif user - computer == 1 or user - computer == -2:
print("승리!")
else:
print("패배!")
except:
print("가위, 바위, 보 중에 선택해줘~")
namespace codingdojang__
{
class Program
{
static void Main(string[] args)
{
List<string> list = new List<string> { "가위", "바위", "보" };
int input = list.BinarySearch(Console.ReadLine());
Random random = new Random();
int com = random.Next(3);
if (input - com == 1 || input - com == -2)
{
Console.WriteLine("이겼습니다.");
}
else if (input == com)
{
Console.WriteLine("비겼습니다.");
}
else
{
Console.WriteLine("졌습니다.");
}
}
}
}
꼼수?
namespace codingdojang__
{
class Program
{
static Random r = new Random();
static void Main(string[] args)
{
R_p_s("가위");
R_p_s("바위");
R_p_s("보");
}
static void R_p_s (string input)
{
int temp = r.Next(1, 4);
if(temp == 1)
{
Console.WriteLine("승");
}
else if(temp == 2)
{
Console.WriteLine("무승부");
}
else
{
Console.WriteLine("패");
}
}
}
}
julia
const table = Dict("가위"=>1,"바위"=>2,"보"=>3)
const table2 = ("가위","바위","보")
comDeck = mod1(rand(UInt),3)
myDeck = table[readline()]
vs = myDeck - comDeck%Int
print("<You>$(table2[myDeck]) : $(table2[comDeck])<Computer>\n",
vs in (1,-2) ? "You Win" : vs == 0 ? "Draw" : "You lose"
)
python 3.7
import random
while True:
user=input("가위바위보를 하세요:")
if user=='가위':
if random.choice(["가위","바위","보"])=="가위":
print("나:가위, 컴퓨터:가위 - 무승부")
elif random.choice(["가위","바위","보"])=="바위":
print("나:가위, 컴퓨터:바위 - 패")
else:
print("나:가위, 컴퓨터:보 - 승")
if user=='바위':
if random.choice(["가위","바위","보"])=="바위":
print("나:바위, 컴퓨터:바위 - 무승부")
elif random.choice(["가위","바위","보"])=="보":
print("나:바위, 컴퓨터:보 - 패")
else:
print("나:바위, 컴퓨터:가위 - 승")
if user=='보':
if random.choice(["가위","바위","보"])=="보":
print("나:보, 컴퓨터:보 - 무승부")
elif random.choice(["가위","바위","보"])=="바위":
print("나:보, 컴퓨터:바위 - 승")
else:
print("나:보, 컴퓨터:가위 - 패")
using System;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
Random random = new Random();
int cpu = random.Next(3);
//Console.WriteLine(cpu);
string a;
while (true)
{
a = Console.ReadLine();
if (a == "가위" || a == "바위" || a == "보")
break;
Console.WriteLine("가위, 바위, 보 중 하나를 입력하세요.");
}
switch(a)
{
case "가위":
switch(cpu)
{
case 0:
Console.Write("cpu : 가위, 비겼습니다.");
break;
case 1:
Console.Write("cpu : 바위, 졌습니다.");
break;
case 2:
Console.Write("cpu : 보, 이겼습니다.");
break;
}
break;
case "바위":
switch (cpu)
{
case 0:
Console.Write("cpu : 가위, 이겼습니다.");
break;
case 1:
Console.Write("cpu : 바위, 비겼습니다.");
break;
case 2:
Console.Write("cpu : 보, 졌습니다.");
break;
}
break;
case "보":
switch (cpu)
{
case 0:
Console.Write("cpu : 가위, 졌습니다.");
break;
case 1:
Console.Write("cpu : 바위, 이겼습니다.");
break;
case 2:
Console.Write("cpu : 보, 비겼습니다.");
break;
}
break;
}
}
}
}
def rsp(a):
import random
x = random.randrange(0, 3)
if a == "가위" or a == "바위" or a == "보":
if x == 0:
c = "가위"
elif x == 1:
c = "바위"
elif x == 2:
c = "보"
if c=="가위" and a=="바위" or c=="바위" and a=="보" or c=="보" and a=="가위":
print("당신 :{} 컴퓨터 : {} 당신이 이겼습니다".format(a,c))
elif c=="가위" and a=="보" or c=="바위" and a=="가위" or c=="보" and a=="바위":
print("당신 :{} 컴퓨터 : {} 컴퓨터가 이겼습니다".format(a,c))
else:
print("비겼습니다 다시 내주세요")
else:
print("다시입력해주세요")
def rock_sizer_paper(user):
from random import choice
lis = ['rock', 'sizer', 'paper']
com = choice(lis)
print('user:', user, '\ncom:', com)
if user == com: return rock_sizer_paper(input('>>>'))
else:
if lis.index(user) == lis.index(com)-1:
return 'win'
else:
return 'lose'
>>>rock
user: rock
com: paper
lose
import random
def kawi():
while True:
com = random.randint(1, 9)
if 1 <= com <= 3:
com = "rock"
elif 4 <= com <= 6:
com = "sissor"
else:
com = "paper"
user=input(">>>")
if user=="rock" and com is "rock":
print("Draw")
elif user =="rock" and com is "sissor":
print("Win")
break
elif user=="rock" and com is "paper":
print("lose")
if user == "sissor" and com is "sissor":
print("Draw")
elif user == "sissor" and com is "paper":
print("Win")
break
elif user == "sissor" and com is "rock":
print("lose")
if user=="paper" and com is "paper":
print("Draw")
elif user =="paper" and com is "rock":
print("Win")
break
elif user=="paper" and com is "sissor":
print("lose")
using System;
namespace rock_paper_scissors
{
class Program
{
static void Main(string[] args)
{
Random r = new Random();
int Computer = r.Next(0, 2);
string Player = null;
while (true)
{
Console.Write("Player : ");
Player = Console.ReadLine();
//Computer가 가위일때.
if (Computer == 0 && Player.Equals("가위"))
{
Console.WriteLine("무승부");
continue;
}
if (Computer == 0 && Player.Equals("바위"))
{
Console.WriteLine("Player Win");
break;
}
if (Computer == 0 && Player.Equals("보"))
{
Console.WriteLine("Computer Win");
continue;
}
//Computer가 바위 일때
if (Computer == 1 && Player.Equals("가위"))
{
Console.WriteLine("Computer Win.");
continue;
}
if (Computer == 1 && Player.Equals("바위"))
{
Console.WriteLine("무승부");
continue;
}
if (Computer == 1 && Player.Equals("보"))
{
Console.WriteLine("Player Win");
break;
}
//Computer가 보 일때
if (Computer == 2 && Player.Equals("가위"))
{
Console.WriteLine("Player Win.");
break;
}
if (Computer == 2 && Player.Equals("바위"))
{
Console.WriteLine("Computer Win");
continue;
}
if (Computer == 2 && Player.Equals("보"))
{
Console.WriteLine("무승부");
continue;
}
}
}
}
}
import random
inp, li = input("input : "), ['가위', '바위', '보', '가위']
com = random.randint(0, 2)
print("COM : ", li[com])
if inp == li[com] :
print("비김")
elif inp == li[com+1] :
print("승리")
else :
print("패배")
public class 가위바위보 {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
String me = scan.nextLine();
Random random = new Random();
int you_int = random.nextInt(3);
String you = null;
if(you_int==0) {
you = "가위";
}
else if(you_int==1) {
you = "바위";
}
else {
you = "보";
}
System.out.println(you);
if(me.equals("가위")&&you.equals("보")) {
System.out.println("승리하셨습니다");
}
else if(me.equals("바위")&&you.equals("가위")) {
System.out.println("승리하셨습니다");
}
else if(me.equals("보")&&you.equals("바위")) {
System.out.println("승리하셨습니다");
}
else if(me.equals(you)) {
System.out.println("비겼습니다");
}
else {
System.out.println("패배하셨습니다.");
}
}
}
import random
lst=["가위","바위","보"]
n=random.randint(0,2)
c=lst[n]
i=input("가위, 바위, 보 중 하나를 입력하십시오: ")
def rcp(i,c):
if i=="가위" and c=="보":
return "승리"
if i=="바위" and c=="가위":
return "승리"
if i=="보" and c=="바위":
return "승리"
elif i==c:
return "무승부"
else:
return "패배"
print("당신: "+str(i),"//","컴퓨터: "+str(c))
print("결과:",rcp(i,c))
import random
a=input('가위/바위/보 : ')
if a=='가위':
a=1
elif a=='바위':
a=2
elif a=='보':
a=3
b=random.randint(1,3)
if b==1:
b='가위'
if b==2:
b='바위'
if b==3:
b='보'
print('컴퓨터의 선택 : ',b)
if b=='가위':
b=1
if b=='바위':
b=2
if b=='보':
b=3
if a+1==b or a-2==b:
print('패배')
elif a-1==b or a+2==b:
print('승리')
else:
print('비김')
user = input("무엇을 내시겠습니까? \n") rock = 0 scissor = 1 paper = 2 a = ['rock', 'scissor', 'paper'] computer = randint(0, 2) user_num = a.find(user) if user_num == 0 and computer == 1:
print("You win!")
elif user_num == 0 and computer == 2:
print("You lose!")
elif user_num == 1 and computer == 0:
print("You lose!")
elif user_num == 1 and computer == 2: print("You win!") elif user_num == 2 and computer == 0: winner = "AI" print("You lose!") elif user_num == 2 and computer == 1: winner = "AI" print("You lose!")
import random
b = input("가위바위보 중에 하나를 내세요\n:")
c = ["가위","바위","보"]
a = random.choice(c)
if a == b:
print("무승부")
elif a == c[0] and b == c[1] or a == c[1] and b == c[2] or a == c[2] and b == c[0]:
print("컴터 패")
else:
print("컴터 승")
import random
com=random.randrange(1,4)
print('가위, 바위, 보 중 하나를 선택해주세요....',end='')
person=input()
print("컴퓨터...",end='')
if (com==1):
print("가위")
elif (com==2):
print("바위")
elif (com==3):
print("보")
print("당신....",person)
if (person=="가위"):
if (com==1):
print("비겼습니다")
elif (com==2):
print("컴퓨터가 이겼습니댜")
elif (com==3):
print("당신이 이겼습니다")
elif (person=="바위"):
if (com==1):
print("당신이 이겼습니다")
elif (com==2):
print("비겼습니다")
elif (com==3):
print("컴퓨터가 이겼습니다")
elif (person=="보"):
if (com==1):
print("컴퓨터가 이겼습니다")
elif (com==2):
print("당신이 이겼습니댜")
elif (com==3):
print("비겼습니다")
import random as r
#가위 0 바위 1 보 2
def pap(com):
if com == 0:
print("졌습니다.(컴퓨터 : 가위)")
elif com == 1:
print("이겼습니다.(컴퓨터 : 바위)")
else:
print("비겼습니다.(컴퓨터 : 보)")
def roc(com):
if com == 2:
print("졌습니다.(컴퓨터 : 보)")
elif com == 0:
print("이겼습니다.(컴퓨터 : 가위)")
else:
print("비겼습니다.(컴퓨터 : 바위)")
def sic(com):
if com==1:
print("졌습니다.(컴퓨터 : 바위)")
elif com==2:
print("이겼습니다.(컴퓨터 : 보)")
else:
print("비겼습니다.(컴퓨터 : 가위)")
while True:
a=input("뭐 낼래?")
ran=r.randint(0,2)
if a=="가위":
sic(ran)
elif a=="바위":
roc(ran)
elif a=="보":
pap(ran)
else:
break
import random
def rps(u):
com_r = {0: '가위', 1: '바위', 2: '보'}
com = random.randint(0, 2)
if (u - com) == 0:
print('유저: {}, 컴퓨터: {}\n 비김!!'.format(com_r[u], com_r[com]))
elif (u - com) % 3 == 1:
print('유저: {}, 컴퓨터: {}\n유저 승리!!'.format(com_r[u], com_r[com]))
else:
print('유저: {}, 컴퓨터: {}\n컴퓨터 승리!!'.format(com_r[u], com_r[com]))
if __name__ == '__main__':
inp = int(input('가위[0] 바위[1] 보[2] 중 하나를 입력하세요: '))
rps(inp)
import random
game=["가위","바위","보"]
while True:
my_choice = input("무엇을 내실건가요:")
computer = random.choice(game)
if ((my_choice == '가위') and (computer == '보')) or ((my_choice == '바위') and (computer == '가위')) or ((my_choice == '보') and (computer == '바위')):
print(f"{my_choice} vs {computer}: You win!")
elif ((my_choice == '가위') and (computer == '바위')) or ((my_choice == '바위') and (computer == '보')) or ((my_choice == '보') and (computer == '가위')):
print(f"{my_choice} vs {computer}: You lose!")
else:
print(f"{my_choice} vs {computer}: Draw!")
파이썬입니다~
import random
pe = ['가위', '바위', '보']
nimpe = input('가위, 바위, 보 중 골라주세요')
nepe = pe[random.randint(0,2)]
print(nimpe)
print(nepe)
result = pe.index(nimpe) - pe.index(nepe)
if result == 0:
print('비겼다')
elif result == 1 or result == -2:
print('이겼다')
elif result == -1 or result == 2:
print('졌다')
import random
m = random.randrange(1,3)
while(True):
N = input('가위,바위,보 중 하나를 고르시오:')
if N == '가위' or N == '바위' or N == '보':
if N == '가위':N = 0
if N == '바위':N = 1
if N == '보':N = 2
break
if N == m:
print('비겼습니다.')
if N == 0:
if m == 1:print('패배하셨습니다','컴퓨터는 바위를 냈습니다')
if m == 2:print('승리하셨습니다','컴퓨터는 보를 냈습니다')
if N == 1:
if m == 0:print('승리하셨습니다','컴퓨터는 가위를 냈습니다')
if m == 2:print('패배하셨습니다','컴퓨터는 보를 냈습니다')
if N == 2:
if m == 0:print('패배하셨습니다','컴퓨터는 가위를 냈습니다')
if m == 1:print('승리하셨습니다','컴퓨터는 바위를 냈습니다')
import random
Ndic = {'바위':0,'가위':1,'보':2}
N = Ndic[input()]
M = random.randint(0,2)
print('비김' if N == M else '짐' if N == 0 and M == 2 else '이김' if N == 2 and M == 0 else '짐' if N > M else '이김')
import random
rps = ["가위","바위","보"]
com = rps[random.randint(0,2)]
me = rps[rps.index(input())]
print("나:{},컴퓨터:{}".format(me,com))
score = rps.index(me)-rps.index(com)
if score == 0:
print("비겼습니다.")
elif score == 1 or -2:
print("이겼습니다.")
elif score == -1 or 2:
print("졌습니다.")
import random
while True:
X = str(input("가위, 바위, 보 중에 하나를 선택하여 적으세요."))
list = ["가위", "바위", "보"]
Y = random.choice(list)
print("내가 낸 것?", X, "\n컴퓨터가 낸 것?", Y)
if X == "가위":
if Y == "가위":
print("무승부")
elif Y == "바위":
print("나의 패배!")
else:
print("나의 승리!")
if X == "바위":
if Y == "바위":
print("무승부")
elif Y == "보":
print("나의 패배!")
else:
print("나의 승리!")
if X == "보":
if Y == "보":
print("무승부")
elif Y == "가위":
print("나의 패배!")
else:
print("나의 승리!")
import random
def game(): # -1 0 1
a=input("가위 바위 보! : ")
b=random.randrange(0,3) # 0: 가위 1: 바위 2:보
if a=='가위':
a=0
if b==0:
print("비겼습니다")
elif b==1:
print("졌습니다")
elif b==2:
print("이겼습니다")
elif a=='바위':
a=1
if b==0:
print("이겼습니다")
elif b==1:
print("비겼습니다")
elif b==2:
print("졌습니다")
elif a=='보':
a=2
if b==0:
print("졌습니다")
elif b==1:
print("이겼습니다")
elif b==2:
print("비겼습니다")
game()
python 3.9입니다.
from random import randint
from time import sleep
choice = ['가위', '바위', '보']
annoucement = ['무승부입니다.', '승리하셨습니다!', '패배하셨습니다.']
print('가위바위보를 합니다.\n')
while True:
sleep(0.8)
computer = randint(0, 2)
sleep(0.5)
try: player = choice.index(input('가위, 바위, 보 중 하나를 입력하세요.: '))
except ValueError: print('올바른 값을 입력하세요.'); continue
sleep(0.3)
print(f'{choice[player]}를 선택하셨습니다. 잠시 후 결과가 공개됩니다.')
win_or_lose = (player - computer + 3) % 3
sleep(1.5)
print(f'컴퓨터는 {choice[computer]}를 선택했습니다.')
print(annoucement[win_or_lose])
if input('끝내시겠습니까? (끝낼 경우 "예" 입력): ') == '예':
break
print()
예시 결과입니다.
가위바위보를 합니다.
가위, 바위, 보 중 하나를 입력하세요.: 가위
가위를 선택하셨습니다. 잠시 후 결과가 공개됩니다.
컴퓨터는 가위를 선택했습니다.
무승부입니다.
끝내시겠습니까? (끝낼 경우 "예" 입력): 아니오
가위, 바위, 보 중 하나를 입력하세요.: 보
보를 선택하셨습니다. 잠시 후 결과가 공개됩니다.
컴퓨터는 보를 선택했습니다.
무승부입니다.
끝내시겠습니까? (끝낼 경우 "예" 입력): 아니오
가위, 바위, 보 중 하나를 입력하세요.: 보
보를 선택하셨습니다. 잠시 후 결과가 공개됩니다.
컴퓨터는 가위를 선택했습니다.
패배하셨습니다.
끝내시겠습니까? (끝낼 경우 "예" 입력): 예
import random
data = ['가위','바위','보']
num = random.choice(data)
num2 = input('가위 바위 보 중 하나 입력:')
if num == '가위' and num2 == '가위':
print('비겼읍니다')
elif num == '가위' and num2 =='바위':
print('졋읍니다')
elif num == '가위' and num2 == '보':
print('이겻읍니다')
elif num == '바위' and num2 == '가위':
print('이겻읍니다')
elif num == '바위' and num2 == '바위':
print('비겻읍니다')
elif num == '바위' and num2 == '보':
print('졋읍니다')
elif num == '보' and num2 == '가위':
print('졋읍니다')
elif num == '보' and num2 == '바위':
print('이겻읍니다')
elif num == '보' and num2 == '보':
print('비겻읍니다')
import random
def Rock_Paper_Scissors(c,u):
if c == u:
print("비겼어")
elif c != u:
if (c == "가위" and u == "바위") or (c == "바위" and u == "보") or (c == "보" and u == "가위"):
print("니가 이겼어!!!!!")
else:
print("니가 졌어....")
if __name__ == '__main__':
c = random.choice(["가위","바위","보"])
u = input("가위,바위,보 중에서 하나를 골라!: ")
Rock_Paper_Scissors(c,u)
import random
tool = ["rock", "scissor", "paper"]
while True:
comp = random.choice(tool)
user = input("Enter rock or scissor or paper: ")
if user == "rock":
if comp == "rock":
print("DRAW")
elif comp == "scissor":
print("YOU WIN")
elif comp == "paper":
print("YOU LOSE")
elif user == "scissor":
if comp == "rock":
print("YOU LOSE")
elif comp == "scissor":
print("DRAW")
elif comp == "paper":
print("YOU WIN")
elif user == "paper":
if comp == "rock":
print("YOU WIN")
elif comp == "scissor":
print("YOU LOSE")
elif comp == "paper":
print("DRAW")
else:
print("Incorrect, Try again.")
from random import randint as rand
lcp = ['가위','바위','보']
while True:
player = str(input("가위~ 바위~ 보~ 입력 하시오"))
if player=='가위' or player=='바위' or player=='보':
break
ranum=rand(0,2)
computer = lcp[ranum]
print('player :',player)
print('com :',computer)
if player=='가위' :
if computer==player:
print('비겼습니다')
elif computer=='바위':
print('졌습니다')
else:
print('이겼습니다')
elif player=='바위' :
if computer==player:
print('비겼습니다')
elif computer=='가위':
print('이겼습니다')
else:
print('졌습니다')
else:
if computer==player:
print('비겼습니다')
elif computer=='바위':
print('이겼습니다')
else:
print('졌습니다')
이미 있어서 그전에 풀이 한거 다시 첨부합니다
package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;
public class test {
public static void main(String[] args) {
Scanner sc =new Scanner(System.in);
while(true) {
String[] com = {"가위", "바위", "보"};
System.out.print("사용자의 값: ");
String user = sc.nextLine();
int len = com.length;
String comrd = com[(int)(Math.random()*len+0)];
System.out.println("컴퓨터의 값: " + comrd);
if(user.equals(comrd)==true) {
System.out.println("비겼습니다.");
}
if(user.equals("가위") && comrd.equals("보") || user.equals("바위") && comrd.equals("가위") || user.equals("보") && comrd.equals("바위")){
System.out.println("이겼습니다.");
}
else {
System.out.println("졌습니다.");
}
}
}
}
제가 코딩 초보여서 간추릴 수 있는거나 틀린 부분 지적해주시면 감사하겠습니다!
import random
import time
dictionary = {'가위':1,"바위":2,"보":3}
while True:
b = str(input("안내면 진거 가위바위보! >>\n유저: "))
if b not in dictionary:
print("다시내주세요 ㅡㅡ")
else:
b = dictionary[b]
a = random.randint(1,3)
if a==1:
print("컴퓨터: 가위!")
elif a==2:
print("컴퓨터: 바위!")
elif a==3:
print("컴퓨터: 보!")
time.sleep(2)
if a==b:
print("다시 한번 ㄱㄱ")
elif a-b==1:
print("컴퓨터: 제가 이겼네요ㅋ")
break
elif a-b!=1:
print("유저: 내가 이겼누 ㅋㅋ")
break
새 문법을 한번 써 봤습니다.
from random import choice
rps = ["가위", "바위", "보"]
record = {"승리":0, "패배":0, "비김":0}
you, com = None, None
while True:
you = input("가위/바위/보>> ")
if you not in rps:
continue
com = choice(rps)
match you, com:
case ("가위", "바위") | ("바위", "보") | ("보", "가위"):
result = "패배"
case ("바위", "가위") | ("보", "바위") | ("가위", "보"):
result = "승리"
case _:
result = "비김"
record[result] += 1
print(f"{you}(Player) vs. {com}(COM) : {result}")
print(record)
print()
python
# 가위 바위 보!
import random
usr = input("가위/바위/보 중 선택하시오: ")
def rock_scissors_paper(usr):
rsp = ['가위', '바위', '보']
computer = random.choice(rsp)
print("컴퓨터:", computer)
win = "이겼습니다."
lose = "졌습니다."
if usr == computer:
return "비겼습니다."
else:
if usr == '가위':
if computer == '바위':
return lose
elif computer == '보':
return win
if usr == '바위':
if computer == '가위':
return win
elif computer == '보':
return lose
if usr == '보':
if computer == '바위':
return win
elif computer == '가위':
return lose
if __name__== "__main__":
result = rock_scissors_paper(usr)
print(result)
import random
val_list = ['가위', '바위', '보']
input_val = ''
print("가위 바위 보 게임")
while(1):
input_val = input("입력 : ")
if input_val not in val_list:
print("잘못된 입력입니다.")
else:
break
ran_value = random.randrange(0, 3)
input_value = val_list.index(input_val)
print("컴퓨터 : {}".format(val_list[ran_value]))
print("유저 : {}".format(val_list[input_value]))
if ran_value == input_value:
print("무승부")
elif ran_value == 2 and input_value == 0:
print("승")
elif ran_value == 0 and input_value == 2:
print("패")
elif ran_value < input_value:
print("승")
else:
print("패")
import random
a=(input("입력해줘"))
b=random.choice(["가위", "바위", "보"])
print(a,b)
if a not in ["가위", "바위", "보"]:
print("장난해?")
else:
if a==b:
print("무승부")
elif (a=="가위" and b=="바위") or (a=="바위" and b=="보") or (a=="보" and b=="가위"):
print("졌다ㅠ")
else:
print("이겼다!")
public static void main(String[] args) {
// 가위바위보게임
// 컴퓨터 : 랜덤으로 1(가위) 2(바위) 3(보)
// 유저(나) : 1(가위) , 2(바위) , 3(보) 중 입력
// 출력
// 컴퓨터 : ??
// 나 : ??
// 승패 : 승 or 패 or 비김(나 기준)
// 내가 비기거나 이기면 한판더
// 내가 지면 게임은 끝남
// 게임이 끝나면 연승횟수 ? 회 라고 출력
// 랜덤으로 뽑기
// 나는 숫자입력
//출력
//컴퓨터 : ??
//나 : ??
//scanner에 변수담기
// == 같은값으로 평가해보기
//
int count = 0;
int winning = 0;
List<Integer> list = new ArrayList<>();
int i = 0 ;
Scanner name1 = new Scanner(System.in);
System.out.println("게임을 시작하기전 귀하의 이름을 입력해주세요.");
String name = name1.nextLine();
while ( true) {
int num = (int) (Math.random() * 3) + 1;
Scanner input = new Scanner(System.in);
System.out.println("가위바위보 게임에 오신것을 환영합니다. 가위(1),바위(2),보(3)중에 숫자로 하나 입력하세요");
int RockPaperScissors = input.nextInt();
if(RockPaperScissors == 1){
System.out.println( " 내가 낸것은 "+ RockPaperScissors +"가위입니다.");
}else if(RockPaperScissors == 2) {
System.out.println( " 내가 낸것은 "+ RockPaperScissors +"바위입니다.");
}else {
System.out.println( " 내가 낸것은 "+ RockPaperScissors +"보 입니다.");
}
if(num==1){
System.out.println( " 컴퓨터가 낸것은 "+ num +"가위입니다.");
}else if(num==2) {
System.out.println( " 컴퓨터가 낸것은 "+ num +"바위입니다.");
}else {
System.out.println( " 컴퓨터가 낸것은 "+ num +"보 입니다.");
}
if(RockPaperScissors < num && num== 2 && RockPaperScissors == 1 ) {
System.out.println("당신이 가위를 내서 바위에게 졌네요.");
break;
}else if (RockPaperScissors < num && num== 3 && RockPaperScissors == 1) {
count++;
winning++;
System.out.println("당신이 가위를 내서 보를 이겼네요.");
}else if(RockPaperScissors > num && num==1 && RockPaperScissors == 2) {
count++;
winning++;
System.out.println("당신이 바위를 내서 가위를 이겼네요.");
}else if(RockPaperScissors < num && num== 3 && RockPaperScissors == 2 ) {
System.out.println("당신이 바위를 내서 보자기에게 졌네요.");
break;
}else if(RockPaperScissors > num && num== 1 && RockPaperScissors == 3 ) {
System.out.println("당신이 보자기를 내서 가위에게 졌네요.");
break;
}else if(RockPaperScissors > num && num== 2 && RockPaperScissors == 3 ) {
count++;
winning++;
System.out.println("당신이 보자기를 내서 바위에게 이겼네요.");
}else{
System.out.println("당신은 비겼네요.");
winning--;
if(winning <= 0){
winning = 0;
}
}
}
System.out.println("게임이 끝났네요." + name +"의 점수를 계산해보겠습니다.");
System.out.println("이긴횟수" + count);
System.out.println("연승횟수" + winning);
}
----출처 91 김훈섭이 작성함.
import random
game = {'가위': 0, '바위': 1, '보': 2}
while True:
comp = random.randint(0,2)
user = input('가위 바위 보 하세요: ')
s = comp - game[user]
res = ''
if s == -2 or s == 1:
res = '승리'
elif s == -1 or s == 2:
res = '패'
elif s == 0:
res = '무승부'
print('\n {0}하였습니다.'.format(res))
if res != '무승부':
break
li = [1,2,3]; cont = 'Y'
import random
while cont == 'Y' or cont == 'y':
user = int(input("Rock:1, Paper:2, Scissors:3 ?>"))
com = random.choice(li)
if user == com :
print("Draw")
elif user == 1:
if com == 2 : print("Paper. YOU WIN")
else: print("Scissors. I WIN")
elif user == 2:
if com == 1: print("Rock. YOU WIN")
else: pirint("Scissors. I WIN")
elif user == 3:
if com == 1: print("Rock. I WIN")
else: print("Paper. YOU WIN")
cont = input("Continue ? Y/N :")
import random
pc = random.choice(['가위','바위','보'])
#시작 멘트
print("컴퓨터와 가위 바위 보 대결")
you = input("가위, 바위, 보 중 하나: ")
if pc == '가위':
if you == '가위':
print('비김')
elif you == "바위":
print('이김')
else:
print('짐')
if pc == '바위':
if you == '가위':
print('짐')
elif you == "바위":
print('비김')
else:
print('이김')
if pc == '보':
if you == '가위':
print('이김')
elif you == "바위":
print('짐')
else:
print('비김')
print('컴퓨터가 낸 것은 %s였습니다.'%pc)