classname
stringlengths 3
26
| id
stringlengths 27
50
| original_code
stringlengths 1.08k
59.9k
| num_file
int64 2
14
| num_line
int64 32
1.88k
| Programming Language
stringclasses 3
values |
---|---|---|---|---|---|
emailgenerator | ./ProjectTest/Java/emailgenerator.java | // emailgenerator/EmailApp.java
package projecttest.emailgenerator;
import com.sun.security.jgss.GSSUtil;
import java.sql.SQLOutput;
import java.util.Scanner;
public class EmailApp {
public static void main(String[] args) {
System.out.println("Generate Organization's Email ==>");
Scanner sc=new Scanner(System.in);
// String x=sc.nextLine();
System.out.println("Generating the email...");
System.out.println("Enter firstname :");
String first=sc.nextLine();
System.out.println("Enter Lastname :");
String second=sc.nextLine();
Email em=new Email(first,second);
while(true) {
System.out.println("1 : Information ");
System.out.println("2 : Change Email");
System.out.println("3 : Change Password");
System.out.println("4 : Disclose Password");
System.out.println("5 : Exit");
System.out.println("Enter operation code :");
int a = sc.nextInt();
switch (a) {
case 1:
System.out.println(em.showInfo());
break;
case 2:
System.out.println("Enter alternate email prefix :");
sc.nextLine();
String alt = sc.nextLine();
em.setEmail(alt+"@drngpit.ac.in");
break;
case 3:
System.out.println("Enter the verification code :");
sc.nextLine();
String s = sc.nextLine();
if (s.equals(em.getVcode())) {
System.out.println("Enter alternate password :");
String p = sc.nextLine();
em.setPassword(p);
} else {
System.out.println("Please Enter valid verification code !!!");
}
System.out.println("Password updated successfully !!!");
break;
case 4:
System.out.println("Password disclose warning !!!");
System.out.println("Enter the verification code :");
sc.nextLine();
String s1 = sc.nextLine();
if (s1.equals(em.getVcode())) {
System.out.println("Your password : " + em.getPassword());
} else {
System.out.println("Please Enter valid verification code !!!");
}
case 5:
System.out.println("Have a great day ahead ! BYE ");
return ;
}
}
}
}
// emailgenerator/Email.java
package projecttest.emailgenerator;
import java.util.Scanner;
public class Email {
private String firstName;
private String lastName;
private String password;
private String department;
private String email;
private int defaultPasswordLength=8;
private int codelen=5;
private String Vcode;
private String company="drngpit.ac.in";
private String name;
public Email(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
System.out.println("Kindly ! Enter department for email creation dear "+this.firstName+" "+this.lastName);
//dept
this.department=setDepartment();
System.out.println("Department:"+department);
//pass
this.password=randomPass(defaultPasswordLength);
System.out.println("New Password :"+password);
//clipping name as one
this.name=firstName+lastName;
//verification code
this.Vcode=vcode(codelen);
System.out.println("Your verification code : "+Vcode);
//Binding
email=name.toLowerCase()+"."+department+"@"+company;
System.out.println("Official mail :"+email);
}
private String setDepartment(){
System.out.println("Enter the department Id\nSales : 1\nDevelopment : 2\nAccounting : 3");
Scanner in=new Scanner(System.in);
int dep=in.nextInt();
if(dep==1){
return "sales";
}
else if(dep==2){
return"dev";
}
else if(dep==3){
return "acc";
}
return"";
}
private String randomPass(int length){
String password="ABCEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%";
char[]pass=new char[length];
for(int i=0;i<length;i++){
int rand=(int)(Math.random()*password.length());
pass[i]=password.charAt(rand);
}
return new String(pass);
}
private String vcode(int codelen){
String samcode="1234567890";
char[]code=new char[codelen];
for(int i=0;i<codelen;i++){
int c=(int)(Math.random()*samcode.length());
code[i]=samcode.charAt(c);
}
return new String(code);
}
public void setPassword(String password) {
this.password = password;
}
public String getDepartment() {
return department;
}
public void setDepartment(String department) {
this.department = department;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword(){
return password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getVcode() {
return Vcode;
}
public String getDept(String dep){
if(dep.equals("dev")){
return "Developers";
}
else if(dep.equals("acc")){
return "Accounts";
}
else if(dep.equals("sales")){
return "Sales";
}
return "";
}
public String showInfo(){
return "Name : "+name+"\nOfficial email : "+email+"\nDepartment : "+getDept(department);
}
}
| 2 | 194 | Java |
heap | ./ProjectTest/Java/heap.java | // heap/LeftistHeap.java
package projecttest.heap;
import java.util.ArrayList;
/*
* This is a leftist heap that follows the same operations as a
* binary min heap, but may be unbalanced at times and follows a
* leftist property, in which the left side is more heavy on the
* right based on the null-path length (npl) values.
*
* Source: https://iq.opengenus.org/leftist-heap/
*
*/
public class LeftistHeap {
private class Node {
private int element, npl;
private Node left, right;
// Node constructor setting the data element and left/right pointers to null
private Node(int element) {
this.element = element;
left = right = null;
npl = 0;
}
}
private Node root;
// Constructor
public LeftistHeap() {
root = null;
}
// Checks if heap is empty
public boolean isEmpty() {
return root == null;
}
// Resets structure to initial state
public void clear() {
// We will put head is null
root = null;
}
// Merge function that merges the contents of another leftist heap with the
// current one
public void merge(LeftistHeap h1) {
// If the present function is rhs then we ignore the merge
root = merge(root, h1.root);
h1.root = null;
}
// Function merge with two Nodes a and b
public Node merge(Node a, Node b) {
if (a == null) return b;
if (b == null) return a;
// Violates leftist property, so must do a swap
if (a.element > b.element) {
Node temp = a;
a = b;
b = temp;
}
// Now we call the function merge to merge a and b
a.right = merge(a.right, b);
// Violates leftist property so must swap here
if (a.left == null) {
a.left = a.right;
a.right = null;
} else {
if (a.left.npl < a.right.npl) {
Node temp = a.left;
a.left = a.right;
a.right = temp;
}
a.npl = a.right.npl + 1;
}
return a;
}
// Function insert. Uses the merge function to add the data
public void insert(int a) {
root = merge(new Node(a), root);
}
// Returns and removes the minimum element in the heap
public int extract_min() {
// If is empty return -1
if (isEmpty()) return -1;
int min = root.element;
root = merge(root.left, root.right);
return min;
}
// Function returning a list of an in order traversal of the data structure
public ArrayList<Integer> in_order() {
ArrayList<Integer> lst = new ArrayList<>();
in_order_aux(root, lst);
return new ArrayList<>(lst);
}
// Auxiliary function for in_order
private void in_order_aux(Node n, ArrayList<Integer> lst) {
if (n == null) return;
in_order_aux(n.left, lst);
lst.add(n.element);
in_order_aux(n.right, lst);
}
}
// heap/FibonacciHeap.java
package projecttest.heap;
public class FibonacciHeap {
private static final double GOLDEN_RATIO = (1 + Math.sqrt(5)) / 2;
private HeapNode min;
private static int totalLinks = 0;
private static int totalCuts = 0;
private int numOfTrees = 0;
private int numOfHeapNodes = 0;
private int markedHeapNoodesCounter = 0;
/*
* a constructor for an empty Heap
* set the min to be null
*/
public FibonacciHeap() {
this.min = null;
}
/*
* a constructor for a Heap with one element
* set the min to be the HeapNode with the given key
* @pre key>=0
* @post empty == false
*/
public FibonacciHeap(int key) {
this.min = new HeapNode(key);
this.numOfTrees++;
this.numOfHeapNodes++;
}
/*
* check if the heap is empty
* $ret == true - if the tree is empty
*/
public boolean empty() {
return (this.min == null);
}
/**
* Creates a node (of type HeapNode) which contains the given key, and inserts it into the heap.
*
* @pre key>=0
* @post (numOfnodes = = $prev numOfnodes + 1)
* @post empty == false
* $ret = the HeapNode we inserted
*/
public HeapNode insert(int key) {
HeapNode toInsert = new HeapNode(key); // creates the node
if (this.empty()) {
this.min = toInsert;
} else { // tree is not empty
min.setNext(toInsert);
this.updateMin(toInsert);
}
this.numOfHeapNodes++;
this.numOfTrees++;
return toInsert;
}
/**
* Delete the node containing the minimum key in the heap
* updates new min
*
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void deleteMin() {
if (this.empty()) {
return;
}
if (this.numOfHeapNodes == 1) { // if there is only one tree
this.min = null;
this.numOfTrees--;
this.numOfHeapNodes--;
return;
}
// change all children's parent to null//
if (this.min.child != null) { // min has a child
HeapNode child = this.min.child;
HeapNode tmpChild = child;
child.parent = null;
while (child.next != tmpChild) {
child = child.next;
child.parent = null;
}
}
// delete the node//
if (this.numOfTrees > 1) {
(this.min.prev).next = this.min.next;
(this.min.next).prev = this.min.prev;
if (this.min.child != null) {
(this.min.prev).setNext(this.min.child);
}
} else { // this.numOfTrees = 1
this.min = this.min.child;
}
this.numOfHeapNodes--;
this.successiveLink(this.min.getNext());
}
/**
* Return the node of the heap whose key is minimal.
* $ret == null if (empty==true)
*/
public HeapNode findMin() {
return this.min;
}
/**
* Meld the heap with heap2
*
* @pre heap2 != null
* @post (numOfnodes = = $prev numOfnodes + heap2.numOfnodes)
*/
public void meld(FibonacciHeap heap2) {
if (heap2.empty()) {
return;
}
if (this.empty()) {
this.min = heap2.min;
} else {
this.min.setNext(heap2.min);
this.updateMin(heap2.min);
}
this.numOfTrees += heap2.numOfTrees;
this.numOfHeapNodes += heap2.numOfHeapNodes;
}
/**
* Return the number of elements in the heap
* $ret == 0 if heap is empty
*/
public int size() {
return this.numOfHeapNodes;
}
/**
* Return a counters array, where the value of the i-th index is the number of trees with rank i
* in the heap. returns an empty array for an empty heap
*/
public int[] countersRep() {
if (this.empty()) {
return new int[0]; /// return an empty array
}
int[] rankArray = new int[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1]; // creates the array
rankArray[this.min.rank]++;
HeapNode curr = this.min.next;
while (curr != this.min) {
rankArray[curr.rank]++;
curr = curr.next;
}
return rankArray;
}
/**
* Deletes the node x from the heap (using decreaseKey(x) to -1)
*
* @pre heap contains x
* @post (numOfnodes = = $prev numOfnodes - 1)
*/
public void delete(HeapNode x) {
this.decreaseKey(x, x.getKey() + 1); // change key to be the minimal (-1)
this.deleteMin(); // delete it
}
/**
* The function decreases the key of the node x by delta.
*
* @pre x.key >= delta (we don't realize it when calling from delete())
* @pre heap contains x
*/
private void decreaseKey(HeapNode x, int delta) {
int newKey = x.getKey() - delta;
x.key = newKey;
if (x.isRoot()) { // no parent to x
this.updateMin(x);
return;
}
if (x.getKey() >= x.parent.getKey()) {
return;
} // we don't need to cut
HeapNode prevParent = x.parent;
this.cut(x);
this.cascadingCuts(prevParent);
}
/**
* returns the current potential of the heap, which is:
* Potential = #trees + 2*#markedNodes
*/
public int potential() {
return numOfTrees + (2 * markedHeapNoodesCounter);
}
/**
* This static function returns the total number of link operations made during the run-time of
* the program. A link operation is the operation which gets as input two trees of the same
* rank, and generates a tree of rank bigger by one.
*/
public static int totalLinks() {
return totalLinks;
}
/**
* This static function returns the total number of cut operations made during the run-time of
* the program. A cut operation is the operation which disconnects a subtree from its parent
* (during decreaseKey/delete methods).
*/
public static int totalCuts() {
return totalCuts;
}
/*
* updates the min of the heap (if needed)
* @pre this.min == @param (posMin) if and only if (posMin.key < this.min.key)
*/
private void updateMin(HeapNode posMin) {
if (posMin.getKey() < this.min.getKey()) {
this.min = posMin;
}
}
/*
* Recursively "runs" all the way up from @param (curr) and mark the nodes.
* stop the recursion if we had arrived to a marked node or to a root.
* if we arrived to a marked node, we cut it and continue recursively.
* called after a node was cut.
* @post (numOfnodes == $prev numOfnodes)
*/
private void cascadingCuts(HeapNode curr) {
if (!curr.isMarked()) { // stop the recursion
curr.mark();
if (!curr.isRoot()) this.markedHeapNoodesCounter++;
} else {
if (curr.isRoot()) {
return;
}
HeapNode prevParent = curr.parent;
this.cut(curr);
this.cascadingCuts(prevParent);
}
}
/*
* cut a node (and his "subtree") from his origin tree and connect it to the heap as a new tree.
* called after a node was cut.
* @post (numOfnodes == $prev numOfnodes)
*/
private void cut(HeapNode curr) {
curr.parent.rank--;
if (curr.marked) {
this.markedHeapNoodesCounter--;
curr.marked = false;
}
if (curr.parent.child == curr) { // we should change the parent's child
if (curr.next == curr) { // curr do not have brothers
curr.parent.child = null;
} else { // curr have brothers
curr.parent.child = curr.next;
}
}
curr.prev.next = curr.next;
curr.next.prev = curr.prev;
curr.next = curr;
curr.prev = curr;
curr.parent = null;
this.min.setNext(curr);
this.updateMin(curr);
this.numOfTrees++;
totalCuts++;
}
/*
*
*/
private void successiveLink(HeapNode curr) {
HeapNode[] buckets = this.toBuckets(curr);
this.min = this.fromBuckets(buckets);
}
/*
*
*/
private HeapNode[] toBuckets(HeapNode curr) {
HeapNode[] buckets = new HeapNode[(int) Math.floor(Math.log(this.size()) / Math.log(GOLDEN_RATIO)) + 1];
curr.prev.next = null;
HeapNode tmpCurr;
while (curr != null) {
tmpCurr = curr;
curr = curr.next;
tmpCurr.next = tmpCurr;
tmpCurr.prev = tmpCurr;
while (buckets[tmpCurr.rank] != null) {
tmpCurr = this.link(tmpCurr, buckets[tmpCurr.rank]);
buckets[tmpCurr.rank - 1] = null;
}
buckets[tmpCurr.rank] = tmpCurr;
}
return buckets;
}
/*
*
*/
private HeapNode fromBuckets(HeapNode[] buckets) {
HeapNode tmpMin = null;
this.numOfTrees = 0;
for (int i = 0; i < buckets.length; i++) {
if (buckets[i] != null) {
this.numOfTrees++;
if (tmpMin == null) {
tmpMin = buckets[i];
tmpMin.next = tmpMin;
tmpMin.prev = tmpMin;
} else {
tmpMin.setNext(buckets[i]);
if (buckets[i].getKey() < tmpMin.getKey()) {
tmpMin = buckets[i];
}
}
}
}
return tmpMin;
}
/*
* link between two nodes (and their trees)
* defines the smaller node to be the parent
*/
private HeapNode link(HeapNode c1, HeapNode c2) {
if (c1.getKey() > c2.getKey()) {
HeapNode c3 = c1;
c1 = c2;
c2 = c3;
}
if (c1.child == null) {
c1.child = c2;
} else {
c1.child.setNext(c2);
}
c2.parent = c1;
c1.rank++;
totalLinks++;
return c1;
}
/**
* public class HeapNode
* each HeapNode belongs to a heap (Inner class)
*/
public class HeapNode {
public int key;
private int rank;
private boolean marked;
private HeapNode child;
private HeapNode next;
private HeapNode prev;
private HeapNode parent;
/*
* a constructor for a heapNode withe key @param (key)
* prev == next == this
* parent == child == null
*/
public HeapNode(int key) {
this.key = key;
this.marked = false;
this.next = this;
this.prev = this;
}
/*
* returns the key of the node.
*/
public int getKey() {
return this.key;
}
/*
* checks whether the node is marked
* $ret = true if one child has been cut
*/
private boolean isMarked() {
return this.marked;
}
/*
* mark a node (after a child was cut)
* @inv root.mark() == false.
*/
private void mark() {
if (this.isRoot()) {
return;
} // check if the node is a root
this.marked = true;
}
/*
* add the node @param (newNext) to be between this and this.next
* works fine also if @param (newNext) does not "stands" alone
*/
private void setNext(HeapNode newNext) {
HeapNode tmpNext = this.next;
this.next = newNext;
this.next.prev.next = tmpNext;
tmpNext.prev = newNext.prev;
this.next.prev = this;
}
/*
* returns the next node to this node
*/
private HeapNode getNext() {
return this.next;
}
/*
* check if the node is a root
* root definition - this.parent == null (uppest in his tree)
*/
private boolean isRoot() {
return (this.parent == null);
}
}
}
// heap/HeapPerformanceTest.java
package projecttest.heap;
import java.util.HashMap;
import java.util.Random;
import java.util.ArrayList;
public class HeapPerformanceTest {
private final int numElements;
public HeapPerformanceTest(int numElements) {
this.numElements = numElements;
}
public HashMap<String, Long> test() {
// Number of elements to test
// Create heaps for insertion and deletion tests
FibonacciHeap fibonacciHeap = new FibonacciHeap();
LeftistHeap leftistHeap = new LeftistHeap();
HashMap<String, Long> ret = new HashMap<>();
// Insertion test
long startTime = System.currentTimeMillis();
for (int i = 0; i < numElements; i++) {
fibonacciHeap.insert(new Random().nextInt());
}
long endTime = System.currentTimeMillis();
ret.put("Fibonacci Heap Insertion Time", endTime - startTime);
startTime = System.currentTimeMillis();
for (int i = 0; i < numElements; i++) {
leftistHeap.insert(new Random().nextInt());
}
endTime = System.currentTimeMillis();
ret.put("Leftist Heap Insertion Time", endTime - startTime);
// Deletion test
startTime = System.currentTimeMillis();
while (!fibonacciHeap.empty()) {
fibonacciHeap.deleteMin();
}
endTime = System.currentTimeMillis();
ret.put("Fibonacci Heap Deletion Time", endTime - startTime);
startTime = System.currentTimeMillis();
while (!leftistHeap.isEmpty()) {
leftistHeap.extract_min();
}
endTime = System.currentTimeMillis();
ret.put("Leftist Heap Deletion Time", endTime - startTime);
// Merge test
FibonacciHeap fibonacciHeap1 = new FibonacciHeap();
FibonacciHeap fibonacciHeap2 = new FibonacciHeap();
LeftistHeap leftistHeap1 = new LeftistHeap();
LeftistHeap leftistHeap2 = new LeftistHeap();
// Populate the heaps for merge test
for (int i = 0; i < numElements / 2; i++) {
fibonacciHeap1.insert(new Random().nextInt());
fibonacciHeap2.insert(new Random().nextInt());
leftistHeap1.insert(new Random().nextInt());
leftistHeap2.insert(new Random().nextInt());
}
// Merge performance test
startTime = System.currentTimeMillis();
fibonacciHeap1.meld(fibonacciHeap2);
endTime = System.currentTimeMillis();
ret.put("Fibonacci Heap Merge Time", endTime - startTime);
startTime = System.currentTimeMillis();
leftistHeap1.merge(leftistHeap2);
endTime = System.currentTimeMillis();
ret.put("Leftist Heap Merge Time", endTime - startTime);
return ret;
}
public static void main(String[] args){
int numElements = Integer.parseInt(args[0]);
HeapPerformanceTest t = new HeapPerformanceTest(numElements);
HashMap<String, Long> ret = t.test();
for (String key : ret.keySet()) {
System.out.println(key + ": " + ret.get(key) + "ms");
}
}
}
| 3 | 629 | Java |
servlet | ./ProjectTest/Java/servlet.java | // servlet/registration.java
package projecttest.servlet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class registration extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String f=request.getParameter("fname");
String c=request.getParameter("cardno");
String cn=request.getParameter("cono");
String ad=request.getParameter("add");
String dob=request.getParameter("dob");
String email=request.getParameter("email");
String pin=request.getParameter("pin");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/votingdb","Vaishnavi","Nelavetla@537");
PreparedStatement ps=con.prepareStatement("insert into register values(?,?,?,?,?,?,?)");
ps.setString(1,f);
ps.setString(2,c);
ps.setString(3,cn);
ps.setString(4,ad);
ps.setString(5,dob);
ps.setString(6,email);
ps.setString(7,pin);
int i=ps.executeUpdate();
if(i>0)
{
out.print("Successfully your account has been created...PLEASE LOGIN");
RequestDispatcher rd=request.getRequestDispatcher("loginpage.html");
rd.include(request,response);
}
else
{
out.print("Failed account creation try again");
RequestDispatcher rd=request.getRequestDispatcher("registration.html");
rd.include(request,response);
}
}
catch (Exception e2) {
out.print("Invalid , Failed account creation try again "+e2);
RequestDispatcher rd=request.getRequestDispatcher("registration.html");
rd.include(request,response);
}
out.close();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
}
}
// servlet/loginpage.java
package projecttest.servlet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class loginpage extends HttpServlet {
private static final long serialVersionUID = 1L;
final static Connection con=DBUtilR.getDBConnection();
static PreparedStatement ps = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter out = response.getWriter();
String card=request.getParameter("cardno");
Integer pin=Integer.parseInt(request.getParameter("pin"));
try {
if(check(card,pin))
{
out.print("Successful Login...You Can Vote Now");
RequestDispatcher rd=request.getRequestDispatcher("vote.html");
rd.include(request,response);
}
else {
out.print("Sorry username or password error , Make new account");
RequestDispatcher rd=request.getRequestDispatcher("registration.html");
rd.include(request,response);
}
}
catch (SQLException e) {
e.printStackTrace();
}
}
static boolean check(String card,Integer pin) throws SQLException
{
boolean r=false;
ps=con.prepareStatement("Select * from register where cardno=? and pin=?");
ps.setString(1,card);
ps.setInt(2,pin);
ResultSet rs=ps.executeQuery();
r=rs.next();
return r;
}
static boolean checkvote(String card) throws SQLException
{
boolean r=false;
ps=con.prepareStatement("Select * from vote where cardno=?");
ps.setString(1,card);
ResultSet rs=ps.executeQuery();
r=rs.next();
return r;
}
}
// servlet/againvote.java
package projecttest.servlet;
import java.io.IOException;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
public class againvote extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doGet(request, response);
}
}
// servlet/thankyou.java
package projecttest.servlet;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
public class thankyou extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
}
}
// servlet/DBUtilR.java
package projecttest.servlet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBUtilR {
static Connection conn = null;
static
{
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/votingdb", "Vaishnavi", "Nelavetla@537");
if(!conn.isClosed()) {
System.out.println("Connection established");
}
} catch (ClassNotFoundException | SQLException e) {
System.out.println("Error in DBUtilFile");
e.printStackTrace();
}
}
public static Connection getDBConnection() {
// TODO Auto-generated method stub
return conn;
}
}
// servlet/vote.java
package projecttest.servlet;
import jakarta.servlet.RequestDispatcher;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
public class vote extends HttpServlet {
private static final long serialVersionUID = 1L;
final static Connection con=DBUtilR.getDBConnection();
static PreparedStatement ps = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String f=request.getParameter("cardno");
String l=request.getParameter("party");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/votingdb","Vaishnavi","Nelavetla@537");
if(checkLogin(f))
{
ps=con.prepareStatement("insert into vote values(?,?)");
ps.setString(1,f);
ps.setString(2,l);
int i=ps.executeUpdate();
if(i>0)
{
out.print("Your Vote has been submitted successfully...");
RequestDispatcher rd=request.getRequestDispatcher("thankyou.html");
rd.include(request,response);
}
else
{
out.print("Failed to submit vote, try again");
RequestDispatcher rd=request.getRequestDispatcher("vote.html");
rd.include(request,response);
}
}
else
{
out.print("Please enter correct card number");
RequestDispatcher rd=request.getRequestDispatcher("vote.html");
rd.include(request,response);
}
}
catch (SQLIntegrityConstraintViolationException e2) {
out.print("Please select any party");
RequestDispatcher rd=request.getRequestDispatcher("vote.html");
rd.include(request,response);
}
catch(Exception e)
{
out.print(" " +e);
RequestDispatcher rd=request.getRequestDispatcher("vote.html");
rd.include(request,response);
}
out.close();
}
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
static boolean checkLogin(String card) throws SQLException
{
boolean r=false;
ps=con.prepareStatement("Select * from register where cardno = ?");
ps.setString(1,card);
ResultSet rs=ps.executeQuery();
r=rs.next();
return r;
}
}
| 6 | 308 | Java |
libraryApp | ./ProjectTest/Java/libraryApp.java | // libraryApp/Book.java
package projecttest.libraryApp;
public class Book {
private int isbn;
private String title;
private String author;
private String genre;
private int quantity;
private int checkedOut;
private int checkedIn;
//Constructor for book object
public Book(int isbn, String title, String author, String genre, int quantity, int checkedOut) {
this.isbn = isbn;
this.title = title;
this.author = author;
this.genre = genre;
this.quantity = quantity;
this.checkedOut = checkedOut;
this.checkedIn = quantity-checkedOut;
}
public int getCheckedIn() {
return checkedIn;
}
public void setCheckedIn(int checkedIn) {
this.checkedIn = checkedIn;
}
public void setIsbn(int isbn) {
this.isbn = isbn;
}
public void setTitle(String title) {
this.title = title;
}
public void setAuthor(String author) {
this.author = author;
}
public void setGenre(String genre) {
this.genre = genre;
}
public void setQuantity(int quantity) {
this.quantity = quantity;
}
public void setCheckedOut(int checkedOut) {
this.checkedOut = checkedOut;
}
//Getter Methods
public int getIsbn() {
return isbn;
}
public String getTitle() {
return title;
}
public String getAuthor() {
return author;
}
public String getGenre() {
return genre;
}
public int getQuantity() {
return quantity;
}
public int getCheckedOut() {
return checkedOut;
}
}
// libraryApp/LibraryApp.java
package projecttest.libraryApp;
public class LibraryApp {
BookRepository repo = new BookRepository();
public void findByTitle(String title) {
repo.searchByTitle(title);
return;
}
public void findByISBN(int isbn) {
repo.searchByISBN(isbn);
return;
}
public boolean findByGenre(String genre) {
if(repo.searchByGenre(genre))
return true;
else
return false;
}
public int findISBN(int isbn) {
return repo.searchISBN(isbn);
}
public boolean withdrawBook(int isbn) {
return repo.getBook(isbn);
}
public boolean depositBook(int isbn) {
return repo.submitBook(isbn);
}
public void getStatus(int isbn) {
repo.bookStatus(isbn);
}
}
// libraryApp/Main.java
package projecttest.libraryApp;
import java.util.Scanner;
public class Main{
static Scanner scan = new Scanner(System.in);
static LibraryApp app = new LibraryApp();
public static void main(String[] args) {
int userChoice=0;
System.out.println("-----Welcome to the Library!-----\n");
do{
System.out.println("\n-----------------------------------");
System.out.println("1. Search book by Title keyword.");
System.out.println("2. Search book by ISBN number.");
System.out.println("3. Search book by Genre.");
System.out.println("4. Book Check In");
System.out.println("5. Book Check Out");
System.out.println("6. Exit from the library.");
System.out.println("-----------------------------------");
System.out.print("\nChoose any option: ");
userChoice = scan.nextInt();
scan.nextLine();
switch(userChoice){
case 1:
System.out.print("Enter the Title of Book: ");
app.findByTitle(scan.nextLine());
break;
case 2:
System.out.println("Enter ISBN number: ");
app.findByISBN(scan.nextInt());
break;
case 3:
System.out.println("Enter Genre: ");
app.findByGenre(scan.nextLine());
break;
case 4:
checkIn();
break;
case 5:
checkOut();
break;
case 6:
System.out.println("\nThanks for visiting. \nSee you again.");
break;
default:
System.out.println("\nInvalid Choice!");
}
}while(userChoice!=6);
}
//Checking book In
private static void checkIn() {
System.out.println("Enter Book's ISBN number : ");
int isbnNum = scan.nextInt();
getStatus(isbnNum);
int bookAvailable = app.findISBN(isbnNum);
if(bookAvailable==1) {
System.out.println(isbnNum);
app.withdrawBook(isbnNum);
System.out.println("Book CheckIn successful.");
getStatus(isbnNum);
}
else
System.out.printf("Book with %d ISBN number not Found in inventory.",isbnNum);
}
//Checking book Out
private static void checkOut() {
System.out.println("\nEnter Book's ISBN number : ");
int isbnNum = scan.nextInt();
int bookAvailable = app.findISBN(isbnNum);
if(bookAvailable==1) {
if(app.depositBook(isbnNum))
System.out.println("Book CheckOut successful.");
else
System.out.println("No Space for more Books.");
}
else
System.out.printf("Book with %d ISBN number not Found in inventory.",isbnNum);
}
private static void getStatus(int isbn) {
app.getStatus(isbn);
}
}
// libraryApp/BookRepository.java
package projecttest.libraryApp;
import java.util.ArrayList;
public class BookRepository {
private ArrayList<Book> books = new ArrayList<>();
private int booksFound = 0;
//Constructor to initialize books
public BookRepository(){
books.add(new Book(253910,"Pride and Prejudice C", "Jane Austen", "Love",10,7));
books.add(new Book(391520,"Programming in ANSI C", "E. Balagurusamy", "Educational",15,10));
books.add(new Book(715332,"Shrimad Bhagavad Gita", "Krishna Dvaipayana", "Motivational",20,18));
books.add(new Book(935141,"Java: The Complete Reference", "Herbert Schildt", "Educational",12,9));
books.add(new Book(459901,"It", "Stephan King", "Horror",7,5));
books.add(new Book(855141,"Disneyland", "Mickey & Minnie", "Love",10,3));
}
//Searching books by Title Keyword
public void searchByTitle(String title) {
booksFound = 0;
for(Book book : books) {
String bookTitle = book.getTitle();
if(bookTitle.toLowerCase().contains(title.toLowerCase())) {
bookDetails(book);
booksFound++;
}
}
System.out.printf("\n%d Book%s Found.\n",booksFound,booksFound>1?"s":"");
return;
}
//Searching books by ISBN Number
public void searchByISBN(int isbn) {
booksFound = 0;
for(Book book : books) {
if(book.getIsbn()==isbn) {
bookDetails(book);
booksFound++;
break;
}
}
System.out.printf("\n%d Book%s Found.\n",booksFound,booksFound>1?"s":"");
return;
}
//Searching books by Genre
public boolean searchByGenre(String genre){
booksFound = 0;
for(Book book : books) {
String bookGenre = book.getGenre();
if(bookGenre.toLowerCase().equals(genre.toLowerCase())) {
bookDetails(book);
booksFound++;
}
}
System.out.printf("\n%d Book%s Found.\n",booksFound,booksFound>1?"s":"");
if(booksFound>0)
return true;
else
return false;
}
// Display Book Details
public void bookDetails(Book book) {
System.out.println("\n+> Book details: \n");
System.out.println("\tTitle: "+book.getTitle()+"\n\tAuthor: "+ book.getAuthor()+"\n\tGenre: "+book.getGenre()+"\n\tISBN: "+book.getIsbn()+"\n\tQuantity: "+book.getQuantity()+"\n\tChecked Out: "+String.valueOf(book.getCheckedOut())+"\n\tAvailable: "+String.valueOf(book.getQuantity()-book.getCheckedOut()));
}
//Searching for ISBN number for checkIn and checkOut
public int searchISBN(int isbn) {
for(Book book:books)
if(book.getIsbn()==isbn)
return 1;
return 0;
}
//withdrawing book
public boolean getBook(int isbn) {
for(Book book: books) {
if(book.getIsbn()==isbn) {
if((book.getQuantity()-book.getCheckedOut())>0) {
book.setCheckedOut(book.getCheckedOut()+1);
return true;
}
}
}
return false;
}
//submitting book
public boolean submitBook(int isbn) {
for(Book book: books) {
if(book.getQuantity()>book.getCheckedIn()) {
book.setCheckedOut(book.getCheckedOut()-1);
return true;
}
}
return false;
}
//Showing status of book
public void bookStatus(int isbn) {
for(Book book: books) {
if(book.getIsbn()==isbn) {
bookDetails(book);
break;
}
}
}
}
| 4 | 340 | Java |
libraryManagement | ./ProjectTest/Java/libraryManagement.java | // libraryManagement/LibFunctions.java
package projecttest.libraryManagement;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Scanner;
public class LibFunctions {
public static void callIssueMenu() {
System.out.println("Reached inside issue book menu");
Member m = new Member();
Book b = new Book();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println("Enter the member id ");
m.setMemberId(Integer.parseInt(sc.nextLine().toString()));
System.out.println("Enter the isbn code ");
b.setIsbnCode(sc.nextLine().toString());
issueBook(m, b);
addStatus = 1;
} catch (Exception e) {
addStatus = 0;
}
}
}
public static void issueBook(Member m, Book b) {
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = null;
String qry = "select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\n"
+ "where m.member_id= " + m.getMemberId() + " \n"
+ "and b.isbn_code = '" + b.getIsbnCode() + "' \n"
+ "and m.member_id=mbr.member_id\n"
+ "and b.isbn_code=mbr.isbn_code and mbr.dor is null ";
rs=stmt.executeQuery(qry);
if (rs.next()) {
System.out.println("The book is already issued and cannot be issued again");
} else {
int k = stmt.executeUpdate("insert into member_book_record values(lib_seq.nextval," + m.getMemberId() + ",'" + b.getIsbnCode() + "',sysdate,null)");
if(k > 0){
k = stmt.executeUpdate("update books set units_available= (units_available-1) where isbn_code = '"+ b.getIsbnCode() +"' ");
conn.commit();
System.out.println("The book is issued successfully");
}else{
conn.rollback();
}
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void callReturnMenu() {
System.out.println("Reached inside return book menu");
Member m = new Member();
Book b = new Book();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println("Enter the member id ");
m.setMemberId(Integer.parseInt(sc.nextLine().toString()));
System.out.println("Enter the isbn code ");
b.setIsbnCode(sc.nextLine().toString());
returnBook(m, b);
addStatus = 1;
} catch (Exception e) {
addStatus = 0;
}
}
}
public static void returnBook(Member m, Book b) {
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
ResultSet rs = null;
String qry = "select m.member_id, b.isbn_code, mbr.rec_id from members m,books b,member_book_record mbr\n"
+ "where m.member_id= " + m.getMemberId() + " \n"
+ "and b.isbn_code = '" + b.getIsbnCode() + "' \n"
+ "and m.member_id=mbr.member_id\n"
+ "and b.isbn_code=mbr.isbn_code and mbr.dor is null ";
rs=stmt.executeQuery(qry);
if (rs.next()) {
Integer recId= rs.getInt(3);
System.out.println("The book is already issued and starting the process to return ");
int k = stmt.executeUpdate("update books set units_available= (units_available+1) where isbn_code = '"+ b.getIsbnCode() +"' ");
if(k > 0){
k = stmt.executeUpdate("update member_book_record set dor= sysdate where rec_id = "+ recId +" ");
conn.commit();
System.out.println("The book is returned successfully");
}else{
conn.rollback();
}
} else{
System.out.println("This book is not issued for the user");
}
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
// libraryManagement/Member.java
package projecttest.libraryManagement;
import java.sql.Date;
/**
*
* @author testuser
*/
public class Member {
private Integer memberId;
private String memberName;
private Date dateOfJoining;
public Member() {
}
public Member(Integer memberId, String memberName, Date dateOfJoining) {
this.memberId = memberId;
this.memberName = memberName;
this.dateOfJoining = dateOfJoining;
}
public Date getDateOfJoining() {
return dateOfJoining;
}
public void setDateOfJoining(Date dateOfJoining) {
this.dateOfJoining = dateOfJoining;
}
public Integer getMemberId() {
return memberId;
}
public void setMemberId(Integer memberId) {
this.memberId = memberId;
}
public String getMemberName() {
return memberName;
}
public void setMemberName(String memberName) {
this.memberName = memberName;
}
}
// libraryManagement/Book.java
package projecttest.libraryManagement;
/**
*
* @author testuser
*/
public class Book {
private String isbnCode;
private String bookName;
private String bookDesc;
private String authorName;
private String subjectName;
private Integer unitsAvailable;
public Book(){
}
public Book(String isbnCode, String bookName, String bookDesc, String authorName, String subjectName, Integer unitsAvailable) {
this.isbnCode = isbnCode;
this.bookName = bookName;
this.bookDesc = bookDesc;
this.authorName = authorName;
this.subjectName = subjectName;
this.unitsAvailable = unitsAvailable;
}
public Integer getUnitsAvailable() {
return unitsAvailable;
}
public void setUnitsAvailable(Integer unitsAvailable) {
this.unitsAvailable = unitsAvailable;
}
public String getIsbnCode() {
return isbnCode;
}
public void setIsbnCode(String isbnCode) {
this.isbnCode = isbnCode;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookDesc() {
return bookDesc;
}
public void setBookDesc(String bookDesc) {
this.bookDesc = bookDesc;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public String getSubjectName() {
return subjectName;
}
public void setSubjectName(String subjectName) {
this.subjectName = subjectName;
}
}
// libraryManagement/UserMenu.java
package projecttest.libraryManagement;
import java.util.Scanner;
/**
*
* @author testuser
*/
public class UserMenu {
public static void main(String[] args) {
String input="";
Scanner sc = new Scanner(System.in);
while(input != "5"){
System.out.println("---------------------------------------------------------");
System.out.println("---------------------------------------------------------");
System.out.println("---------------------------------------------------------");
System.out.println("Select the following options");
System.out.println("Enter 1 for adding a book");
System.out.println("Enter 2 for adding a member");
System.out.println("Enter 3 for issuing a book ");
System.out.println("Enter 4 for returning a book ");
System.out.println("Enter 5 to exit");
input = processUserInput(sc.nextLine().toString());
}
}
public static String processUserInput(String in) {
String retVal="5";
switch(in){
case "1":
System.out.println("---------------------------------------------------------");
System.out.println("You have selected option 1 to add a book");
AddBookMenu.addBookMenu();
return "1";
case "2":
System.out.println("---------------------------------------------------------");
System.out.println("You have selected option 2 to add a member");
AddMemberMenu.addMemberMenu();
return "2";
case "3":
System.out.println("---------------------------------------------------------");
System.out.println("You have selected option 3 to issue a book");
LibFunctions.callIssueMenu();
return "3";
case "4":
System.out.println("---------------------------------------------------------");
System.out.println("You have selected option 4 to return a book");
LibFunctions.callReturnMenu();
return "4";
default:
System.out.println("---------------------------------------------------------");
System.out.println("Thanks for working on this!!");
return "5";
}
}
}
// libraryManagement/LibUtil.java
package projecttest.libraryManagement;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author testuser
*/
public class LibUtil {
public static Connection getConnection() {
Connection conn = null;
try {
Properties prop = new Properties();
FileInputStream in = new FileInputStream("src/DBProperties");
prop.load(in);
String driverName= prop.getProperty("DBDriver");
Class.forName(driverName);
String dbName,user,password;
dbName= prop.getProperty("DBName");
user = prop.getProperty("User");
password= prop.getProperty("Password");
conn= DriverManager.getConnection(dbName, user, password);
return conn;
} catch (Exception e) {
}
return conn;
}
}
// libraryManagement/AddMemberMenu.java
package projecttest.libraryManagement;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author testuser
*/
public class AddMemberMenu {
public static void addMemberMenu() {
System.out.println("Reached the add member menu");
Member m = new Member();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println("Enter the member id ");
m.setMemberId(Integer.parseInt(sc.nextLine().toString()));
System.out.println("Enter the member name");
m.setMemberName(sc.nextLine().toString());
addMember(m);
addStatus = 1;
} catch (Exception e) {
addStatus=0;
}
}
}
public static void addMember(Member m) {
System.out.println("Reached inside add member for member "+m.getMemberId());
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
int k = stmt.executeUpdate("insert into members values ("+m.getMemberId()+",'"+m.getMemberName()+"',sysdate)");
if(k>0){
System.out.println("Added Member successfully");
conn.commit();
}else{
conn.rollback();
}
conn.close();
} catch (Exception e) {
}
}
}
// libraryManagement/AddBookMenu.java
package projecttest.libraryManagement;
import java.sql.Connection;
import java.sql.Statement;
import java.util.Scanner;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author testuser
*/
public class AddBookMenu {
public static void addBookMenu() {
System.out.println("Reached the add book menu");
Book b = new Book();
Scanner sc = new Scanner(System.in);
int addStatus = 0;
while (addStatus == 0) {
try {
System.out.println("Enter the isbn code");
b.setIsbnCode(sc.nextLine().toString());
System.out.println("Enter the book name");
b.setBookName(sc.nextLine().toString());
System.out.println("Enter the book desc");
b.setBookDesc(sc.nextLine().toString());
System.out.println("Enter the author name");
b.setAuthorName(sc.nextLine().toString());
System.out.println("Enter the subject ");
b.setSubjectName(sc.nextLine().toString());
System.out.println("Enter the units available");
b.setUnitsAvailable(Integer.parseInt(sc.nextLine().toString()));
addBook(b);
addStatus = 1;
} catch (Exception e) {
addStatus=0;
}
}
}
public static void addBook(Book b) {
System.out.println("Reached inside addBook for book "+b.getIsbnCode());
Connection conn = LibUtil.getConnection();
try {
Statement stmt = conn.createStatement();
int k = stmt.executeUpdate("insert into books values ('"+b.getIsbnCode()+"','"+b.getBookName()+"','"+b.getBookDesc()+"',"
+ "'"+b.getAuthorName()+"','"+b.getSubjectName()+"',"+b.getUnitsAvailable()+")");
if(k>0){
System.out.println("Added Book successfully");
conn.commit();
}else{
conn.rollback();
}
conn.close();
} catch (Exception e) {
}
}
}
| 7 | 483 | Java |
SimpleChat | ./ProjectTest/Java/SimpleChat.java | // SimpleChat/Server.java
package projecttest.SimpleChat;
import java.io.*;
import java.net.*;
import java.util.*;
class VerySimpleChatServer {
ArrayList clientOutputStreams;
public class ClientHandler implements Runnable {
BufferedReader reader;
Socket sock;
public ClientHandler(Socket clientSocket) {
try {
sock = clientSocket;
InputStreamReader isReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(isReader);
} catch (Exception ex) {
ex.printStackTrace();
}
} // close constructor
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
tellEveryone(message);
} // close while
} catch (Exception ex) {
ex.printStackTrace();
}
} // close run
}
// close inner class
public static void main(String[] args) {
new VerySimpleChatServer().go();
}
public void go() {
clientOutputStreams = new ArrayList();
try {
ServerSocket serverSock = new ServerSocket(5000);
while (true) {
Socket clientSocket = serverSock.accept();
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream());
clientOutputStreams.add(writer);
Thread t = new Thread(new ClientHandler(clientSocket));
t.start();
System.out.println("got a connection");
}
} catch (Exception ex) {
ex.printStackTrace();
}
} // close go
public void tellEveryone(String message) {
Iterator it = clientOutputStreams.iterator();
while (it.hasNext()) {
try {
PrintWriter writer = (PrintWriter) it.next();
writer.println(message);
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
} // end while
} // close tellEveryone
} // close class
// SimpleChat/Client.java
package projecttest.SimpleChat;
import java.io.*;
import java.net.*;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
public class Client {
JTextArea incoming;
JTextField outgoing;
BufferedReader reader;
PrintWriter writer;
Socket sock;
public static void main(String[] args) {
Client client = new Client();
client.go();
}
public void go() {
JFrame frame = new JFrame("Ludicrously Simple Chat Client");
JPanel mainPanel = new JPanel();
incoming = new JTextArea(15, 50);
incoming.setLineWrap(true);
incoming.setWrapStyleWord(true);
incoming.setEditable(false);
JScrollPane qScroller = new JScrollPane(incoming);
qScroller.setVerticalScrollBarPolicy(ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
qScroller.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
outgoing = new JTextField(20);
JButton sendButton = new JButton("Send");
sendButton.addActionListener(new SendButtonListener());
mainPanel.add(qScroller);
mainPanel.add(outgoing);
mainPanel.add(sendButton);
setUpNetworking();
Thread readerThread = new Thread(new IncomingReader());
readerThread.start();
frame.getContentPane().add(BorderLayout.CENTER, mainPanel);
frame.setSize(400, 500);
frame.setVisible(true);
}
private void setUpNetworking() {
try {
sock = new Socket("192.168.5.16", 5000);
InputStreamReader streamReader = new InputStreamReader(sock.getInputStream());
reader = new BufferedReader(streamReader);
writer = new PrintWriter(sock.getOutputStream());
System.out.println("networking established");
} catch (IOException ex) {
ex.printStackTrace();
}
} // close setUpNetworking
public class SendButtonListener implements ActionListener {
public void actionPerformed(ActionEvent ev) {
try {
writer.println(outgoing.getText());
writer.flush();
} catch (Exception ex) {
ex.printStackTrace();
}
outgoing.setText("");
outgoing.requestFocus();
}
} // close inner class
public class IncomingReader implements Runnable {
public void run() {
String message;
try {
while ((message = reader.readLine()) != null) {
System.out.println("read " + message);
incoming.append(message + "\n");
} // close while
} catch (Exception ex) {
ex.printStackTrace();
}
} // close run
}
}
| 2 | 170 | Java |
springmicrometerundertow | ./ProjectTest/Java/springmicrometerundertow.java | // springmicrometerundertow/SpringMicrometerUndertowApplication.java
package projecttest.springmicrometerundertow;
import io.micrometer.core.instrument.MeterRegistry;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.handlers.MetricsHandler;
import io.undertow.servlet.api.MetricsCollector;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.actuate.autoconfigure.metrics.MeterRegistryCustomizer;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.undertow.UndertowDeploymentInfoCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
@SpringBootApplication
@RestController
public class SpringMicrometerUndertowApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMicrometerUndertowApplication.class, args);
}
@Bean
UndertowDeploymentInfoCustomizer undertowDeploymentInfoCustomizer(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) {
return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(undertowMetricsHandlerWrapper);
//return deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(MetricsHandler.WRAPPER);
}
@Bean
MeterRegistryCustomizer<MeterRegistry> micrometerMeterRegistryCustomizer(@Value("${spring.application.name}") String applicationName) {
return registry -> registry.config().commonTags("application.name", applicationName);
}
@GetMapping(value = "/hello", produces = MediaType.APPLICATION_JSON_VALUE)
public String hello(@RequestParam(name = "name", required = true) String name) {
return "Hello " + name + "!";
}
}
// springmicrometerundertow/UndertowMeterBinder.java
package projecttest.springmicrometerundertow;
import io.micrometer.core.instrument.FunctionCounter;
import io.micrometer.core.instrument.FunctionTimer;
import io.micrometer.core.instrument.MeterRegistry;
import io.micrometer.core.instrument.TimeGauge;
import io.micrometer.core.instrument.binder.MeterBinder;
import io.undertow.server.handlers.MetricsHandler;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;
import java.util.concurrent.TimeUnit;
import java.util.function.ToDoubleFunction;
import java.util.function.ToLongFunction;
@Component
public class UndertowMeterBinder implements ApplicationListener<ApplicationReadyEvent> {
private final UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper;
public UndertowMeterBinder(UndertowMetricsHandlerWrapper undertowMetricsHandlerWrapper) {
this.undertowMetricsHandlerWrapper = undertowMetricsHandlerWrapper;
}
@Override
public void onApplicationEvent(ApplicationReadyEvent applicationReadyEvent) {
bindTo(applicationReadyEvent.getApplicationContext().getBean(MeterRegistry.class));
}
public void bindTo(MeterRegistry meterRegistry) {
bind(meterRegistry, undertowMetricsHandlerWrapper.getMetricsHandler());
}
public void bind(MeterRegistry registry, MetricsHandler metricsHandler) {
bindTimer(registry, "undertow.requests", "Number of requests", metricsHandler,
m -> m.getMetrics().getTotalRequests(), m2 -> m2.getMetrics().getMinRequestTime());
bindTimeGauge(registry, "undertow.request.time.max", "The longest request duration in time", metricsHandler,
m -> m.getMetrics().getMaxRequestTime());
bindTimeGauge(registry, "undertow.request.time.min", "The shortest request duration in time", metricsHandler,
m -> m.getMetrics().getMinRequestTime());
bindCounter(registry, "undertow.request.errors", "Total number of error requests ", metricsHandler,
m -> m.getMetrics().getTotalErrors());
}
private void bindTimer(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler,
ToLongFunction<MetricsHandler> countFunc, ToDoubleFunction<MetricsHandler> consumer) {
FunctionTimer.builder(name, metricsHandler, countFunc, consumer, TimeUnit.MILLISECONDS)
.description(desc).register(registry);
}
private void bindTimeGauge(MeterRegistry registry, String name, String desc, MetricsHandler metricResult,
ToDoubleFunction<MetricsHandler> consumer) {
TimeGauge.builder(name, metricResult, TimeUnit.MILLISECONDS, consumer).description(desc)
.register(registry);
}
private void bindCounter(MeterRegistry registry, String name, String desc, MetricsHandler metricsHandler,
ToDoubleFunction<MetricsHandler> consumer) {
FunctionCounter.builder(name, metricsHandler, consumer).description(desc)
.register(registry);
}
}
// springmicrometerundertow/UndertowMetricsHandlerWrapper.java
package projecttest.springmicrometerundertow;
import io.undertow.server.HandlerWrapper;
import io.undertow.server.HttpHandler;
import io.undertow.server.handlers.MetricsHandler;
import org.springframework.stereotype.Component;
@Component
public class UndertowMetricsHandlerWrapper implements HandlerWrapper {
private MetricsHandler metricsHandler;
@Override
public HttpHandler wrap(HttpHandler handler) {
metricsHandler = new MetricsHandler(handler);
return metricsHandler;
}
public MetricsHandler getMetricsHandler() {
return metricsHandler;
}
}
| 3 | 130 | Java |
logrequestresponseundertow | ./ProjectTest/Java/logrequestresponseundertow.java | // logrequestresponseundertow/Song.java
package projecttest.logrequestresponseundertow;
import lombok.*;
@Getter
@Setter
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Song {
private Long id;
private String name;
private String author;
}
// logrequestresponseundertow/Application.java
package projecttest.logrequestresponseundertow;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.undertow.UndertowServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import io.undertow.server.handlers.RequestDumpingHandler;
import lombok.extern.log4j.Log4j2;
@SpringBootApplication
@Log4j2
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
@Bean
public UndertowServletWebServerFactory undertowServletWebServerFactory() {
UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
factory.addDeploymentInfoCustomizers(deploymentInfo ->
deploymentInfo.addInitialHandlerChainWrapper(handler -> {
return new RequestDumpingHandler(handler);
}));
return factory;
}
@Bean
public UndertowServletWebServerFactory UndertowServletWebServerFactory() {
UndertowServletWebServerFactory UndertowServletWebServerFactory = new UndertowServletWebServerFactory();
UndertowServletWebServerFactory.addDeploymentInfoCustomizers(deploymentInfo -> deploymentInfo.addInitialHandlerChainWrapper(handler -> {
return new RequestDumpingHandler(handler);
}));
return UndertowServletWebServerFactory;
}
}
// logrequestresponseundertow/SongController.java
package projecttest.logrequestresponseundertow;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import org.springframework.web.bind.annotation.*;
@RestController
public class SongController {
@PostMapping("/songs")
public Song createSong(@RequestBody Song song) {
song.setId(new Random().nextLong());
return song;
}
@GetMapping("/songs")
public List<Song> getSongs() {
List<Song> songs = new ArrayList<>();
songs.add(Song.builder().id(1L).name("name1").author("author2").build());
songs.add(Song.builder().id(2L).name("name2").author("author2").build());
return songs;
}
}
| 3 | 85 | Java |
Train | ./ProjectTest/Java/Train.java | // Train/Driver.java
package projecttest.Train;
public class Driver
{
/**
* This testdriver wil test the difrent methods from train and trainstation
*/
public static void test() {
Train t1 = new Train("Aarhus", "Berlin", 999);
Train t2 = new Train("Herning", "Copenhagen", 42);
Train t3 = new Train("Aarhus", "Herning", 66);
Train t4 = new Train("Odense", "Herning", 177);
Train t5 = new Train("Aarhus", "Copenhagen", 122);
System.out.println("Opgave 3:");
System.out.println("*******************");
System.out.println(t1);
System.out.println(t2);
System.out.println(t3);
System.out.println(t4);
System.out.println(t5);
System.out.println("*******************");
System.out.println("");
TrainStation ts = new TrainStation("Herning");
ts.addTrain(t1);
ts.addTrain(t2);
ts.addTrain(t3);
ts.addTrain(t4);
ts.addTrain(t5);
System.out.println("Opgave 8:");
System.out.println("*******************");
System.out.println("No. of trains going from or to Herning:");
System.out.println(ts.connectingTrains());
System.out.println("*******************");
System.out.println("");
System.out.println("Opgave 9:");
System.out.println("*******************");
System.out.println("The cheapest train going to Copenhagen is going:");
System.out.println(ts.cheapTrainTo("Copenhagen"));
System.out.println("*******************");
System.out.println("");
System.out.println("Opgave 10:");
System.out.println("*******************");
ts.printTrainStation();
System.out.println("*******************");
System.out.println("");
System.out.println("Opgave 11:");
System.out.println("*******************");
System.out.println("Trains going from Aarhus to Herning:");
for(Train t : ts.trainsFrom("Aarhus")) {
System.out.println(t);
}
System.out.println("*******************");
System.out.println("");
System.out.println("Opgave 12:");
System.out.println("*******************");
System.out.println("The cheapest train going from herning to Copenhagen:");
System.out.println(ts.cheapTrain("Copenhagen"));
System.out.println("*******************");
System.out.println("");
}
}
// Train/TrainStation.java
package projecttest.Train;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.Comparator;
public class TrainStation
{
private String city;
private ArrayList<Train> trains;
public TrainStation(String city)
{
this.city = city;
trains = new ArrayList<Train>();
}
/**
* this method adds trains tot the ArrayList trains
*/
public void addTrain(Train t) {
trains.add(t);
}
/**
* Method will return the number of trains that starts or ends in the
* city of the Trainstation
*/
public int connectingTrains() {
int result = 0;
for(Train t : trains) {
if(city.equals(t.getDeparture()) || city.equals(t.getDestiantion())) {
result ++;
}
}
return result;
}
/**
* This method returns the chepest train go to a spesific destination
*/
public Train cheapTrainTo(String destination) {
Train result = null;
for(Train t : trains) {
if(destination.equals(t.getDestiantion())) {
if(result == null || result.getPrice() > t.getPrice()) {
result = t;
}
}
}
return result;
}
/**
* This method prints out all trains in the ArrayList trains
* in sorted order after the departurs in alphabeticly order
* if they have the same departures then it wil sort after price
* from lovest til highest
*/
public void printTrainStation() {
Collections.sort(trains);
System.out.println("The trainstaion in " + city + " has following trains:");
for(Train t : trains) {
System.out.println(t);
}
}
/**
* This method will return all trains that starts in a given place
* going to the Trainstations city.
*/
public List<Train> trainsFrom(String departure) {
return trains.stream()
.filter(t -> t.getDeparture().equals(departure) && t.getDestiantion().equals(city))
.collect(Collectors.toList());
}
/**
* This method returns the cheapest train strating in the Trainstations
* city, and ends in a given destination
*/
public Train cheapTrain(String destination) {
return trains.stream()
.filter(t -> t.getDeparture().equals(city) && t.getDestiantion().equals(destination))
.min(Comparator.comparing(t -> t.getPrice()))
.orElse(null);
}
}
// Train/Train.java
package projecttest.Train;
import java.util.Collections;
public class Train implements Comparable<Train>
{
private String departure;
private String destination;
private int price;
public Train(String departure, String destination, int price)
{
this.departure = departure;
this.destination = destination;
this.price = price;
}
/**
* A method to get the departure
*/
public String getDeparture() {
return departure;
}
/**
* A method to get the destiantion
*/
public String getDestiantion() {
return destination;
}
/**
* A method to get grice
*/
public int getPrice() {
return price;
}
/**
* This method will format a String of the given way
*/
public String toString() {
return "From " + departure + " to " + destination + " for " + price + " DKK";
}
/**
* This method sorts departures alphabeticly, if they have the same
* departures then it wil sort after price from lovest til highest
*/
public int compareTo(Train other) {
if(!departure.equals(other.departure)) {
return departure.compareTo(other.departure);
} else
{
return price - other.price;
}
}
}
| 3 | 216 | Java |
bankingApplication | ./ProjectTest/Java/bankingApplication.java | // bankingApplication/bankManagement.java
package projecttest.bankingApplication;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;
import java.sql.Statement;
public class bankManagement { // these class provides all
// bank method
private static final int NULL = 0;
static Connection con = connection.getConnection();
static String sql = "";
public static boolean
createAccount(String name,
int passCode) // create account function
{
try {
// validation
if (name == "" || passCode == NULL) {
System.out.println("All Field Required!");
return false;
}
// query
Statement st = con.createStatement();
sql = "INSERT INTO customer(cname,balance,pass_code) values('"
+ name + "',1000," + passCode + ")";
// Execution
if (st.executeUpdate(sql) == 1) {
System.out.println(name
+ ", Now You Login!");
return true;
}
// return
}
catch (SQLIntegrityConstraintViolationException e) {
System.out.println("Username Not Available!");
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean
loginAccount(String name, int passCode) // login method
{
try {
// validation
if (name == "" || passCode == NULL) {
System.out.println("All Field Required!");
return false;
}
// query
sql = "select * from customer where cname='"
+ name + "' and pass_code=" + passCode;
PreparedStatement st
= con.prepareStatement(sql);
ResultSet rs = st.executeQuery();
// Execution
BufferedReader sc = new BufferedReader(
new InputStreamReader(System.in));
if (rs.next()) {
// after login menu driven interface method
int ch = 5;
int amt = 0;
int senderAc = rs.getInt("ac_no");
;
int receiveAc;
while (true) {
try {
System.out.println(
"Hallo, "
+ rs.getString("cname"));
System.out.println(
"1)Transfer Money");
System.out.println("2)View Balance");
System.out.println("5)LogOut");
System.out.print("Enter Choice:");
ch = Integer.parseInt(
sc.readLine());
if (ch == 1) {
System.out.print(
"Enter Receiver A/c No:");
receiveAc = Integer.parseInt(
sc.readLine());
System.out.print(
"Enter Amount:");
amt = Integer.parseInt(
sc.readLine());
if (bankManagement
.transferMoney(
senderAc, receiveAc,
amt)) {
System.out.println(
"MSG : Money Sent Successfully!\n");
}
else {
System.out.println(
"ERR : Failed!\n");
}
}
else if (ch == 2) {
bankManagement.getBalance(
senderAc);
}
else if (ch == 5) {
break;
}
else {
System.out.println(
"Err : Enter Valid input!\n");
}
}
catch (Exception e) {
e.printStackTrace();
}
}
}
else {
return false;
}
// return
return true;
}
catch (SQLIntegrityConstraintViolationException e) {
System.out.println("Username Not Available!");
}
catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static void
getBalance(int acNo) // fetch balance method
{
try {
// query
sql = "select * from customer where ac_no="
+ acNo;
PreparedStatement st
= con.prepareStatement(sql);
ResultSet rs = st.executeQuery(sql);
System.out.println(
"-----------------------------------------------------------");
System.out.printf("%12s %10s %10s\n",
"Account No", "Name",
"Balance");
// Execution
while (rs.next()) {
System.out.printf("%12d %10s %10d.00\n",
rs.getInt("ac_no"),
rs.getString("cname"),
rs.getInt("balance"));
}
System.out.println(
"-----------------------------------------------------------\n");
}
catch (Exception e) {
e.printStackTrace();
}
}
public static boolean transferMoney(int sender_ac,
int reveiver_ac,
int amount)
throws SQLException // transfer money method
{
// validation
if (reveiver_ac == NULL || amount == NULL) {
System.out.println("All Field Required!");
return false;
}
try {
con.setAutoCommit(false);
sql = "select * from customer where ac_no="
+ sender_ac;
PreparedStatement ps
= con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
if (rs.getInt("balance") < amount) {
System.out.println(
"Insufficient Balance!");
return false;
}
}
Statement st = con.createStatement();
// debit
con.setSavepoint();
sql = "update customer set balance=balance-"
+ amount + " where ac_no=" + sender_ac;
if (st.executeUpdate(sql) == 1) {
System.out.println("Amount Debited!");
}
// credit
sql = "update customer set balance=balance+"
+ amount + " where ac_no=" + reveiver_ac;
st.executeUpdate(sql);
con.commit();
return true;
}
catch (Exception e) {
e.printStackTrace();
con.rollback();
}
// return
return false;
}
}
// bankingApplication/connection.java
package projecttest.bankingApplication;
import java.sql.Connection;
import java.sql.DriverManager;
// Global connection Class
public class connection {
static Connection con; // Global Connection Object
public static Connection getConnection()
{
try {
String mysqlJDBCDriver
= "com.mysql.cj.jdbc.Driver"; //jdbc driver
String url
= "jdbc:mysql://localhost:3306/mydata"; //mysql url
String user = "root"; //mysql username
String pass = "Pritesh4@"; //mysql passcode
Class.forName(mysqlJDBCDriver);
con = DriverManager.getConnection(url, user,
pass);
}
catch (Exception e) {
System.out.println("Connection Failed!");
}
return con;
}
}
// bankingApplication/bank.java
package projecttest.bankingApplication;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class bank {
public static void main(String args[]) //main class of bank
throws IOException
{
BufferedReader sc = new BufferedReader(
new InputStreamReader(System.in));
String name = "";
int pass_code;
int ac_no;
int ch;
while (true) {
System.out.println(
"\n ->|| Welcome to InBank ||<- \n");
System.out.println("1)Create Account");
System.out.println("2)Login Account");
try {
System.out.print("\n Enter Input:"); //user input
ch = Integer.parseInt(sc.readLine());
switch (ch) {
case 1:
try {
System.out.print(
"Enter Unique UserName:");
name = sc.readLine();
System.out.print(
"Enter New Password:");
pass_code = Integer.parseInt(
sc.readLine());
if (bankManagement.createAccount(
name, pass_code)) {
System.out.println(
"MSG : Account Created Successfully!\n");
}
else {
System.out.println(
"ERR : Account Creation Failed!\n");
}
}
catch (Exception e) {
System.out.println(
" ERR : Enter Valid Data::Insertion Failed!\n");
}
break;
case 2:
try {
System.out.print(
"Enter UserName:");
name = sc.readLine();
System.out.print(
"Enter Password:");
pass_code = Integer.parseInt(
sc.readLine());
if (bankManagement.loginAccount(
name, pass_code)) {
System.out.println(
"MSG : Logout Successfully!\n");
}
else {
System.out.println(
"ERR : login Failed!\n");
}
}
catch (Exception e) {
System.out.println(
" ERR : Enter Valid Data::Login Failed!\n");
}
break;
default:
System.out.println("Invalid Entry!\n");
}
if (ch == 5) {
System.out.println(
"Exited Successfully!\n\n Thank You :)");
break;
}
}
catch (Exception e) {
System.out.println("Enter Valid Entry!");
}
}
sc.close();
}
}
| 3 | 357 | Java |
springuploads3 | ./ProjectTest/Java/springuploads3.java | // springuploads3/service/StorageService.java
package projecttest.springuploads3.service;
import org.springframework.web.multipart.MultipartFile;
import projecttest.springuploads3.service.model.DownloadedResource;
public interface StorageService {
String upload(MultipartFile multipartFile);
DownloadedResource download(String id);
}
// springuploads3/service/model/DownloadedResource.java
package projecttest.springuploads3.service.model;
import lombok.Builder;
import lombok.Data;
import java.io.InputStream;
@Data
@Builder
public class DownloadedResource {
private String id;
private String fileName;
private Long contentLength;
private InputStream inputStream;
}
// springuploads3/service/S3StorageService.java
package projecttest.springuploads3.service;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.amazonaws.services.s3.model.S3Object;
import projecttest.springuploads3.service.model.DownloadedResource;
import lombok.SneakyThrows;
@Service
public class S3StorageService implements StorageService {
private static final String FILE_EXTENSION = "fileExtension";
private final AmazonS3 amazonS3;
private final String bucketName;
public S3StorageService(AmazonS3 amazonS3, @Value("${aws.s3.bucket-name}") String bucketName) {
this.amazonS3 = amazonS3;
this.bucketName = bucketName;
initializeBucket();
}
@SneakyThrows
@Override
public String upload(MultipartFile multipartFile) {
String key = RandomStringUtils.randomAlphanumeric(50);
amazonS3.putObject(bucketName, key, multipartFile.getInputStream(), extractObjectMetadata(multipartFile));
return key;
}
@Override
public DownloadedResource download(String id) {
S3Object s3Object = amazonS3.getObject(bucketName, id);
String filename = id + "." + s3Object.getObjectMetadata().getUserMetadata().get(FILE_EXTENSION);
Long contentLength = s3Object.getObjectMetadata().getContentLength();
return DownloadedResource.builder().id(id).fileName(filename).contentLength(contentLength).inputStream(s3Object.getObjectContent())
.build();
}
private ObjectMetadata extractObjectMetadata(MultipartFile file) {
ObjectMetadata objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(file.getSize());
objectMetadata.setContentType(file.getContentType());
objectMetadata.getUserMetadata().put(FILE_EXTENSION, FilenameUtils.getExtension(file.getOriginalFilename()));
return objectMetadata;
}
private void initializeBucket() {
if (!amazonS3.doesBucketExistV2(bucketName)) {
amazonS3.createBucket(bucketName);
}
}
}
// springuploads3/controller/FileUploadController.java
package projecttest.springuploads3.controller;
import projecttest.springuploads3.service.StorageService;
import lombok.extern.log4j.Log4j2;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
@Controller
@Log4j2
public class FileUploadController {
private final StorageService storageService;
public FileUploadController(StorageService storageService) {
this.storageService = storageService;
}
@PostMapping(value = "/upload", produces = "application/json")
public ResponseEntity<String> upload(@RequestParam("file") MultipartFile file) {
String key = storageService.upload(file);
return new ResponseEntity<>(key, HttpStatus.OK);
}
}
// springuploads3/controller/FileDownloadController.java
package projecttest.springuploads3.controller;
import projecttest.springuploads3.service.model.DownloadedResource;
import org.springframework.core.io.InputStreamResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import projecttest.springuploads3.service.StorageService;
import lombok.extern.log4j.Log4j2;
@Controller
@Log4j2
public class FileDownloadController {
private final StorageService storageService;
public FileDownloadController(StorageService storageService) {
this.storageService = storageService;
}
@GetMapping("/download")
public ResponseEntity<Resource> download(String id) {
DownloadedResource downloadedResource = storageService.download(id);
return ResponseEntity.ok().header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + downloadedResource.getFileName())
.contentLength(downloadedResource.getContentLength()).contentType(MediaType.APPLICATION_OCTET_STREAM)
.body(new InputStreamResource(downloadedResource.getInputStream()));
}
}
// springuploads3/SpringUploadS3Application.java
package projecttest.springuploads3;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringUploadS3Application {
public static void main(String[] args) {
SpringApplication.run(SpringUploadS3Application.class, args);
}
}
// springuploads3/configuration/S3ClientConfiguration.java
package projecttest.springuploads3.configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.regions.Regions;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
@Configuration
public class S3ClientConfiguration {
@Value("${aws.s3.endpoint-url}")
private String endpointUrl;
@Bean
AmazonS3 amazonS3() {
AwsClientBuilder.EndpointConfiguration endpointConfiguration = new AwsClientBuilder.EndpointConfiguration(endpointUrl,
Regions.US_EAST_1.getName());
return AmazonS3ClientBuilder.standard().withEndpointConfiguration(endpointConfiguration).withPathStyleAccessEnabled(true).build();
}
}
| 7 | 192 | Java |
CalculatorOOPS | ./ProjectTest/Java/CalculatorOOPS.java | // CalculatorOOPS/Divide.java
package projecttest.CalculatorOOPS;
public class Divide implements Operate {
@Override
public Double getResult(Double... numbers){
Double div = numbers[0];
for(int i=1;i< numbers.length;i++){
div /= numbers[i];
}
return div;
}
}
// CalculatorOOPS/Modulus.java
package projecttest.CalculatorOOPS;
public class Modulus implements Operate{
@Override
public Double getResult(Double... numbers){
Double mod = numbers[0];
for (int i = 1; i < numbers.length; i++) {
mod %= numbers[i];
}
return mod;
}
}
// CalculatorOOPS/ReadInput.java
package projecttest.CalculatorOOPS;
import java.util.Scanner;
public class ReadInput {
public static String read(){
Scanner scanner = new Scanner(System.in);
System.out.println("Input Expression Example: 4*3/2");
String inputLine = scanner.nextLine();
scanner.close();
return inputLine;
}
}
// CalculatorOOPS/Operate.java
package projecttest.CalculatorOOPS;
public interface Operate {
Double getResult(Double... numbers);
}
// CalculatorOOPS/Add.java
package projecttest.CalculatorOOPS;
public class Add implements Operate{
@Override
public Double getResult(Double... numbers){
Double sum = 0.0;
for(Double num: numbers){
sum += num;
}
return sum;
}
}
// CalculatorOOPS/Sub.java
package projecttest.CalculatorOOPS;
public class Sub implements Operate{
@Override
public Double getResult(Double... numbers){
Double sub = numbers[0];
for(int i=1;i< numbers.length;i++){
sub -= numbers[i];
}
return sub;
}
}
// CalculatorOOPS/Multiply.java
package projecttest.CalculatorOOPS;
public class Multiply implements Operate {
@Override
public Double getResult(Double... numbers){
Double mul = 1.0;
for(Double num: numbers){
mul *= num;
}
return mul;
}
}
// CalculatorOOPS/Calculator.java
package projecttest.CalculatorOOPS;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.Objects;
import java.util.Queue;
public class Calculator {
public static void main(String[] args){
final String inputExp = ReadInput.read();
Queue<String> operations;
Queue<String> numbers;
String[] numbersArr = inputExp.split("[-+*/%]");
// String[] operArr = inputExp.split("[0-9]+");
String[] operArr = inputExp.split("\\d+");
numbers = new LinkedList<>(Arrays.asList(numbersArr));
operations = new LinkedList<>(Arrays.asList(operArr));
Double res = Double.parseDouble(Objects.requireNonNull(numbers.poll()));
while(!numbers.isEmpty()){
String opr = operations.poll();
Operate operate;
switch(Objects.requireNonNull(opr)){
case "+":
operate = new Add();
break;
case "-":
operate = new Sub();
break;
case "*":
operate = new Multiply();
break;
case "/":
operate = new Divide();
break;
case "%":
operate = new Modulus();
break;
default:
continue;
}
Double num = Double.parseDouble(Objects.requireNonNull(numbers.poll()));
res = operate.getResult(res, num);
}
System.out.println(res);
}
}
| 8 | 138 | Java |
passwordGenerator | ./ProjectTest/Java/passwordGenerator.java | // passwordGenerator/GeneratorTest.java
package projecttest.passwordGenerator;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
class GeneratorTest {
private final Password password= new Password("Secret");
private final Alphabet firstAlphabet = new Alphabet(true,false,false,false);
private final Alphabet secondAlphabet = new Alphabet(false,true,true,true);
private final Generator generator = new Generator(true,false,false,false);
// private final Password generatedPassword = generator.GeneratePassword(4);
@Test
void test1() {
assertEquals("Secret", password.toString());
}
@Test
void test2() {
assertEquals(firstAlphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);
}
@Test
void test3() {
assertEquals(secondAlphabet.getAlphabet(), Alphabet.LOWERCASE_LETTERS + Alphabet.NUMBERS + Alphabet.SYMBOLS);
}
@Test
void test4() {
assertEquals(generator.alphabet.getAlphabet(), Alphabet.UPPERCASE_LETTERS);
}
@Test
void test5() {
assertEquals(generator.alphabet.getAlphabet().length(), 26);
}
}
// passwordGenerator/Main.java
package projecttest.passwordGenerator;
import java.util.Scanner;
public class Main {
public static final Scanner keyboard = new Scanner(System.in);
public static void main(String[] args) {
Generator generator = new Generator(keyboard);
generator.mainLoop();
keyboard.close();
}
}
// passwordGenerator/Generator.java
package projecttest.passwordGenerator;
import java.util.Objects;
import java.util.Scanner;
public class Generator {
Alphabet alphabet;
public static Scanner keyboard;
public Generator(Scanner scanner) {
keyboard = scanner;
}
public Generator(boolean IncludeUpper, boolean IncludeLower, boolean IncludeNum, boolean IncludeSym) {
alphabet = new Alphabet(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);
}
public void mainLoop() {
System.out.println("Welcome to Ziz Password Services :)");
printMenu();
String userOption = "-1";
while (!userOption.equals("4")) {
userOption = keyboard.next();
switch (userOption) {
case "1": {
requestPassword();
printMenu();
}
case "2": {
checkPassword();
printMenu();
}
case "3": {
printUsefulInfo();
printMenu();
}
case "4": printQuitMessage();
default: {
System.out.println();
System.out.println("Kindly select one of the available commands");
printMenu();
}
}
}
}
private Password GeneratePassword(int length) {
final StringBuilder pass = new StringBuilder("");
final int alphabetLength = alphabet.getAlphabet().length();
int max = alphabetLength - 1;
int min = 0;
int range = max - min + 1;
for (int i = 0; i < length; i++) {
int index = (int) (Math.random() * range) + min;
pass.append(alphabet.getAlphabet().charAt(index));
}
return new Password(pass.toString());
}
private void printUsefulInfo() {
System.out.println();
System.out.println("Use a minimum password length of 8 or more characters if permitted");
System.out.println("Include lowercase and uppercase alphabetic characters, numbers and symbols if permitted");
System.out.println("Generate passwords randomly where feasible");
System.out.println("Avoid using the same password twice (e.g., across multiple user accounts and/or software systems)");
System.out.println("Avoid character repetition, keyboard patterns, dictionary words, letter or number sequences," +
"\nusernames, relative or pet names, romantic links (current or past) " +
"and biographical information (e.g., ID numbers, ancestors' names or dates).");
System.out.println("Avoid using information that the user's colleagues and/or " +
"acquaintances might know to be associated with the user");
System.out.println("Do not use passwords which consist wholly of any simple combination of the aforementioned weak components");
}
private void requestPassword() {
boolean IncludeUpper = false;
boolean IncludeLower = false;
boolean IncludeNum = false;
boolean IncludeSym = false;
boolean correctParams = false;
System.out.println();
System.out.println("Hello, welcome to the Password Generator :) answer"
+ " the following questions by Yes or No \n");
do {
System.out.println("Do you want Lowercase letters \"abcd...\" to be used? ");
String input = keyboard.nextLine();
if (isInclude(input)) IncludeLower = true;
System.out.println("Do you want Uppercase letters \"ABCD...\" to be used? ");
input = keyboard.nextLine();
if (isInclude(input)) IncludeUpper = true;
System.out.println("Do you want Numbers \"1234...\" to be used? ");
input = keyboard.nextLine();
if (isInclude(input)) IncludeNum = true;
System.out.println("Do you want Symbols \"!@#$...\" to be used? ");
input = keyboard.nextLine();
if (isInclude(input)) IncludeSym = true;
//No Pool Selected
if (!IncludeUpper && !IncludeLower && !IncludeNum && !IncludeSym) {
System.out.println("You have selected no characters to generate your " +
"password at least one of your answers should be Yes");
correctParams = true;
}
System.out.println("Great! Now enter the length of the password");
int length = keyboard.nextInt();
final Generator generator = new Generator(IncludeUpper, IncludeLower, IncludeNum, IncludeSym);
final Password password = generator.GeneratePassword(length);
System.err.println("Your generated password -> " + password);
} while (correctParams);
}
private boolean isInclude(String Input) {
if (Input.equalsIgnoreCase("yes")) {
return true;
} else {
if (!Input.equalsIgnoreCase("no")) {
PasswordRequestError();
}
return false;
}
}
private void PasswordRequestError() {
System.out.println("You have entered something incorrect let's go over it again \n");
}
private void checkPassword() {
String input;
final Scanner in = new Scanner(System.in);
System.out.print("\nEnter your password:");
input = in.nextLine();
final Password p = new Password(input);
System.out.println(p.calculateScore());
in.close();
}
private void printMenu() {
System.out.println();
System.out.println("Enter 1 - Password Generator");
System.out.println("Enter 2 - Password Strength Check");
System.out.println("Enter 3 - Useful Information");
System.out.println("Enter 4 - Quit");
System.out.print("Choice:");
}
private void printQuitMessage() {
System.out.println("Closing the program bye bye!");
}
}
// passwordGenerator/Alphabet.java
package projecttest.passwordGenerator;
public class Alphabet {
public static final String UPPERCASE_LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
public static final String LOWERCASE_LETTERS = "abcdefghijklmnopqrstuvwxyz";
public static final String NUMBERS = "1234567890";
public static final String SYMBOLS = "!@#$%^&*()-_=+\\/~?";
private final StringBuilder pool;
public Alphabet(boolean uppercaseIncluded, boolean lowercaseIncluded, boolean numbersIncluded, boolean specialCharactersIncluded) {
pool = new StringBuilder();
if (uppercaseIncluded) pool.append(UPPERCASE_LETTERS);
if (lowercaseIncluded) pool.append(LOWERCASE_LETTERS);
if (numbersIncluded) pool.append(NUMBERS);
if (specialCharactersIncluded) pool.append(SYMBOLS);
}
public String getAlphabet() {
return pool.toString();
}
}
// passwordGenerator/Password.java
package projecttest.passwordGenerator;
public class Password {
String Value;
int Length;
public Password(String s) {
Value = s;
Length = s.length();
}
public int CharType(char C) {
int val;
// Char is Uppercase Letter
if ((int) C >= 65 && (int) C <= 90)
val = 1;
// Char is Lowercase Letter
else if ((int) C >= 97 && (int) C <= 122) {
val = 2;
}
// Char is Digit
else if ((int) C >= 60 && (int) C <= 71) {
val = 3;
}
// Char is Symbol
else {
val = 4;
}
return val;
}
public int PasswordStrength() {
String s = this.Value;
boolean UsedUpper = false;
boolean UsedLower = false;
boolean UsedNum = false;
boolean UsedSym = false;
int type;
int Score = 0;
for (int i = 0; i < s.length(); i++) {
char c = s.charAt(i);
type = CharType(c);
if (type == 1) UsedUpper = true;
if (type == 2) UsedLower = true;
if (type == 3) UsedNum = true;
if (type == 4) UsedSym = true;
}
if (UsedUpper) Score += 1;
if (UsedLower) Score += 1;
if (UsedNum) Score += 1;
if (UsedSym) Score += 1;
if (s.length() >= 8) Score += 1;
if (s.length() >= 16) Score += 1;
return Score;
}
public String calculateScore() {
int Score = this.PasswordStrength();
if (Score == 6) {
return "This is a very good password :D check the Useful Information section to make sure it satisfies the guidelines";
} else if (Score >= 4) {
return "This is a good password :) but you can still do better";
} else if (Score >= 3) {
return "This is a medium password :/ try making it better";
} else {
return "This is a weak password :( definitely find a new one";
}
}
@Override
public String toString() {
return Value;
}
}
| 5 | 344 | Java |
springdatamongowithcluster | ./ProjectTest/Java/springdatamongowithcluster.java | // springdatamongowithcluster/SpringDataMongoWithClusterApplication.java
package projecttest.springdatamongowithcluster;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import lombok.extern.log4j.Log4j2;
@SpringBootApplication
@Log4j2
public class SpringDataMongoWithClusterApplication implements CommandLineRunner {
@Autowired
MongoTemplate mongoTemplate;
public static void main(String[] args) {
SpringApplication.run(SpringDataMongoWithClusterApplication.class, args);
}
@Override
public void run(String... args) {
mongoTemplate.dropCollection(Car.class);
mongoTemplate.save(Car.builder().name("Tesla Model S").build());
mongoTemplate.save(Car.builder().name("Tesla Model 3").build());
log.info("-------------------------------");
log.info("Cards found: " + mongoTemplate.count(new Query(), Car.class));
log.info("-------------------------------");
}
}
// springdatamongowithcluster/Car.java
package projecttest.springdatamongowithcluster;
import org.springframework.data.annotation.Id;
import lombok.Builder;
@Builder
public class Car {
@Id
private String id;
private String name;
}
| 2 | 51 | Java |
idcenter | ./ProjectTest/Java/idcenter.java | // idcenter/IdWorker.java
package projecttest.idcenter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Random;
/**
* from https://github.com/twitter/snowflake/blob/master/src/main/scala/com/twitter/service/snowflake/IdWorker.scala
*
* @author adyliu ([email protected])
* @since 1.0
*/
public class IdWorker {
private final long workerId;
private final long datacenterId;
private final long idepoch;
private static final long workerIdBits = 5L;
private static final long datacenterIdBits = 5L;
private static final long maxWorkerId = -1L ^ (-1L << workerIdBits);
private static final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private static final long sequenceBits = 12L;
private static final long workerIdShift = sequenceBits;
private static final long datacenterIdShift = sequenceBits + workerIdBits;
private static final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private static final long sequenceMask = -1L ^ (-1L << sequenceBits);
private long lastTimestamp = -1L;
private long sequence;
private static final Random r = new Random();
public IdWorker() {
this(1344322705519L);
}
public IdWorker(long idepoch) {
this(r.nextInt((int) maxWorkerId), r.nextInt((int) maxDatacenterId), 0, idepoch);
}
public IdWorker(long workerId, long datacenterId, long sequence) {
this(workerId, datacenterId, sequence, 1344322705519L);
}
//
public IdWorker(long workerId, long datacenterId, long sequence, long idepoch) {
this.workerId = workerId;
this.datacenterId = datacenterId;
this.sequence = sequence;
this.idepoch = idepoch;
if (workerId < 0 || workerId > maxWorkerId) {
throw new IllegalArgumentException("workerId is illegal: " + workerId);
}
if (datacenterId < 0 || datacenterId > maxDatacenterId) {
throw new IllegalArgumentException("datacenterId is illegal: " + workerId);
}
if (idepoch >= System.currentTimeMillis()) {
throw new IllegalArgumentException("idepoch is illegal: " + idepoch);
}
}
public long getDatacenterId() {
return datacenterId;
}
public long getWorkerId() {
return workerId;
}
public long getTime() {
return System.currentTimeMillis();
}
public long getId() {
long id = nextId();
return id;
}
private synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new IllegalStateException("Clock moved backwards.");
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0;
}
lastTimestamp = timestamp;
long id = ((timestamp - idepoch) << timestampLeftShift)//
| (datacenterId << datacenterIdShift)//
| (workerId << workerIdShift)//
| sequence;
return id;
}
/**
* get the timestamp (millis second) of id
* @param id the nextId
* @return the timestamp of id
*/
public long getIdTimestamp(long id) {
return idepoch + (id >> timestampLeftShift);
}
private long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
@Override
public String toString() {
final StringBuilder sb = new StringBuilder("IdWorker{");
sb.append("workerId=").append(workerId);
sb.append(", datacenterId=").append(datacenterId);
sb.append(", idepoch=").append(idepoch);
sb.append(", lastTimestamp=").append(lastTimestamp);
sb.append(", sequence=").append(sequence);
sb.append('}');
return sb.toString();
}
}
// idcenter/Base62.java
package projecttest.idcenter;
/**
* A Base62 method
*
* @author adyliu ([email protected])
* @since 1.0
*/
public class Base62 {
private static final String baseDigits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static final int BASE = baseDigits.length();
private static final char[] digitsChar = baseDigits.toCharArray();
private static final int FAST_SIZE = 'z';
private static final int[] digitsIndex = new int[FAST_SIZE + 1];
static {
for (int i = 0; i < FAST_SIZE; i++) {
digitsIndex[i] = -1;
}
//
for (int i = 0; i < BASE; i++) {
digitsIndex[digitsChar[i]] = i;
}
}
public static long decode(String s) {
long result = 0L;
long multiplier = 1;
for (int pos = s.length() - 1; pos >= 0; pos--) {
int index = getIndex(s, pos);
result += index * multiplier;
multiplier *= BASE;
}
return result;
}
public static String encode(long number) {
if (number < 0) throw new IllegalArgumentException("Number(Base62) must be positive: " + number);
if (number == 0) return "0";
StringBuilder buf = new StringBuilder();
while (number != 0) {
buf.append(digitsChar[(int) (number % BASE)]);
number /= BASE;
}
return buf.reverse().toString();
}
private static int getIndex(String s, int pos) {
char c = s.charAt(pos);
if (c > FAST_SIZE) {
throw new IllegalArgumentException("Unknow character for Base62: " + s);
}
int index = digitsIndex[c];
if (index == -1) {
throw new IllegalArgumentException("Unknow character for Base62: " + s);
}
return index;
}
}
// idcenter/Main.java
package projecttest.idcenter;
import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
public class Main {
public static void main(String[] args) {
if (args.length != 3) {
System.err.println("Usage: java -jar idcenter.jar <subcommand> <num> <output>");
System.err.println("Subcommands\nidworker: Sequential ID Creation\nsidworker: Timestamp-based ID Creation");
return;
}
String subcommand = args[0];
int num = Integer.parseInt(args[1]);
String output = args[2];
if (subcommand.equals("idworker")) {
final long idepo = System.currentTimeMillis() - 3600 * 1000L;
IdWorker iw = new IdWorker(1, 1, 0, idepo);
IdWorker iw2 = new IdWorker(idepo);
try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {
for (int i = 0; i < num; i++) {
long id = iw.getId();
long idTimeStamp = iw.getIdTimestamp(id);
long id2 = iw2.getId();
long idTimeStamp2 = iw2.getIdTimestamp(id2);
writer.write("IdWorker1: " + id + ", timestamp: " + idTimeStamp + "\n");
writer.write("IdWorker2: " + id2 + ", timestamp: " + idTimeStamp2 + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
} else if (subcommand.equals("sidworker")) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(output))) {
for (int i = 0; i < num; i++) {
long sid = SidWorker.nextSid();
writer.write("SidWorker: " + sid + "\n");
}
} catch (IOException e) {
e.printStackTrace();
}
} else {
System.err.println("Usage: java -jar idcenter.jar <subcommand> <num> <output>");
System.err.println("Subcommands\nidworker: Sequential ID Creation\nsidworker: Timestamp-based ID Creation");
}
}
}
// idcenter/SidWorker.java
package projecttest.idcenter;
import java.text.SimpleDateFormat;
import java.util.Date;
/**
* generator of 19 bits number with timestamp
*
* @author adyliu ([email protected])
* @since 2016-06-28
*/
public class SidWorker {
private static long lastTimestamp = -1L;
private static int sequence = 0;
private static final long MAX_SEQUENCE = 100;
private static final SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");
/**
* 19 bits number with timestamp (20160628175532000002)
*
* @return 19 bits number with timestamp
*/
public static synchronized long nextSid() {
long now = timeGen();
if (now == lastTimestamp) {
if (sequence++ > MAX_SEQUENCE) {
now = tilNextMillis(lastTimestamp);
sequence = 0;
}
} else {
sequence = 0;
}
lastTimestamp = now;
//
return 100L * Long.parseLong(format.format(new Date(now))) + sequence;
}
private static long tilNextMillis(long lastTimestamp) {
long timestamp = timeGen();
while (timestamp <= lastTimestamp) {
timestamp = timeGen();
}
return timestamp;
}
private static long timeGen() {
return System.currentTimeMillis();
}
}
| 4 | 295 | Java |
PongGame | ./ProjectTest/Java/PongGame.java | // PongGame/Score.java
package projecttest.PongGame;
import java.awt.*;
public class Score extends Rectangle{
static int GAME_WIDTH;
static int GAME_HEIGHT;
int player1;
int player2;
Score(int GAME_WIDTH, int GAME_HEIGHT){
Score.GAME_WIDTH = GAME_WIDTH;
Score.GAME_HEIGHT=GAME_HEIGHT;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.setFont(new Font("Consolas", Font.PLAIN,60));
g.drawLine(GAME_WIDTH/2,0,GAME_WIDTH/2,GAME_HEIGHT);
g.drawString(String.valueOf(player1/10)+String.valueOf(player1%10), (GAME_WIDTH/2)-85, 50);
g.drawString(String.valueOf(player2/10)+String.valueOf(player2%10), (GAME_WIDTH/2)+20, 50);
}
}
// PongGame/GameFrame.java
package projecttest.PongGame;
import java.awt.*;
import javax.swing.*;
public class GameFrame extends JFrame{
GamePanel panel;
GameFrame(){
panel = new GamePanel();
this.add(panel);
this.setTitle("Pong Game");
this.setResizable(false);
this.setBackground(Color.black);
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.pack();
this.setVisible(true);
this.setLocationRelativeTo(null);
}
}
// PongGame/Paddle.java
package projecttest.PongGame;
import java.awt.*;
import java.awt.event.*;
public class Paddle extends Rectangle{
int id;
int yVelocity;
int speed=10;
Paddle(int x, int y, int PADDLE_WIDTH, int PADDLE_HEIGHT, int id){
super(x,y,PADDLE_WIDTH,PADDLE_HEIGHT);
this.id=id;
}
public void keyPressed(KeyEvent e){
switch (id){
case 1:
if(e.getKeyCode()==KeyEvent.VK_W){
setYDirection(-speed);
move();
}
if(e.getKeyCode()==KeyEvent.VK_S){
setYDirection(speed);
move();
}
break;
case 2:
if(e.getKeyCode()==KeyEvent.VK_UP){
setYDirection(-speed);
move();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
setYDirection(speed);
move();
}
break;
}
}
public void keyReleased(KeyEvent e){
switch (id){
case 1:
if(e.getKeyCode()==KeyEvent.VK_W){
setYDirection(0);
move();
}
if(e.getKeyCode()==KeyEvent.VK_S){
setYDirection(0);
move();
}
break;
case 2:
if(e.getKeyCode()==KeyEvent.VK_UP){
setYDirection(0);
move();
}
if(e.getKeyCode()==KeyEvent.VK_DOWN){
setYDirection(0);
move();
}
break;
}
}
public void setYDirection(int yDirection){
yVelocity = yDirection;
}
public void move(){
y=y+yVelocity;
}
public void draw(Graphics g){
if (id==1)
g.setColor(Color.BLUE);
else
g.setColor(Color.red);
g.fillRect(x, y, width, height);
}
}
// PongGame/PongGame.java
package projecttest.PongGame;
public class PongGame {
public static void main(String[] args) {
GameFrame frame = new GameFrame();
}
}
// PongGame/Ball.java
package projecttest.PongGame;
import java.awt.*;
import java.util.*;
public class Ball extends Rectangle{
Random random;
int xVelocity;
int yVelocity;
int initialSpeed = 4 ;
Ball(int x, int y, int width, int height){
super(x, y, width, height);
random = new Random();
int randomXDirection = random.nextInt(2);
if(randomXDirection==0)
randomXDirection--;
setXDirection(randomXDirection*initialSpeed);
int randomYDirection = random.nextInt(2);
if(randomYDirection==0)
randomYDirection--;
setXDirection(randomYDirection*initialSpeed);
}
public void setXDirection(int randomXDirection){
xVelocity = randomXDirection;
}
public void setYDirection(int randomYDirection){
yVelocity=randomYDirection;
}
public void move(){
x+=xVelocity;
y+=yVelocity;
}
public void draw(Graphics g){
g.setColor(Color.white);
g.fillOval(x, y, height, width);
}
}
// PongGame/GamePanel.java
package projecttest.PongGame;
import java.awt.*;
import java.awt.event.*;
import java.util.*;
import javax.swing.*;
public class GamePanel extends JPanel implements Runnable{
static final int GAME_WIDTH = 1000;
static final int GAME_HEIGHT = (int)(GAME_WIDTH * (0.5555));
static final Dimension SCREEN_SIZE = new Dimension(GAME_WIDTH,GAME_HEIGHT);
static final int BALL_DIAMETER = 20;
static final int PADDLE_WIDTH = 25;
static final int PADDLE_HEIGHT = 100;
Thread gameThread;
Image image;
Graphics graphics;
Random random;
Paddle paddle1;
Paddle paddle2;
Ball ball;
Score score;
GamePanel(){
newPaddles();
newBall();
score = new Score(GAME_WIDTH,GAME_HEIGHT);
this.setFocusable(true);
this.addKeyListener(new AL());
this.setPreferredSize(SCREEN_SIZE);
gameThread = new Thread(this);
gameThread.start();
}
public void newBall() {
random = new Random();
ball = new Ball((GAME_WIDTH/2)-(BALL_DIAMETER/2),random.nextInt(GAME_HEIGHT-BALL_DIAMETER),BALL_DIAMETER,BALL_DIAMETER);
}
public void newPaddles() {
paddle1 = new Paddle(0,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,1);
paddle2 = new Paddle(GAME_WIDTH-PADDLE_WIDTH,(GAME_HEIGHT/2)-(PADDLE_HEIGHT/2),PADDLE_WIDTH,PADDLE_HEIGHT,2);
}
public void paint(Graphics g) {
image = createImage(getWidth(),getHeight());
graphics = image.getGraphics();
draw(graphics);
g.drawImage(image,0,0,this);
}
public void draw(Graphics g) {
paddle1.draw(g);
paddle2.draw(g);
ball.draw(g);
score.draw(g);
Toolkit.getDefaultToolkit().sync(); // I forgot to add this line of code in the video, it helps with the animation
}
public void move() {
paddle1.move();
paddle2.move();
ball.move();
}
public void checkCollision() {
//bounce ball off top & bottom window edges
if(ball.y <=0) {
ball.setYDirection(-ball.yVelocity);
}
if(ball.y >= GAME_HEIGHT-BALL_DIAMETER) {
ball.setYDirection(-ball.yVelocity);
}
//bounce ball off paddles
if(ball.intersects(paddle1)) {
ball.xVelocity = Math.abs(ball.xVelocity);
ball.xVelocity++; //optional for more difficulty
if(ball.yVelocity>0)
ball.yVelocity++; //optional for more difficulty
else
ball.yVelocity--;
ball.setXDirection(ball.xVelocity);
ball.setYDirection(ball.yVelocity);
}
if(ball.intersects(paddle2)) {
ball.xVelocity = Math.abs(ball.xVelocity);
ball.xVelocity++; //optional for more difficulty
if(ball.yVelocity>0)
ball.yVelocity++; //optional for more difficulty
else
ball.yVelocity--;
ball.setXDirection(-ball.xVelocity);
ball.setYDirection(ball.yVelocity);
}
//stops paddles at window edges
if(paddle1.y<=0)
paddle1.y=0;
if(paddle1.y >= (GAME_HEIGHT-PADDLE_HEIGHT))
paddle1.y = GAME_HEIGHT-PADDLE_HEIGHT;
if(paddle2.y<=0)
paddle2.y=0;
if(paddle2.y >= (GAME_HEIGHT-PADDLE_HEIGHT))
paddle2.y = GAME_HEIGHT-PADDLE_HEIGHT;
//give a player 1 point and creates new paddles & ball
if(ball.x <=0) {
score.player2++;
newPaddles();
newBall();
System.out.println("Player 2: "+score.player2);
}
if(ball.x >= GAME_WIDTH-BALL_DIAMETER) {
score.player1++;
newPaddles();
newBall();
System.out.println("Player 1: "+score.player1);
}
}
public void run() {
//game loop
long lastTime = System.nanoTime();
double amountOfTicks =60.0;
double ns = 1000000000 / amountOfTicks;
double delta = 0;
while(true) {
long now = System.nanoTime();
delta += (now -lastTime)/ns;
lastTime = now;
if(delta >=1) {
move();
checkCollision();
repaint();
delta--;
}
}
}
public class AL extends KeyAdapter{
public void keyPressed(KeyEvent e) {
paddle1.keyPressed(e);
paddle2.keyPressed(e);
}
public void keyReleased(KeyEvent e) {
paddle1.keyReleased(e);
paddle2.keyReleased(e);
}
}
}
| 6 | 321 | Java |
Actor_relationship_game | ./ProjectTest/Java/Actor_relationship_game.java | // Actor_relationship_game/GraphCreation.java
package projecttest.Actor_relationship_game;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class GraphCreation {
private final TMDBApi tmdbApi;
private final ActorGraph actorGraph;
public GraphCreation() {
this.tmdbApi = new TMDBApi();
this.actorGraph = new ActorGraph();
}
public void createGraph(String fileName) throws IOException {
populateGraphWithActors();
saveGraphToFile(fileName);
}
private void populateGraphWithActors() throws IOException {
String popularActorsJson = tmdbApi.searchPopularActors();
JsonArray actorsArray = JsonParser.parseString(popularActorsJson)
.getAsJsonObject().getAsJsonArray("results");
for (JsonElement actorElement : actorsArray) {
processActorElement(actorElement);
}
}
private void processActorElement(JsonElement actorElement) throws IOException {
JsonObject actorObject = actorElement.getAsJsonObject();
String actorId = actorObject.get("id").getAsString();
String actorName = actorObject.get("name").getAsString();
Actor actor = new Actor(actorId, actorName);
actorGraph.addActor(actor);
populateGraphWithMoviesForActor(actorId);
}
private void populateGraphWithMoviesForActor(String actorId) throws IOException {
String moviesJson = tmdbApi.getMoviesByActorId(actorId);
JsonArray moviesArray = JsonParser.parseString(moviesJson)
.getAsJsonObject().getAsJsonArray("cast");
for (JsonElement movieElement : moviesArray) {
processMovieElement(movieElement, actorId);
}
}
private void processMovieElement(JsonElement movieElement, String actorId) {
JsonObject movieObject = movieElement.getAsJsonObject();
String movieId = movieObject.get("id").getAsString();
String movieTitle = movieObject.get("title").getAsString();
Movie movie = new Movie(movieId, movieTitle);
actorGraph.addMovie(movie);
actorGraph.addActorToMovie(actorId, movieId);
}
private void saveGraphToFile(String fileName) throws IOException {
try (FileOutputStream fileOut = new FileOutputStream(fileName);
ObjectOutputStream out = new ObjectOutputStream(fileOut)) {
out.writeObject(actorGraph);
System.out.println("Serialized data is saved in "+fileName);
}
}
public static void main(String[] args) {
try {
String fileName = args[0];
new GraphCreation().createGraph(fileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Actor_relationship_game/Actor.java
package projecttest.Actor_relationship_game;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Actor implements Serializable{
private static final long serialVersionUID=1L;
private String id;
private String name;
private Set<String> movieIds; // Store movie IDs
public Actor(String id, String name) {
this.id = id;
this.name = name;
this.movieIds = new HashSet<>();
}
// Getters and setters
public Set<String> getMovieIds() {
return movieIds;
}
public String getId() {
return id;
}
public String getName() {
return name;
}
public void setId(String id) {
this.id = id;
}
public void setMovieIds(Set<String> movieIds) {
this.movieIds = movieIds;
}
public void setName(String name) {
this.name = name;
}
}
// Actor_relationship_game/ActorGraph.java
package projecttest.Actor_relationship_game;
import java.io.Serializable;
import java.util.*;
public class ActorGraph implements Serializable {
private static final long serialVersionUID=1L;
private Map<String, Actor> actors;
private Map<String, Movie> movies;
private Map<String, String> nameToIdMap;
private Map<String, String> idToNameMap;
public ActorGraph() {
this.actors = new HashMap<>();
this.movies = new HashMap<>();
this.nameToIdMap = new HashMap<>();
this.idToNameMap = new HashMap<>();
}
// getters
public Map<String, Actor> getActors() {
return actors;
}
public Map<String, Movie> getMovies() {
return movies;
}
public Map<String, String> getIdToNameMap() {
return idToNameMap;
}
public Map<String, String> getNameToIdMap() {
return nameToIdMap;
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
// Methods
public void addActor(Actor actor) {
actors.putIfAbsent(actor.getId(), actor);
nameToIdMap.put(actor.getName(), actor.getId());
idToNameMap.put(actor.getId(), actor.getName());
}
public void addMovie(Movie movie) {
movies.putIfAbsent(movie.getId(), movie);
}
public String getActorIdByName(String name) {
return nameToIdMap.get(name);
}
public String getActorNameById(String id) {
return idToNameMap.get(id);
}
public List<String> getAllActorNames() {
return new ArrayList<>(nameToIdMap.keySet());
}
/**
* This connects an actor to a movie.
* It's useful for building the graph based on TMDB API data.
*/
public void addActorToMovie(String actorId, String movieId) {
if (actors.containsKey(actorId) && movies.containsKey(movieId)) {
Actor actor = actors.get(actorId);
Movie movie = movies.get(movieId);
actor.getMovieIds().add(movieId);
movie.getActorIds().add(actorId);
}
}
/**
* Implements BFS to find the shortest path from startActorId to endActorId.
* It uses a queue for BFS and a map (visited) to track the visited actors and their previous actor in the path.
*/
public List<Map.Entry<String, String>> findConnectionWithPath(String startActorId, String endActorId) {
if (!actors.containsKey(startActorId) || !actors.containsKey(endActorId)) {
return Collections.emptyList();
}
Queue<String> queue = new LinkedList<>();
Map<String, String> visited = new HashMap<>();
Map<String, String> previousMovie = new HashMap<>();
queue.add(startActorId);
visited.put(startActorId, null);
while (!queue.isEmpty()) {
String currentActorId = queue.poll();
Actor currentActor = actors.get(currentActorId);
for (String movieId : currentActor.getMovieIds()) {
Movie movie = movies.get(movieId);
for (String coActorId : movie.getActorIds()) {
if (!visited.containsKey(coActorId)) {
visited.put(coActorId, currentActorId);
previousMovie.put(coActorId, movieId);
queue.add(coActorId);
if (coActorId.equals(endActorId)) {
return buildPath(visited, previousMovie, endActorId);
}
}
}
}
}
return Collections.emptyList();
}
/**
* Helper method to construct the path from the endActorId back to the startActorId using the visited map.
*/
private List<Map.Entry<String, String>> buildPath(Map<String, String> visited, Map<String, String> previousMovie, String endActorId) {
LinkedList<Map.Entry<String, String>> path = new LinkedList<>();
String current = endActorId;
while (current != null) {
String movieId = previousMovie.get(current);
String movieName = (movieId != null) ? movies.get(movieId).getTitle() : "Start";
path.addFirst(new AbstractMap.SimpleEntry<>(idToNameMap.get(current), movieName));
current = visited.get(current);
}
return path;
}
}
// Actor_relationship_game/TMDBApi.java
package projecttest.Actor_relationship_game;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import java.io.IOException;
public class TMDBApi {
private final OkHttpClient client;
private final String apiKey = System.getenv("TMDB_API_KEY"); // get API Key from environmental variable
public TMDBApi() {
this.client = new OkHttpClient();
}
public String getMoviesByActorId(String actorId) throws IOException {
String url = "https://api.themoviedb.org/3/person/" + actorId + "/movie_credits?api_key=" + apiKey;
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
return response.body().string();
}
}
public String searchPopularActors() throws IOException {
String url = "https://api.themoviedb.org/3/person/popular?api_key=" + apiKey;
Request request = new Request.Builder().url(url).build();
try (Response response = client.newCall(request).execute()) {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
}
return response.body().string();
}
}
}
// Actor_relationship_game/Movie.java
package projecttest.Actor_relationship_game;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class Movie implements Serializable {
private static final long serialVersionUID=1L;
private String id;
private String title;
private Set<String> actorIds; // Store actor IDs
public Movie(String id, String title) {
this.id = id;
this.title = title;
this.actorIds = new HashSet<>();
}
// Getters and setters
public String getId() {
return id;
}
public Set<String> getActorIds() {
return actorIds;
}
public String getTitle() {
return title;
}
public void setId(String id) {
this.id = id;
}
public void setActorIds(Set<String> actorIds) {
this.actorIds = actorIds;
}
public void setTitle(String title) {
this.title = title;
}
}
// Actor_relationship_game/ActorGraphUtil.java
package projecttest.Actor_relationship_game;
import java.io.*;
import java.util.List;
public class ActorGraphUtil {
public static void main(String[] args) {
String graphPath = args[0];
String filePath = args[1];
ActorGraph actorGraph = loadGraph(graphPath);
if (actorGraph != null) {
List<String> actorNames = actorGraph.getAllActorNames();
writeActorsToFile(actorNames, filePath);
System.out.println("Actors list has been saved to " + filePath);
} else {
System.out.println("Failed to load the graph.");
}
}
protected static ActorGraph loadGraph(String graphPath) {
try (FileInputStream fileIn = new FileInputStream(graphPath);
ObjectInputStream in = new ObjectInputStream(fileIn)) {
return (ActorGraph) in.readObject();
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
protected static void writeActorsToFile(List<String> actorNames, String fileName) {
try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName))) {
for (String name : actorNames) {
writer.write(name);
writer.newLine();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
// Actor_relationship_game/GameplayInterface.java
package projecttest.Actor_relationship_game;
import java.io.*;
import java.util.*;
import java.util.List;
public class GameplayInterface {
private ActorGraph actorGraph;
public void setActorGraph(ActorGraph actorGraph) {
this.actorGraph = actorGraph;
}
public void loadGraph(String fileName) {
try (FileInputStream fileIn = new FileInputStream(fileName);
ObjectInputStream in = new ObjectInputStream(fileIn)) {
actorGraph = (ActorGraph) in.readObject();
System.out.println("Graph successfully loaded.");
} catch (Exception e) {
e.printStackTrace();
}
}
public void findConnections(List<String[]> actorPairs, String outputFilePath) {
try (PrintWriter writer = new PrintWriter(new FileWriter(outputFilePath))) {
for (String[] pair : actorPairs) {
if (pair.length != 2) {
System.out.println("Invalid actor pair. Skipping.");
continue;
}
String actor1Name = pair[0];
String actor2Name = pair[1];
// Assuming getActorIdByName is a method in ActorGraph that returns the actor's ID given a name
String actor1Id = actorGraph.getActorIdByName(actor1Name);
String actor2Id = actorGraph.getActorIdByName(actor2Name);
if (actor1Id == null || actor2Id == null) {
writer.println("One or both actors not found in the graph.");
continue;
}
List<Map.Entry<String, String>> connectionPath = actorGraph.findConnectionWithPath(actor1Id, actor2Id);
if (connectionPath.isEmpty()) {
writer.println("===================================================");
writer.println("No connection found between " + actor1Name + " and " + actor2Name + ".");
writer.println("===================================================");
writer.println();
} else {
writer.println("===================================================");
writer.println("Connection Number between " + actor1Name + " and " + actor2Name + ":" + (connectionPath.size() - 1));
writer.println("Connection path between " + actor1Name + " and " + actor2Name + ":");
for (int i = 0; i < connectionPath.size(); i++) {
Map.Entry<String, String> step = connectionPath.get(i);
writer.println((i + 1) + ". " + step.getKey() + ": " + step.getValue());
}
writer.println("===================================================");
writer.println();
}
}
} catch (IOException e){
e.printStackTrace();
}
}
private static List<String> readActorsFromFile(String fileName) {
List<String> actors = new ArrayList<>();
try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
String line;
while ((line = reader.readLine()) != null) {
actors.add(line.trim());
}
} catch (IOException e) {
e.printStackTrace();
}
return actors;
}
private static List<String[]> generateAllActorPairs(String fileName) {
List<String> actors = readActorsFromFile(fileName);
List<String[]> pairs = new ArrayList<>();
for (int i = 0; i < actors.size(); i++) {
for (int j = i + 1; j < actors.size(); j++) {
pairs.add(new String[]{actors.get(i), actors.get(j)});
}
}
return pairs;
}
public static void main(String[] args) {
String graphPath = args[0];
String actorPath = args[1];
String filePath = args[2];
GameplayInterface gameplay = new GameplayInterface();
gameplay.loadGraph(graphPath);
List<String[]> actorPairs = generateAllActorPairs(actorPath);
gameplay.findConnections(actorPairs,filePath);
}
}
| 7 | 479 | Java |
springreactivenonreactive | ./ProjectTest/Java/springreactivenonreactive.java | // springreactivenonreactive/repository/NonReactiveRepository.java
package projecttest.springreactivenonreactive.repository;
import org.springframework.data.mongodb.repository.MongoRepository;
import org.springframework.stereotype.Repository;
import projecttest.springreactivenonreactive.model.Message;
@Repository
public interface NonReactiveRepository extends MongoRepository<Message, String> {
}
// springreactivenonreactive/repository/ReactiveRepository.java
package projecttest.springreactivenonreactive.repository;
import org.springframework.data.mongodb.repository.ReactiveMongoRepository;
import org.springframework.stereotype.Repository;
import projecttest.springreactivenonreactive.model.Message;
@Repository
public interface ReactiveRepository extends ReactiveMongoRepository<Message, String> {
}
// springreactivenonreactive/model/Message.java
package projecttest.springreactivenonreactive.model;
import java.util.Date;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import lombok.ToString;
@Document(collection = "messages")
@Getter
@Setter
@NoArgsConstructor
@ToString
public class Message {
@Id
private String id;
@NotBlank
private String content;
@NotNull
private Date createdAt = new Date();
}
// springreactivenonreactive/controller/WebFluxController.java
package projecttest.springreactivenonreactive.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import projecttest.springreactivenonreactive.model.Message;
import projecttest.springreactivenonreactive.repository.ReactiveRepository;
import reactor.core.publisher.Mono;
@RestController
public class WebFluxController {
@Autowired
ReactiveRepository reactiveRepository;
@RequestMapping("/webflux/{id}")
public Mono<Message> findByIdReactive(@PathVariable(value = "id") String id) {
return reactiveRepository.findById(id);
}
@PostMapping("/webflux")
public Mono<Message> postReactive(@Valid @RequestBody Message message) {
return reactiveRepository.save(message);
}
@DeleteMapping("/webflux")
public Mono<Void> deleteAllReactive() {
return reactiveRepository.deleteAll();
}
}
// springreactivenonreactive/controller/MVCSyncController.java
package projecttest.springreactivenonreactive.controller;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import projecttest.springreactivenonreactive.model.Message;
import projecttest.springreactivenonreactive.repository.NonReactiveRepository;
@RestController
public class MVCSyncController {
@Autowired
NonReactiveRepository nonReactiveRepository;
@RequestMapping("/mvcsync/{id}")
public Message findById(@PathVariable(value = "id") String id) {
return nonReactiveRepository.findById(id).orElse(null);
}
@PostMapping("/mvcsync")
public Message post(@Valid @RequestBody Message message) {
return nonReactiveRepository.save(message);
}
}
// springreactivenonreactive/controller/MVCAsyncController.java
package projecttest.springreactivenonreactive.controller;
import java.util.concurrent.CompletableFuture;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import projecttest.springreactivenonreactive.model.Message;
import projecttest.springreactivenonreactive.repository.NonReactiveRepository;
@RestController
public class MVCAsyncController {
@Autowired
NonReactiveRepository nonReactiveRepository;
@RequestMapping("/mvcasync/{id}")
public CompletableFuture<Message> findById(@PathVariable(value = "id") String id) {
return CompletableFuture.supplyAsync(() -> nonReactiveRepository.findById(id).orElse(null));
}
@PostMapping("/mvcasync")
public CompletableFuture<Message> post(@Valid @RequestBody Message message) {
return CompletableFuture.supplyAsync(() -> nonReactiveRepository.save(message));
}
}
// springreactivenonreactive/SpringMvcVsWebfluxApplication.java
package projecttest.springreactivenonreactive;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class SpringMvcVsWebfluxApplication {
public static void main(String[] args) {
SpringApplication.run(SpringMvcVsWebfluxApplication.class, args);
}
}
| 7 | 170 | Java |
redis | ./ProjectTest/Java/redis.java | // redis/RedisConfigurationBuilder.java
package projecttest.redis;
import org.apache.ibatis.cache.CacheException;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Map;
import java.util.Properties;
/**
* Converter from the Config to a proper {@link RedisConfig}.
*
* @author Eduardo Macarron
*/
final class RedisConfigurationBuilder {
/**
* This class instance.
*/
private static final RedisConfigurationBuilder INSTANCE = new RedisConfigurationBuilder();
protected static final String SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME = "redis.properties.filename";
protected static final String REDIS_RESOURCE = "redis.properties";
/**
* Hidden constructor, this class can't be instantiated.
*/
private RedisConfigurationBuilder() {
}
/**
* Return this class instance.
*
* @return this class instance.
*/
public static RedisConfigurationBuilder getInstance() {
return INSTANCE;
}
/**
* Parses the Config and builds a new {@link RedisConfig}.
*
* @return the converted {@link RedisConfig}.
*/
public RedisConfig parseConfiguration() {
return parseConfiguration(getClass().getClassLoader());
}
/**
* Parses the Config and builds a new {@link RedisConfig}.
*
* @param the {@link ClassLoader} used to load the {@code memcached.properties} file in classpath.
* @return the converted {@link RedisConfig}.
*/
public RedisConfig parseConfiguration(ClassLoader classLoader) {
Properties config = new Properties();
String redisPropertiesFilename = System.getProperty(SYSTEM_PROPERTY_REDIS_PROPERTIES_FILENAME, REDIS_RESOURCE);
try (InputStream input = classLoader.getResourceAsStream(redisPropertiesFilename)) {
if (input != null) {
config.load(input);
}
} catch (IOException e) {
throw new RuntimeException(
"An error occurred while reading classpath property '" + redisPropertiesFilename + "', see nested exceptions",
e);
}
RedisConfig jedisConfig = new RedisConfig();
setConfigProperties(config, jedisConfig);
return jedisConfig;
}
private void setConfigProperties(Properties properties, RedisConfig jedisConfig) {
if (properties != null) {
MetaObject metaCache = SystemMetaObject.forObject(jedisConfig);
for (Map.Entry<Object, Object> entry : properties.entrySet()) {
String name = (String) entry.getKey();
// All prefix of 'redis.' on property values
if (name != null && name.startsWith("redis.")) {
name = name.substring(6);
} else {
// Skip non prefixed properties
continue;
}
String value = (String) entry.getValue();
if ("serializer".equals(name)) {
if ("kryo".equalsIgnoreCase(value)) {
jedisConfig.setSerializer(KryoSerializer.INSTANCE);
} else if (!"jdk".equalsIgnoreCase(value)) {
// Custom serializer is not supported yet.
throw new CacheException("Unknown serializer: '" + value + "'");
}
} else if (Arrays.asList("sslSocketFactory", "sslParameters", "hostnameVerifier").contains(name)) {
setInstance(metaCache, name, value);
} else if (metaCache.hasSetter(name)) {
Class<?> type = metaCache.getSetterType(name);
if (String.class == type) {
metaCache.setValue(name, value);
} else if (int.class == type || Integer.class == type) {
metaCache.setValue(name, Integer.valueOf(value));
} else if (long.class == type || Long.class == type) {
metaCache.setValue(name, Long.valueOf(value));
} else if (short.class == type || Short.class == type) {
metaCache.setValue(name, Short.valueOf(value));
} else if (byte.class == type || Byte.class == type) {
metaCache.setValue(name, Byte.valueOf(value));
} else if (float.class == type || Float.class == type) {
metaCache.setValue(name, Float.valueOf(value));
} else if (boolean.class == type || Boolean.class == type) {
metaCache.setValue(name, Boolean.valueOf(value));
} else if (double.class == type || Double.class == type) {
metaCache.setValue(name, Double.valueOf(value));
} else {
throw new CacheException("Unsupported property type: '" + name + "' of type " + type);
}
}
}
}
}
protected void setInstance(MetaObject metaCache, String name, String value) {
if (value == null || value.isEmpty()) {
return;
}
Object instance;
try {
Class<?> clazz = Resources.classForName(value);
instance = clazz.getDeclaredConstructor().newInstance();
} catch (Exception e) {
throw new CacheException("Could not instantiate class: '" + value + "'.", e);
}
metaCache.setValue(name, instance);
}
}
// redis/KryoSerializer.java
package projecttest.redis;
import com.esotericsoftware.kryo.kryo5.Kryo;
import com.esotericsoftware.kryo.kryo5.io.Input;
import com.esotericsoftware.kryo.kryo5.io.Output;
import java.util.Arrays;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
/**
* SerializeUtil with Kryo, which is faster and less space consuming.
*
* @author Lei Jiang([email protected])
*/
public enum KryoSerializer implements Serializer {
// Enum singleton, which is preferred approach since Java 1.5
INSTANCE;
/**
* kryo is thread-unsafe, use ThreadLocal.
*/
private ThreadLocal<Kryo> kryos = ThreadLocal.withInitial(Kryo::new);
/**
* Classes which can not resolved by default kryo serializer, which occurs very
* rare(https://github.com/EsotericSoftware/kryo#using-standard-java-serialization) For these classes, we will use
* fallbackSerializer(use JDKSerializer now) to resolve.
*/
private Set<Class<?>> unnormalClassSet;
/**
* Hash codes of unnormal bytes which can not resolved by default kryo serializer, which will be resolved by
* fallbackSerializer
*/
private Set<Integer> unnormalBytesHashCodeSet;
private Serializer fallbackSerializer;
private KryoSerializer() {
unnormalClassSet = ConcurrentHashMap.newKeySet();
unnormalBytesHashCodeSet = ConcurrentHashMap.newKeySet();
fallbackSerializer = JDKSerializer.INSTANCE;// use JDKSerializer as fallback
}
@Override
public byte[] serialize(Object object) {
if (unnormalClassSet.contains(object.getClass())) {
// For unnormal class
return fallbackSerializer.serialize(object);
}
/**
* In the following cases: 1. This class occurs for the first time. 2. This class have occurred and can be resolved
* by default kryo serializer
*/
try (Output output = new Output(200, -1)) {
kryos.get().writeClassAndObject(output, object);
return output.toBytes();
} catch (Exception e) {
// For unnormal class occurred for the first time, exception will be thrown
unnormalClassSet.add(object.getClass());
return fallbackSerializer.serialize(object);// use fallback Serializer to resolve
}
}
@Override
public Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
int hashCode = Arrays.hashCode(bytes);
if (unnormalBytesHashCodeSet.contains(hashCode)) {
// For unnormal bytes
return fallbackSerializer.unserialize(bytes);
}
/**
* In the following cases: 1. This bytes occurs for the first time. 2. This bytes have occurred and can be resolved
* by default kryo serializer
*/
try (Input input = new Input()) {
input.setBuffer(bytes);
return kryos.get().readClassAndObject(input);
} catch (Exception e) {
// For unnormal bytes occurred for the first time, exception will be thrown
unnormalBytesHashCodeSet.add(hashCode);
return fallbackSerializer.unserialize(bytes);// use fallback Serializer to resolve
}
}
}
// redis/Serializer.java
package projecttest.redis;
public interface Serializer {
/**
* Serialize method
*
* @param object
*
* @return serialized bytes
*/
byte[] serialize(Object object);
/**
* Unserialize method
*
* @param bytes
*
* @return unserialized object
*/
Object unserialize(byte[] bytes);
}
// redis/Main.java
package projecttest.redis;
import java.io.BufferedWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author 11293
*/
public class Main {
private static final String DEFAULT_ID = "REDIS";
private static RedisCache cache = new RedisCache(DEFAULT_ID);
public static void main(String[] args) throws IOException {
if (args.length != 2) {
System.err.println("Error: Two arguments required, the first is the path to the input file, and the second is the path to the output file.");
System.exit(1);
}
String inputFile = args[0];
String outputFile = args[1];
List<String> lines = Files.readAllLines(Paths.get(inputFile));
Map<String, String> localCache = new HashMap<>();
for (String line : lines) {
String[] parts = line.split("\\s+");
if (parts.length == 2) {
String key = parts[0];
String value = parts[1];
cache.putObject(key, value);
localCache.put(key, value);
}
}
try (BufferedWriter writer = Files.newBufferedWriter(Paths.get(outputFile))) {
for (String line : lines) {
String[] parts = line.split("\\s+");
if (parts.length == 2) {
String key = parts[0];
String value = (String) cache.getObject(key);
assert value.equals(localCache.get(key));
writer.write(key + " " + value);
writer.newLine();
}
}
}
}
}
// redis/JDKSerializer.java
package projecttest.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import org.apache.ibatis.cache.CacheException;
public enum JDKSerializer implements Serializer {
// Enum singleton, which is preferred approach since Java 1.5
INSTANCE;
private JDKSerializer() {
// prevent instantiation
}
@Override
public byte[] serialize(Object object) {
try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos)) {
oos.writeObject(object);
return baos.toByteArray();
} catch (Exception e) {
throw new CacheException(e);
}
}
@Override
public Object unserialize(byte[] bytes) {
if (bytes == null) {
return null;
}
try (ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(bais)) {
return ois.readObject();
} catch (Exception e) {
throw new CacheException(e);
}
}
}
// redis/RedisCallback.java
package projecttest.redis;
import redis.clients.jedis.Jedis;
public interface RedisCallback {
Object doWithRedis(Jedis jedis);
}
// redis/RedisCache.java
package projecttest.redis;
import org.apache.ibatis.cache.Cache;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import java.util.Map;
import java.util.concurrent.locks.ReadWriteLock;
/**
* Cache adapter for Redis.
*
* @author Eduardo Macarron
*/
public final class RedisCache implements Cache {
private final ReadWriteLock readWriteLock = new DummyReadWriteLock();
private String id;
private static JedisPool pool;
private final RedisConfig redisConfig;
private Integer timeout;
public RedisCache(final String id) {
if (id == null) {
throw new IllegalArgumentException("Cache instances require an ID");
}
this.id = id;
redisConfig = RedisConfigurationBuilder.getInstance().parseConfiguration();
pool = new JedisPool(redisConfig, redisConfig.getHost(), redisConfig.getPort(), redisConfig.getConnectionTimeout(),
redisConfig.getSoTimeout(), redisConfig.getPassword(), redisConfig.getDatabase(), redisConfig.getClientName(),
redisConfig.isSsl(), redisConfig.getSslSocketFactory(), redisConfig.getSslParameters(),
redisConfig.getHostnameVerifier());
}
private Object execute(RedisCallback callback) {
Jedis jedis = pool.getResource();
try {
return callback.doWithRedis(jedis);
} finally {
jedis.close();
}
}
@Override
public String getId() {
return this.id;
}
@Override
public int getSize() {
return (Integer) execute(jedis -> {
Map<byte[], byte[]> result = jedis.hgetAll(id.getBytes());
return result.size();
});
}
@Override
public void putObject(final Object key, final Object value) {
execute(jedis -> {
final byte[] idBytes = id.getBytes();
jedis.hset(idBytes, key.toString().getBytes(), redisConfig.getSerializer().serialize(value));
if (timeout != null && jedis.ttl(idBytes) == -1) {
jedis.expire(idBytes, timeout);
}
return null;
});
}
@Override
public Object getObject(final Object key) {
return execute(
jedis -> redisConfig.getSerializer().unserialize(jedis.hget(id.getBytes(), key.toString().getBytes())));
}
@Override
public Object removeObject(final Object key) {
return execute(jedis -> jedis.hdel(id, key.toString()));
}
@Override
public void clear() {
execute(jedis -> {
jedis.del(id);
return null;
});
}
@Override
public ReadWriteLock getReadWriteLock() {
return readWriteLock;
}
@Override
public String toString() {
return "Redis {" + id + "}";
}
public void setTimeout(Integer timeout) {
this.timeout = timeout;
}
}
// redis/DummyReadWriteLock.java
package projecttest.redis;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
/**
* @author Iwao AVE!
*/
class DummyReadWriteLock implements ReadWriteLock {
private Lock lock = new DummyLock();
@Override
public Lock readLock() {
return lock;
}
@Override
public Lock writeLock() {
return lock;
}
static class DummyLock implements Lock {
@Override
public void lock() {
// Not implemented
}
@Override
public void lockInterruptibly() throws InterruptedException {
// Not implemented
}
@Override
public boolean tryLock() {
return true;
}
@Override
public boolean tryLock(long paramLong, TimeUnit paramTimeUnit) throws InterruptedException {
return true;
}
@Override
public void unlock() {
// Not implemented
}
@Override
public Condition newCondition() {
return null;
}
}
}
// redis/RedisConfig.java
package projecttest.redis;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.SSLSocketFactory;
public class RedisConfig extends JedisPoolConfig {
private String host = Protocol.DEFAULT_HOST;
private int port = Protocol.DEFAULT_PORT;
private int connectionTimeout = Protocol.DEFAULT_TIMEOUT;
private int soTimeout = Protocol.DEFAULT_TIMEOUT;
private String password;
private int database = Protocol.DEFAULT_DATABASE;
private String clientName;
private boolean ssl;
private SSLSocketFactory sslSocketFactory;
private SSLParameters sslParameters;
private HostnameVerifier hostnameVerifier;
private Serializer serializer = JDKSerializer.INSTANCE;
public boolean isSsl() {
return ssl;
}
public void setSsl(boolean ssl) {
this.ssl = ssl;
}
public SSLSocketFactory getSslSocketFactory() {
return sslSocketFactory;
}
public void setSslSocketFactory(SSLSocketFactory sslSocketFactory) {
this.sslSocketFactory = sslSocketFactory;
}
public SSLParameters getSslParameters() {
return sslParameters;
}
public void setSslParameters(SSLParameters sslParameters) {
this.sslParameters = sslParameters;
}
public HostnameVerifier getHostnameVerifier() {
return hostnameVerifier;
}
public void setHostnameVerifier(HostnameVerifier hostnameVerifier) {
this.hostnameVerifier = hostnameVerifier;
}
public String getHost() {
return host;
}
public void setHost(String host) {
if (host == null || host.isEmpty()) {
host = Protocol.DEFAULT_HOST;
}
this.host = host;
}
public int getPort() {
return port;
}
public void setPort(int port) {
this.port = port;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
if (password == null || password.isEmpty()) {
password = null;
}
this.password = password;
}
public int getDatabase() {
return database;
}
public void setDatabase(int database) {
this.database = database;
}
public String getClientName() {
return clientName;
}
public void setClientName(String clientName) {
if (clientName == null || clientName.isEmpty()) {
clientName = null;
}
this.clientName = clientName;
}
public int getConnectionTimeout() {
return connectionTimeout;
}
public void setConnectionTimeout(int connectionTimeout) {
this.connectionTimeout = connectionTimeout;
}
public int getSoTimeout() {
return soTimeout;
}
public void setSoTimeout(int soTimeout) {
this.soTimeout = soTimeout;
}
public Serializer getSerializer() {
return serializer;
}
public void setSerializer(Serializer serializer) {
this.serializer = serializer;
}
}
| 9 | 651 | Java |
ckmeans | ./ProjectTest/JavaScript/ckmeans.js | // ckmeans/numeric_sort.js
/**
* Sort an array of numbers by their numeric value, ensuring that the
* array is not changed in place.
*
* This is necessary because the default behavior of .sort
* in JavaScript is to sort arrays as string values
*
* [1, 10, 12, 102, 20].sort()
* // output
* [1, 10, 102, 12, 20]
*
* @param {Array<number>} x input array
* @return {Array<number>} sorted array
* @private
* @example
* numericSort([3, 2, 1]) // => [1, 2, 3]
*/
function numericSort(x) {
return (
x
// ensure the array is not changed in-place
.slice()
// comparator function that treats input as numeric
.sort(function (a, b) {
return a - b;
})
);
}
export default numericSort;
// ckmeans/ckmeans.js
import makeMatrix from "./make_matrix.js";
import numericSort from "./numeric_sort.js";
import uniqueCountSorted from "./unique_count_sorted.js";
/**
* Generates incrementally computed values based on the sums and sums of
* squares for the data array
*
* @private
* @param {number} j
* @param {number} i
* @param {Array<number>} sums
* @param {Array<number>} sumsOfSquares
* @return {number}
* @example
* ssq(0, 1, [-1, 0, 2], [1, 1, 5]);
*/
function ssq(j, i, sums, sumsOfSquares) {
let sji; // s(j, i)
if (j > 0) {
const muji = (sums[i] - sums[j - 1]) / (i - j + 1); // mu(j, i)
sji =
sumsOfSquares[i] - sumsOfSquares[j - 1] - (i - j + 1) * muji * muji;
} else {
sji = sumsOfSquares[i] - (sums[i] * sums[i]) / (i + 1);
}
if (sji < 0) {
return 0;
}
return sji;
}
/**
* Function that recursively divides and conquers computations
* for cluster j
*
* @private
* @param {number} iMin Minimum index in cluster to be computed
* @param {number} iMax Maximum index in cluster to be computed
* @param {number} cluster Index of the cluster currently being computed
* @param {Array<Array<number>>} matrix
* @param {Array<Array<number>>} backtrackMatrix
* @param {Array<number>} sums
* @param {Array<number>} sumsOfSquares
*/
function fillMatrixColumn(
iMin,
iMax,
cluster,
matrix,
backtrackMatrix,
sums,
sumsOfSquares
) {
if (iMin > iMax) {
return;
}
// Start at midpoint between iMin and iMax
const i = Math.floor((iMin + iMax) / 2);
matrix[cluster][i] = matrix[cluster - 1][i - 1];
backtrackMatrix[cluster][i] = i;
let jlow = cluster; // the lower end for j
if (iMin > cluster) {
jlow = Math.max(jlow, backtrackMatrix[cluster][iMin - 1] || 0);
}
jlow = Math.max(jlow, backtrackMatrix[cluster - 1][i] || 0);
let jhigh = i - 1; // the upper end for j
if (iMax < matrix[0].length - 1) {
/* c8 ignore start */
jhigh = Math.min(jhigh, backtrackMatrix[cluster][iMax + 1] || 0);
/* c8 ignore end */
}
let sji;
let sjlowi;
let ssqjlow;
let ssqj;
for (let j = jhigh; j >= jlow; --j) {
sji = ssq(j, i, sums, sumsOfSquares);
if (sji + matrix[cluster - 1][jlow - 1] >= matrix[cluster][i]) {
break;
}
// Examine the lower bound of the cluster border
sjlowi = ssq(jlow, i, sums, sumsOfSquares);
ssqjlow = sjlowi + matrix[cluster - 1][jlow - 1];
if (ssqjlow < matrix[cluster][i]) {
// Shrink the lower bound
matrix[cluster][i] = ssqjlow;
backtrackMatrix[cluster][i] = jlow;
}
jlow++;
ssqj = sji + matrix[cluster - 1][j - 1];
if (ssqj < matrix[cluster][i]) {
matrix[cluster][i] = ssqj;
backtrackMatrix[cluster][i] = j;
}
}
fillMatrixColumn(
iMin,
i - 1,
cluster,
matrix,
backtrackMatrix,
sums,
sumsOfSquares
);
fillMatrixColumn(
i + 1,
iMax,
cluster,
matrix,
backtrackMatrix,
sums,
sumsOfSquares
);
}
/**
* Initializes the main matrices used in Ckmeans and kicks
* off the divide and conquer cluster computation strategy
*
* @private
* @param {Array<number>} data sorted array of values
* @param {Array<Array<number>>} matrix
* @param {Array<Array<number>>} backtrackMatrix
*/
function fillMatrices(data, matrix, backtrackMatrix) {
const nValues = matrix[0].length;
// Shift values by the median to improve numeric stability
const shift = data[Math.floor(nValues / 2)];
// Cumulative sum and cumulative sum of squares for all values in data array
const sums = [];
const sumsOfSquares = [];
// Initialize first column in matrix & backtrackMatrix
for (let i = 0, shiftedValue; i < nValues; ++i) {
shiftedValue = data[i] - shift;
if (i === 0) {
sums.push(shiftedValue);
sumsOfSquares.push(shiftedValue * shiftedValue);
} else {
sums.push(sums[i - 1] + shiftedValue);
sumsOfSquares.push(
sumsOfSquares[i - 1] + shiftedValue * shiftedValue
);
}
// Initialize for cluster = 0
matrix[0][i] = ssq(0, i, sums, sumsOfSquares);
backtrackMatrix[0][i] = 0;
}
// Initialize the rest of the columns
let iMin;
for (let cluster = 1; cluster < matrix.length; ++cluster) {
if (cluster < matrix.length - 1) {
iMin = cluster;
} else {
// No need to compute matrix[K-1][0] ... matrix[K-1][N-2]
iMin = nValues - 1;
}
fillMatrixColumn(
iMin,
nValues - 1,
cluster,
matrix,
backtrackMatrix,
sums,
sumsOfSquares
);
}
}
/**
* Ckmeans clustering is an improvement on heuristic-based clustering
* approaches like Jenks. The algorithm was developed in
* [Haizhou Wang and Mingzhou Song](http://journal.r-project.org/archive/2011-2/RJournal_2011-2_Wang+Song.pdf)
* as a [dynamic programming](https://en.wikipedia.org/wiki/Dynamic_programming) approach
* to the problem of clustering numeric data into groups with the least
* within-group sum-of-squared-deviations.
*
* Minimizing the difference within groups - what Wang & Song refer to as
* `withinss`, or within sum-of-squares, means that groups are optimally
* homogenous within and the data is split into representative groups.
* This is very useful for visualization, where you may want to represent
* a continuous variable in discrete color or style groups. This function
* can provide groups that emphasize differences between data.
*
* Being a dynamic approach, this algorithm is based on two matrices that
* store incrementally-computed values for squared deviations and backtracking
* indexes.
*
* This implementation is based on Ckmeans 3.4.6, which introduced a new divide
* and conquer approach that improved runtime from O(kn^2) to O(kn log(n)).
*
* Unlike the [original implementation](https://cran.r-project.org/web/packages/Ckmeans.1d.dp/index.html),
* this implementation does not include any code to automatically determine
* the optimal number of clusters: this information needs to be explicitly
* provided.
*
* ### References
* _Ckmeans.1d.dp: Optimal k-means Clustering in One Dimension by Dynamic
* Programming_ Haizhou Wang and Mingzhou Song ISSN 2073-4859
*
* from The R Journal Vol. 3/2, December 2011
* @param {Array<number>} x input data, as an array of number values
* @param {number} nClusters number of desired classes. This cannot be
* greater than the number of values in the data array.
* @returns {Array<Array<number>>} clustered input
* @throws {Error} if the number of requested clusters is higher than the size of the data
* @example
* ckmeans([-1, 2, -1, 2, 4, 5, 6, -1, 2, -1], 3);
* // The input, clustered into groups of similar numbers.
* //= [[-1, -1, -1, -1], [2, 2, 2], [4, 5, 6]]);
*/
function ckmeans(x, nClusters) {
if (nClusters > x.length) {
throw new Error(
"cannot generate more classes than there are data values"
);
}
const sorted = numericSort(x);
// we'll use this as the maximum number of clusters
const uniqueCount = uniqueCountSorted(sorted);
// if all of the input values are identical, there's one cluster
// with all of the input in it.
if (uniqueCount === 1) {
return [sorted];
}
// named 'S' originally
const matrix = makeMatrix(nClusters, sorted.length);
// named 'J' originally
const backtrackMatrix = makeMatrix(nClusters, sorted.length);
// This is a dynamic programming way to solve the problem of minimizing
// within-cluster sum of squares. It's similar to linear regression
// in this way, and this calculation incrementally computes the
// sum of squares that are later read.
fillMatrices(sorted, matrix, backtrackMatrix);
// The real work of Ckmeans clustering happens in the matrix generation:
// the generated matrices encode all possible clustering combinations, and
// once they're generated we can solve for the best clustering groups
// very quickly.
const clusters = [];
let clusterRight = backtrackMatrix[0].length - 1;
// Backtrack the clusters from the dynamic programming matrix. This
// starts at the bottom-right corner of the matrix (if the top-left is 0, 0),
// and moves the cluster target with the loop.
for (let cluster = backtrackMatrix.length - 1; cluster >= 0; cluster--) {
const clusterLeft = backtrackMatrix[cluster][clusterRight];
// fill the cluster from the sorted input by taking a slice of the
// array. the backtrack matrix makes this easy - it stores the
// indexes where the cluster should start and end.
clusters[cluster] = sorted.slice(clusterLeft, clusterRight + 1);
if (cluster > 0) {
clusterRight = clusterLeft - 1;
}
}
return clusters;
}
export default ckmeans;
// ckmeans/unique_count_sorted.js
/**
* For a sorted input, counting the number of unique values
* is possible in constant time and constant memory. This is
* a simple implementation of the algorithm.
*
* Values are compared with `===`, so objects and non-primitive objects
* are not handled in any special way.
*
* @param {Array<*>} x an array of any kind of value
* @returns {number} count of unique values
* @example
* uniqueCountSorted([1, 2, 3]); // => 3
* uniqueCountSorted([1, 1, 1]); // => 1
*/
function uniqueCountSorted(x) {
let uniqueValueCount = 0;
let lastSeenValue;
for (let i = 0; i < x.length; i++) {
if (i === 0 || x[i] !== lastSeenValue) {
lastSeenValue = x[i];
uniqueValueCount++;
}
}
return uniqueValueCount;
}
export default uniqueCountSorted;
// ckmeans/make_matrix.js
/**
* Create a new column x row matrix.
*
* @private
* @param {number} columns
* @param {number} rows
* @return {Array<Array<number>>} matrix
* @example
* makeMatrix(10, 10);
*/
function makeMatrix(columns, rows) {
const matrix = [];
for (let i = 0; i < columns; i++) {
const column = [];
for (let j = 0; j < rows; j++) {
column.push(0);
}
matrix.push(column);
}
return matrix;
}
export default makeMatrix;
| 4 | 364 | JavaScript |
validate | ./ProjectTest/JavaScript/validate.js | // validate/map.js
// We use a global `WeakMap` to store class-specific information (such as
// options) instead of storing it as a symbol property on each error class to
// ensure:
// - This is not exposed to users or plugin authors
// - This does not change how the error class is printed
// We use a `WeakMap` instead of an object since the key should be the error
// class, not its `name`, because classes might have duplicate names.
export const classesData = new WeakMap()
// The same but for error instances
export const instancesData = new WeakMap()
// validate/validate.js
import { classesData } from './map.js'
// We forbid subclasses that are not known, i.e. not passed to
// `ErrorClass.subclass()`
// - They would not be validated at load time
// - The class would not be normalized until its first instantiation
// - E.g. its `prototype.name` might be missing
// - The list of `ErrorClasses` would be potentially incomplete
// - E.g. `ErrorClass.parse()` would not be able to parse an error class
// until its first instantiation
// This usually happens if a class was:
// - Not passed to the `custom` option of `*Error.subclass()`
// - But was extended from a known class
export const validateSubclass = (ErrorClass) => {
if (classesData.has(ErrorClass)) {
return
}
const { name } = ErrorClass
const { name: parentName } = Object.getPrototypeOf(ErrorClass)
throw new Error(
`"new ${name}()" must not be directly called.
This error class should be created like this instead:
export const ${name} = ${parentName}.subclass('${name}')`,
)
}
| 2 | 37 | JavaScript |
convex | ./ProjectTest/JavaScript/convex.js | // convex/Convex.js
var Shape = require('./Shape')
, vec2 = require('./math/vec2')
, dot = vec2.dot
, polyk = require('./math/polyk')
, shallowClone = require('./Utils').shallowClone;
module.exports = Convex;
/**
* Convex shape class.
* @class Convex
* @constructor
* @extends Shape
* @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
* @param {Array} [options.vertices] An array of vertices that span this shape. Vertices are given in counter-clockwise (CCW) direction.
* @example
* var body = new Body({ mass: 1 });
* var vertices = [[-1,-1], [1,-1], [1,1], [-1,1]];
* var convexShape = new Convex({
* vertices: vertices
* });
* body.addShape(convexShape);
*/
function Convex(options){
options = options ? shallowClone(options) : {};
/**
* Vertices defined in the local frame.
* @property vertices
* @type {Array}
*/
this.vertices = [];
// Copy the verts
var vertices = options.vertices !== undefined ? options.vertices : [];
for(var i=0; i < vertices.length; i++){
this.vertices.push(vec2.clone(vertices[i]));
}
/**
* Edge normals defined in the local frame, pointing out of the shape.
* @property normals
* @type {Array}
*/
var normals = this.normals = [];
for(var i=0; i < vertices.length; i++){
normals.push(vec2.create());
}
this.updateNormals();
/**
* The center of mass of the Convex
* @property centerOfMass
* @type {Array}
*/
this.centerOfMass = vec2.create();
/**
* Triangulated version of this convex. The structure is Array of 3-Arrays, and each subarray contains 3 integers, referencing the vertices.
* @property triangles
* @type {Array}
*/
this.triangles = [];
if(this.vertices.length){
this.updateTriangles();
this.updateCenterOfMass();
}
/**
* The bounding radius of the convex
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
options.type = options.type || Shape.CONVEX;
Shape.call(this, options);
this.updateBoundingRadius();
this.updateArea();
if(this.area < 0){
throw new Error("Convex vertices must be given in counter-clockwise winding.");
}
}
Convex.prototype = new Shape();
Convex.prototype.constructor = Convex;
var tmpVec1 = vec2.create();
var tmpVec2 = vec2.create();
Convex.prototype.updateNormals = function(){
var vertices = this.vertices;
var normals = this.normals;
for(var i = 0; i < vertices.length; i++){
var worldPoint0 = vertices[i];
var worldPoint1 = vertices[(i+1) % vertices.length];
var normal = normals[i];
vec2.subtract(normal, worldPoint1, worldPoint0);
// Get normal - just rotate 90 degrees since vertices are given in CCW
vec2.rotate90cw(normal, normal);
vec2.normalize(normal, normal);
}
};
/**
* Project a Convex onto a world-oriented axis
* @method projectOntoAxis
* @static
* @param {Array} offset
* @param {Array} localAxis
* @param {Array} result
*/
Convex.prototype.projectOntoLocalAxis = function(localAxis, result){
var max=null,
min=null,
v,
value,
localAxis = tmpVec1;
// Get projected position of all vertices
for(var i=0; i<this.vertices.length; i++){
v = this.vertices[i];
value = dot(v, localAxis);
if(max === null || value > max){
max = value;
}
if(min === null || value < min){
min = value;
}
}
if(min > max){
var t = min;
min = max;
max = t;
}
vec2.set(result, min, max);
};
Convex.prototype.projectOntoWorldAxis = function(localAxis, shapeOffset, shapeAngle, result){
var worldAxis = tmpVec2;
this.projectOntoLocalAxis(localAxis, result);
// Project the position of the body onto the axis - need to add this to the result
if(shapeAngle !== 0){
vec2.rotate(worldAxis, localAxis, shapeAngle);
} else {
worldAxis = localAxis;
}
var offset = dot(shapeOffset, worldAxis);
vec2.set(result, result[0] + offset, result[1] + offset);
};
/**
* Update the .triangles property
* @method updateTriangles
*/
Convex.prototype.updateTriangles = function(){
this.triangles.length = 0;
// Rewrite on polyk notation, array of numbers
var polykVerts = [];
for(var i=0; i<this.vertices.length; i++){
var v = this.vertices[i];
polykVerts.push(v[0],v[1]);
}
// Triangulate
var triangles = polyk.Triangulate(polykVerts);
// Loop over all triangles, add their inertia contributions to I
for(var i=0; i<triangles.length; i+=3){
var id1 = triangles[i],
id2 = triangles[i+1],
id3 = triangles[i+2];
// Add to triangles
this.triangles.push([id1,id2,id3]);
}
};
var updateCenterOfMass_centroid = vec2.create(),
updateCenterOfMass_centroid_times_mass = vec2.create(),
updateCenterOfMass_a = vec2.create(),
updateCenterOfMass_b = vec2.create(),
updateCenterOfMass_c = vec2.create();
/**
* Update the .centerOfMass property.
* @method updateCenterOfMass
*/
Convex.prototype.updateCenterOfMass = function(){
var triangles = this.triangles,
verts = this.vertices,
cm = this.centerOfMass,
centroid = updateCenterOfMass_centroid,
a = updateCenterOfMass_a,
b = updateCenterOfMass_b,
c = updateCenterOfMass_c,
centroid_times_mass = updateCenterOfMass_centroid_times_mass;
vec2.set(cm,0,0);
var totalArea = 0;
for(var i=0; i!==triangles.length; i++){
var t = triangles[i],
a = verts[t[0]],
b = verts[t[1]],
c = verts[t[2]];
vec2.centroid(centroid,a,b,c);
// Get mass for the triangle (density=1 in this case)
// http://math.stackexchange.com/questions/80198/area-of-triangle-via-vectors
var m = triangleArea(a,b,c);
totalArea += m;
// Add to center of mass
vec2.scale(centroid_times_mass, centroid, m);
vec2.add(cm, cm, centroid_times_mass);
}
vec2.scale(cm,cm,1/totalArea);
};
/**
* Compute the moment of inertia of the Convex.
* @method computeMomentOfInertia
* @return {Number}
* @see http://www.gamedev.net/topic/342822-moment-of-inertia-of-a-polygon-2d/
*/
Convex.prototype.computeMomentOfInertia = function(){
var denom = 0.0,
numer = 0.0,
N = this.vertices.length;
for(var j = N-1, i = 0; i < N; j = i, i ++){
var p0 = this.vertices[j];
var p1 = this.vertices[i];
var a = Math.abs(vec2.crossLength(p0,p1));
var b = dot(p1,p1) + dot(p1,p0) + dot(p0,p0);
denom += a * b;
numer += a;
}
return (1.0 / 6.0) * (denom / numer);
};
/**
* Updates the .boundingRadius property
* @method updateBoundingRadius
*/
Convex.prototype.updateBoundingRadius = function(){
var verts = this.vertices,
r2 = 0;
for(var i=0; i!==verts.length; i++){
var l2 = vec2.squaredLength(verts[i]);
if(l2 > r2){
r2 = l2;
}
}
this.boundingRadius = Math.sqrt(r2);
};
/**
* Get the area of the triangle spanned by the three points a, b, c. The area is positive if the points are given in counter-clockwise order, otherwise negative.
* @static
* @method triangleArea
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Number}
* @deprecated
*/
Convex.triangleArea = triangleArea;
function triangleArea(a,b,c){
return (((b[0] - a[0])*(c[1] - a[1]))-((c[0] - a[0])*(b[1] - a[1]))) * 0.5;
}
/**
* Update the .area
* @method updateArea
*/
Convex.prototype.updateArea = function(){
this.updateTriangles();
this.area = 0;
var triangles = this.triangles,
verts = this.vertices;
for(var i=0; i!==triangles.length; i++){
var t = triangles[i],
a = verts[t[0]],
b = verts[t[1]],
c = verts[t[2]];
// Get mass for the triangle (density=1 in this case)
var m = triangleArea(a,b,c);
this.area += m;
}
};
/**
* @method computeAABB
* @param {AABB} out
* @param {Array} position
* @param {Number} angle
* @todo: approximate with a local AABB?
*/
Convex.prototype.computeAABB = function(out, position, angle){
out.setFromPoints(this.vertices, position, angle, 0);
};
var intersectConvex_rayStart = vec2.create();
var intersectConvex_rayEnd = vec2.create();
var intersectConvex_normal = vec2.create();
/**
* @method raycast
* @param {RaycastResult} result
* @param {Ray} ray
* @param {array} position
* @param {number} angle
*/
Convex.prototype.raycast = function(result, ray, position, angle){
var rayStart = intersectConvex_rayStart;
var rayEnd = intersectConvex_rayEnd;
var normal = intersectConvex_normal;
var vertices = this.vertices;
// Transform to local shape space
vec2.toLocalFrame(rayStart, ray.from, position, angle);
vec2.toLocalFrame(rayEnd, ray.to, position, angle);
var n = vertices.length;
for (var i = 0; i < n && !result.shouldStop(ray); i++) {
var q1 = vertices[i];
var q2 = vertices[(i+1) % n];
var delta = vec2.getLineSegmentsIntersectionFraction(rayStart, rayEnd, q1, q2);
if(delta >= 0){
vec2.subtract(normal, q2, q1);
vec2.rotate(normal, normal, -Math.PI / 2 + angle);
vec2.normalize(normal, normal);
ray.reportIntersection(result, delta, normal, i);
}
}
};
var pic_r0 = vec2.create();
var pic_r1 = vec2.create();
Convex.prototype.pointTest = function(localPoint){
var r0 = pic_r0,
r1 = pic_r1,
verts = this.vertices,
lastCross = null,
numVerts = verts.length;
for(var i=0; i < numVerts + 1; i++){
var v0 = verts[i % numVerts],
v1 = verts[(i + 1) % numVerts];
vec2.subtract(r0, v0, localPoint);
vec2.subtract(r1, v1, localPoint);
var cross = vec2.crossLength(r0,r1);
if(lastCross === null){
lastCross = cross;
}
// If we got a different sign of the distance vector, the point is out of the polygon
if(cross * lastCross < 0){
return false;
}
lastCross = cross;
}
return true;
};
// convex/math/vec2.js
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
* @class vec2
*/
var vec2 = module.exports = {};
var Utils = require('../Utils');
/**
* Make a cross product and only return the z component
* @method crossLength
* @static
* @param {Array} a
* @param {Array} b
* @return {Number}
*/
vec2.crossLength = function(a,b){
return a[0] * b[1] - a[1] * b[0];
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossVZ
* @static
* @param {Array} out
* @param {Array} vec
* @param {Number} zcomp
* @return {Array}
*/
vec2.crossVZ = function(out, vec, zcomp){
vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossZV
* @static
* @param {Array} out
* @param {Number} zcomp
* @param {Array} vec
* @return {Array}
*/
vec2.crossZV = function(out, zcomp, vec){
vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Rotate a vector by an angle
* @method rotate
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate = function(out,a,angle){
if(angle !== 0){
var c = Math.cos(angle),
s = Math.sin(angle),
x = a[0],
y = a[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
} else {
out[0] = a[0];
out[1] = a[1];
}
return out;
};
/**
* Rotate a vector 90 degrees clockwise
* @method rotate90cw
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate90cw = function(out, a) {
var x = a[0];
var y = a[1];
out[0] = y;
out[1] = -x;
return out;
};
/**
* Transform a point position to local frame.
* @method toLocalFrame
* @param {Array} out
* @param {Array} worldPoint
* @param {Array} framePosition
* @param {Number} frameAngle
* @return {Array}
*/
vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldPoint[0] - framePosition[0],
y = worldPoint[1] - framePosition[1];
out[0] = c * x - s * y;
out[1] = s * x + c * y;
return out;
};
/**
* Transform a point position to global frame.
* @method toGlobalFrame
* @param {Array} out
* @param {Array} localPoint
* @param {Array} framePosition
* @param {Number} frameAngle
*/
vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
var c = Math.cos(frameAngle),
s = Math.sin(frameAngle),
x = localPoint[0],
y = localPoint[1],
addX = framePosition[0],
addY = framePosition[1];
out[0] = c * x - s * y + addX;
out[1] = s * x + c * y + addY;
};
/**
* Transform a vector to local frame.
* @method vectorToLocalFrame
* @param {Array} out
* @param {Array} worldVector
* @param {Number} frameAngle
* @return {Array}
*/
vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldVector[0],
y = worldVector[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
return out;
};
/**
* Transform a vector to global frame.
* @method vectorToGlobalFrame
* @param {Array} out
* @param {Array} localVector
* @param {Number} frameAngle
*/
vec2.vectorToGlobalFrame = vec2.rotate;
/**
* Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
* @method centroid
* @static
* @param {Array} out
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Array} The "out" vector.
*/
vec2.centroid = function(out, a, b, c){
vec2.add(out, a, b);
vec2.add(out, out, c);
vec2.scale(out, out, 1/3);
return out;
};
/**
* Creates a new, empty vec2
* @static
* @method create
* @return {Array} a new 2D vector
*/
vec2.create = function() {
var out = new Utils.ARRAY_TYPE(2);
out[0] = 0;
out[1] = 0;
return out;
};
/**
* Creates a new vec2 initialized with values from an existing vector
* @static
* @method clone
* @param {Array} a vector to clone
* @return {Array} a new 2D vector
*/
vec2.clone = function(a) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Creates a new vec2 initialized with the given values
* @static
* @method fromValues
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} a new 2D vector
*/
vec2.fromValues = function(x, y) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = x;
out[1] = y;
return out;
};
/**
* Copy the values from one vec2 to another
* @static
* @method copy
* @param {Array} out the receiving vector
* @param {Array} a the source vector
* @return {Array} out
*/
vec2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Set the components of a vec2 to the given values
* @static
* @method set
* @param {Array} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} out
*/
vec2.set = function(out, x, y) {
out[0] = x;
out[1] = y;
return out;
};
/**
* Adds two vec2's
* @static
* @method add
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
};
/**
* Subtracts two vec2's
* @static
* @method subtract
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
};
/**
* Multiplies two vec2's
* @static
* @method multiply
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
};
/**
* Divides two vec2's
* @static
* @method divide
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
};
/**
* Scales a vec2 by a scalar number
* @static
* @method scale
* @param {Array} out the receiving vector
* @param {Array} a the vector to scale
* @param {Number} b amount to scale the vector by
* @return {Array} out
*/
vec2.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
};
/**
* Calculates the euclidian distance between two vec2's
* @static
* @method distance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} distance between a and b
*/
vec2.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared euclidian distance between two vec2's
* @static
* @method squaredDistance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} squared distance between a and b
*/
vec2.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x*x + y*y;
};
/**
* Calculates the length of a vec2
* @static
* @method length
* @param {Array} a vector to calculate length of
* @return {Number} length of a
*/
vec2.length = function (a) {
var x = a[0],
y = a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared length of a vec2
* @static
* @method squaredLength
* @param {Array} a vector to calculate squared length of
* @return {Number} squared length of a
*/
vec2.squaredLength = function (a) {
var x = a[0],
y = a[1];
return x*x + y*y;
};
/**
* Negates the components of a vec2
* @static
* @method negate
* @param {Array} out the receiving vector
* @param {Array} a vector to negate
* @return {Array} out
*/
vec2.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
};
/**
* Normalize a vec2
* @static
* @method normalize
* @param {Array} out the receiving vector
* @param {Array} a vector to normalize
* @return {Array} out
*/
vec2.normalize = function(out, a) {
var x = a[0],
y = a[1];
var len = x*x + y*y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
};
/**
* Calculates the dot product of two vec2's
* @static
* @method dot
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} dot product of a and b
*/
vec2.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/**
* Returns a string representation of a vector
* @static
* @method str
* @param {Array} vec vector to represent as a string
* @return {String} string representation of the vector
*/
vec2.str = function (a) {
return 'vec2(' + a[0] + ', ' + a[1] + ')';
};
/**
* Linearly interpolate/mix two vectors.
* @static
* @method lerp
* @param {Array} out
* @param {Array} a First vector
* @param {Array} b Second vector
* @param {number} t Lerp factor
*/
vec2.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
};
/**
* Reflect a vector along a normal.
* @static
* @method reflect
* @param {Array} out
* @param {Array} vector
* @param {Array} normal
*/
vec2.reflect = function(out, vector, normal){
var dot = vector[0] * normal[0] + vector[1] * normal[1];
out[0] = vector[0] - 2 * normal[0] * dot;
out[1] = vector[1] - 2 * normal[1] * dot;
};
/**
* Get the intersection point between two line segments.
* @static
* @method getLineSegmentsIntersection
* @param {Array} out
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {boolean} True if there was an intersection, otherwise false.
*/
vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) {
var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3);
if(t < 0){
return false;
} else {
out[0] = p0[0] + (t * (p1[0] - p0[0]));
out[1] = p0[1] + (t * (p1[1] - p0[1]));
return true;
}
};
/**
* Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
* @static
* @method getLineSegmentsIntersectionFraction
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
*/
vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) {
var s1_x = p1[0] - p0[0];
var s1_y = p1[1] - p0[1];
var s2_x = p3[0] - p2[0];
var s2_y = p3[1] - p2[1];
var s, t;
s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
return t;
}
return -1; // No collision
};
// convex/math/polyk.js
/*
PolyK library
url: http://polyk.ivank.net
Released under MIT licence.
Copyright (c) 2012 Ivan Kuckir
Permission is hereby granted, free of charge, to any person
obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without
restriction, including without limitation the rights to use,
copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the
Software is furnished to do so, subject to the following
conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
*/
var PolyK = {};
/*
Is Polygon self-intersecting?
O(n^2)
*/
/*
PolyK.IsSimple = function(p)
{
var n = p.length>>1;
if(n<4) return true;
var a1 = new PolyK._P(), a2 = new PolyK._P();
var b1 = new PolyK._P(), b2 = new PolyK._P();
var c = new PolyK._P();
for(var i=0; i<n; i++)
{
a1.x = p[2*i ];
a1.y = p[2*i+1];
if(i==n-1) { a2.x = p[0 ]; a2.y = p[1 ]; }
else { a2.x = p[2*i+2]; a2.y = p[2*i+3]; }
for(var j=0; j<n; j++)
{
if(Math.abs(i-j) < 2) continue;
if(j==n-1 && i==0) continue;
if(i==n-1 && j==0) continue;
b1.x = p[2*j ];
b1.y = p[2*j+1];
if(j==n-1) { b2.x = p[0 ]; b2.y = p[1 ]; }
else { b2.x = p[2*j+2]; b2.y = p[2*j+3]; }
if(PolyK._GetLineIntersection(a1,a2,b1,b2,c) != null) return false;
}
}
return true;
}
PolyK.IsConvex = function(p)
{
if(p.length<6) return true;
var l = p.length - 4;
for(var i=0; i<l; i+=2)
if(!PolyK._convex(p[i], p[i+1], p[i+2], p[i+3], p[i+4], p[i+5])) return false;
if(!PolyK._convex(p[l ], p[l+1], p[l+2], p[l+3], p[0], p[1])) return false;
if(!PolyK._convex(p[l+2], p[l+3], p[0 ], p[1 ], p[2], p[3])) return false;
return true;
}
*/
PolyK.GetArea = function(p)
{
if(p.length <6) return 0;
var l = p.length - 2;
var sum = 0;
for(var i=0; i<l; i+=2)
sum += (p[i+2]-p[i]) * (p[i+1]+p[i+3]);
sum += (p[0]-p[l]) * (p[l+1]+p[1]);
return - sum * 0.5;
}
/*
PolyK.GetAABB = function(p)
{
var minx = Infinity;
var miny = Infinity;
var maxx = -minx;
var maxy = -miny;
for(var i=0; i<p.length; i+=2)
{
minx = Math.min(minx, p[i ]);
maxx = Math.max(maxx, p[i ]);
miny = Math.min(miny, p[i+1]);
maxy = Math.max(maxy, p[i+1]);
}
return {x:minx, y:miny, width:maxx-minx, height:maxy-miny};
}
*/
PolyK.Triangulate = function(p)
{
var n = p.length>>1;
if(n<3) return [];
var tgs = [];
var avl = [];
for(var i=0; i<n; i++) avl.push(i);
var i = 0;
var al = n;
while(al > 3)
{
var i0 = avl[(i+0)%al];
var i1 = avl[(i+1)%al];
var i2 = avl[(i+2)%al];
var ax = p[2*i0], ay = p[2*i0+1];
var bx = p[2*i1], by = p[2*i1+1];
var cx = p[2*i2], cy = p[2*i2+1];
var earFound = false;
if(PolyK._convex(ax, ay, bx, by, cx, cy))
{
earFound = true;
for(var j=0; j<al; j++)
{
var vi = avl[j];
if(vi==i0 || vi==i1 || vi==i2) continue;
if(PolyK._PointInTriangle(p[2*vi], p[2*vi+1], ax, ay, bx, by, cx, cy)) {earFound = false; break;}
}
}
if(earFound)
{
tgs.push(i0, i1, i2);
avl.splice((i+1)%al, 1);
al--;
i= 0;
}
else if(i++ > 3*al) break; // no convex angles :(
}
tgs.push(avl[0], avl[1], avl[2]);
return tgs;
}
/*
PolyK.ContainsPoint = function(p, px, py)
{
var n = p.length>>1;
var ax, ay, bx = p[2*n-2]-px, by = p[2*n-1]-py;
var depth = 0;
for(var i=0; i<n; i++)
{
ax = bx; ay = by;
bx = p[2*i ] - px;
by = p[2*i+1] - py;
if(ay< 0 && by< 0) continue; // both "up" or both "donw"
if(ay>=0 && by>=0) continue; // both "up" or both "donw"
if(ax< 0 && bx< 0) continue;
var lx = ax + (bx-ax)*(-ay)/(by-ay);
if(lx>0) depth++;
}
return (depth & 1) == 1;
}
PolyK.Slice = function(p, ax, ay, bx, by)
{
if(PolyK.ContainsPoint(p, ax, ay) || PolyK.ContainsPoint(p, bx, by)) return [p.slice(0)];
var a = new PolyK._P(ax, ay);
var b = new PolyK._P(bx, by);
var iscs = []; // intersections
var ps = []; // points
for(var i=0; i<p.length; i+=2) ps.push(new PolyK._P(p[i], p[i+1]));
for(var i=0; i<ps.length; i++)
{
var isc = new PolyK._P(0,0);
isc = PolyK._GetLineIntersection(a, b, ps[i], ps[(i+1)%ps.length], isc);
if(isc)
{
isc.flag = true;
iscs.push(isc);
ps.splice(i+1,0,isc);
i++;
}
}
if(iscs.length == 0) return [p.slice(0)];
var comp = function(u,v) {return PolyK._P.dist(a,u) - PolyK._P.dist(a,v); }
iscs.sort(comp);
var pgs = [];
var dir = 0;
while(iscs.length > 0)
{
var n = ps.length;
var i0 = iscs[0];
var i1 = iscs[1];
var ind0 = ps.indexOf(i0);
var ind1 = ps.indexOf(i1);
var solved = false;
if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
else
{
i0 = iscs[1];
i1 = iscs[0];
ind0 = ps.indexOf(i0);
ind1 = ps.indexOf(i1);
if(PolyK._firstWithFlag(ps, ind0) == ind1) solved = true;
}
if(solved)
{
dir--;
var pgn = PolyK._getPoints(ps, ind0, ind1);
pgs.push(pgn);
ps = PolyK._getPoints(ps, ind1, ind0);
i0.flag = i1.flag = false;
iscs.splice(0,2);
if(iscs.length == 0) pgs.push(ps);
}
else { dir++; iscs.reverse(); }
if(dir>1) break;
}
var result = [];
for(var i=0; i<pgs.length; i++)
{
var pg = pgs[i];
var npg = [];
for(var j=0; j<pg.length; j++) npg.push(pg[j].x, pg[j].y);
result.push(npg);
}
return result;
}
PolyK.Raycast = function(p, x, y, dx, dy, isc)
{
var l = p.length - 2;
var tp = PolyK._tp;
var a1 = tp[0], a2 = tp[1],
b1 = tp[2], b2 = tp[3], c = tp[4];
a1.x = x; a1.y = y;
a2.x = x+dx; a2.y = y+dy;
if(isc==null) isc = {dist:0, edge:0, norm:{x:0, y:0}, refl:{x:0, y:0}};
isc.dist = Infinity;
for(var i=0; i<l; i+=2)
{
b1.x = p[i ]; b1.y = p[i+1];
b2.x = p[i+2]; b2.y = p[i+3];
var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, i/2, isc);
}
b1.x = b2.x; b1.y = b2.y;
b2.x = p[0]; b2.y = p[1];
var nisc = PolyK._RayLineIntersection(a1, a2, b1, b2, c);
if(nisc) PolyK._updateISC(dx, dy, a1, b1, b2, c, p.length/2, isc);
return (isc.dist != Infinity) ? isc : null;
}
PolyK.ClosestEdge = function(p, x, y, isc)
{
var l = p.length - 2;
var tp = PolyK._tp;
var a1 = tp[0],
b1 = tp[2], b2 = tp[3], c = tp[4];
a1.x = x; a1.y = y;
if(isc==null) isc = {dist:0, edge:0, point:{x:0, y:0}, norm:{x:0, y:0}};
isc.dist = Infinity;
for(var i=0; i<l; i+=2)
{
b1.x = p[i ]; b1.y = p[i+1];
b2.x = p[i+2]; b2.y = p[i+3];
PolyK._pointLineDist(a1, b1, b2, i>>1, isc);
}
b1.x = b2.x; b1.y = b2.y;
b2.x = p[0]; b2.y = p[1];
PolyK._pointLineDist(a1, b1, b2, l>>1, isc);
var idst = 1/isc.dist;
isc.norm.x = (x-isc.point.x)*idst;
isc.norm.y = (y-isc.point.y)*idst;
return isc;
}
PolyK._pointLineDist = function(p, a, b, edge, isc)
{
var x = p.x, y = p.y, x1 = a.x, y1 = a.y, x2 = b.x, y2 = b.y;
var A = x - x1;
var B = y - y1;
var C = x2 - x1;
var D = y2 - y1;
var dot = A * C + B * D;
var len_sq = C * C + D * D;
var param = dot / len_sq;
var xx, yy;
if (param < 0 || (x1 == x2 && y1 == y2)) {
xx = x1;
yy = y1;
}
else if (param > 1) {
xx = x2;
yy = y2;
}
else {
xx = x1 + param * C;
yy = y1 + param * D;
}
var dx = x - xx;
var dy = y - yy;
var dst = Math.sqrt(dx * dx + dy * dy);
if(dst<isc.dist)
{
isc.dist = dst;
isc.edge = edge;
isc.point.x = xx;
isc.point.y = yy;
}
}
PolyK._updateISC = function(dx, dy, a1, b1, b2, c, edge, isc)
{
var nrl = PolyK._P.dist(a1, c);
if(nrl<isc.dist)
{
var ibl = 1/PolyK._P.dist(b1, b2);
var nx = -(b2.y-b1.y)*ibl;
var ny = (b2.x-b1.x)*ibl;
var ddot = 2*(dx*nx+dy*ny);
isc.dist = nrl;
isc.norm.x = nx;
isc.norm.y = ny;
isc.refl.x = -ddot*nx+dx;
isc.refl.y = -ddot*ny+dy;
isc.edge = edge;
}
}
PolyK._getPoints = function(ps, ind0, ind1)
{
var n = ps.length;
var nps = [];
if(ind1<ind0) ind1 += n;
for(var i=ind0; i<= ind1; i++) nps.push(ps[i%n]);
return nps;
}
PolyK._firstWithFlag = function(ps, ind)
{
var n = ps.length;
while(true)
{
ind = (ind+1)%n;
if(ps[ind].flag) return ind;
}
}
*/
PolyK._PointInTriangle = function(px, py, ax, ay, bx, by, cx, cy)
{
var v0x = cx-ax;
var v0y = cy-ay;
var v1x = bx-ax;
var v1y = by-ay;
var v2x = px-ax;
var v2y = py-ay;
var dot00 = v0x*v0x+v0y*v0y;
var dot01 = v0x*v1x+v0y*v1y;
var dot02 = v0x*v2x+v0y*v2y;
var dot11 = v1x*v1x+v1y*v1y;
var dot12 = v1x*v2x+v1y*v2y;
var invDenom = 1 / (dot00 * dot11 - dot01 * dot01);
var u = (dot11 * dot02 - dot01 * dot12) * invDenom;
var v = (dot00 * dot12 - dot01 * dot02) * invDenom;
// Check if point is in triangle
return (u >= 0) && (v >= 0) && (u + v < 1);
}
/*
PolyK._RayLineIntersection = function(a1, a2, b1, b2, c)
{
var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
var day = (a1.y-a2.y), dby = (b1.y-b2.y);
var Den = dax*dby - day*dbx;
if (Den == 0) return null; // parallel
var A = (a1.x * a2.y - a1.y * a2.x);
var B = (b1.x * b2.y - b1.y * b2.x);
var I = c;
var iDen = 1/Den;
I.x = ( A*dbx - dax*B ) * iDen;
I.y = ( A*dby - day*B ) * iDen;
if(!PolyK._InRect(I, b1, b2)) return null;
if((day>0 && I.y>a1.y) || (day<0 && I.y<a1.y)) return null;
if((dax>0 && I.x>a1.x) || (dax<0 && I.x<a1.x)) return null;
return I;
}
PolyK._GetLineIntersection = function(a1, a2, b1, b2, c)
{
var dax = (a1.x-a2.x), dbx = (b1.x-b2.x);
var day = (a1.y-a2.y), dby = (b1.y-b2.y);
var Den = dax*dby - day*dbx;
if (Den == 0) return null; // parallel
var A = (a1.x * a2.y - a1.y * a2.x);
var B = (b1.x * b2.y - b1.y * b2.x);
var I = c;
I.x = ( A*dbx - dax*B ) / Den;
I.y = ( A*dby - day*B ) / Den;
if(PolyK._InRect(I, a1, a2) && PolyK._InRect(I, b1, b2)) return I;
return null;
}
PolyK._InRect = function(a, b, c)
{
if (b.x == c.x) return (a.y>=Math.min(b.y, c.y) && a.y<=Math.max(b.y, c.y));
if (b.y == c.y) return (a.x>=Math.min(b.x, c.x) && a.x<=Math.max(b.x, c.x));
if(a.x >= Math.min(b.x, c.x) && a.x <= Math.max(b.x, c.x)
&& a.y >= Math.min(b.y, c.y) && a.y <= Math.max(b.y, c.y))
return true;
return false;
}
*/
PolyK._convex = function(ax, ay, bx, by, cx, cy)
{
return (ay-by)*(cx-bx) + (bx-ax)*(cy-by) >= 0;
}
/*
PolyK._P = function(x,y)
{
this.x = x;
this.y = y;
this.flag = false;
}
PolyK._P.prototype.toString = function()
{
return "Point ["+this.x+", "+this.y+"]";
}
PolyK._P.dist = function(a,b)
{
var dx = b.x-a.x;
var dy = b.y-a.y;
return Math.sqrt(dx*dx + dy*dy);
}
PolyK._tp = [];
for(var i=0; i<10; i++) PolyK._tp.push(new PolyK._P(0,0));
*/
module.exports = PolyK;
// convex/Line.js
var Shape = require('./Shape')
, shallowClone = require('./Utils').shallowClone
, vec2 = require('./math/vec2');
module.exports = Line;
/**
* Line shape class. The line shape is along the x direction, and stretches from [-length/2, 0] to [length/2,0].
* @class Line
* @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
* @param {Number} [options.length=1] The total length of the line
* @extends Shape
* @constructor
* @example
* var body = new Body();
* var lineShape = new Line({
* length: 1
* });
* body.addShape(lineShape);
*/
function Line(options){
options = options ? shallowClone(options) : {};
/**
* Length of this line
* @property {Number} length
* @default 1
*/
this.length = options.length !== undefined ? options.length : 1;
options.type = Shape.LINE;
Shape.call(this, options);
}
Line.prototype = new Shape();
Line.prototype.constructor = Line;
Line.prototype.computeMomentOfInertia = function(){
return Math.pow(this.length,2) / 12;
};
Line.prototype.updateBoundingRadius = function(){
this.boundingRadius = this.length/2;
};
var points = [vec2.create(),vec2.create()];
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Line.prototype.computeAABB = function(out, position, angle){
var l2 = this.length / 2;
vec2.set(points[0], -l2, 0);
vec2.set(points[1], l2, 0);
out.setFromPoints(points,position,angle,0);
};
var raycast_normal = vec2.create();
var raycast_l0 = vec2.create();
var raycast_l1 = vec2.create();
var raycast_unit_y = vec2.fromValues(0,1);
/**
* @method raycast
* @param {RaycastResult} result
* @param {Ray} ray
* @param {number} angle
* @param {array} position
*/
Line.prototype.raycast = function(result, ray, position, angle){
var from = ray.from;
var to = ray.to;
var l0 = raycast_l0;
var l1 = raycast_l1;
// get start and end of the line
var halfLen = this.length / 2;
vec2.set(l0, -halfLen, 0);
vec2.set(l1, halfLen, 0);
vec2.toGlobalFrame(l0, l0, position, angle);
vec2.toGlobalFrame(l1, l1, position, angle);
var fraction = vec2.getLineSegmentsIntersectionFraction(l0, l1, from, to);
if(fraction >= 0){
var normal = raycast_normal;
vec2.rotate(normal, raycast_unit_y, angle); // todo: this should depend on which side the ray comes from
ray.reportIntersection(result, fraction, normal, -1);
}
};
// convex/Utils.js
/* global P2_ARRAY_TYPE */
module.exports = Utils;
/**
* Misc utility functions
* @class Utils
* @constructor
*/
function Utils(){}
/**
* Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
* @method appendArray
* @static
* @param {Array} a
* @param {Array} b
*/
Utils.appendArray = function(a,b){
if (b.length < 150000) {
a.push.apply(a, b);
} else {
for (var i = 0, len = b.length; i !== len; ++i) {
a.push(b[i]);
}
}
};
/**
* Garbage free Array.splice(). Does not allocate a new array.
* @method splice
* @static
* @param {Array} array
* @param {Number} index
* @param {Number} howmany
*/
Utils.splice = function(array,index,howmany){
howmany = howmany || 1;
for (var i=index, len=array.length-howmany; i < len; i++){
array[i] = array[i + howmany];
}
array.length = len;
};
/**
* Remove an element from an array, if the array contains the element.
* @method arrayRemove
* @static
* @param {Array} array
* @param {Number} element
*/
Utils.arrayRemove = function(array, element){
var idx = array.indexOf(element);
if(idx!==-1){
Utils.splice(array, idx, 1);
}
};
/**
* The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
* @static
* @property {function} ARRAY_TYPE
* @example
* <script>
* <!-- Inject your preferred array type before loading p2.js -->
* P2_ARRAY_TYPE = Array;
* </script>
* <script src="p2.js"></script>
*/
if(typeof P2_ARRAY_TYPE !== 'undefined') {
Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
} else if (typeof Float32Array !== 'undefined'){
Utils.ARRAY_TYPE = Float32Array;
} else {
Utils.ARRAY_TYPE = Array;
}
/**
* Extend an object with the properties of another
* @static
* @method extend
* @param {object} a
* @param {object} b
*/
Utils.extend = function(a,b){
for(var key in b){
a[key] = b[key];
}
};
/**
* Shallow clone an object. Returns a new object instance with the same properties as the input instance.
* @static
* @method shallowClone
* @param {object} obj
*/
Utils.shallowClone = function(obj){
var newObj = {};
Utils.extend(newObj, obj);
return newObj;
};
/**
* Extend an options object with default values.
* @deprecated Not used internally, will be removed.
* @static
* @method defaults
* @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
* @param {object} defaults An object containing default values.
* @return {object} The modified options object.
*/
Utils.defaults = function(options, defaults){
console.warn('Utils.defaults is deprecated.');
options = options || {};
for(var key in defaults){
if(!(key in options)){
options[key] = defaults[key];
}
}
return options;
};
// convex/Shape.js
module.exports = Shape;
var vec2 = require('./math/vec2');
/**
* Base class for shapes. Not to be used directly.
* @class Shape
* @constructor
* @param {object} [options]
* @param {number} [options.angle=0]
* @param {number} [options.collisionGroup=1]
* @param {number} [options.collisionMask=1]
* @param {boolean} [options.collisionResponse=true]
* @param {Material} [options.material=null]
* @param {array} [options.position]
* @param {boolean} [options.sensor=false]
* @param {object} [options.type=0]
*/
function Shape(options){
options = options || {};
/**
* The body this shape is attached to. A shape can only be attached to a single body.
* @property {Body} body
*/
this.body = null;
/**
* Body-local position of the shape.
* @property {Array} position
*/
this.position = vec2.create();
if(options.position){
vec2.copy(this.position, options.position);
}
/**
* Body-local angle of the shape.
* @property {number} angle
*/
this.angle = options.angle || 0;
/**
* The type of the shape. One of:
*
* <ul>
* <li><a href="Shape.html#property_CIRCLE">Shape.CIRCLE</a></li>
* <li><a href="Shape.html#property_PARTICLE">Shape.PARTICLE</a></li>
* <li><a href="Shape.html#property_PLANE">Shape.PLANE</a></li>
* <li><a href="Shape.html#property_CONVEX">Shape.CONVEX</a></li>
* <li><a href="Shape.html#property_LINE">Shape.LINE</a></li>
* <li><a href="Shape.html#property_BOX">Shape.BOX</a></li>
* <li><a href="Shape.html#property_CAPSULE">Shape.CAPSULE</a></li>
* <li><a href="Shape.html#property_HEIGHTFIELD">Shape.HEIGHTFIELD</a></li>
* </ul>
*
* @property {number} type
*/
this.type = options.type || 0;
/**
* Shape object identifier. Read only.
* @readonly
* @type {Number}
* @property id
*/
this.id = Shape.idCounter++;
/**
* Bounding circle radius of this shape
* @readonly
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
/**
* Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
* @property collisionGroup
* @type {Number}
* @example
* // Setup bits for each available group
* var PLAYER = Math.pow(2,0),
* ENEMY = Math.pow(2,1),
* GROUND = Math.pow(2,2)
*
* // Put shapes into their groups
* player1Shape.collisionGroup = PLAYER;
* player2Shape.collisionGroup = PLAYER;
* enemyShape .collisionGroup = ENEMY;
* groundShape .collisionGroup = GROUND;
*
* // Assign groups that each shape collide with.
* // Note that the players can collide with ground and enemies, but not with other players.
* player1Shape.collisionMask = ENEMY | GROUND;
* player2Shape.collisionMask = ENEMY | GROUND;
* enemyShape .collisionMask = PLAYER | GROUND;
* groundShape .collisionMask = PLAYER | ENEMY;
*
* @example
* // How collision check is done
* if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
* // The shapes will collide
* }
*/
this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
* @property {Boolean} collisionResponse
*/
this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
/**
* Collision mask of this shape. See .collisionGroup.
* @property collisionMask
* @type {Number}
*/
this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
/**
* Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
* @property material
* @type {Material}
*/
this.material = options.material || null;
/**
* Area of this shape.
* @property area
* @type {Number}
*/
this.area = 0;
/**
* Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
* @property {Boolean} sensor
*/
this.sensor = options.sensor !== undefined ? options.sensor : false;
if(this.type){
this.updateBoundingRadius();
}
this.updateArea();
}
Shape.idCounter = 0;
/**
* @static
* @property {Number} CIRCLE
*/
Shape.CIRCLE = 1;
/**
* @static
* @property {Number} PARTICLE
*/
Shape.PARTICLE = 2;
/**
* @static
* @property {Number} PLANE
*/
Shape.PLANE = 4;
/**
* @static
* @property {Number} CONVEX
*/
Shape.CONVEX = 8;
/**
* @static
* @property {Number} LINE
*/
Shape.LINE = 16;
/**
* @static
* @property {Number} BOX
*/
Shape.BOX = 32;
/**
* @static
* @property {Number} CAPSULE
*/
Shape.CAPSULE = 64;
/**
* @static
* @property {Number} HEIGHTFIELD
*/
Shape.HEIGHTFIELD = 128;
Shape.prototype = {
/**
* Should return the moment of inertia around the Z axis of the body. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
* @method computeMomentOfInertia
* @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
*/
computeMomentOfInertia: function(){},
/**
* Returns the bounding circle radius of this shape.
* @method updateBoundingRadius
* @return {Number}
*/
updateBoundingRadius: function(){},
/**
* Update the .area property of the shape.
* @method updateArea
*/
updateArea: function(){},
/**
* Compute the world axis-aligned bounding box (AABB) of this shape.
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position World position of the shape.
* @param {Number} angle World angle of the shape.
*/
computeAABB: function(/*out, position, angle*/){
// To be implemented in each subclass
},
/**
* Perform raycasting on this shape.
* @method raycast
* @param {RayResult} result Where to store the resulting data.
* @param {Ray} ray The Ray that you want to use for raycasting.
* @param {array} position World position of the shape (the .position property will be ignored).
* @param {number} angle World angle of the shape (the .angle property will be ignored).
*/
raycast: function(/*result, ray, position, angle*/){
// To be implemented in each subclass
},
/**
* Test if a point is inside this shape.
* @method pointTest
* @param {array} localPoint
* @return {boolean}
*/
pointTest: function(/*localPoint*/){ return false; },
/**
* Transform a world point to local shape space (assumed the shape is transformed by both itself and the body).
* @method worldPointToLocal
* @param {array} out
* @param {array} worldPoint
*/
worldPointToLocal: (function () {
var shapeWorldPosition = vec2.create();
return function (out, worldPoint) {
var body = this.body;
vec2.rotate(shapeWorldPosition, this.position, body.angle);
vec2.add(shapeWorldPosition, shapeWorldPosition, body.position);
vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle);
};
})()
};
| 6 | 1,878 | JavaScript |
spherical | ./ProjectTest/JavaScript/spherical.js | // spherical/MathUtils.js
const _lut = [ '00', '01', '02', '03', '04', '05', '06', '07', '08', '09', '0a', '0b', '0c', '0d', '0e', '0f', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '1a', '1b', '1c', '1d', '1e', '1f', '20', '21', '22', '23', '24', '25', '26', '27', '28', '29', '2a', '2b', '2c', '2d', '2e', '2f', '30', '31', '32', '33', '34', '35', '36', '37', '38', '39', '3a', '3b', '3c', '3d', '3e', '3f', '40', '41', '42', '43', '44', '45', '46', '47', '48', '49', '4a', '4b', '4c', '4d', '4e', '4f', '50', '51', '52', '53', '54', '55', '56', '57', '58', '59', '5a', '5b', '5c', '5d', '5e', '5f', '60', '61', '62', '63', '64', '65', '66', '67', '68', '69', '6a', '6b', '6c', '6d', '6e', '6f', '70', '71', '72', '73', '74', '75', '76', '77', '78', '79', '7a', '7b', '7c', '7d', '7e', '7f', '80', '81', '82', '83', '84', '85', '86', '87', '88', '89', '8a', '8b', '8c', '8d', '8e', '8f', '90', '91', '92', '93', '94', '95', '96', '97', '98', '99', '9a', '9b', '9c', '9d', '9e', '9f', 'a0', 'a1', 'a2', 'a3', 'a4', 'a5', 'a6', 'a7', 'a8', 'a9', 'aa', 'ab', 'ac', 'ad', 'ae', 'af', 'b0', 'b1', 'b2', 'b3', 'b4', 'b5', 'b6', 'b7', 'b8', 'b9', 'ba', 'bb', 'bc', 'bd', 'be', 'bf', 'c0', 'c1', 'c2', 'c3', 'c4', 'c5', 'c6', 'c7', 'c8', 'c9', 'ca', 'cb', 'cc', 'cd', 'ce', 'cf', 'd0', 'd1', 'd2', 'd3', 'd4', 'd5', 'd6', 'd7', 'd8', 'd9', 'da', 'db', 'dc', 'dd', 'de', 'df', 'e0', 'e1', 'e2', 'e3', 'e4', 'e5', 'e6', 'e7', 'e8', 'e9', 'ea', 'eb', 'ec', 'ed', 'ee', 'ef', 'f0', 'f1', 'f2', 'f3', 'f4', 'f5', 'f6', 'f7', 'f8', 'f9', 'fa', 'fb', 'fc', 'fd', 'fe', 'ff' ];
let _seed = 1234567;
const DEG2RAD = Math.PI / 180;
const RAD2DEG = 180 / Math.PI;
// http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/21963136#21963136
function generateUUID() {
const d0 = Math.random() * 0xffffffff | 0;
const d1 = Math.random() * 0xffffffff | 0;
const d2 = Math.random() * 0xffffffff | 0;
const d3 = Math.random() * 0xffffffff | 0;
const uuid = _lut[ d0 & 0xff ] + _lut[ d0 >> 8 & 0xff ] + _lut[ d0 >> 16 & 0xff ] + _lut[ d0 >> 24 & 0xff ] + '-' +
_lut[ d1 & 0xff ] + _lut[ d1 >> 8 & 0xff ] + '-' + _lut[ d1 >> 16 & 0x0f | 0x40 ] + _lut[ d1 >> 24 & 0xff ] + '-' +
_lut[ d2 & 0x3f | 0x80 ] + _lut[ d2 >> 8 & 0xff ] + '-' + _lut[ d2 >> 16 & 0xff ] + _lut[ d2 >> 24 & 0xff ] +
_lut[ d3 & 0xff ] + _lut[ d3 >> 8 & 0xff ] + _lut[ d3 >> 16 & 0xff ] + _lut[ d3 >> 24 & 0xff ];
// .toLowerCase() here flattens concatenated strings to save heap memory space.
return uuid.toLowerCase();
}
function clamp( value, min, max ) {
return Math.max( min, Math.min( max, value ) );
}
// compute euclidean modulo of m % n
// https://en.wikipedia.org/wiki/Modulo_operation
function euclideanModulo( n, m ) {
return ( ( n % m ) + m ) % m;
}
// Linear mapping from range <a1, a2> to range <b1, b2>
function mapLinear( x, a1, a2, b1, b2 ) {
return b1 + ( x - a1 ) * ( b2 - b1 ) / ( a2 - a1 );
}
// https://www.gamedev.net/tutorials/programming/general-and-gameplay-programming/inverse-lerp-a-super-useful-yet-often-overlooked-function-r5230/
function inverseLerp( x, y, value ) {
if ( x !== y ) {
return ( value - x ) / ( y - x );
} else {
return 0;
}
}
// https://en.wikipedia.org/wiki/Linear_interpolation
function lerp( x, y, t ) {
return ( 1 - t ) * x + t * y;
}
// http://www.rorydriscoll.com/2016/03/07/frame-rate-independent-damping-using-lerp/
function damp( x, y, lambda, dt ) {
return lerp( x, y, 1 - Math.exp( - lambda * dt ) );
}
// https://www.desmos.com/calculator/vcsjnyz7x4
function pingpong( x, length = 1 ) {
return length - Math.abs( euclideanModulo( x, length * 2 ) - length );
}
// http://en.wikipedia.org/wiki/Smoothstep
function smoothstep( x, min, max ) {
if ( x <= min ) return 0;
if ( x >= max ) return 1;
x = ( x - min ) / ( max - min );
return x * x * ( 3 - 2 * x );
}
function smootherstep( x, min, max ) {
if ( x <= min ) return 0;
if ( x >= max ) return 1;
x = ( x - min ) / ( max - min );
return x * x * x * ( x * ( x * 6 - 15 ) + 10 );
}
// Random integer from <low, high> interval
function randInt( low, high ) {
return low + Math.floor( Math.random() * ( high - low + 1 ) );
}
// Random float from <low, high> interval
function randFloat( low, high ) {
return low + Math.random() * ( high - low );
}
// Random float from <-range/2, range/2> interval
function randFloatSpread( range ) {
return range * ( 0.5 - Math.random() );
}
// Deterministic pseudo-random float in the interval [ 0, 1 ]
function seededRandom( s ) {
if ( s !== undefined ) _seed = s;
// Mulberry32 generator
let t = _seed += 0x6D2B79F5;
t = Math.imul( t ^ t >>> 15, t | 1 );
t ^= t + Math.imul( t ^ t >>> 7, t | 61 );
return ( ( t ^ t >>> 14 ) >>> 0 ) / 4294967296;
}
function degToRad( degrees ) {
return degrees * DEG2RAD;
}
function radToDeg( radians ) {
return radians * RAD2DEG;
}
function isPowerOfTwo( value ) {
return ( value & ( value - 1 ) ) === 0 && value !== 0;
}
function ceilPowerOfTwo( value ) {
return Math.pow( 2, Math.ceil( Math.log( value ) / Math.LN2 ) );
}
function floorPowerOfTwo( value ) {
return Math.pow( 2, Math.floor( Math.log( value ) / Math.LN2 ) );
}
function setQuaternionFromProperEuler( q, a, b, c, order ) {
// Intrinsic Proper Euler Angles - see https://en.wikipedia.org/wiki/Euler_angles
// rotations are applied to the axes in the order specified by 'order'
// rotation by angle 'a' is applied first, then by angle 'b', then by angle 'c'
// angles are in radians
const cos = Math.cos;
const sin = Math.sin;
const c2 = cos( b / 2 );
const s2 = sin( b / 2 );
const c13 = cos( ( a + c ) / 2 );
const s13 = sin( ( a + c ) / 2 );
const c1_3 = cos( ( a - c ) / 2 );
const s1_3 = sin( ( a - c ) / 2 );
const c3_1 = cos( ( c - a ) / 2 );
const s3_1 = sin( ( c - a ) / 2 );
switch ( order ) {
case 'XYX':
q.set( c2 * s13, s2 * c1_3, s2 * s1_3, c2 * c13 );
break;
case 'YZY':
q.set( s2 * s1_3, c2 * s13, s2 * c1_3, c2 * c13 );
break;
case 'ZXZ':
q.set( s2 * c1_3, s2 * s1_3, c2 * s13, c2 * c13 );
break;
case 'XZX':
q.set( c2 * s13, s2 * s3_1, s2 * c3_1, c2 * c13 );
break;
case 'YXY':
q.set( s2 * c3_1, c2 * s13, s2 * s3_1, c2 * c13 );
break;
case 'ZYZ':
q.set( s2 * s3_1, s2 * c3_1, c2 * s13, c2 * c13 );
break;
default:
console.warn( 'THREE.MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: ' + order );
}
}
function denormalize( value, array ) {
switch ( array.constructor ) {
case Float32Array:
return value;
case Uint32Array:
return value / 4294967295.0;
case Uint16Array:
return value / 65535.0;
case Uint8Array:
return value / 255.0;
case Int32Array:
return Math.max( value / 2147483647.0, - 1.0 );
case Int16Array:
return Math.max( value / 32767.0, - 1.0 );
case Int8Array:
return Math.max( value / 127.0, - 1.0 );
default:
throw new Error( 'Invalid component type.' );
}
}
function normalize( value, array ) {
switch ( array.constructor ) {
case Float32Array:
return value;
case Uint32Array:
return Math.round( value * 4294967295.0 );
case Uint16Array:
return Math.round( value * 65535.0 );
case Uint8Array:
return Math.round( value * 255.0 );
case Int32Array:
return Math.round( value * 2147483647.0 );
case Int16Array:
return Math.round( value * 32767.0 );
case Int8Array:
return Math.round( value * 127.0 );
default:
throw new Error( 'Invalid component type.' );
}
}
const MathUtils = {
DEG2RAD: DEG2RAD,
RAD2DEG: RAD2DEG,
generateUUID: generateUUID,
clamp: clamp,
euclideanModulo: euclideanModulo,
mapLinear: mapLinear,
inverseLerp: inverseLerp,
lerp: lerp,
damp: damp,
pingpong: pingpong,
smoothstep: smoothstep,
smootherstep: smootherstep,
randInt: randInt,
randFloat: randFloat,
randFloatSpread: randFloatSpread,
seededRandom: seededRandom,
degToRad: degToRad,
radToDeg: radToDeg,
isPowerOfTwo: isPowerOfTwo,
ceilPowerOfTwo: ceilPowerOfTwo,
floorPowerOfTwo: floorPowerOfTwo,
setQuaternionFromProperEuler: setQuaternionFromProperEuler,
normalize: normalize,
denormalize: denormalize
};
export {
DEG2RAD,
RAD2DEG,
generateUUID,
clamp,
euclideanModulo,
mapLinear,
inverseLerp,
lerp,
damp,
pingpong,
smoothstep,
smootherstep,
randInt,
randFloat,
randFloatSpread,
seededRandom,
degToRad,
radToDeg,
isPowerOfTwo,
ceilPowerOfTwo,
floorPowerOfTwo,
setQuaternionFromProperEuler,
normalize,
denormalize,
MathUtils
};
// spherical/Spherical.js
import { clamp } from './MathUtils.js';
/**
* Ref: https://en.wikipedia.org/wiki/Spherical_coordinate_system
*
* phi (the polar angle) is measured from the positive y-axis. The positive y-axis is up.
* theta (the azimuthal angle) is measured from the positive z-axis.
*/
class Spherical {
constructor( radius = 1, phi = 0, theta = 0 ) {
this.radius = radius;
this.phi = phi; // polar angle
this.theta = theta; // azimuthal angle
return this;
}
set( radius, phi, theta ) {
this.radius = radius;
this.phi = phi;
this.theta = theta;
return this;
}
copy( other ) {
this.radius = other.radius;
this.phi = other.phi;
this.theta = other.theta;
return this;
}
// restrict phi to be between EPS and PI-EPS
makeSafe() {
const EPS = 0.000001;
this.phi = clamp( this.phi, EPS, Math.PI - EPS );
return this;
}
setFromVector3( v ) {
return this.setFromCartesianCoords( v.x, v.y, v.z );
}
setFromCartesianCoords( x, y, z ) {
this.radius = Math.sqrt( x * x + y * y + z * z );
if ( this.radius === 0 ) {
this.theta = 0;
this.phi = 0;
} else {
this.theta = Math.atan2( x, z );
this.phi = Math.acos( clamp( y / this.radius, - 1, 1 ) );
}
return this;
}
clone() {
return new this.constructor().copy( this );
}
}
export { Spherical };
| 2 | 448 | JavaScript |
circle | ./ProjectTest/JavaScript/circle.js | // circle/vec2.js
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
* @class vec2
*/
var vec2 = module.exports = {};
var Utils = require('./Utils');
/**
* Make a cross product and only return the z component
* @method crossLength
* @static
* @param {Array} a
* @param {Array} b
* @return {Number}
*/
vec2.crossLength = function(a,b){
return a[0] * b[1] - a[1] * b[0];
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossVZ
* @static
* @param {Array} out
* @param {Array} vec
* @param {Number} zcomp
* @return {Array}
*/
vec2.crossVZ = function(out, vec, zcomp){
vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossZV
* @static
* @param {Array} out
* @param {Number} zcomp
* @param {Array} vec
* @return {Array}
*/
vec2.crossZV = function(out, zcomp, vec){
vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Rotate a vector by an angle
* @method rotate
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate = function(out,a,angle){
if(angle !== 0){
var c = Math.cos(angle),
s = Math.sin(angle),
x = a[0],
y = a[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
} else {
out[0] = a[0];
out[1] = a[1];
}
return out;
};
/**
* Rotate a vector 90 degrees clockwise
* @method rotate90cw
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate90cw = function(out, a) {
var x = a[0];
var y = a[1];
out[0] = y;
out[1] = -x;
return out;
};
/**
* Transform a point position to local frame.
* @method toLocalFrame
* @param {Array} out
* @param {Array} worldPoint
* @param {Array} framePosition
* @param {Number} frameAngle
* @return {Array}
*/
vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldPoint[0] - framePosition[0],
y = worldPoint[1] - framePosition[1];
out[0] = c * x - s * y;
out[1] = s * x + c * y;
return out;
};
/**
* Transform a point position to global frame.
* @method toGlobalFrame
* @param {Array} out
* @param {Array} localPoint
* @param {Array} framePosition
* @param {Number} frameAngle
*/
vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
var c = Math.cos(frameAngle),
s = Math.sin(frameAngle),
x = localPoint[0],
y = localPoint[1],
addX = framePosition[0],
addY = framePosition[1];
out[0] = c * x - s * y + addX;
out[1] = s * x + c * y + addY;
};
/**
* Transform a vector to local frame.
* @method vectorToLocalFrame
* @param {Array} out
* @param {Array} worldVector
* @param {Number} frameAngle
* @return {Array}
*/
vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldVector[0],
y = worldVector[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
return out;
};
/**
* Transform a vector to global frame.
* @method vectorToGlobalFrame
* @param {Array} out
* @param {Array} localVector
* @param {Number} frameAngle
*/
vec2.vectorToGlobalFrame = vec2.rotate;
/**
* Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
* @method centroid
* @static
* @param {Array} out
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Array} The "out" vector.
*/
vec2.centroid = function(out, a, b, c){
vec2.add(out, a, b);
vec2.add(out, out, c);
vec2.scale(out, out, 1/3);
return out;
};
/**
* Creates a new, empty vec2
* @static
* @method create
* @return {Array} a new 2D vector
*/
vec2.create = function() {
var out = new Utils.ARRAY_TYPE(2);
out[0] = 0;
out[1] = 0;
return out;
};
/**
* Creates a new vec2 initialized with values from an existing vector
* @static
* @method clone
* @param {Array} a vector to clone
* @return {Array} a new 2D vector
*/
vec2.clone = function(a) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Creates a new vec2 initialized with the given values
* @static
* @method fromValues
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} a new 2D vector
*/
vec2.fromValues = function(x, y) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = x;
out[1] = y;
return out;
};
/**
* Copy the values from one vec2 to another
* @static
* @method copy
* @param {Array} out the receiving vector
* @param {Array} a the source vector
* @return {Array} out
*/
vec2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Set the components of a vec2 to the given values
* @static
* @method set
* @param {Array} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} out
*/
vec2.set = function(out, x, y) {
out[0] = x;
out[1] = y;
return out;
};
/**
* Adds two vec2's
* @static
* @method add
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
};
/**
* Subtracts two vec2's
* @static
* @method subtract
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
};
/**
* Multiplies two vec2's
* @static
* @method multiply
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
};
/**
* Divides two vec2's
* @static
* @method divide
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
};
/**
* Scales a vec2 by a scalar number
* @static
* @method scale
* @param {Array} out the receiving vector
* @param {Array} a the vector to scale
* @param {Number} b amount to scale the vector by
* @return {Array} out
*/
vec2.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
};
/**
* Calculates the euclidian distance between two vec2's
* @static
* @method distance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} distance between a and b
*/
vec2.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared euclidian distance between two vec2's
* @static
* @method squaredDistance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} squared distance between a and b
*/
vec2.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x*x + y*y;
};
/**
* Calculates the length of a vec2
* @static
* @method length
* @param {Array} a vector to calculate length of
* @return {Number} length of a
*/
vec2.length = function (a) {
var x = a[0],
y = a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared length of a vec2
* @static
* @method squaredLength
* @param {Array} a vector to calculate squared length of
* @return {Number} squared length of a
*/
vec2.squaredLength = function (a) {
var x = a[0],
y = a[1];
return x*x + y*y;
};
/**
* Negates the components of a vec2
* @static
* @method negate
* @param {Array} out the receiving vector
* @param {Array} a vector to negate
* @return {Array} out
*/
vec2.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
};
/**
* Normalize a vec2
* @static
* @method normalize
* @param {Array} out the receiving vector
* @param {Array} a vector to normalize
* @return {Array} out
*/
vec2.normalize = function(out, a) {
var x = a[0],
y = a[1];
var len = x*x + y*y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
};
/**
* Calculates the dot product of two vec2's
* @static
* @method dot
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} dot product of a and b
*/
vec2.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/**
* Returns a string representation of a vector
* @static
* @method str
* @param {Array} vec vector to represent as a string
* @return {String} string representation of the vector
*/
vec2.str = function (a) {
return 'vec2(' + a[0] + ', ' + a[1] + ')';
};
/**
* Linearly interpolate/mix two vectors.
* @static
* @method lerp
* @param {Array} out
* @param {Array} a First vector
* @param {Array} b Second vector
* @param {number} t Lerp factor
*/
vec2.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
};
/**
* Reflect a vector along a normal.
* @static
* @method reflect
* @param {Array} out
* @param {Array} vector
* @param {Array} normal
*/
vec2.reflect = function(out, vector, normal){
var dot = vector[0] * normal[0] + vector[1] * normal[1];
out[0] = vector[0] - 2 * normal[0] * dot;
out[1] = vector[1] - 2 * normal[1] * dot;
};
/**
* Get the intersection point between two line segments.
* @static
* @method getLineSegmentsIntersection
* @param {Array} out
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {boolean} True if there was an intersection, otherwise false.
*/
vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) {
var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3);
if(t < 0){
return false;
} else {
out[0] = p0[0] + (t * (p1[0] - p0[0]));
out[1] = p0[1] + (t * (p1[1] - p0[1]));
return true;
}
};
/**
* Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
* @static
* @method getLineSegmentsIntersectionFraction
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
*/
vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) {
var s1_x = p1[0] - p0[0];
var s1_y = p1[1] - p0[1];
var s2_x = p3[0] - p2[0];
var s2_y = p3[1] - p2[1];
var s, t;
s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
return t;
}
return -1; // No collision
};
// circle/Circle.js
var Shape = require('./Shape')
, vec2 = require('./vec2')
, shallowClone = require('./Utils').shallowClone;
module.exports = Circle;
/**
* Circle shape class.
* @class Circle
* @extends Shape
* @constructor
* @param {options} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
* @param {number} [options.radius=1] The radius of this circle
*
* @example
* var body = new Body({ mass: 1 });
* var circleShape = new Circle({
* radius: 1
* });
* body.addShape(circleShape);
*/
function Circle(options){
options = options ? shallowClone(options) : {};
/**
* The radius of the circle.
* @property radius
* @type {number}
*/
this.radius = options.radius !== undefined ? options.radius : 1;
options.type = Shape.CIRCLE;
Shape.call(this, options);
}
Circle.prototype = new Shape();
Circle.prototype.constructor = Circle;
/**
* @method computeMomentOfInertia
* @return {Number}
*/
Circle.prototype.computeMomentOfInertia = function(){
var r = this.radius;
return r * r / 2;
};
/**
* @method updateBoundingRadius
* @return {Number}
*/
Circle.prototype.updateBoundingRadius = function(){
this.boundingRadius = this.radius;
};
/**
* @method updateArea
* @return {Number}
*/
Circle.prototype.updateArea = function(){
this.area = Math.PI * this.radius * this.radius;
};
/**
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position
* @param {Number} angle
*/
Circle.prototype.computeAABB = function(out, position/*, angle*/){
var r = this.radius;
vec2.set(out.upperBound, r, r);
vec2.set(out.lowerBound, -r, -r);
if(position){
vec2.add(out.lowerBound, out.lowerBound, position);
vec2.add(out.upperBound, out.upperBound, position);
}
};
var Ray_intersectSphere_intersectionPoint = vec2.create();
var Ray_intersectSphere_normal = vec2.create();
/**
* @method raycast
* @param {RaycastResult} result
* @param {Ray} ray
* @param {array} position
* @param {number} angle
*/
Circle.prototype.raycast = function(result, ray, position/*, angle*/){
var from = ray.from,
to = ray.to,
r = this.radius;
var a = Math.pow(to[0] - from[0], 2) + Math.pow(to[1] - from[1], 2);
var b = 2 * ((to[0] - from[0]) * (from[0] - position[0]) + (to[1] - from[1]) * (from[1] - position[1]));
var c = Math.pow(from[0] - position[0], 2) + Math.pow(from[1] - position[1], 2) - Math.pow(r, 2);
var delta = Math.pow(b, 2) - 4 * a * c;
var intersectionPoint = Ray_intersectSphere_intersectionPoint;
var normal = Ray_intersectSphere_normal;
if(delta < 0){
// No intersection
return;
} else if(delta === 0){
// single intersection point
vec2.lerp(intersectionPoint, from, to, delta);
vec2.subtract(normal, intersectionPoint, position);
vec2.normalize(normal,normal);
ray.reportIntersection(result, delta, normal, -1);
} else {
var sqrtDelta = Math.sqrt(delta);
var inv2a = 1 / (2 * a);
var d1 = (- b - sqrtDelta) * inv2a;
var d2 = (- b + sqrtDelta) * inv2a;
if(d1 >= 0 && d1 <= 1){
vec2.lerp(intersectionPoint, from, to, d1);
vec2.subtract(normal, intersectionPoint, position);
vec2.normalize(normal,normal);
ray.reportIntersection(result, d1, normal, -1);
if(result.shouldStop(ray)){
return;
}
}
if(d2 >= 0 && d2 <= 1){
vec2.lerp(intersectionPoint, from, to, d2);
vec2.subtract(normal, intersectionPoint, position);
vec2.normalize(normal,normal);
ray.reportIntersection(result, d2, normal, -1);
}
}
};
Circle.prototype.pointTest = function(localPoint){
var radius = this.radius;
return vec2.squaredLength(localPoint) <= radius * radius;
};
// circle/Utils.js
/* global P2_ARRAY_TYPE */
module.exports = Utils;
/**
* Misc utility functions
* @class Utils
* @constructor
*/
function Utils(){}
/**
* Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
* @method appendArray
* @static
* @param {Array} a
* @param {Array} b
*/
Utils.appendArray = function(a,b){
if (b.length < 150000) {
a.push.apply(a, b);
} else {
for (var i = 0, len = b.length; i !== len; ++i) {
a.push(b[i]);
}
}
};
/**
* Garbage free Array.splice(). Does not allocate a new array.
* @method splice
* @static
* @param {Array} array
* @param {Number} index
* @param {Number} howmany
*/
Utils.splice = function(array,index,howmany){
howmany = howmany || 1;
for (var i=index, len=array.length-howmany; i < len; i++){
array[i] = array[i + howmany];
}
array.length = len;
};
/**
* Remove an element from an array, if the array contains the element.
* @method arrayRemove
* @static
* @param {Array} array
* @param {Number} element
*/
Utils.arrayRemove = function(array, element){
var idx = array.indexOf(element);
if(idx!==-1){
Utils.splice(array, idx, 1);
}
};
/**
* The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
* @static
* @property {function} ARRAY_TYPE
* @example
* <script>
* <!-- Inject your preferred array type before loading p2.js -->
* P2_ARRAY_TYPE = Array;
* </script>
* <script src="p2.js"></script>
*/
if(typeof P2_ARRAY_TYPE !== 'undefined') {
Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
} else if (typeof Float32Array !== 'undefined'){
Utils.ARRAY_TYPE = Float32Array;
} else {
Utils.ARRAY_TYPE = Array;
}
/**
* Extend an object with the properties of another
* @static
* @method extend
* @param {object} a
* @param {object} b
*/
Utils.extend = function(a,b){
for(var key in b){
a[key] = b[key];
}
};
/**
* Shallow clone an object. Returns a new object instance with the same properties as the input instance.
* @static
* @method shallowClone
* @param {object} obj
*/
Utils.shallowClone = function(obj){
var newObj = {};
Utils.extend(newObj, obj);
return newObj;
};
/**
* Extend an options object with default values.
* @deprecated Not used internally, will be removed.
* @static
* @method defaults
* @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
* @param {object} defaults An object containing default values.
* @return {object} The modified options object.
*/
Utils.defaults = function(options, defaults){
console.warn('Utils.defaults is deprecated.');
options = options || {};
for(var key in defaults){
if(!(key in options)){
options[key] = defaults[key];
}
}
return options;
};
// circle/Shape.js
module.exports = Shape;
var vec2 = require('./vec2');
/**
* Base class for shapes. Not to be used directly.
* @class Shape
* @constructor
* @param {object} [options]
* @param {number} [options.angle=0]
* @param {number} [options.collisionGroup=1]
* @param {number} [options.collisionMask=1]
* @param {boolean} [options.collisionResponse=true]
* @param {Material} [options.material=null]
* @param {array} [options.position]
* @param {boolean} [options.sensor=false]
* @param {object} [options.type=0]
*/
function Shape(options){
options = options || {};
/**
* The body this shape is attached to. A shape can only be attached to a single body.
* @property {Body} body
*/
this.body = null;
/**
* Body-local position of the shape.
* @property {Array} position
*/
this.position = vec2.create();
if(options.position){
vec2.copy(this.position, options.position);
}
/**
* Body-local angle of the shape.
* @property {number} angle
*/
this.angle = options.angle || 0;
/**
* The type of the shape. One of:
*
* <ul>
* <li><a href="Shape.html#property_CIRCLE">Shape.CIRCLE</a></li>
* <li><a href="Shape.html#property_PARTICLE">Shape.PARTICLE</a></li>
* <li><a href="Shape.html#property_PLANE">Shape.PLANE</a></li>
* <li><a href="Shape.html#property_CONVEX">Shape.CONVEX</a></li>
* <li><a href="Shape.html#property_LINE">Shape.LINE</a></li>
* <li><a href="Shape.html#property_BOX">Shape.BOX</a></li>
* <li><a href="Shape.html#property_CAPSULE">Shape.CAPSULE</a></li>
* <li><a href="Shape.html#property_HEIGHTFIELD">Shape.HEIGHTFIELD</a></li>
* </ul>
*
* @property {number} type
*/
this.type = options.type || 0;
/**
* Shape object identifier. Read only.
* @readonly
* @type {Number}
* @property id
*/
this.id = Shape.idCounter++;
/**
* Bounding circle radius of this shape
* @readonly
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
/**
* Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
* @property collisionGroup
* @type {Number}
* @example
* // Setup bits for each available group
* var PLAYER = Math.pow(2,0),
* ENEMY = Math.pow(2,1),
* GROUND = Math.pow(2,2)
*
* // Put shapes into their groups
* player1Shape.collisionGroup = PLAYER;
* player2Shape.collisionGroup = PLAYER;
* enemyShape .collisionGroup = ENEMY;
* groundShape .collisionGroup = GROUND;
*
* // Assign groups that each shape collide with.
* // Note that the players can collide with ground and enemies, but not with other players.
* player1Shape.collisionMask = ENEMY | GROUND;
* player2Shape.collisionMask = ENEMY | GROUND;
* enemyShape .collisionMask = PLAYER | GROUND;
* groundShape .collisionMask = PLAYER | ENEMY;
*
* @example
* // How collision check is done
* if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
* // The shapes will collide
* }
*/
this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
* @property {Boolean} collisionResponse
*/
this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
/**
* Collision mask of this shape. See .collisionGroup.
* @property collisionMask
* @type {Number}
*/
this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
/**
* Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
* @property material
* @type {Material}
*/
this.material = options.material || null;
/**
* Area of this shape.
* @property area
* @type {Number}
*/
this.area = 0;
/**
* Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
* @property {Boolean} sensor
*/
this.sensor = options.sensor !== undefined ? options.sensor : false;
if(this.type){
this.updateBoundingRadius();
}
this.updateArea();
}
Shape.idCounter = 0;
/**
* @static
* @property {Number} CIRCLE
*/
Shape.CIRCLE = 1;
/**
* @static
* @property {Number} PARTICLE
*/
Shape.PARTICLE = 2;
/**
* @static
* @property {Number} PLANE
*/
Shape.PLANE = 4;
/**
* @static
* @property {Number} CONVEX
*/
Shape.CONVEX = 8;
/**
* @static
* @property {Number} LINE
*/
Shape.LINE = 16;
/**
* @static
* @property {Number} BOX
*/
Shape.BOX = 32;
/**
* @static
* @property {Number} CAPSULE
*/
Shape.CAPSULE = 64;
/**
* @static
* @property {Number} HEIGHTFIELD
*/
Shape.HEIGHTFIELD = 128;
Shape.prototype = {
/**
* Should return the moment of inertia around the Z axis of the body. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
* @method computeMomentOfInertia
* @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
*/
computeMomentOfInertia: function(){},
/**
* Returns the bounding circle radius of this shape.
* @method updateBoundingRadius
* @return {Number}
*/
updateBoundingRadius: function(){},
/**
* Update the .area property of the shape.
* @method updateArea
*/
updateArea: function(){},
/**
* Compute the world axis-aligned bounding box (AABB) of this shape.
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position World position of the shape.
* @param {Number} angle World angle of the shape.
*/
computeAABB: function(/*out, position, angle*/){
// To be implemented in each subclass
},
/**
* Perform raycasting on this shape.
* @method raycast
* @param {RayResult} result Where to store the resulting data.
* @param {Ray} ray The Ray that you want to use for raycasting.
* @param {array} position World position of the shape (the .position property will be ignored).
* @param {number} angle World angle of the shape (the .angle property will be ignored).
*/
raycast: function(/*result, ray, position, angle*/){
// To be implemented in each subclass
},
/**
* Test if a point is inside this shape.
* @method pointTest
* @param {array} localPoint
* @return {boolean}
*/
pointTest: function(/*localPoint*/){ return false; },
/**
* Transform a world point to local shape space (assumed the shape is transformed by both itself and the body).
* @method worldPointToLocal
* @param {array} out
* @param {array} worldPoint
*/
worldPointToLocal: (function () {
var shapeWorldPosition = vec2.create();
return function (out, worldPoint) {
var body = this.body;
vec2.rotate(shapeWorldPosition, this.position, body.angle);
vec2.add(shapeWorldPosition, shapeWorldPosition, body.position);
vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle);
};
})()
};
| 4 | 1,068 | JavaScript |
pixelrender | ./ProjectTest/JavaScript/pixelrender.js | // pixelrender/DomUtil.js
export default {
/**
* Creates and returns a new canvas. The opacity is by default set to 0
*
* @memberof Proton#Proton.DomUtil
* @method createCanvas
*
* @param {String} $id the canvas' id
* @param {Number} $width the canvas' width
* @param {Number} $height the canvas' height
* @param {String} [$position=absolute] the canvas' position, default is 'absolute'
*
* @return {Object}
*/
createCanvas(id, width, height, position = "absolute") {
const dom = document.createElement("canvas");
dom.id = id;
dom.width = width;
dom.height = height;
dom.style.opacity = 0;
dom.style.position = position;
this.transform(dom, -500, -500, 0, 0);
return dom;
},
createDiv(id, width, height) {
const dom = document.createElement("div");
dom.id = id;
dom.style.position = "absolute";
this.resize(dom, width, height);
return dom;
},
resize(dom, width, height) {
dom.style.width = width + "px";
dom.style.height = height + "px";
dom.style.marginLeft = -width / 2 + "px";
dom.style.marginTop = -height / 2 + "px";
},
/**
* Adds a transform: translate(), scale(), rotate() to a given div dom for all browsers
*
* @memberof Proton#Proton.DomUtil
* @method transform
*
* @param {HTMLDivElement} div
* @param {Number} $x
* @param {Number} $y
* @param {Number} $scale
* @param {Number} $rotate
*/
transform(div, x, y, scale, rotate) {
div.style.willChange = "transform";
const transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotate}deg)`;
this.css3(div, "transform", transform);
},
transform3d(div, x, y, scale, rotate) {
div.style.willChange = "transform";
const transform = `translate3d(${x}px, ${y}px, 0) scale(${scale}) rotate(${rotate}deg)`;
this.css3(div, "backfaceVisibility", "hidden");
this.css3(div, "transform", transform);
},
css3(div, key, val) {
const bkey = key.charAt(0).toUpperCase() + key.substr(1);
div.style[`Webkit${bkey}`] = val;
div.style[`Moz${bkey}`] = val;
div.style[`O${bkey}`] = val;
div.style[`ms${bkey}`] = val;
div.style[`${key}`] = val;
}
};
// pixelrender/Pool.js
/**
* Pool is the cache pool of the proton engine, it is very important.
*
* get(target, params, uid)
* Class
* uid = Puid.getId -> Puid save target cache
* target.__puid = uid
*
* body
* uid = Puid.getId -> Puid save target cache
*
*
* expire(target)
* cache[target.__puid] push target
*
*/
import Util from "./Util";
import Puid from "./Puid";
export default class Pool {
/**
* @memberof! Proton#
* @constructor
* @alias Proton.Pool
*
* @todo add description
* @todo add description of properties
*
* @property {Number} total
* @property {Object} cache
*/
constructor(num) {
this.total = 0;
this.cache = {};
}
/**
* @todo add description
*
* @method get
* @memberof Proton#Proton.Pool
*
* @param {Object|Function} target
* @param {Object} [params] just add if `target` is a function
*
* @return {Object}
*/
get(target, params, uid) {
let p;
uid = uid || target.__puid || Puid.getId(target);
if (this.cache[uid] && this.cache[uid].length > 0) {
p = this.cache[uid].pop();
} else {
p = this.createOrClone(target, params);
}
p.__puid = target.__puid || uid;
return p;
}
/**
* @todo add description
*
* @method set
* @memberof Proton#Proton.Pool
*
* @param {Object} target
*
* @return {Object}
*/
expire(target) {
return this.getCache(target.__puid).push(target);
}
/**
* Creates a new class instance
*
* @todo add more documentation
*
* @method create
* @memberof Proton#Proton.Pool
*
* @param {Object|Function} target any Object or Function
* @param {Object} [params] just add if `target` is a function
*
* @return {Object}
*/
createOrClone(target, params) {
this.total++;
if (this.create) {
return this.create(target, params);
} else if (typeof target === "function") {
return Util.classApply(target, params);
} else {
return target.clone();
}
}
/**
* @todo add description - what is in the cache?
*
* @method getCount
* @memberof Proton#Proton.Pool
*
* @return {Number}
*/
getCount() {
let count = 0;
for (let id in this.cache) count += this.cache[id].length;
return count++;
}
/**
* Destroyes all items from Pool.cache
*
* @method destroy
* @memberof Proton#Proton.Pool
*/
destroy() {
for (let id in this.cache) {
this.cache[id].length = 0;
delete this.cache[id];
}
}
/**
* Returns Pool.cache
*
* @method getCache
* @memberof Proton#Proton.Pool
* @private
*
* @param {Number} uid the unique id
*
* @return {Object}
*/
getCache(uid = "default") {
if (!this.cache[uid]) this.cache[uid] = [];
return this.cache[uid];
}
}
// pixelrender/ImgUtil.js
import WebGLUtil from "./WebGLUtil";
import DomUtil from "./DomUtil";
const imgsCache = {};
const canvasCache = {};
let canvasId = 0;
export default {
/**
* This will get the image data. It could be necessary to create a Proton.Zone.
*
* @memberof Proton#Proton.Util
* @method getImageData
*
* @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')'
* @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag');
* @param {Proton.Rectangle} rect
*/
getImageData(context, image, rect) {
context.drawImage(image, rect.x, rect.y);
const imagedata = context.getImageData(rect.x, rect.y, rect.width, rect.height);
context.clearRect(rect.x, rect.y, rect.width, rect.height);
return imagedata;
},
/**
* @memberof Proton#Proton.Util
* @method getImgFromCache
*
* @todo add description
* @todo describe func
*
* @param {Mixed} img
* @param {Proton.Particle} particle
* @param {Boolean} drawCanvas set to true if a canvas should be saved into particle.data.canvas
* @param {Boolean} func
*/
getImgFromCache(img, callback, param) {
const src = typeof img === "string" ? img : img.src;
if (imgsCache[src]) {
callback(imgsCache[src], param);
} else {
const image = new Image();
image.onload = e => {
imgsCache[src] = e.target;
callback(imgsCache[src], param);
};
image.src = src;
}
},
getCanvasFromCache(img, callback, param) {
const src = img.src;
if (!canvasCache[src]) {
const width = WebGLUtil.nhpot(img.width);
const height = WebGLUtil.nhpot(img.height);
const canvas = DomUtil.createCanvas(`proton_canvas_cache_${++canvasId}`, width, height);
const context = canvas.getContext("2d");
context.drawImage(img, 0, 0, img.width, img.height);
canvasCache[src] = canvas;
}
callback && callback(canvasCache[src], param);
return canvasCache[src];
}
};
// pixelrender/Util.js
import ImgUtil from "./ImgUtil";
export default {
/**
* Returns the default if the value is null or undefined
*
* @memberof Proton#Proton.Util
* @method initValue
*
* @param {Mixed} value a specific value, could be everything but null or undefined
* @param {Mixed} defaults the default if the value is null or undefined
*/
initValue(value, defaults) {
value = value !== null && value !== undefined ? value : defaults;
return value;
},
/**
* Checks if the value is a valid array
*
* @memberof Proton#Proton.Util
* @method isArray
*
* @param {Array} value Any array
*
* @returns {Boolean}
*/
isArray(value) {
return Object.prototype.toString.call(value) === "[object Array]";
},
/**
* Destroyes the given array
*
* @memberof Proton#Proton.Util
* @method emptyArray
*
* @param {Array} array Any array
*/
emptyArray(arr) {
if (arr) arr.length = 0;
},
toArray(arr) {
return this.isArray(arr) ? arr : [arr];
},
sliceArray(arr1, index, arr2) {
this.emptyArray(arr2);
for (let i = index; i < arr1.length; i++) {
arr2.push(arr1[i]);
}
},
getRandFromArray(arr) {
if (!arr) return null;
return arr[Math.floor(arr.length * Math.random())];
},
/**
* Destroyes the given object
*
* @memberof Proton#Proton.Util
* @method emptyObject
*
* @param {Object} obj Any object
*/
emptyObject(obj, ignore = null) {
for (let key in obj) {
if (ignore && ignore.indexOf(key) > -1) continue;
delete obj[key];
}
},
/**
* Makes an instance of a class and binds the given array
*
* @memberof Proton#Proton.Util
* @method classApply
*
* @param {Function} constructor A class to make an instance from
* @param {Array} [args] Any array to bind it to the constructor
*
* @return {Object} The instance of constructor, optionally bind with args
*/
classApply(constructor, args = null) {
if (!args) {
return new constructor();
} else {
const FactoryFunc = constructor.bind.apply(constructor, [null].concat(args));
return new FactoryFunc();
}
},
/**
* This will get the image data. It could be necessary to create a Proton.Zone.
*
* @memberof Proton#Proton.Util
* @method getImageData
*
* @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')'
* @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag');
* @param {Proton.Rectangle} rect
*/
getImageData(context, image, rect) {
return ImgUtil.getImageData(context, image, rect);
},
destroyAll(arr, param = null) {
let i = arr.length;
while (i--) {
try {
arr[i].destroy(param);
} catch (e) {}
delete arr[i];
}
arr.length = 0;
},
assign(target, source) {
if (typeof Object.assign !== "function") {
for (let key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
return target;
} else {
return Object.assign(target, source);
}
}
};
// pixelrender/Rectangle.js
export default class Rectangle {
constructor(x, y, w, h) {
this.x = x;
this.y = y;
this.width = w;
this.height = h;
this.bottom = this.y + this.height;
this.right = this.x + this.width;
}
contains(x, y) {
if (x <= this.right && x >= this.x && y <= this.bottom && y >= this.y) return true;
else return false;
}
}
// pixelrender/WebGLUtil.js
export default {
/**
* @memberof Proton#Proton.WebGLUtil
* @method ipot
*
* @todo add description
* @todo add length description
*
* @param {Number} length
*
* @return {Boolean}
*/
ipot(length) {
return (length & (length - 1)) === 0;
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method nhpot
*
* @todo add description
* @todo add length description
*
* @param {Number} length
*
* @return {Number}
*/
nhpot(length) {
--length;
for (let i = 1; i < 32; i <<= 1) {
length = length | (length >> i);
}
return length + 1;
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method makeTranslation
*
* @todo add description
* @todo add tx, ty description
* @todo add return description
*
* @param {Number} tx either 0 or 1
* @param {Number} ty either 0 or 1
*
* @return {Object}
*/
makeTranslation(tx, ty) {
return [1, 0, 0, 0, 1, 0, tx, ty, 1];
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method makeRotation
*
* @todo add description
* @todo add return description
*
* @param {Number} angleInRadians
*
* @return {Object}
*/
makeRotation(angleInRadians) {
let c = Math.cos(angleInRadians);
let s = Math.sin(angleInRadians);
return [c, -s, 0, s, c, 0, 0, 0, 1];
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method makeScale
*
* @todo add description
* @todo add tx, ty description
* @todo add return description
*
* @param {Number} sx either 0 or 1
* @param {Number} sy either 0 or 1
*
* @return {Object}
*/
makeScale(sx, sy) {
return [sx, 0, 0, 0, sy, 0, 0, 0, 1];
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method matrixMultiply
*
* @todo add description
* @todo add a, b description
* @todo add return description
*
* @param {Object} a
* @param {Object} b
*
* @return {Object}
*/
matrixMultiply(a, b) {
let a00 = a[0 * 3 + 0];
let a01 = a[0 * 3 + 1];
let a02 = a[0 * 3 + 2];
let a10 = a[1 * 3 + 0];
let a11 = a[1 * 3 + 1];
let a12 = a[1 * 3 + 2];
let a20 = a[2 * 3 + 0];
let a21 = a[2 * 3 + 1];
let a22 = a[2 * 3 + 2];
let b00 = b[0 * 3 + 0];
let b01 = b[0 * 3 + 1];
let b02 = b[0 * 3 + 2];
let b10 = b[1 * 3 + 0];
let b11 = b[1 * 3 + 1];
let b12 = b[1 * 3 + 2];
let b20 = b[2 * 3 + 0];
let b21 = b[2 * 3 + 1];
let b22 = b[2 * 3 + 2];
return [
a00 * b00 + a01 * b10 + a02 * b20,
a00 * b01 + a01 * b11 + a02 * b21,
a00 * b02 + a01 * b12 + a02 * b22,
a10 * b00 + a11 * b10 + a12 * b20,
a10 * b01 + a11 * b11 + a12 * b21,
a10 * b02 + a11 * b12 + a12 * b22,
a20 * b00 + a21 * b10 + a22 * b20,
a20 * b01 + a21 * b11 + a22 * b21,
a20 * b02 + a21 * b12 + a22 * b22
];
}
};
// pixelrender/Puid.js
const idsMap = {};
const Puid = {
_index: 0,
_cache: {},
id(type) {
if (idsMap[type] === undefined || idsMap[type] === null) idsMap[type] = 0;
return `${type}_${idsMap[type]++}`;
},
getId(target) {
let uid = this.getIdFromCache(target);
if (uid) return uid;
uid = `PUID_${this._index++}`;
this._cache[uid] = target;
return uid;
},
getIdFromCache(target) {
let obj, id;
for (id in this._cache) {
obj = this._cache[id];
if (obj === target) return id;
if (this.isBody(obj, target) && obj.src === target.src) return id;
}
return null;
},
isBody(obj, target) {
return typeof obj === "object" && typeof target === "object" && obj.isInner && target.isInner;
},
getTarget(uid) {
return this._cache[uid];
}
};
export default Puid;
// pixelrender/PixelRenderer.js
import Rectangle from "./Rectangle";
import BaseRenderer from "./BaseRenderer";
export default class PixelRenderer extends BaseRenderer {
constructor(element, rectangle) {
super(element);
this.context = this.element.getContext("2d");
this.imageData = null;
this.rectangle = rectangle;
this.createImageData(rectangle);
this.name = "PixelRenderer";
}
resize(width, height) {
this.element.width = width;
this.element.height = height;
}
createImageData(rectangle) {
this.rectangle = rectangle ? rectangle : new Rectangle(0, 0, this.element.width, this.element.height);
this.imageData = this.context.createImageData(this.rectangle.width, this.rectangle.height);
this.context.putImageData(this.imageData, this.rectangle.x, this.rectangle.y);
}
onProtonUpdate() {
this.context.clearRect(this.rectangle.x, this.rectangle.y, this.rectangle.width, this.rectangle.height);
this.imageData = this.context.getImageData(
this.rectangle.x,
this.rectangle.y,
this.rectangle.width,
this.rectangle.height
);
}
onProtonUpdateAfter() {
this.context.putImageData(this.imageData, this.rectangle.x, this.rectangle.y);
}
onParticleCreated(particle) {}
onParticleUpdate(particle) {
if (this.imageData) {
this.setPixel(
this.imageData,
(particle.p.x - this.rectangle.x) >> 0,
(particle.p.y - this.rectangle.y) >> 0,
particle
);
}
}
setPixel(imagedata, x, y, particle) {
const rgb = particle.rgb;
if (x < 0 || x > this.element.width || y < 0 || y > this.element.height) return;
const i = ((y >> 0) * imagedata.width + (x >> 0)) * 4;
imagedata.data[i] = rgb.r;
imagedata.data[i + 1] = rgb.g;
imagedata.data[i + 2] = rgb.b;
imagedata.data[i + 3] = particle.alpha * 255;
}
onParticleDead(particle) {}
destroy() {
super.destroy();
this.stroke = null;
this.context = null;
this.imageData = null;
this.rectangle = null;
}
}
// pixelrender/BaseRenderer.js
import Pool from "./Pool";
export default class BaseRenderer {
constructor(element, stroke) {
this.pool = new Pool();
this.element = element;
this.stroke = stroke;
this.circleConf = { isCircle: true };
this.initEventHandler();
this.name = "BaseRenderer";
}
setStroke(color = "#000000", thinkness = 1) {
this.stroke = { color, thinkness };
}
initEventHandler() {
this._protonUpdateHandler = () => {
this.onProtonUpdate.call(this);
};
this._protonUpdateAfterHandler = () => {
this.onProtonUpdateAfter.call(this);
};
this._emitterAddedHandler = emitter => {
this.onEmitterAdded.call(this, emitter);
};
this._emitterRemovedHandler = emitter => {
this.onEmitterRemoved.call(this, emitter);
};
this._particleCreatedHandler = particle => {
this.onParticleCreated.call(this, particle);
};
this._particleUpdateHandler = particle => {
this.onParticleUpdate.call(this, particle);
};
this._particleDeadHandler = particle => {
this.onParticleDead.call(this, particle);
};
}
init(proton) {
this.parent = proton;
proton.addEventListener("PROTON_UPDATE", this._protonUpdateHandler);
proton.addEventListener("PROTON_UPDATE_AFTER", this._protonUpdateAfterHandler);
proton.addEventListener("EMITTER_ADDED", this._emitterAddedHandler);
proton.addEventListener("EMITTER_REMOVED", this._emitterRemovedHandler);
proton.addEventListener("PARTICLE_CREATED", this._particleCreatedHandler);
proton.addEventListener("PARTICLE_UPDATE", this._particleUpdateHandler);
proton.addEventListener("PARTICLE_DEAD", this._particleDeadHandler);
}
resize(width, height) {}
destroy() {
this.remove();
this.pool.destroy();
this.pool = null;
this.element = null;
this.stroke = null;
}
remove(proton) {
this.parent.removeEventListener("PROTON_UPDATE", this._protonUpdateHandler);
this.parent.removeEventListener("PROTON_UPDATE_AFTER", this._protonUpdateAfterHandler);
this.parent.removeEventListener("EMITTER_ADDED", this._emitterAddedHandler);
this.parent.removeEventListener("EMITTER_REMOVED", this._emitterRemovedHandler);
this.parent.removeEventListener("PARTICLE_CREATED", this._particleCreatedHandler);
this.parent.removeEventListener("PARTICLE_UPDATE", this._particleUpdateHandler);
this.parent.removeEventListener("PARTICLE_DEAD", this._particleDeadHandler);
this.parent = null;
}
onProtonUpdate() {}
onProtonUpdateAfter() {}
onEmitterAdded(emitter) {}
onEmitterRemoved(emitter) {}
onParticleCreated(particle) {}
onParticleUpdate(particle) {}
onParticleDead(particle) {}
}
| 9 | 794 | JavaScript |
solver | ./ProjectTest/JavaScript/solver.js | // solver/EventEmitter.js
module.exports = EventEmitter;
/**
* Base class for objects that dispatches events.
* @class EventEmitter
* @constructor
* @example
* var emitter = new EventEmitter();
* emitter.on('myEvent', function(evt){
* console.log(evt.message);
* });
* emitter.emit({
* type: 'myEvent',
* message: 'Hello world!'
* });
*/
function EventEmitter() {
this.tmpArray = [];
}
EventEmitter.prototype = {
constructor: EventEmitter,
/**
* Add an event listener
* @method on
* @param {String} type
* @param {Function} listener
* @return {EventEmitter} The self object, for chainability.
* @example
* emitter.on('myEvent', function(evt){
* console.log('myEvt was triggered!');
* });
*/
on: function ( type, listener, context ) {
listener.context = context || this;
if ( this._listeners === undefined ){
this._listeners = {};
}
var listeners = this._listeners;
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
return this;
},
/**
* Remove an event listener
* @method off
* @param {String} type
* @param {Function} listener
* @return {EventEmitter} The self object, for chainability.
* @example
* emitter.on('myEvent', handler); // Add handler
* emitter.off('myEvent', handler); // Remove handler
*/
off: function ( type, listener ) {
var listeners = this._listeners;
if(!listeners || !listeners[type]){
return this;
}
var index = listeners[ type ].indexOf( listener );
if ( index !== - 1 ) {
listeners[ type ].splice( index, 1 );
}
return this;
},
/**
* Check if an event listener is added
* @method has
* @param {String} type
* @param {Function} listener
* @return {Boolean}
*/
has: function ( type, listener ) {
if ( this._listeners === undefined ){
return false;
}
var listeners = this._listeners;
if(listener){
if ( listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1 ) {
return true;
}
} else {
if ( listeners[ type ] !== undefined ) {
return true;
}
}
return false;
},
/**
* Emit an event.
* @method emit
* @param {Object} event
* @param {String} event.type
* @return {EventEmitter} The self object, for chainability.
* @example
* emitter.emit({
* type: 'myEvent',
* customData: 123
* });
*/
emit: function ( event ) {
if ( this._listeners === undefined ){
return this;
}
var listeners = this._listeners;
var listenerArray = listeners[ event.type ];
if ( listenerArray !== undefined ) {
event.target = this;
// Need to copy the listener array, in case some listener was added/removed inside a listener
var tmpArray = this.tmpArray;
for (var i = 0, l = listenerArray.length; i < l; i++) {
tmpArray[i] = listenerArray[i];
}
for (var i = 0, l = tmpArray.length; i < l; i++) {
var listener = tmpArray[ i ];
listener.call( listener.context, event );
}
tmpArray.length = 0;
}
return this;
}
};
// solver/Solver.js
var EventEmitter = require('./EventEmitter');
module.exports = Solver;
/**
* Base class for constraint solvers.
* @class Solver
* @constructor
* @extends EventEmitter
*/
function Solver(options,type){
options = options || {};
EventEmitter.call(this);
this.type = type;
/**
* Current equations in the solver.
*
* @property equations
* @type {Array}
*/
this.equations = [];
/**
* Function that is used to sort all equations before each solve.
* @property equationSortFunction
* @type {function|boolean}
*/
this.equationSortFunction = options.equationSortFunction || false;
}
Solver.prototype = new EventEmitter();
Solver.prototype.constructor = Solver;
/**
* Method to be implemented in each subclass
* @method solve
* @param {Number} dt
* @param {World} world
*/
Solver.prototype.solve = function(/*dt,world*/){
throw new Error("Solver.solve should be implemented by subclasses!");
};
/**
* Sort all equations using the .equationSortFunction. Should be called by subclasses before solving.
* @method sortEquations
*/
Solver.prototype.sortEquations = function(){
if(this.equationSortFunction){
this.equations.sort(this.equationSortFunction);
}
};
/**
* Add an equation to be solved.
*
* @method addEquation
* @param {Equation} eq
*/
Solver.prototype.addEquation = function(eq){
if(eq.enabled){
this.equations.push(eq);
}
};
/**
* Add equations. Same as .addEquation, but this time the argument is an array of Equations
*
* @method addEquations
* @param {Array} eqs
*/
Solver.prototype.addEquations = function(eqs){
for(var i=0, N=eqs.length; i!==N; i++){
var eq = eqs[i];
if(eq.enabled){
this.equations.push(eq);
}
}
};
/**
* Remove an equation.
*
* @method removeEquation
* @param {Equation} eq
*/
Solver.prototype.removeEquation = function(eq){
var i = this.equations.indexOf(eq);
if(i !== -1){
this.equations.splice(i,1);
}
};
/**
* Remove all currently added equations.
*
* @method removeAllEquations
*/
Solver.prototype.removeAllEquations = function(){
this.equations.length=0;
};
/**
* Gauss-Seidel solver.
* @property GS
* @type {Number}
* @static
*/
Solver.GS = 1;
| 2 | 242 | JavaScript |
aggregate | ./ProjectTest/JavaScript/aggregate.js | // aggregate/aggregate.js
import { setNonEnumProp } from './descriptors.js'
// Array of `errors` can be set using an option.
// This is like `AggregateError` except:
// - This is available in any class, removing the need to create separate
// classes for it
// - Any class can opt-in to it or not
// - This uses a named parameter instead of a positional one:
// - This is more monomorphic
// - This parallels the `cause` option
// Child `errors` are always kept, only appended to.
export const setAggregateErrors = (error, errors) => {
if (errors === undefined) {
return
}
if (!Array.isArray(errors)) {
throw new TypeError(`"errors" option must be an array: ${errors}`)
}
setNonEnumProp(error, 'errors', errors)
}
// aggregate/descriptors.js
// Most error core properties are not enumerable
export const setNonEnumProp = (object, propName, value) => {
// eslint-disable-next-line fp/no-mutating-methods
Object.defineProperty(object, propName, {
value,
enumerable: false,
writable: true,
configurable: true,
})
}
| 2 | 32 | JavaScript |
overlapkeeper | ./ProjectTest/JavaScript/overlapkeeper.js | // overlapkeeper/Pool.js
module.exports = Pool;
/**
* Object pooling utility.
* @class Pool
* @constructor
*/
function Pool(options) {
options = options || {};
/**
* @property {Array} objects
* @type {Array}
*/
this.objects = [];
if(options.size !== undefined){
this.resize(options.size);
}
}
/**
* @method resize
* @param {number} size
* @return {Pool} Self, for chaining
*/
Pool.prototype.resize = function (size) {
var objects = this.objects;
while (objects.length > size) {
objects.pop();
}
while (objects.length < size) {
objects.push(this.create());
}
return this;
};
/**
* Get an object from the pool or create a new instance.
* @method get
* @return {Object}
*/
Pool.prototype.get = function () {
var objects = this.objects;
return objects.length ? objects.pop() : this.create();
};
/**
* Clean up and put the object back into the pool for later use.
* @method release
* @param {Object} object
* @return {Pool} Self for chaining
*/
Pool.prototype.release = function (object) {
this.destroy(object);
this.objects.push(object);
return this;
};
// overlapkeeper/OverlapKeeperRecord.js
module.exports = OverlapKeeperRecord;
/**
* Overlap data container for the OverlapKeeper
* @class OverlapKeeperRecord
* @constructor
* @param {Body} bodyA
* @param {Shape} shapeA
* @param {Body} bodyB
* @param {Shape} shapeB
*/
function OverlapKeeperRecord(bodyA, shapeA, bodyB, shapeB){
/**
* @property {Shape} shapeA
*/
this.shapeA = shapeA;
/**
* @property {Shape} shapeB
*/
this.shapeB = shapeB;
/**
* @property {Body} bodyA
*/
this.bodyA = bodyA;
/**
* @property {Body} bodyB
*/
this.bodyB = bodyB;
}
/**
* Set the data for the record
* @method set
* @param {Body} bodyA
* @param {Shape} shapeA
* @param {Body} bodyB
* @param {Shape} shapeB
*/
OverlapKeeperRecord.prototype.set = function(bodyA, shapeA, bodyB, shapeB){
OverlapKeeperRecord.call(this, bodyA, shapeA, bodyB, shapeB);
};
// overlapkeeper/TupleDictionary.js
var Utils = require('./Utils');
module.exports = TupleDictionary;
/**
* @class TupleDictionary
* @constructor
*/
function TupleDictionary() {
/**
* The data storage
* @property data
* @type {Object}
*/
this.data = {};
/**
* Keys that are currently used.
* @property {Array} keys
*/
this.keys = [];
}
/**
* Generate a key given two integers
* @method getKey
* @param {number} i
* @param {number} j
* @return {string}
*/
TupleDictionary.prototype.getKey = function(id1, id2) {
id1 = id1|0;
id2 = id2|0;
if ( (id1|0) === (id2|0) ){
return -1;
}
// valid for values < 2^16
return ((id1|0) > (id2|0) ?
(id1 << 16) | (id2 & 0xFFFF) :
(id2 << 16) | (id1 & 0xFFFF))|0
;
};
/**
* @method getByKey
* @param {Number} key
* @return {Object}
*/
TupleDictionary.prototype.getByKey = function(key) {
key = key|0;
return this.data[key];
};
/**
* @method get
* @param {Number} i
* @param {Number} j
* @return {Number}
*/
TupleDictionary.prototype.get = function(i, j) {
return this.data[this.getKey(i, j)];
};
/**
* Set a value.
* @method set
* @param {Number} i
* @param {Number} j
* @param {Number} value
*/
TupleDictionary.prototype.set = function(i, j, value) {
if(!value){
throw new Error("No data!");
}
var key = this.getKey(i, j);
// Check if key already exists
if(!this.data[key]){
this.keys.push(key);
}
this.data[key] = value;
return key;
};
/**
* Remove all data.
* @method reset
*/
TupleDictionary.prototype.reset = function() {
var data = this.data,
keys = this.keys;
var l = keys.length;
while(l--) {
delete data[keys[l]];
}
keys.length = 0;
};
/**
* Copy another TupleDictionary. Note that all data in this dictionary will be removed.
* @method copy
* @param {TupleDictionary} dict The TupleDictionary to copy into this one.
*/
TupleDictionary.prototype.copy = function(dict) {
this.reset();
Utils.appendArray(this.keys, dict.keys);
var l = dict.keys.length;
while(l--){
var key = dict.keys[l];
this.data[key] = dict.data[key];
}
};
// overlapkeeper/OverlapKeeperRecordPool.js
var OverlapKeeperRecord = require('./OverlapKeeperRecord');
var Pool = require('./Pool');
module.exports = OverlapKeeperRecordPool;
/**
* @class
*/
function OverlapKeeperRecordPool() {
Pool.apply(this, arguments);
}
OverlapKeeperRecordPool.prototype = new Pool();
OverlapKeeperRecordPool.prototype.constructor = OverlapKeeperRecordPool;
/**
* @method create
* @return {OverlapKeeperRecord}
*/
OverlapKeeperRecordPool.prototype.create = function () {
return new OverlapKeeperRecord();
};
/**
* @method destroy
* @param {OverlapKeeperRecord} record
* @return {OverlapKeeperRecordPool}
*/
OverlapKeeperRecordPool.prototype.destroy = function (record) {
record.bodyA = record.bodyB = record.shapeA = record.shapeB = null;
return this;
};
// overlapkeeper/OverlapKeeper.js
var TupleDictionary = require('./TupleDictionary');
var OverlapKeeperRecordPool = require('./OverlapKeeperRecordPool');
module.exports = OverlapKeeper;
/**
* Keeps track of overlaps in the current state and the last step state.
* @class OverlapKeeper
* @constructor
*/
function OverlapKeeper() {
this.overlappingShapesLastState = new TupleDictionary();
this.overlappingShapesCurrentState = new TupleDictionary();
this.recordPool = new OverlapKeeperRecordPool({ size: 16 });
this.tmpDict = new TupleDictionary();
this.tmpArray1 = [];
}
/**
* Ticks one step forward in time. This will move the current overlap state to the "old" overlap state, and create a new one as current.
* @method tick
*/
OverlapKeeper.prototype.tick = function() {
var last = this.overlappingShapesLastState;
var current = this.overlappingShapesCurrentState;
// Save old objects into pool
var l = last.keys.length;
while(l--){
var key = last.keys[l];
var lastObject = last.getByKey(key);
if(lastObject){
// The record is only used in the "last" dict, and will be removed. We might as well pool it.
this.recordPool.release(lastObject);
}
}
// Clear last object
last.reset();
// Transfer from new object to old
last.copy(current);
// Clear current object
current.reset();
};
/**
* @method setOverlapping
* @param {Body} bodyA
* @param {Body} shapeA
* @param {Body} bodyB
* @param {Body} shapeB
*/
OverlapKeeper.prototype.setOverlapping = function(bodyA, shapeA, bodyB, shapeB) {
var current = this.overlappingShapesCurrentState;
// Store current contact state
if(!current.get(shapeA.id, shapeB.id)){
var data = this.recordPool.get();
data.set(bodyA, shapeA, bodyB, shapeB);
current.set(shapeA.id, shapeB.id, data);
}
};
OverlapKeeper.prototype.getNewOverlaps = function(result){
return this.getDiff(this.overlappingShapesLastState, this.overlappingShapesCurrentState, result);
};
OverlapKeeper.prototype.getEndOverlaps = function(result){
return this.getDiff(this.overlappingShapesCurrentState, this.overlappingShapesLastState, result);
};
/**
* Checks if two bodies are currently overlapping.
* @method bodiesAreOverlapping
* @param {Body} bodyA
* @param {Body} bodyB
* @return {boolean}
*/
OverlapKeeper.prototype.bodiesAreOverlapping = function(bodyA, bodyB){
var current = this.overlappingShapesCurrentState;
var l = current.keys.length;
while(l--){
var key = current.keys[l];
var data = current.data[key];
if((data.bodyA === bodyA && data.bodyB === bodyB) || data.bodyA === bodyB && data.bodyB === bodyA){
return true;
}
}
return false;
};
OverlapKeeper.prototype.getDiff = function(dictA, dictB, result){
var result = result || [];
var last = dictA;
var current = dictB;
result.length = 0;
var l = current.keys.length;
while(l--){
var key = current.keys[l];
var data = current.data[key];
if(!data){
throw new Error('Key '+key+' had no data!');
}
var lastData = last.data[key];
if(!lastData){
// Not overlapping in last state, but in current.
result.push(data);
}
}
return result;
};
OverlapKeeper.prototype.isNewOverlap = function(shapeA, shapeB){
var idA = shapeA.id|0,
idB = shapeB.id|0;
var last = this.overlappingShapesLastState;
var current = this.overlappingShapesCurrentState;
// Not in last but in new
return !!!last.get(idA, idB) && !!current.get(idA, idB);
};
OverlapKeeper.prototype.getNewBodyOverlaps = function(result){
this.tmpArray1.length = 0;
var overlaps = this.getNewOverlaps(this.tmpArray1);
return this.getBodyDiff(overlaps, result);
};
OverlapKeeper.prototype.getEndBodyOverlaps = function(result){
this.tmpArray1.length = 0;
var overlaps = this.getEndOverlaps(this.tmpArray1);
return this.getBodyDiff(overlaps, result);
};
OverlapKeeper.prototype.getBodyDiff = function(overlaps, result){
result = result || [];
var accumulator = this.tmpDict;
var l = overlaps.length;
while(l--){
var data = overlaps[l];
// Since we use body id's for the accumulator, these will be a subset of the original one
accumulator.set(data.bodyA.id|0, data.bodyB.id|0, data);
}
l = accumulator.keys.length;
while(l--){
var data = accumulator.getByKey(accumulator.keys[l]);
if(data){
result.push(data.bodyA, data.bodyB);
}
}
accumulator.reset();
return result;
};
// overlapkeeper/Utils.js
/* global P2_ARRAY_TYPE */
module.exports = Utils;
/**
* Misc utility functions
* @class Utils
* @constructor
*/
function Utils(){}
/**
* Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
* @method appendArray
* @static
* @param {Array} a
* @param {Array} b
*/
Utils.appendArray = function(a,b){
if (b.length < 150000) {
a.push.apply(a, b);
} else {
for (var i = 0, len = b.length; i !== len; ++i) {
a.push(b[i]);
}
}
};
/**
* Garbage free Array.splice(). Does not allocate a new array.
* @method splice
* @static
* @param {Array} array
* @param {Number} index
* @param {Number} howmany
*/
Utils.splice = function(array,index,howmany){
howmany = howmany || 1;
for (var i=index, len=array.length-howmany; i < len; i++){
array[i] = array[i + howmany];
}
array.length = len;
};
/**
* Remove an element from an array, if the array contains the element.
* @method arrayRemove
* @static
* @param {Array} array
* @param {Number} element
*/
Utils.arrayRemove = function(array, element){
var idx = array.indexOf(element);
if(idx!==-1){
Utils.splice(array, idx, 1);
}
};
/**
* The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
* @static
* @property {function} ARRAY_TYPE
* @example
* <script>
* <!-- Inject your preferred array type before loading p2.js -->
* P2_ARRAY_TYPE = Array;
* </script>
* <script src="p2.js"></script>
*/
if(typeof P2_ARRAY_TYPE !== 'undefined') {
Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
} else if (typeof Float32Array !== 'undefined'){
Utils.ARRAY_TYPE = Float32Array;
} else {
Utils.ARRAY_TYPE = Array;
}
/**
* Extend an object with the properties of another
* @static
* @method extend
* @param {object} a
* @param {object} b
*/
Utils.extend = function(a,b){
for(var key in b){
a[key] = b[key];
}
};
/**
* Shallow clone an object. Returns a new object instance with the same properties as the input instance.
* @static
* @method shallowClone
* @param {object} obj
*/
Utils.shallowClone = function(obj){
var newObj = {};
Utils.extend(newObj, obj);
return newObj;
};
/**
* Extend an options object with default values.
* @deprecated Not used internally, will be removed.
* @static
* @method defaults
* @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
* @param {object} defaults An object containing default values.
* @return {object} The modified options object.
*/
Utils.defaults = function(options, defaults){
console.warn('Utils.defaults is deprecated.');
options = options || {};
for(var key in defaults){
if(!(key in options)){
options[key] = defaults[key];
}
}
return options;
};
| 6 | 539 | JavaScript |
synergy | ./ProjectTest/JavaScript/synergy.js | // synergy/attribute.js
import { isPrimitive, typeOf } from "./helpers.js"
const pascalToKebab = (string) =>
string.replace(/[\w]([A-Z])/g, function (m) {
return m[0] + "-" + m[1].toLowerCase()
})
const kebabToPascal = (string) =>
string.replace(/[\w]-([\w])/g, function (m) {
return m[0] + m[2].toUpperCase()
})
const parseStyles = (value) => {
let type = typeof value
if (type === "string")
return value.split(";").reduce((o, value) => {
const [k, v] = value.split(":").map((v) => v.trim())
if (k) o[k] = v
return o
}, {})
if (type === "object") return value
return {}
}
const joinStyles = (value) =>
Object.entries(value)
.map(([k, v]) => `${k}: ${v};`)
.join(" ")
const convertStyles = (o) =>
Object.keys(o).reduce((a, k) => {
a[pascalToKebab(k)] = o[k]
return a
}, {})
export const applyAttribute = (node, name, value) => {
if (name === "style") {
value = joinStyles(
convertStyles({
...parseStyles(node.getAttribute("style")),
...parseStyles(value),
})
)
} else if (name === "class") {
switch (typeOf(value)) {
case "Array":
value = value.join(" ")
break
case "Object":
value = Object.keys(value)
.reduce((a, k) => {
if (value[k]) a.push(k)
return a
}, [])
.join(" ")
break
}
} else if (!isPrimitive(value)) {
return (node[kebabToPascal(name)] = value)
}
name = pascalToKebab(name)
if (typeof value === "boolean") {
if (name.startsWith("aria-")) {
value = "" + value
} else if (value) {
value = ""
}
}
let current = node.getAttribute(name)
if (value === current) return
if (typeof value === "string" || typeof value === "number") {
node.setAttribute(name, value)
} else {
node.removeAttribute(name)
}
}
// synergy/css.js
function nextWord(css, count) {
return css.slice(count - 1).split(/[\s+|\n+|,]/)[0]
}
function nextOpenBrace(css, count) {
let index = css.slice(count - 1).indexOf("{")
if (index > -1) {
return count + index
}
}
export function prefixSelectors(prefix, css) {
let insideBlock = false
let look = true
let output = ""
let count = 0
let skip = false
for (let char of css) {
if (char === "@" && nextWord(css, count + 1) === "@media") {
skip = nextOpenBrace(css, count)
}
if (skip) {
if (skip === count) skip = false
}
if (!skip) {
if (char === "}") {
insideBlock = false
look = true
} else if (char === ",") {
look = true
} else if (char === "{") {
insideBlock = true
} else if (look && !insideBlock && !char.match(/\s/)) {
let w = nextWord(css, count + 1)
// console.log({ w })
if (
w !== prefix &&
w.charAt(0) !== "@" &&
w.charAt(0) !== ":" &&
w.charAt(0) !== "*" &&
w !== "html" &&
w !== "body"
) {
output += prefix + " "
}
look = false
}
}
output += char
count += 1
}
return output
}
export function appendStyles(name, css) {
if (document.querySelector(`style#${name}`)) return
const el = document.createElement("style")
el.id = name
el.innerHTML = prefixSelectors(name, css)
document.head.appendChild(el)
}
// synergy/helpers.js
export const wrapToken = (v) => {
v = v.trim()
if (v.startsWith("{{")) return v
return `{{${v}}}`
}
export const last = (v = []) => v[v.length - 1]
export const isWhitespace = (node) => {
return node.nodeType === node.TEXT_NODE && node.nodeValue.trim() === ""
}
export const walk = (node, callback, deep = true) => {
if (!node) return
// if (node.matches?.(`script[type="application/synergy"]`))
// return walk(node.nextSibling, callback, deep)
if (!isWhitespace(node)) {
let v = callback(node)
if (v === false) return
if (v?.nodeName) return walk(v, callback, deep)
}
if (deep) walk(node.firstChild, callback, deep)
walk(node.nextSibling, callback, deep)
}
const transformBrackets = (str = "") => {
let parts = str.split(/(\[[^\]]+\])/).filter((v) => v)
return parts.reduce((a, part) => {
let v = part.charAt(0) === "[" ? "." + part.replace(/\./g, ":") : part
return a + v
}, "")
}
const getTarget = (path, target) => {
let parts = transformBrackets(path)
.split(".")
.map((k) => {
if (k.charAt(0) === "[") {
let p = k.slice(1, -1).replace(/:/g, ".")
return getValueAtPath(p, target)
} else {
return k
}
})
let t =
parts.slice(0, -1).reduce((o, k) => {
return o && o[k]
}, target) || target
return [t, last(parts)]
}
export const getValueAtPath = (path, target) => {
let [a, b] = getTarget(path, target)
let v = a?.[b]
if (typeof v === "function") return v.bind(a)
return v
}
export const setValueAtPath = (path, value, target) => {
let [a, b] = getTarget(path, target)
return (a[b] = value)
}
export const fragmentFromTemplate = (v) => {
if (typeof v === "string") {
if (v.charAt(0) === "#") {
v = document.querySelector(v)
} else {
let tpl = document.createElement("template")
tpl.innerHTML = v.trim()
return tpl.content.cloneNode(true)
}
}
if (v.nodeName === "TEMPLATE") return v.cloneNode(true).content
if (v.nodeName === "defs") return v.firstElementChild.cloneNode(true)
}
export const debounce = (fn) => {
let wait = false
let invoke = false
return () => {
if (wait) {
invoke = true
} else {
wait = true
fn()
requestAnimationFrame(() => {
if (invoke) fn()
wait = false
})
}
}
}
export const isPrimitive = (v) => v === null || typeof v !== "object"
export const typeOf = (v) =>
Object.prototype.toString.call(v).match(/\s(.+[^\]])/)[1]
export const pascalToKebab = (string) =>
string.replace(/[\w]([A-Z])/g, function (m) {
return m[0] + "-" + m[1].toLowerCase()
})
export const kebabToPascal = (string) =>
string.replace(/[\w]-([\w])/g, function (m) {
return m[0] + m[2].toUpperCase()
})
export const applyAttribute = (node, name, value) => {
name = pascalToKebab(name)
if (typeof value === "boolean") {
if (name.startsWith("aria-")) {
value = "" + value
} else if (value) {
value = ""
}
}
if (typeof value === "string" || typeof value === "number") {
node.setAttribute(name, value)
} else {
node.removeAttribute(name)
}
}
export const attributeToProp = (k, v) => {
let name = kebabToPascal(k)
if (v === "") v = true
if (k.startsWith("aria-")) {
if (v === "true") v = true
if (v === "false") v = false
}
return {
name,
value: v,
}
}
export function getDataScript(node) {
return node.querySelector(
`script[type="application/synergy"][id="${node.nodeName}"]`
)
}
export function createDataScript(node) {
let ds = document.createElement("script")
ds.setAttribute("type", "application/synergy")
ds.setAttribute("id", node.nodeName)
node.append(ds)
return ds
}
// synergy/partial.js
import { appendStyles } from "./css.js"
export const partials = {}
export const partial = (name, html, css) => {
if (css) appendStyles(name, css)
partials[name.toUpperCase()] = html
}
// synergy/context.js
import { getValueAtPath, isPrimitive } from "./helpers.js"
const handler = ({ path, identifier, key, index, i, k }) => ({
get(target, property) {
let x = getValueAtPath(path, target)
// x === the collection
if (property === identifier) {
for (let n in x) {
let v = x[n]
if (key) {
if (v[key] === k) return v
} else {
if (n == i) return v
}
}
}
if (property === index) {
for (let n in x) {
let v = x[n]
if (key) {
if (v[key] === k) return n
} else {
if (n == i) return n
}
}
}
let t = key ? x.find((v) => v[key] === k) : x?.[i]
if (t?.hasOwnProperty?.(property)) return t[property]
return Reflect.get(...arguments)
},
set(target, property, value) {
let x = getValueAtPath(path, target)
let t = key ? x.find((v) => v[key] === k) : x[i]
if (t && !isPrimitive(t)) {
t[property] = value
return true
}
return Reflect.set(...arguments)
},
})
export const createContext = (v = []) => {
let context = v
return {
get: () => context,
push: (v) => context.push(v),
wrap: (state) => {
return context.reduce(
(target, ctx) => new Proxy(target, handler(ctx)),
state
)
},
}
}
| 5 | 374 | JavaScript |
easing | ./ProjectTest/JavaScript/easing.js | // easing/BezierEasing.js
/**
* @author pschroen / https://ufo.ai/
*
* Based on https://github.com/gre/bezier-easing
*/
// These values are established by empiricism with tests (tradeoff: performance VS precision)
const NEWTON_ITERATIONS = 4;
const NEWTON_MIN_SLOPE = 0.001;
const SUBDIVISION_PRECISION = 0.0000001;
const SUBDIVISION_MAX_ITERATIONS = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1 / (kSplineTableSize - 1);
function A(aA1, aA2) {
return 1 - 3 * aA2 + 3 * aA1;
}
function B(aA1, aA2) {
return 3 * aA2 - 6 * aA1;
}
function C(aA1) {
return 3 * aA1;
}
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2
function calcBezier(aT, aA1, aA2) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2
function getSlope(aT, aA1, aA2) {
return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX, aA, aB, mX1, mX2) {
let currentX;
let currentT;
let i = 0;
do {
currentT = aA + (aB - aA) / 2;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
for (let i = 0; i < NEWTON_ITERATIONS; i++) {
const currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0) {
return aGuessT;
}
const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function LinearEasing(x) {
return x;
}
export default function bezier(mX1, mY1, mX2, mY2) {
if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {
throw new Error('Bezier x values must be in [0, 1] range');
}
if (mX1 === mY1 && mX2 === mY2) {
return LinearEasing;
}
// Precompute samples table
const sampleValues = new Float32Array(kSplineTableSize);
for (let i = 0; i < kSplineTableSize; i++) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
function getTForX(aX) {
let intervalStart = 0;
let currentSample = 1;
const lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; currentSample++) {
intervalStart += kSampleStepSize;
}
currentSample--;
// Interpolate to provide an initial guess for t
const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
const guessForT = intervalStart + dist * kSampleStepSize;
const initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
return function BezierEasing(x) {
// Because JavaScript numbers are imprecise, we should guarantee the extremes are right
if (x === 0 || x === 1) {
return x;
}
return calcBezier(getTForX(x), mY1, mY2);
};
}
// easing/Easing.js
/**
* @author pschroen / https://ufo.ai/
*
* Based on https://github.com/danro/easing-js
* Based on https://github.com/CreateJS/TweenJS
* Based on https://github.com/tweenjs/tween.js
* Based on https://easings.net/
*/
import BezierEasing from './BezierEasing.js';
export class Easing {
static linear(t) {
return t;
}
static easeInQuad(t) {
return t * t;
}
static easeOutQuad(t) {
return t * (2 - t);
}
static easeInOutQuad(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t;
}
return -0.5 * (--t * (t - 2) - 1);
}
static easeInCubic(t) {
return t * t * t;
}
static easeOutCubic(t) {
return --t * t * t + 1;
}
static easeInOutCubic(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t * t;
}
return 0.5 * ((t -= 2) * t * t + 2);
}
static easeInQuart(t) {
return t * t * t * t;
}
static easeOutQuart(t) {
return 1 - --t * t * t * t;
}
static easeInOutQuart(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t * t * t;
}
return -0.5 * ((t -= 2) * t * t * t - 2);
}
static easeInQuint(t) {
return t * t * t * t * t;
}
static easeOutQuint(t) {
return --t * t * t * t * t + 1;
}
static easeInOutQuint(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t * t * t * t;
}
return 0.5 * ((t -= 2) * t * t * t * t + 2);
}
static easeInSine(t) {
return 1 - Math.sin(((1 - t) * Math.PI) / 2);
}
static easeOutSine(t) {
return Math.sin((t * Math.PI) / 2);
}
static easeInOutSine(t) {
return 0.5 * (1 - Math.sin(Math.PI * (0.5 - t)));
}
static easeInExpo(t) {
return t === 0 ? 0 : Math.pow(1024, t - 1);
}
static easeOutExpo(t) {
return t === 1 ? 1 : 1 - Math.pow(2, -10 * t);
}
static easeInOutExpo(t) {
if (t === 0 || t === 1) {
return t;
}
if ((t *= 2) < 1) {
return 0.5 * Math.pow(1024, t - 1);
}
return 0.5 * (-Math.pow(2, -10 * (t - 1)) + 2);
}
static easeInCirc(t) {
return 1 - Math.sqrt(1 - t * t);
}
static easeOutCirc(t) {
return Math.sqrt(1 - --t * t);
}
static easeInOutCirc(t) {
if ((t *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1);
}
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
}
static easeInBack(t) {
const s = 1.70158;
return t === 1 ? 1 : t * t * ((s + 1) * t - s);
}
static easeOutBack(t) {
const s = 1.70158;
return t === 0 ? 0 : --t * t * ((s + 1) * t + s) + 1;
}
static easeInOutBack(t) {
const s = 1.70158 * 1.525;
if ((t *= 2) < 1) {
return 0.5 * (t * t * ((s + 1) * t - s));
}
return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2);
}
static easeInElastic(t, amplitude = 1, period = 0.3) {
if (t === 0 || t === 1) {
return t;
}
const pi2 = Math.PI * 2;
const s = period / pi2 * Math.asin(1 / amplitude);
return -(amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period));
}
static easeOutElastic(t, amplitude = 1, period = 0.3) {
if (t === 0 || t === 1) {
return t;
}
const pi2 = Math.PI * 2;
const s = period / pi2 * Math.asin(1 / amplitude);
return amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1;
}
static easeInOutElastic(t, amplitude = 1, period = 0.3 * 1.5) {
if (t === 0 || t === 1) {
return t;
}
const pi2 = Math.PI * 2;
const s = period / pi2 * Math.asin(1 / amplitude);
if ((t *= 2) < 1) {
return -0.5 * (amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period));
}
return amplitude * Math.pow(2, -10 * --t) * Math.sin((t - s) * pi2 / period) * 0.5 + 1;
}
static easeInBounce(t) {
return 1 - this.easeOutBounce(1 - t);
}
static easeOutBounce(t) {
const n1 = 7.5625;
const d1 = 2.75;
if (t < 1 / d1) {
return n1 * t * t;
} else if (t < 2 / d1) {
return n1 * (t -= 1.5 / d1) * t + 0.75;
} else if (t < 2.5 / d1) {
return n1 * (t -= 2.25 / d1) * t + 0.9375;
} else {
return n1 * (t -= 2.625 / d1) * t + 0.984375;
}
}
static easeInOutBounce(t) {
if (t < 0.5) {
return this.easeInBounce(t * 2) * 0.5;
}
return this.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
}
static addBezier(name, mX1, mY1, mX2, mY2) {
this[name] = BezierEasing(mX1, mY1, mX2, mY2);
}
}
| 2 | 341 | JavaScript |
check | ./ProjectTest/JavaScript/check.js | // check/check.js
import { isSubclass } from './subclass.js'
// Confirm `custom` option is valid
export const checkCustom = (custom, ParentError) => {
if (typeof custom !== 'function') {
throw new TypeError(
`The "custom" class of "${ParentError.name}.subclass()" must be a class: ${custom}`,
)
}
checkParent(custom, ParentError)
checkPrototype(custom, ParentError)
}
// We do not allow passing `ParentError` without extending from it, since
// `undefined` can be used for it instead.
// We do not allow extending from `ParentError` indirectly:
// - This promotes using subclassing through `ErrorClass.subclass()`, since it
// reduces the risk of user instantiating unregistered class
// - This promotes `ErrorClass.subclass()` as a pattern for subclassing, to
// reduce the risk of directly extending a registered class without
// registering the subclass
const checkParent = (custom, ParentError) => {
if (custom === ParentError) {
throw new TypeError(
`The "custom" class of "${ParentError.name}.subclass()" must extend from ${ParentError.name}, but not be ${ParentError.name} itself.`,
)
}
if (!isSubclass(custom, ParentError)) {
throw new TypeError(
`The "custom" class of "${ParentError.name}.subclass()" must extend from ${ParentError.name}.`,
)
}
if (Object.getPrototypeOf(custom) !== ParentError) {
throw new TypeError(
`The "custom" class of "${ParentError.name}.subclass()" must extend directly from ${ParentError.name}.`,
)
}
}
const checkPrototype = (custom, ParentError) => {
if (typeof custom.prototype !== 'object' || custom.prototype === null) {
throw new TypeError(
`The "custom" class's prototype of "${ParentError.name}.subclass()" is invalid: ${custom.prototype}`,
)
}
if (custom.prototype.constructor !== custom) {
throw new TypeError(
`The "custom" class of "${ParentError.name}.subclass()" has an invalid "constructor" property.`,
)
}
}
// check/subclass.js
// Check if `ErrorClass` is a subclass of `ParentClass`.
// We encourage `instanceof` over `error.name` for checking since this:
// - Prevents name collisions with other libraries
// - Allows checking if any error came from a given library
// - Includes error classes in the exported interface explicitly instead of
// implicitly, so that users are mindful about breaking changes
// - Bundles classes with TypeScript documentation, types and autocompletion
// - Encourages documenting error types
// Checking class with `error.name` is still supported, but not documented
// - Since it is widely used and can be better in specific cases
// This also provides with namespacing, i.e. prevents classes of the same name
// but in different libraries to be considered equal. As opposed to the
// following alternatives:
// - Namespacing all error names with a common prefix since this:
// - Leads to verbose error names
// - Requires either an additional option, or guessing ambiguously whether
// error names are meant to include a namespace prefix
// - Using a separate `namespace` property: this adds too much complexity and
// is less standard than `instanceof`
export const isSubclass = (ErrorClass, ParentClass) =>
ParentClass === ErrorClass || isProtoOf.call(ParentClass, ErrorClass)
const { isPrototypeOf: isProtoOf } = Object.prototype
| 2 | 78 | JavaScript |
animation | ./ProjectTest/JavaScript/animation.js | // animation/AnimationAction.js
import { WrapAroundEnding, ZeroCurvatureEnding, ZeroSlopeEnding, LoopPingPong, LoopOnce, LoopRepeat, NormalAnimationBlendMode, AdditiveAnimationBlendMode } from './constants.js';
class AnimationAction {
constructor( mixer, clip, localRoot = null, blendMode = clip.blendMode ) {
this._mixer = mixer;
this._clip = clip;
this._localRoot = localRoot;
this.blendMode = blendMode;
const tracks = clip.tracks,
nTracks = tracks.length,
interpolants = new Array( nTracks );
const interpolantSettings = {
endingStart: ZeroCurvatureEnding,
endingEnd: ZeroCurvatureEnding
};
for ( let i = 0; i !== nTracks; ++ i ) {
const interpolant = tracks[ i ].createInterpolant( null );
interpolants[ i ] = interpolant;
interpolant.settings = interpolantSettings;
}
this._interpolantSettings = interpolantSettings;
this._interpolants = interpolants; // bound by the mixer
// inside: PropertyMixer (managed by the mixer)
this._propertyBindings = new Array( nTracks );
this._cacheIndex = null; // for the memory manager
this._byClipCacheIndex = null; // for the memory manager
this._timeScaleInterpolant = null;
this._weightInterpolant = null;
this.loop = LoopRepeat;
this._loopCount = - 1;
// global mixer time when the action is to be started
// it's set back to 'null' upon start of the action
this._startTime = null;
// scaled local time of the action
// gets clamped or wrapped to 0..clip.duration according to loop
this.time = 0;
this.timeScale = 1;
this._effectiveTimeScale = 1;
this.weight = 1;
this._effectiveWeight = 1;
this.repetitions = Infinity; // no. of repetitions when looping
this.paused = false; // true -> zero effective time scale
this.enabled = true; // false -> zero effective weight
this.clampWhenFinished = false;// keep feeding the last frame?
this.zeroSlopeAtStart = true;// for smooth interpolation w/o separate
this.zeroSlopeAtEnd = true;// clips for start, loop and end
}
// State & Scheduling
play() {
this._mixer._activateAction( this );
return this;
}
stop() {
this._mixer._deactivateAction( this );
return this.reset();
}
reset() {
this.paused = false;
this.enabled = true;
this.time = 0; // restart clip
this._loopCount = - 1;// forget previous loops
this._startTime = null;// forget scheduling
return this.stopFading().stopWarping();
}
isRunning() {
return this.enabled && ! this.paused && this.timeScale !== 0 &&
this._startTime === null && this._mixer._isActiveAction( this );
}
// return true when play has been called
isScheduled() {
return this._mixer._isActiveAction( this );
}
startAt( time ) {
this._startTime = time;
return this;
}
setLoop( mode, repetitions ) {
this.loop = mode;
this.repetitions = repetitions;
return this;
}
// Weight
// set the weight stopping any scheduled fading
// although .enabled = false yields an effective weight of zero, this
// method does *not* change .enabled, because it would be confusing
setEffectiveWeight( weight ) {
this.weight = weight;
// note: same logic as when updated at runtime
this._effectiveWeight = this.enabled ? weight : 0;
return this.stopFading();
}
// return the weight considering fading and .enabled
getEffectiveWeight() {
return this._effectiveWeight;
}
fadeIn( duration ) {
return this._scheduleFading( duration, 0, 1 );
}
fadeOut( duration ) {
return this._scheduleFading( duration, 1, 0 );
}
crossFadeFrom( fadeOutAction, duration, warp ) {
fadeOutAction.fadeOut( duration );
this.fadeIn( duration );
if ( warp ) {
const fadeInDuration = this._clip.duration,
fadeOutDuration = fadeOutAction._clip.duration,
startEndRatio = fadeOutDuration / fadeInDuration,
endStartRatio = fadeInDuration / fadeOutDuration;
fadeOutAction.warp( 1.0, startEndRatio, duration );
this.warp( endStartRatio, 1.0, duration );
}
return this;
}
crossFadeTo( fadeInAction, duration, warp ) {
return fadeInAction.crossFadeFrom( this, duration, warp );
}
stopFading() {
const weightInterpolant = this._weightInterpolant;
if ( weightInterpolant !== null ) {
this._weightInterpolant = null;
this._mixer._takeBackControlInterpolant( weightInterpolant );
}
return this;
}
// Time Scale Control
// set the time scale stopping any scheduled warping
// although .paused = true yields an effective time scale of zero, this
// method does *not* change .paused, because it would be confusing
setEffectiveTimeScale( timeScale ) {
this.timeScale = timeScale;
this._effectiveTimeScale = this.paused ? 0 : timeScale;
return this.stopWarping();
}
// return the time scale considering warping and .paused
getEffectiveTimeScale() {
return this._effectiveTimeScale;
}
setDuration( duration ) {
this.timeScale = this._clip.duration / duration;
return this.stopWarping();
}
syncWith( action ) {
this.time = action.time;
this.timeScale = action.timeScale;
return this.stopWarping();
}
halt( duration ) {
return this.warp( this._effectiveTimeScale, 0, duration );
}
warp( startTimeScale, endTimeScale, duration ) {
const mixer = this._mixer,
now = mixer.time,
timeScale = this.timeScale;
let interpolant = this._timeScaleInterpolant;
if ( interpolant === null ) {
interpolant = mixer._lendControlInterpolant();
this._timeScaleInterpolant = interpolant;
}
const times = interpolant.parameterPositions,
values = interpolant.sampleValues;
times[ 0 ] = now;
times[ 1 ] = now + duration;
values[ 0 ] = startTimeScale / timeScale;
values[ 1 ] = endTimeScale / timeScale;
return this;
}
stopWarping() {
const timeScaleInterpolant = this._timeScaleInterpolant;
if ( timeScaleInterpolant !== null ) {
this._timeScaleInterpolant = null;
this._mixer._takeBackControlInterpolant( timeScaleInterpolant );
}
return this;
}
// Object Accessors
getMixer() {
return this._mixer;
}
getClip() {
return this._clip;
}
getRoot() {
return this._localRoot || this._mixer._root;
}
// Interna
_update( time, deltaTime, timeDirection, accuIndex ) {
// called by the mixer
if ( ! this.enabled ) {
// call ._updateWeight() to update ._effectiveWeight
this._updateWeight( time );
return;
}
const startTime = this._startTime;
if ( startTime !== null ) {
// check for scheduled start of action
const timeRunning = ( time - startTime ) * timeDirection;
if ( timeRunning < 0 || timeDirection === 0 ) {
deltaTime = 0;
} else {
this._startTime = null; // unschedule
deltaTime = timeDirection * timeRunning;
}
}
// apply time scale and advance time
deltaTime *= this._updateTimeScale( time );
const clipTime = this._updateTime( deltaTime );
// note: _updateTime may disable the action resulting in
// an effective weight of 0
const weight = this._updateWeight( time );
if ( weight > 0 ) {
const interpolants = this._interpolants;
const propertyMixers = this._propertyBindings;
switch ( this.blendMode ) {
case AdditiveAnimationBlendMode:
for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
interpolants[ j ].evaluate( clipTime );
propertyMixers[ j ].accumulateAdditive( weight );
}
break;
case NormalAnimationBlendMode:
default:
for ( let j = 0, m = interpolants.length; j !== m; ++ j ) {
interpolants[ j ].evaluate( clipTime );
propertyMixers[ j ].accumulate( accuIndex, weight );
}
}
}
}
_updateWeight( time ) {
let weight = 0;
if ( this.enabled ) {
weight = this.weight;
const interpolant = this._weightInterpolant;
if ( interpolant !== null ) {
const interpolantValue = interpolant.evaluate( time )[ 0 ];
weight *= interpolantValue;
if ( time > interpolant.parameterPositions[ 1 ] ) {
this.stopFading();
if ( interpolantValue === 0 ) {
// faded out, disable
this.enabled = false;
}
}
}
}
this._effectiveWeight = weight;
return weight;
}
_updateTimeScale( time ) {
let timeScale = 0;
if ( ! this.paused ) {
timeScale = this.timeScale;
const interpolant = this._timeScaleInterpolant;
if ( interpolant !== null ) {
const interpolantValue = interpolant.evaluate( time )[ 0 ];
timeScale *= interpolantValue;
if ( time > interpolant.parameterPositions[ 1 ] ) {
this.stopWarping();
if ( timeScale === 0 ) {
// motion has halted, pause
this.paused = true;
} else {
// warp done - apply final time scale
this.timeScale = timeScale;
}
}
}
}
this._effectiveTimeScale = timeScale;
return timeScale;
}
_updateTime( deltaTime ) {
const duration = this._clip.duration;
const loop = this.loop;
let time = this.time + deltaTime;
let loopCount = this._loopCount;
const pingPong = ( loop === LoopPingPong );
if ( deltaTime === 0 ) {
if ( loopCount === - 1 ) return time;
return ( pingPong && ( loopCount & 1 ) === 1 ) ? duration - time : time;
}
if ( loop === LoopOnce ) {
if ( loopCount === - 1 ) {
// just started
this._loopCount = 0;
this._setEndings( true, true, false );
}
handle_stop: {
if ( time >= duration ) {
time = duration;
} else if ( time < 0 ) {
time = 0;
} else {
this.time = time;
break handle_stop;
}
if ( this.clampWhenFinished ) this.paused = true;
else this.enabled = false;
this.time = time;
this._mixer.dispatchEvent( {
type: 'finished', action: this,
direction: deltaTime < 0 ? - 1 : 1
} );
}
} else { // repetitive Repeat or PingPong
if ( loopCount === - 1 ) {
// just started
if ( deltaTime >= 0 ) {
loopCount = 0;
this._setEndings( true, this.repetitions === 0, pingPong );
} else {
// when looping in reverse direction, the initial
// transition through zero counts as a repetition,
// so leave loopCount at -1
this._setEndings( this.repetitions === 0, true, pingPong );
}
}
if ( time >= duration || time < 0 ) {
// wrap around
const loopDelta = Math.floor( time / duration ); // signed
time -= duration * loopDelta;
loopCount += Math.abs( loopDelta );
const pending = this.repetitions - loopCount;
if ( pending <= 0 ) {
// have to stop (switch state, clamp time, fire event)
if ( this.clampWhenFinished ) this.paused = true;
else this.enabled = false;
time = deltaTime > 0 ? duration : 0;
this.time = time;
this._mixer.dispatchEvent( {
type: 'finished', action: this,
direction: deltaTime > 0 ? 1 : - 1
} );
} else {
// keep running
if ( pending === 1 ) {
// entering the last round
const atStart = deltaTime < 0;
this._setEndings( atStart, ! atStart, pingPong );
} else {
this._setEndings( false, false, pingPong );
}
this._loopCount = loopCount;
this.time = time;
this._mixer.dispatchEvent( {
type: 'loop', action: this, loopDelta: loopDelta
} );
}
} else {
this.time = time;
}
if ( pingPong && ( loopCount & 1 ) === 1 ) {
// invert time for the "pong round"
return duration - time;
}
}
return time;
}
_setEndings( atStart, atEnd, pingPong ) {
const settings = this._interpolantSettings;
if ( pingPong ) {
settings.endingStart = ZeroSlopeEnding;
settings.endingEnd = ZeroSlopeEnding;
} else {
// assuming for LoopOnce atStart == atEnd == true
if ( atStart ) {
settings.endingStart = this.zeroSlopeAtStart ? ZeroSlopeEnding : ZeroCurvatureEnding;
} else {
settings.endingStart = WrapAroundEnding;
}
if ( atEnd ) {
settings.endingEnd = this.zeroSlopeAtEnd ? ZeroSlopeEnding : ZeroCurvatureEnding;
} else {
settings.endingEnd = WrapAroundEnding;
}
}
}
_scheduleFading( duration, weightNow, weightThen ) {
const mixer = this._mixer, now = mixer.time;
let interpolant = this._weightInterpolant;
if ( interpolant === null ) {
interpolant = mixer._lendControlInterpolant();
this._weightInterpolant = interpolant;
}
const times = interpolant.parameterPositions,
values = interpolant.sampleValues;
times[ 0 ] = now;
values[ 0 ] = weightNow;
times[ 1 ] = now + duration;
values[ 1 ] = weightThen;
return this;
}
}
export { AnimationAction };
// animation/constants.js
export const REVISION = '172dev';
export const MOUSE = { LEFT: 0, MIDDLE: 1, RIGHT: 2, ROTATE: 0, DOLLY: 1, PAN: 2 };
export const TOUCH = { ROTATE: 0, PAN: 1, DOLLY_PAN: 2, DOLLY_ROTATE: 3 };
export const CullFaceNone = 0;
export const CullFaceBack = 1;
export const CullFaceFront = 2;
export const CullFaceFrontBack = 3;
export const BasicShadowMap = 0;
export const PCFShadowMap = 1;
export const PCFSoftShadowMap = 2;
export const VSMShadowMap = 3;
export const FrontSide = 0;
export const BackSide = 1;
export const DoubleSide = 2;
export const NoBlending = 0;
export const NormalBlending = 1;
export const AdditiveBlending = 2;
export const SubtractiveBlending = 3;
export const MultiplyBlending = 4;
export const CustomBlending = 5;
export const AddEquation = 100;
export const SubtractEquation = 101;
export const ReverseSubtractEquation = 102;
export const MinEquation = 103;
export const MaxEquation = 104;
export const ZeroFactor = 200;
export const OneFactor = 201;
export const SrcColorFactor = 202;
export const OneMinusSrcColorFactor = 203;
export const SrcAlphaFactor = 204;
export const OneMinusSrcAlphaFactor = 205;
export const DstAlphaFactor = 206;
export const OneMinusDstAlphaFactor = 207;
export const DstColorFactor = 208;
export const OneMinusDstColorFactor = 209;
export const SrcAlphaSaturateFactor = 210;
export const ConstantColorFactor = 211;
export const OneMinusConstantColorFactor = 212;
export const ConstantAlphaFactor = 213;
export const OneMinusConstantAlphaFactor = 214;
export const NeverDepth = 0;
export const AlwaysDepth = 1;
export const LessDepth = 2;
export const LessEqualDepth = 3;
export const EqualDepth = 4;
export const GreaterEqualDepth = 5;
export const GreaterDepth = 6;
export const NotEqualDepth = 7;
export const MultiplyOperation = 0;
export const MixOperation = 1;
export const AddOperation = 2;
export const NoToneMapping = 0;
export const LinearToneMapping = 1;
export const ReinhardToneMapping = 2;
export const CineonToneMapping = 3;
export const ACESFilmicToneMapping = 4;
export const CustomToneMapping = 5;
export const AgXToneMapping = 6;
export const NeutralToneMapping = 7;
export const AttachedBindMode = 'attached';
export const DetachedBindMode = 'detached';
export const UVMapping = 300;
export const CubeReflectionMapping = 301;
export const CubeRefractionMapping = 302;
export const EquirectangularReflectionMapping = 303;
export const EquirectangularRefractionMapping = 304;
export const CubeUVReflectionMapping = 306;
export const RepeatWrapping = 1000;
export const ClampToEdgeWrapping = 1001;
export const MirroredRepeatWrapping = 1002;
export const NearestFilter = 1003;
export const NearestMipmapNearestFilter = 1004;
export const NearestMipMapNearestFilter = 1004;
export const NearestMipmapLinearFilter = 1005;
export const NearestMipMapLinearFilter = 1005;
export const LinearFilter = 1006;
export const LinearMipmapNearestFilter = 1007;
export const LinearMipMapNearestFilter = 1007;
export const LinearMipmapLinearFilter = 1008;
export const LinearMipMapLinearFilter = 1008;
export const UnsignedByteType = 1009;
export const ByteType = 1010;
export const ShortType = 1011;
export const UnsignedShortType = 1012;
export const IntType = 1013;
export const UnsignedIntType = 1014;
export const FloatType = 1015;
export const HalfFloatType = 1016;
export const UnsignedShort4444Type = 1017;
export const UnsignedShort5551Type = 1018;
export const UnsignedInt248Type = 1020;
export const UnsignedInt5999Type = 35902;
export const AlphaFormat = 1021;
export const RGBFormat = 1022;
export const RGBAFormat = 1023;
export const LuminanceFormat = 1024;
export const LuminanceAlphaFormat = 1025;
export const DepthFormat = 1026;
export const DepthStencilFormat = 1027;
export const RedFormat = 1028;
export const RedIntegerFormat = 1029;
export const RGFormat = 1030;
export const RGIntegerFormat = 1031;
export const RGBIntegerFormat = 1032;
export const RGBAIntegerFormat = 1033;
export const RGB_S3TC_DXT1_Format = 33776;
export const RGBA_S3TC_DXT1_Format = 33777;
export const RGBA_S3TC_DXT3_Format = 33778;
export const RGBA_S3TC_DXT5_Format = 33779;
export const RGB_PVRTC_4BPPV1_Format = 35840;
export const RGB_PVRTC_2BPPV1_Format = 35841;
export const RGBA_PVRTC_4BPPV1_Format = 35842;
export const RGBA_PVRTC_2BPPV1_Format = 35843;
export const RGB_ETC1_Format = 36196;
export const RGB_ETC2_Format = 37492;
export const RGBA_ETC2_EAC_Format = 37496;
export const RGBA_ASTC_4x4_Format = 37808;
export const RGBA_ASTC_5x4_Format = 37809;
export const RGBA_ASTC_5x5_Format = 37810;
export const RGBA_ASTC_6x5_Format = 37811;
export const RGBA_ASTC_6x6_Format = 37812;
export const RGBA_ASTC_8x5_Format = 37813;
export const RGBA_ASTC_8x6_Format = 37814;
export const RGBA_ASTC_8x8_Format = 37815;
export const RGBA_ASTC_10x5_Format = 37816;
export const RGBA_ASTC_10x6_Format = 37817;
export const RGBA_ASTC_10x8_Format = 37818;
export const RGBA_ASTC_10x10_Format = 37819;
export const RGBA_ASTC_12x10_Format = 37820;
export const RGBA_ASTC_12x12_Format = 37821;
export const RGBA_BPTC_Format = 36492;
export const RGB_BPTC_SIGNED_Format = 36494;
export const RGB_BPTC_UNSIGNED_Format = 36495;
export const RED_RGTC1_Format = 36283;
export const SIGNED_RED_RGTC1_Format = 36284;
export const RED_GREEN_RGTC2_Format = 36285;
export const SIGNED_RED_GREEN_RGTC2_Format = 36286;
export const LoopOnce = 2200;
export const LoopRepeat = 2201;
export const LoopPingPong = 2202;
export const InterpolateDiscrete = 2300;
export const InterpolateLinear = 2301;
export const InterpolateSmooth = 2302;
export const ZeroCurvatureEnding = 2400;
export const ZeroSlopeEnding = 2401;
export const WrapAroundEnding = 2402;
export const NormalAnimationBlendMode = 2500;
export const AdditiveAnimationBlendMode = 2501;
export const TrianglesDrawMode = 0;
export const TriangleStripDrawMode = 1;
export const TriangleFanDrawMode = 2;
export const BasicDepthPacking = 3200;
export const RGBADepthPacking = 3201;
export const RGBDepthPacking = 3202;
export const RGDepthPacking = 3203;
export const TangentSpaceNormalMap = 0;
export const ObjectSpaceNormalMap = 1;
// Color space string identifiers, matching CSS Color Module Level 4 and WebGPU names where available.
export const NoColorSpace = '';
export const SRGBColorSpace = 'srgb';
export const LinearSRGBColorSpace = 'srgb-linear';
export const LinearTransfer = 'linear';
export const SRGBTransfer = 'srgb';
export const ZeroStencilOp = 0;
export const KeepStencilOp = 7680;
export const ReplaceStencilOp = 7681;
export const IncrementStencilOp = 7682;
export const DecrementStencilOp = 7683;
export const IncrementWrapStencilOp = 34055;
export const DecrementWrapStencilOp = 34056;
export const InvertStencilOp = 5386;
export const NeverStencilFunc = 512;
export const LessStencilFunc = 513;
export const EqualStencilFunc = 514;
export const LessEqualStencilFunc = 515;
export const GreaterStencilFunc = 516;
export const NotEqualStencilFunc = 517;
export const GreaterEqualStencilFunc = 518;
export const AlwaysStencilFunc = 519;
export const NeverCompare = 512;
export const LessCompare = 513;
export const EqualCompare = 514;
export const LessEqualCompare = 515;
export const GreaterCompare = 516;
export const NotEqualCompare = 517;
export const GreaterEqualCompare = 518;
export const AlwaysCompare = 519;
export const StaticDrawUsage = 35044;
export const DynamicDrawUsage = 35048;
export const StreamDrawUsage = 35040;
export const StaticReadUsage = 35045;
export const DynamicReadUsage = 35049;
export const StreamReadUsage = 35041;
export const StaticCopyUsage = 35046;
export const DynamicCopyUsage = 35050;
export const StreamCopyUsage = 35042;
export const GLSL1 = '100';
export const GLSL3 = '300 es';
export const WebGLCoordinateSystem = 2000;
export const WebGPUCoordinateSystem = 2001;
| 2 | 911 | JavaScript |
controls | ./ProjectTest/JavaScript/controls.js | // controls/Controls.js
import { EventDispatcher } from './EventDispatcher.js';
class Controls extends EventDispatcher {
constructor( object, domElement = null ) {
super();
this.object = object;
this.domElement = domElement;
this.enabled = true;
this.state = - 1;
this.keys = {};
this.mouseButtons = { LEFT: null, MIDDLE: null, RIGHT: null };
this.touches = { ONE: null, TWO: null };
}
connect() {}
disconnect() {}
dispose() {}
update( /* delta */ ) {}
}
export { Controls };
// controls/EventDispatcher.js
/**
* https://github.com/mrdoob/eventdispatcher.js/
*/
class EventDispatcher {
addEventListener( type, listener ) {
if ( this._listeners === undefined ) this._listeners = {};
const listeners = this._listeners;
if ( listeners[ type ] === undefined ) {
listeners[ type ] = [];
}
if ( listeners[ type ].indexOf( listener ) === - 1 ) {
listeners[ type ].push( listener );
}
}
hasEventListener( type, listener ) {
if ( this._listeners === undefined ) return false;
const listeners = this._listeners;
return listeners[ type ] !== undefined && listeners[ type ].indexOf( listener ) !== - 1;
}
removeEventListener( type, listener ) {
if ( this._listeners === undefined ) return;
const listeners = this._listeners;
const listenerArray = listeners[ type ];
if ( listenerArray !== undefined ) {
const index = listenerArray.indexOf( listener );
if ( index !== - 1 ) {
listenerArray.splice( index, 1 );
}
}
}
dispatchEvent( event ) {
if ( this._listeners === undefined ) return;
const listeners = this._listeners;
const listenerArray = listeners[ event.type ];
if ( listenerArray !== undefined ) {
event.target = this;
// Make a copy, in case listeners are removed while iterating.
const array = listenerArray.slice( 0 );
for ( let i = 0, l = array.length; i < l; i ++ ) {
array[ i ].call( this, event );
}
event.target = null;
}
}
}
export { EventDispatcher };
| 2 | 119 | JavaScript |
particle | ./ProjectTest/JavaScript/particle.js | // particle/Particle.js
var Shape = require('./Shape')
, shallowClone = require('./Utils').shallowClone
, copy = require('./vec2').copy;
module.exports = Particle;
/**
* Particle shape class.
* @class Particle
* @constructor
* @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
* @extends Shape
* @example
* var body = new Body();
* var shape = new Particle();
* body.addShape(shape);
*/
function Particle(options){
options = options ? shallowClone(options) : {};
options.type = Shape.PARTICLE;
Shape.call(this, options);
}
Particle.prototype = new Shape();
Particle.prototype.constructor = Particle;
Particle.prototype.computeMomentOfInertia = function(){
return 0; // Can't rotate a particle
};
Particle.prototype.updateBoundingRadius = function(){
this.boundingRadius = 0;
};
/**
* @method computeAABB
* @param {AABB} out
* @param {Array} position
* @param {Number} angle
*/
Particle.prototype.computeAABB = function(out, position/*, angle*/){
copy(out.lowerBound, position);
copy(out.upperBound, position);
};
// particle/vec2.js
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
* @class vec2
*/
var vec2 = module.exports = {};
var Utils = require('./Utils');
/**
* Make a cross product and only return the z component
* @method crossLength
* @static
* @param {Array} a
* @param {Array} b
* @return {Number}
*/
vec2.crossLength = function(a,b){
return a[0] * b[1] - a[1] * b[0];
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossVZ
* @static
* @param {Array} out
* @param {Array} vec
* @param {Number} zcomp
* @return {Array}
*/
vec2.crossVZ = function(out, vec, zcomp){
vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossZV
* @static
* @param {Array} out
* @param {Number} zcomp
* @param {Array} vec
* @return {Array}
*/
vec2.crossZV = function(out, zcomp, vec){
vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Rotate a vector by an angle
* @method rotate
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate = function(out,a,angle){
if(angle !== 0){
var c = Math.cos(angle),
s = Math.sin(angle),
x = a[0],
y = a[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
} else {
out[0] = a[0];
out[1] = a[1];
}
return out;
};
/**
* Rotate a vector 90 degrees clockwise
* @method rotate90cw
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate90cw = function(out, a) {
var x = a[0];
var y = a[1];
out[0] = y;
out[1] = -x;
return out;
};
/**
* Transform a point position to local frame.
* @method toLocalFrame
* @param {Array} out
* @param {Array} worldPoint
* @param {Array} framePosition
* @param {Number} frameAngle
* @return {Array}
*/
vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldPoint[0] - framePosition[0],
y = worldPoint[1] - framePosition[1];
out[0] = c * x - s * y;
out[1] = s * x + c * y;
return out;
};
/**
* Transform a point position to global frame.
* @method toGlobalFrame
* @param {Array} out
* @param {Array} localPoint
* @param {Array} framePosition
* @param {Number} frameAngle
*/
vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
var c = Math.cos(frameAngle),
s = Math.sin(frameAngle),
x = localPoint[0],
y = localPoint[1],
addX = framePosition[0],
addY = framePosition[1];
out[0] = c * x - s * y + addX;
out[1] = s * x + c * y + addY;
};
/**
* Transform a vector to local frame.
* @method vectorToLocalFrame
* @param {Array} out
* @param {Array} worldVector
* @param {Number} frameAngle
* @return {Array}
*/
vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldVector[0],
y = worldVector[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
return out;
};
/**
* Transform a vector to global frame.
* @method vectorToGlobalFrame
* @param {Array} out
* @param {Array} localVector
* @param {Number} frameAngle
*/
vec2.vectorToGlobalFrame = vec2.rotate;
/**
* Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
* @method centroid
* @static
* @param {Array} out
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Array} The "out" vector.
*/
vec2.centroid = function(out, a, b, c){
vec2.add(out, a, b);
vec2.add(out, out, c);
vec2.scale(out, out, 1/3);
return out;
};
/**
* Creates a new, empty vec2
* @static
* @method create
* @return {Array} a new 2D vector
*/
vec2.create = function() {
var out = new Utils.ARRAY_TYPE(2);
out[0] = 0;
out[1] = 0;
return out;
};
/**
* Creates a new vec2 initialized with values from an existing vector
* @static
* @method clone
* @param {Array} a vector to clone
* @return {Array} a new 2D vector
*/
vec2.clone = function(a) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Creates a new vec2 initialized with the given values
* @static
* @method fromValues
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} a new 2D vector
*/
vec2.fromValues = function(x, y) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = x;
out[1] = y;
return out;
};
/**
* Copy the values from one vec2 to another
* @static
* @method copy
* @param {Array} out the receiving vector
* @param {Array} a the source vector
* @return {Array} out
*/
vec2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Set the components of a vec2 to the given values
* @static
* @method set
* @param {Array} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} out
*/
vec2.set = function(out, x, y) {
out[0] = x;
out[1] = y;
return out;
};
/**
* Adds two vec2's
* @static
* @method add
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
};
/**
* Subtracts two vec2's
* @static
* @method subtract
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
};
/**
* Multiplies two vec2's
* @static
* @method multiply
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
};
/**
* Divides two vec2's
* @static
* @method divide
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
};
/**
* Scales a vec2 by a scalar number
* @static
* @method scale
* @param {Array} out the receiving vector
* @param {Array} a the vector to scale
* @param {Number} b amount to scale the vector by
* @return {Array} out
*/
vec2.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
};
/**
* Calculates the euclidian distance between two vec2's
* @static
* @method distance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} distance between a and b
*/
vec2.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared euclidian distance between two vec2's
* @static
* @method squaredDistance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} squared distance between a and b
*/
vec2.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x*x + y*y;
};
/**
* Calculates the length of a vec2
* @static
* @method length
* @param {Array} a vector to calculate length of
* @return {Number} length of a
*/
vec2.length = function (a) {
var x = a[0],
y = a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared length of a vec2
* @static
* @method squaredLength
* @param {Array} a vector to calculate squared length of
* @return {Number} squared length of a
*/
vec2.squaredLength = function (a) {
var x = a[0],
y = a[1];
return x*x + y*y;
};
/**
* Negates the components of a vec2
* @static
* @method negate
* @param {Array} out the receiving vector
* @param {Array} a vector to negate
* @return {Array} out
*/
vec2.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
};
/**
* Normalize a vec2
* @static
* @method normalize
* @param {Array} out the receiving vector
* @param {Array} a vector to normalize
* @return {Array} out
*/
vec2.normalize = function(out, a) {
var x = a[0],
y = a[1];
var len = x*x + y*y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
};
/**
* Calculates the dot product of two vec2's
* @static
* @method dot
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} dot product of a and b
*/
vec2.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/**
* Returns a string representation of a vector
* @static
* @method str
* @param {Array} vec vector to represent as a string
* @return {String} string representation of the vector
*/
vec2.str = function (a) {
return 'vec2(' + a[0] + ', ' + a[1] + ')';
};
/**
* Linearly interpolate/mix two vectors.
* @static
* @method lerp
* @param {Array} out
* @param {Array} a First vector
* @param {Array} b Second vector
* @param {number} t Lerp factor
*/
vec2.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
};
/**
* Reflect a vector along a normal.
* @static
* @method reflect
* @param {Array} out
* @param {Array} vector
* @param {Array} normal
*/
vec2.reflect = function(out, vector, normal){
var dot = vector[0] * normal[0] + vector[1] * normal[1];
out[0] = vector[0] - 2 * normal[0] * dot;
out[1] = vector[1] - 2 * normal[1] * dot;
};
/**
* Get the intersection point between two line segments.
* @static
* @method getLineSegmentsIntersection
* @param {Array} out
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {boolean} True if there was an intersection, otherwise false.
*/
vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) {
var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3);
if(t < 0){
return false;
} else {
out[0] = p0[0] + (t * (p1[0] - p0[0]));
out[1] = p0[1] + (t * (p1[1] - p0[1]));
return true;
}
};
/**
* Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
* @static
* @method getLineSegmentsIntersectionFraction
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
*/
vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) {
var s1_x = p1[0] - p0[0];
var s1_y = p1[1] - p0[1];
var s2_x = p3[0] - p2[0];
var s2_y = p3[1] - p2[1];
var s, t;
s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
return t;
}
return -1; // No collision
};
// particle/Utils.js
/* global P2_ARRAY_TYPE */
module.exports = Utils;
/**
* Misc utility functions
* @class Utils
* @constructor
*/
function Utils(){}
/**
* Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
* @method appendArray
* @static
* @param {Array} a
* @param {Array} b
*/
Utils.appendArray = function(a,b){
if (b.length < 150000) {
a.push.apply(a, b);
} else {
for (var i = 0, len = b.length; i !== len; ++i) {
a.push(b[i]);
}
}
};
/**
* Garbage free Array.splice(). Does not allocate a new array.
* @method splice
* @static
* @param {Array} array
* @param {Number} index
* @param {Number} howmany
*/
Utils.splice = function(array,index,howmany){
howmany = howmany || 1;
for (var i=index, len=array.length-howmany; i < len; i++){
array[i] = array[i + howmany];
}
array.length = len;
};
/**
* Remove an element from an array, if the array contains the element.
* @method arrayRemove
* @static
* @param {Array} array
* @param {Number} element
*/
Utils.arrayRemove = function(array, element){
var idx = array.indexOf(element);
if(idx!==-1){
Utils.splice(array, idx, 1);
}
};
/**
* The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
* @static
* @property {function} ARRAY_TYPE
* @example
* <script>
* <!-- Inject your preferred array type before loading p2.js -->
* P2_ARRAY_TYPE = Array;
* </script>
* <script src="p2.js"></script>
*/
if(typeof P2_ARRAY_TYPE !== 'undefined') {
Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
} else if (typeof Float32Array !== 'undefined'){
Utils.ARRAY_TYPE = Float32Array;
} else {
Utils.ARRAY_TYPE = Array;
}
/**
* Extend an object with the properties of another
* @static
* @method extend
* @param {object} a
* @param {object} b
*/
Utils.extend = function(a,b){
for(var key in b){
a[key] = b[key];
}
};
/**
* Shallow clone an object. Returns a new object instance with the same properties as the input instance.
* @static
* @method shallowClone
* @param {object} obj
*/
Utils.shallowClone = function(obj){
var newObj = {};
Utils.extend(newObj, obj);
return newObj;
};
/**
* Extend an options object with default values.
* @deprecated Not used internally, will be removed.
* @static
* @method defaults
* @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
* @param {object} defaults An object containing default values.
* @return {object} The modified options object.
*/
Utils.defaults = function(options, defaults){
console.warn('Utils.defaults is deprecated.');
options = options || {};
for(var key in defaults){
if(!(key in options)){
options[key] = defaults[key];
}
}
return options;
};
// particle/Shape.js
module.exports = Shape;
var vec2 = require('./vec2');
/**
* Base class for shapes. Not to be used directly.
* @class Shape
* @constructor
* @param {object} [options]
* @param {number} [options.angle=0]
* @param {number} [options.collisionGroup=1]
* @param {number} [options.collisionMask=1]
* @param {boolean} [options.collisionResponse=true]
* @param {Material} [options.material=null]
* @param {array} [options.position]
* @param {boolean} [options.sensor=false]
* @param {object} [options.type=0]
*/
function Shape(options){
options = options || {};
/**
* The body this shape is attached to. A shape can only be attached to a single body.
* @property {Body} body
*/
this.body = null;
/**
* Body-local position of the shape.
* @property {Array} position
*/
this.position = vec2.create();
if(options.position){
vec2.copy(this.position, options.position);
}
/**
* Body-local angle of the shape.
* @property {number} angle
*/
this.angle = options.angle || 0;
/**
* The type of the shape. One of:
*
* <ul>
* <li><a href="Shape.html#property_CIRCLE">Shape.CIRCLE</a></li>
* <li><a href="Shape.html#property_PARTICLE">Shape.PARTICLE</a></li>
* <li><a href="Shape.html#property_PLANE">Shape.PLANE</a></li>
* <li><a href="Shape.html#property_CONVEX">Shape.CONVEX</a></li>
* <li><a href="Shape.html#property_LINE">Shape.LINE</a></li>
* <li><a href="Shape.html#property_BOX">Shape.BOX</a></li>
* <li><a href="Shape.html#property_CAPSULE">Shape.CAPSULE</a></li>
* <li><a href="Shape.html#property_HEIGHTFIELD">Shape.HEIGHTFIELD</a></li>
* </ul>
*
* @property {number} type
*/
this.type = options.type || 0;
/**
* Shape object identifier. Read only.
* @readonly
* @type {Number}
* @property id
*/
this.id = Shape.idCounter++;
/**
* Bounding circle radius of this shape
* @readonly
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
/**
* Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
* @property collisionGroup
* @type {Number}
* @example
* // Setup bits for each available group
* var PLAYER = Math.pow(2,0),
* ENEMY = Math.pow(2,1),
* GROUND = Math.pow(2,2)
*
* // Put shapes into their groups
* player1Shape.collisionGroup = PLAYER;
* player2Shape.collisionGroup = PLAYER;
* enemyShape .collisionGroup = ENEMY;
* groundShape .collisionGroup = GROUND;
*
* // Assign groups that each shape collide with.
* // Note that the players can collide with ground and enemies, but not with other players.
* player1Shape.collisionMask = ENEMY | GROUND;
* player2Shape.collisionMask = ENEMY | GROUND;
* enemyShape .collisionMask = PLAYER | GROUND;
* groundShape .collisionMask = PLAYER | ENEMY;
*
* @example
* // How collision check is done
* if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
* // The shapes will collide
* }
*/
this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
* @property {Boolean} collisionResponse
*/
this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
/**
* Collision mask of this shape. See .collisionGroup.
* @property collisionMask
* @type {Number}
*/
this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
/**
* Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
* @property material
* @type {Material}
*/
this.material = options.material || null;
/**
* Area of this shape.
* @property area
* @type {Number}
*/
this.area = 0;
/**
* Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
* @property {Boolean} sensor
*/
this.sensor = options.sensor !== undefined ? options.sensor : false;
if(this.type){
this.updateBoundingRadius();
}
this.updateArea();
}
Shape.idCounter = 0;
/**
* @static
* @property {Number} CIRCLE
*/
Shape.CIRCLE = 1;
/**
* @static
* @property {Number} PARTICLE
*/
Shape.PARTICLE = 2;
/**
* @static
* @property {Number} PLANE
*/
Shape.PLANE = 4;
/**
* @static
* @property {Number} CONVEX
*/
Shape.CONVEX = 8;
/**
* @static
* @property {Number} LINE
*/
Shape.LINE = 16;
/**
* @static
* @property {Number} BOX
*/
Shape.BOX = 32;
/**
* @static
* @property {Number} CAPSULE
*/
Shape.CAPSULE = 64;
/**
* @static
* @property {Number} HEIGHTFIELD
*/
Shape.HEIGHTFIELD = 128;
Shape.prototype = {
/**
* Should return the moment of inertia around the Z axis of the body. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
* @method computeMomentOfInertia
* @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
*/
computeMomentOfInertia: function(){},
/**
* Returns the bounding circle radius of this shape.
* @method updateBoundingRadius
* @return {Number}
*/
updateBoundingRadius: function(){},
/**
* Update the .area property of the shape.
* @method updateArea
*/
updateArea: function(){},
/**
* Compute the world axis-aligned bounding box (AABB) of this shape.
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position World position of the shape.
* @param {Number} angle World angle of the shape.
*/
computeAABB: function(/*out, position, angle*/){
// To be implemented in each subclass
},
/**
* Perform raycasting on this shape.
* @method raycast
* @param {RayResult} result Where to store the resulting data.
* @param {Ray} ray The Ray that you want to use for raycasting.
* @param {array} position World position of the shape (the .position property will be ignored).
* @param {number} angle World angle of the shape (the .angle property will be ignored).
*/
raycast: function(/*result, ray, position, angle*/){
// To be implemented in each subclass
},
/**
* Test if a point is inside this shape.
* @method pointTest
* @param {array} localPoint
* @return {boolean}
*/
pointTest: function(/*localPoint*/){ return false; },
/**
* Transform a world point to local shape space (assumed the shape is transformed by both itself and the body).
* @method worldPointToLocal
* @param {array} out
* @param {array} worldPoint
*/
worldPointToLocal: (function () {
var shapeWorldPosition = vec2.create();
return function (out, worldPoint) {
var body = this.body;
vec2.rotate(shapeWorldPosition, this.position, body.angle);
vec2.add(shapeWorldPosition, shapeWorldPosition, body.position);
vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle);
};
})()
};
| 4 | 963 | JavaScript |
zone | ./ProjectTest/JavaScript/zone.js | // zone/MathUtil.js
const PI = 3.1415926;
const INFINITY = Infinity;
const MathUtil = {
PI: PI,
PIx2: PI * 2,
PI_2: PI / 2,
PI_180: PI / 180,
N180_PI: 180 / PI,
Infinity: -999,
isInfinity(num) {
return num === this.Infinity || num === INFINITY;
},
randomAToB(a, b, isInt = false) {
if (!isInt) return a + Math.random() * (b - a);
else return ((Math.random() * (b - a)) >> 0) + a;
},
randomFloating(center, f, isInt) {
return this.randomAToB(center - f, center + f, isInt);
},
randomColor() {
return "#" + ("00000" + ((Math.random() * 0x1000000) << 0).toString(16)).slice(-6);
},
randomZone(display) {},
floor(num, k = 4) {
const digits = Math.pow(10, k);
return Math.floor(num * digits) / digits;
},
degreeTransform(a) {
return (a * PI) / 180;
},
toColor16(num) {
return `#${num.toString(16)}`;
}
};
export default MathUtil;
// zone/Vector2D.js
import MathUtil from "./MathUtil";
export default class Vector2D {
constructor(x, y) {
this.x = x || 0;
this.y = y || 0;
}
set(x, y) {
this.x = x;
this.y = y;
return this;
}
setX(x) {
this.x = x;
return this;
}
setY(y) {
this.y = y;
return this;
}
getGradient() {
if (this.x !== 0) return Math.atan2(this.y, this.x);
else if (this.y > 0) return MathUtil.PI_2;
else if (this.y < 0) return -MathUtil.PI_2;
}
copy(v) {
this.x = v.x;
this.y = v.y;
return this;
}
add(v, w) {
if (w !== undefined) {
return this.addVectors(v, w);
}
this.x += v.x;
this.y += v.y;
return this;
}
addXY(a, b) {
this.x += a;
this.y += b;
return this;
}
addVectors(a, b) {
this.x = a.x + b.x;
this.y = a.y + b.y;
return this;
}
sub(v, w) {
if (w !== undefined) {
return this.subVectors(v, w);
}
this.x -= v.x;
this.y -= v.y;
return this;
}
subVectors(a, b) {
this.x = a.x - b.x;
this.y = a.y - b.y;
return this;
}
divideScalar(s) {
if (s !== 0) {
this.x /= s;
this.y /= s;
} else {
this.set(0, 0);
}
return this;
}
multiplyScalar(s) {
this.x *= s;
this.y *= s;
return this;
}
negate() {
return this.multiplyScalar(-1);
}
dot(v) {
return this.x * v.x + this.y * v.y;
}
lengthSq() {
return this.x * this.x + this.y * this.y;
}
length() {
return Math.sqrt(this.x * this.x + this.y * this.y);
}
normalize() {
return this.divideScalar(this.length());
}
distanceTo(v) {
return Math.sqrt(this.distanceToSquared(v));
}
rotate(tha) {
const x = this.x;
const y = this.y;
this.x = x * Math.cos(tha) + y * Math.sin(tha);
this.y = -x * Math.sin(tha) + y * Math.cos(tha);
return this;
}
distanceToSquared(v) {
const dx = this.x - v.x;
const dy = this.y - v.y;
return dx * dx + dy * dy;
}
lerp(v, alpha) {
this.x += (v.x - this.x) * alpha;
this.y += (v.y - this.y) * alpha;
return this;
}
equals(v) {
return v.x === this.x && v.y === this.y;
}
clear() {
this.x = 0.0;
this.y = 0.0;
return this;
}
clone() {
return new Vector2D(this.x, this.y);
}
}
// zone/Zone.js
import Vector2D from "./Vector2D";
export default class Zone {
constructor() {
this.vector = new Vector2D(0, 0);
this.random = 0;
this.crossType = "dead";
this.alert = true;
}
getPosition() {}
crossing(particle) {}
destroy() {
this.vector = null;
}
}
| 3 | 223 | JavaScript |
magnetic | ./ProjectTest/JavaScript/magnetic.js | // magnetic/BezierEasing.js
/**
* @author pschroen / https://ufo.ai/
*
* Based on https://github.com/gre/bezier-easing
*/
// These values are established by empiricism with tests (tradeoff: performance VS precision)
const NEWTON_ITERATIONS = 4;
const NEWTON_MIN_SLOPE = 0.001;
const SUBDIVISION_PRECISION = 0.0000001;
const SUBDIVISION_MAX_ITERATIONS = 10;
const kSplineTableSize = 11;
const kSampleStepSize = 1 / (kSplineTableSize - 1);
function A(aA1, aA2) {
return 1 - 3 * aA2 + 3 * aA1;
}
function B(aA1, aA2) {
return 3 * aA2 - 6 * aA1;
}
function C(aA1) {
return 3 * aA1;
}
// Returns x(t) given t, x1, and x2, or y(t) given t, y1, and y2
function calcBezier(aT, aA1, aA2) {
return ((A(aA1, aA2) * aT + B(aA1, aA2)) * aT + C(aA1)) * aT;
}
// Returns dx/dt given t, x1, and x2, or dy/dt given t, y1, and y2
function getSlope(aT, aA1, aA2) {
return 3 * A(aA1, aA2) * aT * aT + 2 * B(aA1, aA2) * aT + C(aA1);
}
function binarySubdivide(aX, aA, aB, mX1, mX2) {
let currentX;
let currentT;
let i = 0;
do {
currentT = aA + (aB - aA) / 2;
currentX = calcBezier(currentT, mX1, mX2) - aX;
if (currentX > 0) {
aB = currentT;
} else {
aA = currentT;
}
} while (Math.abs(currentX) > SUBDIVISION_PRECISION && ++i < SUBDIVISION_MAX_ITERATIONS);
return currentT;
}
function newtonRaphsonIterate(aX, aGuessT, mX1, mX2) {
for (let i = 0; i < NEWTON_ITERATIONS; i++) {
const currentSlope = getSlope(aGuessT, mX1, mX2);
if (currentSlope === 0) {
return aGuessT;
}
const currentX = calcBezier(aGuessT, mX1, mX2) - aX;
aGuessT -= currentX / currentSlope;
}
return aGuessT;
}
function LinearEasing(x) {
return x;
}
export default function bezier(mX1, mY1, mX2, mY2) {
if (!(0 <= mX1 && mX1 <= 1 && 0 <= mX2 && mX2 <= 1)) {
throw new Error('Bezier x values must be in [0, 1] range');
}
if (mX1 === mY1 && mX2 === mY2) {
return LinearEasing;
}
// Precompute samples table
const sampleValues = new Float32Array(kSplineTableSize);
for (let i = 0; i < kSplineTableSize; i++) {
sampleValues[i] = calcBezier(i * kSampleStepSize, mX1, mX2);
}
function getTForX(aX) {
let intervalStart = 0;
let currentSample = 1;
const lastSample = kSplineTableSize - 1;
for (; currentSample !== lastSample && sampleValues[currentSample] <= aX; currentSample++) {
intervalStart += kSampleStepSize;
}
currentSample--;
// Interpolate to provide an initial guess for t
const dist = (aX - sampleValues[currentSample]) / (sampleValues[currentSample + 1] - sampleValues[currentSample]);
const guessForT = intervalStart + dist * kSampleStepSize;
const initialSlope = getSlope(guessForT, mX1, mX2);
if (initialSlope >= NEWTON_MIN_SLOPE) {
return newtonRaphsonIterate(aX, guessForT, mX1, mX2);
} else if (initialSlope === 0) {
return guessForT;
} else {
return binarySubdivide(aX, intervalStart, intervalStart + kSampleStepSize, mX1, mX2);
}
}
return function BezierEasing(x) {
// Because JavaScript numbers are imprecise, we should guarantee the extremes are right
if (x === 0 || x === 1) {
return x;
}
return calcBezier(getTForX(x), mY1, mY2);
};
}
// magnetic/EventEmitter.js
/**
* @author pschroen / https://ufo.ai/
*
* Based on https://developer.mozilla.org/en-US/docs/Web/API/EventTarget#simple_implementation_of_eventtarget
*/
/**
* A simple implementation of EventTarget with event parameter spread.
*/
export class EventEmitter {
constructor() {
this.callbacks = {};
}
on(type, callback) {
if (!this.callbacks[type]) {
this.callbacks[type] = [];
}
this.callbacks[type].push(callback);
}
off(type, callback) {
if (!this.callbacks[type]) {
return;
}
if (callback) {
const index = this.callbacks[type].indexOf(callback);
if (~index) {
this.callbacks[type].splice(index, 1);
}
} else {
delete this.callbacks[type];
}
}
emit(type, ...event) {
if (!this.callbacks[type]) {
return;
}
const stack = this.callbacks[type].slice();
for (let i = 0, l = stack.length; i < l; i++) {
stack[i].call(this, ...event);
}
}
destroy() {
for (const prop in this) {
this[prop] = null;
}
return null;
}
}
// magnetic/Tween.js
/**
* @author pschroen / https://ufo.ai/
*/
import { Easing } from './Easing.js';
import { ticker } from './Ticker.js';
const Tweens = [];
/**
* Tween animation engine.
* @see {@link https://github.com/alienkitty/alien.js/wiki/Tween | Documentation}
* @see {@link https://easings.net/ | Easing Functions Cheat Sheet}
* @example
* ticker.start();
*
* const data = {
* radius: 0
* };
*
* tween(data, { radius: 24, spring: 1.2, damping: 0.4 }, 1000, 'easeOutElastic', null, () => {
* console.log(data.radius);
* });
*/
export class Tween {
constructor(object, props, duration, ease, delay = 0, complete, update) {
if (typeof delay !== 'number') {
update = complete;
complete = delay;
delay = 0;
}
this.object = object;
this.duration = duration;
this.elapsed = 0;
this.ease = typeof ease === 'function' ? ease : Easing[ease] || Easing['easeOutCubic'];
this.delay = delay;
this.complete = complete;
this.update = update;
this.isAnimating = false;
this.from = {};
this.to = Object.assign({}, props);
this.spring = this.to.spring;
this.damping = this.to.damping;
delete this.to.spring;
delete this.to.damping;
for (const prop in this.to) {
if (typeof this.to[prop] === 'number' && typeof object[prop] === 'number') {
this.from[prop] = object[prop];
}
}
this.start();
}
// Event handlers
onUpdate = (time, delta) => {
this.elapsed += delta;
const progress = Math.max(0, Math.min(1, (this.elapsed - this.delay) / this.duration));
const alpha = this.ease(progress, this.spring, this.damping);
for (const prop in this.from) {
this.object[prop] = this.from[prop] + (this.to[prop] - this.from[prop]) * alpha;
}
if (this.update) {
this.update();
}
if (progress === 1) {
clearTween(this);
if (this.complete) {
this.complete();
}
}
};
// Public methods
start() {
if (this.isAnimating) {
return;
}
this.isAnimating = true;
ticker.add(this.onUpdate);
}
stop() {
if (!this.isAnimating) {
return;
}
this.isAnimating = false;
ticker.remove(this.onUpdate);
}
}
/**
* Defers a function by the given duration.
* @param {number} duration Time to wait in milliseconds.
* @param {function} complete Callback function.
* @returns {Tween}
* @example
* delayedCall(500, animateIn);
* @example
* delayedCall(500, () => animateIn(delay));
* @example
* timeout = delayedCall(500, () => animateIn(delay));
*/
export function delayedCall(duration, complete) {
const tween = new Tween(complete, null, duration, 'linear', 0, complete);
Tweens.push(tween);
return tween;
}
/**
* Defers by the given duration.
* @param {number} [duration=0] Time to wait in milliseconds.
* @returns {Promise}
* @example
* await wait(250);
*/
export function wait(duration = 0) {
return new Promise(resolve => delayedCall(duration, resolve));
}
/**
* Defers to the next tick.
* @param {function} [complete] Callback function.
* @returns {Promise}
* @example
* defer(resize);
* @example
* defer(() => resize());
* @example
* await defer();
*/
export function defer(complete) {
const promise = new Promise(resolve => delayedCall(0, resolve));
if (complete) {
promise.then(complete);
}
return promise;
}
/**
* Tween that animates to the given destination properties.
* @see {@link https://easings.net/ | Easing Functions Cheat Sheet}
* @param {object} object Target object.
* @param {object} props Tween properties.
* @param {number} duration Time in milliseconds.
* @param {string|function} ease Ease string or function.
* @param {number} [delay=0] Time to wait in milliseconds.
* @param {function} [complete] Callback function when the animation has completed.
* @param {function} [update] Callback function every time the animation updates.
* @returns {Promise}
* @example
* tween(data, { value: 0.3 }, 1000, 'linear');
*/
export function tween(object, props, duration, ease, delay = 0, complete, update) {
if (typeof delay !== 'number') {
update = complete;
complete = delay;
delay = 0;
}
const promise = new Promise(resolve => {
const tween = new Tween(object, props, duration, ease, delay, resolve, update);
Tweens.push(tween);
});
if (complete) {
promise.then(complete);
}
return promise;
}
/**
* Immediately clears all delayedCalls and tweens of a given object.
* @param {object} object Target object.
* @returns {void}
* @example
* delayedCall(500, animateIn);
* clearTween(animateIn);
* @example
* clearTween(timeout);
* timeout = delayedCall(500, () => animateIn());
* @example
* tween(data, { value: 0.3 }, 1000, 'linear');
* clearTween(data);
*/
export function clearTween(object) {
if (object instanceof Tween) {
object.stop();
const index = Tweens.indexOf(object);
if (~index) {
Tweens.splice(index, 1);
}
} else {
for (let i = Tweens.length - 1; i >= 0; i--) {
if (Tweens[i].object === object) {
clearTween(Tweens[i]);
}
}
}
}
// magnetic/Component.js
/**
* @author pschroen / https://ufo.ai/
*/
import { EventEmitter } from './EventEmitter.js';
import { ticker } from './Ticker.js';
import { clearTween, tween } from './Tween.js';
/**
* A base class for components with tween and destroy methods.
*/
export class Component {
constructor() {
this.events = new EventEmitter();
this.children = [];
}
add(child) {
if (!this.children) {
return;
}
this.children.push(child);
child.parent = this;
return child;
}
remove(child) {
if (!this.children) {
return;
}
const index = this.children.indexOf(child);
if (~index) {
this.children.splice(index, 1);
}
}
tween(props, duration, ease, delay, complete, update) {
if (!ticker.isAnimating) {
ticker.start();
}
return tween(this, props, duration, ease, delay, complete, update);
}
clearTween() {
clearTween(this);
return this;
}
destroy() {
if (!this.children) {
return;
}
if (this.parent && this.parent.remove) {
this.parent.remove(this);
}
this.clearTween();
this.events.destroy();
for (let i = this.children.length - 1; i >= 0; i--) {
if (this.children[i] && this.children[i].destroy) {
this.children[i].destroy();
}
}
for (const prop in this) {
this[prop] = null;
}
return null;
}
}
// magnetic/Ticker.js
/**
* @author pschroen / https://ufo.ai/
*/
var RequestFrame;
var CancelFrame;
if (typeof window !== 'undefined') {
RequestFrame = window.requestAnimationFrame;
CancelFrame = window.cancelAnimationFrame;
} else {
const startTime = performance.now();
const timestep = 1000 / 60;
RequestFrame = callback => {
return setTimeout(() => {
callback(performance.now() - startTime);
}, timestep);
};
CancelFrame = clearTimeout;
}
/**
* A minimal requestAnimationFrame render loop with worker support.
* @example
* ticker.add(onUpdate);
* ticker.start();
*
* function onUpdate(time, delta, frame) {
* console.log(time, delta, frame);
* }
*
* setTimeout(() => {
* ticker.remove(onUpdate);
* }, 1000);
*/
export class Ticker {
constructor() {
this.callbacks = [];
this.last = performance.now();
this.time = 0;
this.delta = 0;
this.frame = 0;
this.isAnimating = false;
}
// Event handlers
onTick = time => {
if (this.isAnimating) {
this.requestId = RequestFrame(this.onTick);
}
this.delta = time - this.last;
this.last = time;
this.time = time * 0.001; // seconds
this.frame++;
for (let i = this.callbacks.length - 1; i >= 0; i--) {
const callback = this.callbacks[i];
if (!callback) {
continue;
}
if (callback.fps) {
const delta = time - callback.last;
if (delta < 1000 / callback.fps) {
continue;
}
callback.last = time;
callback.frame++;
callback(this.time, delta, callback.frame);
continue;
}
callback(this.time, this.delta, this.frame);
}
};
// Public methods
add(callback, fps) {
if (fps) {
callback.fps = fps;
callback.last = performance.now();
callback.frame = 0;
}
this.callbacks.unshift(callback);
}
remove(callback) {
const index = this.callbacks.indexOf(callback);
if (~index) {
this.callbacks.splice(index, 1);
}
}
start() {
if (this.isAnimating) {
return;
}
this.isAnimating = true;
this.requestId = RequestFrame(this.onTick);
}
stop() {
if (!this.isAnimating) {
return;
}
this.isAnimating = false;
CancelFrame(this.requestId);
}
setRequestFrame(request) {
RequestFrame = request;
}
setCancelFrame(cancel) {
CancelFrame = cancel;
}
}
export const ticker = new Ticker();
// magnetic/Magnetic.js
/**
* @author pschroen / https://ufo.ai/
*
* Based on https://gist.github.com/jesperlandberg/66484c7bb456661662f57361851bfc31
*/
import { Component } from './Component.js';
export class Magnetic extends Component {
constructor(object, {
threshold = 50
} = {}) {
super();
this.object = object;
this.threshold = threshold;
this.hoveredIn = false;
this.init();
this.enable();
}
init() {
this.object.css({ willChange: 'transform' });
}
addListeners() {
window.addEventListener('pointerdown', this.onPointerDown);
window.addEventListener('pointermove', this.onPointerMove);
window.addEventListener('pointerup', this.onPointerUp);
}
removeListeners() {
window.removeEventListener('pointerdown', this.onPointerDown);
window.removeEventListener('pointermove', this.onPointerMove);
window.removeEventListener('pointerup', this.onPointerUp);
}
// Event handlers
onPointerDown = e => {
this.onPointerMove(e);
};
onPointerMove = ({ clientX, clientY }) => {
const { left, top, width, height } = this.object.element.getBoundingClientRect();
const x = clientX - (left + width / 2);
const y = clientY - (top + height / 2);
const distance = Math.sqrt(x * x + y * y);
if (distance < (width + height) / 2 + this.threshold) {
this.onHover({ type: 'over', x, y });
} else if (this.hoveredIn) {
this.onHover({ type: 'out' });
}
};
onPointerUp = () => {
this.onHover({ type: 'out' });
};
onHover = ({ type, x, y }) => {
this.object.clearTween();
if (type === 'over') {
this.object.tween({
x: x * 0.8,
y: y * 0.8,
skewX: x * 0.125,
skewY: 0,
rotation: x * 0.05,
scale: 1.1
}, 500, 'easeOutCubic');
this.hoveredIn = true;
} else {
this.object.tween({
x: 0,
y: 0,
skewX: 0,
skewY: 0,
rotation: 0,
scale: 1,
spring: 1.2,
damping: 0.4
}, 1000, 'easeOutElastic');
this.hoveredIn = false;
}
};
// Public methods
enable() {
this.addListeners();
}
disable() {
this.removeListeners();
}
destroy() {
this.disable();
return super.destroy();
}
}
// magnetic/Easing.js
/**
* @author pschroen / https://ufo.ai/
*
* Based on https://github.com/danro/easing-js
* Based on https://github.com/CreateJS/TweenJS
* Based on https://github.com/tweenjs/tween.js
* Based on https://easings.net/
*/
import BezierEasing from './BezierEasing.js';
export class Easing {
static linear(t) {
return t;
}
static easeInQuad(t) {
return t * t;
}
static easeOutQuad(t) {
return t * (2 - t);
}
static easeInOutQuad(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t;
}
return -0.5 * (--t * (t - 2) - 1);
}
static easeInCubic(t) {
return t * t * t;
}
static easeOutCubic(t) {
return --t * t * t + 1;
}
static easeInOutCubic(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t * t;
}
return 0.5 * ((t -= 2) * t * t + 2);
}
static easeInQuart(t) {
return t * t * t * t;
}
static easeOutQuart(t) {
return 1 - --t * t * t * t;
}
static easeInOutQuart(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t * t * t;
}
return -0.5 * ((t -= 2) * t * t * t - 2);
}
static easeInQuint(t) {
return t * t * t * t * t;
}
static easeOutQuint(t) {
return --t * t * t * t * t + 1;
}
static easeInOutQuint(t) {
if ((t *= 2) < 1) {
return 0.5 * t * t * t * t * t;
}
return 0.5 * ((t -= 2) * t * t * t * t + 2);
}
static easeInSine(t) {
return 1 - Math.sin(((1 - t) * Math.PI) / 2);
}
static easeOutSine(t) {
return Math.sin((t * Math.PI) / 2);
}
static easeInOutSine(t) {
return 0.5 * (1 - Math.sin(Math.PI * (0.5 - t)));
}
static easeInExpo(t) {
return t === 0 ? 0 : Math.pow(1024, t - 1);
}
static easeOutExpo(t) {
return t === 1 ? 1 : 1 - Math.pow(2, -10 * t);
}
static easeInOutExpo(t) {
if (t === 0 || t === 1) {
return t;
}
if ((t *= 2) < 1) {
return 0.5 * Math.pow(1024, t - 1);
}
return 0.5 * (-Math.pow(2, -10 * (t - 1)) + 2);
}
static easeInCirc(t) {
return 1 - Math.sqrt(1 - t * t);
}
static easeOutCirc(t) {
return Math.sqrt(1 - --t * t);
}
static easeInOutCirc(t) {
if ((t *= 2) < 1) {
return -0.5 * (Math.sqrt(1 - t * t) - 1);
}
return 0.5 * (Math.sqrt(1 - (t -= 2) * t) + 1);
}
static easeInBack(t) {
const s = 1.70158;
return t === 1 ? 1 : t * t * ((s + 1) * t - s);
}
static easeOutBack(t) {
const s = 1.70158;
return t === 0 ? 0 : --t * t * ((s + 1) * t + s) + 1;
}
static easeInOutBack(t) {
const s = 1.70158 * 1.525;
if ((t *= 2) < 1) {
return 0.5 * (t * t * ((s + 1) * t - s));
}
return 0.5 * ((t -= 2) * t * ((s + 1) * t + s) + 2);
}
static easeInElastic(t, amplitude = 1, period = 0.3) {
if (t === 0 || t === 1) {
return t;
}
const pi2 = Math.PI * 2;
const s = period / pi2 * Math.asin(1 / amplitude);
return -(amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period));
}
static easeOutElastic(t, amplitude = 1, period = 0.3) {
if (t === 0 || t === 1) {
return t;
}
const pi2 = Math.PI * 2;
const s = period / pi2 * Math.asin(1 / amplitude);
return amplitude * Math.pow(2, -10 * t) * Math.sin((t - s) * pi2 / period) + 1;
}
static easeInOutElastic(t, amplitude = 1, period = 0.3 * 1.5) {
if (t === 0 || t === 1) {
return t;
}
const pi2 = Math.PI * 2;
const s = period / pi2 * Math.asin(1 / amplitude);
if ((t *= 2) < 1) {
return -0.5 * (amplitude * Math.pow(2, 10 * --t) * Math.sin((t - s) * pi2 / period));
}
return amplitude * Math.pow(2, -10 * --t) * Math.sin((t - s) * pi2 / period) * 0.5 + 1;
}
static easeInBounce(t) {
return 1 - this.easeOutBounce(1 - t);
}
static easeOutBounce(t) {
const n1 = 7.5625;
const d1 = 2.75;
if (t < 1 / d1) {
return n1 * t * t;
} else if (t < 2 / d1) {
return n1 * (t -= 1.5 / d1) * t + 0.75;
} else if (t < 2.5 / d1) {
return n1 * (t -= 2.25 / d1) * t + 0.9375;
} else {
return n1 * (t -= 2.625 / d1) * t + 0.984375;
}
}
static easeInOutBounce(t) {
if (t < 0.5) {
return this.easeInBounce(t * 2) * 0.5;
}
return this.easeOutBounce(t * 2 - 1) * 0.5 + 0.5;
}
static addBezier(name, mX1, mY1, mX2, mY2) {
this[name] = BezierEasing(mX1, mY1, mX2, mY2);
}
}
| 7 | 949 | JavaScript |
plane | ./ProjectTest/JavaScript/plane.js | // plane/vec2.js
/* Copyright (c) 2013, Brandon Jones, Colin MacKenzie IV. All rights reserved.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */
/**
* The vec2 object from glMatrix, with some extensions and some removed methods. See http://glmatrix.net.
* @class vec2
*/
var vec2 = module.exports = {};
var Utils = require('./Utils');
/**
* Make a cross product and only return the z component
* @method crossLength
* @static
* @param {Array} a
* @param {Array} b
* @return {Number}
*/
vec2.crossLength = function(a,b){
return a[0] * b[1] - a[1] * b[0];
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossVZ
* @static
* @param {Array} out
* @param {Array} vec
* @param {Number} zcomp
* @return {Array}
*/
vec2.crossVZ = function(out, vec, zcomp){
vec2.rotate(out,vec,-Math.PI/2);// Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Cross product between a vector and the Z component of a vector
* @method crossZV
* @static
* @param {Array} out
* @param {Number} zcomp
* @param {Array} vec
* @return {Array}
*/
vec2.crossZV = function(out, zcomp, vec){
vec2.rotate(out,vec,Math.PI/2); // Rotate according to the right hand rule
vec2.scale(out,out,zcomp); // Scale with z
return out;
};
/**
* Rotate a vector by an angle
* @method rotate
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate = function(out,a,angle){
if(angle !== 0){
var c = Math.cos(angle),
s = Math.sin(angle),
x = a[0],
y = a[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
} else {
out[0] = a[0];
out[1] = a[1];
}
return out;
};
/**
* Rotate a vector 90 degrees clockwise
* @method rotate90cw
* @static
* @param {Array} out
* @param {Array} a
* @param {Number} angle
* @return {Array}
*/
vec2.rotate90cw = function(out, a) {
var x = a[0];
var y = a[1];
out[0] = y;
out[1] = -x;
return out;
};
/**
* Transform a point position to local frame.
* @method toLocalFrame
* @param {Array} out
* @param {Array} worldPoint
* @param {Array} framePosition
* @param {Number} frameAngle
* @return {Array}
*/
vec2.toLocalFrame = function(out, worldPoint, framePosition, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldPoint[0] - framePosition[0],
y = worldPoint[1] - framePosition[1];
out[0] = c * x - s * y;
out[1] = s * x + c * y;
return out;
};
/**
* Transform a point position to global frame.
* @method toGlobalFrame
* @param {Array} out
* @param {Array} localPoint
* @param {Array} framePosition
* @param {Number} frameAngle
*/
vec2.toGlobalFrame = function(out, localPoint, framePosition, frameAngle){
var c = Math.cos(frameAngle),
s = Math.sin(frameAngle),
x = localPoint[0],
y = localPoint[1],
addX = framePosition[0],
addY = framePosition[1];
out[0] = c * x - s * y + addX;
out[1] = s * x + c * y + addY;
};
/**
* Transform a vector to local frame.
* @method vectorToLocalFrame
* @param {Array} out
* @param {Array} worldVector
* @param {Number} frameAngle
* @return {Array}
*/
vec2.vectorToLocalFrame = function(out, worldVector, frameAngle){
var c = Math.cos(-frameAngle),
s = Math.sin(-frameAngle),
x = worldVector[0],
y = worldVector[1];
out[0] = c*x -s*y;
out[1] = s*x +c*y;
return out;
};
/**
* Transform a vector to global frame.
* @method vectorToGlobalFrame
* @param {Array} out
* @param {Array} localVector
* @param {Number} frameAngle
*/
vec2.vectorToGlobalFrame = vec2.rotate;
/**
* Compute centroid of a triangle spanned by vectors a,b,c. See http://easycalculation.com/analytical/learn-centroid.php
* @method centroid
* @static
* @param {Array} out
* @param {Array} a
* @param {Array} b
* @param {Array} c
* @return {Array} The "out" vector.
*/
vec2.centroid = function(out, a, b, c){
vec2.add(out, a, b);
vec2.add(out, out, c);
vec2.scale(out, out, 1/3);
return out;
};
/**
* Creates a new, empty vec2
* @static
* @method create
* @return {Array} a new 2D vector
*/
vec2.create = function() {
var out = new Utils.ARRAY_TYPE(2);
out[0] = 0;
out[1] = 0;
return out;
};
/**
* Creates a new vec2 initialized with values from an existing vector
* @static
* @method clone
* @param {Array} a vector to clone
* @return {Array} a new 2D vector
*/
vec2.clone = function(a) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Creates a new vec2 initialized with the given values
* @static
* @method fromValues
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} a new 2D vector
*/
vec2.fromValues = function(x, y) {
var out = new Utils.ARRAY_TYPE(2);
out[0] = x;
out[1] = y;
return out;
};
/**
* Copy the values from one vec2 to another
* @static
* @method copy
* @param {Array} out the receiving vector
* @param {Array} a the source vector
* @return {Array} out
*/
vec2.copy = function(out, a) {
out[0] = a[0];
out[1] = a[1];
return out;
};
/**
* Set the components of a vec2 to the given values
* @static
* @method set
* @param {Array} out the receiving vector
* @param {Number} x X component
* @param {Number} y Y component
* @return {Array} out
*/
vec2.set = function(out, x, y) {
out[0] = x;
out[1] = y;
return out;
};
/**
* Adds two vec2's
* @static
* @method add
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.add = function(out, a, b) {
out[0] = a[0] + b[0];
out[1] = a[1] + b[1];
return out;
};
/**
* Subtracts two vec2's
* @static
* @method subtract
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.subtract = function(out, a, b) {
out[0] = a[0] - b[0];
out[1] = a[1] - b[1];
return out;
};
/**
* Multiplies two vec2's
* @static
* @method multiply
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.multiply = function(out, a, b) {
out[0] = a[0] * b[0];
out[1] = a[1] * b[1];
return out;
};
/**
* Divides two vec2's
* @static
* @method divide
* @param {Array} out the receiving vector
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Array} out
*/
vec2.divide = function(out, a, b) {
out[0] = a[0] / b[0];
out[1] = a[1] / b[1];
return out;
};
/**
* Scales a vec2 by a scalar number
* @static
* @method scale
* @param {Array} out the receiving vector
* @param {Array} a the vector to scale
* @param {Number} b amount to scale the vector by
* @return {Array} out
*/
vec2.scale = function(out, a, b) {
out[0] = a[0] * b;
out[1] = a[1] * b;
return out;
};
/**
* Calculates the euclidian distance between two vec2's
* @static
* @method distance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} distance between a and b
*/
vec2.distance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared euclidian distance between two vec2's
* @static
* @method squaredDistance
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} squared distance between a and b
*/
vec2.squaredDistance = function(a, b) {
var x = b[0] - a[0],
y = b[1] - a[1];
return x*x + y*y;
};
/**
* Calculates the length of a vec2
* @static
* @method length
* @param {Array} a vector to calculate length of
* @return {Number} length of a
*/
vec2.length = function (a) {
var x = a[0],
y = a[1];
return Math.sqrt(x*x + y*y);
};
/**
* Calculates the squared length of a vec2
* @static
* @method squaredLength
* @param {Array} a vector to calculate squared length of
* @return {Number} squared length of a
*/
vec2.squaredLength = function (a) {
var x = a[0],
y = a[1];
return x*x + y*y;
};
/**
* Negates the components of a vec2
* @static
* @method negate
* @param {Array} out the receiving vector
* @param {Array} a vector to negate
* @return {Array} out
*/
vec2.negate = function(out, a) {
out[0] = -a[0];
out[1] = -a[1];
return out;
};
/**
* Normalize a vec2
* @static
* @method normalize
* @param {Array} out the receiving vector
* @param {Array} a vector to normalize
* @return {Array} out
*/
vec2.normalize = function(out, a) {
var x = a[0],
y = a[1];
var len = x*x + y*y;
if (len > 0) {
//TODO: evaluate use of glm_invsqrt here?
len = 1 / Math.sqrt(len);
out[0] = a[0] * len;
out[1] = a[1] * len;
}
return out;
};
/**
* Calculates the dot product of two vec2's
* @static
* @method dot
* @param {Array} a the first operand
* @param {Array} b the second operand
* @return {Number} dot product of a and b
*/
vec2.dot = function (a, b) {
return a[0] * b[0] + a[1] * b[1];
};
/**
* Returns a string representation of a vector
* @static
* @method str
* @param {Array} vec vector to represent as a string
* @return {String} string representation of the vector
*/
vec2.str = function (a) {
return 'vec2(' + a[0] + ', ' + a[1] + ')';
};
/**
* Linearly interpolate/mix two vectors.
* @static
* @method lerp
* @param {Array} out
* @param {Array} a First vector
* @param {Array} b Second vector
* @param {number} t Lerp factor
*/
vec2.lerp = function (out, a, b, t) {
var ax = a[0],
ay = a[1];
out[0] = ax + t * (b[0] - ax);
out[1] = ay + t * (b[1] - ay);
return out;
};
/**
* Reflect a vector along a normal.
* @static
* @method reflect
* @param {Array} out
* @param {Array} vector
* @param {Array} normal
*/
vec2.reflect = function(out, vector, normal){
var dot = vector[0] * normal[0] + vector[1] * normal[1];
out[0] = vector[0] - 2 * normal[0] * dot;
out[1] = vector[1] - 2 * normal[1] * dot;
};
/**
* Get the intersection point between two line segments.
* @static
* @method getLineSegmentsIntersection
* @param {Array} out
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {boolean} True if there was an intersection, otherwise false.
*/
vec2.getLineSegmentsIntersection = function(out, p0, p1, p2, p3) {
var t = vec2.getLineSegmentsIntersectionFraction(p0, p1, p2, p3);
if(t < 0){
return false;
} else {
out[0] = p0[0] + (t * (p1[0] - p0[0]));
out[1] = p0[1] + (t * (p1[1] - p0[1]));
return true;
}
};
/**
* Get the intersection fraction between two line segments. If successful, the intersection is at p0 + t * (p1 - p0)
* @static
* @method getLineSegmentsIntersectionFraction
* @param {Array} p0
* @param {Array} p1
* @param {Array} p2
* @param {Array} p3
* @return {number} A number between 0 and 1 if there was an intersection, otherwise -1.
*/
vec2.getLineSegmentsIntersectionFraction = function(p0, p1, p2, p3) {
var s1_x = p1[0] - p0[0];
var s1_y = p1[1] - p0[1];
var s2_x = p3[0] - p2[0];
var s2_y = p3[1] - p2[1];
var s, t;
s = (-s1_y * (p0[0] - p2[0]) + s1_x * (p0[1] - p2[1])) / (-s2_x * s1_y + s1_x * s2_y);
t = ( s2_x * (p0[1] - p2[1]) - s2_y * (p0[0] - p2[0])) / (-s2_x * s1_y + s1_x * s2_y);
if (s >= 0 && s <= 1 && t >= 0 && t <= 1) { // Collision detected
return t;
}
return -1; // No collision
};
// plane/Plane.js
var Shape = require('./Shape')
, vec2 = require('./vec2')
, Utils = require('./Utils');
module.exports = Plane;
/**
* Plane shape class. The plane is facing in the Y direction.
* @class Plane
* @extends Shape
* @constructor
* @param {object} [options] (Note that this options object will be passed on to the {{#crossLink "Shape"}}{{/crossLink}} constructor.)
* @example
* var body = new Body();
* var shape = new Plane();
* body.addShape(shape);
*/
function Plane(options){
options = options ? Utils.shallowClone(options) : {};
options.type = Shape.PLANE;
Shape.call(this, options);
}
Plane.prototype = new Shape();
Plane.prototype.constructor = Plane;
/**
* Compute moment of inertia
* @method computeMomentOfInertia
*/
Plane.prototype.computeMomentOfInertia = function(){
return 0; // Plane is infinite. The inertia should therefore be infinty but by convention we set 0 here
};
/**
* Update the bounding radius
* @method updateBoundingRadius
*/
Plane.prototype.updateBoundingRadius = function(){
this.boundingRadius = Number.MAX_VALUE;
};
/**
* @method computeAABB
* @param {AABB} out
* @param {Array} position
* @param {Number} angle
*/
Plane.prototype.computeAABB = function(out, position, angle){
var a = angle % (2 * Math.PI);
var set = vec2.set;
var max = 1e7;
var lowerBound = out.lowerBound;
var upperBound = out.upperBound;
// Set max bounds
set(lowerBound, -max, -max);
set(upperBound, max, max);
if(a === 0){
// y goes from -inf to 0
upperBound[1] = position[1];
} else if(a === Math.PI / 2){
// x goes from 0 to inf
lowerBound[0] = position[0];
} else if(a === Math.PI){
// y goes from 0 to inf
lowerBound[1] = position[1];
} else if(a === 3*Math.PI/2){
// x goes from -inf to 0
upperBound[0] = position[0];
}
};
Plane.prototype.updateArea = function(){
this.area = Number.MAX_VALUE;
};
var intersectPlane_planePointToFrom = vec2.create();
var intersectPlane_normal = vec2.create();
var intersectPlane_len = vec2.create();
/**
* @method raycast
* @param {RayResult} result
* @param {Ray} ray
* @param {array} position
* @param {number} angle
*/
Plane.prototype.raycast = function(result, ray, position, angle){
var from = ray.from;
var to = ray.to;
var direction = ray.direction;
var planePointToFrom = intersectPlane_planePointToFrom;
var normal = intersectPlane_normal;
var len = intersectPlane_len;
// Get plane normal
vec2.set(normal, 0, 1);
vec2.rotate(normal, normal, angle);
vec2.subtract(len, from, position);
var planeToFrom = vec2.dot(len, normal);
vec2.subtract(len, to, position);
var planeToTo = vec2.dot(len, normal);
if(planeToFrom * planeToTo > 0){
// "from" and "to" are on the same side of the plane... bail out
return;
}
if(vec2.squaredDistance(from, to) < planeToFrom * planeToFrom){
return;
}
var n_dot_dir = vec2.dot(normal, direction);
vec2.subtract(planePointToFrom, from, position);
var t = -vec2.dot(normal, planePointToFrom) / n_dot_dir / ray.length;
ray.reportIntersection(result, t, normal, -1);
};
Plane.prototype.pointTest = function(localPoint){
return localPoint[1] <= 0;
};
// plane/Utils.js
/* global P2_ARRAY_TYPE */
module.exports = Utils;
/**
* Misc utility functions
* @class Utils
* @constructor
*/
function Utils(){}
/**
* Append the values in array b to the array a. See <a href="http://stackoverflow.com/questions/1374126/how-to-append-an-array-to-an-existing-javascript-array/1374131#1374131">this</a> for an explanation.
* @method appendArray
* @static
* @param {Array} a
* @param {Array} b
*/
Utils.appendArray = function(a,b){
if (b.length < 150000) {
a.push.apply(a, b);
} else {
for (var i = 0, len = b.length; i !== len; ++i) {
a.push(b[i]);
}
}
};
/**
* Garbage free Array.splice(). Does not allocate a new array.
* @method splice
* @static
* @param {Array} array
* @param {Number} index
* @param {Number} howmany
*/
Utils.splice = function(array,index,howmany){
howmany = howmany || 1;
for (var i=index, len=array.length-howmany; i < len; i++){
array[i] = array[i + howmany];
}
array.length = len;
};
/**
* Remove an element from an array, if the array contains the element.
* @method arrayRemove
* @static
* @param {Array} array
* @param {Number} element
*/
Utils.arrayRemove = function(array, element){
var idx = array.indexOf(element);
if(idx!==-1){
Utils.splice(array, idx, 1);
}
};
/**
* The array type to use for internal numeric computations throughout the library. Float32Array is used if it is available, but falls back on Array. If you want to set array type manually, inject it via the global variable P2_ARRAY_TYPE. See example below.
* @static
* @property {function} ARRAY_TYPE
* @example
* <script>
* <!-- Inject your preferred array type before loading p2.js -->
* P2_ARRAY_TYPE = Array;
* </script>
* <script src="p2.js"></script>
*/
if(typeof P2_ARRAY_TYPE !== 'undefined') {
Utils.ARRAY_TYPE = P2_ARRAY_TYPE;
} else if (typeof Float32Array !== 'undefined'){
Utils.ARRAY_TYPE = Float32Array;
} else {
Utils.ARRAY_TYPE = Array;
}
/**
* Extend an object with the properties of another
* @static
* @method extend
* @param {object} a
* @param {object} b
*/
Utils.extend = function(a,b){
for(var key in b){
a[key] = b[key];
}
};
/**
* Shallow clone an object. Returns a new object instance with the same properties as the input instance.
* @static
* @method shallowClone
* @param {object} obj
*/
Utils.shallowClone = function(obj){
var newObj = {};
Utils.extend(newObj, obj);
return newObj;
};
/**
* Extend an options object with default values.
* @deprecated Not used internally, will be removed.
* @static
* @method defaults
* @param {object} options The options object. May be falsy: in this case, a new object is created and returned.
* @param {object} defaults An object containing default values.
* @return {object} The modified options object.
*/
Utils.defaults = function(options, defaults){
console.warn('Utils.defaults is deprecated.');
options = options || {};
for(var key in defaults){
if(!(key in options)){
options[key] = defaults[key];
}
}
return options;
};
// plane/Shape.js
module.exports = Shape;
var vec2 = require('./vec2');
/**
* Base class for shapes. Not to be used directly.
* @class Shape
* @constructor
* @param {object} [options]
* @param {number} [options.angle=0]
* @param {number} [options.collisionGroup=1]
* @param {number} [options.collisionMask=1]
* @param {boolean} [options.collisionResponse=true]
* @param {Material} [options.material=null]
* @param {array} [options.position]
* @param {boolean} [options.sensor=false]
* @param {object} [options.type=0]
*/
function Shape(options){
options = options || {};
/**
* The body this shape is attached to. A shape can only be attached to a single body.
* @property {Body} body
*/
this.body = null;
/**
* Body-local position of the shape.
* @property {Array} position
*/
this.position = vec2.create();
if(options.position){
vec2.copy(this.position, options.position);
}
/**
* Body-local angle of the shape.
* @property {number} angle
*/
this.angle = options.angle || 0;
/**
* The type of the shape. One of:
*
* <ul>
* <li><a href="Shape.html#property_CIRCLE">Shape.CIRCLE</a></li>
* <li><a href="Shape.html#property_PARTICLE">Shape.PARTICLE</a></li>
* <li><a href="Shape.html#property_PLANE">Shape.PLANE</a></li>
* <li><a href="Shape.html#property_CONVEX">Shape.CONVEX</a></li>
* <li><a href="Shape.html#property_LINE">Shape.LINE</a></li>
* <li><a href="Shape.html#property_BOX">Shape.BOX</a></li>
* <li><a href="Shape.html#property_CAPSULE">Shape.CAPSULE</a></li>
* <li><a href="Shape.html#property_HEIGHTFIELD">Shape.HEIGHTFIELD</a></li>
* </ul>
*
* @property {number} type
*/
this.type = options.type || 0;
/**
* Shape object identifier. Read only.
* @readonly
* @type {Number}
* @property id
*/
this.id = Shape.idCounter++;
/**
* Bounding circle radius of this shape
* @readonly
* @property boundingRadius
* @type {Number}
*/
this.boundingRadius = 0;
/**
* Collision group that this shape belongs to (bit mask). See <a href="http://www.aurelienribon.com/blog/2011/07/box2d-tutorial-collision-filtering/">this tutorial</a>.
* @property collisionGroup
* @type {Number}
* @example
* // Setup bits for each available group
* var PLAYER = Math.pow(2,0),
* ENEMY = Math.pow(2,1),
* GROUND = Math.pow(2,2)
*
* // Put shapes into their groups
* player1Shape.collisionGroup = PLAYER;
* player2Shape.collisionGroup = PLAYER;
* enemyShape .collisionGroup = ENEMY;
* groundShape .collisionGroup = GROUND;
*
* // Assign groups that each shape collide with.
* // Note that the players can collide with ground and enemies, but not with other players.
* player1Shape.collisionMask = ENEMY | GROUND;
* player2Shape.collisionMask = ENEMY | GROUND;
* enemyShape .collisionMask = PLAYER | GROUND;
* groundShape .collisionMask = PLAYER | ENEMY;
*
* @example
* // How collision check is done
* if(shapeA.collisionGroup & shapeB.collisionMask)!=0 && (shapeB.collisionGroup & shapeA.collisionMask)!=0){
* // The shapes will collide
* }
*/
this.collisionGroup = options.collisionGroup !== undefined ? options.collisionGroup : 1;
/**
* Whether to produce contact forces when in contact with other bodies. Note that contacts will be generated, but they will be disabled. That means that this shape will move through other body shapes, but it will still trigger contact events, etc.
* @property {Boolean} collisionResponse
*/
this.collisionResponse = options.collisionResponse !== undefined ? options.collisionResponse : true;
/**
* Collision mask of this shape. See .collisionGroup.
* @property collisionMask
* @type {Number}
*/
this.collisionMask = options.collisionMask !== undefined ? options.collisionMask : 1;
/**
* Material to use in collisions for this Shape. If this is set to null, the world will use default material properties instead.
* @property material
* @type {Material}
*/
this.material = options.material || null;
/**
* Area of this shape.
* @property area
* @type {Number}
*/
this.area = 0;
/**
* Set to true if you want this shape to be a sensor. A sensor does not generate contacts, but it still reports contact events. This is good if you want to know if a shape is overlapping another shape, without them generating contacts.
* @property {Boolean} sensor
*/
this.sensor = options.sensor !== undefined ? options.sensor : false;
if(this.type){
this.updateBoundingRadius();
}
this.updateArea();
}
Shape.idCounter = 0;
/**
* @static
* @property {Number} CIRCLE
*/
Shape.CIRCLE = 1;
/**
* @static
* @property {Number} PARTICLE
*/
Shape.PARTICLE = 2;
/**
* @static
* @property {Number} PLANE
*/
Shape.PLANE = 4;
/**
* @static
* @property {Number} CONVEX
*/
Shape.CONVEX = 8;
/**
* @static
* @property {Number} LINE
*/
Shape.LINE = 16;
/**
* @static
* @property {Number} BOX
*/
Shape.BOX = 32;
/**
* @static
* @property {Number} CAPSULE
*/
Shape.CAPSULE = 64;
/**
* @static
* @property {Number} HEIGHTFIELD
*/
Shape.HEIGHTFIELD = 128;
Shape.prototype = {
/**
* Should return the moment of inertia around the Z axis of the body. See <a href="http://en.wikipedia.org/wiki/List_of_moments_of_inertia">Wikipedia's list of moments of inertia</a>.
* @method computeMomentOfInertia
* @return {Number} If the inertia is infinity or if the object simply isn't possible to rotate, return 0.
*/
computeMomentOfInertia: function(){},
/**
* Returns the bounding circle radius of this shape.
* @method updateBoundingRadius
* @return {Number}
*/
updateBoundingRadius: function(){},
/**
* Update the .area property of the shape.
* @method updateArea
*/
updateArea: function(){},
/**
* Compute the world axis-aligned bounding box (AABB) of this shape.
* @method computeAABB
* @param {AABB} out The resulting AABB.
* @param {Array} position World position of the shape.
* @param {Number} angle World angle of the shape.
*/
computeAABB: function(/*out, position, angle*/){
// To be implemented in each subclass
},
/**
* Perform raycasting on this shape.
* @method raycast
* @param {RayResult} result Where to store the resulting data.
* @param {Ray} ray The Ray that you want to use for raycasting.
* @param {array} position World position of the shape (the .position property will be ignored).
* @param {number} angle World angle of the shape (the .angle property will be ignored).
*/
raycast: function(/*result, ray, position, angle*/){
// To be implemented in each subclass
},
/**
* Test if a point is inside this shape.
* @method pointTest
* @param {array} localPoint
* @return {boolean}
*/
pointTest: function(/*localPoint*/){ return false; },
/**
* Transform a world point to local shape space (assumed the shape is transformed by both itself and the body).
* @method worldPointToLocal
* @param {array} out
* @param {array} worldPoint
*/
worldPointToLocal: (function () {
var shapeWorldPosition = vec2.create();
return function (out, worldPoint) {
var body = this.body;
vec2.rotate(shapeWorldPosition, this.position, body.angle);
vec2.add(shapeWorldPosition, shapeWorldPosition, body.position);
vec2.toLocalFrame(out, worldPoint, shapeWorldPosition, this.body.angle + this.angle);
};
})()
};
| 4 | 1,052 | JavaScript |
span | ./ProjectTest/JavaScript/span.js | // span/Span.js
import Util from "./Util";
import MathUtil from "./MathUtil";
export default class Span {
constructor(a, b, center) {
if (Util.isArray(a)) {
this.isArray = true;
this.a = a;
} else {
this.isArray = false;
this.a = Util.initValue(a, 1);
this.b = Util.initValue(b, this.a);
this.center = Util.initValue(center, false);
}
}
getValue(isInt = false) {
if (this.isArray) {
return Util.getRandFromArray(this.a);
} else {
if (!this.center) {
return MathUtil.randomAToB(this.a, this.b, isInt);
} else {
return MathUtil.randomFloating(this.a, this.b, isInt);
}
}
}
/**
* Returns a new Span object
*
* @memberof Proton#Proton.Util
* @method setSpanValue
*
* @todo a, b and c should be 'Mixed' or 'Number'?
*
* @param {Mixed | Span} a
* @param {Mixed} b
* @param {Mixed} c
*
* @return {Span}
*/
static setSpanValue(a, b, c) {
if (a instanceof Span) {
return a;
} else {
if (b === undefined) {
return new Span(a);
} else {
if (c === undefined) return new Span(a, b);
else return new Span(a, b, c);
}
}
}
/**
* Returns the value from a Span, if the param is not a Span it will return the given parameter
*
* @memberof Proton#Proton.Util
* @method getValue
*
* @param {Mixed | Span} pan
*
* @return {Mixed} the value of Span OR the parameter if it is not a Span
*/
static getSpanValue(pan) {
return pan instanceof Span ? pan.getValue() : pan;
}
}
// span/DomUtil.js
export default {
/**
* Creates and returns a new canvas. The opacity is by default set to 0
*
* @memberof Proton#Proton.DomUtil
* @method createCanvas
*
* @param {String} $id the canvas' id
* @param {Number} $width the canvas' width
* @param {Number} $height the canvas' height
* @param {String} [$position=absolute] the canvas' position, default is 'absolute'
*
* @return {Object}
*/
createCanvas(id, width, height, position = "absolute") {
const dom = document.createElement("canvas");
dom.id = id;
dom.width = width;
dom.height = height;
dom.style.opacity = 0;
dom.style.position = position;
this.transform(dom, -500, -500, 0, 0);
return dom;
},
createDiv(id, width, height) {
const dom = document.createElement("div");
dom.id = id;
dom.style.position = "absolute";
this.resize(dom, width, height);
return dom;
},
resize(dom, width, height) {
dom.style.width = width + "px";
dom.style.height = height + "px";
dom.style.marginLeft = -width / 2 + "px";
dom.style.marginTop = -height / 2 + "px";
},
/**
* Adds a transform: translate(), scale(), rotate() to a given div dom for all browsers
*
* @memberof Proton#Proton.DomUtil
* @method transform
*
* @param {HTMLDivElement} div
* @param {Number} $x
* @param {Number} $y
* @param {Number} $scale
* @param {Number} $rotate
*/
transform(div, x, y, scale, rotate) {
div.style.willChange = "transform";
const transform = `translate(${x}px, ${y}px) scale(${scale}) rotate(${rotate}deg)`;
this.css3(div, "transform", transform);
},
transform3d(div, x, y, scale, rotate) {
div.style.willChange = "transform";
const transform = `translate3d(${x}px, ${y}px, 0) scale(${scale}) rotate(${rotate}deg)`;
this.css3(div, "backfaceVisibility", "hidden");
this.css3(div, "transform", transform);
},
css3(div, key, val) {
const bkey = key.charAt(0).toUpperCase() + key.substr(1);
div.style[`Webkit${bkey}`] = val;
div.style[`Moz${bkey}`] = val;
div.style[`O${bkey}`] = val;
div.style[`ms${bkey}`] = val;
div.style[`${key}`] = val;
}
};
// span/ImgUtil.js
import WebGLUtil from "./WebGLUtil";
import DomUtil from "./DomUtil";
const imgsCache = {};
const canvasCache = {};
let canvasId = 0;
export default {
/**
* This will get the image data. It could be necessary to create a Proton.Zone.
*
* @memberof Proton#Proton.Util
* @method getImageData
*
* @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')'
* @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag');
* @param {Proton.Rectangle} rect
*/
getImageData(context, image, rect) {
context.drawImage(image, rect.x, rect.y);
const imagedata = context.getImageData(rect.x, rect.y, rect.width, rect.height);
context.clearRect(rect.x, rect.y, rect.width, rect.height);
return imagedata;
},
/**
* @memberof Proton#Proton.Util
* @method getImgFromCache
*
* @todo add description
* @todo describe func
*
* @param {Mixed} img
* @param {Proton.Particle} particle
* @param {Boolean} drawCanvas set to true if a canvas should be saved into particle.data.canvas
* @param {Boolean} func
*/
getImgFromCache(img, callback, param) {
const src = typeof img === "string" ? img : img.src;
if (imgsCache[src]) {
callback(imgsCache[src], param);
} else {
const image = new Image();
image.onload = e => {
imgsCache[src] = e.target;
callback(imgsCache[src], param);
};
image.src = src;
}
},
getCanvasFromCache(img, callback, param) {
const src = img.src;
if (!canvasCache[src]) {
const width = WebGLUtil.nhpot(img.width);
const height = WebGLUtil.nhpot(img.height);
const canvas = DomUtil.createCanvas(`proton_canvas_cache_${++canvasId}`, width, height);
const context = canvas.getContext("2d");
context.drawImage(img, 0, 0, img.width, img.height);
canvasCache[src] = canvas;
}
callback && callback(canvasCache[src], param);
return canvasCache[src];
}
};
// span/Util.js
import ImgUtil from "./ImgUtil";
export default {
/**
* Returns the default if the value is null or undefined
*
* @memberof Proton#Proton.Util
* @method initValue
*
* @param {Mixed} value a specific value, could be everything but null or undefined
* @param {Mixed} defaults the default if the value is null or undefined
*/
initValue(value, defaults) {
value = value !== null && value !== undefined ? value : defaults;
return value;
},
/**
* Checks if the value is a valid array
*
* @memberof Proton#Proton.Util
* @method isArray
*
* @param {Array} value Any array
*
* @returns {Boolean}
*/
isArray(value) {
return Object.prototype.toString.call(value) === "[object Array]";
},
/**
* Destroyes the given array
*
* @memberof Proton#Proton.Util
* @method emptyArray
*
* @param {Array} array Any array
*/
emptyArray(arr) {
if (arr) arr.length = 0;
},
toArray(arr) {
return this.isArray(arr) ? arr : [arr];
},
sliceArray(arr1, index, arr2) {
this.emptyArray(arr2);
for (let i = index; i < arr1.length; i++) {
arr2.push(arr1[i]);
}
},
getRandFromArray(arr) {
if (!arr) return null;
return arr[Math.floor(arr.length * Math.random())];
},
/**
* Destroyes the given object
*
* @memberof Proton#Proton.Util
* @method emptyObject
*
* @param {Object} obj Any object
*/
emptyObject(obj, ignore = null) {
for (let key in obj) {
if (ignore && ignore.indexOf(key) > -1) continue;
delete obj[key];
}
},
/**
* Makes an instance of a class and binds the given array
*
* @memberof Proton#Proton.Util
* @method classApply
*
* @param {Function} constructor A class to make an instance from
* @param {Array} [args] Any array to bind it to the constructor
*
* @return {Object} The instance of constructor, optionally bind with args
*/
classApply(constructor, args = null) {
if (!args) {
return new constructor();
} else {
const FactoryFunc = constructor.bind.apply(constructor, [null].concat(args));
return new FactoryFunc();
}
},
/**
* This will get the image data. It could be necessary to create a Proton.Zone.
*
* @memberof Proton#Proton.Util
* @method getImageData
*
* @param {HTMLCanvasElement} context any canvas, must be a 2dContext 'canvas.getContext('2d')'
* @param {Object} image could be any dom image, e.g. document.getElementById('thisIsAnImgTag');
* @param {Proton.Rectangle} rect
*/
getImageData(context, image, rect) {
return ImgUtil.getImageData(context, image, rect);
},
destroyAll(arr, param = null) {
let i = arr.length;
while (i--) {
try {
arr[i].destroy(param);
} catch (e) {}
delete arr[i];
}
arr.length = 0;
},
assign(target, source) {
if (typeof Object.assign !== "function") {
for (let key in source) {
if (Object.prototype.hasOwnProperty.call(source, key)) {
target[key] = source[key];
}
}
return target;
} else {
return Object.assign(target, source);
}
}
};
// span/WebGLUtil.js
export default {
/**
* @memberof Proton#Proton.WebGLUtil
* @method ipot
*
* @todo add description
* @todo add length description
*
* @param {Number} length
*
* @return {Boolean}
*/
ipot(length) {
return (length & (length - 1)) === 0;
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method nhpot
*
* @todo add description
* @todo add length description
*
* @param {Number} length
*
* @return {Number}
*/
nhpot(length) {
--length;
for (let i = 1; i < 32; i <<= 1) {
length = length | (length >> i);
}
return length + 1;
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method makeTranslation
*
* @todo add description
* @todo add tx, ty description
* @todo add return description
*
* @param {Number} tx either 0 or 1
* @param {Number} ty either 0 or 1
*
* @return {Object}
*/
makeTranslation(tx, ty) {
return [1, 0, 0, 0, 1, 0, tx, ty, 1];
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method makeRotation
*
* @todo add description
* @todo add return description
*
* @param {Number} angleInRadians
*
* @return {Object}
*/
makeRotation(angleInRadians) {
let c = Math.cos(angleInRadians);
let s = Math.sin(angleInRadians);
return [c, -s, 0, s, c, 0, 0, 0, 1];
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method makeScale
*
* @todo add description
* @todo add tx, ty description
* @todo add return description
*
* @param {Number} sx either 0 or 1
* @param {Number} sy either 0 or 1
*
* @return {Object}
*/
makeScale(sx, sy) {
return [sx, 0, 0, 0, sy, 0, 0, 0, 1];
},
/**
* @memberof Proton#Proton.WebGLUtil
* @method matrixMultiply
*
* @todo add description
* @todo add a, b description
* @todo add return description
*
* @param {Object} a
* @param {Object} b
*
* @return {Object}
*/
matrixMultiply(a, b) {
let a00 = a[0 * 3 + 0];
let a01 = a[0 * 3 + 1];
let a02 = a[0 * 3 + 2];
let a10 = a[1 * 3 + 0];
let a11 = a[1 * 3 + 1];
let a12 = a[1 * 3 + 2];
let a20 = a[2 * 3 + 0];
let a21 = a[2 * 3 + 1];
let a22 = a[2 * 3 + 2];
let b00 = b[0 * 3 + 0];
let b01 = b[0 * 3 + 1];
let b02 = b[0 * 3 + 2];
let b10 = b[1 * 3 + 0];
let b11 = b[1 * 3 + 1];
let b12 = b[1 * 3 + 2];
let b20 = b[2 * 3 + 0];
let b21 = b[2 * 3 + 1];
let b22 = b[2 * 3 + 2];
return [
a00 * b00 + a01 * b10 + a02 * b20,
a00 * b01 + a01 * b11 + a02 * b21,
a00 * b02 + a01 * b12 + a02 * b22,
a10 * b00 + a11 * b10 + a12 * b20,
a10 * b01 + a11 * b11 + a12 * b21,
a10 * b02 + a11 * b12 + a12 * b22,
a20 * b00 + a21 * b10 + a22 * b20,
a20 * b01 + a21 * b11 + a22 * b21,
a20 * b02 + a21 * b12 + a22 * b22
];
}
};
// span/MathUtil.js
const PI = 3.1415926;
const INFINITY = Infinity;
const MathUtil = {
PI: PI,
PIx2: PI * 2,
PI_2: PI / 2,
PI_180: PI / 180,
N180_PI: 180 / PI,
Infinity: -999,
isInfinity(num) {
return num === this.Infinity || num === INFINITY;
},
randomAToB(a, b, isInt = false) {
if (!isInt) return a + Math.random() * (b - a);
else return ((Math.random() * (b - a)) >> 0) + a;
},
randomFloating(center, f, isInt) {
return this.randomAToB(center - f, center + f, isInt);
},
randomColor() {
return "#" + ("00000" + ((Math.random() * 0x1000000) << 0).toString(16)).slice(-6);
},
randomZone(display) {},
floor(num, k = 4) {
const digits = Math.pow(10, k);
return Math.floor(num * digits) / digits;
},
degreeTransform(a) {
return (a * PI) / 180;
},
toColor16(num) {
return `#${num.toString(16)}`;
}
};
export default MathUtil;
| 6 | 536 | JavaScript |
t_test | ./ProjectTest/JavaScript/t_test.js | // t_test/t_test.js
import mean from "./mean.js";
import standardDeviation from "./standard_deviation.js";
/**
* This is to compute [a one-sample t-test](https://en.wikipedia.org/wiki/Student%27s_t-test#One-sample_t-test), comparing the mean
* of a sample to a known value, x.
*
* in this case, we're trying to determine whether the
* population mean is equal to the value that we know, which is `x`
* here. Usually the results here are used to look up a
* [p-value](http://en.wikipedia.org/wiki/P-value), which, for
* a certain level of significance, will let you determine that the
* null hypothesis can or cannot be rejected.
*
* @param {Array<number>} x sample of one or more numbers
* @param {number} expectedValue expected value of the population mean
* @returns {number} value
* @example
* tTest([1, 2, 3, 4, 5, 6], 3.385).toFixed(2); // => '0.16'
*/
function tTest(x, expectedValue) {
// The mean of the sample
const sampleMean = mean(x);
// The standard deviation of the sample
const sd = standardDeviation(x);
// Square root the length of the sample
const rootN = Math.sqrt(x.length);
// returning the t value
return (sampleMean - expectedValue) / (sd / rootN);
}
export default tTest;
// t_test/sum_nth_power_deviations.js
import mean from "./mean.js";
/**
* The sum of deviations to the Nth power.
* When n=2 it's the sum of squared deviations.
* When n=3 it's the sum of cubed deviations.
*
* @param {Array<number>} x
* @param {number} n power
* @returns {number} sum of nth power deviations
*
* @example
* var input = [1, 2, 3];
* // since the variance of a set is the mean squared
* // deviations, we can calculate that with sumNthPowerDeviations:
* sumNthPowerDeviations(input, 2) / input.length;
*/
function sumNthPowerDeviations(x, n) {
const meanValue = mean(x);
let sum = 0;
let tempValue;
let i;
// This is an optimization: when n is 2 (we're computing a number squared),
// multiplying the number by itself is significantly faster than using
// the Math.pow method.
if (n === 2) {
for (i = 0; i < x.length; i++) {
tempValue = x[i] - meanValue;
sum += tempValue * tempValue;
}
} else {
for (i = 0; i < x.length; i++) {
sum += Math.pow(x[i] - meanValue, n);
}
}
return sum;
}
export default sumNthPowerDeviations;
// t_test/sum.js
/**
* Our default sum is the [Kahan-Babuska algorithm](https://pdfs.semanticscholar.org/1760/7d467cda1d0277ad272deb2113533131dc09.pdf).
* This method is an improvement over the classical
* [Kahan summation algorithm](https://en.wikipedia.org/wiki/Kahan_summation_algorithm).
* It aims at computing the sum of a list of numbers while correcting for
* floating-point errors. Traditionally, sums are calculated as many
* successive additions, each one with its own floating-point roundoff. These
* losses in precision add up as the number of numbers increases. This alternative
* algorithm is more accurate than the simple way of calculating sums by simple
* addition.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x input
* @return {number} sum of all input numbers
* @example
* sum([1, 2, 3]); // => 6
*/
function sum(x) {
// If the array is empty, we needn't bother computing its sum
if (x.length === 0) {
return 0;
}
// Initializing the sum as the first number in the array
let sum = x[0];
// Keeping track of the floating-point error correction
let correction = 0;
let transition;
if (typeof sum !== "number") {
return Number.NaN;
}
for (let i = 1; i < x.length; i++) {
if (typeof x[i] !== "number") {
return Number.NaN;
}
transition = sum + x[i];
// Here we need to update the correction in a different fashion
// if the new absolute value is greater than the absolute sum
if (Math.abs(sum) >= Math.abs(x[i])) {
correction += sum - transition + x[i];
} else {
correction += x[i] - transition + sum;
}
sum = transition;
}
// Returning the corrected sum
return sum + correction;
}
export default sum;
// t_test/mean.js
import sum from "./sum.js";
/**
* The mean, _also known as average_,
* is the sum of all values over the number of values.
* This is a [measure of central tendency](https://en.wikipedia.org/wiki/Central_tendency):
* a method of finding a typical or central value of a set of numbers.
*
* This runs in `O(n)`, linear time, with respect to the length of the array.
*
* @param {Array<number>} x sample of one or more data points
* @throws {Error} if the length of x is less than one
* @returns {number} mean
* @example
* mean([0, 10]); // => 5
*/
function mean(x) {
if (x.length === 0) {
throw new Error("mean requires at least one data point");
}
return sum(x) / x.length;
}
export default mean;
// t_test/variance.js
import sumNthPowerDeviations from "./sum_nth_power_deviations.js";
/**
* The [variance](http://en.wikipedia.org/wiki/Variance)
* is the sum of squared deviations from the mean.
*
* This is an implementation of variance, not sample variance:
* see the `sampleVariance` method if you want a sample measure.
*
* @param {Array<number>} x a population of one or more data points
* @returns {number} variance: a value greater than or equal to zero.
* zero indicates that all values are identical.
* @throws {Error} if x's length is 0
* @example
* variance([1, 2, 3, 4, 5, 6]); // => 2.9166666666666665
*/
function variance(x) {
if (x.length === 0) {
throw new Error("variance requires at least one data point");
}
// Find the mean of squared deviations between the
// mean value and each value.
return sumNthPowerDeviations(x, 2) / x.length;
}
export default variance;
// t_test/standard_deviation.js
import variance from "./variance.js";
/**
* The [standard deviation](http://en.wikipedia.org/wiki/Standard_deviation)
* is the square root of the variance. This is also known as the population
* standard deviation. It's useful for measuring the amount
* of variation or dispersion in a set of values.
*
* Standard deviation is only appropriate for full-population knowledge: for
* samples of a population, {@link sampleStandardDeviation} is
* more appropriate.
*
* @param {Array<number>} x input
* @returns {number} standard deviation
* @example
* variance([2, 4, 4, 4, 5, 5, 7, 9]); // => 4
* standardDeviation([2, 4, 4, 4, 5, 5, 7, 9]); // => 2
*/
function standardDeviation(x) {
if (x.length === 1) {
return 0;
}
const v = variance(x);
return Math.sqrt(v);
}
export default standardDeviation;
| 6 | 213 | JavaScript |
uno | ./ProjectTest/Python/uno.py | '''
uno/player.py
'''
class UnoPlayer:
def __init__(self, player_id, np_random):
''' Initilize a player.
Args:
player_id (int): The id of the player
'''
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.stack = []
def get_player_id(self):
''' Return the id of the player
'''
return self.player_id
'''
uno/dealer.py
'''
from utils import init_deck
class UnoDealer:
''' Initialize a uno dealer class
'''
def __init__(self, np_random):
self.np_random = np_random
self.deck = init_deck()
self.shuffle()
def shuffle(self):
''' Shuffle the deck
'''
self.np_random.shuffle(self.deck)
def deal_cards(self, player, num):
''' Deal some cards from deck to one player
Args:
player (object): The object of DoudizhuPlayer
num (int): The number of cards to be dealed
'''
for _ in range(num):
player.hand.append(self.deck.pop())
def flip_top_card(self):
''' Flip top card when a new game starts
Returns:
(object): The object of UnoCard at the top of the deck
'''
top_card = self.deck.pop()
while top_card.trait == 'wild_draw_4':
self.deck.append(top_card)
self.shuffle()
top_card = self.deck.pop()
return top_card
'''
uno/card.py
'''
from termcolor import colored
class UnoCard:
info = {'type': ['number', 'action', 'wild'],
'color': ['r', 'g', 'b', 'y'],
'trait': ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'skip', 'reverse', 'draw_2', 'wild', 'wild_draw_4']
}
def __init__(self, card_type, color, trait):
''' Initialize the class of UnoCard
Args:
card_type (str): The type of card
color (str): The color of card
trait (str): The trait of card
'''
self.type = card_type
self.color = color
self.trait = trait
self.str = self.get_str()
def get_str(self):
''' Get the string representation of card
Return:
(str): The string of card's color and trait
'''
return self.color + '-' + self.trait
@staticmethod
def print_cards(cards, wild_color=False):
''' Print out card in a nice form
Args:
card (str or list): The string form or a list of a UNO card
wild_color (boolean): True if assign collor to wild cards
'''
if isinstance(cards, str):
cards = [cards]
for i, card in enumerate(cards):
if card == 'draw':
trait = 'Draw'
else:
color, trait = card.split('-')
if trait == 'skip':
trait = 'Skip'
elif trait == 'reverse':
trait = 'Reverse'
elif trait == 'draw_2':
trait = 'Draw-2'
elif trait == 'wild':
trait = 'Wild'
elif trait == 'wild_draw_4':
trait = 'Wild-Draw-4'
if trait == 'Draw' or (trait[:4] == 'Wild' and not wild_color):
print(trait, end='')
elif color == 'r':
print(colored(trait, 'red'), end='')
elif color == 'g':
print(colored(trait, 'green'), end='')
elif color == 'b':
print(colored(trait, 'blue'), end='')
elif color == 'y':
print(colored(trait, 'yellow'), end='')
if i < len(cards) - 1:
print(', ', end='')
'''
uno/judger.py
'''
class UnoJudger:
@staticmethod
def judge_winner(players, np_random):
''' Judge the winner of the game
Args:
players (list): The list of players who play the game
Returns:
(list): The player id of the winner
'''
count_1 = len(players[0].hand)
count_2 = len(players[1].hand)
if count_1 == count_2:
return [0, 1]
if count_1 < count_2:
return [0]
return [1]
'''
uno/game.py
'''
from copy import deepcopy
import numpy as np
from uno import Dealer
from uno import Player
from uno import Round
class UnoGame:
def __init__(self, allow_step_back=False, num_players=2):
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
self.num_players = num_players
self.payoffs = [0 for _ in range(self.num_players)]
def configure(self, game_config):
''' Specifiy some game specific parameters, such as number of players
'''
self.num_players = game_config['game_num_players']
def init_game(self):
''' Initialize players and state
Returns:
(tuple): Tuple containing:
(dict): The first state in one game
(int): Current player's id
'''
# Initalize payoffs
self.payoffs = [0 for _ in range(self.num_players)]
# Initialize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initialize four players to play the game
self.players = [Player(i, self.np_random) for i in range(self.num_players)]
# Deal 7 cards to each player to prepare for the game
for player in self.players:
self.dealer.deal_cards(player, 7)
# Initialize a Round
self.round = Round(self.dealer, self.num_players, self.np_random)
# flip and perfrom top card
top_card = self.round.flip_top_card()
self.round.perform_top_card(self.players, top_card)
# Save the hisory for stepping back to the last state.
self.history = []
player_id = self.round.current_player
state = self.get_state(player_id)
return state, player_id
def step(self, action):
''' Get the next state
Args:
action (str): A specific action
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next plater's id
'''
if self.allow_step_back:
# First snapshot the current state
his_dealer = deepcopy(self.dealer)
his_round = deepcopy(self.round)
his_players = deepcopy(self.players)
self.history.append((his_dealer, his_players, his_round))
self.round.proceed_round(self.players, action)
player_id = self.round.current_player
state = self.get_state(player_id)
return state, player_id
def step_back(self):
''' Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
'''
if not self.history:
return False
self.dealer, self.players, self.round = self.history.pop()
return True
def get_state(self, player_id):
''' Return player's state
Args:
player_id (int): player id
Returns:
(dict): The state of the player
'''
state = self.round.get_state(self.players, player_id)
state['num_players'] = self.get_num_players()
state['current_player'] = self.round.current_player
return state
def get_payoffs(self):
''' Return the payoffs of the game
Returns:
(list): Each entry corresponds to the payoff of one player
'''
winner = self.round.winner
if winner is not None and len(winner) == 1:
self.payoffs[winner[0]] = 1
self.payoffs[1 - winner[0]] = -1
return self.payoffs
def get_legal_actions(self):
''' Return the legal actions for current player
Returns:
(list): A list of legal actions
'''
return self.round.get_legal_actions(self.players, self.round.current_player)
def get_num_players(self):
''' Return the number of players in Limit Texas Hold'em
Returns:
(int): The number of players in the game
'''
return self.num_players
@staticmethod
def get_num_actions():
''' Return the number of applicable actions
Returns:
(int): The number of actions. There are 61 actions
'''
return 61
def get_player_id(self):
''' Return the current player's id
Returns:
(int): current player's id
'''
return self.round.current_player
def is_over(self):
''' Check if the game is over
Returns:
(boolean): True if the game is over
'''
return self.round.is_over
'''
uno/utils.py
'''
import os
import json
import numpy as np
from collections import OrderedDict
import rlcard
from uno.card import UnoCard as Card
# Read required docs
ROOT_PATH = rlcard.__path__[0]
# a map of abstract action to its index and a list of abstract action
with open(os.path.join(ROOT_PATH, 'games/uno/jsondata/action_space.json'), 'r') as file:
ACTION_SPACE = json.load(file, object_pairs_hook=OrderedDict)
ACTION_LIST = list(ACTION_SPACE.keys())
# a map of color to its index
COLOR_MAP = {'r': 0, 'g': 1, 'b': 2, 'y': 3}
# a map of trait to its index
TRAIT_MAP = {'0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7,
'8': 8, '9': 9, 'skip': 10, 'reverse': 11, 'draw_2': 12,
'wild': 13, 'wild_draw_4': 14}
WILD = ['r-wild', 'g-wild', 'b-wild', 'y-wild']
WILD_DRAW_4 = ['r-wild_draw_4', 'g-wild_draw_4', 'b-wild_draw_4', 'y-wild_draw_4']
def init_deck():
''' Generate uno deck of 108 cards
'''
deck = []
card_info = Card.info
for color in card_info['color']:
# init number cards
for num in card_info['trait'][:10]:
deck.append(Card('number', color, num))
if num != '0':
deck.append(Card('number', color, num))
# init action cards
for action in card_info['trait'][10:13]:
deck.append(Card('action', color, action))
deck.append(Card('action', color, action))
# init wild cards
for wild in card_info['trait'][-2:]:
deck.append(Card('wild', color, wild))
return deck
def cards2list(cards):
''' Get the corresponding string representation of cards
Args:
cards (list): list of UnoCards objects
Returns:
(string): string representation of cards
'''
cards_list = []
for card in cards:
cards_list.append(card.get_str())
return cards_list
def hand2dict(hand):
''' Get the corresponding dict representation of hand
Args:
hand (list): list of string of hand's card
Returns:
(dict): dict of hand
'''
hand_dict = {}
for card in hand:
if card not in hand_dict:
hand_dict[card] = 1
else:
hand_dict[card] += 1
return hand_dict
def encode_hand(plane, hand):
''' Encode hand and represerve it into plane
Args:
plane (array): 3*4*15 numpy array
hand (list): list of string of hand's card
Returns:
(array): 3*4*15 numpy array
'''
# plane = np.zeros((3, 4, 15), dtype=int)
plane[0] = np.ones((4, 15), dtype=int)
hand = hand2dict(hand)
for card, count in hand.items():
card_info = card.split('-')
color = COLOR_MAP[card_info[0]]
trait = TRAIT_MAP[card_info[1]]
if trait >= 13:
if plane[1][0][trait] == 0:
for index in range(4):
plane[0][index][trait] = 0
plane[1][index][trait] = 1
else:
plane[0][color][trait] = 0
plane[count][color][trait] = 1
return plane
def encode_target(plane, target):
''' Encode target and represerve it into plane
Args:
plane (array): 1*4*15 numpy array
target(str): string of target card
Returns:
(array): 1*4*15 numpy array
'''
target_info = target.split('-')
color = COLOR_MAP[target_info[0]]
trait = TRAIT_MAP[target_info[1]]
plane[color][trait] = 1
return plane
'''
uno/__init__.py
'''
from uno.dealer import UnoDealer as Dealer
from uno.judger import UnoJudger as Judger
from uno.player import UnoPlayer as Player
from uno.round import UnoRound as Round
from uno.game import UnoGame as Game
'''
uno/round.py
'''
from card import UnoCard
from utils import cards2list, WILD, WILD_DRAW_4
class UnoRound:
def __init__(self, dealer, num_players, np_random):
''' Initialize the round class
Args:
dealer (object): the object of UnoDealer
num_players (int): the number of players in game
'''
self.np_random = np_random
self.dealer = dealer
self.target = None
self.current_player = 0
self.num_players = num_players
self.direction = 1
self.played_cards = []
self.is_over = False
self.winner = None
def flip_top_card(self):
''' Flip the top card of the card pile
Returns:
(object of UnoCard): the top card in game
'''
top = self.dealer.flip_top_card()
if top.trait == 'wild':
top.color = self.np_random.choice(UnoCard.info['color'])
self.target = top
self.played_cards.append(top)
return top
def perform_top_card(self, players, top_card):
''' Perform the top card
Args:
players (list): list of UnoPlayer objects
top_card (object): object of UnoCard
'''
if top_card.trait == 'skip':
self.current_player = 1
elif top_card.trait == 'reverse':
self.direction = -1
self.current_player = (0 + self.direction) % self.num_players
elif top_card.trait == 'draw_2':
player = players[self.current_player]
self.dealer.deal_cards(player, 2)
def proceed_round(self, players, action):
''' Call other Classes' functions to keep one round running
Args:
player (object): object of UnoPlayer
action (str): string of legal action
'''
if action == 'draw':
self._perform_draw_action(players)
return None
player = players[self.current_player]
card_info = action.split('-')
color = card_info[0]
trait = card_info[1]
# remove corresponding card
remove_index = None
if trait == 'wild' or trait == 'wild_draw_4':
for index, card in enumerate(player.hand):
if trait == card.trait:
card.color = color # update the color of wild card to match the action
remove_index = index
break
else:
for index, card in enumerate(player.hand):
if color == card.color and trait == card.trait:
remove_index = index
break
card = player.hand.pop(remove_index)
if not player.hand:
self.is_over = True
self.winner = [self.current_player]
self.played_cards.append(card)
# perform the number action
if card.type == 'number':
self.current_player = (self.current_player + self.direction) % self.num_players
self.target = card
# perform non-number action
else:
self._preform_non_number_action(players, card)
def get_legal_actions(self, players, player_id):
wild_flag = 0
wild_draw_4_flag = 0
legal_actions = []
wild_4_actions = []
hand = players[player_id].hand
target = self.target
if target.type == 'wild':
for card in hand:
if card.type == 'wild':
if card.trait == 'wild_draw_4':
if wild_draw_4_flag == 0:
wild_draw_4_flag = 1
wild_4_actions.extend(WILD_DRAW_4)
else:
if wild_flag == 0:
wild_flag = 1
legal_actions.extend(WILD)
elif card.color == target.color:
legal_actions.append(card.str)
# target is aciton card or number card
else:
for card in hand:
if card.type == 'wild':
if card.trait == 'wild_draw_4':
if wild_draw_4_flag == 0:
wild_draw_4_flag = 1
wild_4_actions.extend(WILD_DRAW_4)
else:
if wild_flag == 0:
wild_flag = 1
legal_actions.extend(WILD)
elif card.color == target.color or card.trait == target.trait:
legal_actions.append(card.str)
if not legal_actions:
legal_actions = wild_4_actions
if not legal_actions:
legal_actions = ['draw']
return legal_actions
def get_state(self, players, player_id):
''' Get player's state
Args:
players (list): The list of UnoPlayer
player_id (int): The id of the player
'''
state = {}
player = players[player_id]
state['hand'] = cards2list(player.hand)
state['target'] = self.target.str
state['played_cards'] = cards2list(self.played_cards)
state['legal_actions'] = self.get_legal_actions(players, player_id)
state['num_cards'] = []
for player in players:
state['num_cards'].append(len(player.hand))
return state
def replace_deck(self):
''' Add cards have been played to deck
'''
self.dealer.deck.extend(self.played_cards)
self.dealer.shuffle()
self.played_cards = []
def _perform_draw_action(self, players):
# replace deck if there is no card in draw pile
if not self.dealer.deck:
self.replace_deck()
#self.is_over = True
#self.winner = UnoJudger.judge_winner(players)
#return None
card = self.dealer.deck.pop()
# draw a wild card
if card.type == 'wild':
card.color = self.np_random.choice(UnoCard.info['color'])
self.target = card
self.played_cards.append(card)
self.current_player = (self.current_player + self.direction) % self.num_players
# draw a card with the same color of target
elif card.color == self.target.color:
if card.type == 'number':
self.target = card
self.played_cards.append(card)
self.current_player = (self.current_player + self.direction) % self.num_players
else:
self.played_cards.append(card)
self._preform_non_number_action(players, card)
# draw a card with the diffrent color of target
else:
players[self.current_player].hand.append(card)
self.current_player = (self.current_player + self.direction) % self.num_players
def _preform_non_number_action(self, players, card):
current = self.current_player
direction = self.direction
num_players = self.num_players
# perform reverse card
if card.trait == 'reverse':
self.direction = -1 * direction
# perfrom skip card
elif card.trait == 'skip':
current = (current + direction) % num_players
# perform draw_2 card
elif card.trait == 'draw_2':
if len(self.dealer.deck) < 2:
self.replace_deck()
#self.is_over = True
#self.winner = UnoJudger.judge_winner(players)
#return None
self.dealer.deal_cards(players[(current + direction) % num_players], 2)
current = (current + direction) % num_players
# perfrom wild_draw_4 card
elif card.trait == 'wild_draw_4':
if len(self.dealer.deck) < 4:
self.replace_deck()
#self.is_over = True
#self.winner = UnoJudger.judge_winner(players)
#return None
self.dealer.deal_cards(players[(current + direction) % num_players], 4)
current = (current + direction) % num_players
self.current_player = (current + self.direction) % num_players
self.target = card
| 8 | 669 | Python |
tree | ./ProjectTest/Python/tree.py | '''
tree/base.py
'''
# coding:utf-8
import numpy as np
from scipy import stats
def f_entropy(p):
# Convert values to probability
p = np.bincount(p) / float(p.shape[0])
ep = stats.entropy(p)
if ep == -float("inf"):
return 0.0
return ep
def information_gain(y, splits):
splits_entropy = sum([f_entropy(split) * (float(split.shape[0]) / y.shape[0]) for split in splits])
return f_entropy(y) - splits_entropy
def mse_criterion(y, splits):
y_mean = np.mean(y)
return -sum([np.sum((split - y_mean) ** 2) * (float(split.shape[0]) / y.shape[0]) for split in splits])
def xgb_criterion(y, left, right, loss):
left = loss.gain(left["actual"], left["y_pred"])
right = loss.gain(right["actual"], right["y_pred"])
initial = loss.gain(y["actual"], y["y_pred"])
gain = left + right - initial
return gain
def get_split_mask(X, column, value):
left_mask = X[:, column] < value
right_mask = X[:, column] >= value
return left_mask, right_mask
def split(X, y, value):
left_mask = X < value
right_mask = X >= value
return y[left_mask], y[right_mask]
def split_dataset(X, target, column, value, return_X=True):
left_mask, right_mask = get_split_mask(X, column, value)
left, right = {}, {}
for key in target.keys():
left[key] = target[key][left_mask]
right[key] = target[key][right_mask]
if return_X:
left_X, right_X = X[left_mask], X[right_mask]
return left_X, right_X, left, right
else:
return left, right
'''
tree/tree.py
'''
# coding:utf-8
import random
import numpy as np
from scipy import stats
from base import split, split_dataset, xgb_criterion
random.seed(111)
class Tree(object):
"""Recursive implementation of decision tree."""
def __init__(self, regression=False, criterion=None, n_classes=None):
self.regression = regression
self.impurity = None
self.threshold = None
self.column_index = None
self.outcome = None
self.criterion = criterion
self.loss = None
self.n_classes = n_classes # Only for classification
self.left_child = None
self.right_child = None
@property
def is_terminal(self):
return not bool(self.left_child and self.right_child)
def _find_splits(self, X):
"""Find all possible split values."""
split_values = set()
# Get unique values in a sorted order
x_unique = list(np.unique(X))
for i in range(1, len(x_unique)):
# Find a point between two values
average = (x_unique[i - 1] + x_unique[i]) / 2.0
split_values.add(average)
return list(split_values)
def _find_best_split(self, X, target, n_features):
"""Find best feature and value for a split. Greedy algorithm."""
# Sample random subset of features
subset = random.sample(list(range(0, X.shape[1])), n_features)
max_gain, max_col, max_val = None, None, None
for column in subset:
split_values = self._find_splits(X[:, column])
for value in split_values:
if self.loss is None:
# Random forest
splits = split(X[:, column], target["y"], value)
gain = self.criterion(target["y"], splits)
else:
# Gradient boosting
left, right = split_dataset(X, target, column, value, return_X=False)
gain = xgb_criterion(target, left, right, self.loss)
if (max_gain is None) or (gain > max_gain):
max_col, max_val, max_gain = column, value, gain
return max_col, max_val, max_gain
def _train(self, X, target, max_features=None, min_samples_split=10, max_depth=None, minimum_gain=0.01):
try:
# Exit from recursion using assert syntax
assert X.shape[0] > min_samples_split
assert max_depth > 0
if max_features is None:
max_features = X.shape[1]
column, value, gain = self._find_best_split(X, target, max_features)
assert gain is not None
if self.regression:
assert gain != 0
else:
assert gain > minimum_gain
self.column_index = column
self.threshold = value
self.impurity = gain
# Split dataset
left_X, right_X, left_target, right_target = split_dataset(X, target, column, value)
# Grow left and right child
self.left_child = Tree(self.regression, self.criterion, self.n_classes)
self.left_child._train(
left_X, left_target, max_features, min_samples_split, max_depth - 1, minimum_gain
)
self.right_child = Tree(self.regression, self.criterion, self.n_classes)
self.right_child._train(
right_X, right_target, max_features, min_samples_split, max_depth - 1, minimum_gain
)
except AssertionError:
self._calculate_leaf_value(target)
def train(self, X, target, max_features=None, min_samples_split=10, max_depth=None, minimum_gain=0.01, loss=None):
"""Build a decision tree from training set.
Parameters
----------
X : array-like
Feature dataset.
target : dictionary or array-like
Target values.
max_features : int or None
The number of features to consider when looking for the best split.
min_samples_split : int
The minimum number of samples required to split an internal node.
max_depth : int
Maximum depth of the tree.
minimum_gain : float, default 0.01
Minimum gain required for splitting.
loss : function, default None
Loss function for gradient boosting.
"""
if not isinstance(target, dict):
target = {"y": target}
# Loss for gradient boosting
if loss is not None:
self.loss = loss
if not self.regression:
self.n_classes = len(np.unique(target['y']))
self._train(X, target, max_features=max_features, min_samples_split=min_samples_split,
max_depth=max_depth, minimum_gain=minimum_gain)
def _calculate_leaf_value(self, targets):
"""Find optimal value for leaf."""
if self.loss is not None:
# Gradient boosting
self.outcome = self.loss.approximate(targets["actual"], targets["y_pred"])
else:
# Random Forest
if self.regression:
# Mean value for regression task
self.outcome = np.mean(targets["y"])
else:
# Probability for classification task
self.outcome = np.bincount(targets["y"], minlength=self.n_classes) / targets["y"].shape[0]
def predict_row(self, row):
"""Predict single row."""
if not self.is_terminal:
if row[self.column_index] < self.threshold:
return self.left_child.predict_row(row)
else:
return self.right_child.predict_row(row)
return self.outcome
def predict(self, X):
result = np.zeros(X.shape[0])
for i in range(X.shape[0]):
result[i] = self.predict_row(X[i, :])
return result
| 2 | 225 | Python |
mahjong | ./ProjectTest/Python/mahjong.py | '''
mahjong/player.py
'''
class MahjongPlayer:
def __init__(self, player_id, np_random):
''' Initilize a player.
Args:
player_id (int): The id of the player
'''
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.pile = []
def get_player_id(self):
''' Return the id of the player
'''
return self.player_id
def print_hand(self):
''' Print the cards in hand in string.
'''
print([c.get_str() for c in self.hand])
def print_pile(self):
''' Print the cards in pile of the player in string.
'''
print([[c.get_str() for c in s]for s in self.pile])
def play_card(self, dealer, card):
''' Play one card
Args:
dealer (object): Dealer
Card (object): The card to be play.
'''
card = self.hand.pop(self.hand.index(card))
dealer.table.append(card)
def chow(self, dealer, cards):
''' Perform Chow
Args:
dealer (object): Dealer
Cards (object): The cards to be Chow.
'''
last_card = dealer.table.pop(-1)
for card in cards:
if card in self.hand and card != last_card:
self.hand.pop(self.hand.index(card))
self.pile.append(cards)
def gong(self, dealer, cards):
''' Perform Gong
Args:
dealer (object): Dealer
Cards (object): The cards to be Gong.
'''
for card in cards:
if card in self.hand:
self.hand.pop(self.hand.index(card))
self.pile.append(cards)
def pong(self, dealer, cards):
''' Perform Pong
Args:
dealer (object): Dealer
Cards (object): The cards to be Pong.
'''
for card in cards:
if card in self.hand:
self.hand.pop(self.hand.index(card))
self.pile.append(cards)
'''
mahjong/dealer.py
'''
from utils import init_deck
class MahjongDealer:
''' Initialize a mahjong dealer class
'''
def __init__(self, np_random):
self.np_random = np_random
self.deck = init_deck()
self.shuffle()
self.table = []
def shuffle(self):
''' Shuffle the deck
'''
self.np_random.shuffle(self.deck)
def deal_cards(self, player, num):
''' Deal some cards from deck to one player
Args:
player (object): The object of DoudizhuPlayer
num (int): The number of cards to be dealed
'''
for _ in range(num):
player.hand.append(self.deck.pop())
## For test
'''
mahjong/card.py
'''
class MahjongCard:
info = {'type': ['dots', 'bamboo', 'characters', 'dragons', 'winds'],
'trait': ['1', '2', '3', '4', '5', '6', '7', '8', '9', 'green', 'red', 'white', 'east', 'west', 'north', 'south']
}
def __init__(self, card_type, trait):
''' Initialize the class of MahjongCard
Args:
card_type (str): The type of card
trait (str): The trait of card
'''
self.type = card_type
self.trait = trait
self.index_num = 0
def get_str(self):
''' Get the string representation of card
Return:
(str): The string of card's color and trait
'''
return self.type+ '-'+ self.trait
def set_index_num(self, index_num):
self.index_num = index_num
'''
mahjong/judger.py
'''
# -*- coding: utf-8 -*-
''' Implement Mahjong Judger class
'''
from collections import defaultdict
import numpy as np
class MahjongJudger:
''' Determine what cards a player can play
'''
def __init__(self, np_random):
''' Initilize the Judger class for Mahjong
'''
self.np_random = np_random
@staticmethod
def judge_pong_gong(dealer, players, last_player):
''' Judge which player has pong/gong
Args:
dealer (object): The dealer object.
players (list): List of all players
last_player (int): The player id of last player
'''
last_card = dealer.table[-1]
last_card_str = last_card.get_str()
#last_card_value = last_card_str.split("-")[-1]
#last_card_type = last_card_str.split("-")[0]
for player in players:
hand = [card.get_str() for card in player.hand]
hand_dict = defaultdict(list)
for card in hand:
hand_dict[card.split("-")[0]].append(card.split("-")[1])
#pile = player.pile
# check gong
if hand.count(last_card_str) == 3 and last_player != player.player_id:
return 'gong', player, [last_card]*4
# check pong
if hand.count(last_card_str) == 2 and last_player != player.player_id:
return 'pong', player, [last_card]*3
return False, None, None
def judge_chow(self, dealer, players, last_player):
''' Judge which player has chow
Args:
dealer (object): The dealer object.
players (list): List of all players
last_player (int): The player id of last player
'''
last_card = dealer.table[-1]
last_card_str = last_card.get_str()
last_card_type = last_card_str.split("-")[0]
last_card_index = last_card.index_num
for player in players:
if last_card_type != "dragons" and last_card_type != "winds" and last_player == player.get_player_id() - 1:
# Create 9 dimensional vector where each dimension represent a specific card with the type same as last_card_type
# Numbers in each dimension represent how many of that card the player has it in hand
# If the last_card_type is 'characters' for example, and the player has cards: characters_3, characters_6, characters_3,
# The hand_list vector looks like: [0,0,2,0,0,1,0,0,0]
hand_list = np.zeros(9)
for card in player.hand:
if card.get_str().split("-")[0] == last_card_type:
hand_list[card.index_num] = hand_list[card.index_num]+1
#pile = player.pile
#check chow
test_cases = []
if last_card_index == 0:
if hand_list[last_card_index+1] > 0 and hand_list[last_card_index+2] > 0:
test_cases.append([last_card_index+1, last_card_index+2])
elif last_card_index < 9:
if hand_list[last_card_index-2] > 0 and hand_list[last_card_index-1] > 0:
test_cases.append([last_card_index-2, last_card_index-1])
else:
if hand_list[last_card_index-1] > 0 and hand_list[last_card_index+1] > 0:
test_cases.append([last_card_index-1, last_card_index+1])
if not test_cases:
continue
for l in test_cases:
cards = []
for i in l:
for card in player.hand:
if card.index_num == i and card.get_str().split("-")[0] == last_card_type:
cards.append(card)
break
cards.append(last_card)
return 'chow', player, cards
return False, None, None
def judge_game(self, game):
''' Judge which player has win the game
Args:
dealer (object): The dealer object.
players (list): List of all players
last_player (int): The player id of last player
'''
players_val = []
win_player = -1
for player in game.players:
win, val = self.judge_hu(player)
players_val.append(val)
if win:
win_player = player.player_id
if win_player != -1 or len(game.dealer.deck) == 0:
return True, win_player, players_val
else:
#player_id = players_val.index(max(players_val))
return False, win_player, players_val
def judge_hu(self, player):
''' Judge whether the player has win the game
Args:
player (object): Target player
Return:
Result (bool): Win or not
Maximum_score (int): Set count score of the player
'''
set_count = 0
hand = [card.get_str() for card in player.hand]
count_dict = {card: hand.count(card) for card in hand}
set_count = len(player.pile)
if set_count >= 4:
return True, set_count
used = []
maximum = 0
for each in count_dict:
if each in used:
continue
tmp_set_count = 0
tmp_hand = hand.copy()
if count_dict[each] == 2:
for _ in range(count_dict[each]):
tmp_hand.pop(tmp_hand.index(each))
tmp_set_count, _set = self.cal_set(tmp_hand)
used.extend(_set)
if tmp_set_count + set_count > maximum:
maximum = tmp_set_count + set_count
if tmp_set_count + set_count >= 4:
#print(player.get_player_id(), sorted([card.get_str() for card in player.hand]))
#print([[c.get_str() for c in s] for s in player.pile])
#print(len(player.hand), sum([len(s) for s in player.pile]))
#exit()
return True, maximum
return False, maximum
@staticmethod
def check_consecutive(_list):
''' Check if list is consecutive
Args:
_list (list): The target list
Return:
Result (bool): consecutive or not
'''
l = list(map(int, _list))
if sorted(l) == list(range(min(l), max(l)+1)):
return True
return False
def cal_set(self, cards):
''' Calculate the set for given cards
Args:
Cards (list): List of cards.
Return:
Set_count (int):
Sets (list): List of cards that has been pop from user's hand
'''
tmp_cards = cards.copy()
sets = []
set_count = 0
_dict = {card: tmp_cards.count(card) for card in tmp_cards}
# check pong/gang
for each in _dict:
if _dict[each] == 3 or _dict[each] == 4:
set_count += 1
for _ in range(_dict[each]):
tmp_cards.pop(tmp_cards.index(each))
# get all of the traits of each type in hand (except dragons and winds)
_dict_by_type = defaultdict(list)
for card in tmp_cards:
_type = card.split("-")[0]
_trait = card.split("-")[1]
if _type == 'dragons' or _type == 'winds':
continue
else:
_dict_by_type[_type].append(_trait)
for _type in _dict_by_type.keys():
values = sorted(_dict_by_type[_type])
if len(values) > 2:
for index, _ in enumerate(values):
if index == 0:
test_case = [values[index], values[index+1], values[index+2]]
elif index == len(values)-1:
test_case = [values[index-2], values[index-1], values[index]]
else:
test_case = [values[index-1], values[index], values[index+1]]
if self.check_consecutive(test_case):
set_count += 1
for each in test_case:
values.pop(values.index(each))
c = _type+"-"+str(each)
sets.append(c)
if c in tmp_cards:
tmp_cards.pop(tmp_cards.index(c))
return set_count, sets
'''
mahjong/game.py
'''
import numpy as np
from copy import deepcopy
from mahjong import Dealer
from mahjong import Player
from mahjong import Round
from mahjong import Judger
class MahjongGame:
def __init__(self, allow_step_back=False):
'''Initialize the class MajongGame
'''
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
self.num_players = 4
def init_game(self):
''' Initialilze the game of Mahjong
This version supports two-player Mahjong
Returns:
(tuple): Tuple containing:
(dict): The first state of the game
(int): Current player's id
'''
# Initialize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initialize four players to play the game
self.players = [Player(i, self.np_random) for i in range(self.num_players)]
self.judger = Judger(self.np_random)
self.round = Round(self.judger, self.dealer, self.num_players, self.np_random)
# Deal 13 cards to each player to prepare for the game
for player in self.players:
self.dealer.deal_cards(player, 13)
# Save the hisory for stepping back to the last state.
self.history = []
self.dealer.deal_cards(self.players[self.round.current_player], 1)
state = self.get_state(self.round.current_player)
self.cur_state = state
return state, self.round.current_player
def step(self, action):
''' Get the next state
Args:
action (str): a specific action. (call, raise, fold, or check)
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next plater's id
'''
# First snapshot the current state
if self.allow_step_back:
hist_dealer = deepcopy(self.dealer)
hist_round = deepcopy(self.round)
hist_players = deepcopy(self.players)
self.history.append((hist_dealer, hist_players, hist_round))
self.round.proceed_round(self.players, action)
state = self.get_state(self.round.current_player)
self.cur_state = state
return state, self.round.current_player
def step_back(self):
''' Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
'''
if not self.history:
return False
self.dealer, self.players, self.round = self.history.pop()
return True
def get_state(self, player_id):
''' Return player's state
Args:
player_id (int): player id
Returns:
(dict): The state of the player
'''
state = self.round.get_state(self.players, player_id)
return state
@staticmethod
def get_legal_actions(state):
''' Return the legal actions for current player
Returns:
(list): A list of legal actions
'''
if state['valid_act'] == ['play']:
state['valid_act'] = state['action_cards']
return state['action_cards']
else:
return state['valid_act']
@staticmethod
def get_num_actions():
''' Return the number of applicable actions
Returns:
(int): The number of actions. There are 4 actions (call, raise, check and fold)
'''
return 38
def get_num_players(self):
''' return the number of players in Mahjong
returns:
(int): the number of players in the game
'''
return self.num_players
def get_player_id(self):
''' return the id of current player in Mahjong
returns:
(int): the number of players in the game
'''
return self.round.current_player
def is_over(self):
''' Check if the game is over
Returns:
(boolean): True if the game is over
'''
win, player, _ = self.judger.judge_game(self)
#pile =[sorted([c.get_str() for c in s ]) for s in self.players[player].pile if self.players[player].pile != None]
#cards = sorted([c.get_str() for c in self.players[player].hand])
#count = len(cards) + sum([len(p) for p in pile])
self.winner = player
#print(win, player, players_val)
#print(win, self.round.current_player, player, cards, pile, count)
return win
'''
mahjong/utils.py
'''
import numpy as np
from card import MahjongCard as Card
card_encoding_dict = {}
num = 0
for _type in ['bamboo', 'characters', 'dots']:
for _trait in ['1', '2', '3', '4', '5', '6', '7', '8', '9']:
card = _type+"-"+_trait
card_encoding_dict[card] = num
num += 1
for _trait in ['green', 'red', 'white']:
card = 'dragons-'+_trait
card_encoding_dict[card] = num
num += 1
for _trait in ['east', 'west', 'north', 'south']:
card = 'winds-'+_trait
card_encoding_dict[card] = num
num += 1
card_encoding_dict['pong'] = num
card_encoding_dict['chow'] = num + 1
card_encoding_dict['gong'] = num + 2
card_encoding_dict['stand'] = num + 3
card_decoding_dict = {card_encoding_dict[key]: key for key in card_encoding_dict.keys()}
def init_deck():
deck = []
info = Card.info
for _type in info['type']:
index_num = 0
if _type != 'dragons' and _type != 'winds':
for _trait in info['trait'][:9]:
card = Card(_type, _trait)
card.set_index_num(index_num)
index_num = index_num + 1
deck.append(card)
elif _type == 'dragons':
for _trait in info['trait'][9:12]:
card = Card(_type, _trait)
card.set_index_num(index_num)
index_num = index_num + 1
deck.append(card)
else:
for _trait in info['trait'][12:]:
card = Card(_type, _trait)
card.set_index_num(index_num)
index_num = index_num + 1
deck.append(card)
deck = deck * 4
return deck
def pile2list(pile):
cards_list = []
for each in pile:
cards_list.extend(each)
return cards_list
def cards2list(cards):
cards_list = []
for each in cards:
cards_list.append(each.get_str())
return cards_list
def encode_cards(cards):
plane = np.zeros((34,4), dtype=int)
cards = cards2list(cards)
for card in list(set(cards)):
index = card_encoding_dict[card]
num = cards.count(card)
plane[index][:num] = 1
return plane
'''
mahjong/__init__.py
'''
from mahjong.dealer import MahjongDealer as Dealer
from mahjong.card import MahjongCard as Card
from mahjong.player import MahjongPlayer as Player
from mahjong.judger import MahjongJudger as Judger
from mahjong.round import MahjongRound as Round
from mahjong.game import MahjongGame as Game
'''
mahjong/round.py
'''
class MahjongRound:
def __init__(self, judger, dealer, num_players, np_random):
''' Initialize the round class
Args:
judger (object): the object of MahjongJudger
dealer (object): the object of MahjongDealer
num_players (int): the number of players in game
'''
self.np_random = np_random
self.judger = judger
self.dealer = dealer
self.target = None
self.current_player = 0
self.last_player = None
self.num_players = num_players
self.direction = 1
self.played_cards = []
self.is_over = False
self.player_before_act = 0
self.prev_status = None
self.valid_act = False
self.last_cards = []
def proceed_round(self, players, action):
''' Call other Classes's functions to keep one round running
Args:
player (object): object of UnoPlayer
action (str): string of legal action
'''
#hand_len = [len(p.hand) for p in players]
#pile_len = [sum([len([c for c in p]) for p in pp.pile]) for pp in players]
#total_len = [i + j for i, j in zip(hand_len, pile_len)]
if action == 'stand':
(valid_act, player, cards) = self.judger.judge_chow(self.dealer, players, self.last_player)
if valid_act:
self.valid_act = valid_act
self.last_cards = cards
self.last_player = self.current_player
self.current_player = player.player_id
else:
self.last_player = self.current_player
self.current_player = (self.player_before_act + 1) % 4
self.dealer.deal_cards(players[self.current_player], 1)
self.valid_act = False
elif action == 'gong':
players[self.current_player].gong(self.dealer, self.last_cards)
self.last_player = self.current_player
self.valid_act = False
elif action == 'pong':
players[self.current_player].pong(self.dealer, self.last_cards)
self.last_player = self.current_player
self.valid_act = False
elif action == 'chow':
players[self.current_player].chow(self.dealer, self.last_cards)
self.last_player = self.current_player
self.valid_act = False
else: # Play game: Proceed to next player
players[self.current_player].play_card(self.dealer, action)
self.player_before_act = self.current_player
self.last_player = self.current_player
(valid_act, player, cards) = self.judger.judge_pong_gong(self.dealer, players, self.last_player)
if valid_act:
self.valid_act = valid_act
self.last_cards = cards
self.last_player = self.current_player
self.current_player = player.player_id
else:
self.last_player = self.current_player
self.current_player = (self.current_player + 1) % 4
self.dealer.deal_cards(players[self.current_player], 1)
#hand_len = [len(p.hand) for p in players]
#pile_len = [sum([len([c for c in p]) for p in pp.pile]) for pp in players]
#total_len = [i + j for i, j in zip(hand_len, pile_len)]
def get_state(self, players, player_id):
''' Get player's state
Args:
players (list): The list of MahjongPlayer
player_id (int): The id of the player
Return:
state (dict): The information of the state
'''
state = {}
#(valid_act, player, cards) = self.judger.judge_pong_gong(self.dealer, players, self.last_player)
if self.valid_act: # PONG/GONG/CHOW
state['valid_act'] = [self.valid_act, 'stand']
state['table'] = self.dealer.table
state['player'] = self.current_player
state['current_hand'] = players[self.current_player].hand
state['players_pile'] = {p.player_id: p.pile for p in players}
state['action_cards'] = self.last_cards # For doing action (pong, chow, gong)
else: # Regular Play
state['valid_act'] = ['play']
state['table'] = self.dealer.table
state['player'] = self.current_player
state['current_hand'] = players[player_id].hand
state['players_pile'] = {p.player_id: p.pile for p in players}
state['action_cards'] = players[player_id].hand # For doing action (pong, chow, gong)
return state
| 8 | 703 | Python |
thefuzz | ./ProjectTest/Python/thefuzz.py | '''
thefuzz/fuzz.py
'''
#!/usr/bin/env python
from rapidfuzz.fuzz import (
ratio as _ratio,
partial_ratio as _partial_ratio,
token_set_ratio as _token_set_ratio,
token_sort_ratio as _token_sort_ratio,
partial_token_set_ratio as _partial_token_set_ratio,
partial_token_sort_ratio as _partial_token_sort_ratio,
WRatio as _WRatio,
QRatio as _QRatio,
)
import utils
###########################
# Basic Scoring Functions #
###########################
def _rapidfuzz_scorer(scorer, s1, s2, force_ascii, full_process):
"""
wrapper around rapidfuzz function to be compatible with the API of thefuzz
"""
if full_process:
if s1 is None or s2 is None:
return 0
s1 = utils.full_process(s1, force_ascii=force_ascii)
s2 = utils.full_process(s2, force_ascii=force_ascii)
return int(round(scorer(s1, s2)))
def ratio(s1, s2):
return _rapidfuzz_scorer(_ratio, s1, s2, False, False)
def partial_ratio(s1, s2):
"""
Return the ratio of the most similar substring
as a number between 0 and 100.
"""
return _rapidfuzz_scorer(_partial_ratio, s1, s2, False, False)
##############################
# Advanced Scoring Functions #
##############################
# Sorted Token
# find all alphanumeric tokens in the string
# sort those tokens and take ratio of resulting joined strings
# controls for unordered string elements
def token_sort_ratio(s1, s2, force_ascii=True, full_process=True):
"""
Return a measure of the sequences' similarity between 0 and 100
but sorting the token before comparing.
"""
return _rapidfuzz_scorer(_token_sort_ratio, s1, s2, force_ascii, full_process)
def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True):
"""
Return the ratio of the most similar substring as a number between
0 and 100 but sorting the token before comparing.
"""
return _rapidfuzz_scorer(
_partial_token_sort_ratio, s1, s2, force_ascii, full_process
)
def token_set_ratio(s1, s2, force_ascii=True, full_process=True):
return _rapidfuzz_scorer(_token_set_ratio, s1, s2, force_ascii, full_process)
def partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True):
return _rapidfuzz_scorer(
_partial_token_set_ratio, s1, s2, force_ascii, full_process
)
###################
# Combination API #
###################
# q is for quick
def QRatio(s1, s2, force_ascii=True, full_process=True):
"""
Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (Default: True)
:full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)
:return: similarity ratio
"""
return _rapidfuzz_scorer(_QRatio, s1, s2, force_ascii, full_process)
def UQRatio(s1, s2, full_process=True):
"""
Unicode quick ratio
Calls QRatio with force_ascii set to False
:param s1:
:param s2:
:return: similarity ratio
"""
return QRatio(s1, s2, force_ascii=False, full_process=full_process)
# w is for weighted
def WRatio(s1, s2, force_ascii=True, full_process=True):
"""
Return a measure of the sequences' similarity between 0 and 100, using different algorithms.
**Steps in the order they occur**
#. Run full_process from utils on both strings
#. Short circuit if this makes either string empty
#. Take the ratio of the two processed strings (fuzz.ratio)
#. Run checks to compare the length of the strings
* If one of the strings is more than 1.5 times as long as the other
use partial_ratio comparisons - scale partial results by 0.9
(this makes sure only full results can return 100)
* If one of the strings is over 8 times as long as the other
instead scale by 0.6
#. Run the other ratio functions
* if using partial ratio functions call partial_ratio,
partial_token_sort_ratio and partial_token_set_ratio
scale all of these by the ratio based on length
* otherwise call token_sort_ratio and token_set_ratio
* all token based comparisons are scaled by 0.95
(on top of any partial scalars)
#. Take the highest value from these results
round it and return it as an integer.
:param s1:
:param s2:
:param force_ascii: Allow only ascii characters
:type force_ascii: bool
:full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)
:return:
"""
return _rapidfuzz_scorer(_WRatio, s1, s2, force_ascii, full_process)
def UWRatio(s1, s2, full_process=True):
"""
Return a measure of the sequences' similarity between 0 and 100,
using different algorithms. Same as WRatio but preserving unicode.
"""
return WRatio(s1, s2, force_ascii=False, full_process=full_process)
'''
thefuzz/utils.py
'''
from rapidfuzz.utils import default_process as _default_process
translation_table = {i: None for i in range(128, 256)} # ascii dammit!
def ascii_only(s):
return s.translate(translation_table)
def full_process(s, force_ascii=False):
"""
Process string by
-- removing all but letters and numbers
-- trim whitespace
-- force to lower case
if force_ascii == True, force convert to ascii
"""
if force_ascii:
s = ascii_only(str(s))
return _default_process(s)
'''
thefuzz/__init__.py
'''
__version__ = '0.22.1'
| 3 | 183 | Python |
nolimitholdem | ./ProjectTest/Python/nolimitholdem.py | '''
nolimitholdem/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
nolimitholdem/player.py
'''
from enum import Enum
class PlayerStatus(Enum):
ALIVE = 0
FOLDED = 1
ALLIN = 2
class LimitHoldemPlayer:
def __init__(self, player_id, np_random):
"""
Initialize a player.
Args:
player_id (int): The id of the player
"""
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.status = PlayerStatus.ALIVE
# The chips that this player has put in until now
self.in_chips = 0
def get_state(self, public_cards, all_chips, legal_actions):
"""
Encode the state for the player
Args:
public_cards (list): A list of public cards that seen by all the players
all_chips (int): The chips that all players have put in
Returns:
(dict): The state of the player
"""
return {
'hand': [c.get_index() for c in self.hand],
'public_cards': [c.get_index() for c in public_cards],
'all_chips': all_chips,
'my_chips': self.in_chips,
'legal_actions': legal_actions
}
def get_player_id(self):
return self.player_id
class NolimitholdemPlayer(LimitHoldemPlayer):
def __init__(self, player_id, init_chips, np_random):
"""
Initialize a player.
Args:
player_id (int): The id of the player
init_chips (int): The number of chips the player has initially
"""
super().__init__(player_id, np_random)
self.remained_chips = init_chips
def bet(self, chips):
quantity = chips if chips <= self.remained_chips else self.remained_chips
self.in_chips += quantity
self.remained_chips -= quantity
'''
nolimitholdem/dealer.py
'''
from nolimitholdem.utils import init_standard_deck
class NolimitholdemDealer:
def __init__(self, np_random):
self.np_random = np_random
self.deck = init_standard_deck()
self.shuffle()
self.pot = 0
def shuffle(self):
self.np_random.shuffle(self.deck)
def deal_card(self):
"""
Deal one card from the deck
Returns:
(Card): The drawn card from the deck
"""
return self.deck.pop()
'''
nolimitholdem/judger.py
'''
from nolimitholdem.utils import compare_hands
import numpy as np
class NolimitholdemJudger:
"""The Judger class for limit texas holdem"""
def __init__(self, np_random):
self.np_random = np_random
def judge_game(self, players, hands):
"""
Judge the winner of the game.
Args:
players (list): The list of players who play the game
hands (list): The list of hands that from the players
Returns:
(list): Each entry of the list corresponds to one entry of the
"""
# Convert the hands into card indexes
hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands]
in_chips = [p.in_chips for p in players]
remaining = sum(in_chips)
payoffs = [0] * len(hands)
while remaining > 0:
winners = compare_hands(hands)
each_win = self.split_pots_among_players(in_chips, winners)
for i in range(len(players)):
if winners[i]:
remaining -= each_win[i]
payoffs[i] += each_win[i] - in_chips[i]
hands[i] = None
in_chips[i] = 0
elif in_chips[i] > 0:
payoffs[i] += each_win[i] - in_chips[i]
in_chips[i] = each_win[i]
assert sum(payoffs) == 0
return payoffs
def split_pot_among_players(self, in_chips, winners):
"""
Splits the next (side) pot among players.
Function is called in loop by distribute_pots_among_players until all chips are allocated.
Args:
in_chips (list): List with number of chips bet not yet distributed for each player
winners (list): List with 1 if the player is among winners else 0
Returns:
(list): Of how much chips each player get after this pot has been split and list of chips left to distribute
"""
nb_winners_in_pot = sum((winners[i] and in_chips[i] > 0) for i in range(len(in_chips)))
nb_players_in_pot = sum(in_chips[i] > 0 for i in range(len(in_chips)))
if nb_winners_in_pot == 0 or nb_winners_in_pot == nb_players_in_pot:
# no winner or all winners for this pot
allocated = list(in_chips) # we give back their chips to each players in this pot
in_chips_after = len(in_chips) * [0] # no more chips to distribute
else:
amount_in_pot_by_player = min(v for v in in_chips if v > 0)
how_much_one_win, remaining = divmod(amount_in_pot_by_player * nb_players_in_pot, nb_winners_in_pot)
'''
In the event of a split pot that cannot be divided equally for every winner, the winner who is sitting
closest to the left of the dealer receives the remaining differential in chips cf
https://www.betclic.fr/poker/house-rules--play-safely--betclic-poker-cpok_rules to simplify and as this
case is very rare, we will give the remaining differential in chips to a random winner
'''
allocated = len(in_chips) * [0]
in_chips_after = list(in_chips)
for i in range(len(in_chips)): # iterate on all players
if in_chips[i] == 0: # player not in pot
continue
if winners[i]:
allocated[i] += how_much_one_win
in_chips_after[i] -= amount_in_pot_by_player
if remaining > 0:
random_winning_player = self.np_random.choice(
[i for i in range(len(winners)) if winners[i] and in_chips[i] > 0])
allocated[random_winning_player] += remaining
assert sum(in_chips[i] - in_chips_after[i] for i in range(len(in_chips))) == sum(allocated)
return allocated, in_chips_after
def split_pots_among_players(self, in_chips_initial, winners):
"""
Splits main pot and side pots among players (to handle special case of all-in players).
Args:
in_chips_initial (list): List with number of chips bet for each player
winners (list): List with 1 if the player is among winners else 0
Returns:
(list): List of how much chips each player get back after all pots have been split
"""
in_chips = list(in_chips_initial)
assert len(in_chips) == len(winners)
assert all(v == 0 or v == 1 for v in winners)
assert sum(winners) >= 1 # there must be at least one winner
allocated = np.zeros(len(in_chips), dtype=int)
while any(v > 0 for v in in_chips): # while there are still chips to allocate
allocated_current_pot, in_chips = self.split_pot_among_players(in_chips, winners)
allocated += allocated_current_pot # element-wise addition
assert all(chips >= 0 for chips in allocated) # check that all players got a non negative amount of chips
assert sum(in_chips_initial) == sum(allocated) # check that all chips bet have been allocated
return list(allocated)
'''
nolimitholdem/game.py
'''
from enum import Enum
import numpy as np
from copy import deepcopy
from nolimitholdem import PlayerStatus
from nolimitholdem import Dealer
from nolimitholdem import Player
from nolimitholdem import Judger
from nolimitholdem import Round, Action
from copy import deepcopy, copy
# import numpy as np
# from limitholdem import Dealer
# from limitholdem import Player, PlayerStatus
# from limitholdem import Judger
# from limitholdem import Round
class LimitHoldemGame:
def __init__(self, allow_step_back=False, num_players=2):
"""Initialize the class limit holdem game"""
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
# Some configurations of the game
# These arguments can be specified for creating new games
# Small blind and big blind
self.small_blind = 1
self.big_blind = 2 * self.small_blind
# Raise amount and allowed times
self.raise_amount = self.big_blind
self.allowed_raise_num = 4
self.num_players = num_players
# Save betting history
self.history_raise_nums = [0 for _ in range(4)]
self.dealer = None
self.players = None
self.judger = None
self.public_cards = None
self.game_pointer = None
self.round = None
self.round_counter = None
self.history = None
self.history_raises_nums = None
def configure(self, game_config):
"""Specify some game specific parameters, such as number of players"""
self.num_players = game_config['game_num_players']
def init_game(self):
"""
Initialize the game of limit texas holdem
This version supports two-player limit texas holdem
Returns:
(tuple): Tuple containing:
(dict): The first state of the game
(int): Current player's id
"""
# Initialize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initialize two players to play the game
self.players = [Player(i, self.np_random) for i in range(self.num_players)]
# Initialize a judger class which will decide who wins in the end
self.judger = Judger(self.np_random)
# Deal cards to each player to prepare for the first round
for i in range(2 * self.num_players):
self.players[i % self.num_players].hand.append(self.dealer.deal_card())
# Initialize public cards
self.public_cards = []
# Randomly choose a small blind and a big blind
s = self.np_random.randint(0, self.num_players)
b = (s + 1) % self.num_players
self.players[b].in_chips = self.big_blind
self.players[s].in_chips = self.small_blind
# The player next to the big blind plays the first
self.game_pointer = (b + 1) % self.num_players
# Initialize a bidding round, in the first round, the big blind and the small blind needs to
# be passed to the round for processing.
self.round = Round(raise_amount=self.raise_amount,
allowed_raise_num=self.allowed_raise_num,
num_players=self.num_players,
np_random=self.np_random)
self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])
# Count the round. There are 4 rounds in each game.
self.round_counter = 0
# Save the history for stepping back to the last state.
self.history = []
state = self.get_state(self.game_pointer)
# Save betting history
self.history_raise_nums = [0 for _ in range(4)]
return state, self.game_pointer
def step(self, action):
"""
Get the next state
Args:
action (str): a specific action. (call, raise, fold, or check)
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next player id
"""
if self.allow_step_back:
# First snapshot the current state
r = deepcopy(self.round)
b = self.game_pointer
r_c = self.round_counter
d = deepcopy(self.dealer)
p = deepcopy(self.public_cards)
ps = deepcopy(self.players)
rn = copy(self.history_raise_nums)
self.history.append((r, b, r_c, d, p, ps, rn))
# Then we proceed to the next round
self.game_pointer = self.round.proceed_round(self.players, action)
# Save the current raise num to history
self.history_raise_nums[self.round_counter] = self.round.have_raised
# If a round is over, we deal more public cards
if self.round.is_over():
# For the first round, we deal 3 cards
if self.round_counter == 0:
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
# For the following rounds, we deal only 1 card
elif self.round_counter <= 2:
self.public_cards.append(self.dealer.deal_card())
# Double the raise amount for the last two rounds
if self.round_counter == 1:
self.round.raise_amount = 2 * self.raise_amount
self.round_counter += 1
self.round.start_new_round(self.game_pointer)
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def step_back(self):
"""
Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
"""
if len(self.history) > 0:
self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \
self.players, self.history_raises_nums = self.history.pop()
return True
return False
def get_num_players(self):
"""
Return the number of players in limit texas holdem
Returns:
(int): The number of players in the game
"""
return self.num_players
@staticmethod
def get_num_actions():
"""
Return the number of applicable actions
Returns:
(int): The number of actions. There are 4 actions (call, raise, check and fold)
"""
return 4
def get_player_id(self):
"""
Return the current player's id
Returns:
(int): current player's id
"""
return self.game_pointer
def get_state(self, player):
"""
Return player's state
Args:
player (int): player id
Returns:
(dict): The state of the player
"""
chips = [self.players[i].in_chips for i in range(self.num_players)]
legal_actions = self.get_legal_actions()
state = self.players[player].get_state(self.public_cards, chips, legal_actions)
state['raise_nums'] = self.history_raise_nums
return state
def is_over(self):
"""
Check if the game is over
Returns:
(boolean): True if the game is over
"""
alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players]
# If only one player is alive, the game is over.
if sum(alive_players) == 1:
return True
# If all rounds are finished
if self.round_counter >= 4:
return True
return False
def get_payoffs(self):
"""
Return the payoffs of the game
Returns:
(list): Each entry corresponds to the payoff of one player
"""
hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players]
chips_payoffs = self.judger.judge_game(self.players, hands)
payoffs = np.array(chips_payoffs) / self.big_blind
return payoffs
def get_legal_actions(self):
"""
Return the legal actions for current player
Returns:
(list): A list of legal actions
"""
return self.round.get_legal_actions()
class Stage(Enum):
PREFLOP = 0
FLOP = 1
TURN = 2
RIVER = 3
END_HIDDEN = 4
SHOWDOWN = 5
class NolimitholdemGame(LimitHoldemGame):
def __init__(self, allow_step_back=False, num_players=2):
"""Initialize the class no limit holdem Game"""
super().__init__(allow_step_back, num_players)
self.np_random = np.random.RandomState()
# small blind and big blind
self.small_blind = 1
self.big_blind = 2 * self.small_blind
# config players
self.init_chips = [100] * num_players
# If None, the dealer will be randomly chosen
self.dealer_id = None
def configure(self, game_config):
"""
Specify some game specific parameters, such as number of players, initial chips, and dealer id.
If dealer_id is None, he will be randomly chosen
"""
self.num_players = game_config['game_num_players']
# must have num_players length
self.init_chips = [game_config['chips_for_each']] * game_config["game_num_players"]
self.dealer_id = game_config['dealer_id']
def init_game(self):
"""
Initialize the game of not limit holdem
This version supports two-player no limit texas holdem
Returns:
(tuple): Tuple containing:
(dict): The first state of the game
(int): Current player's id
"""
if self.dealer_id is None:
self.dealer_id = self.np_random.randint(0, self.num_players)
# Initialize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initialize players to play the game
self.players = [Player(i, self.init_chips[i], self.np_random) for i in range(self.num_players)]
# Initialize a judger class which will decide who wins in the end
self.judger = Judger(self.np_random)
# Deal cards to each player to prepare for the first round
for i in range(2 * self.num_players):
self.players[i % self.num_players].hand.append(self.dealer.deal_card())
# Initialize public cards
self.public_cards = []
self.stage = Stage.PREFLOP
# Big blind and small blind
s = (self.dealer_id + 1) % self.num_players
b = (self.dealer_id + 2) % self.num_players
self.players[b].bet(chips=self.big_blind)
self.players[s].bet(chips=self.small_blind)
# The player next to the big blind plays the first
self.game_pointer = (b + 1) % self.num_players
# Initialize a bidding round, in the first round, the big blind and the small blind needs to
# be passed to the round for processing.
self.round = Round(self.num_players, self.big_blind, dealer=self.dealer, np_random=self.np_random)
self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])
# Count the round. There are 4 rounds in each game.
self.round_counter = 0
# Save the history for stepping back to the last state.
self.history = []
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def get_legal_actions(self):
"""
Return the legal actions for current player
Returns:
(list): A list of legal actions
"""
return self.round.get_nolimit_legal_actions(players=self.players)
def step(self, action):
"""
Get the next state
Args:
action (str): a specific action. (call, raise, fold, or check)
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next player id
"""
if action not in self.get_legal_actions():
print(action, self.get_legal_actions())
print(self.get_state(self.game_pointer))
raise Exception('Action not allowed')
if self.allow_step_back:
# First snapshot the current state
r = deepcopy(self.round)
b = self.game_pointer
r_c = self.round_counter
d = deepcopy(self.dealer)
p = deepcopy(self.public_cards)
ps = deepcopy(self.players)
self.history.append((r, b, r_c, d, p, ps))
# Then we proceed to the next round
self.game_pointer = self.round.proceed_round(self.players, action)
players_in_bypass = [1 if player.status in (PlayerStatus.FOLDED, PlayerStatus.ALLIN) else 0 for player in self.players]
if self.num_players - sum(players_in_bypass) == 1:
last_player = players_in_bypass.index(0)
if self.round.raised[last_player] >= max(self.round.raised):
# If the last player has put enough chips, he is also bypassed
players_in_bypass[last_player] = 1
# If a round is over, we deal more public cards
if self.round.is_over():
# Game pointer goes to the first player not in bypass after the dealer, if there is one
self.game_pointer = (self.dealer_id + 1) % self.num_players
if sum(players_in_bypass) < self.num_players:
while players_in_bypass[self.game_pointer]:
self.game_pointer = (self.game_pointer + 1) % self.num_players
# For the first round, we deal 3 cards
if self.round_counter == 0:
self.stage = Stage.FLOP
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
if len(self.players) == np.sum(players_in_bypass):
self.round_counter += 1
# For the following rounds, we deal only 1 card
if self.round_counter == 1:
self.stage = Stage.TURN
self.public_cards.append(self.dealer.deal_card())
if len(self.players) == np.sum(players_in_bypass):
self.round_counter += 1
if self.round_counter == 2:
self.stage = Stage.RIVER
self.public_cards.append(self.dealer.deal_card())
if len(self.players) == np.sum(players_in_bypass):
self.round_counter += 1
self.round_counter += 1
self.round.start_new_round(self.game_pointer)
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def get_state(self, player_id):
"""
Return player's state
Args:
player_id (int): player id
Returns:
(dict): The state of the player
"""
self.dealer.pot = np.sum([player.in_chips for player in self.players])
chips = [self.players[i].in_chips for i in range(self.num_players)]
legal_actions = self.get_legal_actions()
state = self.players[player_id].get_state(self.public_cards, chips, legal_actions)
state['stakes'] = [self.players[i].remained_chips for i in range(self.num_players)]
state['current_player'] = self.game_pointer
state['pot'] = self.dealer.pot
state['stage'] = self.stage
return state
def step_back(self):
"""
Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
"""
if len(self.history) > 0:
self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, self.players = self.history.pop()
self.stage = Stage(self.round_counter)
return True
return False
def get_num_players(self):
"""
Return the number of players in no limit texas holdem
Returns:
(int): The number of players in the game
"""
return self.num_players
def get_payoffs(self):
"""
Return the payoffs of the game
Returns:
(list): Each entry corresponds to the payoff of one player
"""
hands = [p.hand + self.public_cards if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else None for p in self.players]
chips_payoffs = self.judger.judge_game(self.players, hands)
return chips_payoffs
@staticmethod
def get_num_actions():
"""
Return the number of applicable actions
Returns:
(int): The number of actions. There are 6 actions (call, raise_half_pot, raise_pot, all_in, check and fold)
"""
return len(Action)
'''
nolimitholdem/utils.py
'''
import numpy as np
from nolimitholdem import Card
def init_standard_deck():
''' Initialize a standard deck of 52 cards
Returns:
(list): A list of Card object
'''
suit_list = ['S', 'H', 'D', 'C']
rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
res = [Card(suit, rank) for suit in suit_list for rank in rank_list]
return res
class Hand:
def __init__(self, all_cards):
self.all_cards = all_cards # two hand cards + five public cards
self.category = 0
#type of a players' best five cards, greater combination has higher number eg: 0:"Not_Yet_Evaluated" 1: "High_Card" , 9:"Straight_Flush"
self.best_five = []
#the largest combination of five cards in all the seven cards
self.flush_cards = []
#cards with same suit
self.cards_by_rank = []
#cards after sort
self.product = 1
#cards’ type indicator
self.RANK_TO_STRING = {2: "2", 3: "3", 4: "4", 5: "5", 6: "6",
7: "7", 8: "8", 9: "9", 10: "T", 11: "J", 12: "Q", 13: "K", 14: "A"}
self.STRING_TO_RANK = {v:k for k, v in self.RANK_TO_STRING.items()}
self.RANK_LOOKUP = "23456789TJQKA"
self.SUIT_LOOKUP = "SCDH"
def get_hand_five_cards(self):
'''
Get the best five cards of a player
Returns:
(list): the best five cards among the seven cards of a player
'''
return self.best_five
def _sort_cards(self):
'''
Sort all the seven cards ascendingly according to RANK_LOOKUP
'''
self.all_cards = sorted(
self.all_cards, key=lambda card: self.RANK_LOOKUP.index(card[1]))
def evaluateHand(self):
"""
Evaluate all the seven cards, get the best combination catagory
And pick the best five cards (for comparing in case 2 hands have the same Category) .
"""
if len(self.all_cards) != 7:
raise Exception(
"There are not enough 7 cards in this hand, quit evaluation now ! ")
self._sort_cards()
self.cards_by_rank, self.product = self._getcards_by_rank(
self.all_cards)
if self._has_straight_flush():
self.category = 9
#Straight Flush
elif self._has_four():
self.category = 8
#Four of a Kind
self.best_five = self._get_Four_of_a_kind_cards()
elif self._has_fullhouse():
self.category = 7
#Full house
self.best_five = self._get_Fullhouse_cards()
elif self._has_flush():
self.category = 6
#Flush
i = len(self.flush_cards)
self.best_five = [card for card in self.flush_cards[i-5:i]]
elif self._has_straight(self.all_cards):
self.category = 5
#Straight
elif self._has_three():
self.category = 4
#Three of a Kind
self.best_five = self._get_Three_of_a_kind_cards()
elif self._has_two_pairs():
self.category = 3
#Two Pairs
self.best_five = self._get_Two_Pair_cards()
elif self._has_pair():
self.category = 2
#One Pair
self.best_five = self._get_One_Pair_cards()
elif self._has_high_card():
self.category = 1
#High Card
self.best_five = self._get_High_cards()
def _has_straight_flush(self):
'''
Check the existence of straight_flush cards
Returns:
True: exist
False: not exist
'''
self.flush_cards = self._getflush_cards()
if len(self.flush_cards) > 0:
straightflush_cards = self._get_straightflush_cards()
if len(straightflush_cards) > 0:
self.best_five = straightflush_cards
return True
return False
def _get_straightflush_cards(self):
'''
Pick straight_flush cards
Returns:
(list): the straightflush cards
'''
straightflush_cards = self._get_straight_cards(self.flush_cards)
return straightflush_cards
def _getflush_cards(self):
'''
Pick flush cards
Returns:
(list): the flush cards
'''
card_string = ''.join(self.all_cards)
for suit in self.SUIT_LOOKUP:
suit_count = card_string.count(suit)
if suit_count >= 5:
flush_cards = [
card for card in self.all_cards if card[0] == suit]
return flush_cards
return []
def _has_flush(self):
'''
Check the existence of flush cards
Returns:
True: exist
False: not exist
'''
if len(self.flush_cards) > 0:
return True
else:
return False
def _has_straight(self, all_cards):
'''
Check the existence of straight cards
Returns:
True: exist
False: not exist
'''
diff_rank_cards = self._get_different_rank_list(all_cards)
self.best_five = self._get_straight_cards(diff_rank_cards)
if len(self.best_five) != 0:
return True
else:
return False
@classmethod
def _get_different_rank_list(self, all_cards):
'''
Get cards with different ranks, that is to say, remove duplicate-ranking cards, for picking straight cards' use
Args:
(list): two hand cards + five public cards
Returns:
(list): a list of cards with duplicate-ranking cards removed
'''
different_rank_list = []
different_rank_list.append(all_cards[0])
for card in all_cards:
if(card[1] != different_rank_list[-1][1]):
different_rank_list.append(card)
return different_rank_list
def _get_straight_cards(self, Cards):
'''
Pick straight cards
Returns:
(list): the straight cards
'''
ranks = [self.STRING_TO_RANK[c[1]] for c in Cards]
highest_card = Cards[-1]
if highest_card[1] == 'A':
Cards.insert(0, highest_card)
ranks.insert(0, 1)
for i_last in range(len(ranks) - 1, 3, -1):
if ranks[i_last-4] + 4 == ranks[i_last]: # works because ranks are unique and sorted in ascending order
return Cards[i_last-4:i_last+1]
return []
def _getcards_by_rank(self, all_cards):
'''
Get cards by rank
Args:
(list): # two hand cards + five public cards
Return:
card_group(list): cards after sort
product(int):cards‘ type indicator
'''
card_group = []
card_group_element = []
product = 1
prime_lookup = {0: 1, 1: 1, 2: 2, 3: 3, 4: 5}
count = 0
current_rank = 0
for card in all_cards:
rank = self.RANK_LOOKUP.index(card[1])
if rank == current_rank:
count += 1
card_group_element.append(card)
elif rank != current_rank:
product *= prime_lookup[count]
# Explanation :
# if count == 2, then product *= 2
# if count == 3, then product *= 3
# if count == 4, then product *= 5
# if there is a Quad, then product = 5 ( 4, 1, 1, 1) or product = 10 ( 4, 2, 1) or product= 15 (4,3)
# if there is a Fullhouse, then product = 12 ( 3, 2, 2) or product = 9 (3, 3, 1) or product = 6 ( 3, 2, 1, 1)
# if there is a Trip, then product = 3 ( 3, 1, 1, 1, 1)
# if there is two Pair, then product = 4 ( 2, 1, 2, 1, 1) or product = 8 ( 2, 2, 2, 1)
# if there is one Pair, then product = 2 (2, 1, 1, 1, 1, 1)
# if there is HighCard, then product = 1 (1, 1, 1, 1, 1, 1, 1)
card_group_element.insert(0, count)
card_group.append(card_group_element)
# reset counting
count = 1
card_group_element = []
card_group_element.append(card)
current_rank = rank
# the For Loop misses operation for the last card
# These 3 lines below to compensate that
product *= prime_lookup[count]
# insert the number of same rank card to the beginning of the
card_group_element.insert(0, count)
# after the loop, there is still one last card to add
card_group.append(card_group_element)
return card_group, product
def _has_four(self):
'''
Check the existence of four cards
Returns:
True: exist
False: not exist
'''
if self.product == 5 or self.product == 10 or self.product == 15:
return True
else:
return False
def _has_fullhouse(self):
'''
Check the existence of fullhouse cards
Returns:
True: exist
False: not exist
'''
if self.product == 6 or self.product == 9 or self.product == 12:
return True
else:
return False
def _has_three(self):
'''
Check the existence of three cards
Returns:
True: exist
False: not exist
'''
if self.product == 3:
return True
else:
return False
def _has_two_pairs(self):
'''
Check the existence of 2 pair cards
Returns:
True: exist
False: not exist
'''
if self.product == 4 or self.product == 8:
return True
else:
return False
def _has_pair(self):
'''
Check the existence of 1 pair cards
Returns:
True: exist
False: not exist
'''
if self.product == 2:
return True
else:
return False
def _has_high_card(self):
'''
Check the existence of high cards
Returns:
True: exist
False: not exist
'''
if self.product == 1:
return True
else:
return False
def _get_Four_of_a_kind_cards(self):
'''
Get the four of a kind cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Four_of_a_Kind = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 4:
Four_of_a_Kind = cards_by_rank.pop(i)
break
# The Last cards_by_rank[The Second element]
kicker = cards_by_rank[-1][1]
Four_of_a_Kind[0] = kicker
return Four_of_a_Kind
def _get_Fullhouse_cards(self):
'''
Get the fullhouse cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Fullhouse = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 3:
Trips = cards_by_rank.pop(i)[1:4]
break
for i in reversed(range(cards_len - 1)):
if cards_by_rank[i][0] >= 2:
TwoPair = cards_by_rank.pop(i)[1:3]
break
Fullhouse = TwoPair + Trips
return Fullhouse
def _get_Three_of_a_kind_cards(self):
'''
Get the three of a kind cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Trip_cards = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 3:
Trip_cards += cards_by_rank.pop(i)[1:4]
break
Trip_cards += cards_by_rank.pop(-1)[1:2]
Trip_cards += cards_by_rank.pop(-1)[1:2]
Trip_cards.reverse()
return Trip_cards
def _get_Two_Pair_cards(self):
'''
Get the two pair cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Two_Pair_cards = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 2 and len(Two_Pair_cards) < 3:
Two_Pair_cards += cards_by_rank.pop(i)[1:3]
Two_Pair_cards += cards_by_rank.pop(-1)[1:2]
Two_Pair_cards.reverse()
return Two_Pair_cards
def _get_One_Pair_cards(self):
'''
Get the one pair cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
One_Pair_cards = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 2:
One_Pair_cards += cards_by_rank.pop(i)[1:3]
break
One_Pair_cards += cards_by_rank.pop(-1)[1:2]
One_Pair_cards += cards_by_rank.pop(-1)[1:2]
One_Pair_cards += cards_by_rank.pop(-1)[1:2]
One_Pair_cards.reverse()
return One_Pair_cards
def _get_High_cards(self):
'''
Get the high cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
High_cards = self.all_cards[2:7]
return High_cards
def compare_ranks(position, hands, winner):
'''
Compare cards in same position of plays' five handcards
Args:
position(int): the position of a card in a sorted handcard
hands(list): cards of those players.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
winner: array of same length than hands with 1 if the hand is among winners and 0 among losers
Returns:
new updated winner array
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
assert len(hands) == len(winner)
RANKS = '23456789TJQKA'
cards_figure_all_players = [None]*len(hands) #cards without suit
for i, hand in enumerate(hands):
if winner[i]:
cards = hands[i].get_hand_five_cards()
if len(cards[0]) != 1:# remove suit
for p in range(5):
cards[p] = cards[p][1:]
cards_figure_all_players[i] = cards
rival_ranks = [] # ranks of rival_figures
for i, cards_figure in enumerate(cards_figure_all_players):
if winner[i]:
rank = cards_figure_all_players[i][position]
rival_ranks.append(RANKS.index(rank))
else:
rival_ranks.append(-1) # player has already lost
new_winner = list(winner)
for i, rival_rank in enumerate(rival_ranks):
if rival_rank != max(rival_ranks):
new_winner[i] = 0
return new_winner
def determine_winner(key_index, hands, all_players, potential_winner_index):
'''
Find out who wins in the situation of having players with same highest hand_catagory
Args:
key_index(int): the position of a card in a sorted handcard
hands(list): cards of those players with same highest hand_catagory.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
all_players(list): all the players in this round, 0 for losing and 1 for winning or draw
potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
winner = [1]*len(hands)
i_index = 0
while i_index < len(key_index) and sum(winner) > 1:
index_break_tie = key_index[i_index]
winner = compare_ranks(index_break_tie, hands, winner)
i_index += 1
for i in range(len(potential_winner_index)):
if winner[i]:
all_players[potential_winner_index[i]] = 1
return all_players
def determine_winner_straight(hands, all_players, potential_winner_index):
'''
Find out who wins in the situation of having players all having a straight or straight flush
Args:
key_index(int): the position of a card in a sorted handcard
hands(list): cards of those players which all have a straight or straight flush
all_players(list): all the players in this round, 0 for losing and 1 for winning or draw
potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
highest_ranks = []
for hand in hands:
highest_rank = hand.STRING_TO_RANK[hand.best_five[-1][1]] # cards are sorted in ascending order
highest_ranks.append(highest_rank)
max_highest_rank = max(highest_ranks)
for i_player in range(len(highest_ranks)):
if highest_ranks[i_player] == max_highest_rank:
all_players[potential_winner_index[i_player]] = 1
return all_players
def determine_winner_four_of_a_kind(hands, all_players, potential_winner_index):
'''
Find out who wins in the situation of having players which all have a four of a kind
Args:
key_index(int): the position of a card in a sorted handcard
hands(list): cards of those players with a four of a kind
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
all_players(list): all the players in this round, 0 for losing and 1 for winning or draw
potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
ranks = []
for hand in hands:
rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind
rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker
ranks.append((rank_1, rank_2))
max_rank = max(ranks)
for i, rank in enumerate(ranks):
if rank == max_rank:
all_players[potential_winner_index[i]] = 1
return all_players
def compare_hands(hands):
'''
Compare all palyer's all seven cards
Args:
hands(list): cards of those players with same highest hand_catagory.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
if hands[0] == None:
return [0, 1]
elif hands[1] == None:
return [1, 0]
'''
hand_category = [] #such as high_card, straight_flush, etc
all_players = [0]*len(hands) #all the players in this round, 0 for losing and 1 for winning or draw
if None in hands:
fold_players = [i for i, j in enumerate(hands) if j is None]
if len(fold_players) == len(all_players) - 1:
for _ in enumerate(hands):
if _[0] in fold_players:
all_players[_[0]] = 0
else:
all_players[_[0]] = 1
return all_players
else:
for _ in enumerate(hands):
if hands[_[0]] is not None:
hand = Hand(hands[_[0]])
hand.evaluateHand()
hand_category.append(hand.category)
elif hands[_[0]] is None:
hand_category.append(0)
else:
for i in enumerate(hands):
hand = Hand(hands[i[0]])
hand.evaluateHand()
hand_category.append(hand.category)
potential_winner_index = [i for i, j in enumerate(hand_category) if j == max(hand_category)]# potential winner are those with same max card_catagory
return final_compare(hands, potential_winner_index, all_players)
def final_compare(hands, potential_winner_index, all_players):
'''
Find out the winners from those who didn't fold
Args:
hands(list): cards of those players with same highest hand_catagory.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
potential_winner_index(list): index of those with same max card_catagory in all_players
all_players(list): a list of all the player's win/lose situation, 0 for lose and 1 for win
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
if hands[0] == None:
return [0, 1]
elif hands[1] == None:
return [1, 0]
'''
if len(potential_winner_index) == 1:
all_players[potential_winner_index[0]] = 1
return all_players
elif len(potential_winner_index) > 1:
# compare when having equal max categories
equal_hands = []
for _ in potential_winner_index:
hand = Hand(hands[_])
hand.evaluateHand()
equal_hands.append(hand)
hand = equal_hands[0]
if hand.category == 8:
return determine_winner_four_of_a_kind(equal_hands, all_players, potential_winner_index)
if hand.category == 7:
return determine_winner([2, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 4:
return determine_winner([2, 1, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 3:
return determine_winner([4, 2, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 2:
return determine_winner([4, 2, 1, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 1 or hand.category == 6:
return determine_winner([4, 3, 2, 1, 0], equal_hands, all_players, potential_winner_index)
if hand.category in [5, 9]:
return determine_winner_straight(equal_hands, all_players, potential_winner_index)
'''
nolimitholdem/__init__.py
'''
from nolimitholdem.base import Card as Card
from nolimitholdem.dealer import NolimitholdemDealer as Dealer
from nolimitholdem.judger import NolimitholdemJudger as Judger
from nolimitholdem.player import NolimitholdemPlayer as Player
from nolimitholdem.player import PlayerStatus
from nolimitholdem.round import Action
from nolimitholdem.round import NolimitholdemRound as Round
from nolimitholdem.game import NolimitholdemGame as Game
'''
nolimitholdem/round.py
'''
# -*- coding: utf-8 -*-
"""Implement no limit texas holdem Round class"""
from enum import Enum
from nolimitholdem import PlayerStatus
class Action(Enum):
FOLD = 0
CHECK_CALL = 1
#CALL = 2
# RAISE_3BB = 3
RAISE_HALF_POT = 2
RAISE_POT = 3
# RAISE_2POT = 5
ALL_IN = 4
# SMALL_BLIND = 7
# BIG_BLIND = 8
class NolimitholdemRound:
"""Round can call functions from other classes to keep the game running"""
def __init__(self, num_players, init_raise_amount, dealer, np_random):
"""
Initialize the round class
Args:
num_players (int): The number of players
init_raise_amount (int): The min raise amount when every round starts
"""
self.np_random = np_random
self.game_pointer = None
self.num_players = num_players
self.init_raise_amount = init_raise_amount
self.dealer = dealer
# Count the number without raise
# If every player agree to not raise, the round is over
self.not_raise_num = 0
# Count players that are not playing anymore (folded or all-in)
self.not_playing_num = 0
# Raised amount for each player
self.raised = [0 for _ in range(self.num_players)]
def start_new_round(self, game_pointer, raised=None):
"""
Start a new bidding round
Args:
game_pointer (int): The game_pointer that indicates the next player
raised (list): Initialize the chips for each player
Note: For the first round of the game, we need to setup the big/small blind
"""
self.game_pointer = game_pointer
self.not_raise_num = 0
if raised:
self.raised = raised
else:
self.raised = [0 for _ in range(self.num_players)]
def proceed_round(self, players, action):
"""
Call functions from other classes to keep one round running
Args:
players (list): The list of players that play the game
action (str/int): An legal action taken by the player
Returns:
(int): The game_pointer that indicates the next player
"""
player = players[self.game_pointer]
if action == Action.CHECK_CALL:
diff = max(self.raised) - self.raised[self.game_pointer]
self.raised[self.game_pointer] = max(self.raised)
player.bet(chips=diff)
self.not_raise_num += 1
elif action == Action.ALL_IN:
all_in_quantity = player.remained_chips
self.raised[self.game_pointer] = all_in_quantity + self.raised[self.game_pointer]
player.bet(chips=all_in_quantity)
self.not_raise_num = 1
elif action == Action.RAISE_POT:
self.raised[self.game_pointer] += self.dealer.pot
player.bet(chips=self.dealer.pot)
self.not_raise_num = 1
elif action == Action.RAISE_HALF_POT:
quantity = int(self.dealer.pot / 2)
self.raised[self.game_pointer] += quantity
player.bet(chips=quantity)
self.not_raise_num = 1
elif action == Action.FOLD:
player.status = PlayerStatus.FOLDED
if player.remained_chips < 0:
raise Exception("Player in negative stake")
if player.remained_chips == 0 and player.status != PlayerStatus.FOLDED:
player.status = PlayerStatus.ALLIN
self.game_pointer = (self.game_pointer + 1) % self.num_players
if player.status == PlayerStatus.ALLIN:
self.not_playing_num += 1
self.not_raise_num -= 1 # Because already counted in not_playing_num
if player.status == PlayerStatus.FOLDED:
self.not_playing_num += 1
# Skip the folded players
while players[self.game_pointer].status == PlayerStatus.FOLDED:
self.game_pointer = (self.game_pointer + 1) % self.num_players
return self.game_pointer
def get_nolimit_legal_actions(self, players):
"""
Obtain the legal actions for the current player
Args:
players (list): The players in the game
Returns:
(list): A list of legal actions
"""
full_actions = list(Action)
# The player can always check or call
player = players[self.game_pointer]
diff = max(self.raised) - self.raised[self.game_pointer]
# If the current player has no more chips after call, we cannot raise
if diff > 0 and diff >= player.remained_chips:
full_actions.remove(Action.RAISE_HALF_POT)
full_actions.remove(Action.RAISE_POT)
full_actions.remove(Action.ALL_IN)
# Even if we can raise, we have to check remained chips
else:
if self.dealer.pot > player.remained_chips:
full_actions.remove(Action.RAISE_POT)
if int(self.dealer.pot / 2) > player.remained_chips:
full_actions.remove(Action.RAISE_HALF_POT)
# Can't raise if the total raise amount is leq than the max raise amount of this round
# If raise by pot, there is no such concern
if Action.RAISE_HALF_POT in full_actions and \
int(self.dealer.pot / 2) + self.raised[self.game_pointer] <= max(self.raised):
full_actions.remove(Action.RAISE_HALF_POT)
return full_actions
def is_over(self):
"""
Check whether the round is over
Returns:
(boolean): True if the current round is over
"""
if self.not_raise_num + self.not_playing_num >= self.num_players:
return True
return False
| 8 | 1,562 | Python |
stock3 | ./ProjectTest/Python/stock3.py | '''
stock3/stock.py
'''
# stock.py
from structure import Structure
from validate import String, PositiveInteger, PositiveFloat
class Stock(Structure):
name = String('name')
shares = PositiveInteger('shares')
price = PositiveFloat('price')
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares):
self.shares -= nshares
'''
stock3/reader.py
'''
# reader.py
import csv
import logging
log = logging.getLogger(__name__)
def convert_csv(lines, converter, *, headers=None):
rows = csv.reader(lines)
if headers is None:
headers = next(rows)
records = []
for rowno, row in enumerate(rows, start=1):
try:
records.append(converter(headers, row))
except ValueError as e:
log.warning('Row %s: Bad row: %s', rowno, row)
log.debug('Row %s: Reason: %s', rowno, row)
return records
def csv_as_dicts(lines, types, *, headers=None):
return convert_csv(lines,
lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })
def csv_as_instances(lines, cls, *, headers=None):
return convert_csv(lines,
lambda headers, row: cls.from_row(row))
def read_csv_as_dicts(filename, types, *, headers=None):
'''
Read CSV data into a list of dictionaries with optional type conversion
'''
with open(filename) as file:
return csv_as_dicts(file, types, headers=headers)
def read_csv_as_instances(filename, cls, *, headers=None):
'''
Read CSV data into a list of instances
'''
with open(filename) as file:
return csv_as_instances(file, cls, headers=headers)
'''
stock3/validate.py
'''
# validate.py
class Validator:
def __init__(self, name=None):
self.name = name
def __set_name__(self, cls, name):
self.name = name
@classmethod
def check(cls, value):
return value
def __set__(self, instance, value):
instance.__dict__[self.name] = self.check(value)
# Collect all derived classes into a dict
validators = { }
@classmethod
def __init_subclass__(cls):
cls.validators[cls.__name__] = cls
class Typed(Validator):
expected_type = object
@classmethod
def check(cls, value):
if not isinstance(value, cls.expected_type):
raise TypeError(f'expected {cls.expected_type}')
return super().check(value)
_typed_classes = [
('Integer', int),
('Float', float),
('String', str) ]
globals().update((name, type(name, (Typed,), {'expected_type':ty}))
for name, ty in _typed_classes)
class Positive(Validator):
@classmethod
def check(cls, value):
if value < 0:
raise ValueError('must be >= 0')
return super().check(value)
class NonEmpty(Validator):
@classmethod
def check(cls, value):
if len(value) == 0:
raise ValueError('must be non-empty')
return super().check(value)
class PositiveInteger(Integer, Positive):
pass
class PositiveFloat(Float, Positive):
pass
class NonEmptyString(String, NonEmpty):
pass
from inspect import signature
from functools import wraps
def isvalidator(item):
return isinstance(item, type) and issubclass(item, Validator)
def validated(func):
sig = signature(func)
# Gather the function annotations
annotations = { name:val for name, val in func.__annotations__.items()
if isvalidator(val) }
# Get the return annotation (if any)
retcheck = annotations.pop('return', None)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
# Enforce return check (if any)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
def enforce(**annotations):
retcheck = annotations.pop('return_', None)
def decorate(func):
sig = signature(func)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
return decorate
'''
stock3/structure.py
'''
# structure.py
from validate import Validator, validated
from collections import ChainMap
class StructureMeta(type):
@classmethod
def __prepare__(meta, clsname, bases):
return ChainMap({}, Validator.validators)
@staticmethod
def __new__(meta, name, bases, methods):
methods = methods.maps[0]
return super().__new__(meta, name, bases, methods)
class Structure(metaclass=StructureMeta):
_fields = ()
_types = ()
def __setattr__(self, name, value):
if name.startswith('_') or name in self._fields:
super().__setattr__(name, value)
else:
raise AttributeError('No attribute %s' % name)
def __repr__(self):
return '%s(%s)' % (type(self).__name__,
', '.join(repr(getattr(self, name)) for name in self._fields))
def __iter__(self):
for name in self._fields:
yield getattr(self, name)
def __eq__(self, other):
return isinstance(other, type(self)) and tuple(self) == tuple(other)
@classmethod
def from_row(cls, row):
rowdata = [ func(val) for func, val in zip(cls._types, row) ]
return cls(*rowdata)
@classmethod
def create_init(cls):
'''
Create an __init__ method from _fields
'''
args = ','.join(cls._fields)
code = f'def __init__(self, {args}):\n'
for name in cls._fields:
code += f' self.{name} = {name}\n'
locs = { }
exec(code, locs)
cls.__init__ = locs['__init__']
@classmethod
def __init_subclass__(cls):
# Apply the validated decorator to subclasses
validate_attributes(cls)
def validate_attributes(cls):
'''
Class decorator that scans a class definition for Validators
and builds a _fields variable that captures their definition order.
'''
validators = []
for name, val in vars(cls).items():
if isinstance(val, Validator):
validators.append(val)
# Apply validated decorator to any callable with annotations
elif callable(val) and val.__annotations__:
setattr(cls, name, validated(val))
# Collect all of the field names
cls._fields = tuple([v.name for v in validators])
# Collect type conversions. The lambda x:x is an identity
# function that's used in case no expected_type is found.
cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)
for v in validators ])
# Create the __init__ method
if cls._fields:
cls.create_init()
return cls
def typed_structure(clsname, **validators):
cls = type(clsname, (Structure,), validators)
return cls
| 4 | 286 | Python |
slugify | ./ProjectTest/Python/slugify.py | '''
slugify/slugify.py
'''
from __future__ import annotations
import re
import unicodedata
from collections.abc import Iterable
from html.entities import name2codepoint
try:
import unidecode
except ImportError:
import text_unidecode as unidecode
__all__ = ['slugify', 'smart_truncate']
CHAR_ENTITY_PATTERN = re.compile(r'&(%s);' % '|'.join(name2codepoint))
DECIMAL_PATTERN = re.compile(r'&#(\d+);')
HEX_PATTERN = re.compile(r'&#x([\da-fA-F]+);')
QUOTE_PATTERN = re.compile(r'[\']+')
DISALLOWED_CHARS_PATTERN = re.compile(r'[^-a-zA-Z0-9]+')
DISALLOWED_UNICODE_CHARS_PATTERN = re.compile(r'[\W_]+')
DUPLICATE_DASH_PATTERN = re.compile(r'-{2,}')
NUMBERS_PATTERN = re.compile(r'(?<=\d),(?=\d)')
DEFAULT_SEPARATOR = '-'
def smart_truncate(
string: str,
max_length: int = 0,
word_boundary: bool = False,
separator: str = " ",
save_order: bool = False,
) -> str:
"""
Truncate a string.
:param string (str): string for modification
:param max_length (int): output string length
:param word_boundary (bool):
:param save_order (bool): if True then word order of output string is like input string
:param separator (str): separator between words
:return:
"""
string = string.strip(separator)
if not max_length:
return string
if len(string) < max_length:
return string
if not word_boundary:
return string[:max_length].strip(separator)
if separator not in string:
return string[:max_length]
truncated = ''
for word in string.split(separator):
if word:
next_len = len(truncated) + len(word)
if next_len < max_length:
truncated += '{}{}'.format(word, separator)
elif next_len == max_length:
truncated += '{}'.format(word)
break
else:
if save_order:
break
if not truncated: # pragma: no cover
truncated = string[:max_length]
return truncated.strip(separator)
def slugify(
text: str,
entities: bool = True,
decimal: bool = True,
hexadecimal: bool = True,
max_length: int = 0,
word_boundary: bool = False,
separator: str = DEFAULT_SEPARATOR,
save_order: bool = False,
stopwords: Iterable[str] = (),
regex_pattern: re.Pattern[str] | str | None = None,
lowercase: bool = True,
replacements: Iterable[Iterable[str]] = (),
allow_unicode: bool = False,
) -> str:
"""
Make a slug from the given text.
:param text (str): initial text
:param entities (bool): converts html entities to unicode
:param decimal (bool): converts html decimal to unicode
:param hexadecimal (bool): converts html hexadecimal to unicode
:param max_length (int): output string length
:param word_boundary (bool): truncates to complete word even if length ends up shorter than max_length
:param save_order (bool): if parameter is True and max_length > 0 return whole words in the initial order
:param separator (str): separator between words
:param stopwords (iterable): words to discount
:param regex_pattern (str): regex pattern for disallowed characters
:param lowercase (bool): activate case sensitivity by setting it to False
:param replacements (iterable): list of replacement rules e.g. [['|', 'or'], ['%', 'percent']]
:param allow_unicode (bool): allow unicode characters
:return (str):
"""
# user-specific replacements
if replacements:
for old, new in replacements:
text = text.replace(old, new)
# ensure text is unicode
if not isinstance(text, str):
text = str(text, 'utf-8', 'ignore')
# replace quotes with dashes - pre-process
text = QUOTE_PATTERN.sub(DEFAULT_SEPARATOR, text)
# normalize text, convert to unicode if required
if allow_unicode:
text = unicodedata.normalize('NFKC', text)
else:
text = unicodedata.normalize('NFKD', text)
text = unidecode.unidecode(text)
# ensure text is still in unicode
if not isinstance(text, str):
text = str(text, 'utf-8', 'ignore')
# character entity reference
if entities:
text = CHAR_ENTITY_PATTERN.sub(lambda m: chr(name2codepoint[m.group(1)]), text)
# decimal character reference
if decimal:
try:
text = DECIMAL_PATTERN.sub(lambda m: chr(int(m.group(1))), text)
except Exception:
pass
# hexadecimal character reference
if hexadecimal:
try:
text = HEX_PATTERN.sub(lambda m: chr(int(m.group(1), 16)), text)
except Exception:
pass
# re normalize text
if allow_unicode:
text = unicodedata.normalize('NFKC', text)
else:
text = unicodedata.normalize('NFKD', text)
# make the text lowercase (optional)
if lowercase:
text = text.lower()
# remove generated quotes -- post-process
text = QUOTE_PATTERN.sub('', text)
# cleanup numbers
text = NUMBERS_PATTERN.sub('', text)
# replace all other unwanted characters
if allow_unicode:
pattern = regex_pattern or DISALLOWED_UNICODE_CHARS_PATTERN
else:
pattern = regex_pattern or DISALLOWED_CHARS_PATTERN
text = re.sub(pattern, DEFAULT_SEPARATOR, text)
# remove redundant
text = DUPLICATE_DASH_PATTERN.sub(DEFAULT_SEPARATOR, text).strip(DEFAULT_SEPARATOR)
# remove stopwords
if stopwords:
if lowercase:
stopwords_lower = [s.lower() for s in stopwords]
words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords_lower]
else:
words = [w for w in text.split(DEFAULT_SEPARATOR) if w not in stopwords]
text = DEFAULT_SEPARATOR.join(words)
# finalize user-specific replacements
if replacements:
for old, new in replacements:
text = text.replace(old, new)
# smart truncate if requested
if max_length > 0:
text = smart_truncate(text, max_length, word_boundary, DEFAULT_SEPARATOR, save_order)
if separator != DEFAULT_SEPARATOR:
text = text.replace(DEFAULT_SEPARATOR, separator)
return text
'''
slugify/__init__.py
'''
from slugify.special import *
from slugify.slugify import *
'''
slugify/special.py
'''
from __future__ import annotations
def add_uppercase_char(char_list: list[tuple[str, str]]) -> list[tuple[str, str]]:
""" Given a replacement char list, this adds uppercase chars to the list """
for item in char_list:
char, xlate = item
upper_dict = char.upper(), xlate.capitalize()
if upper_dict not in char_list and char != upper_dict[0]:
char_list.insert(0, upper_dict)
return char_list
# Language specific pre translations
# Source awesome-slugify
_CYRILLIC = [ # package defaults:
(u'ё', u'e'), # io / yo
(u'я', u'ya'), # ia
(u'х', u'h'), # kh
(u'у', u'y'), # u
(u'щ', u'sch'), # sch
(u'ю', u'u'), # iu / yu
]
CYRILLIC = add_uppercase_char(_CYRILLIC)
_GERMAN = [ # package defaults:
(u'ä', u'ae'), # a
(u'ö', u'oe'), # o
(u'ü', u'ue'), # u
]
GERMAN = add_uppercase_char(_GERMAN)
_GREEK = [ # package defaults:
(u'χ', u'ch'), # kh
(u'Ξ', u'X'), # Ks
(u'ϒ', u'Y'), # U
(u'υ', u'y'), # u
(u'ύ', u'y'),
(u'ϋ', u'y'),
(u'ΰ', u'y'),
]
GREEK = add_uppercase_char(_GREEK)
# Pre translations
PRE_TRANSLATIONS = CYRILLIC + GERMAN + GREEK
| 3 | 246 | Python |
keras_preprocessing | ./ProjectTest/Python/keras_preprocessing.py | '''
keras_preprocessing/text.py
'''
# -*- coding: utf-8 -*-
"""Utilities for text input preprocessing.
"""
import json
import warnings
from collections import OrderedDict, defaultdict
from hashlib import md5
import numpy as np
maketrans = str.maketrans
def text_to_word_sequence(text,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True, split=" "):
"""Converts a text to a sequence of words (or tokens).
# Arguments
text: Input text (string).
filters: list (or concatenation) of characters to filter out, such as
punctuation. Default: ``!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``,
includes basic punctuation, tabs, and newlines.
lower: boolean. Whether to convert the input to lowercase.
split: str. Separator for word splitting.
# Returns
A list of words (or tokens).
"""
if lower:
text = text.lower()
translate_dict = {c: split for c in filters}
translate_map = maketrans(translate_dict)
text = text.translate(translate_map)
seq = text.split(split)
return [i for i in seq if i]
def one_hot(text, n,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True,
split=' ',
analyzer=None):
"""One-hot encodes a text into a list of word indexes of size n.
This is a wrapper to the `hashing_trick` function using `hash` as the
hashing function; unicity of word to index mapping non-guaranteed.
# Arguments
text: Input text (string).
n: int. Size of vocabulary.
filters: list (or concatenation) of characters to filter out, such as
punctuation. Default: ``!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``,
includes basic punctuation, tabs, and newlines.
lower: boolean. Whether to set the text to lowercase.
split: str. Separator for word splitting.
analyzer: function. Custom analyzer to split the text
# Returns
List of integers in [1, n]. Each integer encodes a word
(unicity non-guaranteed).
"""
return hashing_trick(text, n,
hash_function=hash,
filters=filters,
lower=lower,
split=split,
analyzer=analyzer)
def hashing_trick(text, n,
hash_function=None,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True,
split=' ',
analyzer=None):
"""Converts a text to a sequence of indexes in a fixed-size hashing space.
# Arguments
text: Input text (string).
n: Dimension of the hashing space.
hash_function: defaults to python `hash` function, can be 'md5' or
any function that takes in input a string and returns a int.
Note that 'hash' is not a stable hashing function, so
it is not consistent across different runs, while 'md5'
is a stable hashing function.
filters: list (or concatenation) of characters to filter out, such as
punctuation. Default: ``!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\\t\\n``,
includes basic punctuation, tabs, and newlines.
lower: boolean. Whether to set the text to lowercase.
split: str. Separator for word splitting.
analyzer: function. Custom analyzer to split the text
# Returns
A list of integer word indices (unicity non-guaranteed).
`0` is a reserved index that won't be assigned to any word.
Two or more words may be assigned to the same index, due to possible
collisions by the hashing function.
The [probability](
https://en.wikipedia.org/wiki/Birthday_problem#Probability_table)
of a collision is in relation to the dimension of the hashing space and
the number of distinct objects.
"""
if hash_function is None:
hash_function = hash
elif hash_function == 'md5':
def hash_function(w):
return int(md5(w.encode()).hexdigest(), 16)
if analyzer is None:
seq = text_to_word_sequence(text,
filters=filters,
lower=lower,
split=split)
else:
seq = analyzer(text)
return [(hash_function(w) % (n - 1) + 1) for w in seq]
class Tokenizer(object):
"""Text tokenization utility class.
This class allows to vectorize a text corpus, by turning each
text into either a sequence of integers (each integer being the index
of a token in a dictionary) or into a vector where the coefficient
for each token could be binary, based on word count, based on tf-idf...
# Arguments
num_words: the maximum number of words to keep, based
on word frequency. Only the most common `num_words-1` words will
be kept.
filters: a string where each element is a character that will be
filtered from the texts. The default is all punctuation, plus
tabs and line breaks, minus the `'` character.
lower: boolean. Whether to convert the texts to lowercase.
split: str. Separator for word splitting.
char_level: if True, every character will be treated as a token.
oov_token: if given, it will be added to word_index and used to
replace out-of-vocabulary words during text_to_sequence calls
analyzer: function. Custom analyzer to split the text.
The default analyzer is text_to_word_sequence
By default, all punctuation is removed, turning the texts into
space-separated sequences of words
(words maybe include the `'` character). These sequences are then
split into lists of tokens. They will then be indexed or vectorized.
`0` is a reserved index that won't be assigned to any word.
"""
def __init__(self, num_words=None,
filters='!"#$%&()*+,-./:;<=>?@[\\]^_`{|}~\t\n',
lower=True,
split=' ',
char_level=False,
oov_token=None,
analyzer=None,
**kwargs):
# Legacy support
if 'nb_words' in kwargs:
warnings.warn('The `nb_words` argument in `Tokenizer` '
'has been renamed `num_words`.')
num_words = kwargs.pop('nb_words')
document_count = kwargs.pop('document_count', 0)
if kwargs:
raise TypeError('Unrecognized keyword arguments: ' + str(kwargs))
self.word_counts = OrderedDict()
self.word_docs = defaultdict(int)
self.filters = filters
self.split = split
self.lower = lower
self.num_words = num_words
self.document_count = document_count
self.char_level = char_level
self.oov_token = oov_token
self.index_docs = defaultdict(int)
self.word_index = {}
self.index_word = {}
self.analyzer = analyzer
def fit_on_texts(self, texts):
"""Updates internal vocabulary based on a list of texts.
In the case where texts contains lists,
we assume each entry of the lists to be a token.
Required before using `texts_to_sequences` or `texts_to_matrix`.
# Arguments
texts: can be a list of strings,
a generator of strings (for memory-efficiency),
or a list of list of strings.
"""
for text in texts:
self.document_count += 1
if self.char_level or isinstance(text, list):
if self.lower:
if isinstance(text, list):
text = [text_elem.lower() for text_elem in text]
else:
text = text.lower()
seq = text
else:
if self.analyzer is None:
seq = text_to_word_sequence(text,
filters=self.filters,
lower=self.lower,
split=self.split)
else:
seq = self.analyzer(text)
for w in seq:
if w in self.word_counts:
self.word_counts[w] += 1
else:
self.word_counts[w] = 1
for w in set(seq):
# In how many documents each word occurs
self.word_docs[w] += 1
wcounts = list(self.word_counts.items())
wcounts.sort(key=lambda x: x[1], reverse=True)
# forcing the oov_token to index 1 if it exists
if self.oov_token is None:
sorted_voc = []
else:
sorted_voc = [self.oov_token]
sorted_voc.extend(wc[0] for wc in wcounts)
# note that index 0 is reserved, never assigned to an existing word
self.word_index = dict(
zip(sorted_voc, list(range(1, len(sorted_voc) + 1))))
self.index_word = {c: w for w, c in self.word_index.items()}
for w, c in list(self.word_docs.items()):
self.index_docs[self.word_index[w]] = c
def fit_on_sequences(self, sequences):
"""Updates internal vocabulary based on a list of sequences.
Required before using `sequences_to_matrix`
(if `fit_on_texts` was never called).
# Arguments
sequences: A list of sequence.
A "sequence" is a list of integer word indices.
"""
self.document_count += len(sequences)
for seq in sequences:
seq = set(seq)
for i in seq:
self.index_docs[i] += 1
def texts_to_sequences(self, texts):
"""Transforms each text in texts to a sequence of integers.
Only top `num_words-1` most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
# Arguments
texts: A list of texts (strings).
# Returns
A list of sequences.
"""
return list(self.texts_to_sequences_generator(texts))
def texts_to_sequences_generator(self, texts):
"""Transforms each text in `texts` to a sequence of integers.
Each item in texts can also be a list,
in which case we assume each item of that list to be a token.
Only top `num_words-1` most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
# Arguments
texts: A list of texts (strings).
# Yields
Yields individual sequences.
"""
num_words = self.num_words
oov_token_index = self.word_index.get(self.oov_token)
for text in texts:
if self.char_level or isinstance(text, list):
if self.lower:
if isinstance(text, list):
text = [text_elem.lower() for text_elem in text]
else:
text = text.lower()
seq = text
else:
if self.analyzer is None:
seq = text_to_word_sequence(text,
filters=self.filters,
lower=self.lower,
split=self.split)
else:
seq = self.analyzer(text)
vect = []
for w in seq:
i = self.word_index.get(w)
if i is not None:
if num_words and i >= num_words:
if oov_token_index is not None:
vect.append(oov_token_index)
else:
vect.append(i)
elif self.oov_token is not None:
vect.append(oov_token_index)
yield vect
def sequences_to_texts(self, sequences):
"""Transforms each sequence into a list of text.
Only top `num_words-1` most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
# Arguments
sequences: A list of sequences (list of integers).
# Returns
A list of texts (strings)
"""
return list(self.sequences_to_texts_generator(sequences))
def sequences_to_texts_generator(self, sequences):
"""Transforms each sequence in `sequences` to a list of texts(strings).
Each sequence has to a list of integers.
In other words, sequences should be a list of sequences
Only top `num_words-1` most frequent words will be taken into account.
Only words known by the tokenizer will be taken into account.
# Arguments
sequences: A list of sequences.
# Yields
Yields individual texts.
"""
num_words = self.num_words
oov_token_index = self.word_index.get(self.oov_token)
for seq in sequences:
vect = []
for num in seq:
word = self.index_word.get(num)
if word is not None:
if num_words and num >= num_words:
if oov_token_index is not None:
vect.append(self.index_word[oov_token_index])
else:
vect.append(word)
elif self.oov_token is not None:
vect.append(self.index_word[oov_token_index])
vect = ' '.join(vect)
yield vect
def texts_to_matrix(self, texts, mode='binary'):
"""Convert a list of texts to a Numpy matrix.
# Arguments
texts: list of strings.
mode: one of "binary", "count", "tfidf", "freq".
# Returns
A Numpy matrix.
"""
sequences = self.texts_to_sequences(texts)
return self.sequences_to_matrix(sequences, mode=mode)
def sequences_to_matrix(self, sequences, mode='binary'):
"""Converts a list of sequences into a Numpy matrix.
# Arguments
sequences: list of sequences
(a sequence is a list of integer word indices).
mode: one of "binary", "count", "tfidf", "freq"
# Returns
A Numpy matrix.
# Raises
ValueError: In case of invalid `mode` argument,
or if the Tokenizer requires to be fit to sample data.
"""
if not self.num_words:
if self.word_index:
num_words = len(self.word_index) + 1
else:
raise ValueError('Specify a dimension (`num_words` argument), '
'or fit on some text data first.')
else:
num_words = self.num_words
if mode == 'tfidf' and not self.document_count:
raise ValueError('Fit the Tokenizer on some data '
'before using tfidf mode.')
x = np.zeros((len(sequences), num_words))
for i, seq in enumerate(sequences):
if not seq:
continue
counts = defaultdict(int)
for j in seq:
if j >= num_words:
continue
counts[j] += 1
for j, c in list(counts.items()):
if mode == 'count':
x[i][j] = c
elif mode == 'freq':
x[i][j] = c / len(seq)
elif mode == 'binary':
x[i][j] = 1
elif mode == 'tfidf':
# Use weighting scheme 2 in
# https://en.wikipedia.org/wiki/Tf%E2%80%93idf
tf = 1 + np.log(c)
idf = np.log(1 + self.document_count /
(1 + self.index_docs.get(j, 0)))
x[i][j] = tf * idf
else:
raise ValueError('Unknown vectorization mode:', mode)
return x
def get_config(self):
'''Returns the tokenizer configuration as Python dictionary.
The word count dictionaries used by the tokenizer get serialized
into plain JSON, so that the configuration can be read by other
projects.
# Returns
A Python dictionary with the tokenizer configuration.
'''
json_word_counts = json.dumps(self.word_counts)
json_word_docs = json.dumps(self.word_docs)
json_index_docs = json.dumps(self.index_docs)
json_word_index = json.dumps(self.word_index)
json_index_word = json.dumps(self.index_word)
return {
'num_words': self.num_words,
'filters': self.filters,
'lower': self.lower,
'split': self.split,
'char_level': self.char_level,
'oov_token': self.oov_token,
'document_count': self.document_count,
'word_counts': json_word_counts,
'word_docs': json_word_docs,
'index_docs': json_index_docs,
'index_word': json_index_word,
'word_index': json_word_index
}
def to_json(self, **kwargs):
"""Returns a JSON string containing the tokenizer configuration.
To load a tokenizer from a JSON string, use
`keras.preprocessing.text.tokenizer_from_json(json_string)`.
# Arguments
**kwargs: Additional keyword arguments
to be passed to `json.dumps()`.
# Returns
A JSON string containing the tokenizer configuration.
"""
config = self.get_config()
tokenizer_config = {
'class_name': self.__class__.__name__,
'config': config
}
return json.dumps(tokenizer_config, **kwargs)
def tokenizer_from_json(json_string):
"""Parses a JSON tokenizer configuration file and returns a
tokenizer instance.
# Arguments
json_string: JSON string encoding a tokenizer configuration.
# Returns
A Keras Tokenizer instance
"""
tokenizer_config = json.loads(json_string)
config = tokenizer_config.get('config')
word_counts = json.loads(config.pop('word_counts'))
word_docs = json.loads(config.pop('word_docs'))
index_docs = json.loads(config.pop('index_docs'))
# Integer indexing gets converted to strings with json.dumps()
index_docs = {int(k): v for k, v in index_docs.items()}
index_word = json.loads(config.pop('index_word'))
index_word = {int(k): v for k, v in index_word.items()}
word_index = json.loads(config.pop('word_index'))
tokenizer = Tokenizer(**config)
tokenizer.word_counts = word_counts
tokenizer.word_docs = word_docs
tokenizer.index_docs = index_docs
tokenizer.word_index = word_index
tokenizer.index_word = index_word
return tokenizer
'''
keras_preprocessing/sequence.py
'''
# -*- coding: utf-8 -*-
"""Utilities for preprocessing sequence data.
"""
import json
import random
import numpy as np
def pad_sequences(sequences, maxlen=None, dtype='int32',
padding='pre', truncating='pre', value=0.):
"""Pads sequences to the same length.
This function transforms a list of
`num_samples` sequences (lists of integers)
into a 2D Numpy array of shape `(num_samples, num_timesteps)`.
`num_timesteps` is either the `maxlen` argument if provided,
or the length of the longest sequence otherwise.
Sequences that are shorter than `num_timesteps`
are padded with `value` at the beginning or the end
if padding='post.
Sequences longer than `num_timesteps` are truncated
so that they fit the desired length.
The position where padding or truncation happens is determined by
the arguments `padding` and `truncating`, respectively.
Pre-padding is the default.
# Arguments
sequences: List of lists, where each element is a sequence.
maxlen: Int, maximum length of all sequences.
dtype: Type of the output sequences.
To pad sequences with variable length strings, you can use `object`.
padding: String, 'pre' or 'post':
pad either before or after each sequence.
truncating: String, 'pre' or 'post':
remove values from sequences larger than
`maxlen`, either at the beginning or at the end of the sequences.
value: Float or String, padding value.
# Returns
x: Numpy array with shape `(len(sequences), maxlen)`
# Raises
ValueError: In case of invalid values for `truncating` or `padding`,
or in case of invalid shape for a `sequences` entry.
"""
if not hasattr(sequences, '__len__'):
raise ValueError('`sequences` must be iterable.')
num_samples = len(sequences)
lengths = []
sample_shape = ()
flag = True
# take the sample shape from the first non empty sequence
# checking for consistency in the main loop below.
for x in sequences:
try:
lengths.append(len(x))
if flag and len(x):
sample_shape = np.asarray(x).shape[1:]
flag = False
except TypeError:
raise ValueError('`sequences` must be a list of iterables. '
'Found non-iterable: ' + str(x))
if maxlen is None:
maxlen = np.max(lengths)
is_dtype_str = np.issubdtype(dtype, np.str_) or np.issubdtype(dtype, np.unicode_)
if isinstance(value, str) and dtype != object and not is_dtype_str:
raise ValueError("`dtype` {} is not compatible with `value`'s type: {}\n"
"You should set `dtype=object` for variable length strings."
.format(dtype, type(value)))
x = np.full((num_samples, maxlen) + sample_shape, value, dtype=dtype)
for idx, s in enumerate(sequences):
if not len(s):
continue # empty list/array was found
if truncating == 'pre':
trunc = s[-maxlen:]
elif truncating == 'post':
trunc = s[:maxlen]
else:
raise ValueError('Truncating type "%s" '
'not understood' % truncating)
# check `trunc` has expected shape
trunc = np.asarray(trunc, dtype=dtype)
if trunc.shape[1:] != sample_shape:
raise ValueError('Shape of sample %s of sequence at position %s '
'is different from expected shape %s' %
(trunc.shape[1:], idx, sample_shape))
if padding == 'post':
x[idx, :len(trunc)] = trunc
elif padding == 'pre':
x[idx, -len(trunc):] = trunc
else:
raise ValueError('Padding type "%s" not understood' % padding)
return x
def make_sampling_table(size, sampling_factor=1e-5):
"""Generates a word rank-based probabilistic sampling table.
Used for generating the `sampling_table` argument for `skipgrams`.
`sampling_table[i]` is the probability of sampling
the word i-th most common word in a dataset
(more common words should be sampled less frequently, for balance).
The sampling probabilities are generated according
to the sampling distribution used in word2vec:
```
p(word) = (min(1, sqrt(word_frequency / sampling_factor) /
(word_frequency / sampling_factor)))
```
We assume that the word frequencies follow Zipf's law (s=1) to derive
a numerical approximation of frequency(rank):
`frequency(rank) ~ 1/(rank * (log(rank) + gamma) + 1/2 - 1/(12*rank))`
where `gamma` is the Euler-Mascheroni constant.
# Arguments
size: Int, number of possible words to sample.
sampling_factor: The sampling factor in the word2vec formula.
# Returns
A 1D Numpy array of length `size` where the ith entry
is the probability that a word of rank i should be sampled.
"""
gamma = 0.577
rank = np.arange(size)
rank[0] = 1
inv_fq = rank * (np.log(rank) + gamma) + 0.5 - 1. / (12. * rank)
f = sampling_factor * inv_fq
return np.minimum(1., f / np.sqrt(f))
def skipgrams(sequence, vocabulary_size,
window_size=4, negative_samples=1., shuffle=True,
categorical=False, sampling_table=None, seed=None):
"""Generates skipgram word pairs.
This function transforms a sequence of word indexes (list of integers)
into tuples of words of the form:
- (word, word in the same window), with label 1 (positive samples).
- (word, random word from the vocabulary), with label 0 (negative samples).
Read more about Skipgram in this gnomic paper by Mikolov et al.:
[Efficient Estimation of Word Representations in
Vector Space](http://arxiv.org/pdf/1301.3781v3.pdf)
# Arguments
sequence: A word sequence (sentence), encoded as a list
of word indices (integers). If using a `sampling_table`,
word indices are expected to match the rank
of the words in a reference dataset (e.g. 10 would encode
the 10-th most frequently occurring token).
Note that index 0 is expected to be a non-word and will be skipped.
vocabulary_size: Int, maximum possible word index + 1
window_size: Int, size of sampling windows (technically half-window).
The window of a word `w_i` will be
`[i - window_size, i + window_size+1]`.
negative_samples: Float >= 0. 0 for no negative (i.e. random) samples.
1 for same number as positive samples.
shuffle: Whether to shuffle the word couples before returning them.
categorical: bool. if False, labels will be
integers (eg. `[0, 1, 1 .. ]`),
if `True`, labels will be categorical, e.g.
`[[1,0],[0,1],[0,1] .. ]`.
sampling_table: 1D array of size `vocabulary_size` where the entry i
encodes the probability to sample a word of rank i.
seed: Random seed.
# Returns
couples, labels: where `couples` are int pairs and
`labels` are either 0 or 1.
# Note
By convention, index 0 in the vocabulary is
a non-word and will be skipped.
"""
couples = []
labels = []
for i, wi in enumerate(sequence):
if not wi:
continue
if sampling_table is not None:
if sampling_table[wi] < random.random():
continue
window_start = max(0, i - window_size)
window_end = min(len(sequence), i + window_size + 1)
for j in range(window_start, window_end):
if j != i:
wj = sequence[j]
if not wj:
continue
couples.append([wi, wj])
if categorical:
labels.append([0, 1])
else:
labels.append(1)
if negative_samples > 0:
num_negative_samples = int(len(labels) * negative_samples)
words = [c[0] for c in couples]
random.shuffle(words)
couples += [[words[i % len(words)],
random.randint(1, vocabulary_size - 1)]
for i in range(num_negative_samples)]
if categorical:
labels += [[1, 0]] * num_negative_samples
else:
labels += [0] * num_negative_samples
if shuffle:
if seed is None:
seed = random.randint(0, 10e6)
random.seed(seed)
random.shuffle(couples)
random.seed(seed)
random.shuffle(labels)
return couples, labels
def _remove_long_seq(maxlen, seq, label):
"""Removes sequences that exceed the maximum length.
# Arguments
maxlen: Int, maximum length of the output sequences.
seq: List of lists, where each sublist is a sequence.
label: List where each element is an integer.
# Returns
new_seq, new_label: shortened lists for `seq` and `label`.
"""
new_seq, new_label = [], []
for x, y in zip(seq, label):
if len(x) < maxlen:
new_seq.append(x)
new_label.append(y)
return new_seq, new_label
class TimeseriesGenerator(object):
"""Utility class for generating batches of temporal data.
This class takes in a sequence of data-points gathered at
equal intervals, along with time series parameters such as
stride, length of history, etc., to produce batches for
training/validation.
# Arguments
data: Indexable generator (such as list or Numpy array)
containing consecutive data points (timesteps).
The data should be at 2D, and axis 0 is expected
to be the time dimension.
targets: Targets corresponding to timesteps in `data`.
It should have same length as `data`.
length: Length of the output sequences (in number of timesteps).
sampling_rate: Period between successive individual timesteps
within sequences. For rate `r`, timesteps
`data[i]`, `data[i-r]`, ... `data[i - length]`
are used for create a sample sequence.
stride: Period between successive output sequences.
For stride `s`, consecutive output samples would
be centered around `data[i]`, `data[i+s]`, `data[i+2*s]`, etc.
start_index: Data points earlier than `start_index` will not be used
in the output sequences. This is useful to reserve part of the
data for test or validation.
end_index: Data points later than `end_index` will not be used
in the output sequences. This is useful to reserve part of the
data for test or validation.
shuffle: Whether to shuffle output samples,
or instead draw them in chronological order.
reverse: Boolean: if `true`, timesteps in each output sample will be
in reverse chronological order.
batch_size: Number of timeseries samples in each batch
(except maybe the last one).
# Returns
A [Sequence](/utils/#sequence) instance.
# Examples
```python
from keras.preprocessing.sequence import TimeseriesGenerator
import numpy as np
data = np.array([[i] for i in range(50)])
targets = np.array([[i] for i in range(50)])
data_gen = TimeseriesGenerator(data, targets,
length=10, sampling_rate=2,
batch_size=2)
assert len(data_gen) == 20
batch_0 = data_gen[0]
x, y = batch_0
assert np.array_equal(x,
np.array([[[0], [2], [4], [6], [8]],
[[1], [3], [5], [7], [9]]]))
assert np.array_equal(y,
np.array([[10], [11]]))
```
"""
def __init__(self, data, targets, length,
sampling_rate=1,
stride=1,
start_index=0,
end_index=None,
shuffle=False,
reverse=False,
batch_size=128):
if len(data) != len(targets):
raise ValueError('Data and targets have to be' +
' of same length. '
'Data length is {}'.format(len(data)) +
' while target length is {}'.format(len(targets)))
self.data = data
self.targets = targets
self.length = length
self.sampling_rate = sampling_rate
self.stride = stride
self.start_index = start_index + length
if end_index is None:
end_index = len(data) - 1
self.end_index = end_index
self.shuffle = shuffle
self.reverse = reverse
self.batch_size = batch_size
if self.start_index > self.end_index:
raise ValueError('`start_index+length=%i > end_index=%i` '
'is disallowed, as no part of the sequence '
'would be left to be used as current step.'
% (self.start_index, self.end_index))
def __len__(self):
return (self.end_index - self.start_index +
self.batch_size * self.stride) // (self.batch_size * self.stride)
def __getitem__(self, index):
if self.shuffle:
rows = np.random.randint(
self.start_index, self.end_index + 1, size=self.batch_size)
else:
i = self.start_index + self.batch_size * self.stride * index
rows = np.arange(i, min(i + self.batch_size *
self.stride, self.end_index + 1), self.stride)
samples = np.array([self.data[row - self.length:row:self.sampling_rate]
for row in rows])
targets = np.array([self.targets[row] for row in rows])
if self.reverse:
return samples[:, ::-1, ...], targets
return samples, targets
def get_config(self):
'''Returns the TimeseriesGenerator configuration as Python dictionary.
# Returns
A Python dictionary with the TimeseriesGenerator configuration.
'''
data = self.data
if type(self.data).__module__ == np.__name__:
data = self.data.tolist()
try:
json_data = json.dumps(data)
except TypeError:
raise TypeError('Data not JSON Serializable:', data)
targets = self.targets
if type(self.targets).__module__ == np.__name__:
targets = self.targets.tolist()
try:
json_targets = json.dumps(targets)
except TypeError:
raise TypeError('Targets not JSON Serializable:', targets)
return {
'data': json_data,
'targets': json_targets,
'length': self.length,
'sampling_rate': self.sampling_rate,
'stride': self.stride,
'start_index': self.start_index,
'end_index': self.end_index,
'shuffle': self.shuffle,
'reverse': self.reverse,
'batch_size': self.batch_size
}
def to_json(self, **kwargs):
"""Returns a JSON string containing the timeseries generator
configuration. To load a generator from a JSON string, use
`keras.preprocessing.sequence.timeseries_generator_from_json(json_string)`.
# Arguments
**kwargs: Additional keyword arguments
to be passed to `json.dumps()`.
# Returns
A JSON string containing the tokenizer configuration.
"""
config = self.get_config()
timeseries_generator_config = {
'class_name': self.__class__.__name__,
'config': config
}
return json.dumps(timeseries_generator_config, **kwargs)
def timeseries_generator_from_json(json_string):
"""Parses a JSON timeseries generator configuration file and
returns a timeseries generator instance.
# Arguments
json_string: JSON string encoding a timeseries
generator configuration.
# Returns
A Keras TimeseriesGenerator instance
"""
full_config = json.loads(json_string)
config = full_config.get('config')
data = json.loads(config.pop('data'))
config['data'] = data
targets = json.loads(config.pop('targets'))
config['targets'] = targets
return TimeseriesGenerator(**config)
'''
keras_preprocessing/__init__.py
'''
"""Enables dynamic setting of underlying Keras module.
"""
_KERAS_BACKEND = None
_KERAS_UTILS = None
def set_keras_submodules(backend, utils):
# Deprecated, will be removed in the future.
global _KERAS_BACKEND
global _KERAS_UTILS
_KERAS_BACKEND = backend
_KERAS_UTILS = utils
def get_keras_submodule(name):
# Deprecated, will be removed in the future.
if name not in {'backend', 'utils'}:
raise ImportError(
'Can only retrieve "backend" and "utils". '
'Requested: %s' % name)
if _KERAS_BACKEND is None:
raise ImportError('You need to first `import keras` '
'in order to use `keras_preprocessing`. '
'For instance, you can do:\n\n'
'```\n'
'import keras\n'
'from keras_preprocessing import image\n'
'```\n\n'
'Or, preferably, this equivalent formulation:\n\n'
'```\n'
'from keras import preprocessing\n'
'```\n')
if name == 'backend':
return _KERAS_BACKEND
elif name == 'utils':
return _KERAS_UTILS
__version__ = '1.1.2'
| 3 | 1,002 | Python |
blackjack | ./ProjectTest/Python/blackjack.py | '''
blackjack/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
blackjack/player.py
'''
class BlackjackPlayer:
def __init__(self, player_id, np_random):
''' Initialize a Blackjack player class
Args:
player_id (int): id for the player
'''
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.status = 'alive'
self.score = 0
def get_player_id(self):
''' Return player's id
'''
return self.player_id
'''
blackjack/dealer.py
'''
import numpy as np
from blackjack import Card
def init_standard_deck():
''' Initialize a standard deck of 52 cards
Returns:
(list): A list of Card object
'''
suit_list = ['S', 'H', 'D', 'C']
rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
res = [Card(suit, rank) for suit in suit_list for rank in rank_list]
return res
class BlackjackDealer:
def __init__(self, np_random, num_decks=1):
''' Initialize a Blackjack dealer class
'''
self.np_random = np_random
self.num_decks = num_decks
self.deck = init_standard_deck()
if self.num_decks not in [0, 1]: # 0 indicates infinite decks of cards
self.deck = self.deck * self.num_decks # copy m standard decks of cards
self.shuffle()
self.hand = []
self.status = 'alive'
self.score = 0
def shuffle(self):
''' Shuffle the deck
'''
shuffle_deck = np.array(self.deck)
self.np_random.shuffle(shuffle_deck)
self.deck = list(shuffle_deck)
def deal_card(self, player):
''' Distribute one card to the player
Args:
player_id (int): the target player's id
'''
idx = self.np_random.choice(len(self.deck))
card = self.deck[idx]
if self.num_decks != 0: # If infinite decks, do not pop card from deck
self.deck.pop(idx)
# card = self.deck.pop()
player.hand.append(card)
'''
blackjack/judger.py
'''
class BlackjackJudger:
def __init__(self, np_random):
''' Initialize a BlackJack judger class
'''
self.np_random = np_random
self.rank2score = {"A":11, "2":2, "3":3, "4":4, "5":5, "6":6, "7":7, "8":8, "9":9, "T":10, "J":10, "Q":10, "K":10}
def judge_round(self, player):
''' Judge the target player's status
Args:
player (int): target player's id
Returns:
status (str): the status of the target player
score (int): the current score of the player
'''
score = self.judge_score(player.hand)
if score <= 21:
return "alive", score
else:
return "bust", score
def judge_game(self, game, game_pointer):
''' Judge the winner of the game
Args:
game (class): target game class
'''
'''
game.winner['dealer'] doesn't need anymore if we change code like this
player bust (whether dealer bust or not) => game.winner[playerX] = -1
player and dealer tie => game.winner[playerX] = 1
dealer bust and player not bust => game.winner[playerX] = 2
player get higher score than dealer => game.winner[playerX] = 2
dealer get higher score than player => game.winner[playerX] = -1
game.winner[playerX] = 0 => the game is still ongoing
'''
if game.players[game_pointer].status == 'bust':
game.winner['player' + str(game_pointer)] = -1
elif game.dealer.status == 'bust':
game.winner['player' + str(game_pointer)] = 2
else:
if game.players[game_pointer].score > game.dealer.score:
game.winner['player' + str(game_pointer)] = 2
elif game.players[game_pointer].score < game.dealer.score:
game.winner['player' + str(game_pointer)] = -1
else:
game.winner['player' + str(game_pointer)] = 1
def judge_score(self, cards):
''' Judge the score of a given cards set
Args:
cards (list): a list of cards
Returns:
score (int): the score of the given cards set
'''
score = 0
count_a = 0
for card in cards:
card_score = self.rank2score[card.rank]
score += card_score
if card.rank == 'A':
count_a += 1
while score > 21 and count_a > 0:
count_a -= 1
score -= 10
return score
'''
blackjack/game.py
'''
from copy import deepcopy
import numpy as np
from blackjack import Dealer
from blackjack import Player
from blackjack import Judger
class BlackjackGame:
def __init__(self, allow_step_back=False):
''' Initialize the class Blackjack Game
'''
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
def configure(self, game_config):
''' Specifiy some game specific parameters, such as number of players
'''
self.num_players = game_config['game_num_players']
self.num_decks = game_config['game_num_decks']
def init_game(self):
''' Initialilze the game
Returns:
state (dict): the first state of the game
player_id (int): current player's id
'''
self.dealer = Dealer(self.np_random, self.num_decks)
self.players = []
for i in range(self.num_players):
self.players.append(Player(i, self.np_random))
self.judger = Judger(self.np_random)
for i in range(2):
for j in range(self.num_players):
self.dealer.deal_card(self.players[j])
self.dealer.deal_card(self.dealer)
for i in range(self.num_players):
self.players[i].status, self.players[i].score = self.judger.judge_round(self.players[i])
self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer)
self.winner = {'dealer': 0}
for i in range(self.num_players):
self.winner['player' + str(i)] = 0
self.history = []
self.game_pointer = 0
return self.get_state(self.game_pointer), self.game_pointer
def step(self, action):
''' Get the next state
Args:
action (str): a specific action of blackjack. (Hit or Stand)
Returns:/
dict: next player's state
int: next plater's id
'''
if self.allow_step_back:
p = deepcopy(self.players[self.game_pointer])
d = deepcopy(self.dealer)
w = deepcopy(self.winner)
self.history.append((d, p, w))
next_state = {}
# Play hit
if action != "stand":
self.dealer.deal_card(self.players[self.game_pointer])
self.players[self.game_pointer].status, self.players[self.game_pointer].score = self.judger.judge_round(
self.players[self.game_pointer])
if self.players[self.game_pointer].status == 'bust':
# game over, set up the winner, print out dealer's hand # If bust, pass the game pointer
if self.game_pointer >= self.num_players - 1:
while self.judger.judge_score(self.dealer.hand) < 17:
self.dealer.deal_card(self.dealer)
self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer)
for i in range(self.num_players):
self.judger.judge_game(self, i)
self.game_pointer = 0
else:
self.game_pointer += 1
elif action == "stand": # If stand, first try to pass the pointer, if it's the last player, dealer deal for himself, then judge game for everyone using a loop
self.players[self.game_pointer].status, self.players[self.game_pointer].score = self.judger.judge_round(
self.players[self.game_pointer])
if self.game_pointer >= self.num_players - 1:
while self.judger.judge_score(self.dealer.hand) < 17:
self.dealer.deal_card(self.dealer)
self.dealer.status, self.dealer.score = self.judger.judge_round(self.dealer)
for i in range(self.num_players):
self.judger.judge_game(self, i)
self.game_pointer = 0
else:
self.game_pointer += 1
hand = [card.get_index() for card in self.players[self.game_pointer].hand]
if self.is_over():
dealer_hand = [card.get_index() for card in self.dealer.hand]
else:
dealer_hand = [card.get_index() for card in self.dealer.hand[1:]]
for i in range(self.num_players):
next_state['player' + str(i) + ' hand'] = [card.get_index() for card in self.players[i].hand]
next_state['dealer hand'] = dealer_hand
next_state['actions'] = ('hit', 'stand')
next_state['state'] = (hand, dealer_hand)
return next_state, self.game_pointer
def step_back(self):
''' Return to the previous state of the game
Returns:
Status (bool): check if the step back is success or not
'''
#while len(self.history) > 0:
if len(self.history) > 0:
self.dealer, self.players[self.game_pointer], self.winner = self.history.pop()
return True
return False
def get_num_players(self):
''' Return the number of players in blackjack
Returns:
number_of_player (int): blackjack only have 1 player
'''
return self.num_players
@staticmethod
def get_num_actions():
''' Return the number of applicable actions
Returns:
number_of_actions (int): there are only two actions (hit and stand)
'''
return 2
def get_player_id(self):
''' Return the current player's id
Returns:
player_id (int): current player's id
'''
return self.game_pointer
def get_state(self, player_id):
''' Return player's state
Args:
player_id (int): player id
Returns:
state (dict): corresponding player's state
'''
'''
before change state only have two keys (action, state)
but now have more than 4 keys (action, state, player0 hand, player1 hand, ... , dealer hand)
Although key 'state' have duplicated information with key 'player hand' and 'dealer hand', I couldn't remove it because of other codes
To remove it, we need to change dqn agent too in my opinion
'''
state = {}
state['actions'] = ('hit', 'stand')
hand = [card.get_index() for card in self.players[player_id].hand]
if self.is_over():
dealer_hand = [card.get_index() for card in self.dealer.hand]
else:
dealer_hand = [card.get_index() for card in self.dealer.hand[1:]]
for i in range(self.num_players):
state['player' + str(i) + ' hand'] = [card.get_index() for card in self.players[i].hand]
state['dealer hand'] = dealer_hand
state['state'] = (hand, dealer_hand)
return state
def is_over(self):
''' Check if the game is over
Returns:
status (bool): True/False
'''
'''
I should change here because judger and self.winner is changed too
'''
for i in range(self.num_players):
if self.winner['player' + str(i)] == 0:
return False
return True
'''
blackjack/__init__.py
'''
from blackjack.base import Card as Card
from blackjack.dealer import BlackjackDealer as Dealer
from blackjack.judger import BlackjackJudger as Judger
from blackjack.player import BlackjackPlayer as Player
from blackjack.game import BlackjackGame as Game
| 6 | 401 | Python |
fuzzywuzzy | ./ProjectTest/Python/fuzzywuzzy.py | '''
fuzzywuzzy/string_processing.py
'''
from __future__ import unicode_literals
import re
import string
import sys
PY3 = sys.version_info[0] == 3
if PY3:
string = str
class StringProcessor(object):
"""
This class defines method to process strings in the most
efficient way. Ideally all the methods below use unicode strings
for both input and output.
"""
regex = re.compile(r"(?ui)\W")
@classmethod
def replace_non_letters_non_numbers_with_whitespace(cls, a_string):
"""
This function replaces any sequence of non letters and non
numbers with a single white space.
"""
return cls.regex.sub(" ", a_string)
strip = staticmethod(string.strip)
to_lower_case = staticmethod(string.lower)
to_upper_case = staticmethod(string.upper)
'''
fuzzywuzzy/fuzz.py
'''
#!/usr/bin/env python
# encoding: utf-8
from __future__ import unicode_literals
import platform
import warnings
try:
from .StringMatcher import StringMatcher as SequenceMatcher
except ImportError:
if platform.python_implementation() != "PyPy":
warnings.warn('Using slow pure-python SequenceMatcher. Install python-Levenshtein to remove this warning')
from difflib import SequenceMatcher
import utils
###########################
# Basic Scoring Functions #
###########################
@utils.check_for_none
@utils.check_for_equivalence
@utils.check_empty_string
def ratio(s1, s2):
s1, s2 = utils.make_type_consistent(s1, s2)
m = SequenceMatcher(None, s1, s2)
return utils.intr(100 * m.ratio())
@utils.check_for_none
@utils.check_for_equivalence
@utils.check_empty_string
def partial_ratio(s1, s2):
""""Return the ratio of the most similar substring
as a number between 0 and 100."""
s1, s2 = utils.make_type_consistent(s1, s2)
if len(s1) <= len(s2):
shorter = s1
longer = s2
else:
shorter = s2
longer = s1
m = SequenceMatcher(None, shorter, longer)
blocks = m.get_matching_blocks()
# each block represents a sequence of matching characters in a string
# of the form (idx_1, idx_2, len)
# the best partial match will block align with at least one of those blocks
# e.g. shorter = "abcd", longer = XXXbcdeEEE
# block = (1,3,3)
# best score === ratio("abcd", "Xbcd")
scores = []
for block in blocks:
long_start = block[1] - block[0] if (block[1] - block[0]) > 0 else 0
long_end = long_start + len(shorter)
long_substr = longer[long_start:long_end]
m2 = SequenceMatcher(None, shorter, long_substr)
r = m2.ratio()
if r > .995:
return 100
else:
scores.append(r)
return utils.intr(100 * max(scores))
##############################
# Advanced Scoring Functions #
##############################
def _process_and_sort(s, force_ascii, full_process=True):
"""Return a cleaned string with token sorted."""
# pull tokens
ts = utils.full_process(s, force_ascii=force_ascii) if full_process else s
tokens = ts.split()
# sort tokens and join
sorted_string = u" ".join(sorted(tokens))
return sorted_string.strip()
# Sorted Token
# find all alphanumeric tokens in the string
# sort those tokens and take ratio of resulting joined strings
# controls for unordered string elements
@utils.check_for_none
def _token_sort(s1, s2, partial=True, force_ascii=True, full_process=True):
sorted1 = _process_and_sort(s1, force_ascii, full_process=full_process)
sorted2 = _process_and_sort(s2, force_ascii, full_process=full_process)
if partial:
return partial_ratio(sorted1, sorted2)
else:
return ratio(sorted1, sorted2)
def token_sort_ratio(s1, s2, force_ascii=True, full_process=True):
"""Return a measure of the sequences' similarity between 0 and 100
but sorting the token before comparing.
"""
return _token_sort(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process)
def partial_token_sort_ratio(s1, s2, force_ascii=True, full_process=True):
"""Return the ratio of the most similar substring as a number between
0 and 100 but sorting the token before comparing.
"""
return _token_sort(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process)
@utils.check_for_none
def _token_set(s1, s2, partial=True, force_ascii=True, full_process=True):
"""Find all alphanumeric tokens in each string...
- treat them as a set
- construct two strings of the form:
<sorted_intersection><sorted_remainder>
- take ratios of those two strings
- controls for unordered partial matches"""
if not full_process and s1 == s2:
return 100
p1 = utils.full_process(s1, force_ascii=force_ascii) if full_process else s1
p2 = utils.full_process(s2, force_ascii=force_ascii) if full_process else s2
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
# pull tokens
tokens1 = set(p1.split())
tokens2 = set(p2.split())
intersection = tokens1.intersection(tokens2)
diff1to2 = tokens1.difference(tokens2)
diff2to1 = tokens2.difference(tokens1)
sorted_sect = " ".join(sorted(intersection))
sorted_1to2 = " ".join(sorted(diff1to2))
sorted_2to1 = " ".join(sorted(diff2to1))
combined_1to2 = sorted_sect + " " + sorted_1to2
combined_2to1 = sorted_sect + " " + sorted_2to1
# strip
sorted_sect = sorted_sect.strip()
combined_1to2 = combined_1to2.strip()
combined_2to1 = combined_2to1.strip()
if partial:
ratio_func = partial_ratio
else:
ratio_func = ratio
pairwise = [
ratio_func(sorted_sect, combined_1to2),
ratio_func(sorted_sect, combined_2to1),
ratio_func(combined_1to2, combined_2to1)
]
return max(pairwise)
def token_set_ratio(s1, s2, force_ascii=True, full_process=True):
return _token_set(s1, s2, partial=False, force_ascii=force_ascii, full_process=full_process)
def partial_token_set_ratio(s1, s2, force_ascii=True, full_process=True):
return _token_set(s1, s2, partial=True, force_ascii=force_ascii, full_process=full_process)
###################
# Combination API #
###################
# q is for quick
def QRatio(s1, s2, force_ascii=True, full_process=True):
"""
Quick ratio comparison between two strings.
Runs full_process from utils on both strings
Short circuits if either of the strings is empty after processing.
:param s1:
:param s2:
:param force_ascii: Allow only ASCII characters (Default: True)
:full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)
:return: similarity ratio
"""
if full_process:
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
else:
p1 = s1
p2 = s2
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
return ratio(p1, p2)
def UQRatio(s1, s2, full_process=True):
"""
Unicode quick ratio
Calls QRatio with force_ascii set to False
:param s1:
:param s2:
:return: similarity ratio
"""
return QRatio(s1, s2, force_ascii=False, full_process=full_process)
# w is for weighted
def WRatio(s1, s2, force_ascii=True, full_process=True):
"""
Return a measure of the sequences' similarity between 0 and 100, using different algorithms.
**Steps in the order they occur**
#. Run full_process from utils on both strings
#. Short circuit if this makes either string empty
#. Take the ratio of the two processed strings (fuzz.ratio)
#. Run checks to compare the length of the strings
* If one of the strings is more than 1.5 times as long as the other
use partial_ratio comparisons - scale partial results by 0.9
(this makes sure only full results can return 100)
* If one of the strings is over 8 times as long as the other
instead scale by 0.6
#. Run the other ratio functions
* if using partial ratio functions call partial_ratio,
partial_token_sort_ratio and partial_token_set_ratio
scale all of these by the ratio based on length
* otherwise call token_sort_ratio and token_set_ratio
* all token based comparisons are scaled by 0.95
(on top of any partial scalars)
#. Take the highest value from these results
round it and return it as an integer.
:param s1:
:param s2:
:param force_ascii: Allow only ascii characters
:type force_ascii: bool
:full_process: Process inputs, used here to avoid double processing in extract functions (Default: True)
:return:
"""
if full_process:
p1 = utils.full_process(s1, force_ascii=force_ascii)
p2 = utils.full_process(s2, force_ascii=force_ascii)
else:
p1 = s1
p2 = s2
if not utils.validate_string(p1):
return 0
if not utils.validate_string(p2):
return 0
# should we look at partials?
try_partial = True
unbase_scale = .95
partial_scale = .90
base = ratio(p1, p2)
len_ratio = float(max(len(p1), len(p2))) / min(len(p1), len(p2))
# if strings are similar length, don't use partials
if len_ratio < 1.5:
try_partial = False
# if one string is much much shorter than the other
if len_ratio > 8:
partial_scale = .6
if try_partial:
partial = partial_ratio(p1, p2) * partial_scale
ptsor = partial_token_sort_ratio(p1, p2, full_process=False) \
* unbase_scale * partial_scale
ptser = partial_token_set_ratio(p1, p2, full_process=False) \
* unbase_scale * partial_scale
return utils.intr(max(base, partial, ptsor, ptser))
else:
tsor = token_sort_ratio(p1, p2, full_process=False) * unbase_scale
tser = token_set_ratio(p1, p2, full_process=False) * unbase_scale
return utils.intr(max(base, tsor, tser))
def UWRatio(s1, s2, full_process=True):
"""Return a measure of the sequences' similarity between 0 and 100,
using different algorithms. Same as WRatio but preserving unicode.
"""
return WRatio(s1, s2, force_ascii=False, full_process=full_process)
'''
fuzzywuzzy/utils.py
'''
from __future__ import unicode_literals
import sys
import functools
from string_processing import StringProcessor
PY3 = sys.version_info[0] == 3
def validate_string(s):
"""
Check input has length and that length > 0
:param s:
:return: True if len(s) > 0 else False
"""
try:
return len(s) > 0
except TypeError:
return False
def check_for_equivalence(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
if args[0] == args[1]:
return 100
return func(*args, **kwargs)
return decorator
def check_for_none(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
if args[0] is None or args[1] is None:
return 0
return func(*args, **kwargs)
return decorator
def check_empty_string(func):
@functools.wraps(func)
def decorator(*args, **kwargs):
if len(args[0]) == 0 or len(args[1]) == 0:
return 0
return func(*args, **kwargs)
return decorator
bad_chars = str("").join([chr(i) for i in range(128, 256)]) # ascii dammit!
if PY3:
translation_table = dict((ord(c), None) for c in bad_chars)
unicode = str
def asciionly(s):
if PY3:
return s.translate(translation_table)
else:
return s.translate(None, bad_chars)
def asciidammit(s):
if type(s) is str:
return asciionly(s)
elif type(s) is unicode:
return asciionly(s.encode('ascii', 'ignore'))
else:
return asciidammit(unicode(s))
def make_type_consistent(s1, s2):
"""If both objects aren't either both string or unicode instances force them to unicode"""
if isinstance(s1, str) and isinstance(s2, str):
return s1, s2
elif isinstance(s1, unicode) and isinstance(s2, unicode):
return s1, s2
else:
return unicode(s1), unicode(s2)
def full_process(s, force_ascii=False):
"""Process string by
-- removing all but letters and numbers
-- trim whitespace
-- force to lower case
if force_ascii == True, force convert to ascii"""
if force_ascii:
s = asciidammit(s)
# Keep only Letters and Numbers (see Unicode docs).
string_out = StringProcessor.replace_non_letters_non_numbers_with_whitespace(s)
# Force into lowercase.
string_out = StringProcessor.to_lower_case(string_out)
# Remove leading and trailing whitespaces.
string_out = StringProcessor.strip(string_out)
return string_out
def intr(n):
'''Returns a correctly rounded integer'''
return int(round(n))
'''
fuzzywuzzy/__init__.py
'''
# -*- coding: utf-8 -*-
__version__ = '0.18.0'
'''
fuzzywuzzy/StringMatcher.py
'''
#!/usr/bin/env python
# encoding: utf-8
"""
StringMatcher.py
ported from python-Levenshtein
[https://github.com/miohtama/python-Levenshtein]
License available here: https://github.com/miohtama/python-Levenshtein/blob/master/COPYING
"""
from Levenshtein import *
from warnings import warn
class StringMatcher:
"""A SequenceMatcher-like class built on the top of Levenshtein"""
def _reset_cache(self):
self._ratio = self._distance = None
self._opcodes = self._editops = self._matching_blocks = None
def __init__(self, isjunk=None, seq1='', seq2=''):
if isjunk:
warn("isjunk not NOT implemented, it will be ignored")
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seqs(self, seq1, seq2):
self._str1, self._str2 = seq1, seq2
self._reset_cache()
def set_seq1(self, seq1):
self._str1 = seq1
self._reset_cache()
def set_seq2(self, seq2):
self._str2 = seq2
self._reset_cache()
def get_opcodes(self):
if not self._opcodes:
if self._editops:
self._opcodes = opcodes(self._editops, self._str1, self._str2)
else:
self._opcodes = opcodes(self._str1, self._str2)
return self._opcodes
def get_editops(self):
if not self._editops:
if self._opcodes:
self._editops = editops(self._opcodes, self._str1, self._str2)
else:
self._editops = editops(self._str1, self._str2)
return self._editops
def get_matching_blocks(self):
if not self._matching_blocks:
self._matching_blocks = matching_blocks(self.get_opcodes(),
self._str1, self._str2)
return self._matching_blocks
def ratio(self):
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def quick_ratio(self):
# This is usually quick enough :o)
if not self._ratio:
self._ratio = ratio(self._str1, self._str2)
return self._ratio
def real_quick_ratio(self):
len1, len2 = len(self._str1), len(self._str2)
return 2.0 * min(len1, len2) / (len1 + len2)
def distance(self):
if not self._distance:
self._distance = distance(self._str1, self._str2)
return self._distance
'''
fuzzywuzzy/process.py
'''
#!/usr/bin/env python
# encoding: utf-8
import fuzz
import utils
import heapq
import logging
from functools import partial
default_scorer = fuzz.WRatio
default_processor = utils.full_process
def extractWithoutOrder(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
"""Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
generator of tuples containing the match and its score. If a dictionary
is used, also returns the key for each match.
Arguments:
query: An object representing the thing we want to find.
choices: An iterable or dictionary-like object containing choices
to be matched against the query. Dictionary arguments of
{key: value} pairs will attempt to match the query against
each value.
processor: Optional function of the form f(a) -> b, where a is the query or
individual choice and b is the choice to be used in matching.
This can be used to match against, say, the first element of
a list:
lambda x: x[0]
Defaults to fuzzywuzzy.utils.full_process().
scorer: Optional function for scoring matches between the query and
an individual processed choice. This should be a function
of the form f(query, choice) -> int.
By default, fuzz.WRatio() is used and expects both query and
choice to be strings.
score_cutoff: Optional argument for score threshold. No matches with
a score less than this number will be returned. Defaults to 0.
Returns:
Generator of tuples containing the match and its score.
If a list is used for choices, then the result will be 2-tuples.
If a dictionary is used, then the result will be 3-tuples containing
the key for each match.
For example, searching for 'bird' in the dictionary
{'bard': 'train', 'dog': 'man'}
may return
('train', 22, 'bard'), ('man', 0, 'dog')
"""
# Catch generators without lengths
def no_process(x):
return x
try:
if choices is None or len(choices) == 0:
return
except TypeError:
pass
# If the processor was removed by setting it to None
# perfom a noop as it still needs to be a function
if processor is None:
processor = no_process
# Run the processor on the input query.
processed_query = processor(query)
if len(processed_query) == 0:
logging.warning(u"Applied processor reduces input query to empty string, "
"all comparisons will have score 0. "
"[Query: \'{0}\']".format(query))
# Don't run full_process twice
if scorer in [fuzz.WRatio, fuzz.QRatio,
fuzz.token_set_ratio, fuzz.token_sort_ratio,
fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio,
fuzz.UWRatio, fuzz.UQRatio] \
and processor == utils.full_process:
processor = no_process
# Only process the query once instead of for every choice
if scorer in [fuzz.UWRatio, fuzz.UQRatio]:
pre_processor = partial(utils.full_process, force_ascii=False)
scorer = partial(scorer, full_process=False)
elif scorer in [fuzz.WRatio, fuzz.QRatio,
fuzz.token_set_ratio, fuzz.token_sort_ratio,
fuzz.partial_token_set_ratio, fuzz.partial_token_sort_ratio]:
pre_processor = partial(utils.full_process, force_ascii=True)
scorer = partial(scorer, full_process=False)
else:
pre_processor = no_process
processed_query = pre_processor(processed_query)
try:
# See if choices is a dictionary-like object.
for key, choice in choices.items():
processed = pre_processor(processor(choice))
score = scorer(processed_query, processed)
if score >= score_cutoff:
yield (choice, score, key)
except AttributeError:
# It's a list; just iterate over it.
for choice in choices:
processed = pre_processor(processor(choice))
score = scorer(processed_query, processed)
if score >= score_cutoff:
yield (choice, score)
def extract(query, choices, processor=default_processor, scorer=default_scorer, limit=5):
"""Select the best match in a list or dictionary of choices.
Find best matches in a list or dictionary of choices, return a
list of tuples containing the match and its score. If a dictionary
is used, also returns the key for each match.
Arguments:
query: An object representing the thing we want to find.
choices: An iterable or dictionary-like object containing choices
to be matched against the query. Dictionary arguments of
{key: value} pairs will attempt to match the query against
each value.
processor: Optional function of the form f(a) -> b, where a is the query or
individual choice and b is the choice to be used in matching.
This can be used to match against, say, the first element of
a list:
lambda x: x[0]
Defaults to fuzzywuzzy.utils.full_process().
scorer: Optional function for scoring matches between the query and
an individual processed choice. This should be a function
of the form f(query, choice) -> int.
By default, fuzz.WRatio() is used and expects both query and
choice to be strings.
limit: Optional maximum for the number of elements returned. Defaults
to 5.
Returns:
List of tuples containing the match and its score.
If a list is used for choices, then the result will be 2-tuples.
If a dictionary is used, then the result will be 3-tuples containing
the key for each match.
For example, searching for 'bird' in the dictionary
{'bard': 'train', 'dog': 'man'}
may return
[('train', 22, 'bard'), ('man', 0, 'dog')]
"""
sl = extractWithoutOrder(query, choices, processor, scorer)
return heapq.nlargest(limit, sl, key=lambda i: i[1]) if limit is not None else \
sorted(sl, key=lambda i: i[1], reverse=True)
def extractBests(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0, limit=5):
"""Get a list of the best matches to a collection of choices.
Convenience function for getting the choices with best scores.
Args:
query: A string to match against
choices: A list or dictionary of choices, suitable for use with
extract().
processor: Optional function for transforming choices before matching.
See extract().
scorer: Scoring function for extract().
score_cutoff: Optional argument for score threshold. No matches with
a score less than this number will be returned. Defaults to 0.
limit: Optional maximum for the number of elements returned. Defaults
to 5.
Returns: A a list of (match, score) tuples.
"""
best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)
return heapq.nlargest(limit, best_list, key=lambda i: i[1]) if limit is not None else \
sorted(best_list, key=lambda i: i[1], reverse=True)
def extractOne(query, choices, processor=default_processor, scorer=default_scorer, score_cutoff=0):
"""Find the single best match above a score in a list of choices.
This is a convenience method which returns the single best choice.
See extract() for the full arguments list.
Args:
query: A string to match against
choices: A list or dictionary of choices, suitable for use with
extract().
processor: Optional function for transforming choices before matching.
See extract().
scorer: Scoring function for extract().
score_cutoff: Optional argument for score threshold. If the best
match is found, but it is not greater than this number, then
return None anyway ("not a good enough match"). Defaults to 0.
Returns:
A tuple containing a single match and its score, if a match
was found that was above score_cutoff. Otherwise, returns None.
"""
best_list = extractWithoutOrder(query, choices, processor, scorer, score_cutoff)
try:
return max(best_list, key=lambda i: i[1])
except ValueError:
return None
def dedupe(contains_dupes, threshold=70, scorer=fuzz.token_set_ratio):
"""This convenience function takes a list of strings containing duplicates and uses fuzzy matching to identify
and remove duplicates. Specifically, it uses the process.extract to identify duplicates that
score greater than a user defined threshold. Then, it looks for the longest item in the duplicate list
since we assume this item contains the most entity information and returns that. It breaks string
length ties on an alphabetical sort.
Note: as the threshold DECREASES the number of duplicates that are found INCREASES. This means that the
returned deduplicated list will likely be shorter. Raise the threshold for fuzzy_dedupe to be less
sensitive.
Args:
contains_dupes: A list of strings that we would like to dedupe.
threshold: the numerical value (0,100) point at which we expect to find duplicates.
Defaults to 70 out of 100
scorer: Optional function for scoring matches between the query and
an individual processed choice. This should be a function
of the form f(query, choice) -> int.
By default, fuzz.token_set_ratio() is used and expects both query and
choice to be strings.
Returns:
A deduplicated list. For example:
In: contains_dupes = ['Frodo Baggin', 'Frodo Baggins', 'F. Baggins', 'Samwise G.', 'Gandalf', 'Bilbo Baggins']
In: fuzzy_dedupe(contains_dupes)
Out: ['Frodo Baggins', 'Samwise G.', 'Bilbo Baggins', 'Gandalf']
"""
extractor = []
# iterate over items in *contains_dupes*
for item in contains_dupes:
# return all duplicate matches found
matches = extract(item, contains_dupes, limit=None, scorer=scorer)
# filter matches based on the threshold
filtered = [x for x in matches if x[1] > threshold]
# if there is only 1 item in *filtered*, no duplicates were found so append to *extracted*
if len(filtered) == 1:
extractor.append(filtered[0][0])
else:
# alpha sort
filtered = sorted(filtered, key=lambda x: x[0])
# length sort
filter_sort = sorted(filtered, key=lambda x: len(x[0]), reverse=True)
# take first item as our 'canonical example'
extractor.append(filter_sort[0][0])
# uniquify *extractor* list
keys = {}
for e in extractor:
keys[e] = 1
extractor = keys.keys()
# check that extractor differs from contain_dupes (e.g. duplicates were found)
# if not, then return the original list
if len(extractor) == len(contains_dupes):
return contains_dupes
else:
return extractor
| 6 | 808 | Python |
gin_rummy | ./ProjectTest/Python/gin_rummy.py | '''
gin_rummy/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
gin_rummy/player.py
'''
from typing import List
from gin_rummy import Card
import utils
import melding
class GinRummyPlayer:
def __init__(self, player_id: int, np_random):
''' Initialize a GinRummy player class
Args:
player_id (int): id for the player
'''
self.np_random = np_random
self.player_id = player_id
self.hand = [] # type: List[Card]
self.known_cards = [] # type: List[Card] # opponent knows cards picked up by player and not yet discarded
# memoization for speed
self.meld_kinds_by_rank_id = [[] for _ in range(13)] # type: List[List[List[Card]]]
self.meld_run_by_suit_id = [[] for _ in range(4)] # type: List[List[List[Card]]]
def get_player_id(self) -> int:
''' Return player's id
'''
return self.player_id
def get_meld_clusters(self) -> List[List[List[Card]]]:
result = [] # type: List[List[List[Card]]]
all_run_melds = [frozenset(meld_kind) for meld_kinds in self.meld_kinds_by_rank_id for meld_kind in meld_kinds]
all_set_melds = [frozenset(meld_run) for meld_runs in self.meld_run_by_suit_id for meld_run in meld_runs]
all_melds = all_run_melds + all_set_melds
all_melds_count = len(all_melds)
for i in range(0, all_melds_count):
first_meld = all_melds[i]
first_meld_list = list(first_meld)
meld_cluster_1 = [first_meld_list]
result.append(meld_cluster_1)
for j in range(i + 1, all_melds_count):
second_meld = all_melds[j]
second_meld_list = list(second_meld)
if not second_meld.isdisjoint(first_meld):
continue
meld_cluster_2 = [first_meld_list, second_meld_list]
result.append(meld_cluster_2)
for k in range(j + 1, all_melds_count):
third_meld = all_melds[k]
third_meld_list = list(third_meld)
if not third_meld.isdisjoint(first_meld) or not third_meld.isdisjoint(second_meld):
continue
meld_cluster_3 = [first_meld_list, second_meld_list, third_meld_list]
result.append(meld_cluster_3)
return result
def did_populate_hand(self):
self.meld_kinds_by_rank_id = [[] for _ in range(13)]
self.meld_run_by_suit_id = [[] for _ in range(4)]
all_set_melds = melding.get_all_set_melds(hand=self.hand)
for set_meld in all_set_melds:
rank_id = utils.get_rank_id(set_meld[0])
self.meld_kinds_by_rank_id[rank_id].append(set_meld)
all_run_melds = melding.get_all_run_melds(hand=self.hand)
for run_meld in all_run_melds:
suit_id = utils.get_suit_id(run_meld[0])
self.meld_run_by_suit_id[suit_id].append(run_meld)
def add_card_to_hand(self, card: Card):
self.hand.append(card)
self._increase_meld_kinds_by_rank_id(card=card)
self._increase_run_kinds_by_suit_id(card=card)
def remove_card_from_hand(self, card: Card):
self.hand.remove(card)
self._reduce_meld_kinds_by_rank_id(card=card)
self._reduce_run_kinds_by_suit_id(card=card)
def __str__(self):
return "N" if self.player_id == 0 else "S"
@staticmethod
def short_name_of(player_id: int) -> str:
return "N" if player_id == 0 else "S"
@staticmethod
def opponent_id_of(player_id: int) -> int:
return (player_id + 1) % 2
# private methods
def _increase_meld_kinds_by_rank_id(self, card: Card):
rank_id = utils.get_rank_id(card)
meld_kinds = self.meld_kinds_by_rank_id[rank_id]
if len(meld_kinds) == 0:
card_rank = card.rank
meld_kind = [card for card in self.hand if card.rank == card_rank]
if len(meld_kind) >= 3:
self.meld_kinds_by_rank_id[rank_id].append(meld_kind)
else: # must have all cards of given rank
suits = ['S', 'H', 'D', 'C']
max_kind_meld = [Card(suit, card.rank) for suit in suits]
self.meld_kinds_by_rank_id[rank_id] = [max_kind_meld]
for meld_card in max_kind_meld:
self.meld_kinds_by_rank_id[rank_id].append([card for card in max_kind_meld if card != meld_card])
def _reduce_meld_kinds_by_rank_id(self, card: Card):
rank_id = utils.get_rank_id(card)
meld_kinds = self.meld_kinds_by_rank_id[rank_id]
if len(meld_kinds) > 1:
suits = ['S', 'H', 'D', 'C']
self.meld_kinds_by_rank_id[rank_id] = [[Card(suit, card.rank) for suit in suits if suit != card.suit]]
else:
self.meld_kinds_by_rank_id[rank_id] = []
def _increase_run_kinds_by_suit_id(self, card: Card):
suit_id = utils.get_suit_id(card=card)
self.meld_run_by_suit_id[suit_id] = melding.get_all_run_melds_for_suit(cards=self.hand, suit=card.suit)
def _reduce_run_kinds_by_suit_id(self, card: Card):
suit_id = utils.get_suit_id(card=card)
meld_runs = self.meld_run_by_suit_id[suit_id]
self.meld_run_by_suit_id[suit_id] = [meld_run for meld_run in meld_runs if card not in meld_run]
'''
gin_rummy/judge.py
'''
from typing import TYPE_CHECKING
from typing import List, Tuple
from action_event import *
from scorers import GinRummyScorer
import melding
from gin_rummy_error import GinRummyProgramError
import utils
class GinRummyJudge:
'''
Judge decides legal actions for current player
'''
def __init__(self, game: 'GinRummyGame'):
''' Initialize the class GinRummyJudge
:param game: GinRummyGame
'''
self.game = game
self.scorer = GinRummyScorer()
def get_legal_actions(self) -> List[ActionEvent]:
"""
:return: List[ActionEvent] of legal actions
"""
legal_actions = [] # type: List[ActionEvent]
last_action = self.game.get_last_action()
if last_action is None or \
isinstance(last_action, DrawCardAction) or \
isinstance(last_action, PickUpDiscardAction):
current_player = self.game.get_current_player()
going_out_deadwood_count = self.game.settings.going_out_deadwood_count
hand = current_player.hand
meld_clusters = current_player.get_meld_clusters() # improve speed 2020-Apr
knock_cards, gin_cards = _get_going_out_cards(meld_clusters=meld_clusters,
hand=hand,
going_out_deadwood_count=going_out_deadwood_count)
if self.game.settings.is_allowed_gin and gin_cards:
legal_actions = [GinAction()]
else:
cards_to_discard = [card for card in hand]
if isinstance(last_action, PickUpDiscardAction):
if not self.game.settings.is_allowed_to_discard_picked_up_card:
picked_up_card = self.game.round.move_sheet[-1].card
cards_to_discard.remove(picked_up_card)
discard_actions = [DiscardAction(card=card) for card in cards_to_discard]
legal_actions = discard_actions
if self.game.settings.is_allowed_knock:
if current_player.player_id == 0 or not self.game.settings.is_south_never_knocks:
if knock_cards:
knock_actions = [KnockAction(card=card) for card in knock_cards]
if not self.game.settings.is_always_knock:
legal_actions.extend(knock_actions)
else:
legal_actions = knock_actions
elif isinstance(last_action, DeclareDeadHandAction):
legal_actions = [ScoreNorthPlayerAction()]
elif isinstance(last_action, GinAction):
legal_actions = [ScoreNorthPlayerAction()]
elif isinstance(last_action, DiscardAction):
can_draw_card = len(self.game.round.dealer.stock_pile) > self.game.settings.stockpile_dead_card_count
if self.game.settings.max_drawn_card_count < 52: # NOTE: this
drawn_card_actions = [action for action in self.game.actions if isinstance(action, DrawCardAction)]
if len(drawn_card_actions) >= self.game.settings.max_drawn_card_count:
can_draw_card = False
move_count = len(self.game.round.move_sheet)
if move_count >= self.game.settings.max_move_count:
legal_actions = [DeclareDeadHandAction()] # prevent unlimited number of moves in a game
elif can_draw_card:
legal_actions = [DrawCardAction()]
if self.game.settings.is_allowed_pick_up_discard:
legal_actions.append(PickUpDiscardAction())
else:
legal_actions = [DeclareDeadHandAction()]
if self.game.settings.is_allowed_pick_up_discard:
legal_actions.append(PickUpDiscardAction())
elif isinstance(last_action, KnockAction):
legal_actions = [ScoreNorthPlayerAction()]
elif isinstance(last_action, ScoreNorthPlayerAction):
legal_actions = [ScoreSouthPlayerAction()]
elif isinstance(last_action, ScoreSouthPlayerAction):
pass
else:
raise Exception('get_legal_actions: unknown last_action={}'.format(last_action))
return legal_actions
def get_going_out_cards(hand: List[Card], going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]:
'''
:param hand: List[Card] -- must have 11 cards
:param going_out_deadwood_count: int
:return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned
'''
if not len(hand) == 11:
raise GinRummyProgramError("len(hand) is {}: should be 11.".format(len(hand)))
meld_clusters = melding.get_meld_clusters(hand=hand)
knock_cards, gin_cards = _get_going_out_cards(meld_clusters=meld_clusters,
hand=hand,
going_out_deadwood_count=going_out_deadwood_count)
return list(knock_cards), list(gin_cards)
#
# private methods
#
def _get_going_out_cards(meld_clusters: List[List[List[Card]]],
hand: List[Card],
going_out_deadwood_count: int) -> Tuple[List[Card], List[Card]]:
'''
:param meld_clusters
:param hand: List[Card] -- must have 11 cards
:param going_out_deadwood_count: int
:return List[Card], List[Card: cards in hand that be knocked, cards in hand that can be ginned
'''
if not len(hand) == 11:
raise GinRummyProgramError("len(hand) is {}: should be 11.".format(len(hand)))
knock_cards = set()
gin_cards = set()
for meld_cluster in meld_clusters:
meld_cards = [card for meld_pile in meld_cluster for card in meld_pile]
hand_deadwood = [card for card in hand if card not in meld_cards] # hand has 11 cards
if len(hand_deadwood) == 0:
# all 11 cards are melded;
# take gin_card as first card of first 4+ meld;
# could also take gin_card as last card of 4+ meld, but won't do this.
for meld_pile in meld_cluster:
if len(meld_pile) >= 4:
gin_cards.add(meld_pile[0])
break
elif len(hand_deadwood) == 1:
card = hand_deadwood[0]
gin_cards.add(card)
else:
hand_deadwood_values = [utils.get_deadwood_value(card) for card in hand_deadwood]
hand_deadwood_count = sum(hand_deadwood_values)
max_hand_deadwood_value = max(hand_deadwood_values, default=0)
if hand_deadwood_count <= 10 + max_hand_deadwood_value:
for card in hand_deadwood:
next_deadwood_count = hand_deadwood_count - utils.get_deadwood_value(card)
if next_deadwood_count <= going_out_deadwood_count:
knock_cards.add(card)
return list(knock_cards), list(gin_cards)
'''
gin_rummy/move.py
'''
from typing import List
from gin_rummy import Player
from action_event import *
from gin_rummy_error import GinRummyProgramError
#
# These classes are used to keep a move_sheet history of the moves in a round.
#
class GinRummyMove(object):
pass
class PlayerMove(GinRummyMove):
def __init__(self, player: Player, action: ActionEvent):
super().__init__()
self.player = player
self.action = action
class DealHandMove(GinRummyMove):
def __init__(self, player_dealing: Player, shuffled_deck: List[Card]):
super().__init__()
self.player_dealing = player_dealing
self.shuffled_deck = shuffled_deck
def __str__(self):
shuffled_deck_text = " ".join([str(card) for card in self.shuffled_deck])
return "{} deal shuffled_deck=[{}]".format(self.player_dealing, shuffled_deck_text)
class DrawCardMove(PlayerMove):
def __init__(self, player: Player, action: DrawCardAction, card: Card):
super().__init__(player, action)
if not isinstance(action, DrawCardAction):
raise GinRummyProgramError("action must be DrawCardAction.")
self.card = card
def __str__(self):
return "{} {} {}".format(self.player, self.action, str(self.card))
class PickupDiscardMove(PlayerMove):
def __init__(self, player: Player, action: PickUpDiscardAction, card: Card):
super().__init__(player, action)
if not isinstance(action, PickUpDiscardAction):
raise GinRummyProgramError("action must be PickUpDiscardAction.")
self.card = card
def __str__(self):
return "{} {} {}".format(self.player, self.action, str(self.card))
class DeclareDeadHandMove(PlayerMove):
def __init__(self, player: Player, action: DeclareDeadHandAction):
super().__init__(player, action)
if not isinstance(action, DeclareDeadHandAction):
raise GinRummyProgramError("action must be DeclareDeadHandAction.")
def __str__(self):
return "{} {}".format(self.player, self.action)
class DiscardMove(PlayerMove):
def __init__(self, player: Player, action: DiscardAction):
super().__init__(player, action)
if not isinstance(action, DiscardAction):
raise GinRummyProgramError("action must be DiscardAction.")
def __str__(self):
return "{} {}".format(self.player, self.action)
class KnockMove(PlayerMove):
def __init__(self, player: Player, action: KnockAction):
super().__init__(player, action)
if not isinstance(action, KnockAction):
raise GinRummyProgramError("action must be KnockAction.")
def __str__(self):
return "{} {}".format(self.player, self.action)
class GinMove(PlayerMove):
def __init__(self, player: Player, action: GinAction):
super().__init__(player, action)
if not isinstance(action, GinAction):
raise GinRummyProgramError("action must be GinAction.")
def __str__(self):
return "{} {}".format(self.player, self.action)
class ScoreNorthMove(PlayerMove):
def __init__(self, player: Player,
action: ScoreNorthPlayerAction,
best_meld_cluster: List[List[Card]],
deadwood_count: int):
super().__init__(player, action)
if not isinstance(action, ScoreNorthPlayerAction):
raise GinRummyProgramError("action must be ScoreNorthPlayerAction.")
self.best_meld_cluster = best_meld_cluster # for information use only
self.deadwood_count = deadwood_count # for information use only
def __str__(self):
best_meld_cluster_str = [[str(card) for card in meld_pile] for meld_pile in self.best_meld_cluster]
best_meld_cluster_text = "{}".format(best_meld_cluster_str)
return "{} {} {} {}".format(self.player, self.action, self.deadwood_count, best_meld_cluster_text)
class ScoreSouthMove(PlayerMove):
def __init__(self, player: Player,
action: ScoreSouthPlayerAction,
best_meld_cluster: List[List[Card]],
deadwood_count: int):
super().__init__(player, action)
if not isinstance(action, ScoreSouthPlayerAction):
raise GinRummyProgramError("action must be ScoreSouthPlayerAction.")
self.best_meld_cluster = best_meld_cluster # for information use only
self.deadwood_count = deadwood_count # for information use only
def __str__(self):
best_meld_cluster_str = [[str(card) for card in meld_pile] for meld_pile in self.best_meld_cluster]
best_meld_cluster_text = "{}".format(best_meld_cluster_str)
return "{} {} {} {}".format(self.player, self.action, self.deadwood_count, best_meld_cluster_text)
'''
gin_rummy/dealer.py
'''
from gin_rummy import Player
import utils as utils
class GinRummyDealer:
''' Initialize a GinRummy dealer class
'''
def __init__(self, np_random):
''' Empty discard_pile, set shuffled_deck, set stock_pile
'''
self.np_random = np_random
self.discard_pile = [] # type: List[Card]
self.shuffled_deck = utils.get_deck() # keep a copy of the shuffled cards at start of new hand
self.np_random.shuffle(self.shuffled_deck)
self.stock_pile = self.shuffled_deck.copy() # type: List[Card]
def deal_cards(self, player: Player, num: int):
''' Deal some cards from stock_pile to one player
Args:
player (Player): The Player object
num (int): The number of cards to be dealt
'''
for _ in range(num):
player.hand.append(self.stock_pile.pop())
player.did_populate_hand()
'''
gin_rummy/settings.py
'''
from typing import Dict, Any
from enum import Enum
class DealerForRound(int, Enum):
North = 0
South = 1
Random = 2
class Setting(str, Enum):
dealer_for_round = "dealer_for_round"
stockpile_dead_card_count = "stockpile_dead_card_count"
going_out_deadwood_count = "going_out_deadwood_count"
max_drawn_card_count = "max_drawn_card_count"
max_move_count = "max_move_count"
is_allowed_knock = "is_allowed_knock"
is_allowed_gin = "is_allowed_gin"
is_allowed_pick_up_discard = "is_allowed_pick_up_discard"
is_allowed_to_discard_picked_up_card = "is_allowed_to_discard_picked_up_card"
is_always_knock = "is_always_knock"
is_south_never_knocks = "is_south_never_knocks"
@staticmethod
def default_setting() -> Dict['Setting', Any]:
return {Setting.dealer_for_round: DealerForRound.Random,
Setting.stockpile_dead_card_count: 2,
Setting.going_out_deadwood_count: 10, # Can specify going_out_deadwood_count before running game.
Setting.max_drawn_card_count: 52,
Setting.max_move_count: 200, # prevent unlimited number of moves in a game
Setting.is_allowed_knock: True,
Setting.is_allowed_gin: True,
Setting.is_allowed_pick_up_discard: True,
Setting.is_allowed_to_discard_picked_up_card: False,
Setting.is_always_knock: False,
Setting.is_south_never_knocks: False
}
@staticmethod
def simple_gin_rummy_setting(): # speeding up training 200213
# North should be agent being trained.
# North always deals.
# South never knocks.
# North always knocks when can.
return {Setting.dealer_for_round: DealerForRound.North,
Setting.stockpile_dead_card_count: 2,
Setting.going_out_deadwood_count: 10, # Can specify going_out_deadwood_count before running game.
Setting.max_drawn_card_count: 52,
Setting.max_move_count: 200, # prevent unlimited number of moves in a game
Setting.is_allowed_knock: True,
Setting.is_allowed_gin: True,
Setting.is_allowed_pick_up_discard: True,
Setting.is_allowed_to_discard_picked_up_card: False,
Setting.is_always_knock: True,
Setting.is_south_never_knocks: True
}
dealer_for_round = Setting.dealer_for_round
stockpile_dead_card_count = Setting.stockpile_dead_card_count
going_out_deadwood_count = Setting.going_out_deadwood_count
max_drawn_card_count = Setting.max_drawn_card_count
max_move_count = Setting.max_move_count
is_allowed_knock = Setting.is_allowed_knock
is_allowed_gin = Setting.is_allowed_gin
is_allowed_pick_up_discard = Setting.is_allowed_pick_up_discard
is_allowed_to_discard_picked_up_card = Setting.is_allowed_to_discard_picked_up_card
is_always_knock = Setting.is_always_knock
is_south_never_knocks = Setting.is_south_never_knocks
class Settings(object):
def __init__(self):
self.scorer_name = "GinRummyScorer"
default_setting = Setting.default_setting()
self.dealer_for_round = default_setting[Setting.dealer_for_round]
self.stockpile_dead_card_count = default_setting[Setting.stockpile_dead_card_count]
self.going_out_deadwood_count = default_setting[Setting.going_out_deadwood_count]
self.max_drawn_card_count = default_setting[Setting.max_drawn_card_count]
self.max_move_count = default_setting[Setting.max_move_count]
self.is_allowed_knock = default_setting[Setting.is_allowed_knock]
self.is_allowed_gin = default_setting[Setting.is_allowed_gin]
self.is_allowed_pick_up_discard = default_setting[Setting.is_allowed_pick_up_discard]
self.is_allowed_to_discard_picked_up_card = default_setting[Setting.is_allowed_to_discard_picked_up_card]
self.is_always_knock = default_setting[Setting.is_always_knock]
self.is_south_never_knocks = default_setting[Setting.is_south_never_knocks]
def change_settings(self, config: Dict[Setting, Any]):
corrected_config = Settings.get_config_with_invalid_settings_set_to_default_value(config=config)
for key, value in corrected_config.items():
if key == Setting.dealer_for_round:
self.dealer_for_round = value
elif key == Setting.stockpile_dead_card_count:
self.stockpile_dead_card_count = value
elif key == Setting.going_out_deadwood_count:
self.going_out_deadwood_count = value
elif key == Setting.max_drawn_card_count:
self.max_drawn_card_count = value
elif key == Setting.max_move_count:
self.max_move_count = value
elif key == Setting.is_allowed_knock:
self.is_allowed_knock = value
elif key == Setting.is_allowed_gin:
self.is_allowed_gin = value
elif key == Setting.is_allowed_pick_up_discard:
self.is_allowed_pick_up_discard = value
elif key == Setting.is_allowed_to_discard_picked_up_card:
self.is_allowed_to_discard_picked_up_card = value
elif key == Setting.is_always_knock:
self.is_always_knock = value
elif key == Setting.is_south_never_knocks:
self.is_south_never_knocks = value
def print_settings(self):
print("========== Settings ==========")
print("scorer_name={}".format(self.scorer_name))
print("dealer_for_round={}".format(self.dealer_for_round))
print("stockpile_dead_card_count={}".format(self.stockpile_dead_card_count))
print("going_out_deadwood_count={}".format(self.going_out_deadwood_count))
print("max_drawn_card_count={}".format(self.max_drawn_card_count))
print("max_move_count={}".format(self.max_move_count))
print("is_allowed_knock={}".format(self.is_allowed_knock))
print("is_allowed_gin={}".format(self.is_allowed_gin))
print("is_allowed_pick_up_discard={}".format(self.is_allowed_pick_up_discard))
print("is_allowed_to_discard_picked_up_card={}".format(self.is_allowed_to_discard_picked_up_card))
print("is_always_knock={}".format(self.is_always_knock))
print("is_south_never_knocks={}".format(self.is_south_never_knocks))
print("==============================")
@staticmethod
def get_config_with_invalid_settings_set_to_default_value(config: Dict[Setting, Any]) -> Dict[Setting, Any]:
# Set each invalid setting to its default_value.
result = config.copy()
default_setting = Setting.default_setting()
for key, value in config.items():
if key == dealer_for_round and not isinstance(value, DealerForRound):
result[dealer_for_round] = default_setting[dealer_for_round]
elif key == stockpile_dead_card_count and not isinstance(value, int):
result[stockpile_dead_card_count] = default_setting[stockpile_dead_card_count]
elif key == going_out_deadwood_count and not isinstance(value, int):
result[going_out_deadwood_count] = default_setting[going_out_deadwood_count]
elif key == max_drawn_card_count and not isinstance(value, int):
result[max_drawn_card_count] = default_setting[max_drawn_card_count]
elif key == max_move_count and not isinstance(value, int):
result[max_move_count] = default_setting[max_move_count]
elif key == is_allowed_knock and not isinstance(value, bool):
result[is_allowed_knock] = default_setting[is_allowed_knock]
elif key == is_allowed_gin and not isinstance(value, bool):
result[is_allowed_gin] = default_setting[is_allowed_gin]
elif key == is_allowed_pick_up_discard and not isinstance(value, bool):
result[is_allowed_pick_up_discard] = default_setting[is_allowed_pick_up_discard]
elif key == is_allowed_to_discard_picked_up_card and not isinstance(value, bool):
result[is_allowed_to_discard_picked_up_card] = default_setting[is_allowed_to_discard_picked_up_card]
elif key == is_always_knock and not isinstance(value, bool):
result[is_always_knock] = default_setting[is_always_knock]
elif key == is_south_never_knocks and not isinstance(value, bool):
result[is_south_never_knocks] = default_setting[is_south_never_knocks]
return result
'''
gin_rummy/action_event.py
'''
from gin_rummy import Card
import utils as utils
# ====================================
# Action_ids:
# 0 -> score_player_0_id
# 1 -> score_player_1_id
# 2 -> draw_card_id
# 3 -> pick_up_discard_id
# 4 -> declare_dead_hand_id
# 5 -> gin_id
# 6 to 57 -> discard_id card_id
# 58 to 109 -> knock_id card_id
# ====================================
score_player_0_action_id = 0
score_player_1_action_id = 1
draw_card_action_id = 2
pick_up_discard_action_id = 3
declare_dead_hand_action_id = 4
gin_action_id = 5
discard_action_id = 6
knock_action_id = discard_action_id + 52
class ActionEvent(object):
def __init__(self, action_id: int):
self.action_id = action_id
def __eq__(self, other):
result = False
if isinstance(other, ActionEvent):
result = self.action_id == other.action_id
return result
@staticmethod
def get_num_actions():
''' Return the number of possible actions in the game
'''
return knock_action_id + 52 # FIXME: sensitive to code changes 200213
@staticmethod
def decode_action(action_id) -> 'ActionEvent':
''' Action id -> the action_event in the game.
Args:
action_id (int): the id of the action
Returns:
action (ActionEvent): the action that will be passed to the game engine.
'''
if action_id == score_player_0_action_id:
action_event = ScoreNorthPlayerAction()
elif action_id == score_player_1_action_id:
action_event = ScoreSouthPlayerAction()
elif action_id == draw_card_action_id:
action_event = DrawCardAction()
elif action_id == pick_up_discard_action_id:
action_event = PickUpDiscardAction()
elif action_id == declare_dead_hand_action_id:
action_event = DeclareDeadHandAction()
elif action_id == gin_action_id:
action_event = GinAction()
elif action_id in range(discard_action_id, discard_action_id + 52):
card_id = action_id - discard_action_id
card = utils.get_card(card_id=card_id)
action_event = DiscardAction(card=card)
elif action_id in range(knock_action_id, knock_action_id + 52):
card_id = action_id - knock_action_id
card = utils.get_card(card_id=card_id)
action_event = KnockAction(card=card)
else:
raise Exception("decode_action: unknown action_id={}".format(action_id))
return action_event
class ScoreNorthPlayerAction(ActionEvent):
def __init__(self):
super().__init__(action_id=score_player_0_action_id)
def __str__(self):
return "score N"
class ScoreSouthPlayerAction(ActionEvent):
def __init__(self):
super().__init__(action_id=score_player_1_action_id)
def __str__(self):
return "score S"
class DrawCardAction(ActionEvent):
def __init__(self):
super().__init__(action_id=draw_card_action_id)
def __str__(self):
return "draw_card"
class PickUpDiscardAction(ActionEvent):
def __init__(self):
super().__init__(action_id=pick_up_discard_action_id)
def __str__(self):
return "pick_up_discard"
class DeclareDeadHandAction(ActionEvent):
def __init__(self):
super().__init__(action_id=declare_dead_hand_action_id)
def __str__(self):
return "declare_dead_hand"
class GinAction(ActionEvent):
def __init__(self):
super().__init__(action_id=gin_action_id)
def __str__(self):
return "gin"
class DiscardAction(ActionEvent):
def __init__(self, card: Card):
card_id = utils.get_card_id(card)
super().__init__(action_id=discard_action_id + card_id)
self.card = card
def __str__(self):
return "discard {}".format(str(self.card))
class KnockAction(ActionEvent):
def __init__(self, card: Card):
card_id = utils.get_card_id(card)
super().__init__(action_id=knock_action_id + card_id)
self.card = card
def __str__(self):
return "knock {}".format(str(self.card))
'''
gin_rummy/scorers.py
'''
from typing import TYPE_CHECKING
from typing import Callable
from action_event import *
from gin_rummy import Player
from move import ScoreNorthMove, ScoreSouthMove
from gin_rummy_error import GinRummyProgramError
import melding
import utils
class GinRummyScorer:
def __init__(self, name: str = None, get_payoff: Callable[[Player, 'GinRummyGame'], int or float] = None):
self.name = name if name is not None else "GinRummyScorer"
self.get_payoff = get_payoff if get_payoff else get_payoff_gin_rummy_v1
def get_payoffs(self, game: 'GinRummyGame'):
payoffs = [0, 0]
for i in range(2):
player = game.round.players[i]
payoff = self.get_payoff(player=player, game=game)
payoffs[i] = payoff
return payoffs
def get_payoff_gin_rummy_v0(player: Player, game: 'GinRummyGame') -> int:
''' Get the payoff of player: deadwood_count of player
Returns:
payoff (int or float): payoff for player (lower is better)
'''
moves = game.round.move_sheet
if player.player_id == 0:
score_player_move = moves[-2]
if not isinstance(score_player_move, ScoreNorthMove):
raise GinRummyProgramError("score_player_move must be ScoreNorthMove.")
else:
score_player_move = moves[-1]
if not isinstance(score_player_move, ScoreSouthMove):
raise GinRummyProgramError("score_player_move must be ScoreSouthMove.")
deadwood_count = score_player_move.deadwood_count
return deadwood_count
def get_payoff_gin_rummy_v1(player: Player, game: 'GinRummyGame') -> float:
''' Get the payoff of player:
a) 1.0 if player gins
b) 0.2 if player knocks
c) -deadwood_count / 100 otherwise
Returns:
payoff (int or float): payoff for player (higher is better)
'''
# payoff is 1.0 if player gins
# payoff is 0.2 if player knocks
# payoff is -deadwood_count / 100 if otherwise
# The goal is to have the agent learn how to knock and gin.
# The negative payoff when the agent fails to knock or gin should encourage the agent to form melds.
# The payoff is scaled to lie between -1 and 1.
going_out_action = game.round.going_out_action
going_out_player_id = game.round.going_out_player_id
if going_out_player_id == player.player_id and isinstance(going_out_action, KnockAction):
payoff = 0.2
elif going_out_player_id == player.player_id and isinstance(going_out_action, GinAction):
payoff = 1
else:
hand = player.hand
best_meld_clusters = melding.get_best_meld_clusters(hand=hand)
best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]
deadwood_count = utils.get_deadwood_count(hand, best_meld_cluster)
payoff = -deadwood_count / 100
return payoff
'''
gin_rummy/game.py
'''
import numpy as np
from gin_rummy import Player
from round import GinRummyRound
from gin_rummy import Judger
from settings import Settings, DealerForRound
from action_event import *
class GinRummyGame:
''' Game class. This class will interact with outer environment.
'''
def __init__(self, allow_step_back=False):
'''Initialize the class GinRummyGame
'''
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
self.judge = Judger(game=self)
self.settings = Settings()
self.actions = None # type: List[ActionEvent] or None # must reset in init_game
self.round = None # round: GinRummyRound or None, must reset in init_game
self.num_players = 2
def init_game(self):
''' Initialize all characters in the game and start round 1
'''
dealer_id = self.np_random.choice([0, 1])
if self.settings.dealer_for_round == DealerForRound.North:
dealer_id = 0
elif self.settings.dealer_for_round == DealerForRound.South:
dealer_id = 1
self.actions = []
self.round = GinRummyRound(dealer_id=dealer_id, np_random=self.np_random)
for i in range(2):
num = 11 if i == 0 else 10
player = self.round.players[(dealer_id + 1 + i) % 2]
self.round.dealer.deal_cards(player=player, num=num)
current_player_id = self.round.current_player_id
state = self.get_state(player_id=current_player_id)
return state, current_player_id
def step(self, action: ActionEvent):
''' Perform game action and return next player number, and the state for next player
'''
if isinstance(action, ScoreNorthPlayerAction):
self.round.score_player_0(action)
elif isinstance(action, ScoreSouthPlayerAction):
self.round.score_player_1(action)
elif isinstance(action, DrawCardAction):
self.round.draw_card(action)
elif isinstance(action, PickUpDiscardAction):
self.round.pick_up_discard(action)
elif isinstance(action, DeclareDeadHandAction):
self.round.declare_dead_hand(action)
elif isinstance(action, GinAction):
self.round.gin(action, going_out_deadwood_count=self.settings.going_out_deadwood_count)
elif isinstance(action, DiscardAction):
self.round.discard(action)
elif isinstance(action, KnockAction):
self.round.knock(action)
else:
raise Exception('Unknown step action={}'.format(action))
self.actions.append(action)
next_player_id = self.round.current_player_id
next_state = self.get_state(player_id=next_player_id)
return next_state, next_player_id
def step_back(self):
''' Takes one step backward and restore to the last state
'''
raise NotImplementedError
def get_num_players(self):
''' Return the number of players in the game
'''
return 2
def get_num_actions(self):
''' Return the number of possible actions in the game
'''
return ActionEvent.get_num_actions()
def get_player_id(self):
''' Return the current player that will take actions soon
'''
return self.round.current_player_id
def is_over(self):
''' Return whether the current game is over
'''
return self.round.is_over
def get_current_player(self) -> Player or None:
return self.round.get_current_player()
def get_last_action(self) -> ActionEvent or None:
return self.actions[-1] if self.actions and len(self.actions) > 0 else None
def get_state(self, player_id: int):
''' Get player's state
Return:
state (dict): The information of the state
'''
state = {}
if not self.is_over():
discard_pile = self.round.dealer.discard_pile
top_discard = [] if not discard_pile else [discard_pile[-1]]
dead_cards = discard_pile[:-1]
last_action = self.get_last_action()
opponent_id = (player_id + 1) % 2
opponent = self.round.players[opponent_id]
known_cards = opponent.known_cards
if isinstance(last_action, ScoreNorthPlayerAction) or isinstance(last_action, ScoreSouthPlayerAction):
known_cards = opponent.hand
unknown_cards = self.round.dealer.stock_pile + [card for card in opponent.hand if card not in known_cards]
state['player_id'] = self.round.current_player_id
state['hand'] = [x.get_index() for x in self.round.players[self.round.current_player_id].hand]
state['top_discard'] = [x.get_index() for x in top_discard]
state['dead_cards'] = [x.get_index() for x in dead_cards]
state['opponent_known_cards'] = [x.get_index() for x in known_cards]
state['unknown_cards'] = [x.get_index() for x in unknown_cards]
return state
@staticmethod
def decode_action(action_id) -> ActionEvent: # FIXME 200213 should return str
''' Action id -> the action_event in the game.
Args:
action_id (int): the id of the action
Returns:
action (ActionEvent): the action that will be passed to the game engine.
'''
return ActionEvent.decode_action(action_id=action_id)
'''
gin_rummy/utils.py
'''
from typing import List, Iterable
import numpy as np
from gin_rummy import Card
from gin_rummy_error import GinRummyProgramError
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
valid_suit = ['S', 'H', 'D', 'C']
rank_to_deadwood_value = {"A": 1, "2": 2, "3": 3, "4": 4, "5": 5, "6": 6, "7": 7, "8": 8, "9": 9,
"T": 10, "J": 10, "Q": 10, "K": 10}
def card_from_card_id(card_id: int) -> Card:
''' Make card from its card_id
Args:
card_id: int in range(0, 52)
'''
if not (0 <= card_id < 52):
raise GinRummyProgramError("card_id is {}: should be 0 <= card_id < 52.".format(card_id))
rank_id = card_id % 13
suit_id = card_id // 13
rank = Card.valid_rank[rank_id]
suit = Card.valid_suit[suit_id]
return Card(rank=rank, suit=suit)
# deck is always in order from AS, 2S, ..., AH, 2H, ..., AD, 2D, ..., AC, 2C, ... QC, KC
_deck = [card_from_card_id(card_id) for card_id in range(52)] # want this to be read-only
def card_from_text(text: str) -> Card:
if len(text) != 2:
raise GinRummyProgramError("len(text) is {}: should be 2.".format(len(text)))
return Card(rank=text[0], suit=text[1])
def get_deck() -> List[Card]:
return _deck.copy()
def get_card(card_id: int):
return _deck[card_id]
def get_card_id(card: Card) -> int:
rank_id = get_rank_id(card)
suit_id = get_suit_id(card)
return rank_id + 13 * suit_id
def get_rank_id(card: Card) -> int:
return Card.valid_rank.index(card.rank)
def get_suit_id(card: Card) -> int:
return Card.valid_suit.index(card.suit)
def get_deadwood_value(card: Card) -> int:
rank = card.rank
deadwood_value = rank_to_deadwood_value.get(rank, 10) # default to 10 is key does not exist
return deadwood_value
def get_deadwood(hand: Iterable[Card], meld_cluster: List[Iterable[Card]]) -> List[Card]:
if len(list(hand)) != 10:
raise GinRummyProgramError("Hand contain {} cards: should be 10 cards.".format(len(list(hand))))
meld_cards = [card for meld_pile in meld_cluster for card in meld_pile]
deadwood = [card for card in hand if card not in meld_cards]
return deadwood
def get_deadwood_count(hand: List[Card], meld_cluster: List[Iterable[Card]]) -> int:
if len(hand) != 10:
raise GinRummyProgramError("Hand contain {} cards: should be 10 cards.".format(len(hand)))
deadwood = get_deadwood(hand=hand, meld_cluster=meld_cluster)
deadwood_values = [get_deadwood_value(card) for card in deadwood]
return sum(deadwood_values)
def decode_cards(env_cards: np.ndarray) -> List[Card]:
result = [] # type: List[Card]
if len(env_cards) != 52:
raise GinRummyProgramError("len(env_cards) is {}: should be 52.".format(len(env_cards)))
for i in range(52):
if env_cards[i] == 1:
card = _deck[i]
result.append(card)
return result
def encode_cards(cards: List[Card]) -> np.ndarray:
plane = np.zeros(52, dtype=int)
for card in cards:
card_id = get_card_id(card)
plane[card_id] = 1
return plane
'''
gin_rummy/__init__.py
'''
from gin_rummy.base import Card as Card
from gin_rummy.player import GinRummyPlayer as Player
from gin_rummy.dealer import GinRummyDealer as Dealer
from gin_rummy.judge import GinRummyJudge as Judger
from gin_rummy.game import GinRummyGame as Game
'''
gin_rummy/melding.py
'''
from typing import List
from gin_rummy import Card
import utils
from gin_rummy_error import GinRummyProgramError
# ===============================================================
# Terminology:
# run_meld - three or more cards of same suit in sequence
# set_meld - three or more cards of same rank
# meld_pile - a run_meld or a set_meld
# meld_piles - a list of meld_pile
# meld_cluster - same as meld_piles, but usually with the piles being mutually disjoint
# meld_clusters - a list of meld_cluster
# ===============================================================
def get_meld_clusters(hand: List[Card]) -> List[List[List[Card]]]:
result = [] # type: List[List[List[Card]]]
all_run_melds = [frozenset(x) for x in get_all_run_melds(hand)]
all_set_melds = [frozenset(x) for x in get_all_set_melds(hand)]
all_melds = all_run_melds + all_set_melds
all_melds_count = len(all_melds)
for i in range(0, all_melds_count):
first_meld = all_melds[i]
first_meld_list = list(first_meld)
meld_cluster_1 = [first_meld_list]
result.append(meld_cluster_1)
for j in range(i + 1, all_melds_count):
second_meld = all_melds[j]
second_meld_list = list(second_meld)
if not second_meld.isdisjoint(first_meld):
continue
meld_cluster_2 = [first_meld_list, second_meld_list]
result.append(meld_cluster_2)
for k in range(j + 1, all_melds_count):
third_meld = all_melds[k]
third_meld_list = list(third_meld)
if not third_meld.isdisjoint(first_meld) or not third_meld.isdisjoint(second_meld):
continue
meld_cluster_3 = [first_meld_list, second_meld_list, third_meld_list]
result.append(meld_cluster_3)
return result
def get_best_meld_clusters(hand: List[Card]) -> List[List[List[Card]]]:
if len(hand) != 10:
raise GinRummyProgramError("Hand contain {} cards: should be 10 cards.".format(len(hand)))
result = [] # type: List[List[List[Card]]]
meld_clusters = get_meld_clusters(hand=hand) # type: List[List[List[Card]]]
meld_clusters_count = len(meld_clusters)
if meld_clusters_count > 0:
deadwood_counts = [utils.get_deadwood_count(hand=hand, meld_cluster=meld_cluster)
for meld_cluster in meld_clusters]
best_deadwood_count = min(deadwood_counts)
for i in range(meld_clusters_count):
if deadwood_counts[i] == best_deadwood_count:
result.append(meld_clusters[i])
return result
def get_all_run_melds(hand: List[Card]) -> List[List[Card]]:
card_count = len(hand)
hand_by_suit = sorted(hand, key=utils.get_card_id)
max_run_melds = []
i = 0
while i < card_count - 2:
card_i = hand_by_suit[i]
j = i + 1
card_j = hand_by_suit[j]
while utils.get_rank_id(card_j) == utils.get_rank_id(card_i) + j - i and card_j.suit == card_i.suit:
j += 1
if j < card_count:
card_j = hand_by_suit[j]
else:
break
max_run_meld = hand_by_suit[i:j]
if len(max_run_meld) >= 3:
max_run_melds.append(max_run_meld)
i = j
result = []
for max_run_meld in max_run_melds:
max_run_meld_count = len(max_run_meld)
for i in range(max_run_meld_count - 2):
for j in range(i + 3, max_run_meld_count + 1):
result.append(max_run_meld[i:j])
return result
def get_all_set_melds(hand: List[Card]) -> List[List[Card]]:
max_set_melds = []
hand_by_rank = sorted(hand, key=lambda x: x.rank)
set_meld = []
current_rank = None
for card in hand_by_rank:
if current_rank is None or current_rank == card.rank:
set_meld.append(card)
else:
if len(set_meld) >= 3:
max_set_melds.append(set_meld)
set_meld = [card]
current_rank = card.rank
if len(set_meld) >= 3:
max_set_melds.append(set_meld)
result = []
for max_set_meld in max_set_melds:
result.append(max_set_meld)
if len(max_set_meld) == 4:
for meld_card in max_set_meld:
result.append([card for card in max_set_meld if card != meld_card])
return result
def get_all_run_melds_for_suit(cards: List[Card], suit: str) -> List[List[Card]]:
cards_for_suit = [card for card in cards if card.suit == suit]
cards_for_suit_count = len(cards_for_suit)
cards_for_suit = sorted(cards_for_suit, key=utils.get_card_id)
max_run_melds = []
i = 0
while i < cards_for_suit_count - 2:
card_i = cards_for_suit[i]
j = i + 1
card_j = cards_for_suit[j]
while utils.get_rank_id(card_j) == utils.get_rank_id(card_i) + j - i:
j += 1
if j < cards_for_suit_count:
card_j = cards_for_suit[j]
else:
break
max_run_meld = cards_for_suit[i:j]
if len(max_run_meld) >= 3:
max_run_melds.append(max_run_meld)
i = j
result = []
for max_run_meld in max_run_melds:
max_run_meld_count = len(max_run_meld)
for i in range(max_run_meld_count - 2):
for j in range(i + 3, max_run_meld_count + 1):
result.append(max_run_meld[i:j])
return result
'''
gin_rummy/round.py
'''
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from move import GinRummyMove
from typing import List
from gin_rummy import Dealer
from action_event import DrawCardAction, PickUpDiscardAction, DeclareDeadHandAction
from action_event import DiscardAction, KnockAction, GinAction
from action_event import ScoreNorthPlayerAction, ScoreSouthPlayerAction
from move import DealHandMove
from move import DrawCardMove, PickupDiscardMove, DeclareDeadHandMove
from move import DiscardMove, KnockMove, GinMove
from move import ScoreNorthMove, ScoreSouthMove
from gin_rummy_error import GinRummyProgramError
from gin_rummy import Player
import judge
import melding
import utils
class GinRummyRound:
def __init__(self, dealer_id: int, np_random):
''' Initialize the round class
The round class maintains the following instances:
1) dealer: the dealer of the round; dealer has stock_pile and discard_pile
2) players: the players in the round; each player has his own hand_pile
3) current_player_id: the id of the current player who has the move
4) is_over: true if the round is over
5) going_out_action: knock or gin or None
6) going_out_player_id: id of player who went out or None
7) move_sheet: history of the moves of the player (including the deal_hand_move)
The round class maintains a list of moves made by the players in self.move_sheet.
move_sheet is similar to a chess score sheet.
I didn't want to call it a score_sheet since it is not keeping score.
I could have called move_sheet just moves, but that might conflict with the name moves used elsewhere.
I settled on the longer name "move_sheet" to indicate that it is the official list of moves being made.
Args:
dealer_id: int
'''
self.np_random = np_random
self.dealer_id = dealer_id
self.dealer = Dealer(self.np_random)
self.players = [Player(player_id=0, np_random=self.np_random), Player(player_id=1, np_random=self.np_random)]
self.current_player_id = (dealer_id + 1) % 2
self.is_over = False
self.going_out_action = None # going_out_action: int or None
self.going_out_player_id = None # going_out_player_id: int or None
self.move_sheet = [] # type: List[GinRummyMove]
player_dealing = Player(player_id=dealer_id, np_random=self.np_random)
shuffled_deck = self.dealer.shuffled_deck
self.move_sheet.append(DealHandMove(player_dealing=player_dealing, shuffled_deck=shuffled_deck))
def get_current_player(self) -> Player or None:
current_player_id = self.current_player_id
return None if current_player_id is None else self.players[current_player_id]
def draw_card(self, action: DrawCardAction):
# when current_player takes DrawCardAction step, the move is recorded and executed
# current_player keeps turn
current_player = self.players[self.current_player_id]
if not len(current_player.hand) == 10:
raise GinRummyProgramError("len(current_player.hand) is {}: should be 10.".format(len(current_player.hand)))
card = self.dealer.stock_pile.pop()
self.move_sheet.append(DrawCardMove(current_player, action=action, card=card))
current_player.add_card_to_hand(card=card)
def pick_up_discard(self, action: PickUpDiscardAction):
# when current_player takes PickUpDiscardAction step, the move is recorded and executed
# opponent knows that the card is in current_player hand
# current_player keeps turn
current_player = self.players[self.current_player_id]
if not len(current_player.hand) == 10:
raise GinRummyProgramError("len(current_player.hand) is {}: should be 10.".format(len(current_player.hand)))
card = self.dealer.discard_pile.pop()
self.move_sheet.append(PickupDiscardMove(current_player, action, card=card))
current_player.add_card_to_hand(card=card)
current_player.known_cards.append(card)
def declare_dead_hand(self, action: DeclareDeadHandAction):
# when current_player takes DeclareDeadHandAction step, the move is recorded and executed
# north becomes current_player to score his hand
current_player = self.players[self.current_player_id]
self.move_sheet.append(DeclareDeadHandMove(current_player, action))
self.going_out_action = action
self.going_out_player_id = self.current_player_id
if not len(current_player.hand) == 10:
raise GinRummyProgramError("len(current_player.hand) is {}: should be 10.".format(len(current_player.hand)))
self.current_player_id = 0
def discard(self, action: DiscardAction):
# when current_player takes DiscardAction step, the move is recorded and executed
# opponent knows that the card is no longer in current_player hand
# current_player loses his turn and the opponent becomes the current player
current_player = self.players[self.current_player_id]
if not len(current_player.hand) == 11:
raise GinRummyProgramError("len(current_player.hand) is {}: should be 11.".format(len(current_player.hand)))
self.move_sheet.append(DiscardMove(current_player, action))
card = action.card
current_player.remove_card_from_hand(card=card)
if card in current_player.known_cards:
current_player.known_cards.remove(card)
self.dealer.discard_pile.append(card)
self.current_player_id = (self.current_player_id + 1) % 2
def knock(self, action: KnockAction):
# when current_player takes KnockAction step, the move is recorded and executed
# opponent knows that the card is no longer in current_player hand
# north becomes current_player to score his hand
current_player = self.players[self.current_player_id]
self.move_sheet.append(KnockMove(current_player, action))
self.going_out_action = action
self.going_out_player_id = self.current_player_id
if not len(current_player.hand) == 11:
raise GinRummyProgramError("len(current_player.hand) is {}: should be 11.".format(len(current_player.hand)))
card = action.card
current_player.remove_card_from_hand(card=card)
if card in current_player.known_cards:
current_player.known_cards.remove(card)
self.current_player_id = 0
def gin(self, action: GinAction, going_out_deadwood_count: int):
# when current_player takes GinAction step, the move is recorded and executed
# opponent knows that the card is no longer in current_player hand
# north becomes current_player to score his hand
current_player = self.players[self.current_player_id]
self.move_sheet.append(GinMove(current_player, action))
self.going_out_action = action
self.going_out_player_id = self.current_player_id
if not len(current_player.hand) == 11:
raise GinRummyProgramError("len(current_player.hand) is {}: should be 11.".format(len(current_player.hand)))
_, gin_cards = judge.get_going_out_cards(current_player.hand, going_out_deadwood_count)
card = gin_cards[0]
current_player.remove_card_from_hand(card=card)
if card in current_player.known_cards:
current_player.known_cards.remove(card)
self.current_player_id = 0
def score_player_0(self, action: ScoreNorthPlayerAction):
# when current_player takes ScoreNorthPlayerAction step, the move is recorded and executed
# south becomes current player
if not self.current_player_id == 0:
raise GinRummyProgramError("current_player_id is {}: should be 0.".format(self.current_player_id))
current_player = self.get_current_player()
best_meld_clusters = melding.get_best_meld_clusters(hand=current_player.hand)
best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]
deadwood_count = utils.get_deadwood_count(hand=current_player.hand, meld_cluster=best_meld_cluster)
self.move_sheet.append(ScoreNorthMove(player=current_player,
action=action,
best_meld_cluster=best_meld_cluster,
deadwood_count=deadwood_count))
self.current_player_id = 1
def score_player_1(self, action: ScoreSouthPlayerAction):
# when current_player takes ScoreSouthPlayerAction step, the move is recorded and executed
# south remains current player
# the round is over
if not self.current_player_id == 1:
raise GinRummyProgramError("current_player_id is {}: should be 1.".format(self.current_player_id))
current_player = self.get_current_player()
best_meld_clusters = melding.get_best_meld_clusters(hand=current_player.hand)
best_meld_cluster = [] if not best_meld_clusters else best_meld_clusters[0]
deadwood_count = utils.get_deadwood_count(hand=current_player.hand, meld_cluster=best_meld_cluster)
self.move_sheet.append(ScoreSouthMove(player=current_player,
action=action,
best_meld_cluster=best_meld_cluster,
deadwood_count=deadwood_count))
self.is_over = True
'''
gin_rummy/gin_rummy_error.py
'''
class GinRummyError(Exception):
pass
class GinRummyProgramError(GinRummyError):
pass
| 14 | 1,453 | Python |
stock2 | ./ProjectTest/Python/stock2.py | '''
stock2/stock.py
'''
# stock.py
from structure import Structure
class Stock(Structure):
name = String()
shares = PositiveInteger()
price = PositiveFloat()
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares: PositiveInteger):
self.shares -= nshares
'''
stock2/reader.py
'''
# reader.py
import csv
import logging
log = logging.getLogger(__name__)
def convert_csv(lines, converter, *, headers=None):
rows = csv.reader(lines)
if headers is None:
headers = next(rows)
records = []
for rowno, row in enumerate(rows, start=1):
try:
records.append(converter(headers, row))
except ValueError as e:
log.warning('Row %s: Bad row: %s', rowno, row)
log.debug('Row %s: Reason: %s', rowno, row)
return records
def csv_as_dicts(lines, types, *, headers=None):
return convert_csv(lines,
lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })
def csv_as_instances(lines, cls, *, headers=None):
return convert_csv(lines,
lambda headers, row: cls.from_row(row))
def read_csv_as_dicts(filename, types, *, headers=None):
'''
Read CSV data into a list of dictionaries with optional type conversion
'''
with open(filename) as file:
return csv_as_dicts(file, types, headers=headers)
def read_csv_as_instances(filename, cls, *, headers=None):
'''
Read CSV data into a list of instances
'''
with open(filename) as file:
return csv_as_instances(file, cls, headers=headers)
'''
stock2/validate.py
'''
# validate.py
class Validator:
def __init__(self, name=None):
self.name = name
def __set_name__(self, cls, name):
self.name = name
@classmethod
def check(cls, value):
return value
def __set__(self, instance, value):
instance.__dict__[self.name] = self.check(value)
# Collect all derived classes into a dict
validators = { }
@classmethod
def __init_subclass__(cls):
cls.validators[cls.__name__] = cls
class Typed(Validator):
expected_type = object
@classmethod
def check(cls, value):
if not isinstance(value, cls.expected_type):
raise TypeError(f'expected {cls.expected_type}')
return super().check(value)
_typed_classes = [
('Integer', int),
('Float', float),
('String', str) ]
globals().update((name, type(name, (Typed,), {'expected_type':ty}))
for name, ty in _typed_classes)
class Positive(Validator):
@classmethod
def check(cls, value):
if value < 0:
raise ValueError('must be >= 0')
return super().check(value)
class NonEmpty(Validator):
@classmethod
def check(cls, value):
if len(value) == 0:
raise ValueError('must be non-empty')
return super().check(value)
class PositiveInteger(Integer, Positive):
pass
class PositiveFloat(Float, Positive):
pass
class NonEmptyString(String, NonEmpty):
pass
from inspect import signature
from functools import wraps
def isvalidator(item):
return isinstance(item, type) and issubclass(item, Validator)
def validated(func):
sig = signature(func)
# Gather the function annotations
annotations = { name:val for name, val in func.__annotations__.items()
if isvalidator(val) }
# Get the return annotation (if any)
retcheck = annotations.pop('return', None)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
# Enforce return check (if any)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
def enforce(**annotations):
retcheck = annotations.pop('return_', None)
def decorate(func):
sig = signature(func)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
return decorate
'''
stock2/tableformat.py
'''
# tableformat.py
from abc import ABC, abstractmethod
def print_table(records, fields, formatter):
if not isinstance(formatter, TableFormatter):
raise RuntimeError('Expected a TableFormatter')
formatter.headings(fields)
for r in records:
rowdata = [getattr(r, fieldname) for fieldname in fields]
formatter.row(rowdata)
class TableFormatter(ABC):
@abstractmethod
def headings(self, headers):
pass
@abstractmethod
def row(self, rowdata):
pass
class TextTableFormatter(TableFormatter):
def headings(self, headers):
print(' '.join('%10s' % h for h in headers))
print(('-'*10 + ' ')*len(headers))
def row(self, rowdata):
print(' '.join('%10s' % d for d in rowdata))
class CSVTableFormatter(TableFormatter):
def headings(self, headers):
print(','.join(headers))
def row(self, rowdata):
print(','.join(str(d) for d in rowdata))
class HTMLTableFormatter(TableFormatter):
def headings(self, headers):
print('<tr>', end=' ')
for h in headers:
print('<th>%s</th>' % h, end=' ')
print('</tr>')
def row(self, rowdata):
print('<tr>', end=' ')
for d in rowdata:
print('<td>%s</td>' % d, end=' ')
print('</tr>')
class ColumnFormatMixin:
formats = []
def row(self, rowdata):
rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]
super().row(rowdata)
class UpperHeadersMixin:
def headings(self, headers):
super().headings([h.upper() for h in headers])
def create_formatter(name, column_formats=None, upper_headers=False):
if name == 'text':
formatter_cls = TextTableFormatter
elif name == 'csv':
formatter_cls = CSVTableFormatter
elif name == 'html':
formatter_cls = HTMLTableFormatter
else:
raise RuntimeError('Unknown format %s' % name)
if column_formats:
class formatter_cls(ColumnFormatMixin, formatter_cls):
formats = column_formats
if upper_headers:
class formatter_cls(UpperHeadersMixin, formatter_cls):
pass
return formatter_cls()
'''
stock2/structure.py
'''
# structure.py
from validate import Validator, validated
from collections import ChainMap
class StructureMeta(type):
@classmethod
def __prepare__(meta, clsname, bases):
return ChainMap({}, Validator.validators)
@staticmethod
def __new__(meta, name, bases, methods):
methods = methods.maps[0]
return super().__new__(meta, name, bases, methods)
class Structure(metaclass=StructureMeta):
_fields = ()
_types = ()
def __setattr__(self, name, value):
if name.startswith('_') or name in self._fields:
super().__setattr__(name, value)
else:
raise AttributeError('No attribute %s' % name)
def __repr__(self):
return '%s(%s)' % (type(self).__name__,
', '.join(repr(getattr(self, name)) for name in self._fields))
@classmethod
def from_row(cls, row):
rowdata = [ func(val) for func, val in zip(cls._types, row) ]
return cls(*rowdata)
@classmethod
def create_init(cls):
'''
Create an __init__ method from _fields
'''
args = ','.join(cls._fields)
code = f'def __init__(self, {args}):\n'
for name in cls._fields:
code += f' self.{name} = {name}\n'
locs = { }
exec(code, locs)
cls.__init__ = locs['__init__']
@classmethod
def __init_subclass__(cls):
# Apply the validated decorator to subclasses
validate_attributes(cls)
def validate_attributes(cls):
'''
Class decorator that scans a class definition for Validators
and builds a _fields variable that captures their definition order.
'''
validators = []
for name, val in vars(cls).items():
if isinstance(val, Validator):
validators.append(val)
# Apply validated decorator to any callable with annotations
elif callable(val) and val.__annotations__:
setattr(cls, name, validated(val))
# Collect all of the field names
cls._fields = tuple([v.name for v in validators])
# Collect type conversions. The lambda x:x is an identity
# function that's used in case no expected_type is found.
cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)
for v in validators ])
# Create the __init__ method
if cls._fields:
cls.create_init()
return cls
def typed_structure(clsname, **validators):
cls = type(clsname, (Structure,), validators)
return cls
| 5 | 361 | Python |
stock | ./ProjectTest/Python/stock.py | '''
stock/stock.py
'''
# stock.py
from structure import Structure
from validate import String, PositiveInteger, PositiveFloat
class Stock(Structure):
name = String()
shares = PositiveInteger()
price = PositiveFloat()
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares: PositiveInteger):
self.shares -= nshares
'''
stock/validate.py
'''
# validate.py
class Validator:
def __init__(self, name=None):
self.name = name
def __set_name__(self, cls, name):
self.name = name
@classmethod
def check(cls, value):
return value
def __set__(self, instance, value):
instance.__dict__[self.name] = self.check(value)
class Typed(Validator):
expected_type = object
@classmethod
def check(cls, value):
if not isinstance(value, cls.expected_type):
raise TypeError(f'expected {cls.expected_type}')
return super().check(value)
class Integer(Typed):
expected_type = int
class Float(Typed):
expected_type = float
class String(Typed):
expected_type = str
class Positive(Validator):
@classmethod
def check(cls, value):
if value < 0:
raise ValueError('must be >= 0')
return super().check(value)
class NonEmpty(Validator):
@classmethod
def check(cls, value):
if len(value) == 0:
raise ValueError('must be non-empty')
return super().check(value)
class PositiveInteger(Integer, Positive):
pass
class PositiveFloat(Float, Positive):
pass
class NonEmptyString(String, NonEmpty):
pass
from inspect import signature
from functools import wraps
def isvalidator(item):
return isinstance(item, type) and issubclass(item, Validator)
def validated(func):
sig = signature(func)
# Gather the function annotations
annotations = { name:val for name, val in func.__annotations__.items()
if isvalidator(val) }
# Get the return annotation (if any)
retcheck = annotations.pop('return', None)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
# Enforce return check (if any)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
def enforce(**annotations):
retcheck = annotations.pop('return_', None)
def decorate(func):
sig = signature(func)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
return decorate
'''
stock/structure.py
'''
# structure.py
from validate import Validator, validated
class Structure:
_fields = ()
_types = ()
def __setattr__(self, name, value):
if name.startswith('_') or name in self._fields:
super().__setattr__(name, value)
else:
raise AttributeError('No attribute %s' % name)
def __repr__(self):
return '%s(%s)' % (type(self).__name__,
', '.join(repr(getattr(self, name)) for name in self._fields))
@classmethod
def from_row(cls, row):
rowdata = [ func(val) for func, val in zip(cls._types, row) ]
return cls(*rowdata)
@classmethod
def create_init(cls):
'''
Create an __init__ method from _fields
'''
args = ','.join(cls._fields)
code = f'def __init__(self, {args}):\n'
for name in cls._fields:
code += f' self.{name} = {name}\n'
locs = { }
exec(code, locs)
cls.__init__ = locs['__init__']
@classmethod
def __init_subclass__(cls):
# Apply the validated decorator to subclasses
validate_attributes(cls)
def validate_attributes(cls):
'''
Class decorator that scans a class definition for Validators
and builds a _fields variable that captures their definition order.
'''
validators = []
for name, val in vars(cls).items():
if isinstance(val, Validator):
validators.append(val)
# Apply validated decorator to any callable with annotations
elif callable(val) and val.__annotations__:
setattr(cls, name, validated(val))
# Collect all of the field names
cls._fields = tuple([v.name for v in validators])
# Collect type conversions. The lambda x:x is an identity
# function that's used in case no expected_type is found.
cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)
for v in validators ])
# Create the __init__ method
if cls._fields:
cls.create_init()
return cls
| 3 | 217 | Python |
structly | ./ProjectTest/Python/structly.py | '''
structly/stock.py
'''
# stock.py
from structly.structure import Structure
class Stock(Structure):
name = String()
shares = PositiveInteger()
price = PositiveFloat()
@property
def cost(self):
return self.shares * self.price
def sell(self, nshares: PositiveInteger):
self.shares -= nshares
'''
structly/structly/reader.py
'''
# reader.py
import csv
import logging
log = logging.getLogger(__name__)
def convert_csv(lines, converter, *, headers=None):
rows = csv.reader(lines)
if headers is None:
headers = next(rows)
records = []
for rowno, row in enumerate(rows, start=1):
try:
records.append(converter(headers, row))
except ValueError as e:
log.warning('Row %s: Bad row: %s', rowno, row)
log.debug('Row %s: Reason: %s', rowno, row)
return records
def csv_as_dicts(lines, types, *, headers=None):
return convert_csv(lines,
lambda headers, row: { name: func(val) for name, func, val in zip(headers, types, row) })
def csv_as_instances(lines, cls, *, headers=None):
return convert_csv(lines,
lambda headers, row: cls.from_row(row))
def read_csv_as_dicts(filename, types, *, headers=None):
'''
Read CSV data into a list of dictionaries with optional type conversion
'''
with open(filename) as file:
return csv_as_dicts(file, types, headers=headers)
def read_csv_as_instances(filename, cls, *, headers=None):
'''
Read CSV data into a list of instances
'''
with open(filename) as file:
return csv_as_instances(file, cls, headers=headers)
'''
structly/structly/validate.py
'''
# validate.py
class Validator:
def __init__(self, name=None):
self.name = name
def __set_name__(self, cls, name):
self.name = name
@classmethod
def check(cls, value):
return value
def __set__(self, instance, value):
instance.__dict__[self.name] = self.check(value)
# Collect all derived classes into a dict
validators = { }
@classmethod
def __init_subclass__(cls):
cls.validators[cls.__name__] = cls
class Typed(Validator):
expected_type = object
@classmethod
def check(cls, value):
if not isinstance(value, cls.expected_type):
raise TypeError(f'expected {cls.expected_type}')
return super().check(value)
_typed_classes = [
('Integer', int),
('Float', float),
('String', str) ]
globals().update((name, type(name, (Typed,), {'expected_type':ty}))
for name, ty in _typed_classes)
class Positive(Validator):
@classmethod
def check(cls, value):
if value < 0:
raise ValueError('must be >= 0')
return super().check(value)
class NonEmpty(Validator):
@classmethod
def check(cls, value):
if len(value) == 0:
raise ValueError('must be non-empty')
return super().check(value)
class PositiveInteger(Integer, Positive):
pass
class PositiveFloat(Float, Positive):
pass
class NonEmptyString(String, NonEmpty):
pass
from inspect import signature
from functools import wraps
def isvalidator(item):
return isinstance(item, type) and issubclass(item, Validator)
def validated(func):
sig = signature(func)
# Gather the function annotations
annotations = { name:val for name, val in func.__annotations__.items()
if isvalidator(val) }
# Get the return annotation (if any)
retcheck = annotations.pop('return', None)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
# Enforce return check (if any)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
def enforce(**annotations):
retcheck = annotations.pop('return_', None)
def decorate(func):
sig = signature(func)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
return decorate
'''
structly/structly/__init__.py
'''
'''
structly/structly/tableformat.py
'''
# tableformat.py
from abc import ABC, abstractmethod
def print_table(records, fields, formatter):
if not isinstance(formatter, TableFormatter):
raise RuntimeError('Expected a TableFormatter')
formatter.headings(fields)
for r in records:
rowdata = [getattr(r, fieldname) for fieldname in fields]
formatter.row(rowdata)
class TableFormatter(ABC):
@abstractmethod
def headings(self, headers):
pass
@abstractmethod
def row(self, rowdata):
pass
class TextTableFormatter(TableFormatter):
def headings(self, headers):
print(' '.join('%10s' % h for h in headers))
print(('-'*10 + ' ')*len(headers))
def row(self, rowdata):
print(' '.join('%10s' % d for d in rowdata))
class CSVTableFormatter(TableFormatter):
def headings(self, headers):
print(','.join(headers))
def row(self, rowdata):
print(','.join(str(d) for d in rowdata))
class HTMLTableFormatter(TableFormatter):
def headings(self, headers):
print('<tr>', end=' ')
for h in headers:
print('<th>%s</th>' % h, end=' ')
print('</tr>')
def row(self, rowdata):
print('<tr>', end=' ')
for d in rowdata:
print('<td>%s</td>' % d, end=' ')
print('</tr>')
class ColumnFormatMixin:
formats = []
def row(self, rowdata):
rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]
super().row(rowdata)
class UpperHeadersMixin:
def headings(self, headers):
super().headings([h.upper() for h in headers])
def create_formatter(name, column_formats=None, upper_headers=False):
if name == 'text':
formatter_cls = TextTableFormatter
elif name == 'csv':
formatter_cls = CSVTableFormatter
elif name == 'html':
formatter_cls = HTMLTableFormatter
else:
raise RuntimeError('Unknown format %s' % name)
if column_formats:
class formatter_cls(ColumnFormatMixin, formatter_cls):
formats = column_formats
if upper_headers:
class formatter_cls(UpperHeadersMixin, formatter_cls):
pass
return formatter_cls()
'''
structly/structly/structure.py
'''
# structure.py
from structly.validate import Validator, validated
from collections import ChainMap
class StructureMeta(type):
@classmethod
def __prepare__(meta, clsname, bases):
return ChainMap({}, Validator.validators)
@staticmethod
def __new__(meta, name, bases, methods):
methods = methods.maps[0]
return super().__new__(meta, name, bases, methods)
class Structure(metaclass=StructureMeta):
_fields = ()
_types = ()
def __setattr__(self, name, value):
if name.startswith('_') or name in self._fields:
super().__setattr__(name, value)
else:
raise AttributeError('No attribute %s' % name)
def __repr__(self):
return '%s(%s)' % (type(self).__name__,
', '.join(repr(getattr(self, name)) for name in self._fields))
def __iter__(self):
for name in self._fields:
yield getattr(self, name)
def __eq__(self, other):
return isinstance(other, type(self)) and tuple(self) == tuple(other)
@classmethod
def from_row(cls, row):
rowdata = [ func(val) for func, val in zip(cls._types, row) ]
return cls(*rowdata)
@classmethod
def create_init(cls):
'''
Create an __init__ method from _fields
'''
args = ','.join(cls._fields)
code = f'def __init__(self, {args}):\n'
for name in cls._fields:
code += f' self.{name} = {name}\n'
locs = { }
exec(code, locs)
cls.__init__ = locs['__init__']
@classmethod
def __init_subclass__(cls):
# Apply the validated decorator to subclasses
validate_attributes(cls)
def validate_attributes(cls):
'''
Class decorator that scans a class definition for Validators
and builds a _fields variable that captures their definition order.
'''
validators = []
for name, val in vars(cls).items():
if isinstance(val, Validator):
validators.append(val)
# Apply validated decorator to any callable with annotations
elif callable(val) and val.__annotations__:
setattr(cls, name, validated(val))
# Collect all of the field names
cls._fields = tuple([v.name for v in validators])
# Collect type conversions. The lambda x:x is an identity
# function that's used in case no expected_type is found.
cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)
for v in validators ])
# Create the __init__ method
if cls._fields:
cls.create_init()
return cls
def typed_structure(clsname, **validators):
cls = type(clsname, (Structure,), validators)
return cls
| 6 | 369 | Python |
leducholdem | ./ProjectTest/Python/leducholdem.py | '''
leducholdem/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
leducholdem/player.py
'''
from enum import Enum
class PlayerStatus(Enum):
ALIVE = 0
FOLDED = 1
ALLIN = 2
class LeducholdemPlayer:
def __init__(self, player_id, np_random):
''' Initilize a player.
Args:
player_id (int): The id of the player
'''
self.np_random = np_random
self.player_id = player_id
self.status = 'alive'
self.hand = None
# The chips that this player has put in until now
self.in_chips = 0
def get_state(self, public_card, all_chips, legal_actions):
''' Encode the state for the player
Args:
public_card (object): The public card that seen by all the players
all_chips (int): The chips that all players have put in
Returns:
(dict): The state of the player
'''
state = {}
state['hand'] = self.hand.get_index()
state['public_card'] = public_card.get_index() if public_card else None
state['all_chips'] = all_chips
state['my_chips'] = self.in_chips
state['legal_actions'] = legal_actions
return state
def get_player_id(self):
''' Return the id of the player
'''
return self.player_id
'''
leducholdem/dealer.py
'''
from leducholdem.utils import init_standard_deck
from leducholdem import Card
class LimitHoldemDealer:
def __init__(self, np_random):
self.np_random = np_random
self.deck = init_standard_deck()
self.shuffle()
self.pot = 0
def shuffle(self):
self.np_random.shuffle(self.deck)
def deal_card(self):
"""
Deal one card from the deck
Returns:
(Card): The drawn card from the deck
"""
return self.deck.pop()
class LeducholdemDealer(LimitHoldemDealer):
def __init__(self, np_random):
''' Initialize a leducholdem dealer class
'''
self.np_random = np_random
self.deck = [Card('S', 'J'), Card('H', 'J'), Card('S', 'Q'), Card('H', 'Q'), Card('S', 'K'), Card('H', 'K')]
self.shuffle()
self.pot = 0
'''
leducholdem/judger.py
'''
from leducholdem.utils import rank2int
class LeducholdemJudger:
''' The Judger class for Leduc Hold'em
'''
def __init__(self, np_random):
''' Initialize a judger class
'''
self.np_random = np_random
@staticmethod
def judge_game(players, public_card):
''' Judge the winner of the game.
Args:
players (list): The list of players who play the game
public_card (object): The public card that seen by all the players
Returns:
(list): Each entry of the list corresponds to one entry of the
'''
# Judge who are the winners
winners = [0] * len(players)
fold_count = 0
ranks = []
# If every player folds except one, the alive player is the winner
for idx, player in enumerate(players):
ranks.append(rank2int(player.hand.rank))
if player.status == 'folded':
fold_count += 1
elif player.status == 'alive':
alive_idx = idx
if fold_count == (len(players) - 1):
winners[alive_idx] = 1
# If any of the players matches the public card wins
if sum(winners) < 1:
for idx, player in enumerate(players):
if player.hand.rank == public_card.rank:
winners[idx] = 1
break
# If non of the above conditions, the winner player is the one with the highest card rank
if sum(winners) < 1:
max_rank = max(ranks)
max_index = [i for i, j in enumerate(ranks) if j == max_rank]
for idx in max_index:
winners[idx] = 1
# Compute the total chips
total = 0
for p in players:
total += p.in_chips
each_win = float(total) / sum(winners)
payoffs = []
for i, _ in enumerate(players):
if winners[i] == 1:
payoffs.append(each_win - players[i].in_chips)
else:
payoffs.append(float(-players[i].in_chips))
return payoffs
'''
leducholdem/game.py
'''
import numpy as np
from copy import copy, deepcopy
from leducholdem import Dealer
from leducholdem import Player, PlayerStatus
from leducholdem import Judger
from leducholdem import Round
class LimitHoldemGame:
def __init__(self, allow_step_back=False, num_players=2):
"""Initialize the class limit holdem game"""
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
# Some configurations of the game
# These arguments can be specified for creating new games
# Small blind and big blind
self.small_blind = 1
self.big_blind = 2 * self.small_blind
# Raise amount and allowed times
self.raise_amount = self.big_blind
self.allowed_raise_num = 4
self.num_players = num_players
# Save betting history
self.history_raise_nums = [0 for _ in range(4)]
self.dealer = None
self.players = None
self.judger = None
self.public_cards = None
self.game_pointer = None
self.round = None
self.round_counter = None
self.history = None
self.history_raises_nums = None
def configure(self, game_config):
"""Specify some game specific parameters, such as number of players"""
self.num_players = game_config['game_num_players']
def init_game(self):
"""
Initialize the game of limit texas holdem
This version supports two-player limit texas holdem
Returns:
(tuple): Tuple containing:
(dict): The first state of the game
(int): Current player's id
"""
# Initialize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initialize two players to play the game
self.players = [Player(i, self.np_random) for i in range(self.num_players)]
# Initialize a judger class which will decide who wins in the end
self.judger = Judger(self.np_random)
# Deal cards to each player to prepare for the first round
for i in range(2 * self.num_players):
self.players[i % self.num_players].hand.append(self.dealer.deal_card())
# Initialize public cards
self.public_cards = []
# Randomly choose a small blind and a big blind
s = self.np_random.randint(0, self.num_players)
b = (s + 1) % self.num_players
self.players[b].in_chips = self.big_blind
self.players[s].in_chips = self.small_blind
# The player next to the big blind plays the first
self.game_pointer = (b + 1) % self.num_players
# Initialize a bidding round, in the first round, the big blind and the small blind needs to
# be passed to the round for processing.
self.round = Round(raise_amount=self.raise_amount,
allowed_raise_num=self.allowed_raise_num,
num_players=self.num_players,
np_random=self.np_random)
self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])
# Count the round. There are 4 rounds in each game.
self.round_counter = 0
# Save the history for stepping back to the last state.
self.history = []
state = self.get_state(self.game_pointer)
# Save betting history
self.history_raise_nums = [0 for _ in range(4)]
return state, self.game_pointer
def step(self, action):
"""
Get the next state
Args:
action (str): a specific action. (call, raise, fold, or check)
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next player id
"""
if self.allow_step_back:
# First snapshot the current state
r = deepcopy(self.round)
b = self.game_pointer
r_c = self.round_counter
d = deepcopy(self.dealer)
p = deepcopy(self.public_cards)
ps = deepcopy(self.players)
rn = copy(self.history_raise_nums)
self.history.append((r, b, r_c, d, p, ps, rn))
# Then we proceed to the next round
self.game_pointer = self.round.proceed_round(self.players, action)
# Save the current raise num to history
self.history_raise_nums[self.round_counter] = self.round.have_raised
# If a round is over, we deal more public cards
if self.round.is_over():
# For the first round, we deal 3 cards
if self.round_counter == 0:
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
# For the following rounds, we deal only 1 card
elif self.round_counter <= 2:
self.public_cards.append(self.dealer.deal_card())
# Double the raise amount for the last two rounds
if self.round_counter == 1:
self.round.raise_amount = 2 * self.raise_amount
self.round_counter += 1
self.round.start_new_round(self.game_pointer)
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def step_back(self):
"""
Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
"""
if len(self.history) > 0:
self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \
self.players, self.history_raises_nums = self.history.pop()
return True
return False
def get_num_players(self):
"""
Return the number of players in limit texas holdem
Returns:
(int): The number of players in the game
"""
return self.num_players
@staticmethod
def get_num_actions():
"""
Return the number of applicable actions
Returns:
(int): The number of actions. There are 4 actions (call, raise, check and fold)
"""
return 4
def get_player_id(self):
"""
Return the current player's id
Returns:
(int): current player's id
"""
return self.game_pointer
def get_state(self, player):
"""
Return player's state
Args:
player (int): player id
Returns:
(dict): The state of the player
"""
chips = [self.players[i].in_chips for i in range(self.num_players)]
legal_actions = self.get_legal_actions()
state = self.players[player].get_state(self.public_cards, chips, legal_actions)
state['raise_nums'] = self.history_raise_nums
return state
def is_over(self):
"""
Check if the game is over
Returns:
(boolean): True if the game is over
"""
alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players]
# If only one player is alive, the game is over.
if sum(alive_players) == 1:
return True
# If all rounds are finished
if self.round_counter >= 4:
return True
return False
def get_payoffs(self):
"""
Return the payoffs of the game
Returns:
(list): Each entry corresponds to the payoff of one player
"""
hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players]
chips_payoffs = self.judger.judge_game(self.players, hands)
payoffs = np.array(chips_payoffs) / self.big_blind
return payoffs
def get_legal_actions(self):
"""
Return the legal actions for current player
Returns:
(list): A list of legal actions
"""
return self.round.get_legal_actions()
class LeducholdemGame(LimitHoldemGame):
def __init__(self, allow_step_back=False, num_players=2):
''' Initialize the class leducholdem Game
'''
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
''' No big/small blind
# Some configarations of the game
# These arguments are fixed in Leduc Hold'em Game
# Raise amount and allowed times
self.raise_amount = 2
self.allowed_raise_num = 2
self.num_players = 2
'''
# Some configarations of the game
# These arguments can be specified for creating new games
# Small blind and big blind
self.small_blind = 1
self.big_blind = 2 * self.small_blind
# Raise amount and allowed times
self.raise_amount = self.big_blind
self.allowed_raise_num = 2
self.num_players = num_players
def configure(self, game_config):
''' Specifiy some game specific parameters, such as number of players
'''
self.num_players = game_config['game_num_players']
def init_game(self):
''' Initialilze the game of Limit Texas Hold'em
This version supports two-player limit texas hold'em
Returns:
(tuple): Tuple containing:
(dict): The first state of the game
(int): Current player's id
'''
# Initilize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initilize two players to play the game
self.players = [Player(i, self.np_random) for i in range(self.num_players)]
# Initialize a judger class which will decide who wins in the end
self.judger = Judger(self.np_random)
# Prepare for the first round
for i in range(self.num_players):
self.players[i].hand = self.dealer.deal_card()
# Randomly choose a small blind and a big blind
s = self.np_random.randint(0, self.num_players)
b = (s + 1) % self.num_players
self.players[b].in_chips = self.big_blind
self.players[s].in_chips = self.small_blind
self.public_card = None
# The player with small blind plays the first
self.game_pointer = s
# Initilize a bidding round, in the first round, the big blind and the small blind needs to
# be passed to the round for processing.
self.round = Round(raise_amount=self.raise_amount,
allowed_raise_num=self.allowed_raise_num,
num_players=self.num_players,
np_random=self.np_random)
self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])
# Count the round. There are 2 rounds in each game.
self.round_counter = 0
# Save the hisory for stepping back to the last state.
self.history = []
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def step(self, action):
''' Get the next state
Args:
action (str): a specific action. (call, raise, fold, or check)
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next plater's id
'''
if self.allow_step_back:
# First snapshot the current state
r = copy(self.round)
r_raised = copy(self.round.raised)
gp = self.game_pointer
r_c = self.round_counter
d_deck = copy(self.dealer.deck)
p = copy(self.public_card)
ps = [copy(self.players[i]) for i in range(self.num_players)]
ps_hand = [copy(self.players[i].hand) for i in range(self.num_players)]
self.history.append((r, r_raised, gp, r_c, d_deck, p, ps, ps_hand))
# Then we proceed to the next round
self.game_pointer = self.round.proceed_round(self.players, action)
# If a round is over, we deal more public cards
if self.round.is_over():
# For the first round, we deal 1 card as public card. Double the raise amount for the second round
if self.round_counter == 0:
self.public_card = self.dealer.deal_card()
self.round.raise_amount = 2 * self.raise_amount
self.round_counter += 1
self.round.start_new_round(self.game_pointer)
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def get_state(self, player):
''' Return player's state
Args:
player_id (int): player id
Returns:
(dict): The state of the player
'''
chips = [self.players[i].in_chips for i in range(self.num_players)]
legal_actions = self.get_legal_actions()
state = self.players[player].get_state(self.public_card, chips, legal_actions)
state['current_player'] = self.game_pointer
return state
def is_over(self):
''' Check if the game is over
Returns:
(boolean): True if the game is over
'''
alive_players = [1 if p.status=='alive' else 0 for p in self.players]
# If only one player is alive, the game is over.
if sum(alive_players) == 1:
return True
# If all rounds are finshed
if self.round_counter >= 2:
return True
return False
def get_payoffs(self):
''' Return the payoffs of the game
Returns:
(list): Each entry corresponds to the payoff of one player
'''
chips_payoffs = self.judger.judge_game(self.players, self.public_card)
payoffs = np.array(chips_payoffs) / (self.big_blind)
return payoffs
def step_back(self):
''' Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
'''
if len(self.history) > 0:
self.round, r_raised, self.game_pointer, self.round_counter, d_deck, self.public_card, self.players, ps_hand = self.history.pop()
self.round.raised = r_raised
self.dealer.deck = d_deck
for i, hand in enumerate(ps_hand):
self.players[i].hand = hand
return True
return False
'''
leducholdem/utils.py
'''
from leducholdem import Card
def init_standard_deck():
''' Initialize a standard deck of 52 cards
Returns:
(list): A list of Card object
'''
suit_list = ['S', 'H', 'D', 'C']
rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
res = [Card(suit, rank) for suit in suit_list for rank in rank_list]
return res
def rank2int(rank):
''' Get the coresponding number of a rank.
Args:
rank(str): rank stored in Card object
Returns:
(int): the number corresponding to the rank
Note:
1. If the input rank is an empty string, the function will return -1.
2. If the input rank is not valid, the function will return None.
'''
if rank == '':
return -1
elif rank.isdigit():
if int(rank) >= 2 and int(rank) <= 10:
return int(rank)
else:
return None
elif rank == 'A':
return 14
elif rank == 'T':
return 10
elif rank == 'J':
return 11
elif rank == 'Q':
return 12
elif rank == 'K':
return 13
return None
'''
leducholdem/__init__.py
'''
from leducholdem.base import Card as Card
from leducholdem.dealer import LeducholdemDealer as Dealer
from leducholdem.judger import LeducholdemJudger as Judger
from leducholdem.player import LeducholdemPlayer as Player
from leducholdem.player import PlayerStatus
from leducholdem.round import LeducholdemRound as Round
from leducholdem.game import LeducholdemGame as Game
'''
leducholdem/round.py
'''
# -*- coding: utf-8 -*-
''' Implement Leduc Hold'em Round class
'''
class LimitHoldemRound:
"""Round can call other Classes' functions to keep the game running"""
def __init__(self, raise_amount, allowed_raise_num, num_players, np_random):
"""
Initialize the round class
Args:
raise_amount (int): the raise amount for each raise
allowed_raise_num (int): The number of allowed raise num
num_players (int): The number of players
"""
self.np_random = np_random
self.game_pointer = None
self.raise_amount = raise_amount
self.allowed_raise_num = allowed_raise_num
self.num_players = num_players
# Count the number of raise
self.have_raised = 0
# Count the number without raise
# If every player agree to not raise, the round is over
self.not_raise_num = 0
# Raised amount for each player
self.raised = [0 for _ in range(self.num_players)]
self.player_folded = None
def start_new_round(self, game_pointer, raised=None):
"""
Start a new bidding round
Args:
game_pointer (int): The game_pointer that indicates the next player
raised (list): Initialize the chips for each player
Note: For the first round of the game, we need to setup the big/small blind
"""
self.game_pointer = game_pointer
self.have_raised = 0
self.not_raise_num = 0
if raised:
self.raised = raised
else:
self.raised = [0 for _ in range(self.num_players)]
def proceed_round(self, players, action):
"""
Call other classes functions to keep one round running
Args:
players (list): The list of players that play the game
action (str): An legal action taken by the player
Returns:
(int): The game_pointer that indicates the next player
"""
if action not in self.get_legal_actions():
raise Exception('{} is not legal action. Legal actions: {}'.format(action, self.get_legal_actions()))
if action == 'call':
diff = max(self.raised) - self.raised[self.game_pointer]
self.raised[self.game_pointer] = max(self.raised)
players[self.game_pointer].in_chips += diff
self.not_raise_num += 1
elif action == 'raise':
diff = max(self.raised) - self.raised[self.game_pointer] + self.raise_amount
self.raised[self.game_pointer] = max(self.raised) + self.raise_amount
players[self.game_pointer].in_chips += diff
self.have_raised += 1
self.not_raise_num = 1
elif action == 'fold':
players[self.game_pointer].status = 'folded'
self.player_folded = True
elif action == 'check':
self.not_raise_num += 1
self.game_pointer = (self.game_pointer + 1) % self.num_players
# Skip the folded players
while players[self.game_pointer].status == 'folded':
self.game_pointer = (self.game_pointer + 1) % self.num_players
return self.game_pointer
def get_legal_actions(self):
"""
Obtain the legal actions for the current player
Returns:
(list): A list of legal actions
"""
full_actions = ['call', 'raise', 'fold', 'check']
# If the the number of raises already reaches the maximum number raises, we can not raise any more
if self.have_raised >= self.allowed_raise_num:
full_actions.remove('raise')
# If the current chips are less than that of the highest one in the round, we can not check
if self.raised[self.game_pointer] < max(self.raised):
full_actions.remove('check')
# If the current player has put in the chips that are more than others, we can not call
if self.raised[self.game_pointer] == max(self.raised):
full_actions.remove('call')
return full_actions
def is_over(self):
"""
Check whether the round is over
Returns:
(boolean): True if the current round is over
"""
if self.not_raise_num >= self.num_players:
return True
return False
class LeducholdemRound(LimitHoldemRound):
''' Round can call other Classes' functions to keep the game running
'''
def __init__(self, raise_amount, allowed_raise_num, num_players, np_random):
''' Initilize the round class
Args:
raise_amount (int): the raise amount for each raise
allowed_raise_num (int): The number of allowed raise num
num_players (int): The number of players
'''
super(LeducholdemRound, self).__init__(raise_amount, allowed_raise_num, num_players, np_random=np_random)
| 8 | 833 | Python |
bridge | ./ProjectTest/Python/bridge.py | '''
bridge/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
bridge/player.py
'''
from typing import List
from bridge_card import BridgeCard
class BridgePlayer:
def __init__(self, player_id: int, np_random):
''' Initialize a BridgePlayer player class
Args:
player_id (int): id for the player
'''
if player_id < 0 or player_id > 3:
raise Exception(f'BridgePlayer has invalid player_id: {player_id}')
self.np_random = np_random
self.player_id: int = player_id
self.hand: List[BridgeCard] = []
def remove_card_from_hand(self, card: BridgeCard):
self.hand.remove(card)
def __str__(self):
return ['N', 'E', 'S', 'W'][self.player_id]
'''
bridge/move.py
'''
#
# These classes are used to keep a move_sheet history of the moves in a round.
#
from action_event import ActionEvent, BidAction, PassAction, DblAction, RdblAction, PlayCardAction
from bridge_card import BridgeCard
from bridge import Player
class BridgeMove(object): # Interface
pass
class PlayerMove(BridgeMove): # Interface
def __init__(self, player: Player, action: ActionEvent):
super().__init__()
self.player = player
self.action = action
class CallMove(PlayerMove): # Interface
def __init__(self, player: Player, action: ActionEvent):
super().__init__(player=player, action=action)
class DealHandMove(BridgeMove):
def __init__(self, dealer: Player, shuffled_deck: [BridgeCard]):
super().__init__()
self.dealer = dealer
self.shuffled_deck = shuffled_deck
def __str__(self):
shuffled_deck_text = " ".join([str(card) for card in self.shuffled_deck])
return f'{self.dealer} deal shuffled_deck=[{shuffled_deck_text}]'
class MakePassMove(CallMove):
def __init__(self, player: Player):
super().__init__(player=player, action=PassAction())
def __str__(self):
return f'{self.player} {self.action}'
class MakeDblMove(CallMove):
def __init__(self, player: Player):
super().__init__(player=player, action=DblAction())
def __str__(self):
return f'{self.player} {self.action}'
class MakeRdblMove(CallMove):
def __init__(self, player: Player):
super().__init__(player=player, action=RdblAction())
def __str__(self):
return f'{self.player} {self.action}'
class MakeBidMove(CallMove):
def __init__(self, player: Player, bid_action: BidAction):
super().__init__(player=player, action=bid_action)
self.action = bid_action # Note: keep type as BidAction rather than ActionEvent
def __str__(self):
return f'{self.player} bids {self.action}'
class PlayCardMove(PlayerMove):
def __init__(self, player: Player, action: PlayCardAction):
super().__init__(player=player, action=action)
self.action = action # Note: keep type as PlayCardAction rather than ActionEvent
@property
def card(self):
return self.action.card
def __str__(self):
return f'{self.player} plays {self.action}'
'''
bridge/dealer.py
'''
from typing import List
from bridge import Player
from bridge_card import BridgeCard
class BridgeDealer:
''' Initialize a BridgeDealer dealer class
'''
def __init__(self, np_random):
''' set shuffled_deck, set stock_pile
'''
self.np_random = np_random
self.shuffled_deck: List[BridgeCard] = BridgeCard.get_deck() # keep a copy of the shuffled cards at start of new hand
self.np_random.shuffle(self.shuffled_deck)
self.stock_pile: List[BridgeCard] = self.shuffled_deck.copy()
def deal_cards(self, player: Player, num: int):
''' Deal some cards from stock_pile to one player
Args:
player (BridgePlayer): The BridgePlayer object
num (int): The number of cards to be dealt
'''
for _ in range(num):
player.hand.append(self.stock_pile.pop())
'''
bridge/judger.py
'''
from typing import List
from typing import TYPE_CHECKING
from action_event import PlayCardAction
from action_event import ActionEvent, BidAction, PassAction, DblAction, RdblAction
from move import MakeBidMove, MakeDblMove, MakeRdblMove
from bridge_card import BridgeCard
class BridgeJudger:
'''
Judger decides legal actions for current player
'''
def __init__(self, game: 'BridgeGame'):
''' Initialize the class BridgeJudger
:param game: BridgeGame
'''
self.game: BridgeGame = game
def get_legal_actions(self) -> List[ActionEvent]:
"""
:return: List[ActionEvent] of legal actions
"""
legal_actions: List[ActionEvent] = []
if not self.game.is_over():
current_player = self.game.round.get_current_player()
if not self.game.round.is_bidding_over():
legal_actions.append(PassAction())
last_make_bid_move: MakeBidMove or None = None
last_dbl_move: MakeDblMove or None = None
last_rdbl_move: MakeRdblMove or None = None
for move in reversed(self.game.round.move_sheet):
if isinstance(move, MakeBidMove):
last_make_bid_move = move
break
elif isinstance(move, MakeRdblMove):
last_rdbl_move = move
elif isinstance(move, MakeDblMove) and not last_rdbl_move:
last_dbl_move = move
first_bid_action_id = ActionEvent.first_bid_action_id
next_bid_action_id = last_make_bid_move.action.action_id + 1 if last_make_bid_move else first_bid_action_id
for bid_action_id in range(next_bid_action_id, first_bid_action_id + 35):
action = BidAction.from_action_id(action_id=bid_action_id)
legal_actions.append(action)
if last_make_bid_move and last_make_bid_move.player.player_id % 2 != current_player.player_id % 2 and not last_dbl_move and not last_rdbl_move:
legal_actions.append(DblAction())
if last_dbl_move and last_dbl_move.player.player_id % 2 != current_player.player_id % 2:
legal_actions.append(RdblAction())
else:
trick_moves = self.game.round.get_trick_moves()
hand = self.game.round.players[current_player.player_id].hand
legal_cards = hand
if trick_moves and len(trick_moves) < 4:
led_card: BridgeCard = trick_moves[0].card
cards_of_led_suit = [card for card in hand if card.suit == led_card.suit]
if cards_of_led_suit:
legal_cards = cards_of_led_suit
for card in legal_cards:
action = PlayCardAction(card=card)
legal_actions.append(action)
return legal_actions
'''
bridge/action_event.py
'''
from bridge_card import BridgeCard
# ====================================
# Action_ids:
# 0 -> no_bid_action_id
# 1 to 35 -> bid_action_id (bid amount by suit or NT)
# 36 -> pass_action_id
# 37 -> dbl_action_id
# 38 -> rdbl_action_id
# 39 to 90 -> play_card_action_id
# ====================================
class ActionEvent(object): # Interface
no_bid_action_id = 0
first_bid_action_id = 1
pass_action_id = 36
dbl_action_id = 37
rdbl_action_id = 38
first_play_card_action_id = 39
def __init__(self, action_id: int):
self.action_id = action_id
def __eq__(self, other):
result = False
if isinstance(other, ActionEvent):
result = self.action_id == other.action_id
return result
@staticmethod
def from_action_id(action_id: int):
if action_id == ActionEvent.pass_action_id:
return PassAction()
elif ActionEvent.first_bid_action_id <= action_id <= 35:
bid_amount = 1 + (action_id - ActionEvent.first_bid_action_id) // 5
bid_suit_id = (action_id - ActionEvent.first_bid_action_id) % 5
bid_suit = BridgeCard.suits[bid_suit_id] if bid_suit_id < 4 else None
return BidAction(bid_amount, bid_suit)
elif action_id == ActionEvent.dbl_action_id:
return DblAction()
elif action_id == ActionEvent.rdbl_action_id:
return RdblAction()
elif ActionEvent.first_play_card_action_id <= action_id < ActionEvent.first_play_card_action_id + 52:
card_id = action_id - ActionEvent.first_play_card_action_id
card = BridgeCard.card(card_id=card_id)
return PlayCardAction(card=card)
else:
raise Exception(f'ActionEvent from_action_id: invalid action_id={action_id}')
@staticmethod
def get_num_actions():
''' Return the number of possible actions in the game
'''
return 1 + 35 + 3 + 52 # no_bid, 35 bids, pass, dbl, rdl, 52 play_card
class CallActionEvent(ActionEvent): # Interface
pass
class PassAction(CallActionEvent):
def __init__(self):
super().__init__(action_id=ActionEvent.pass_action_id)
def __str__(self):
return "pass"
def __repr__(self):
return "pass"
class BidAction(CallActionEvent):
def __init__(self, bid_amount: int, bid_suit: str or None):
suits = BridgeCard.suits
if bid_suit and bid_suit not in suits:
raise Exception(f'BidAction has invalid suit: {bid_suit}')
if bid_suit in suits:
bid_suit_id = suits.index(bid_suit)
else:
bid_suit_id = 4
bid_action_id = bid_suit_id + 5 * (bid_amount - 1) + ActionEvent.first_bid_action_id
super().__init__(action_id=bid_action_id)
self.bid_amount = bid_amount
self.bid_suit = bid_suit
def __str__(self):
bid_suit = self.bid_suit
if not bid_suit:
bid_suit = 'NT'
return f'{self.bid_amount}{bid_suit}'
def __repr__(self):
return self.__str__()
class DblAction(CallActionEvent):
def __init__(self):
super().__init__(action_id=ActionEvent.dbl_action_id)
def __str__(self):
return "dbl"
def __repr__(self):
return "dbl"
class RdblAction(CallActionEvent):
def __init__(self):
super().__init__(action_id=ActionEvent.rdbl_action_id)
def __str__(self):
return "rdbl"
def __repr__(self):
return "rdbl"
class PlayCardAction(ActionEvent):
def __init__(self, card: BridgeCard):
play_card_action_id = ActionEvent.first_play_card_action_id + card.card_id
super().__init__(action_id=play_card_action_id)
self.card: BridgeCard = card
def __str__(self):
return f"{self.card}"
def __repr__(self):
return f"{self.card}"
'''
bridge/tray.py
'''
class Tray(object):
def __init__(self, board_id: int):
if board_id <= 0:
raise Exception(f'Tray: invalid board_id={board_id}')
self.board_id = board_id
@property
def dealer_id(self):
return (self.board_id - 1) % 4
@property
def vul(self):
vul_none = [0, 0, 0, 0]
vul_n_s = [1, 0, 1, 0]
vul_e_w = [0, 1, 0, 1]
vul_all = [1, 1, 1, 1]
basic_vuls = [vul_none, vul_n_s, vul_e_w, vul_all]
offset = (self.board_id - 1) // 4
return basic_vuls[(self.board_id - 1 + offset) % 4]
def __str__(self):
return f'{self.board_id}: dealer_id={self.dealer_id} vul={self.vul}'
'''
bridge/game.py
'''
from typing import List
import numpy as np
from bridge import Judger
from round import BridgeRound
from action_event import ActionEvent, CallActionEvent, PlayCardAction
class BridgeGame:
''' Game class. This class will interact with outer environment.
'''
def __init__(self, allow_step_back=False):
'''Initialize the class BridgeGame
'''
self.allow_step_back: bool = allow_step_back
self.np_random = np.random.RandomState()
self.judger: Judger = Judger(game=self)
self.actions: [ActionEvent] = [] # must reset in init_game
self.round: BridgeRound or None = None # must reset in init_game
self.num_players: int = 4
def init_game(self):
''' Initialize all characters in the game and start round 1
'''
board_id = self.np_random.choice([1, 2, 3, 4])
self.actions: List[ActionEvent] = []
self.round = BridgeRound(num_players=self.num_players, board_id=board_id, np_random=self.np_random)
for player_id in range(4):
player = self.round.players[player_id]
self.round.dealer.deal_cards(player=player, num=13)
current_player_id = self.round.current_player_id
state = self.get_state(player_id=current_player_id)
return state, current_player_id
def step(self, action: ActionEvent):
''' Perform game action and return next player number, and the state for next player
'''
if isinstance(action, CallActionEvent):
self.round.make_call(action=action)
elif isinstance(action, PlayCardAction):
self.round.play_card(action=action)
else:
raise Exception(f'Unknown step action={action}')
self.actions.append(action)
next_player_id = self.round.current_player_id
next_state = self.get_state(player_id=next_player_id)
return next_state, next_player_id
def get_num_players(self) -> int:
''' Return the number of players in the game
'''
return self.num_players
@staticmethod
def get_num_actions() -> int:
''' Return the number of possible actions in the game
'''
return ActionEvent.get_num_actions()
def get_player_id(self):
''' Return the current player that will take actions soon
'''
return self.round.current_player_id
def is_over(self) -> bool:
''' Return whether the current game is over
'''
return self.round.is_over()
def get_state(self, player_id: int): # wch: not really used
''' Get player's state
Return:
state (dict): The information of the state
'''
state = {}
if not self.is_over():
state['player_id'] = player_id
state['current_player_id'] = self.round.current_player_id
state['hand'] = self.round.players[player_id].hand
else:
state['player_id'] = player_id
state['current_player_id'] = self.round.current_player_id
state['hand'] = self.round.players[player_id].hand
return state
'''
bridge/__init__.py
'''
from bridge.base import Card as Card
from bridge.player import BridgePlayer as Player
from bridge.dealer import BridgeDealer as Dealer
from bridge.judger import BridgeJudger as Judger
from bridge.game import BridgeGame as Game
'''
bridge/round.py
'''
from typing import List
from bridge import Dealer
from bridge import Player
from action_event import CallActionEvent, PassAction, DblAction, RdblAction, BidAction, PlayCardAction
from move import BridgeMove, DealHandMove, PlayCardMove, MakeBidMove, MakePassMove, MakeDblMove, MakeRdblMove, CallMove
from tray import Tray
class BridgeRound:
@property
def dealer_id(self) -> int:
return self.tray.dealer_id
@property
def vul(self):
return self.tray.vul
@property
def board_id(self) -> int:
return self.tray.board_id
@property
def round_phase(self):
if self.is_over():
result = 'game over'
elif self.is_bidding_over():
result = 'play card'
else:
result = 'make bid'
return result
def __init__(self, num_players: int, board_id: int, np_random):
''' Initialize the round class
The round class maintains the following instances:
1) dealer: the dealer of the round; dealer has trick_pile
2) players: the players in the round; each player has his own hand_pile
3) current_player_id: the id of the current player who has the move
4) doubling_cube: 2 if contract is doubled; 4 if contract is redoubled; else 1
5) play_card_count: count of PlayCardMoves
5) move_sheet: history of the moves of the players (including the deal_hand_move)
The round class maintains a list of moves made by the players in self.move_sheet.
move_sheet is similar to a chess score sheet.
I didn't want to call it a score_sheet since it is not keeping score.
I could have called move_sheet just moves, but that might conflict with the name moves used elsewhere.
I settled on the longer name "move_sheet" to indicate that it is the official list of moves being made.
Args:
num_players: int
board_id: int
np_random
'''
tray = Tray(board_id=board_id)
dealer_id = tray.dealer_id
self.tray = tray
self.np_random = np_random
self.dealer: Dealer = Dealer(self.np_random)
self.players: List[Player] = []
for player_id in range(num_players):
self.players.append(Player(player_id=player_id, np_random=self.np_random))
self.current_player_id: int = dealer_id
self.doubling_cube: int = 1
self.play_card_count: int = 0
self.contract_bid_move: MakeBidMove or None = None
self.won_trick_counts = [0, 0] # count of won tricks by side
self.move_sheet: List[BridgeMove] = []
self.move_sheet.append(DealHandMove(dealer=self.players[dealer_id], shuffled_deck=self.dealer.shuffled_deck))
def is_bidding_over(self) -> bool:
''' Return whether the current bidding is over
'''
is_bidding_over = True
if len(self.move_sheet) < 5:
is_bidding_over = False
else:
last_make_pass_moves: List[MakePassMove] = []
for move in reversed(self.move_sheet):
if isinstance(move, MakePassMove):
last_make_pass_moves.append(move)
if len(last_make_pass_moves) == 3:
break
elif isinstance(move, CallMove):
is_bidding_over = False
break
else:
break
return is_bidding_over
def is_over(self) -> bool:
''' Return whether the current game is over
'''
is_over = True
if not self.is_bidding_over():
is_over = False
elif self.contract_bid_move:
for player in self.players:
if player.hand:
is_over = False
break
return is_over
def get_current_player(self) -> Player or None:
current_player_id = self.current_player_id
return None if current_player_id is None else self.players[current_player_id]
def get_trick_moves(self) -> List[PlayCardMove]:
trick_moves: List[PlayCardMove] = []
if self.is_bidding_over():
if self.play_card_count > 0:
trick_pile_count = self.play_card_count % 4
if trick_pile_count == 0:
trick_pile_count = 4 # wch: note this
for move in self.move_sheet[-trick_pile_count:]:
if isinstance(move, PlayCardMove):
trick_moves.append(move)
if len(trick_moves) != trick_pile_count:
raise Exception(f'get_trick_moves: count of trick_moves={[str(move.card) for move in trick_moves]} does not equal {trick_pile_count}')
return trick_moves
def get_trump_suit(self) -> str or None:
trump_suit = None
if self.contract_bid_move:
trump_suit = self.contract_bid_move.action.bid_suit
return trump_suit
def make_call(self, action: CallActionEvent):
# when current_player takes CallActionEvent step, the move is recorded and executed
current_player = self.players[self.current_player_id]
if isinstance(action, PassAction):
self.move_sheet.append(MakePassMove(current_player))
elif isinstance(action, BidAction):
self.doubling_cube = 1
make_bid_move = MakeBidMove(current_player, action)
self.contract_bid_move = make_bid_move
self.move_sheet.append(make_bid_move)
elif isinstance(action, DblAction):
self.doubling_cube = 2
self.move_sheet.append(MakeDblMove(current_player))
elif isinstance(action, RdblAction):
self.doubling_cube = 4
self.move_sheet.append(MakeRdblMove(current_player))
if self.is_bidding_over():
if not self.is_over():
self.current_player_id = self.get_left_defender().player_id
else:
self.current_player_id = (self.current_player_id + 1) % 4
def play_card(self, action: PlayCardAction):
# when current_player takes PlayCardAction step, the move is recorded and executed
current_player = self.players[self.current_player_id]
self.move_sheet.append(PlayCardMove(current_player, action))
card = action.card
current_player.remove_card_from_hand(card=card)
self.play_card_count += 1
# update current_player_id
trick_moves = self.get_trick_moves()
if len(trick_moves) == 4:
trump_suit = self.get_trump_suit()
winning_card = trick_moves[0].card
trick_winner = trick_moves[0].player
for move in trick_moves[1:]:
trick_card = move.card
trick_player = move.player
if trick_card.suit == winning_card.suit:
if trick_card.card_id > winning_card.card_id:
winning_card = trick_card
trick_winner = trick_player
elif trick_card.suit == trump_suit:
winning_card = trick_card
trick_winner = trick_player
self.current_player_id = trick_winner.player_id
self.won_trick_counts[trick_winner.player_id % 2] += 1
else:
self.current_player_id = (self.current_player_id + 1) % 4
def get_declarer(self) -> Player or None:
declarer = None
if self.contract_bid_move:
trump_suit = self.contract_bid_move.action.bid_suit
side = self.contract_bid_move.player.player_id % 2
for move in self.move_sheet:
if isinstance(move, MakeBidMove) and move.action.bid_suit == trump_suit and move.player.player_id % 2 == side:
declarer = move.player
break
return declarer
def get_dummy(self) -> Player or None:
dummy = None
declarer = self.get_declarer()
if declarer:
dummy = self.players[(declarer.player_id + 2) % 4]
return dummy
def get_left_defender(self) -> Player or None:
left_defender = None
declarer = self.get_declarer()
if declarer:
left_defender = self.players[(declarer.player_id + 1) % 4]
return left_defender
def get_right_defender(self) -> Player or None:
right_defender = None
declarer = self.get_declarer()
if declarer:
right_defender = self.players[(declarer.player_id + 3) % 4]
return right_defender
def get_perfect_information(self):
state = {}
last_call_move = None
if not self.is_bidding_over() or self.play_card_count == 0:
last_move = self.move_sheet[-1]
if isinstance(last_move, CallMove):
last_call_move = last_move
trick_moves = [None, None, None, None]
if self.is_bidding_over():
for trick_move in self.get_trick_moves():
trick_moves[trick_move.player.player_id] = trick_move.card
state['move_count'] = len(self.move_sheet)
state['tray'] = self.tray
state['current_player_id'] = self.current_player_id
state['round_phase'] = self.round_phase
state['last_call_move'] = last_call_move
state['doubling_cube'] = self.doubling_cube
state['contact'] = self.contract_bid_move if self.is_bidding_over() and self.contract_bid_move else None
state['hands'] = [player.hand for player in self.players]
state['trick_moves'] = trick_moves
return state
def print_scene(self):
print(f'===== Board: {self.tray.board_id} move: {len(self.move_sheet)} player: {self.players[self.current_player_id]} phase: {self.round_phase} =====')
print(f'dealer={self.players[self.tray.dealer_id]}')
print(f'vul={self.vul}')
if not self.is_bidding_over() or self.play_card_count == 0:
last_move = self.move_sheet[-1]
last_call_text = f'{last_move}' if isinstance(last_move, CallMove) else 'None'
print(f'last call: {last_call_text}')
if self.is_bidding_over() and self.contract_bid_move:
bid_suit = self.contract_bid_move.action.bid_suit
doubling_cube = self.doubling_cube
if not bid_suit:
bid_suit = 'NT'
doubling_cube_text = "" if doubling_cube == 1 else "dbl" if doubling_cube == 2 else "rdbl"
print(f'contract: {self.contract_bid_move.player} {self.contract_bid_move.action.bid_amount}{bid_suit} {doubling_cube_text}')
for player in self.players:
print(f'{player}: {[str(card) for card in player.hand]}')
if self.is_bidding_over():
trick_pile = ['None', 'None', 'None', 'None']
for trick_move in self.get_trick_moves():
trick_pile[trick_move.player.player_id] = trick_move.card
print(f'trick_pile: {[str(card) for card in trick_pile]}')
'''
bridge/bridge_card.py
'''
from bridge import Card
class BridgeCard(Card):
suits = ['C', 'D', 'H', 'S']
ranks = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A']
@staticmethod
def card(card_id: int):
return _deck[card_id]
@staticmethod
def get_deck() -> [Card]:
return _deck.copy()
def __init__(self, suit: str, rank: str):
super().__init__(suit=suit, rank=rank)
suit_index = BridgeCard.suits.index(self.suit)
rank_index = BridgeCard.ranks.index(self.rank)
self.card_id = 13 * suit_index + rank_index
def __str__(self):
return f'{self.rank}{self.suit}'
def __repr__(self):
return f'{self.rank}{self.suit}'
# deck is always in order from 2C, ... KC, AC, 2D, ... KD, AD, 2H, ... KH, AH, 2S, ... KS, AS
_deck = [BridgeCard(suit=suit, rank=rank) for suit in BridgeCard.suits for rank in BridgeCard.ranks] # want this to be read-only
| 11 | 792 | Python |
stock4 | ./ProjectTest/Python/stock4.py | '''
stock4/validate.py
'''
# validate.py
class Validator:
def __init__(self, name=None):
self.name = name
def __set_name__(self, cls, name):
self.name = name
@classmethod
def check(cls, value):
return value
def __set__(self, instance, value):
instance.__dict__[self.name] = self.check(value)
# Collect all derived classes into a dict
validators = { }
@classmethod
def __init_subclass__(cls):
cls.validators[cls.__name__] = cls
class Typed(Validator):
expected_type = object
@classmethod
def check(cls, value):
if not isinstance(value, cls.expected_type):
raise TypeError(f'expected {cls.expected_type}')
return super().check(value)
_typed_classes = [
('Integer', int),
('Float', float),
('String', str) ]
globals().update((name, type(name, (Typed,), {'expected_type':ty}))
for name, ty in _typed_classes)
class Positive(Validator):
@classmethod
def check(cls, value):
if value < 0:
raise ValueError('must be >= 0')
return super().check(value)
class NonEmpty(Validator):
@classmethod
def check(cls, value):
if len(value) == 0:
raise ValueError('must be non-empty')
return super().check(value)
class PositiveInteger(Integer, Positive):
pass
class PositiveFloat(Float, Positive):
pass
class NonEmptyString(String, NonEmpty):
pass
from inspect import signature
from functools import wraps
def isvalidator(item):
return isinstance(item, type) and issubclass(item, Validator)
def validated(func):
sig = signature(func)
# Gather the function annotations
annotations = { name:val for name, val in func.__annotations__.items()
if isvalidator(val) }
# Get the return annotation (if any)
retcheck = annotations.pop('return', None)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
# Enforce return check (if any)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
def enforce(**annotations):
retcheck = annotations.pop('return_', None)
def decorate(func):
sig = signature(func)
@wraps(func)
def wrapper(*args, **kwargs):
bound = sig.bind(*args, **kwargs)
errors = []
# Enforce argument checks
for name, validator in annotations.items():
try:
validator.check(bound.arguments[name])
except Exception as e:
errors.append(f' {name}: {e}')
if errors:
raise TypeError('Bad Arguments\n' + '\n'.join(errors))
result = func(*args, **kwargs)
if retcheck:
try:
retcheck.check(result)
except Exception as e:
raise TypeError(f'Bad return: {e}') from None
return result
return wrapper
return decorate
'''
stock4/tableformat.py
'''
# tableformat.py
from abc import ABC, abstractmethod
def print_table(records, fields, formatter):
if not isinstance(formatter, TableFormatter):
raise RuntimeError('Expected a TableFormatter')
formatter.headings(fields)
for r in records:
rowdata = [getattr(r, fieldname) for fieldname in fields]
formatter.row(rowdata)
class TableFormatter(ABC):
@abstractmethod
def headings(self, headers):
pass
@abstractmethod
def row(self, rowdata):
pass
class TextTableFormatter(TableFormatter):
def headings(self, headers):
print(' '.join('%10s' % h for h in headers))
print(('-'*10 + ' ')*len(headers))
def row(self, rowdata):
print(' '.join('%10s' % d for d in rowdata))
class CSVTableFormatter(TableFormatter):
def headings(self, headers):
print(','.join(headers))
def row(self, rowdata):
print(','.join(str(d) for d in rowdata))
class HTMLTableFormatter(TableFormatter):
def headings(self, headers):
print('<tr>', end=' ')
for h in headers:
print('<th>%s</th>' % h, end=' ')
print('</tr>')
def row(self, rowdata):
print('<tr>', end=' ')
for d in rowdata:
print('<td>%s</td>' % d, end=' ')
print('</tr>')
class ColumnFormatMixin:
formats = []
def row(self, rowdata):
rowdata = [ (fmt % item) for fmt, item in zip(self.formats, rowdata)]
super().row(rowdata)
class UpperHeadersMixin:
def headings(self, headers):
super().headings([h.upper() for h in headers])
def create_formatter(name, column_formats=None, upper_headers=False):
if name == 'text':
formatter_cls = TextTableFormatter
elif name == 'csv':
formatter_cls = CSVTableFormatter
elif name == 'html':
formatter_cls = HTMLTableFormatter
else:
raise RuntimeError('Unknown format %s' % name)
if column_formats:
class formatter_cls(ColumnFormatMixin, formatter_cls):
formats = column_formats
if upper_headers:
class formatter_cls(UpperHeadersMixin, formatter_cls):
pass
return formatter_cls()
'''
stock4/ticker.py
'''
# ticker.py
from structure import Structure
class Ticker(Structure):
name = String()
price = Float()
date = String()
time = String()
change = Float()
open = Float()
high = Float()
low = Float()
volume = Integer()
'''
stock4/structure.py
'''
# structure.py
from validate import Validator, validated
from collections import ChainMap
class StructureMeta(type):
@classmethod
def __prepare__(meta, clsname, bases):
return ChainMap({}, Validator.validators)
@staticmethod
def __new__(meta, name, bases, methods):
methods = methods.maps[0]
return super().__new__(meta, name, bases, methods)
class Structure(metaclass=StructureMeta):
_fields = ()
_types = ()
def __setattr__(self, name, value):
if name.startswith('_') or name in self._fields:
super().__setattr__(name, value)
else:
raise AttributeError('No attribute %s' % name)
def __repr__(self):
return '%s(%s)' % (type(self).__name__,
', '.join(repr(getattr(self, name)) for name in self._fields))
def __iter__(self):
for name in self._fields:
yield getattr(self, name)
def __eq__(self, other):
return isinstance(other, type(self)) and tuple(self) == tuple(other)
@classmethod
def from_row(cls, row):
rowdata = [ func(val) for func, val in zip(cls._types, row) ]
return cls(*rowdata)
@classmethod
def create_init(cls):
'''
Create an __init__ method from _fields
'''
args = ','.join(cls._fields)
code = f'def __init__(self, {args}):\n'
for name in cls._fields:
code += f' self.{name} = {name}\n'
locs = { }
exec(code, locs)
cls.__init__ = locs['__init__']
@classmethod
def __init_subclass__(cls):
# Apply the validated decorator to subclasses
validate_attributes(cls)
def validate_attributes(cls):
'''
Class decorator that scans a class definition for Validators
and builds a _fields variable that captures their definition order.
'''
validators = []
for name, val in vars(cls).items():
if isinstance(val, Validator):
validators.append(val)
# Apply validated decorator to any callable with annotations
elif callable(val) and val.__annotations__:
setattr(cls, name, validated(val))
# Collect all of the field names
cls._fields = tuple([v.name for v in validators])
# Collect type conversions. The lambda x:x is an identity
# function that's used in case no expected_type is found.
cls._types = tuple([ getattr(v, 'expected_type', lambda x: x)
for v in validators ])
# Create the __init__ method
if cls._fields:
cls.create_init()
return cls
def typed_structure(clsname, **validators):
cls = type(clsname, (Structure,), validators)
return cls
| 4 | 323 | Python |
doudizhu | ./ProjectTest/Python/doudizhu.py | '''
doudizhu/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
doudizhu/player.py
'''
# -*- coding: utf-8 -*-
''' Implement Doudizhu Player class
'''
import functools
from doudizhu.utils import get_gt_cards
from doudizhu.utils import cards2str, doudizhu_sort_card
class DoudizhuPlayer:
''' Player can store cards in the player's hand and the role,
determine the actions can be made according to the rules,
and can perfrom corresponding action
'''
def __init__(self, player_id, np_random):
''' Give the player an id in one game
Args:
player_id (int): the player_id of a player
Notes:
1. role: A player's temporary role in one game(landlord or peasant)
2. played_cards: The cards played in one round
3. hand: Initial cards
4. _current_hand: The rest of the cards after playing some of them
'''
self.np_random = np_random
self.player_id = player_id
self.initial_hand = None
self._current_hand = []
self.role = ''
self.played_cards = None
self.singles = '3456789TJQKA2BR'
#record cards removed from self._current_hand for each play()
# and restore cards back to self._current_hand when play_back()
self._recorded_played_cards = []
@property
def current_hand(self):
return self._current_hand
def set_current_hand(self, value):
self._current_hand = value
def get_state(self, public, others_hands, num_cards_left, actions):
state = {}
state['seen_cards'] = public['seen_cards']
state['landlord'] = public['landlord']
state['trace'] = public['trace'].copy()
state['played_cards'] = public['played_cards']
state['self'] = self.player_id
state['current_hand'] = cards2str(self._current_hand)
state['others_hand'] = others_hands
state['num_cards_left'] = num_cards_left
state['actions'] = actions
return state
def available_actions(self, greater_player=None, judger=None):
''' Get the actions can be made based on the rules
Args:
greater_player (DoudizhuPlayer object): player who played
current biggest cards.
judger (DoudizhuJudger object): object of DoudizhuJudger
Returns:
list: list of string of actions. Eg: ['pass', '8', '9', 'T', 'J']
'''
actions = []
if greater_player is None or greater_player.player_id == self.player_id:
actions = judger.get_playable_cards(self)
else:
actions = get_gt_cards(self, greater_player)
return actions
def play(self, action, greater_player=None):
''' Perfrom action
Args:
action (string): specific action
greater_player (DoudizhuPlayer object): The player who played current biggest cards.
Returns:
object of DoudizhuPlayer: If there is a new greater_player, return it, if not, return None
'''
trans = {'B': 'BJ', 'R': 'RJ'}
if action == 'pass':
self._recorded_played_cards.append([])
return greater_player
else:
removed_cards = []
self.played_cards = action
for play_card in action:
if play_card in trans:
play_card = trans[play_card]
for _, remain_card in enumerate(self._current_hand):
if remain_card.rank != '':
remain_card = remain_card.rank
else:
remain_card = remain_card.suit
if play_card == remain_card:
removed_cards.append(self.current_hand[_])
self._current_hand.remove(self._current_hand[_])
break
self._recorded_played_cards.append(removed_cards)
return self
def play_back(self):
''' Restore recorded cards back to self._current_hand
'''
removed_cards = self._recorded_played_cards.pop()
self._current_hand.extend(removed_cards)
self._current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card))
'''
doudizhu/dealer.py
'''
# -*- coding: utf-8 -*-
''' Implement Doudizhu Dealer class
'''
import functools
from doudizhu import Card
from doudizhu.utils import cards2str, doudizhu_sort_card
def init_54_deck():
''' Initialize a standard deck of 52 cards, BJ and RJ
Returns:
(list): Alist of Card object
'''
suit_list = ['S', 'H', 'D', 'C']
rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
res = [Card(suit, rank) for suit in suit_list for rank in rank_list]
res.append(Card('BJ', ''))
res.append(Card('RJ', ''))
return res
class DoudizhuDealer:
''' Dealer will shuffle, deal cards, and determine players' roles
'''
def __init__(self, np_random):
'''Give dealer the deck
Notes:
1. deck with 54 cards including black joker and red joker
'''
self.np_random = np_random
self.deck = init_54_deck()
self.deck.sort(key=functools.cmp_to_key(doudizhu_sort_card))
self.landlord = None
def shuffle(self):
''' Randomly shuffle the deck
'''
self.np_random.shuffle(self.deck)
def deal_cards(self, players):
''' Deal cards to players
Args:
players (list): list of DoudizhuPlayer objects
'''
hand_num = (len(self.deck) - 3) // len(players)
for index, player in enumerate(players):
current_hand = self.deck[index*hand_num:(index+1)*hand_num]
current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card))
player.set_current_hand(current_hand)
player.initial_hand = cards2str(player.current_hand)
def determine_role(self, players):
''' Determine landlord and peasants according to players' hand
Args:
players (list): list of DoudizhuPlayer objects
Returns:
int: landlord's player_id
'''
# deal cards
self.shuffle()
self.deal_cards(players)
players[0].role = 'landlord'
self.landlord = players[0]
players[1].role = 'peasant'
players[2].role = 'peasant'
#players[0].role = 'peasant'
#self.landlord = players[0]
## determine 'landlord'
#max_score = get_landlord_score(
# cards2str(self.landlord.current_hand))
#for player in players[1:]:
# player.role = 'peasant'
# score = get_landlord_score(
# cards2str(player.current_hand))
# if score > max_score:
# max_score = score
# self.landlord = player
#self.landlord.role = 'landlord'
# give the 'landlord' the three cards
self.landlord.current_hand.extend(self.deck[-3:])
self.landlord.current_hand.sort(key=functools.cmp_to_key(doudizhu_sort_card))
self.landlord.initial_hand = cards2str(self.landlord.current_hand)
return self.landlord.player_id
'''
doudizhu/judger.py
'''
# -*- coding: utf-8 -*-
''' Implement Doudizhu Judger class
'''
import numpy as np
import collections
from itertools import combinations
from bisect import bisect_left
from doudizhu.utils import CARD_RANK_STR, CARD_RANK_STR_INDEX
from doudizhu.utils import cards2str, contains_cards
class DoudizhuJudger:
''' Determine what cards a player can play
'''
@staticmethod
def chain_indexes(indexes_list):
''' Find chains for solos, pairs and trios by using indexes_list
Args:
indexes_list: the indexes of cards those have the same count, the count could be 1, 2, or 3.
Returns:
list of tuples: [(start_index1, length1), (start_index1, length1), ...]
'''
chains = []
prev_index = -100
count = 0
start = None
for i in indexes_list:
if (i[0] >= 12): #no chains for '2BR'
break
if (i[0] == prev_index + 1):
count += 1
else:
if (count > 1):
chains.append((start, count))
count = 1
start = i[0]
prev_index = i[0]
if (count > 1):
chains.append((start, count))
return chains
@classmethod
def solo_attachments(cls, hands, chain_start, chain_length, size):
''' Find solo attachments for trio_chain_solo_x and four_two_solo
Args:
hands:
chain_start: the index of start card of the trio_chain or trio or four
chain_length: the size of the sequence of the chain, 1 for trio_solo or four_two_solo
size: count of solos for the attachments
Returns:
list of tuples: [attachment1, attachment2, ...]
Each attachment has two elemnts,
the first one contains indexes of attached cards smaller than the index of chain_start,
the first one contains indexes of attached cards larger than the index of chain_start
'''
attachments = set()
candidates = []
prev_card = None
same_card_count = 0
for card in hands:
#dont count those cards in the chain
if (CARD_RANK_STR_INDEX[card] >= chain_start and CARD_RANK_STR_INDEX[card] < chain_start + chain_length):
continue
if (card == prev_card):
#attachments can not have bomb
if (same_card_count == 3):
continue
#attachments can not have 3 same cards consecutive with the trio (except 3 cards of '222')
elif (same_card_count == 2 and (CARD_RANK_STR_INDEX[card] == chain_start - 1 or CARD_RANK_STR_INDEX[card] == chain_start + chain_length) and card != '2'):
continue
else:
same_card_count += 1
else:
prev_card = card
same_card_count = 1
candidates.append(CARD_RANK_STR_INDEX[card])
for attachment in combinations(candidates, size):
if (attachment[-1] == 14 and attachment[-2] == 13):
continue
i = bisect_left(attachment, chain_start)
attachments.add((attachment[:i], attachment[i:]))
return list(attachments)
@classmethod
def pair_attachments(cls, cards_count, chain_start, chain_length, size):
''' Find pair attachments for trio_chain_pair_x and four_two_pair
Args:
cards_count:
chain_start: the index of start card of the trio_chain or trio or four
chain_length: the size of the sequence of the chain, 1 for trio_pair or four_two_pair
size: count of pairs for the attachments
Returns:
list of tuples: [attachment1, attachment2, ...]
Each attachment has two elemnts,
the first one contains indexes of attached cards smaller than the index of chain_start,
the first one contains indexes of attached cards larger than the index of chain_start
'''
attachments = set()
candidates = []
for i, _ in enumerate(cards_count):
if (i >= chain_start and i < chain_start + chain_length):
continue
if (cards_count[i] == 2 or cards_count[i] == 3):
candidates.append(i)
elif (cards_count[i] == 4):
candidates.append(i)
for attachment in combinations(candidates, size):
if (attachment[-1] == 14 and attachment[-2] == 13):
continue
i = bisect_left(attachment, chain_start)
attachments.add((attachment[:i], attachment[i:]))
return list(attachments)
@staticmethod
def playable_cards_from_hand(current_hand):
''' Get playable cards from hand
Returns:
set: set of string of playable cards
'''
cards_dict = collections.defaultdict(int)
for card in current_hand:
cards_dict[card] += 1
cards_count = np.array([cards_dict[k] for k in CARD_RANK_STR])
playable_cards = set()
non_zero_indexes = np.argwhere(cards_count > 0)
more_than_1_indexes = np.argwhere(cards_count > 1)
more_than_2_indexes = np.argwhere(cards_count > 2)
more_than_3_indexes = np.argwhere(cards_count > 3)
#solo
for i in non_zero_indexes:
playable_cards.add(CARD_RANK_STR[i[0]])
#pair
for i in more_than_1_indexes:
playable_cards.add(CARD_RANK_STR[i[0]] * 2)
#bomb, four_two_solo, four_two_pair
for i in more_than_3_indexes:
cards = CARD_RANK_STR[i[0]] * 4
playable_cards.add(cards)
for left, right in DoudizhuJudger.solo_attachments(current_hand, i[0], 1, 2):
pre_attached = ''
for j in left:
pre_attached += CARD_RANK_STR[j]
post_attached = ''
for j in right:
post_attached += CARD_RANK_STR[j]
playable_cards.add(pre_attached + cards + post_attached)
for left, right in DoudizhuJudger.pair_attachments(cards_count, i[0], 1, 2):
pre_attached = ''
for j in left:
pre_attached += CARD_RANK_STR[j] * 2
post_attached = ''
for j in right:
post_attached += CARD_RANK_STR[j] * 2
playable_cards.add(pre_attached + cards + post_attached)
#solo_chain_5 -- #solo_chain_12
solo_chain_indexes = DoudizhuJudger.chain_indexes(non_zero_indexes)
for (start_index, length) in solo_chain_indexes:
s, l = start_index, length
while(l >= 5):
cards = ''
curr_index = s - 1
curr_length = 0
while (curr_length < l and curr_length < 12):
curr_index += 1
curr_length += 1
cards += CARD_RANK_STR[curr_index]
if (curr_length >= 5):
playable_cards.add(cards)
l -= 1
s += 1
#pair_chain_3 -- #pair_chain_10
pair_chain_indexes = DoudizhuJudger.chain_indexes(more_than_1_indexes)
for (start_index, length) in pair_chain_indexes:
s, l = start_index, length
while(l >= 3):
cards = ''
curr_index = s - 1
curr_length = 0
while (curr_length < l and curr_length < 10):
curr_index += 1
curr_length += 1
cards += CARD_RANK_STR[curr_index] * 2
if (curr_length >= 3):
playable_cards.add(cards)
l -= 1
s += 1
#trio, trio_solo and trio_pair
for i in more_than_2_indexes:
playable_cards.add(CARD_RANK_STR[i[0]] * 3)
for j in non_zero_indexes:
if (j < i):
playable_cards.add(CARD_RANK_STR[j[0]] + CARD_RANK_STR[i[0]] * 3)
elif (j > i):
playable_cards.add(CARD_RANK_STR[i[0]] * 3 + CARD_RANK_STR[j[0]])
for j in more_than_1_indexes:
if (j < i):
playable_cards.add(CARD_RANK_STR[j[0]] * 2 + CARD_RANK_STR[i[0]] * 3)
elif (j > i):
playable_cards.add(CARD_RANK_STR[i[0]] * 3 + CARD_RANK_STR[j[0]] * 2)
#trio_solo, trio_pair, #trio -- trio_chain_2 -- trio_chain_6; trio_solo_chain_2 -- trio_solo_chain_5; trio_pair_chain_2 -- trio_pair_chain_4
trio_chain_indexes = DoudizhuJudger.chain_indexes(more_than_2_indexes)
for (start_index, length) in trio_chain_indexes:
s, l = start_index, length
while(l >= 2):
cards = ''
curr_index = s - 1
curr_length = 0
while (curr_length < l and curr_length < 6):
curr_index += 1
curr_length += 1
cards += CARD_RANK_STR[curr_index] * 3
#trio_chain_2 to trio_chain_6
if (curr_length >= 2 and curr_length <= 6):
playable_cards.add(cards)
#trio_solo_chain_2 to trio_solo_chain_5
if (curr_length >= 2 and curr_length <= 5):
for left, right in DoudizhuJudger.solo_attachments(current_hand, s, curr_length, curr_length):
pre_attached = ''
for j in left:
pre_attached += CARD_RANK_STR[j]
post_attached = ''
for j in right:
post_attached += CARD_RANK_STR[j]
playable_cards.add(pre_attached + cards + post_attached)
#trio_pair_chain2 -- trio_pair_chain_4
if (curr_length >= 2 and curr_length <= 4):
for left, right in DoudizhuJudger.pair_attachments(cards_count, s, curr_length, curr_length):
pre_attached = ''
for j in left:
pre_attached += CARD_RANK_STR[j] * 2
post_attached = ''
for j in right:
post_attached += CARD_RANK_STR[j] * 2
playable_cards.add(pre_attached + cards + post_attached)
l -= 1
s += 1
#rocket
if (cards_count[13] and cards_count[14]):
playable_cards.add(CARD_RANK_STR[13] + CARD_RANK_STR[14])
return playable_cards
def __init__(self, players, np_random):
''' Initilize the Judger class for Dou Dizhu
'''
self.playable_cards = [set() for _ in range(3)]
self._recorded_removed_playable_cards = [[] for _ in range(3)]
for player in players:
player_id = player.player_id
current_hand = cards2str(player.current_hand)
self.playable_cards[player_id] = self.playable_cards_from_hand(current_hand)
def calc_playable_cards(self, player):
''' Recalculate all legal cards the player can play according to his
current hand.
Args:
player (DoudizhuPlayer object): object of DoudizhuPlayer
init_flag (boolean): For the first time, set it True to accelerate
the preocess.
Returns:
list: list of string of playable cards
'''
removed_playable_cards = []
player_id = player.player_id
current_hand = cards2str(player.current_hand)
missed = None
for single in player.singles:
if single not in current_hand:
missed = single
break
playable_cards = self.playable_cards[player_id].copy()
if missed is not None:
position = player.singles.find(missed)
player.singles = player.singles[position+1:]
for cards in playable_cards:
if missed in cards or (not contains_cards(current_hand, cards)):
removed_playable_cards.append(cards)
self.playable_cards[player_id].remove(cards)
else:
for cards in playable_cards:
if not contains_cards(current_hand, cards):
#del self.playable_cards[player_id][cards]
removed_playable_cards.append(cards)
self.playable_cards[player_id].remove(cards)
self._recorded_removed_playable_cards[player_id].append(removed_playable_cards)
return self.playable_cards[player_id]
def restore_playable_cards(self, player_id):
''' restore playable_cards for judger for game.step_back().
Args:
player_id: The id of the player whose playable_cards need to be restored
'''
removed_playable_cards = self._recorded_removed_playable_cards[player_id].pop()
self.playable_cards[player_id].update(removed_playable_cards)
def get_playable_cards(self, player):
''' Provide all legal cards the player can play according to his
current hand.
Args:
player (DoudizhuPlayer object): object of DoudizhuPlayer
init_flag (boolean): For the first time, set it True to accelerate
the preocess.
Returns:
list: list of string of playable cards
'''
return self.playable_cards[player.player_id]
@staticmethod
def judge_game(players, player_id):
''' Judge whether the game is over
Args:
players (list): list of DoudizhuPlayer objects
player_id (int): integer of player's id
Returns:
(bool): True if the game is over
'''
player = players[player_id]
if not player.current_hand:
return True
return False
@staticmethod
def judge_payoffs(landlord_id, winner_id):
payoffs = np.array([0, 0, 0])
if winner_id == landlord_id:
payoffs[landlord_id] = 1
else:
for index, _ in enumerate(payoffs):
if index != landlord_id:
payoffs[index] = 1
return payoffs
'''
doudizhu/game.py
'''
# -*- coding: utf-8 -*-
''' Implement Doudizhu Game class
'''
import functools
from heapq import merge
import numpy as np
from doudizhu.utils import cards2str, doudizhu_sort_card, CARD_RANK_STR
from doudizhu import Player
from doudizhu import Round
from doudizhu import Judger
class DoudizhuGame:
''' Provide game APIs for env to run doudizhu and get corresponding state
information.
'''
def __init__(self, allow_step_back=False):
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
self.num_players = 3
def init_game(self):
''' Initialize players and state.
Returns:
dict: first state in one game
int: current player's id
'''
# initialize public variables
self.winner_id = None
self.history = []
# initialize players
self.players = [Player(num, self.np_random)
for num in range(self.num_players)]
# initialize round to deal cards and determine landlord
self.played_cards = [np.zeros((len(CARD_RANK_STR), ), dtype=np.int32)
for _ in range(self.num_players)]
self.round = Round(self.np_random, self.played_cards)
self.round.initiate(self.players)
# initialize judger
self.judger = Judger(self.players, self.np_random)
# get state of first player
player_id = self.round.current_player
self.state = self.get_state(player_id)
return self.state, player_id
def step(self, action):
''' Perform one draw of the game
Args:
action (str): specific action of doudizhu. Eg: '33344'
Returns:
dict: next player's state
int: next player's id
'''
if self.allow_step_back:
# TODO: don't record game.round, game.players, game.judger if allow_step_back not set
pass
# perfrom action
player = self.players[self.round.current_player]
self.round.proceed_round(player, action)
if (action != 'pass'):
self.judger.calc_playable_cards(player)
if self.judger.judge_game(self.players, self.round.current_player):
self.winner_id = self.round.current_player
next_id = (player.player_id+1) % len(self.players)
self.round.current_player = next_id
# get next state
state = self.get_state(next_id)
self.state = state
return state, next_id
def step_back(self):
''' Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
'''
if not self.round.trace:
return False
#winner_id will be always None no matter step_back from any case
self.winner_id = None
#reverse round
player_id, cards = self.round.step_back(self.players)
#reverse player
if (cards != 'pass'):
self.players[player_id].played_cards = self.round.find_last_played_cards_in_trace(player_id)
self.players[player_id].play_back()
#reverse judger.played_cards if needed
if (cards != 'pass'):
self.judger.restore_playable_cards(player_id)
self.state = self.get_state(self.round.current_player)
return True
def get_state(self, player_id):
''' Return player's state
Args:
player_id (int): player id
Returns:
(dict): The state of the player
'''
player = self.players[player_id]
others_hands = self._get_others_current_hand(player)
num_cards_left = [len(self.players[i].current_hand) for i in range(self.num_players)]
if self.is_over():
actions = []
else:
actions = list(player.available_actions(self.round.greater_player, self.judger))
state = player.get_state(self.round.public, others_hands, num_cards_left, actions)
return state
@staticmethod
def get_num_actions():
''' Return the total number of abstract acitons
Returns:
int: the total number of abstract actions of doudizhu
'''
return 27472
def get_player_id(self):
''' Return current player's id
Returns:
int: current player's id
'''
return self.round.current_player
def get_num_players(self):
''' Return the number of players in doudizhu
Returns:
int: the number of players in doudizhu
'''
return self.num_players
def is_over(self):
''' Judge whether a game is over
Returns:
Bool: True(over) / False(not over)
'''
if self.winner_id is None:
return False
return True
def _get_others_current_hand(self, player):
player_up = self.players[(player.player_id+1) % len(self.players)]
player_down = self.players[(player.player_id-1) % len(self.players)]
others_hand = merge(player_up.current_hand, player_down.current_hand, key=functools.cmp_to_key(doudizhu_sort_card))
return cards2str(others_hand)
'''
doudizhu/utils.py
'''
''' Doudizhu utils
'''
import os
import json
from collections import OrderedDict
import threading
import collections
# import rlcard
# Read required docs
ROOT_PATH = '.'
# if not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/action_space.txt')) \
# or not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/card_type.json')) \
# or not os.path.isfile(os.path.join(ROOT_PATH, '/jsondata/type_card.json')):
# import zipfile
# with zipfile.ZipFile(os.path.join(ROOT_PATH, 'jsondata.zip'),"r") as zip_ref:
# zip_ref.extractall(os.path.join(ROOT_PATH, '/'))
# Action space
action_space_path = os.path.join(ROOT_PATH, './jsondata/action_space.txt')
with open(action_space_path, 'r') as f:
ID_2_ACTION = f.readline().strip().split()
ACTION_2_ID = {}
for i, action in enumerate(ID_2_ACTION):
ACTION_2_ID[action] = i
# a map of card to its type. Also return both dict and list to accelerate
card_type_path = os.path.join(ROOT_PATH, './jsondata/card_type.json')
with open(card_type_path, 'r') as f:
data = json.load(f, object_pairs_hook=OrderedDict)
CARD_TYPE = (data, list(data), set(data))
# a map of type to its cards
type_card_path = os.path.join(ROOT_PATH, './jsondata/type_card.json')
with open(type_card_path, 'r') as f:
TYPE_CARD = json.load(f, object_pairs_hook=OrderedDict)
# rank list of solo character of cards
CARD_RANK_STR = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',
'A', '2', 'B', 'R']
CARD_RANK_STR_INDEX = {'3': 0, '4': 1, '5': 2, '6': 3, '7': 4,
'8': 5, '9': 6, 'T': 7, 'J': 8, 'Q': 9,
'K': 10, 'A': 11, '2': 12, 'B': 13, 'R': 14}
# rank list
CARD_RANK = ['3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K',
'A', '2', 'BJ', 'RJ']
INDEX = {'3': 0, '4': 1, '5': 2, '6': 3, '7': 4,
'8': 5, '9': 6, 'T': 7, 'J': 8, 'Q': 9,
'K': 10, 'A': 11, '2': 12, 'B': 13, 'R': 14}
INDEX = OrderedDict(sorted(INDEX.items(), key=lambda t: t[1]))
def doudizhu_sort_str(card_1, card_2):
''' Compare the rank of two cards of str representation
Args:
card_1 (str): str representation of solo card
card_2 (str): str representation of solo card
Returns:
int: 1(card_1 > card_2) / 0(card_1 = card2) / -1(card_1 < card_2)
'''
key_1 = CARD_RANK_STR.index(card_1)
key_2 = CARD_RANK_STR.index(card_2)
if key_1 > key_2:
return 1
if key_1 < key_2:
return -1
return 0
def doudizhu_sort_card(card_1, card_2):
''' Compare the rank of two cards of Card object
Args:
card_1 (object): object of Card
card_2 (object): object of card
'''
key = []
for card in [card_1, card_2]:
if card.rank == '':
key.append(CARD_RANK.index(card.suit))
else:
key.append(CARD_RANK.index(card.rank))
if key[0] > key[1]:
return 1
if key[0] < key[1]:
return -1
return 0
def get_landlord_score(current_hand):
''' Roughly judge the quality of the hand, and provide a score as basis to
bid landlord.
Args:
current_hand (str): string of cards. Eg: '56888TTQKKKAA222R'
Returns:
int: score
'''
score_map = {'A': 1, '2': 2, 'B': 3, 'R': 4}
score = 0
# rocket
if current_hand[-2:] == 'BR':
score += 8
current_hand = current_hand[:-2]
length = len(current_hand)
i = 0
while i < length:
# bomb
if i <= (length - 4) and current_hand[i] == current_hand[i+3]:
score += 6
i += 4
continue
# 2, Black Joker, Red Joker
if current_hand[i] in score_map:
score += score_map[current_hand[i]]
i += 1
return score
def cards2str_with_suit(cards):
''' Get the corresponding string representation of cards with suit
Args:
cards (list): list of Card objects
Returns:
string: string representation of cards
'''
return ' '.join([card.suit+card.rank for card in cards])
def cards2str(cards):
''' Get the corresponding string representation of cards
Args:
cards (list): list of Card objects
Returns:
string: string representation of cards
'''
response = ''
for card in cards:
if card.rank == '':
response += card.suit[0]
else:
response += card.rank
return response
class LocalObjs(threading.local):
def __init__(self):
self.cached_candidate_cards = None
_local_objs = LocalObjs()
def contains_cards(candidate, target):
''' Check if cards of candidate contains cards of target.
Args:
candidate (string): A string representing the cards of candidate
target (string): A string representing the number of cards of target
Returns:
boolean
'''
# In normal cases, most continuous calls of this function
# will test different targets against the same candidate.
# So the cached counts of each card in candidate can speed up
# the comparison for following tests if candidate keeps the same.
if not _local_objs.cached_candidate_cards or _local_objs.cached_candidate_cards != candidate:
_local_objs.cached_candidate_cards = candidate
cards_dict = collections.defaultdict(int)
for card in candidate:
cards_dict[card] += 1
_local_objs.cached_candidate_cards_dict = cards_dict
cards_dict = _local_objs.cached_candidate_cards_dict
if (target == ''):
return True
curr_card = target[0]
curr_count = 1
for card in target[1:]:
if (card != curr_card):
if (cards_dict[curr_card] < curr_count):
return False
curr_card = card
curr_count = 1
else:
curr_count += 1
if (cards_dict[curr_card] < curr_count):
return False
return True
def encode_cards(plane, cards):
''' Encode cards and represerve it into plane.
Args:
cards (list or str): list or str of cards, every entry is a
character of solo representation of card
'''
if not cards:
return None
layer = 1
if len(cards) == 1:
rank = CARD_RANK_STR.index(cards[0])
plane[layer][rank] = 1
plane[0][rank] = 0
else:
for index, card in enumerate(cards):
if index == 0:
continue
if card == cards[index-1]:
layer += 1
else:
rank = CARD_RANK_STR.index(cards[index-1])
plane[layer][rank] = 1
layer = 1
plane[0][rank] = 0
rank = CARD_RANK_STR.index(cards[-1])
plane[layer][rank] = 1
plane[0][rank] = 0
def get_gt_cards(player, greater_player):
''' Provide player's cards which are greater than the ones played by
previous player in one round
Args:
player (DoudizhuPlayer object): the player waiting to play cards
greater_player (DoudizhuPlayer object): the player who played current biggest cards.
Returns:
list: list of string of greater cards
Note:
1. return value contains 'pass'
'''
# add 'pass' to legal actions
gt_cards = ['pass']
current_hand = cards2str(player.current_hand)
target_cards = greater_player.played_cards
target_types = CARD_TYPE[0][target_cards]
type_dict = {}
for card_type, weight in target_types:
if card_type not in type_dict:
type_dict[card_type] = weight
if 'rocket' in type_dict:
return gt_cards
type_dict['rocket'] = -1
if 'bomb' not in type_dict:
type_dict['bomb'] = -1
for card_type, weight in type_dict.items():
candidate = TYPE_CARD[card_type]
for can_weight, cards_list in candidate.items():
if int(can_weight) > int(weight):
for cards in cards_list:
# TODO: improve efficiency
if cards not in gt_cards and contains_cards(current_hand, cards):
# if self.contains_cards(current_hand, cards):
gt_cards.append(cards)
return gt_cards
'''
doudizhu/__init__.py
'''
from doudizhu.base import Card as Card
from doudizhu.dealer import DoudizhuDealer as Dealer
from doudizhu.judger import DoudizhuJudger as Judger
from doudizhu.player import DoudizhuPlayer as Player
from doudizhu.round import DoudizhuRound as Round
from doudizhu.game import DoudizhuGame as Game
'''
doudizhu/round.py
'''
# -*- coding: utf-8 -*-
''' Implement Doudizhu Round class
'''
import functools
import numpy as np
from doudizhu import Dealer
from doudizhu.utils import cards2str, doudizhu_sort_card
from doudizhu.utils import CARD_RANK_STR, CARD_RANK_STR_INDEX
class DoudizhuRound:
''' Round can call other Classes' functions to keep the game running
'''
def __init__(self, np_random, played_cards):
self.np_random = np_random
self.played_cards = played_cards
self.trace = []
self.greater_player = None
self.dealer = Dealer(self.np_random)
self.deck_str = cards2str(self.dealer.deck)
def initiate(self, players):
''' Call dealer to deal cards and bid landlord.
Args:
players (list): list of DoudizhuPlayer objects
'''
landlord_id = self.dealer.determine_role(players)
seen_cards = self.dealer.deck[-3:]
seen_cards.sort(key=functools.cmp_to_key(doudizhu_sort_card))
self.seen_cards = cards2str(seen_cards)
self.landlord_id = landlord_id
self.current_player = landlord_id
self.public = {'deck': self.deck_str, 'seen_cards': self.seen_cards,
'landlord': self.landlord_id, 'trace': self.trace,
'played_cards': ['' for _ in range(len(players))]}
@staticmethod
def cards_ndarray_to_str(ndarray_cards):
result = []
for cards in ndarray_cards:
_result = []
for i, _ in enumerate(cards):
if cards[i] != 0:
_result.extend([CARD_RANK_STR[i]] * cards[i])
result.append(''.join(_result))
return result
def update_public(self, action):
''' Update public trace and played cards
Args:
action(str): string of legal specific action
'''
self.trace.append((self.current_player, action))
if action != 'pass':
for c in action:
self.played_cards[self.current_player][CARD_RANK_STR_INDEX[c]] += 1
if self.current_player == 0 and c in self.seen_cards:
self.seen_cards = self.seen_cards.replace(c, '')
self.public['seen_cards'] = self.seen_cards
self.public['played_cards'] = self.cards_ndarray_to_str(self.played_cards)
def proceed_round(self, player, action):
''' Call other Classes's functions to keep one round running
Args:
player (object): object of DoudizhuPlayer
action (str): string of legal specific action
Returns:
object of DoudizhuPlayer: player who played current biggest cards.
'''
self.update_public(action)
self.greater_player = player.play(action, self.greater_player)
return self.greater_player
def step_back(self, players):
''' Reverse the last action
Args:
players (list): list of DoudizhuPlayer objects
Returns:
The last player id and the cards played
'''
player_id, cards = self.trace.pop()
self.current_player = player_id
if (cards != 'pass'):
for card in cards:
# self.played_cards.remove(card)
self.played_cards[player_id][CARD_RANK_STR_INDEX[card]] -= 1
self.public['played_cards'] = self.cards_ndarray_to_str(self.played_cards)
greater_player_id = self.find_last_greater_player_id_in_trace()
if (greater_player_id is not None):
self.greater_player = players[greater_player_id]
else:
self.greater_player = None
return player_id, cards
def find_last_greater_player_id_in_trace(self):
''' Find the last greater_player's id in trace
Returns:
The last greater_player's id in trace
'''
for i in range(len(self.trace) - 1, -1, -1):
_id, action = self.trace[i]
if (action != 'pass'):
return _id
return None
def find_last_played_cards_in_trace(self, player_id):
''' Find the player_id's last played_cards in trace
Returns:
The player_id's last played_cards in trace
'''
for i in range(len(self.trace) - 1, -1, -1):
_id, action = self.trace[i]
if (_id == player_id and action != 'pass'):
return action
return None
| 8 | 1,178 | Python |
limitholdem | ./ProjectTest/Python/limitholdem.py | '''
limitholdem/base.py
'''
''' Game-related base classes
'''
class Card:
'''
Card stores the suit and rank of a single card
Note:
The suit variable in a standard card game should be one of [S, H, D, C, BJ, RJ] meaning [Spades, Hearts, Diamonds, Clubs, Black Joker, Red Joker]
Similarly the rank variable should be one of [A, 2, 3, 4, 5, 6, 7, 8, 9, T, J, Q, K]
'''
suit = None
rank = None
valid_suit = ['S', 'H', 'D', 'C', 'BJ', 'RJ']
valid_rank = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
def __init__(self, suit, rank):
''' Initialize the suit and rank of a card
Args:
suit: string, suit of the card, should be one of valid_suit
rank: string, rank of the card, should be one of valid_rank
'''
self.suit = suit
self.rank = rank
def __eq__(self, other):
if isinstance(other, Card):
return self.rank == other.rank and self.suit == other.suit
else:
# don't attempt to compare against unrelated types
return NotImplemented
def __hash__(self):
suit_index = Card.valid_suit.index(self.suit)
rank_index = Card.valid_rank.index(self.rank)
return rank_index + 100 * suit_index
def __str__(self):
''' Get string representation of a card.
Returns:
string: the combination of rank and suit of a card. Eg: AS, 5H, JD, 3C, ...
'''
return self.rank + self.suit
def get_index(self):
''' Get index of a card.
Returns:
string: the combination of suit and rank of a card. Eg: 1S, 2H, AD, BJ, RJ...
'''
return self.suit+self.rank
'''
limitholdem/player.py
'''
from enum import Enum
class PlayerStatus(Enum):
ALIVE = 0
FOLDED = 1
ALLIN = 2
class LimitHoldemPlayer:
def __init__(self, player_id, np_random):
"""
Initialize a player.
Args:
player_id (int): The id of the player
"""
self.np_random = np_random
self.player_id = player_id
self.hand = []
self.status = PlayerStatus.ALIVE
# The chips that this player has put in until now
self.in_chips = 0
def get_state(self, public_cards, all_chips, legal_actions):
"""
Encode the state for the player
Args:
public_cards (list): A list of public cards that seen by all the players
all_chips (int): The chips that all players have put in
Returns:
(dict): The state of the player
"""
return {
'hand': [c.get_index() for c in self.hand],
'public_cards': [c.get_index() for c in public_cards],
'all_chips': all_chips,
'my_chips': self.in_chips,
'legal_actions': legal_actions
}
def get_player_id(self):
return self.player_id
'''
limitholdem/dealer.py
'''
from limitholdem.utils import init_standard_deck
class LimitHoldemDealer:
def __init__(self, np_random):
self.np_random = np_random
self.deck = init_standard_deck()
self.shuffle()
self.pot = 0
def shuffle(self):
self.np_random.shuffle(self.deck)
def deal_card(self):
"""
Deal one card from the deck
Returns:
(Card): The drawn card from the deck
"""
return self.deck.pop()
'''
limitholdem/judger.py
'''
from limitholdem.utils import compare_hands
import numpy as np
class LimitHoldemJudger:
"""The Judger class for limit texas holdem"""
def __init__(self, np_random):
self.np_random = np_random
def judge_game(self, players, hands):
"""
Judge the winner of the game.
Args:
players (list): The list of players who play the game
hands (list): The list of hands that from the players
Returns:
(list): Each entry of the list corresponds to one entry of the
"""
# Convert the hands into card indexes
hands = [[card.get_index() for card in hand] if hand is not None else None for hand in hands]
in_chips = [p.in_chips for p in players]
remaining = sum(in_chips)
payoffs = [0] * len(hands)
while remaining > 0:
winners = compare_hands(hands)
each_win = self.split_pots_among_players(in_chips, winners)
for i in range(len(players)):
if winners[i]:
remaining -= each_win[i]
payoffs[i] += each_win[i] - in_chips[i]
hands[i] = None
in_chips[i] = 0
elif in_chips[i] > 0:
payoffs[i] += each_win[i] - in_chips[i]
in_chips[i] = each_win[i]
assert sum(payoffs) == 0
return payoffs
def split_pot_among_players(self, in_chips, winners):
"""
Splits the next (side) pot among players.
Function is called in loop by distribute_pots_among_players until all chips are allocated.
Args:
in_chips (list): List with number of chips bet not yet distributed for each player
winners (list): List with 1 if the player is among winners else 0
Returns:
(list): Of how much chips each player get after this pot has been split and list of chips left to distribute
"""
nb_winners_in_pot = sum((winners[i] and in_chips[i] > 0) for i in range(len(in_chips)))
nb_players_in_pot = sum(in_chips[i] > 0 for i in range(len(in_chips)))
if nb_winners_in_pot == 0 or nb_winners_in_pot == nb_players_in_pot:
# no winner or all winners for this pot
allocated = list(in_chips) # we give back their chips to each players in this pot
in_chips_after = len(in_chips) * [0] # no more chips to distribute
else:
amount_in_pot_by_player = min(v for v in in_chips if v > 0)
how_much_one_win, remaining = divmod(amount_in_pot_by_player * nb_players_in_pot, nb_winners_in_pot)
'''
In the event of a split pot that cannot be divided equally for every winner, the winner who is sitting
closest to the left of the dealer receives the remaining differential in chips cf
https://www.betclic.fr/poker/house-rules--play-safely--betclic-poker-cpok_rules to simplify and as this
case is very rare, we will give the remaining differential in chips to a random winner
'''
allocated = len(in_chips) * [0]
in_chips_after = list(in_chips)
for i in range(len(in_chips)): # iterate on all players
if in_chips[i] == 0: # player not in pot
continue
if winners[i]:
allocated[i] += how_much_one_win
in_chips_after[i] -= amount_in_pot_by_player
if remaining > 0:
random_winning_player = self.np_random.choice(
[i for i in range(len(winners)) if winners[i] and in_chips[i] > 0])
allocated[random_winning_player] += remaining
assert sum(in_chips[i] - in_chips_after[i] for i in range(len(in_chips))) == sum(allocated)
return allocated, in_chips_after
def split_pots_among_players(self, in_chips_initial, winners):
"""
Splits main pot and side pots among players (to handle special case of all-in players).
Args:
in_chips_initial (list): List with number of chips bet for each player
winners (list): List with 1 if the player is among winners else 0
Returns:
(list): List of how much chips each player get back after all pots have been split
"""
in_chips = list(in_chips_initial)
assert len(in_chips) == len(winners)
assert all(v == 0 or v == 1 for v in winners)
assert sum(winners) >= 1 # there must be at least one winner
allocated = np.zeros(len(in_chips), dtype=int)
while any(v > 0 for v in in_chips): # while there are still chips to allocate
allocated_current_pot, in_chips = self.split_pot_among_players(in_chips, winners)
allocated += allocated_current_pot # element-wise addition
assert all(chips >= 0 for chips in allocated) # check that all players got a non negative amount of chips
assert sum(in_chips_initial) == sum(allocated) # check that all chips bet have been allocated
return list(allocated)
'''
limitholdem/game.py
'''
from copy import deepcopy, copy
import numpy as np
from limitholdem import Dealer
from limitholdem import Player, PlayerStatus
from limitholdem import Judger
from limitholdem import Round
class LimitHoldemGame:
def __init__(self, allow_step_back=False, num_players=2):
"""Initialize the class limit holdem game"""
self.allow_step_back = allow_step_back
self.np_random = np.random.RandomState()
# Some configurations of the game
# These arguments can be specified for creating new games
# Small blind and big blind
self.small_blind = 1
self.big_blind = 2 * self.small_blind
# Raise amount and allowed times
self.raise_amount = self.big_blind
self.allowed_raise_num = 4
self.num_players = num_players
# Save betting history
self.history_raise_nums = [0 for _ in range(4)]
self.dealer = None
self.players = None
self.judger = None
self.public_cards = None
self.game_pointer = None
self.round = None
self.round_counter = None
self.history = None
self.history_raises_nums = None
def configure(self, game_config):
"""Specify some game specific parameters, such as number of players"""
self.num_players = game_config['game_num_players']
def init_game(self):
"""
Initialize the game of limit texas holdem
This version supports two-player limit texas holdem
Returns:
(tuple): Tuple containing:
(dict): The first state of the game
(int): Current player's id
"""
# Initialize a dealer that can deal cards
self.dealer = Dealer(self.np_random)
# Initialize two players to play the game
self.players = [Player(i, self.np_random) for i in range(self.num_players)]
# Initialize a judger class which will decide who wins in the end
self.judger = Judger(self.np_random)
# Deal cards to each player to prepare for the first round
for i in range(2 * self.num_players):
self.players[i % self.num_players].hand.append(self.dealer.deal_card())
# Initialize public cards
self.public_cards = []
# Randomly choose a small blind and a big blind
s = self.np_random.randint(0, self.num_players)
b = (s + 1) % self.num_players
self.players[b].in_chips = self.big_blind
self.players[s].in_chips = self.small_blind
# The player next to the big blind plays the first
self.game_pointer = (b + 1) % self.num_players
# Initialize a bidding round, in the first round, the big blind and the small blind needs to
# be passed to the round for processing.
self.round = Round(raise_amount=self.raise_amount,
allowed_raise_num=self.allowed_raise_num,
num_players=self.num_players,
np_random=self.np_random)
self.round.start_new_round(game_pointer=self.game_pointer, raised=[p.in_chips for p in self.players])
# Count the round. There are 4 rounds in each game.
self.round_counter = 0
# Save the history for stepping back to the last state.
self.history = []
state = self.get_state(self.game_pointer)
# Save betting history
self.history_raise_nums = [0 for _ in range(4)]
return state, self.game_pointer
def step(self, action):
"""
Get the next state
Args:
action (str): a specific action. (call, raise, fold, or check)
Returns:
(tuple): Tuple containing:
(dict): next player's state
(int): next player id
"""
if self.allow_step_back:
# First snapshot the current state
r = deepcopy(self.round)
b = self.game_pointer
r_c = self.round_counter
d = deepcopy(self.dealer)
p = deepcopy(self.public_cards)
ps = deepcopy(self.players)
rn = copy(self.history_raise_nums)
self.history.append((r, b, r_c, d, p, ps, rn))
# Then we proceed to the next round
self.game_pointer = self.round.proceed_round(self.players, action)
# Save the current raise num to history
self.history_raise_nums[self.round_counter] = self.round.have_raised
# If a round is over, we deal more public cards
if self.round.is_over():
# For the first round, we deal 3 cards
if self.round_counter == 0:
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
self.public_cards.append(self.dealer.deal_card())
# For the following rounds, we deal only 1 card
elif self.round_counter <= 2:
self.public_cards.append(self.dealer.deal_card())
# Double the raise amount for the last two rounds
if self.round_counter == 1:
self.round.raise_amount = 2 * self.raise_amount
self.round_counter += 1
self.round.start_new_round(self.game_pointer)
state = self.get_state(self.game_pointer)
return state, self.game_pointer
def step_back(self):
"""
Return to the previous state of the game
Returns:
(bool): True if the game steps back successfully
"""
if len(self.history) > 0:
self.round, self.game_pointer, self.round_counter, self.dealer, self.public_cards, \
self.players, self.history_raises_nums = self.history.pop()
return True
return False
def get_num_players(self):
"""
Return the number of players in limit texas holdem
Returns:
(int): The number of players in the game
"""
return self.num_players
@staticmethod
def get_num_actions():
"""
Return the number of applicable actions
Returns:
(int): The number of actions. There are 4 actions (call, raise, check and fold)
"""
return 4
def get_player_id(self):
"""
Return the current player's id
Returns:
(int): current player's id
"""
return self.game_pointer
def get_state(self, player):
"""
Return player's state
Args:
player (int): player id
Returns:
(dict): The state of the player
"""
chips = [self.players[i].in_chips for i in range(self.num_players)]
legal_actions = self.get_legal_actions()
state = self.players[player].get_state(self.public_cards, chips, legal_actions)
state['raise_nums'] = self.history_raise_nums
return state
def is_over(self):
"""
Check if the game is over
Returns:
(boolean): True if the game is over
"""
alive_players = [1 if p.status in (PlayerStatus.ALIVE, PlayerStatus.ALLIN) else 0 for p in self.players]
# If only one player is alive, the game is over.
if sum(alive_players) == 1:
return True
# If all rounds are finished
if self.round_counter >= 4:
return True
return False
def get_payoffs(self):
"""
Return the payoffs of the game
Returns:
(list): Each entry corresponds to the payoff of one player
"""
hands = [p.hand + self.public_cards if p.status == PlayerStatus.ALIVE else None for p in self.players]
chips_payoffs = self.judger.judge_game(self.players, hands)
payoffs = np.array(chips_payoffs) / self.big_blind
return payoffs
def get_legal_actions(self):
"""
Return the legal actions for current player
Returns:
(list): A list of legal actions
"""
return self.round.get_legal_actions()
'''
limitholdem/utils.py
'''
import numpy as np
from limitholdem import Card
def init_standard_deck():
''' Initialize a standard deck of 52 cards
Returns:
(list): A list of Card object
'''
suit_list = ['S', 'H', 'D', 'C']
rank_list = ['A', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K']
res = [Card(suit, rank) for suit in suit_list for rank in rank_list]
return res
class Hand:
def __init__(self, all_cards):
self.all_cards = all_cards # two hand cards + five public cards
self.category = 0
#type of a players' best five cards, greater combination has higher number eg: 0:"Not_Yet_Evaluated" 1: "High_Card" , 9:"Straight_Flush"
self.best_five = []
#the largest combination of five cards in all the seven cards
self.flush_cards = []
#cards with same suit
self.cards_by_rank = []
#cards after sort
self.product = 1
#cards’ type indicator
self.RANK_TO_STRING = {2: "2", 3: "3", 4: "4", 5: "5", 6: "6",
7: "7", 8: "8", 9: "9", 10: "T", 11: "J", 12: "Q", 13: "K", 14: "A"}
self.STRING_TO_RANK = {v:k for k, v in self.RANK_TO_STRING.items()}
self.RANK_LOOKUP = "23456789TJQKA"
self.SUIT_LOOKUP = "SCDH"
def get_hand_five_cards(self):
'''
Get the best five cards of a player
Returns:
(list): the best five cards among the seven cards of a player
'''
return self.best_five
def _sort_cards(self):
'''
Sort all the seven cards ascendingly according to RANK_LOOKUP
'''
self.all_cards = sorted(
self.all_cards, key=lambda card: self.RANK_LOOKUP.index(card[1]))
def evaluateHand(self):
"""
Evaluate all the seven cards, get the best combination catagory
And pick the best five cards (for comparing in case 2 hands have the same Category) .
"""
if len(self.all_cards) != 7:
raise Exception(
"There are not enough 7 cards in this hand, quit evaluation now ! ")
self._sort_cards()
self.cards_by_rank, self.product = self._getcards_by_rank(
self.all_cards)
if self._has_straight_flush():
self.category = 9
#Straight Flush
elif self._has_four():
self.category = 8
#Four of a Kind
self.best_five = self._get_Four_of_a_kind_cards()
elif self._has_fullhouse():
self.category = 7
#Full house
self.best_five = self._get_Fullhouse_cards()
elif self._has_flush():
self.category = 6
#Flush
i = len(self.flush_cards)
self.best_five = [card for card in self.flush_cards[i-5:i]]
elif self._has_straight(self.all_cards):
self.category = 5
#Straight
elif self._has_three():
self.category = 4
#Three of a Kind
self.best_five = self._get_Three_of_a_kind_cards()
elif self._has_two_pairs():
self.category = 3
#Two Pairs
self.best_five = self._get_Two_Pair_cards()
elif self._has_pair():
self.category = 2
#One Pair
self.best_five = self._get_One_Pair_cards()
elif self._has_high_card():
self.category = 1
#High Card
self.best_five = self._get_High_cards()
def _has_straight_flush(self):
'''
Check the existence of straight_flush cards
Returns:
True: exist
False: not exist
'''
self.flush_cards = self._getflush_cards()
if len(self.flush_cards) > 0:
straightflush_cards = self._get_straightflush_cards()
if len(straightflush_cards) > 0:
self.best_five = straightflush_cards
return True
return False
def _get_straightflush_cards(self):
'''
Pick straight_flush cards
Returns:
(list): the straightflush cards
'''
straightflush_cards = self._get_straight_cards(self.flush_cards)
return straightflush_cards
def _getflush_cards(self):
'''
Pick flush cards
Returns:
(list): the flush cards
'''
card_string = ''.join(self.all_cards)
for suit in self.SUIT_LOOKUP:
suit_count = card_string.count(suit)
if suit_count >= 5:
flush_cards = [
card for card in self.all_cards if card[0] == suit]
return flush_cards
return []
def _has_flush(self):
'''
Check the existence of flush cards
Returns:
True: exist
False: not exist
'''
if len(self.flush_cards) > 0:
return True
else:
return False
def _has_straight(self, all_cards):
'''
Check the existence of straight cards
Returns:
True: exist
False: not exist
'''
diff_rank_cards = self._get_different_rank_list(all_cards)
self.best_five = self._get_straight_cards(diff_rank_cards)
if len(self.best_five) != 0:
return True
else:
return False
@classmethod
def _get_different_rank_list(self, all_cards):
'''
Get cards with different ranks, that is to say, remove duplicate-ranking cards, for picking straight cards' use
Args:
(list): two hand cards + five public cards
Returns:
(list): a list of cards with duplicate-ranking cards removed
'''
different_rank_list = []
different_rank_list.append(all_cards[0])
for card in all_cards:
if(card[1] != different_rank_list[-1][1]):
different_rank_list.append(card)
return different_rank_list
def _get_straight_cards(self, Cards):
'''
Pick straight cards
Returns:
(list): the straight cards
'''
ranks = [self.STRING_TO_RANK[c[1]] for c in Cards]
highest_card = Cards[-1]
if highest_card[1] == 'A':
Cards.insert(0, highest_card)
ranks.insert(0, 1)
for i_last in range(len(ranks) - 1, 3, -1):
if ranks[i_last-4] + 4 == ranks[i_last]: # works because ranks are unique and sorted in ascending order
return Cards[i_last-4:i_last+1]
return []
def _getcards_by_rank(self, all_cards):
'''
Get cards by rank
Args:
(list): # two hand cards + five public cards
Return:
card_group(list): cards after sort
product(int):cards‘ type indicator
'''
card_group = []
card_group_element = []
product = 1
prime_lookup = {0: 1, 1: 1, 2: 2, 3: 3, 4: 5}
count = 0
current_rank = 0
for card in all_cards:
rank = self.RANK_LOOKUP.index(card[1])
if rank == current_rank:
count += 1
card_group_element.append(card)
elif rank != current_rank:
product *= prime_lookup[count]
# Explanation :
# if count == 2, then product *= 2
# if count == 3, then product *= 3
# if count == 4, then product *= 5
# if there is a Quad, then product = 5 ( 4, 1, 1, 1) or product = 10 ( 4, 2, 1) or product= 15 (4,3)
# if there is a Fullhouse, then product = 12 ( 3, 2, 2) or product = 9 (3, 3, 1) or product = 6 ( 3, 2, 1, 1)
# if there is a Trip, then product = 3 ( 3, 1, 1, 1, 1)
# if there is two Pair, then product = 4 ( 2, 1, 2, 1, 1) or product = 8 ( 2, 2, 2, 1)
# if there is one Pair, then product = 2 (2, 1, 1, 1, 1, 1)
# if there is HighCard, then product = 1 (1, 1, 1, 1, 1, 1, 1)
card_group_element.insert(0, count)
card_group.append(card_group_element)
# reset counting
count = 1
card_group_element = []
card_group_element.append(card)
current_rank = rank
# the For Loop misses operation for the last card
# These 3 lines below to compensate that
product *= prime_lookup[count]
# insert the number of same rank card to the beginning of the
card_group_element.insert(0, count)
# after the loop, there is still one last card to add
card_group.append(card_group_element)
return card_group, product
def _has_four(self):
'''
Check the existence of four cards
Returns:
True: exist
False: not exist
'''
if self.product == 5 or self.product == 10 or self.product == 15:
return True
else:
return False
def _has_fullhouse(self):
'''
Check the existence of fullhouse cards
Returns:
True: exist
False: not exist
'''
if self.product == 6 or self.product == 9 or self.product == 12:
return True
else:
return False
def _has_three(self):
'''
Check the existence of three cards
Returns:
True: exist
False: not exist
'''
if self.product == 3:
return True
else:
return False
def _has_two_pairs(self):
'''
Check the existence of 2 pair cards
Returns:
True: exist
False: not exist
'''
if self.product == 4 or self.product == 8:
return True
else:
return False
def _has_pair(self):
'''
Check the existence of 1 pair cards
Returns:
True: exist
False: not exist
'''
if self.product == 2:
return True
else:
return False
def _has_high_card(self):
'''
Check the existence of high cards
Returns:
True: exist
False: not exist
'''
if self.product == 1:
return True
else:
return False
def _get_Four_of_a_kind_cards(self):
'''
Get the four of a kind cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Four_of_a_Kind = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 4:
Four_of_a_Kind = cards_by_rank.pop(i)
break
# The Last cards_by_rank[The Second element]
kicker = cards_by_rank[-1][1]
Four_of_a_Kind[0] = kicker
return Four_of_a_Kind
def _get_Fullhouse_cards(self):
'''
Get the fullhouse cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Fullhouse = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 3:
Trips = cards_by_rank.pop(i)[1:4]
break
for i in reversed(range(cards_len - 1)):
if cards_by_rank[i][0] >= 2:
TwoPair = cards_by_rank.pop(i)[1:3]
break
Fullhouse = TwoPair + Trips
return Fullhouse
def _get_Three_of_a_kind_cards(self):
'''
Get the three of a kind cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Trip_cards = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 3:
Trip_cards += cards_by_rank.pop(i)[1:4]
break
Trip_cards += cards_by_rank.pop(-1)[1:2]
Trip_cards += cards_by_rank.pop(-1)[1:2]
Trip_cards.reverse()
return Trip_cards
def _get_Two_Pair_cards(self):
'''
Get the two pair cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
Two_Pair_cards = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 2 and len(Two_Pair_cards) < 3:
Two_Pair_cards += cards_by_rank.pop(i)[1:3]
Two_Pair_cards += cards_by_rank.pop(-1)[1:2]
Two_Pair_cards.reverse()
return Two_Pair_cards
def _get_One_Pair_cards(self):
'''
Get the one pair cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
One_Pair_cards = []
cards_by_rank = self.cards_by_rank
cards_len = len(cards_by_rank)
for i in reversed(range(cards_len)):
if cards_by_rank[i][0] == 2:
One_Pair_cards += cards_by_rank.pop(i)[1:3]
break
One_Pair_cards += cards_by_rank.pop(-1)[1:2]
One_Pair_cards += cards_by_rank.pop(-1)[1:2]
One_Pair_cards += cards_by_rank.pop(-1)[1:2]
One_Pair_cards.reverse()
return One_Pair_cards
def _get_High_cards(self):
'''
Get the high cards among a player's cards
Returns:
(list): best five hand cards after sort
'''
High_cards = self.all_cards[2:7]
return High_cards
def compare_ranks(position, hands, winner):
'''
Compare cards in same position of plays' five handcards
Args:
position(int): the position of a card in a sorted handcard
hands(list): cards of those players.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
winner: array of same length than hands with 1 if the hand is among winners and 0 among losers
Returns:
new updated winner array
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
assert len(hands) == len(winner)
RANKS = '23456789TJQKA'
cards_figure_all_players = [None]*len(hands) #cards without suit
for i, hand in enumerate(hands):
if winner[i]:
cards = hands[i].get_hand_five_cards()
if len(cards[0]) != 1:# remove suit
for p in range(5):
cards[p] = cards[p][1:]
cards_figure_all_players[i] = cards
rival_ranks = [] # ranks of rival_figures
for i, cards_figure in enumerate(cards_figure_all_players):
if winner[i]:
rank = cards_figure_all_players[i][position]
rival_ranks.append(RANKS.index(rank))
else:
rival_ranks.append(-1) # player has already lost
new_winner = list(winner)
for i, rival_rank in enumerate(rival_ranks):
if rival_rank != max(rival_ranks):
new_winner[i] = 0
return new_winner
def determine_winner(key_index, hands, all_players, potential_winner_index):
'''
Find out who wins in the situation of having players with same highest hand_catagory
Args:
key_index(int): the position of a card in a sorted handcard
hands(list): cards of those players with same highest hand_catagory.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
all_players(list): all the players in this round, 0 for losing and 1 for winning or draw
potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
winner = [1]*len(hands)
i_index = 0
while i_index < len(key_index) and sum(winner) > 1:
index_break_tie = key_index[i_index]
winner = compare_ranks(index_break_tie, hands, winner)
i_index += 1
for i in range(len(potential_winner_index)):
if winner[i]:
all_players[potential_winner_index[i]] = 1
return all_players
def determine_winner_straight(hands, all_players, potential_winner_index):
'''
Find out who wins in the situation of having players all having a straight or straight flush
Args:
key_index(int): the position of a card in a sorted handcard
hands(list): cards of those players which all have a straight or straight flush
all_players(list): all the players in this round, 0 for losing and 1 for winning or draw
potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
highest_ranks = []
for hand in hands:
highest_rank = hand.STRING_TO_RANK[hand.best_five[-1][1]] # cards are sorted in ascending order
highest_ranks.append(highest_rank)
max_highest_rank = max(highest_ranks)
for i_player in range(len(highest_ranks)):
if highest_ranks[i_player] == max_highest_rank:
all_players[potential_winner_index[i_player]] = 1
return all_players
def determine_winner_four_of_a_kind(hands, all_players, potential_winner_index):
'''
Find out who wins in the situation of having players which all have a four of a kind
Args:
key_index(int): the position of a card in a sorted handcard
hands(list): cards of those players with a four of a kind
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
all_players(list): all the players in this round, 0 for losing and 1 for winning or draw
potential_winner_index(list): the positions of those players with same highest hand_catagory in all_players
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
'''
ranks = []
for hand in hands:
rank_1 = hand.STRING_TO_RANK[hand.best_five[-1][1]] # rank of the four of a kind
rank_2 = hand.STRING_TO_RANK[hand.best_five[0][1]] # rank of the kicker
ranks.append((rank_1, rank_2))
max_rank = max(ranks)
for i, rank in enumerate(ranks):
if rank == max_rank:
all_players[potential_winner_index[i]] = 1
return all_players
def compare_hands(hands):
'''
Compare all palyer's all seven cards
Args:
hands(list): cards of those players with same highest hand_catagory.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
if hands[0] == None:
return [0, 1]
elif hands[1] == None:
return [1, 0]
'''
hand_category = [] #such as high_card, straight_flush, etc
all_players = [0]*len(hands) #all the players in this round, 0 for losing and 1 for winning or draw
if None in hands:
fold_players = [i for i, j in enumerate(hands) if j is None]
if len(fold_players) == len(all_players) - 1:
for _ in enumerate(hands):
if _[0] in fold_players:
all_players[_[0]] = 0
else:
all_players[_[0]] = 1
return all_players
else:
for _ in enumerate(hands):
if hands[_[0]] is not None:
hand = Hand(hands[_[0]])
hand.evaluateHand()
hand_category.append(hand.category)
elif hands[_[0]] is None:
hand_category.append(0)
else:
for i in enumerate(hands):
hand = Hand(hands[i[0]])
hand.evaluateHand()
hand_category.append(hand.category)
potential_winner_index = [i for i, j in enumerate(hand_category) if j == max(hand_category)]# potential winner are those with same max card_catagory
return final_compare(hands, potential_winner_index, all_players)
def final_compare(hands, potential_winner_index, all_players):
'''
Find out the winners from those who didn't fold
Args:
hands(list): cards of those players with same highest hand_catagory.
e.g. hands = [['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CJ', 'SJ', 'H9', 'B9', 'C2', 'C8', 'C7'], ['CT', 'ST', 'H9', 'B9', 'C2', 'C8', 'C7']]
potential_winner_index(list): index of those with same max card_catagory in all_players
all_players(list): a list of all the player's win/lose situation, 0 for lose and 1 for win
Returns:
[0, 1, 0]: player1 wins
[1, 0, 0]: player0 wins
[1, 1, 1]: draw
[1, 1, 0]: player1 and player0 draws
if hands[0] == None:
return [0, 1]
elif hands[1] == None:
return [1, 0]
'''
if len(potential_winner_index) == 1:
all_players[potential_winner_index[0]] = 1
return all_players
elif len(potential_winner_index) > 1:
# compare when having equal max categories
equal_hands = []
for _ in potential_winner_index:
hand = Hand(hands[_])
hand.evaluateHand()
equal_hands.append(hand)
hand = equal_hands[0]
if hand.category == 8:
return determine_winner_four_of_a_kind(equal_hands, all_players, potential_winner_index)
if hand.category == 7:
return determine_winner([2, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 4:
return determine_winner([2, 1, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 3:
return determine_winner([4, 2, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 2:
return determine_winner([4, 2, 1, 0], equal_hands, all_players, potential_winner_index)
if hand.category == 1 or hand.category == 6:
return determine_winner([4, 3, 2, 1, 0], equal_hands, all_players, potential_winner_index)
if hand.category in [5, 9]:
return determine_winner_straight(equal_hands, all_players, potential_winner_index)
'''
limitholdem/__init__.py
'''
from limitholdem.base import Card as Card
from limitholdem.dealer import LimitHoldemDealer as Dealer
from limitholdem.judger import LimitHoldemJudger as Judger
from limitholdem.player import LimitHoldemPlayer as Player
from limitholdem.player import PlayerStatus
from limitholdem.round import LimitHoldemRound as Round
from limitholdem.game import LimitHoldemGame as Game
'''
limitholdem/round.py
'''
# -*- coding: utf-8 -*-
"""Limit texas holdem round class implementation"""
class LimitHoldemRound:
"""Round can call other Classes' functions to keep the game running"""
def __init__(self, raise_amount, allowed_raise_num, num_players, np_random):
"""
Initialize the round class
Args:
raise_amount (int): the raise amount for each raise
allowed_raise_num (int): The number of allowed raise num
num_players (int): The number of players
"""
self.np_random = np_random
self.game_pointer = None
self.raise_amount = raise_amount
self.allowed_raise_num = allowed_raise_num
self.num_players = num_players
# Count the number of raise
self.have_raised = 0
# Count the number without raise
# If every player agree to not raise, the round is over
self.not_raise_num = 0
# Raised amount for each player
self.raised = [0 for _ in range(self.num_players)]
self.player_folded = None
def start_new_round(self, game_pointer, raised=None):
"""
Start a new bidding round
Args:
game_pointer (int): The game_pointer that indicates the next player
raised (list): Initialize the chips for each player
Note: For the first round of the game, we need to setup the big/small blind
"""
self.game_pointer = game_pointer
self.have_raised = 0
self.not_raise_num = 0
if raised:
self.raised = raised
else:
self.raised = [0 for _ in range(self.num_players)]
def proceed_round(self, players, action):
"""
Call other classes functions to keep one round running
Args:
players (list): The list of players that play the game
action (str): An legal action taken by the player
Returns:
(int): The game_pointer that indicates the next player
"""
if action not in self.get_legal_actions():
raise Exception('{} is not legal action. Legal actions: {}'.format(action, self.get_legal_actions()))
if action == 'call':
diff = max(self.raised) - self.raised[self.game_pointer]
self.raised[self.game_pointer] = max(self.raised)
players[self.game_pointer].in_chips += diff
self.not_raise_num += 1
elif action == 'raise':
diff = max(self.raised) - self.raised[self.game_pointer] + self.raise_amount
self.raised[self.game_pointer] = max(self.raised) + self.raise_amount
players[self.game_pointer].in_chips += diff
self.have_raised += 1
self.not_raise_num = 1
elif action == 'fold':
players[self.game_pointer].status = 'folded'
self.player_folded = True
elif action == 'check':
self.not_raise_num += 1
self.game_pointer = (self.game_pointer + 1) % self.num_players
# Skip the folded players
while players[self.game_pointer].status == 'folded':
self.game_pointer = (self.game_pointer + 1) % self.num_players
return self.game_pointer
def get_legal_actions(self):
"""
Obtain the legal actions for the current player
Returns:
(list): A list of legal actions
"""
full_actions = ['call', 'raise', 'fold', 'check']
# If the the number of raises already reaches the maximum number raises, we can not raise any more
if self.have_raised >= self.allowed_raise_num:
full_actions.remove('raise')
# If the current chips are less than that of the highest one in the round, we can not check
if self.raised[self.game_pointer] < max(self.raised):
full_actions.remove('check')
# If the current player has put in the chips that are more than others, we can not call
if self.raised[self.game_pointer] == max(self.raised):
full_actions.remove('call')
return full_actions
def is_over(self):
"""
Check whether the round is over
Returns:
(boolean): True if the current round is over
"""
if self.not_raise_num >= self.num_players:
return True
return False
| 8 | 1,243 | Python |
svm | ./ProjectTest/Python/svm.py | '''
svm/base.py
'''
# coding:utf-8
import numpy as np
class BaseEstimator:
y_required = True
fit_required = True
def _setup_input(self, X, y=None):
"""Ensure inputs to an estimator are in the expected format.
Ensures X and y are stored as numpy ndarrays by converting from an
array-like object if necessary. Enables estimators to define whether
they require a set of y target values or not with y_required, e.g.
kmeans clustering requires no target labels and is fit against only X.
Parameters
----------
X : array-like
Feature dataset.
y : array-like
Target values. By default is required, but if y_required = false
then may be omitted.
"""
if not isinstance(X, np.ndarray):
X = np.array(X)
if X.size == 0:
raise ValueError("Got an empty matrix.")
if X.ndim == 1:
self.n_samples, self.n_features = 1, X.shape
else:
self.n_samples, self.n_features = X.shape[0], np.prod(X.shape[1:])
self.X = X
if self.y_required:
if y is None:
raise ValueError("Missed required argument y")
if not isinstance(y, np.ndarray):
y = np.array(y)
if y.size == 0:
raise ValueError("The targets array must be no-empty.")
self.y = y
def fit(self, X, y=None):
self._setup_input(X, y)
def predict(self, X=None):
if not isinstance(X, np.ndarray):
X = np.array(X)
if self.X is not None or not self.fit_required:
return self._predict(X)
else:
raise ValueError("You must call `fit` before `predict`")
def _predict(self, X=None):
raise NotImplementedError()
'''
svm/kernerls.py
'''
# coding:utf-8
import numpy as np
import scipy.spatial.distance as dist
class Linear(object):
def __call__(self, x, y):
return np.dot(x, y.T)
def __repr__(self):
return "Linear kernel"
class Poly(object):
def __init__(self, degree=2):
self.degree = degree
def __call__(self, x, y):
return np.dot(x, y.T) ** self.degree
def __repr__(self):
return "Poly kernel"
class RBF(object):
def __init__(self, gamma=0.1):
self.gamma = gamma
def __call__(self, x, y):
x = np.atleast_2d(x)
y = np.atleast_2d(y)
return np.exp(-self.gamma * dist.cdist(x, y) ** 2).flatten()
def __repr__(self):
return "RBF kernel"
'''
svm/__init__.py
'''
# coding:utf-8
'''
svm/svm.py
'''
# coding:utf-8
import logging
import numpy as np
from base import BaseEstimator
from kernerls import Linear
np.random.seed(9999)
"""
References:
The Simplified SMO Algorithm http://cs229.stanford.edu/materials/smo.pdf
"""
class SVM(BaseEstimator):
def __init__(self, C=1.0, kernel=None, tol=1e-3, max_iter=100):
"""Support vector machines implementation using simplified SMO optimization.
Parameters
----------
C : float, default 1.0
kernel : Kernel object
tol : float , default 1e-3
max_iter : int, default 100
"""
self.C = C
self.tol = tol
self.max_iter = max_iter
if kernel is None:
self.kernel = Linear()
else:
self.kernel = kernel
self.b = 0
self.alpha = None
self.K = None
def fit(self, X, y=None):
self._setup_input(X, y)
self.K = np.zeros((self.n_samples, self.n_samples))
for i in range(self.n_samples):
self.K[:, i] = self.kernel(self.X, self.X[i, :])
self.alpha = np.zeros(self.n_samples)
self.sv_idx = np.arange(0, self.n_samples)
return self._train()
def _train(self):
iters = 0
while iters < self.max_iter:
iters += 1
alpha_prev = np.copy(self.alpha)
for j in range(self.n_samples):
# Pick random i
i = self.random_index(j)
eta = 2.0 * self.K[i, j] - self.K[i, i] - self.K[j, j]
if eta >= 0:
continue
L, H = self._find_bounds(i, j)
# Error for current examples
e_i, e_j = self._error(i), self._error(j)
# Save old alphas
alpha_io, alpha_jo = self.alpha[i], self.alpha[j]
# Update alpha
self.alpha[j] -= (self.y[j] * (e_i - e_j)) / eta
self.alpha[j] = self.clip(self.alpha[j], H, L)
self.alpha[i] = self.alpha[i] + self.y[i] * self.y[j] * (alpha_jo - self.alpha[j])
# Find intercept
b1 = (
self.b - e_i - self.y[i] * (self.alpha[i] - alpha_io) * self.K[i, i]
- self.y[j] * (self.alpha[j] - alpha_jo) * self.K[i, j]
)
b2 = (
self.b - e_j - self.y[j] * (self.alpha[j] - alpha_jo) * self.K[j, j]
- self.y[i] * (self.alpha[i] - alpha_io) * self.K[i, j]
)
if 0 < self.alpha[i] < self.C:
self.b = b1
elif 0 < self.alpha[j] < self.C:
self.b = b2
else:
self.b = 0.5 * (b1 + b2)
# Check convergence
diff = np.linalg.norm(self.alpha - alpha_prev)
if diff < self.tol:
break
logging.info("Convergence has reached after %s." % iters)
# Save support vectors index
self.sv_idx = np.where(self.alpha > 0)[0]
def _predict(self, X=None):
n = X.shape[0]
result = np.zeros(n)
for i in range(n):
result[i] = np.sign(self._predict_row(X[i, :]))
return result
def _predict_row(self, X):
k_v = self.kernel(self.X[self.sv_idx], X)
return np.dot((self.alpha[self.sv_idx] * self.y[self.sv_idx]).T, k_v.T) + self.b
def clip(self, alpha, H, L):
if alpha > H:
alpha = H
if alpha < L:
alpha = L
return alpha
def _error(self, i):
"""Error for single example."""
return self._predict_row(self.X[i]) - self.y[i]
def _find_bounds(self, i, j):
"""Find L and H such that L <= alpha <= H.
Also, alpha must satisfy the constraint 0 <= αlpha <= C.
"""
if self.y[i] != self.y[j]:
L = max(0, self.alpha[j] - self.alpha[i])
H = min(self.C, self.C - self.alpha[i] + self.alpha[j])
else:
L = max(0, self.alpha[i] + self.alpha[j] - self.C)
H = min(self.C, self.alpha[i] + self.alpha[j])
return L, H
def random_index(self, z):
i = z
while i == z:
i = np.random.randint(0, self.n_samples)
return i
| 4 | 238 | Python |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.