在Java游戏开发中,XOR(异或)操作有多种用途,主要体现在以下几个方面:
以下是一些简单的Java代码示例,展示了XOR操作在不同场景下的应用:
public class XORCipher {
private static final char KEY = 'K';
public static String encrypt(String str) {
StringBuilder encrypted = new StringBuilder();
for (char ch : str.toCharArray()) {
encrypted.append((char) (ch ^ KEY));
}
return encrypted.toString();
}
public static String decrypt(String str) {
return encrypt(str); // XOR is symmetric
}
public static void main(String[] args) {
String original = "Hello, World!";
String encrypted = encrypt(original);
String decrypted = decrypt(encrypted);
System.out.println("Original: " + original);
System.out.println("Encrypted: " + encrypted);
System.out.println("Decrypted: " + decrypted);
}
}
public class BitMaskExample {
public static void main(String[] args) {
int flags = 0b1010; // 初始状态
// 设置第2位为1
flags |= (1 << 1);
System.out.println(Integer.toBinaryString(flags)); // 输出: 1011
// 清除第3位
flags &= ~(1 << 2);
System.out.println(Integer.toBinaryString(flags)); // 输出: 1011 & ~100 = 1011 & 0111 = 101
// 切换第4位
flags ^= (1 << 3);
System.out.println(Integer.toBinaryString(flags)); // 输出: 101 ^ 1000 = 1101
}
}
public class CollisionDetection {
public static boolean isColliding(int x1, int y1, int width1, int height1,
int x2, int y2, int width2, int height2) {
return (x1 < x2 + width2 && x1 + width1 > x2 &&
y1 < y2 + height2 && y1 + height1 > y2);
}
public static void main(String[] args) {
int x1 = 10, y1 = 10, width1 = 50, height1 = 50;
int x2 = 30, y2 = 30, width2 = 50, height2 = 50;
System.out.println("Collision: " + isColliding(x1, y1, width1, height1, x2, y2, width2, height2));
}
}
通过这些示例可以看出,XOR操作在Java游戏开发中具有广泛的应用,能够简化代码逻辑并提高开发效率。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。