-
Notifications
You must be signed in to change notification settings - Fork 0
/
boa.cpp
77 lines (74 loc) · 2.27 KB
/
boa.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#include "boa.h"
#include "ui_boa.h"
#include <QKeyEvent>
#include <QDebug>
Boa::Boa(QString img) :
Snake(nullptr,img)
{
id=1;
}
Boa::~Boa()
{
delete ui;
}
void Boa::keyPressEvent(QKeyEvent* ev)
{
switch(ev->key())
{
case Qt::Key_W:
turnup();
break;
case Qt::Key_D:
turnright();
break;
case Qt::Key_S:
turndown();
break;
case Qt::Key_A:
turnleft();
break;
}
}
// 人机作战中的AI自动移动
void Boa::automove()
{
double p=rand()%100/100.0;
if(board->get_impedenceid(get_next())>=2||p>0.6||board->get_impedenceid(get_next(2))>=2||board->get_snakeid(get_next())>id||board->get_snakeid(get_next(2))>id)
{
// 当前方有障碍或者随机生成的0-1间数大于0.8时,改变方向
int dir=1;
Xy_pos headpos=snakeBody.front().xy_pos;
Xy_pos up=Xy_pos(headpos.x,headpos.y-1);
Xy_pos down=Xy_pos(headpos.x,headpos.y+1);
Xy_pos right=Xy_pos(headpos.x+1,headpos.y);
Xy_pos left=Xy_pos(headpos.x-1,headpos.y);
//计算随机转向各个方向的概率分布(所有非安全的转向的概率设为0)
int a1=1,a2=1,a3=1,a4=1;
if(board->get_impedenceid(up)>=2||board->get_snakeid(up)>id||direction==3||up.y<0)a1=0;
if(board->get_impedenceid(right)>=2||board->get_snakeid(right)>id||direction==4||right.x>board->width)a2=0;
if(board->get_impedenceid(down)>=2||board->get_snakeid(down)>id||direction==1||down.y>board->height)a3=0;
if(board->get_impedenceid(left)>=2||board->get_snakeid(left)>id||direction==2||left.x<0)a4=0;
int sum=a1+a2+a3+a4;
double randf=rand()%50/49.0;
if(randf<a1/(double)sum)dir=1;
if(randf>a1/(double)sum&&randf<(a1+a2)/(double)sum)dir=2;
if(randf>(a1+a2)/(double)sum&&randf<(a1+a2+a3)/(double)sum)dir=3;
if(randf>(a1+a2+a3)/(double)sum)dir=4;
//qDebug()<<dir;
switch(dir)
{
case 1:
turnup();
break;
case 2:
turnright();
break;
case 3:
turndown();
break;
case 4:
turnleft();
break;
}
}
}