实现简单的吃豆人运行效果:
//114通过上下左右键控制吃豆人的移动
class DrawBeans{
int x;
int y;
int sz, flag;
int forward;
DrawBeans(int x, int y, int sz){
this.x = x;
this.y = y;
this.sz = sz;
flag = 0;
forward = 0;
}
void draw_right(){
forward = 0;
draw_bean(radians(30), radians(330));
draw_eye();
}
void draw_left(){
forward = 2;
draw_bean(radians(210), radians(510));
draw_eye();
}
void draw_up(){
forward = 3;
draw_bean(radians(300), radians(600));
draw_eye();
}
void draw_down(){
forward = 1;
draw_bean(radians(120), radians(420));
draw_eye();
}
void draw_ellipse(){
fill(255, 255, 0);
ellipse(x, y, sz, sz);
draw_eye();
}
void draw_eye(){
fill(0);
if(forward == 0){
ellipse(x+sz/4-4, y-sz/4, 5, 5);
}else if(forward == 1){
ellipse(x+sz/4, y+sz/4 -4, 5, 5);
}else if(forward == 2){
ellipse(x-sz/4+4, y-sz/4, 5, 5);
}else if(forward == 3){
ellipse(x-sz/4, y-sz/4+4, 5, 5);
}
noFill();
fill(255, 255, 0);
}
void draw_bean(float start, float stop){
arc(x, y, sz, sz, start, stop);
fill(255, 255, 0);
}
void move_right(){
if(x+sz/2 == width){
x = width-sz/2;
draw_right();
}else
{
if(flag < 10){
draw_right();
flag+=1;
}else if(flag>=10 && flag <15){
draw_ellipse();
flag+=1;
}else if(flag == 15){
flag = 0;
}
x += 1;
}
}
void move_left(){
if(x-sz/2 == 0){
x = sz/2;
draw_left();
}else
{
if(flag < 10){
draw_left();
flag+=1;
}else if(flag>=10 && flag <15){
draw_ellipse();
flag+=1;
}else if(flag == 15){
flag = 0;
}
x -= 1;
}
}
void move_up(){
if(y == sz/2){
y = sz/2;
draw_up();
}else
{
if(flag < 10){
draw_up();
flag+=1;
}else if(flag>=10 && flag <15){
draw_ellipse();
flag+=1;
}else if(flag == 15){
flag = 0;
}
y-= 1;
}
}
void move_down(){
if(y+sz/2 == height){
y = height-sz/2;
draw_down();
}else
{
if(flag < 10){
draw_down();
flag+=1;
}else if(flag>=10 && flag <15){
draw_ellipse();
flag+=1;
}else if(flag == 15){
flag = 0;
}
y += 1;
}
}
void draw_default(){
if(forward == 0)
move_right();
else if(forward == 1)
move_down();
else if(forward == 2)
move_left();
else if(forward == 3)
move_up();
}
};
DrawBeans db;
void setup(){
db = new DrawBeans(100, 100, 40);
size(640, 480);
noStroke();
smooth();
frameRate(120);
}
void draw(){
background(120);
if(keyPressed && key == CODED){
if(keyCode == RIGHT){
db.move_right();
}else if(keyCode == DOWN){
db.move_down();
}else if(keyCode == LEFT){
db.move_left();
}else if(keyCode == UP){
db.move_up();
}
}
else{
db.draw_default();
}
}
程序运行结果:
函数使用说明:
通过前面的简单代码就可以实现吃豆人的移动,类成员函数和成员变量还需要进行修改优化
版权声明:本文为Ant_look原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。