1 / 63

Game Programming 11 AI in game programming

Game Programming 11 AI in game programming. 2010 년 2 학기 디지털콘텐츠전공. What is AI?. What is intelligence (constrained to games)? When is a game considered intelligent?. Any sufficiently advanced technology is indistinguishable from magic (intelligence)”. What is AI?.

adsila
Download Presentation

Game Programming 11 AI in game programming

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Game Programming 11AI in game programming 2010년 2학기 디지털콘텐츠전공

  2. What is AI? • What is intelligence (constrained to games)? • When is a game considered intelligent? Any sufficiently advanced technology is indistinguishable from magic (intelligence)”

  3. What is AI? • AI is (traditionally) the control of every non-human entity in a game: • The other cars in a car game • The opponents and monsters in shooter games • Your units, your enemy’s units and your enemy in a RTS game • But, typically does not refer to passive things that just react to the player and never initiate action • That’s physics or game logic • For example, the blocks in Tetris are not AI, nor is a flag blowing in the wind • It’s a somewhat arbitrary distinction

  4. Perception Management • Perceive (Sensor information) • Think (Evaluate perceived data) • Act (execute planned action)

  5. AI Update Step • The sensing phase determines the state of the world • May be very simple - state changes all come by message • Or complex - figure out what is visible, where your team is, etc • The thinking phase decides what to do given the world • The core of AI • The acting phase tells the animation what to do • Generally not that interesting (for this course) AI Module Sensing Game Engine Thinking Acting

  6. AI in the Game Loop • AI is updated as part of the game loop, after user input, and before rendering • There are issues here: • Which AI goes first? • Does the AI run on every frame? • Is the AI synchronized?

  7. AI and Animation • AI determines what to do and the animation does it • AI drives animation, deciding what action the animation system should be animating • Scenario 1: The AI issues orders like “move from A to B”, and it’s up to the animation system to do the rest • Scenario 2: The AI controls everything down to the animation clip to play • Which scenario is best depends on the nature of the AI system and the nature of the animation system • Is the animation system based on move trees (motion capture), or physics, or something else • Does the AI look after collision avoidance? Does it do detailed planning?

  8. AI by Polling • The AI gets called at a fixed rate • Senses: It looks to see what has changed in the world. For instance: • Queries what it can see • Checks to see if its animation has finished running • And then acts on it • Why is this generally inefficient?

  9. Event Driven AI • Event driven AI does everything in response to events in the world • Events sent by message (basically, a function gets called when a message arrives, just like a user interface) • Example messages: • A certain amount of time has passed, so update yourself • You have heard a sound • Someone has entered your field of view • Note that messages can completely replace sensing, but typically do not. Why not? • Real system are a mix - something changes, so you do some sensing

  10. Requirements for Games AI • They need to be fast (i.e contrary to some academic AI approaches which are ‘optimal’ – we will give you both) • Games do not need optimal solutions (they need to be fun) • Games may need to combine several techniques • The goal is to design agents that provide the illusion of intelligence

  11. Goals of Game AI • Goal driven - the AI decides what it should do, and then figures out how to do it: • Reactive - the AI responds immediately to changes in the world • Knowledge intensive - the AI knows a lot about the world and how it behaves, and embodies knowledge in its own behavior • Characteristic - Embodies a believable, consistent character • Fast and easy development • Games do not need optimal solutions (they need to be fun) • Games may need to combine several techniques • The goal is to design agents that provide the illusion of intelligenc • Low CPU and memory usage • These conflict in almost every way – how?

  12. AI Techniques in Games • Basic problem: Given the state of the world, what should I do? • A wide range of solutions in games: • Finite state machines, Decision trees, Rule based systems, Neural networks, Fuzzy logic • A wider range of solutions in the academic world: • Complex planning systems, logic programming, genetic algorithms, Bayes-nets • Typically, too slow for games

  13. Techniques used today • Deterministic: • Finite State Machines • Decision trees • Fuzzy State machines • Statistical: • Baysian Approaches • Neural Networks • Evolutionary algorithms/ Artificial life

  14. Two Measures of Complexity • Complexity of Execution • How fast does it run as more knowledge is added? • How much memory is required as more knowledge is added? • Determines the run-time cost of the AI • Complexity of Specification • How hard is it to write the code? • As more “knowledge” is added, how much more code needs to be added? • Determines the development cost, and risk

  15. Different games need different methods • Action Games (lead a character through a set of levels) • Fighting Games Physical combat • Sports Games (icehockey and football) • Racing Games (Car, bikes, speedboats) • Adventure games ( plots based on exploration and problem solving) • Role Playing games (D&D) • Board games (Chess, checkers) • Strategic games (i.e. military type battle scenarios) • Simulation Games (simcity)

  16. Cases • Chess: Large search trees • Packman: Random FSM (weighted randomness) • Smart environments: Information is not coded in the NPC but in their environment

  17. FSM(Finite State Machine) • 유한상태기계(Finite State Machine) •  유한 개의 상태들로 구성된 간단한 기계 •  구성요소 • 현재 상태(Current State) • 입력(Input) • 출력 상태(Output State) • 전이(transition) 함수의 4가지 요소로 구성 • 현재 상태는 현재 FSM의 상태를 말하고, 입력은 FSM에 들어온 입력 정보, • 출력 상태는 다음 단계의 상태(Next State), 전이 함수는 입력 정보와 현재 상태를 기반으로 출력 상태를 결정

  18. 입력/출력

  19. 확률적인 상태 선택 • 확률적인 상태 선택은 주어진 확률에 따른 빈도로 다음 상태를 선택 • 아래의 그림 • 공격(S0), 후퇴(S1), 정지(S2), 랜덤(S3) 등 4가지 상태 •  공격은 0.4의 확률, 후퇴는 0.3의 확률, 정지는 0.1의 확률, 랜덤은 0.2의 확률이라고 한다면 각 상태의 선택은 이 확률에 맞게 선택. • e.g. int state_table[0, 0, 0, 0, 1, 1, 1, 2, 3, 3] • new_state = state_table[rand()%10]

  20. The ghosts' behavior in Pac-Man is implemented as a finite state machine. There is one Evade state, which is the same for all ghosts, and then each ghost has its own Chase state, the actions of which are implemented differently for each ghost. The input of the player eating one of the power pills is the condition for the transition from Chase to Evade. The input of a timer running down is the condition for the transition from Evade to Chase. Quake-style bots are implemented as finite state machines. They have states such as FindArmor, FindHealth, Seekcover, and Run- "Away. Even the weapons in Quake implement their own mini finite state machines. For example, a rocket may implement states such as Mov~T, ouchobject, and Die. W Players in sports simulations such as the soccer game FIFA2002 are implemented as state machines. They have states such as Strike, Dribble, ChaseBall, and Markplayer. In addition, the teams themr ., vyelves are often implemented as FSMs and can have states such as FckOff, Defend, or WalkOutOnField. The NPCs (non-player characters) in RTSs (real-time strategy \ g y e s ) such as Warcraft make use of finite state machines. They ,' have states such as MoveToPosition, Patrol, and FollowPath. Examples • The ghosts' behavior in Pac-Man are FSM • Evade • own Chase state • Quake-style bots. • FindArmor • FindHealth • Seekcover • Run-Away • Sports simulations i.e. FIFA2002 • Player • Strike, • Dribble • ChaseBall • Markplayer. • Team • FaceOff • Defend, • WalkOutOnField • The NPCs (non-player characters) in RTSs (real-time strategy) such as Warcraft • MoveToPosition • Patrol • FollowPath.

  21. Example: 레이싱 AI

  22. 목차 • AI에 적합한 경주 트랙 표현 • 레이싱 AI 로직

  23. AI에 적합한 경주 트랙 표현

  24. 접촉선 - 경주 트랙의 기본적인 구축 요소들로 트랙의 왼쪽, 오른쪽 경계들 - 가상의 주행선(driving line)들 역시 이들을 통해서 결정됨 - 주행선 노드들은 왼쪽과 오른쪽 경계를 따라서배치됨 - 접촉선에서 접촉선으로 이 노드들을 이어나가면 차가 달릴 주행선이 됨

  25. 구역 - 경주 트랙은 노드들의 이중 연결 목록(doubly linked list)로 구성 - 단일 연결이 아닌 이중 연결을 사용한 이유 : 트랙을 거꾸로 되밟아 갈 수도 있기 때문 - 각 구역은 또한 출발선으로부터의 거리도 가지는데, 이는 AI로 하여금 현재 어디까지 와 있으며 결승전까지는 얼마나 남았는 지, 그리고 적과의 상대적인 거리는 어느 정도인지를 쉽게 알 수 있게 하기 위해서임 - 이 거리를 계산하는 방식 : 주행선 노드들을 따라서 거리를 계속 누적하는 것임

  26. 주행선들 - 주행선들은 접촉선들 사이의 최적의 경로를 정의하는 데 쓰임 - 각 선은 선의 시작위치의 세계 좌표, 선의 길이, 그리고 앞쪽 벡터와 오른쪽 벡터를 가진다. - 전방 벡터 XZ 평면에 투영 (Y를 0으로) : 주행선에 대한 차의 방향을 계산하기 쉽게 하기 위해. - 한 점이 한 구역 안에 들어 있는 지의 여부를 쉽게 판단하기 위해서, 구역은 항상 블록 사각형이 되도록 한다. 블록사각형이 되려면, 각 변의 두 끝점들이 그 변의 대변에 해당하는 평면의 양의 쪽에 있어야 함.

  27. 구역찾기 및 거리 현재 구역 찾기 - AI는 각 차가 현재 어떤 구역에 놓여 있는 지를 알아야 함 - 주어진 구역에 대해, 주어진 차가 그 구역의 각 평면의 양의 쪽에 있다면, 그 차는 그 구역 안에 있는 것임 구역 안에서의 거리 - 구역 안에서 차가 얼마나 나아갔는 지를 알아내는 방법 : 주행선과 평행한 방향의 주행 거리 계산

  28. 구역 내 정보 저장 - AI가 환경을 좀 더 잘 이해할 수 있게 하기 위해, 각 구역마다 그에 관련된 정보를 저장해 둠 - 차가 구역들을 지나쳐갈 때, AI는 그 정보에 대해 몇 가지 간단한 비교들을 수행해서 빠르게 의사결정을 내리게 됨

  29. 여러가지 attributes • 경로의 종류 • - 지름길, 긴 경로, 무기 줍기 경로, 비포장 도로, 직선 코스 • - AI는 갈림길이 나 있을 때 이러한 정보를 이용해서 선택하게 됨 • 지면의 종류 • - 일반적으로 AI는 더 짧은 경로를 택하게 되겠지만, 만일 더 짧은 경로가 빙판이나 비포장 도로라면, 그런 길에서도 속도를 크게 늦출 필요가 없는 차에 대해서만 그런 경로를 택해야 할 것임 • - AI가 정보 판단 위해 각 구역에 구역의 지면에 대한 정보를 포함시킴 • 벽 • - 구역의 좌우변에 벽이 존재하는 지의 여부를 저장해 두면, AI는 그것을 이용해서 해당 벽으로부터 안전한 거리를 유지 • 제동/가속 • - AI가 주행 전략을 결정하는 데 도움됨

  30. 정리 • - 경주 트랙을 구역으로 나누고, 구역마다 AI의 판단에 유용한 정보를 넣어두면 AI 시스템의 복잡성을 줄이는 데 도움 됨 • - 3차원 트랙 정보를 2차원으로 투영해서 정보를 추출하면 계산의 복잡성이 크게 줄어듬

  31. 레이싱 AI 로직 개요 : 트랙을 따라서 차를 몰 수 있는 AI의 구현방법에 대해 설명 기본적인 AI 구조 유한 상태 기계 - AI로직을 단순화하기 위해, 현재의 경주 상황을 유한기계로 관리 고정된 시간 간격 - AI를 가변 시간 간격으로 돌리면, 프레임율이나 기타 요인들에 따라 다른 결과가 나올 수 있다 : AI가 브레이크를 밟을 시점을 놓치거나, 장애물에 대해 너무 늦게 반응하거나 또는 네트웍 플에이에서 동기화가 깨지는 현상이 빚어짐 - 고정된 시간 간격을 사용하면, AI 로직이 서로 다른 플랫폼들에서 프레임율에 상관없이 항상 동일하게 실해가능

  32. 차의 제어 - 방향 조정, 가속/제동 값들을 담는 하나의 간단한 구조체 사용 - dx : 방향 조정, -1.0 → 완전한 왼쪽, 1.0 → 완전한 오른쪽 - dy : 음수 → 제동의 양, 양수 → 가속의 양 2차원으로의 단순화 - 시각적인 면에서 볼 때 높낮이가 있는 3차원적 구조로 표현될 수 있으나, 본 질적으로는 2차원적인 하나의 길 - Y 성분을 0으로 해서 XZ평면에 투영하면 많은 계산들을 단순화할 수 있다.

  33. 출발점 - 경주가 시작되기 전에 가장 먼저 할 일 : AI의 값들을 출발 위치에 맞게 초기화함 - 적절한 함수를 통해 출발 위치가 있는 구역을 가리키는 포인터를 얻기 - 내부적으로 그 포인터를 2가지로 구분 ① 현재 ② 마지막으로 유효 : 차가 크랙을 벗어나서 뒤짚혔다던가 할 때 차를 다시 올려놓을 구역 - FSM의 초기 상태는 STATE_STARTING_GRID로 설정 : 파란불 신호가 들어 오면 바뀌게 됨 - 출발 신호가 떨어지면 상태는 STATE_RACING으로 전이

  34. 경주시작 • FSM의 가장 복잡한 상태는 경주 모드, 즉 STATE_RACING • 구역 따라가기 • - AI가 판단내리기 위해서는, 기본적으로 현재 자신이 제어하는 에이전트가 게임 세계의 어디쯤에 위치하는 지를 알아야 함 • - 레이싱 게임의 경우, 에이전트의 위치는 경주 트랙 상의 어느 한 지점이 될 것임 • - 점검할 구역을 줄이는 방법 → 응집성 : 현재 구역을 검색의 출발점으로 삼음, 차가 현재 구역을 벗어났다면, 현재 구역의 이전, 다음 포인터가 가리키는 구역들로부터 차례로 점검

  35. 판단 • 갈림길 • - 가장 적합한 길 선택 • - 선택의 기준 : 현재 요구와 각 경로의 특징 (예: 지면의 종류, 경로의 종류, 지름길 여부) • 미리 내다보기 • - 좀 더 지능적인 AI를 위해서는, AI가 현재의 사건들에만 반응하는 것이 아니라, 어느 정도는 앞도 내다볼 수 있어야 함. (예) 잠시 후 급하게 구부러진 코너에 도달하게 된다면, 매끄러운 코너링을 위해 미리 속도를 줄여나갈 필요가 있음 • - 미리 내다 보기 : 차의 현재 위치에서 일정 거리 이내의 다음 구역들을 점검하는 식으로 일어남

  36. 구역 내 정보의 활용 • 헤어핀 턴 • - 헤어핀 턴 같은 급격한 모퉁이가 나타나는 경우에는 트랙에서 벗어날 위험이 존재 : 이를 방지 위해 헤어핀 안쪽 변들에 특별한 표시를 해두고, 이동 코드에서는 구역에 그러한 “헤어핀“ 표시가 존재하는 경우에 대해 직선 경로를 선택하지 말아야 함.

  37. 주행 파라미터 결정 • 목표로의 주행 • - AI가 어떤 목표를 선택했다면, 거기까지 도달하기 위한 적절한 행동들을 취해야 함 • - AI는 목표에 대한 상대적인 방향을 계산하고, 그에 따라 적절한 방향 조정을 수행해야 함 • 추월 • - AI가 상대방 차에 가까워지면, 그 차를 앞질러 나갈 길을 찾아야 함 : 구역에 미리 정의되어 있는 추월선을 사용

  38. 주행 파라미터 결정 • 언더스티어와 오버스티어 • - 차의 움직임을 물리 역학에 좀 더 근접한 방식으로 모델링하는 게임에서 고려 • - 오버스티어(oversteer) : 차가 뱅뱅 돌게 되고, 언더스티어가 일어나면 최적의 코너링 선을 벗어나게 됨. • - 언더스티어(understeer) : 최적의 코너링 선을 벗어나게 됨 • 그런 상황들을 감지하고 차의 방향이나 가속, 제동 등을 조절해서 차를 제대로 달리게 하는 방법

  39. 벽 피하기 • - FSM의 현재 상태에 대한 처리가 끝났다면, AI는 차가 벽에 부딪힐 위험이 있는 지 판단하고, 필요하다면 차의 이동을 조절해야 함 • - 미래의 예상 위치를 얻어서 그 위치에 해당하는 구역을 찾고, 그 구역의 가장자리들과 예상 위치를 비교 후 충돌 위험이 있다면 차의 방향을 적절히 보정함

  40. 기타 FSM 상태들 - AI에서 중요한 역할을 하는 기타 상태 - STATE_AIRBORNE : 경주 트랙에 점프대가 놓여 있거나 굴곡이 심하다면 차가 공중에 뜨는 경우인데, AI는 이 상태에서 차가 제대로 착지할 수 있도록 해야 함 : 차의 바퀴가 지면에 닿으면 FSM은 다시 STATE_RACING으로 돌아감 - STATE_OFF_TRACK : 차가 어떤 구역에도 속하지 않은 경우에 해당하는 상태 : 이 상태에서 AI는 차를 다시 트랙으로 되돌려 보내야 함

  41. 게임의 재미 증진 • - AI 차가 플레이어보다 너무 앞서 나간다면, 의도적으로 플레이어에게 역전의 기회를 제공할 필요가 있음 • - 방법 • : 플레이어와의 거리에 비례해서 AI차의 최고 속도를 제한 • : 모둥이에서 좀 더 일찍 제동을 걸고, 좀 더 늦게 가속을 가하는 방법 • : 지름길을 무시하고 먼 길로 돌아가거나 일부러 울퉁불퉁한 길 택함 • : AI 차가 플레이어 차를 제외한 다른 AI 차들만 공격하게 함

  42. 열린 거리 조건 하에서의 경쟁적인 AI 레이싱 개요 : AI가 조종하는 차량이 임의의 도로들과 교차로들로 이루어진 네트웍을 경쟁적이며 매우 사실적인 방식으로 주행하는 데 필요한 기본적인 기능들 설명

  43. 맵의 구성요소들

  44. 도시 주행 현재 위치 알아내기 - 차가 도로에 있는 지 교차로에 있는 지 알아야 함 - 기본 노선에서의 상대적인 위치를 알아야 함 - 다가오는 장애물들을 피하기 위한 경로 결정 도로 캐시의 갱신 - 도로 캐시는 현재 도로와 다음의 두 도로 구간들로 이루어짐 모든 가능한 경로들의 나열 - 현재의 도로 구간을 주행하는 데 사용할 수 있는 모든 가능한 경로들을 나열

  45. Introduction to Path Finding • A Common Situation of Game AI • Path Planning • From a start position to a destination point • Most Popular Technique • A* (A Star) • 1968 • A search algorithm • Favorite teaching example : 15-puzzle • Algorithm that searches in a state space for the least costly path from start state to a goal state by examining the neighboring states

  46. Dijkstra vs. A* Without ostacale With ostacale By courtesy of : http://theory.stanford.edu/~amitp/GameProgramming/

  47. Dijkstra vs. A* • Dijkstra: compute the optimal solution • Diskstra: search space much larger than A* • A*: simple • A*: fast • A*: “good” result • A*: employ heuristic estimate to eliminate many paths with high costs -> speedup process to compute satisfactory “shortest” paths

  48. A*: cost functions • Goal: compute a path from a start point S to a goal point G • Cost at point n: • f(n) = g(n) + h(n) • g(n): distance from the start point to point n • h(n): estimated distance from point n to the goal point • f(n): current estimated cost for point n

  49. A*: cost functions • The role of h(n) • A major cost evaluation function of A* • Guide the performance of A* d(n): the actual distance between S and G h(n) = 0 : A* is equivalent to Dijkstra algorithm h(n) <= d (n) : guarantee to compute the shortest path; the lower the value h(n), the more node A* expands h(n) = d (n) : follow the best path; never expand anything else; difficult to compute h(n) in this way! h(n) > d(n) : not guarantee to compute a best path; but very fast h(n) >> g(n) : h(n) dominates -> A* becomes the best first search (BSF)

More Related