안녕하세요. 쥐똥박사입니다.

이번엔 파이썬으로 야구게임 만들어 봅니다.


 
import random
# 게임을 위한 랜덤 숫자 생성
ran_num = ["0", "0", "0"]
ran_num[0] = str(random.randrange(1, 9, 1))
ran_num[1] = ran_num[0]
ran_num[2] = ran_num[0]
while (ran_num[0] == ran_num[1]):
    ran_num[1] = str(random.randrange(1, 9, 1))
while (ran_num[0] == ran_num[2] or ran_num[1] == ran_num[2]):
    ran_num[2] = str(random.randrange(1, 9, 1))

t_count = 0 # 횟수
s_count = 0 # 스트라이크
b_count = 0 # 볼

print("\n")
while ( s_count < 3 ):
    num = str(input("숫자 3자리를 입력하세요. ex)123 : "))
    if(num == ""):
        print("\n\n숫자를 입력해주세요. \n\n")
        continue
    if(len(num) != 3):
        print("\n\n숫자 3자리만 입력해주세요.\n\n")
        continue
    if(num.isalpha()):
        print("\n\n문자를 입력할 수 없습니다.\n\n")
        continue

    s_count = 0
    b_count = 0

    for i in range(0, 3):
        for j in range(0, 3):
            if(num[i] == str(ran_num[j]) and i == j):
                s_count += 1
            elif(num[i] == str(ran_num[j]) and i != j):
                b_count += 1
    print("\n[", s_count, "] 스트라이크! [", b_count, "] 볼!\n")
    t_count += 1
print(t_count, "번 만에 스트라이크!!")
 
결과:


'언어 > Python' 카테고리의 다른 글

[윈도우10] 파이썬(Python) 설치  (0) 2017.11.28
블로그 이미지

Gddong

,

안녕하세요. 쥐똥박사입니다.

이번엔 자바(java)로 야구게임 만들어 봅시다.



 
/* package whatever; // don't place package name! */

import java.util.*;
import java.lang.*;
import java.io.*;

import java.util.Random;  //랜덤 임폴트
import java.util.Scanner;  //입력 임폴트

/* Name of the class has to be "Main" only if the class is public. */
class BaseBall
{
	static int strike =0; //스트라이크 변수 선언
	static int ball = 0; //볼 변수 선언
	
	public static void main (String[] args) throws java.lang.Exception
	{
		int computer[] = new int[3]; //컴퓨터가 정한 값
		int user[] = new int[3]; //유저가 정한 값
		
		Random random = new Random();
		
		
		//여기서부터 컴퓨터가 정할 값
		//중복방지.
		//random.nextInt(10); 이것은 1~9사이에 랜덤
		
		//computer 3중에 1번째가 0이면 랜덤 값 넣음
		while(computer[0] == 0){
			computer[0] = random.nextInt(10);
		}
		
		//computer 3중에 1번째와 2번째가 중복되거나,
		//2번째가 0이라면 랜덤 값 넣음
		while(computer[0] == computer[1] || computer[1] == 0){
			computer[1] = random.nextInt(10);
		}
		
		//computer 3중에 1번째와 3번째가 중복되거나,
		//2번째와 3번째가 중복되거나,
		//3번째가 0이라면 랜덤 값 넣음
		while(computer[0] == computer[2] || computer[1] == computer[2] || computer[2] == 0){
			computer[2] = random.nextInt(10);
		}
		
		
		
		//유저가 정한 값
		
		//입력 s 변수 선언
		Scanner s= new Scanner(System.in);
		
		while(strike < 3){ //스트라이크 3이 될 때 까지 무한 루프
		
			//3번 반복하여 유저 입력 받음.
			for(int i = 0; i < user.length; i++){
				System.out.print("\n"+(i+1) + "번째 수: ");
				user[i]=s.nextInt();
				
				//만약 10이상이거나, 0이하면 오류 출력
				while(user[i] >=10 || user[i] <= 0){
					System.out.println("error: 1~9사이에 입력 하세요.");
					System.out.print(i+1 + "번째 수: ");
					user[i]=s.nextInt();
				}
			}
			
			//여기서 결과 체크
			
			//strike, ball 체크 
			for(int i = 0; i< 3; i++){
				for(int j=0; j<3; j++){
					
					//컴퓨터 정한 값과
					//유저가 정한 값을 같으면
					if(computer[i] == user[j]){
						//computer i번째와
						//user j번째가 같으면
						//스트라이크!
						if(i==j){
							strike+=1;
						}else{	//아니면 볼!
							ball+=1;
						}
					}
				}
			}
			
			//만약 strike, ball 아무도 못맞췄다면
			if(strike == 0 && ball==0){
				System.out.println("\n아웃!!\n");
			}else if(strike == 3){ //만약 스트라이크 3개라면
				System.out.print("\n스트라이크!!");
				System.exit(0); //무한루프 탈출하여 종료!
			}else{
				System.out.println("\n"+strike+" 스트라이크"+ball+" 볼\n");
				strike=0;
				ball=0;
			}
		}
	}
}


'언어 > JAVA' 카테고리의 다른 글

자바(java) 업데이트 하는법  (0) 2017.11.27
Windows10 이클립스(eclipse) 설치방법  (2) 2017.11.20
자바(java) 설치방법  (5) 2017.11.17
블로그 이미지

Gddong

,

안녕하세요. 쥐똥박사입니다.


자 이번엔 js로 로또번호 생성하는 소스를 만들어보겠습니다.


JAVASCRIPT




HTML





결과:



여기서 가장 중요한 것은

9번줄에 있는 parseInt(Math.random() * 45) + 1; 부분대해서 설명 하겠습니다.

parseInt는 정수형 변환 하는겁니다.
안그러면 랜덤 숫자 추출하고나서 +1를 더하지 못하게 됩니다. 
왜냐하면 숫자가아닌 문자 타입으로 되어 있기 때문입니다.

Math 함수는 여러가지 수학적 상수와 함수들이 모여 있습니다.
즉 Math.PI 이렇게만 해도 파이값을 구할 수 있습니다.

Math.random()은 숫자가 랜덤값으로 구하게됩니다. 
그런데 옆에 왜 *45를 하는 걸까요?

랜덤 값은 소수만 출력 됩니다.  ex) 0.15376958879564406

0.15376958879564406 x 45 = 6.91963149580398..

이렇게 해서 정수화해서 소수 없애면 6이 됩니다.
그런데 로또숫자는 0부터가 아닌 1부터 시작 하므로 +1하게됩니다.
그러면 6+1 = 7 이렇게 랜덤숫자 가져오게 됩니다. 

이해되셨나요?


'언어 > JavaScript' 카테고리의 다른 글

[js]자바스크립트로 실시간 디지털시계 만들기  (0) 2017.12.04
블로그 이미지

Gddong

,