( 난이도 : 노가다 or 약간쉬움 )
현우는 갑자기 가위바위보를 하고싶었다
하지만 현우는 같이 가위바위보를 해줄친구가 없었다.... (미안하다 친구없는놈 으로만들어서..)
부모님은 일나가시고 여동생도 지금 학교에서 방과후활동때문에 늦는다해서 같이해줄친구가없어
거울과 가위바위보를 하던도중 몹시나 자괴감이들어 컴퓨터랑이라도 가위바위보를 해야겠다는 마음을먹었다.
불상하고 딱한 현우를위해 좀만도와주자...
문제: 말그대로 가위바위보!
입력으로 가위바위보중 세가지중 하나를입력받는다
그리고 컴퓨터가 낼것도 렌덤으로꺼네서 둘이비교후 같으면 비겼다
을출력 다를경우 승패를알려주면된다
(난이도 up.ver) :
모든 경우의수를 조건문으로 틀어막아도된다
ex:
if (me=="가위" && you=="보"){
printf("승리하셨습니다")
}
else if (me=="가위" && you=="주먹"){
printf("패배하셨습니다")
}
.
.
.
하지만 수식을이용해서도 할수있으니 한번해보자!
내생각대로 힌트 : 0 ? 1 ? 2?
39개의 풀이가 있습니다.
import random as r
import time
def main():
list=['바위','가위','보']
a=int(input("1,바위 2,가위 3,보 중 하날골라"))
while not a in [1,2,3]:
a=int(input("정확한번호를 입력해 주십시오."))
user=a-1
print('\n{} 를 고르셨습니다 과연 현명한선택일까요?'.format(list[user]))
for i in range(3):
print('\n')
print(' 두근 ','.'*(i+1))
time.sleep(1+(i/3))
print('\n 고기두근 ....\n')
time.sleep(1+(4/3))
computer=r.randint(0,2)
if (computer-user)==0: #컴퓨터가낸 값에서 유져값을뺐는데 0이면 비긴거겟죠?
return ("user :{} vs {}: computer \n ::비-김::".format(list[user],list[computer]))
elif (computer-user)%3==1: #그리고 3으로나눈 나머지가 1일때 이긴거겠죠? 바위가위보 순서생각하시고
return ("user :{} vs {}: computer \n ::YOU WIN!::".format(list[user],list[computer]))
else : return ("user :{} vs {}: computer \n ::YOU DIE-::".format(list[user],list[computer]))
print(main())
지인의도움?으로 약간깔끔해진거같군요 헿; 그리고 약간 게임같이꾸며봤어요 ㅋㅋㅋ
(코딩시작한지 벌서3달이 다되가네요 여러분은 실력을어떻게올렸나요?)
const enum TRCT {
'가위' = 0,
'바위' = 1,
'보' = 2
}
const enum Result {
'draw',
'win',
'lose'
}
const arrRCT: [TRCT, TRCT, TRCT] = [TRCT.가위, TRCT.바위, TRCT.보];
class RCT {
constructor() { }
private makeComRCT = (): TRCT => arrRCT[Math.floor(Math.random() * 3)];
matchRCT = (usrRCT: TRCT) => (usrRCT - this.makeComRCT() + 3) % 3;
}
const printResult = (res) => {
switch (res) {
case Result.draw:
return console.log('비김');
case Result.win:
return console.log('승리');
case Result.lose:
return console.log('패배');
default:
break;
};
}
const rct = new RCT();
const res = rct.matchRCT(TRCT.가위);
printResult(res);
public static void main(String[] args) {
while (true) {
int P = Math.abs(new Scanner(System.in).nextInt());
if (P > 2)
break;
int C = new Random().nextInt(3);
System.out.println("컴 : " + ToLanguage(C) + "\n너 : " + ToLanguage(P)
+ ((P + 1 > 2 ? 0 : P + 1) == C ? "\nWin" : P == C ? "\nDraw" : "\nLose"));
}
}
private static String ToLanguage(int n) {
switch (n) {
case 0:
return "바위";
case 1:
return "가위";
}
return "보";
}
문제대로 풀이
import random
dic = ['가위', '바위', '보']
while True:
while True:
me = input('무엇을 냅니까(가위, 바위, 보)? ')
if me in dic:
break
com = random.choice(dic)
print('컴퓨터는 ' + com + '을(를) 냈습니다.')
# (순환)리스트에서 com이 자기 바로 뒤에 오면 이기고, 바로 앞에 오면 진다.
if com == me:
print('비겼습니다.')
elif com == dic[dic.index(me) - 1]:
print('승리했습니다.')
else:
print('패배했습니다.')
print()
그리고 딥러닝 가위바위보 (막 갖다 붙임!)
혼자가위바위보를 1000판 정도 하고 나면 계속 질 지도 모른다.
import random
dic = ['가위', '바위', '보']
freq = {x:0 for x in dic}
draw, win, lose = 0, 0, 0
while True:
# 내가 가위를 많이 냈으면 컴퓨터가 바위를 낼 확률이 높아진다.
com = random.choice(dic +
freq['보'] * ['가위'] +
freq['가위'] * ['바위'] +
freq['바위'] * ['보']
)
while True:
me = input('무엇을 냅니까(가위, 바위, 보)? ')
if me in dic:
break
print('컴퓨터는 ' + com + '을(를) 냈습니다.')
freq[me] += 1
if com == me:
draw += 1
print('비겼습니다.')
elif com == dic[dic.index(me) - 1]:
win += 1
print('승리했습니다.')
else:
lose += 1
print('패배했습니다.')
print()
print('전적: {}승 {}무 {}패'.format(win, draw, lose))
print()
from random import randrange
RPS = ('가위', '바위', '보')
myhand = int(input('0: 가위, 1: 바위, 2: 보\n>>> '))
comhand = randrange(3)
print(RPS[myhand], RPS[comhand], sep=' : ')
if myhand - comhand == 1: print('승리')
elif myhand == comhand: print('무승부')
else: print('패배')
C#
using System;
namespace CD194
{
class Program
{
static void Main(string[] args)
{
while (true)
{
Console.Write("[0] Rock, [1] Scissors, [2] Paper, [3] Exit : ");
if (int.TryParse(Console.ReadLine(), out int input))
{
if (input == 3) { break; }
else if (input >= 0 && input < 3) { Game((RSP)input); } // 게임 수행
else { continue; }
}
}
}
enum RSP { Rock, Scissors, Paper }
static Random rnd = new Random();
static void Game(RSP user) // user: 사용자 선택
{
int computer = rnd.Next(0, 3); // computer: 컴퓨터 선택
// 판단부
string result = string.Empty;
if ((computer + 1) % 3 == (int)user) { result = "Computer wins."; }
else if (((int)user + 1) % 3 == computer) { result = "User wins."; }
else { result = "Draw game."; }
Console.WriteLine($"Computer: {(RSP)computer}, User: {user} => {result}");
}
}
}
import random
Dkbb={'가위':'보','바위':'가위','보':'바위'} #딕셔너리
rkbb=['가위','바위','보']
Mkbb=input('가위,바위,보 입력 :')
while Mkbb in rkbb:
Ckbb=random.choice(rkbb) #컴퓨터가 결정
print('나:',Mkbb,' PC:',Ckbb)
if Mkbb == Ckbb:
print('비겼습니다.')
elif Ckbb == Dkbb[Mkbb]:
print('우와 승리.')
else:
print('에구 졌다.')
print()
Mkbb=input('가위,바위,보 입력 :')
파이썬의 딕셔너리를 이용 하였습니다. 계속 반복되면 가위,바위,보 이외의 것을 압력시 종료 됩니다.
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int main()
{
srand(time(NULL));
while(1){
char inputhand;
int myhand, comhand;
printf("\n\n========================================\n");
printf("가위바위보 게임에 오신것을 환영합니다.\n");
printf("가위는 X 바위는 O 보는 #을 입력해주세요.\n");
printf("나가시려면 숫자 9를 입력해 주세요.\n");
scanf("%c", &inputhand);
getchar(); // flush 처리입니다 //
switch(inputhand){
case 'x' :
case 'X' : printf("가위를 내셨습니다.\n"); myhand = 0; break;
case 'o' :
case 'O' : printf("바위를 내셨습니다.\n"); myhand = 1; break;
case '#' : printf("보를 내셨습니다.\n"); myhand = 2; break;
case '9' : printf("종료합니다.\n"); myhand = -1; break;
default : printf("입력 오류"); myhand = -1; break;
}
if(myhand == -1)
{
break;
}
else
{
comhand = rand()%3;
switch(comhand){
case 0 : printf("컴퓨터가 가위를 냈습니다.\n"); break;
case 1 : printf("컴퓨터가 바위를 냈습니다.\n"); break;
case 2 : printf("컴퓨터가 보를 냈습니다\n"); break;
}
if(comhand == myhand) // 두 값이 같으면 항상 비깁니다!
{
printf("비겼습니다!\n");
continue;
}
else if(comhand - myhand == 1 || comhand - myhand == -2) // ex) 가위 - 보 = -2 , 보 - 바위 = 1 -> 나의 패배
{
printf("졌습니다!\n");
continue;
}
else
{
printf("이겼습니다!\n");
continue;
}
}
}
return 0;
}
0 1 2 가위 바위 보로 받아서 뺄셈 연산으로 승패를 구분지을 수 있습니다 ㅎㅎ 사람 vs 컴 인 부분입니다
#주먹 0 가위 1 보 2
#0 -1 = -1 = 주먹이김
#0 -2 = -2 = 보자기 이김
#1 -0 = 1= 주먹 이김
#1 -2 = -1 = 가위 이김
#2 -0 = 2 = 보자기 이김
#2 -1 = 1 = 가위 이김
#-1 이나 2일경우 me 이김
#-2 이나 1일경우 컴퓨터 이김
#나머지는 무승부.
import random
dicts={0:'주먹',1:'가위',2:'보'}
me=random.randint(0,2)
you=random.randint(0,2)
print('나는',dicts[me],'컴퓨터는',dicts[you])
if (me-you) == -1 or (me-you) == 2: print('내가 승리')
elif (me-you) == -2 or (me-you) ==1: print('컴퓨터 이김')
else: print('무승부')
#include <iostream>
#include <time.h>
#include <stdlib.h>
int main(int argc, char** argv) {
srand(time(NULL));
int input;
int com;
printf("1. 가위 2. 바위 3. 보 { 선택하자! }\n");
scanf("%d",&input);
com=rand()%3+1;
printf("컴퓨터는 ");
if (com==1) {
printf("가위를 선택\n");
} else if (com==2) {
printf("바위를 선택\n");
} else if (com==3) {
printf("보를 선택\n");
}
if(com==input) {
printf("무승부!");
} else {
if(com==1&&input==2) {
printf("승리하셨습니다.");
} else if(com==2&&input==3) {
printf("승리하셨습니다.");
} else if(com==3&&input==1) {
printf("승리하셨습니다.");
} else if(com==1&&input==3) {
printf("패배하셨습니다.");
} else if(com==3&&input==2) {
printf("패배하셨습니다.");
} else if(com==2&&input==1) {
printf("패배하셨습니다.");
}
}
return 0;
}
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;
}
}
from random import choice
print('Rock Scissors Paper Game\n\nRock: R\nScissors: S\nPaper : P\n-------------------------------\n')
while True:
player = input('Your Chice? : ').upper()
print('\n')
if player in ['R','S','P']:
result = player+' '+choice(['R','S','P'])
if result in ['R S','S P','P R']:
print('YOU WIN! %s \n'%(result))
elif result in ['R R','S S','P P']:
print('DRAW! %s \n'%(result))
else:
print('YOU LOST! %s \n'%(result))
if input('ONE MORE TIME?\n') in ['YES','y','Y','네','응']:
print('\n')
continue
else:
break
else:
print('This card does not exist\n')
continue
더욱 효율적으로 하기 보단 가독성과 즐거움을 우선적으로 코딩했습니다.
from random import *
def RSP(string):
dict = {"가위":1,"바위":0,"보":-1}
com = randint(-1,1) #순서대로 가위:1, 바위:0, 보:-1
if dict[string] - com == 0: return "비김"
elif dict[string] - com == -1: return "이김"
else: return "짐"
print(RSP(input()))
Ruby
user, comp = -> { %w[가위 바위 보].index gets.chop }, -> { rand(3) }
play = ->(p1, p2) { puts '[winner] ' + %w[none p1 p2][p1.() - p2.() % 3] }
play[user, comp] # user vs computer
Test
# test with pvp : draw, p1 win, p2 win
$stdin = StringIO.new("가위\n가위\n" + "가위\n보\n" + "바위\n보\n")
expect { 3.times { play[user, user] } }.
to output("[winner] none\n" + "[winner] p1\n" + "[winner] p2\n").to_stdout
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))
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("졌습니다.");
}
}
}
}
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))
#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;
}
import random
d = {'가위' : 0, '보' : 1, '바위' : 2}
def rsp(a, b):
if a == b:
print('비겼습니다.')
return
x, y = d[a], d[b]
if (x-y) % 3 > (y-x) % 3: print('승리하였습니다.')
else: print('패배하였습니다.')
while True:
you = random.choice(('가위', '바위', '보'))
me = input('가위바위보를 내세요 : ')
print('상대방은 %s를 냈습니다.' %you)
rsp(me, you)
from random import randint
com = randint(0, 2)
case1 = ['가위', '바위', '보']
case2 = ['바위', '보', '가위']
case3 = ['보', '가위', '바위']
def make_result(n):
if n == 0:
return print('비겼습니다')
elif n == 1:
return print('이겼습니다')
elif n == 2:
return print('졌습니다')
while 1:
me = input('가위 바위 보?')
if me not in case1:
print("다시 입력하세요")
continue
if me == case1[0]:
print('me : %s, com : %s' % (me, case1[com]))
make_result(com)
elif me == case2[0]:
print('me : %s, com : %s' % (me, case2[com]))
make_result(com)
elif me == case3[0]:
print('me : %s, com : %s' % (me, case3[com]))
make_result(com)
break
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("패배하셨습니다.");
}
}
}
a = input("a = ") b = input("b = ")
if a == 'r':
if b == 'p' :
print('b win !')
elif b == 's':
print('a win!')
else :
print('draw!')
elif a == 'p':
if b == 's' :
print('b win !')
elif b == 'r':
print('a win!')
else :
print('draw!')
else :
if b == 'p' :
print('a win !')
elif b == 'r':
print('b win!')
else :
print('draw!')
간단하게 파이썬으로 만들어보았습니다!!
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
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('비김')
import random
while(1):
me=input('가위, 바위, 보.....')
com=random.randint(1,3)
if me=='가위':
if com==1:
print('비겼습니다')
elif com==2:
print('컴퓨터가 이겼습니다')
else:
print('당신이 이겼습니다')
elif me=='바위':
if com==1:
print('당신이 이겼습니다')
elif com==2:
print('비겼습니다')
else:
print('컴퓨터가 이겼습니다')
elif me=='보':
if com==1:
print('컴퓨터가 이겼습니다')
elif com==2:
print('당신이 이겼습니다')
else:
print('비겼습니다')
else:
print('가위 바위 보 중에서 입력을 해주세요')
python 3.8
import random
d=['가위','바위','보','q'] # 0 가위 1 바위 2 보 3 종료
f=d.index(input('가위, 바위, 보 또는 q 중 입력... '))
ds=[0,0,0] # 사람 이김, 비김, 패 count
while f != 3:
s = random.randint(1,100) % 3 # ran값 0,1,2
if (f==0 and s==2) or (f==1 and s== 0) or ( f==2 and s==1): # 사람 승
ds[0]=ds[0]+1
print('사람 승')
elif f == s: # 비김
ds[1]=ds[1]+1
print('비김')
else: # 사람 패
ds[2]=ds[2]+1
print('컴터 승')
f=d.index(input())
print('사람 : 총 %d 번 중 %d 승, %d 비김, %d 패' % (sum(ds), ds[0], ds[1], ds[2]))
# q입력 때까지 반복하여 게임함
import random
class RPS:
def __init__(self):
com = random.randint(0, 2)
self.com = com
def rps(self, me):
user = me - 1
rps = {0: '가위', 1: '바위', 2: '보'}
print('유저: {}, 컴퓨터: {} 선택'.format(rps[user], rps[self.com]))
if user == self.com: return '비김'
elif (user - self.com)%3 == 1: return '유저 승리!!!'
else: return '컴퓨터 승리!'
if __name__ == '__main__':
g = RPS()
print(g.rps(int(input('1번 가위, 2번 바위, 3번 보 중 선택하세요.\n'))))
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 as r
lst = ["가위", "바위", "보"]
user = lst.index(input("가위, 바위, 보 중에 하나 입력 : "))
com = r.randint(0, 2)
if user - com == 0:
res = "비김"
elif user - com == 1 or -2:
res = "이김"
elif user - com == -1 or 2:
res = "짐"
print("[컴퓨터 : {}] | [유저 : {}] | [결과 : {}]".format(lst[com], lst[user], res))
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()
예시 결과입니다.
가위바위보를 합니다.
가위, 바위, 보 중 하나를 입력하세요.: 코딩도장
올바른 값을 입력하세요.
가위, 바위, 보 중 하나를 입력하세요.: 보
보를 선택하셨습니다. 잠시 후 결과가 공개됩니다.
컴퓨터는 가위를 선택했습니다.
패배하셨습니다.
끝내시겠습니까? (끝낼 경우 "예" 입력): 아니오
가위, 바위, 보 중 하나를 입력하세요.: 바위
바위를 선택하셨습니다. 잠시 후 결과가 공개됩니다.
컴퓨터는 가위를 선택했습니다.
승리하셨습니다!
끝내시겠습니까? (끝낼 경우 "예" 입력): 예
from random import *
l = ["가위", "바위", "보"]
y = input("무엇을 내시겠습니까?")
if y not in l:
print("가위, 바위, 보 중 하나를 입력하세요.")
quit()
c = randint(0, 2)
if c == l.index(y):
print(f"YOU : {y} COM : {l[c]} 비겼습니다!")
elif c == l.index(y) + 1 or c == l.index(y) - 2:
print(f"YOU : {y} COM : {l[c]} 졌습니다!")
else:
print(f"YOU : {y} COM : {l[c]} 이겼습니다!")
자바로 구현한 소스입니다.
package rcp;
import java.util.*;
public class rcp {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while(true) {
System.out.println("가위, 바위, 보 중에 고르세요 [가위(0),바위(1),보(2)]");
System.out.print("종료(3) >> ");
int num = sc.nextInt(); // 유저가 가위, 바위, 보 선정을 하기 위해 숫자를 넣음 0 - 바위 / 1 - 가위 / 2 - 보
String user = null; // 플레이어
int randNum = (int)(Math.random()*2); // 컴퓨터가 가위, 바위, 보 선정을 하기 위해 난수 함수 발생시키는 변수
String com = null; // 컴퓨터
if(num == 0) {
user = "바위";
}
if(num == 1) {
user = "가위";
}
if(num == 2) {
user = "보";
}
if(num == 3) {
break;
}
if(randNum == 0) {
com = "바위";
}
if(randNum == 1) {
com = "가위";
}
if(randNum == 2) {
com = "보";
}
if(user.equals(com)){
System.out.println("유저 >> " + user);
System.out.println("컴퓨터 >> " + com);
System.out.println("비겼습니다.");
}
if((num == 0 && randNum == 2) || (num == 1 && randNum == 0) || (num == 2 && randNum == 1)){
System.out.println("유저 >> " + user);
System.out.println("컴퓨터 >> " + com);
System.out.println("컴퓨터가 이겼습니다.");
}
if((num == 0 && randNum == 1) || (num == 1 && randNum == 2) || (num == 2 && randNum == 0)){
System.out.println("유저 >> " + user);
System.out.println("컴퓨터 >> " + com);
System.out.println("유저가 이겼습니다.");
}
}
System.out.println("게임이 종료되었습니다.");
}
}
import random
def Rock_Paper_Scissors(c,u):
print('컴퓨터는'+ c +'를 냈다')
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('졌습니다')
import random
# RPS = Rock_Paper_Scissors
def RPS():
man = random.choice(['가위','바위','보'])
com = random.choice(['가위','바위','보'])
if man == com: return '비겼다'
elif man == '가위' and com == '바위': return '이겼다'
elif man == '가위' and com == '보': return '졌다'
elif man == '바위' and com == '가위': return '이겼다'
elif man == '바위' and com == '보': return '졌다'
elif man == '보' and com == '가위': return '졌다'
elif man == '보' and com == '바위': return '이겼다'
print(RPS())
package org.javaturotials.ex;
import java.util.*;
import java.util.stream.Collectors;
public class test {
int vot(String me){
String[] rand_com = {"가위","바위","보"};
int len = rand_com.length;
int count=0;
String comp = rand_com[(int)(Math.random()*len + 0)];
System.out.println(comp);
if(me.equals(comp)) {
count=0;
}
else if((me.equals("바위")&&comp.equals("가위")) ||(me.equals("가위")&&comp.equals("보")) || (me.equals("보")&&comp.equals("바위"))){
count=1;
}
else if((me.equals("가위")&&comp.equals("바위")) ||(me.equals("보")&&comp.equals("가위")) || (me.equals("바위")&&comp.equals("보"))){
count=2;
}
return count;
}
public static void main(String[] args) {
while(true) {
Scanner sc = new Scanner(System.in);
test a1 = new test();
int ct=0;
ct=a1.vot(sc.nextLine());
if(ct==0) {
System.out.println("비겼습니다.");
}
if(ct==1) {
System.out.println("이겼습니다.");
}
if(ct==2) {
System.out.println("졌습니다.");
}
}
}
}
# 조건문을 사용하지 않고 알고리즘과 인덱싱으로 풀이
import random
dict_rsp = {0:'가위', 1:'바위', 2:'보'}
index=['비겼습니다.','졌습니다.','이겼습니다.']
while True:
i = int(input("'가위'=0, '바위'=1, '보'=2 "))
com = random.randint(0, 2) # 컴퓨터의 가위바위보 선택
print(f'당신은 {dict_rsp[i%3]}, 컴퓨터는 {dict_rsp[com]}')
print(f'결과는 {index[com-i%3]}')
python
import random
while True:
user = input("가위바위보 게임입니다. 가위, 바위, 보 중에 하나를 입력해주세요")
if user == "가위" or user == "바위" or user == "보":
break
elif user != "가위" or user != "바위" or user != "보":
print("!!!Error!!! 다시 입력해주십시오")
continue
computer = random.randint(1,3)
if computer == 1:
computer = "가위"
elif computer == 2:
computer = "바위"
else:
computer = "보"
print(f"user: {user} \n computer: {computer}")
if user == computer:
print("무승부입니다. 다행이네요.")
elif user == "가위":
if computer == "바위":
print("안타갑지만 패배하셨습니다ㅠㅠㅠ.")
elif computer == "보":
print("!!!축하드립니다!!! 승리하셨습니다.")
elif user == "바위":
if computer == "보":
print("안타갑지만 패배하셨습니다ㅠㅠㅠ.")
elif computer == "가위":
print("!!!축하드립니다!!! 승리하셨습니다.")
elif user == "보":
if computer == "가위":
print("안타갑지만 패배하셨습니다ㅠㅠㅠ.")
elif computer == '바위':
print("!!!축하드립니다!!! 승리하셨습니다.")
java
import java.util.Random;
import java.util.*;
class rock_scissors_paper
{
public static void main(String[] args)
{
Random random = new Random();
int flag = 0;
Scanner scanner = new Scanner(System.in);
flag = random.nextInt(3);
System.out.printf("가위, 바위, 보 중에 하나를 입력해주세요.");
while (true)
{
String user = scanner.nextLine();
if (user.equals("가위") == false && user.equals("바위") == false && user.equals("보") == false) {
System.out.printf("ERROR!!! 다시 입력해주십시오!!!");
continue;
}
if (flag == 0) //computer: 가위
{
String computer = "가위";
if (user.equals("가위") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("무승부입니다.");
break;
}
if (user.equals("바위") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("승리하였습니다.");
break;
}
if (user.equals("보") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("패배하였습니다.");
break;
}
}
if (flag == 1) //computer: 바위
{
String computer = "바위";
if (user.equals("가위") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("패배하였습니다.");
break;
}
if (user.equals("바위") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("무승부입니다.");
break;
}
if (user.equals("보") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("승리하였습니다.");
break;
}
}
if (flag == 2) //computer: 보
{
String computer = "보";
if (user.equals("가위") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("승리하였습니다.");
break;
}
if (user.equals("바위") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("패배하였습니다.");
break;
}
if (user.equals("보") == true)
{
System.out.printf("컴퓨터: %s, 유저: %s", computer, user);
System.out.printf("무승부입니다.");
break;
}
}
}
}
}