no image
[고1 프로그래밍] 12 - (1)
class SoldOutError(Exception): pass chicken = 10 waiting = 1 # 틀 안에는 현재 만석, 대기번호 1부터 시작 while(True): try: print("[남은 치킨 : {0}]".format(chicken)) order = int(input("치킨 몇 마리 주문하시겠습니까?")) if order > chicken: # 남은 치킨보다 주문량이 많을때 print("재료가 부족합니다.") elif order
2023.12.04
no image
[고1 프로그래밍] 11 - (5)
class House: # 매물 초기화 def __init__(self, location, house_type, deal_type, price, completion_year): self.location = location self.house_type = house_type self.deal_type = deal_type self.price = price self.completion_year = completion_year # 매물 정보 표시 def show_detail(self): print(self.location, self.house_type, self.deal_type\ , self.price, self.completion_year) houses = [] house1 = House("강남", "아파..
2023.11.30
no image
[고1 화면구현] 11 - (2)
변수 선언, 전역/지역/블록 변수
2023.11.21
no image
[고1 게임엔진] 11 - (2)
보낼 파일 public class GameCounter : MonoBehaviour { // 1. 카운터 본체를 만든다. public static int count; // 공유하는 카운터의 값 public int startCount = 0; // 카운터 초깃값 private void Start() { count = startCount; // 카운터값 리셋 } } ------------------------------------------------------- using UnityEngine.UI; // UI 사용 public class Forever_ShowCount : MonoBehaviour { // 2. 계속 카운터 값을 표시한다. void Update() { GetComponent().text ..
2023.11.20
no image
[고1 프로그래밍] 11 - (4)
class Unit: def __init__(self): print("Unit 생성자") class Flyable: def __init__(self): print("Flyable 생성자") class FlyableUnit(Unit, Flyable): def __init__(self): #super().__init__() Unit.__init__(self) Flyable.__init__(self) # 드랍쉽 dropship = FlyableUnit() 나도코딩 - 스타크래프트 try: print("나누기 전용 계산기입니다.") num1 = int(input("첫 번째 숫자를 입력하세요 : ")) num2 = int(input("두 번째 숫자를 입력하세요 : ")) print("{0} / {1} = {2}"..
2023.11.20
no image
[고1 프로그래밍] 11 - (3)
# 일반 유닛 class Unit: def __init__(self, name, hp, speed): self.name = name self.hp = hp self.speed = speed def move(self, location): print("[지상 유닛 이동]") print("{0} : {1} 방향으로 이동합니다. [속도 : {2}]"\ .format(self.name, location, self.speed)) # 메딕 : 의무병(공격력 없음, 사람으로 된 유니싱 다쳤을 때 치료해주어 체력을 회복시켜 줌) # 공격 유닛 class AttackUnit(Unit): def __init__(self, name, hp, speed, damage): Unit.__init__(self, name, hp, s..
2023.11.15
no image
[고1 게임엔진] 11 - (1)
using System.Collections; using System.Collections.Generic; using UnityEngine; public class OnUpKeyPress_Throw : MonoBehaviour { // 플레이어 이동, 반전관련 변수선언 public float speed = 5; float vx; // x축 이동량 bool leftFlag = false; // 좌우반전 bool upFlag = false; // 위쪽 방향키 눌렸는지 여부 //프리팹 만들기------------------------------------ public GameObject sushi; // 공장에 넘겨줄 원본(프리팹) GameObject newSushi; // 공장에 찍어낸 새로운 아이템(프리팹..
2023.11.13
no image
[고1 프로그래밍] 11 - (2)
# 일반 유닛 class Unit: def __init__(self, name, hp, speed): self.name = name self.hp = hp self.speed = speed def move(self, location): print("[지상 유닛 이동]") print("{0} : {1} 방향으로 이동합니다. [속도 : {2}]"\ .format(self.name, location, self.speed)) # 메딕 : 의무병(공격력 없음, 사람으로 된 유니싱 다쳤을 때 치료해주어 체력을 회복시켜 줌) # 공격 유닛 class AttackUnit(Unit): def __init__(self, name, hp, speed, damage): Unit.__init__(self, name, hp, s..
2023.11.13
no image
[고1 화면구현] 11 - (1)
마우스 올려 보세요 ​ 마우스 올려 보세요 마우스 올려 보세요 링크의 href에 자바스크립트 작성 클릭해보세요 lib.js function over(obj) { obj.src="banana.png"; } function out(obj) { obj.src="apple.png"; } document.write()로 HTML 콘텐츠 출력
2023.11.09
class SoldOutError(Exception):
    pass

chicken = 10
waiting = 1 # 틀 안에는 현재 만석, 대기번호 1부터 시작
while(True):
    try:
        print("[남은 치킨 : {0}]".format(chicken))
        order = int(input("치킨 몇 마리 주문하시겠습니까?"))
        if order > chicken: # 남은 치킨보다 주문량이 많을때
            print("재료가 부족합니다.")    
        elif order <= 0:
            raise ValueError    
        else:
            print("[대기번호 {0}] {1} 마리 주문이 완료되었습니다."\
                    .format(waiting, order))
            waiting += 1
            chicken -= order

        if chicken == 0:
            raise SoldOutError
    except ValueError:
        print("잘못된 값을 입력하였습니다.")
    except SoldOutError:
        print("재고가 소진되어 더 이상 주문을 받지 않습니다.")
        break
class House:
    # 매물 초기화
    def __init__(self, location, house_type, deal_type, price, completion_year):
        self.location = location
        self.house_type = house_type
        self.deal_type = deal_type
        self.price = price
        self.completion_year = completion_year

    # 매물 정보 표시
    def show_detail(self):
        print(self.location, self.house_type, self.deal_type\
                , self.price, self.completion_year)


houses = []
house1 = House("강남", "아파트", "매매", "10억", "2010년")
house2 = House("마포", "오피스텔", "전세", "5억", "2007년")
house3 = House("송파", "빌라", "월세", "500/50", "2000년")

houses.append(house1)
houses.append(house2)
houses.append(house3)

print("총 {0}대의 매물이 있습니다.".format(len(houses)))
for house in houses:
    house.show_detail()
import turtle as t
t.shape("turtle")

d=100
t.forward(d)
t.left(120)
t.forward(d)
t.left(120)
t.forward(d)
t.left(120)
t.mainloop()
import turtle
t=turtle.Pen()

t.forward(80)
t.right(90)
t.forward(40)
t.right(90)
t.forward(80)
t.lt(90)
t.forward(40)
t.lt(90)
t.forward(80)

turtle.mainloop()
import turtle

t1=turtle.Turtle()
t2=turtle.Turtle()

t1.forward(100)
t2.forward(200)

t1.lt(120)
t2.rt(120)

t1.fd(100)
t2.fd(200)

t1.lt(120)
t2.rt(120)

t1.fd(100)
t2.fd(200)

t1.lt(120)
t2.rt(120)

turtle.done()
class BigNumberError(Exception):
    def __init__(self, msg):
        self.msg = msg

    def __str__(self):
        return self.msg

try:
    print("나누기 전용 계산기입니다.")
    num1 = int(input("첫 번째 숫자를 입력하세요 : "))
    num2 = int(input("두 번째 숫자를 입력하세요 : "))
    if num1 >= 10 or num2 >= 10:
        raise BigNumberError("입력값 : {0}, {1}".format(num1, num2))
    print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
    print("잘못된 값을 입력하였습니다. 한 자리 숫자만 입력하세요.")
except BigNumberError as err:
    print("에러가 발생했습니다. 한 자리 숫자만 입력하세요.")  
    print(err)
finally:
    print("계산기를 이용해 주셔서 감사합니다.")
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>변수 선언</title>
</head>
<body>
    <h3>변수 선언, 전역/지역/블록 변수</h3>
    <hr>
    <script>
    let x;
    function f() {
        let y;
        x = 10;
        y = 20;
        z = 30;
        if(y == 20) {
            let b = 40; 
            b++;
            document.write("if 블록 내 블록변수 b = " + b + "<br>");
        }
    document.write("함수 f() 내 지역변수 y = " + y + "<br>");
    }
    f();
    document.write("전역변수 x = " + x + "<br>");
    document.write("전역변수 z = " + z);
    </script>
</body>
</html>
<!DOCTYPE html>
<html lang="ko"?
<head>
    <meta charset="utf-8">
    <title>리터럴</title>
</head>
<body>
    <h3>리터럴</h3>
    <hr>
    <script>
        let oct = 015;
        let hex = 0x15;
        let condition = true;

        document.write("8진수 015는 십진수로 " + oct + "<br>");
        document.write("16진수 015는 십진수로 " + hex + "<br>");
        document.write("condition은 " + condition + "<br>");
        document.write('문자열 : 단일인용부호로도 표현' + "<br>");
        document.write("그녀는 \"누구세요\"라고 말했습니다.");
    </script>
</body>

'----------고1---------- > 화면구현' 카테고리의 다른 글

[고1 화면구현] 11 - (1)  (0) 2023.11.09
[고1 화면구현] 10 - (4)  (0) 2023.10.26
[고1 화면구현] 10 - (3)  (0) 2023.10.19
[고1 화면구현] 10 - (2)  (1) 2023.10.10
[고1 화면구현] 10 - (1)  (0) 2023.10.05

보낼 파일

public class GameCounter : MonoBehaviour
{
    // 1. 카운터 본체를 만든다.

    public static int count; // 공유하는 카운터의 값
    public int startCount = 0; // 카운터 초깃값
    private void Start()
    {
        count = startCount; // 카운터값 리셋
    }
}

-------------------------------------------------------

using UnityEngine.UI; // UI 사용

public class Forever_ShowCount : MonoBehaviour
{
    // 2. 계속 카운터 값을 표시한다.

    void Update()
    {
        GetComponent<Text>().text = GameCounter.count.ToString();
    }
}

-------------------------------------------------------

public class OnCollision_CountAndHide : MonoBehaviour
{
    // 플레이어와 충돌하면 카운터를 1씩 증가하고, 자신은 사라진다. (삭제한다)

    public string targetName; // 목표 오브젝트 저장

    private void OnCollisionEnter2D(Collision2D collision)
    {
        // 만약 충돌한 것이 목표 오브젝트라면
        if (collision.gameObject.name == targetName)
        {
            // 카운터 1씩 증가시키고
            GameCounter.count++;

            // 자기자신 삭제
            this.gameObject.SetActive(false);
        }
    }
}

-------------------------------------------------------

using UnityEngine.SceneManagement; // 씬 전환에 필요

public class OnFinished : MonoBehaviour
{
    public int lastCount = 3; // 카운터의 최종값
    public string sceneName;  // 씬 이름 저장

    private void FixedUpdate()
    {
        // 카운터가 최종값(3)이 되면
        if (GameCounter.count == lastCount)
        {
            // 씬 전환
            SceneManager.LoadScene(sceneName);
        }
    }
}

 

 

초밥 액션 게임

 

 

Text UI 추가

 

카메라 설정

 

텍스트 가운데 정렬

 

Canvas - Text에 적용

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class GameCounter : MonoBehaviour
{
    // 1. 카운터 본체를 만든다.

    public static int count; // 공유하는 카운터의 값
    public int startCount = 0; // 카운터 초깃값
    private void Start()
    {
        count = startCount; // 카운터값 리셋
    }
}

 

Canvas - Jumsu에 적용 (Scene Name에 SecondScene)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI; // UI 사용

public class Forever_ShowCount : MonoBehaviour
{
    // 2. 계속 카운터 값을 표시한다.

    void Update()
    {
        GetComponent<Text>().text = GameCounter.count.ToString();
    }
}
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement; // 씬 전환에 필요

public class OnFinished : MonoBehaviour
{
    public int lastCount = 3; // 카운터의 최종값
    public string sceneName;  // 씬 이름 저장

    private void FixedUpdate()
    {
        // 카운터가 최종값(3)이 되면
        if (GameCounter.count == lastCount)
        {
            // 씬 전환
            SceneManager.LoadScene(sceneName);
        }
    }
}

 

초밥에 적용 (TargetName에 Player)

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnCollision_CountAndHide : MonoBehaviour
{
    // 플레이어와 충돌하면 카운터를 1씩 증가하고, 자신은 사라진다. (삭제한다)

    public string targetName; // 목표 오브젝트 저장

    private void OnCollisionEnter2D(Collision2D collision)
    {
        // 만약 충돌한 것이 목표 오브젝트라면
        if (collision.gameObject.name == targetName)
        {
            // 카운터 1씩 증가시키고
            GameCounter.count++;

            // 자기자신 삭제
            this.gameObject.SetActive(false);
        }
    }
}

 

 

빌드

'----------고1---------- > 게임엔진' 카테고리의 다른 글

[고1 게임엔진] 12 - (1)  (5) 2023.12.27
[고1 게임엔진] 11 - (1)  (0) 2023.11.13
[고1 게임엔진] 10 - (3)  (0) 2023.10.18
[고1 게임엔진] 10 - (2)  (2) 2023.10.16
[고1 게임엔진] 10 - (1)  (0) 2023.10.11
class Unit:
    def __init__(self):
        print("Unit 생성자")

class Flyable:
    def __init__(self):
        print("Flyable 생성자")

class FlyableUnit(Unit, Flyable):
    def __init__(self):
        #super().__init__()
        Unit.__init__(self)
        Flyable.__init__(self)

# 드랍쉽
dropship = FlyableUnit()

나도코딩 - 스타크래프트

try:
    print("나누기 전용 계산기입니다.")
    num1 = int(input("첫 번째 숫자를 입력하세요 : "))
    num2 = int(input("두 번째 숫자를 입력하세요 : "))
    print("{0} / {1} = {2}".format(num1, num2, int(num1/num2)))
except ValueError:
    print("에러! 잘못된 값을 입력하였습니다.")
# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 : {2}]"\
                .format(self.name, location, self.speed))
        
# 메딕 : 의무병(공격력 없음, 사람으로 된 유니싱 다쳤을 때 치료해주어 체력을 회복시켜 줌)
# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed)
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격합니다.[공격력 : {2}"\
                .format(self.name, location, self.damage))
        
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현제 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))
    
# 드랍쉽 : 공중 유닛, 수송기, 마린/파이어뱃/탱크 등을 수송. 공격 불가
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다.[속도 : {2}]"\
                .format(name, location, self.flying_speed))
        
# 날 수 있는 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed는 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 벌처 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐", 80, 10, 20)

# 배틀크루저 : 공중 유닛, 체력이 굉장히 좋음, 공격력도 좋음
battlecruiser = FlyableAttackUnit("배틀크루저", 500, 25, 3)

vulture.move("11시")
battlecruiser.move("9시")
# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 : {2}]"\
                .format(self.name, location, self.speed))
        
# 메딕 : 의무병(공격력 없음, 사람으로 된 유니싱 다쳤을 때 치료해주어 체력을 회복시켜 줌)
# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed)
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격합니다.[공격력 : {2}"\
                .format(self.name, location, self.damage))
        
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현제 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))
    
# 드랍쉽 : 공중 유닛, 수송기, 마린/파이어뱃/탱크 등을 수송. 공격 불가

# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다.[속도 : {2}]"\
                .format(name, location, self.flying_speed))
        
# 날 수 있는 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed는 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 건물
class BuildingUnit(Unit):
    def __init__(self, name, hp, location):
        pass

# 서플라이 디폿 : 건물, 1개 건물 = 8 유닛
supply_depot = BuildingUnit("서플라이 디폿", 500, "7시")

def game_start():
    print("[알림] 새로운 게임을 시작합니다.")

def game_over():
    pass

game_start()
game_over()
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class OnUpKeyPress_Throw : MonoBehaviour
{
    // 플레이어 이동, 반전관련 변수선언
    public float speed = 5;
    float vx; // x축 이동량
    bool leftFlag = false; // 좌우반전
    bool upFlag = false; // 위쪽 방향키 눌렸는지 여부
    //프리팹 만들기------------------------------------
    public GameObject sushi; // 공장에 넘겨줄 원본(프리팹)
    GameObject newSushi; // 공장에 찍어낸 새로운 아이템(프리팹)
    //프리팹이 던져지는 위치와 힘을 지정
    public float offsetY = 1; // 프리팹이 던져지는 간격(Y축)
    public float throwX = 4;  // x축으로 던지는 힘
    public float throwY = 8;  // y축으로 던지는 힘

    // 메인카메라와 관련된 변수선언
    Vector3 camPos; // 카메라의 원래위치를 저장해두는 변수

    void Start()
    {
        // 카메라의 원래위치를 저장해둔다.
        camPos = Camera.main.transform.position;
    }

    void Update()
    {
        // 키보드 좌우방향키 입력 검사
        vx = 0; // 초기화

        if (Input.GetKey("right"))
        {
            vx = speed;
            leftFlag = false;
        }
        if (Input.GetKey("left"))
        {
            vx = -speed;
            leftFlag = true;
        }
    }

    void FixedUpdate()
    {
        // 플레이어 이동, 반전
        transform.Translate(vx / 50, 0, 0);
        GetComponent<SpriteRenderer>().flipX = leftFlag;

        if (Input.GetKey("up")) // 위쪽 키가 눌리면
        {
            if (upFlag == false)
            {
                upFlag = true;

                // 프리팹이 플레이어의 위치에 나오도록(프리팹이 나올 위치)
                Vector3 newPos = this.transform.position; // 현재 플레이어의 위치값
                newPos.y += offsetY; // 플레이어의 조금 위에
                newPos.z = -5; // 카메라의 앞에

                // 프리팹을 만들고, 프리팹이 나올 위치를 설정
                newSushi = Instantiate(sushi);
                newSushi.transform.position = newPos;

                // 프리팹 던지기(AddForce)
                Rigidbody2D rb = newSushi.GetComponent<Rigidbody2D>();

                if (leftFlag == true)
                {
                    rb.AddForce(new Vector2(-throwX, throwY), ForceMode2D.Impulse);
                }
                else
                {
                    rb.AddForce(new Vector2(throwX, throwY), ForceMode2D.Impulse);
                }
            }
        }
        else
        {
            upFlag = false;
        }
    }
    // 모든 오브젝트의 움직임이 끝난 후에 카메라를 이동시킨다.
    
    void LateUpdate()
    {
        // 일단 플레이어의 위치를 저장
        Vector3 playerPos = transform.position; // x, y, z

        // 그 플레이어의 위치를 카메라위치로 변경
        playerPos.z = -10; // 카메라의 위치값(z)
        playerPos.y = camPos.y; // 카메라의 원래 높이값
        Camera.main.transform.position = playerPos;
    }
}

'----------고1---------- > 게임엔진' 카테고리의 다른 글

[고1 게임엔진] 12 - (1)  (5) 2023.12.27
[고1 게임엔진] 11 - (2)  (2) 2023.11.20
[고1 게임엔진] 10 - (3)  (0) 2023.10.18
[고1 게임엔진] 10 - (2)  (2) 2023.10.16
[고1 게임엔진] 10 - (1)  (0) 2023.10.11
# 일반 유닛
class Unit:
    def __init__(self, name, hp, speed):
        self.name = name
        self.hp = hp
        self.speed = speed

    def move(self, location):
        print("[지상 유닛 이동]")
        print("{0} : {1} 방향으로 이동합니다. [속도 : {2}]"\
                .format(self.name, location, self.speed))
        
# 메딕 : 의무병(공격력 없음, 사람으로 된 유니싱 다쳤을 때 치료해주어 체력을 회복시켜 줌)
# 공격 유닛
class AttackUnit(Unit):
    def __init__(self, name, hp, speed, damage):
        Unit.__init__(self, name, hp, speed)
        self.damage = damage

    def attack(self, location):
        print("{0} : {1} 방향으로 적군을 공격합니다.[공격력 : {2}"\
                .format(self.name, location, self.damage))
        
    def damaged(self, damage):
        print("{0} : {1} 데미지를 입었습니다.".format(self.name, damage))
        self.hp -= damage
        print("{0} : 현제 체력은 {1} 입니다.".format(self.name, self.hp))
        if self.hp <= 0:
            print("{0} : 파괴되었습니다.".format(self.name))
    
# 드랍쉽 : 공중 유닛, 수송기, 마린/파이어뱃/탱크 등을 수송. 공격 불가
# 날 수 있는 기능을 가진 클래스
class Flyable:
    def __init__(self, flying_speed):
        self.flying_speed = flying_speed

    def fly(self, name, location):
        print("{0} : {1} 방향으로 날아갑니다.[속도 : {2}]"\
                .format(name, location, self.flying_speed))
        
# 날 수 있는 공격 유닛 클래스
class FlyableAttackUnit(AttackUnit, Flyable):
    def __init__(self, name, hp, damage, flying_speed):
        AttackUnit.__init__(self, name, hp, 0, damage) # 지상 speed는 0
        Flyable.__init__(self, flying_speed)

    def move(self, location):   # move 재정의
        print("[공중 유닛 이동]")
        self.fly(self.name, location)

# 벌처 : 지상 유닛, 기동성이 좋음
vulture = AttackUnit("벌쳐", 80, 10, 20)

# 배틀크루저 : 공중 유닛, 체력이 굉장히 좋음, 공격력도 좋음
battlecruiser = FlyableAttackUnit("배틀크루저", 500, 25, 3)

vulture.move("11시")
battlecruiser.fly("배틀크루저", "9시")
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>외부 파일에 있는 자바스크립트 작성</title>
        <script src="lib.js">
        </script>
    </head>
    <body>
        <h3>마우스 올려 보세요</h3>
        <hr>
        <img src="banana.png" alt="이미지"
            onmouseover="over(this)"
            onmouseout="out(this)">
    </body>
</html>​
<!DOCTYPE html>
<html>
    <head>
        <title>이벤트 리스터 속성에 자바스크립트 코드</title>
    </head>
    <body>
        <h3>마우스 올려 보세요</h3>
        <hr>
        <img src="apple.png" alt="이미지"
            onmouseover="this.src='banana.png'"
            onmouseout="this.src='apple.png'">
    </body>
</html>
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>script 태그에 자바스크립트 작성</title>
        <script>
            function over(obj) {
                obj.src="banana.png";
            }
            function out(obj) {
                obj.src="apple.png";
            }
        </script>
    </head>
    <body>
        <h3>마우스 올려 보세요</h3>
        <hr>
        <img src="apple.png" alt="이미지"
            onmouseover="over(this)"
            onmouseout="out(this)">
    </body>
</html>
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>URL에 자바스크립트 작성</title>
    </head>
    <body>
        <h3>링크의 href에 자바스크립트 작성</h3>
        <hr>
        <a href="Javascript:alert('클릭하셨어요?')">클릭해보세요</a>
    </body>
</html>

lib.js

function over(obj) {
    obj.src="banana.png";
}
function out(obj) {
    obj.src="apple.png";
}
<!DOCTYPE html>
<html lang="ko">
    <head>
        <meta charset="utf-8">
        <title>document.write() 사용</title>
    </head>
    <body>
        <h3>document.write()로 HTML 콘텐츠 출력</h3>
        <hr>
        <script>
            document.write("<h3>Welcome!</h3>");
            document.write("2+5는 <br>");
            document.write("<mark>7 입니다.</mark>");
        </script>
    </body>
</html>

'----------고1---------- > 화면구현' 카테고리의 다른 글

[고1 화면구현] 11 - (2)  (0) 2023.11.21
[고1 화면구현] 10 - (4)  (0) 2023.10.26
[고1 화면구현] 10 - (3)  (0) 2023.10.19
[고1 화면구현] 10 - (2)  (1) 2023.10.10
[고1 화면구현] 10 - (1)  (0) 2023.10.05