School Commit Init
This commit is contained in:
@@ -0,0 +1,91 @@
|
||||
class BlackjackGame {
|
||||
constructor() {
|
||||
this.deck = this.shuffleDeck(this.generateDeck());
|
||||
this.playerHand = [];
|
||||
this.dealerHand = [];
|
||||
this.hasStarted = false;
|
||||
}
|
||||
|
||||
generateDeck() {
|
||||
// Generate a deck of cards
|
||||
const deck = [];
|
||||
const suits = ['♠', '♣', '♥', '♦'];
|
||||
const ranks = ['A', '2', '3', '4', '5', '6', '7', '8', '9','10', 'J', 'Q', 'K'];
|
||||
for (let suit of suits) {
|
||||
for (let rank of ranks) {
|
||||
deck.push(rank + suit);
|
||||
}
|
||||
}
|
||||
return deck;
|
||||
}
|
||||
|
||||
shuffleDeck(deck) {
|
||||
// Shuffle the deck
|
||||
for (let i = deck.length - 1; i > 0; i--) {
|
||||
const j = Math.floor(Math.random() * (i + 1));
|
||||
[deck[i], deck[j]] = [deck[j], deck[i]];
|
||||
}
|
||||
return deck;
|
||||
|
||||
}
|
||||
|
||||
dealInitialHands() {
|
||||
this.deck = this.shuffleDeck(this.generateDeck());
|
||||
this.playerHand = [this.deck.pop(), this.deck.pop()];
|
||||
this.dealerHand = [this.deck.pop(), this.deck.pop()];
|
||||
this.hasStarted = true;
|
||||
}
|
||||
|
||||
playerHit() {
|
||||
const card = this.deck.pop();
|
||||
this.playerHand.push(card);
|
||||
}
|
||||
|
||||
playerStand() {
|
||||
this.dealerPlay();
|
||||
}
|
||||
|
||||
dealerPlay() {
|
||||
while (this.getHandValue(this.dealerHand) < 17 && this.getHandValue(this.dealerHand) <= this.getHandValue(this.playerHand)) {
|
||||
this.dealerHand.push(this.deck.pop());
|
||||
}
|
||||
}
|
||||
|
||||
determineWinner() {
|
||||
const playerValue = this.getHandValue(this.playerHand);
|
||||
const dealerValue = this.getHandValue(this.dealerHand);
|
||||
this.hasStarted = false;
|
||||
if (playerValue > 21 || (dealerValue <= 21 && dealerValue > playerValue)) {
|
||||
return 'Dealer';
|
||||
} else if (playerValue === 21 || (dealerValue > 21) || (playerValue < 21 && playerValue > dealerValue)) {
|
||||
return 'Player';
|
||||
} else {
|
||||
return 'Push';
|
||||
}
|
||||
}
|
||||
|
||||
getHandValue(hand) {
|
||||
// Calculate hand value
|
||||
let value = 0;
|
||||
let aces = 0;
|
||||
for (let card of hand) {
|
||||
const rank = card.slice(0, -1);
|
||||
if (rank === 'A') {
|
||||
aces++;
|
||||
value += 11;
|
||||
} else if (['J', 'Q', 'K'].includes(rank)) {
|
||||
value += 10;
|
||||
} else {
|
||||
value += Number(rank);
|
||||
}
|
||||
}
|
||||
while (value > 21 && aces > 0) {
|
||||
value -= 10;
|
||||
aces--;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
|
||||
module.exports = BlackjackGame;
|
||||
|
||||
@@ -0,0 +1,138 @@
|
||||
import socket
|
||||
import json
|
||||
|
||||
class Client:
|
||||
def __init__(self, address, port):
|
||||
self.address = address
|
||||
self.port = port
|
||||
self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
||||
def connect(self):
|
||||
self.socket.connect((self.address, self.port))
|
||||
|
||||
def send(self, message):
|
||||
self.socket.send(message.encode())
|
||||
|
||||
def receive_string(self):
|
||||
return self.socket.recv(1024).decode()
|
||||
|
||||
def receive(self):
|
||||
return json.loads(self.socket.recv(1024))
|
||||
|
||||
def close(self):
|
||||
self.socket.close()
|
||||
|
||||
class UI:
|
||||
def __init__(self):
|
||||
self.client = Client("172.30.114.67", 3000)
|
||||
self.client.connect()
|
||||
print(self.client.receive_string())
|
||||
self.run()
|
||||
def run(self):
|
||||
while True:
|
||||
option = input("Choose an option: ")
|
||||
match option:
|
||||
case "1":
|
||||
self.client.send(option)
|
||||
data = self.client.receive()
|
||||
print("\nPlayer hand:")
|
||||
for card in data['playerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nPlayer score:", data['playerScore'])
|
||||
|
||||
print("\nDealer hand:")
|
||||
for card in data['dealerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nDealer score:", data['dealerScore'])
|
||||
case "2":
|
||||
self.client.send(option)
|
||||
print(self.client.receive_string())
|
||||
self.client.close()
|
||||
exit()
|
||||
case "stand":
|
||||
self.client.send(option)
|
||||
data = self.client.receive()
|
||||
if(data.get('error') != None):
|
||||
print(data['error'])
|
||||
continue
|
||||
print("\nPlayer hand:")
|
||||
for card in data['playerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nPlayer score:", data['playerScore'])
|
||||
|
||||
print("\nDealer hand:")
|
||||
for card in data['dealerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nDealer score:", data['dealerScore'])
|
||||
if(data.get('winner') != None):
|
||||
print("Winner: " + data['winner'])
|
||||
print(self.client.receive_string())
|
||||
else:
|
||||
print("hit or stand?")
|
||||
case "s":
|
||||
self.client.send(option)
|
||||
data = self.client.receive()
|
||||
if(data.get('error') != None):
|
||||
print(data['error'])
|
||||
continue
|
||||
print("\nPlayer hand:")
|
||||
for card in data['playerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nPlayer score:", data['playerScore'])
|
||||
|
||||
print("\nDealer hand:")
|
||||
for card in data['dealerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nDealer score:", data['dealerScore'])
|
||||
if(data.get('winner') != None):
|
||||
print("Winner: " + data['winner'])
|
||||
print(self.client.receive_string())
|
||||
else:
|
||||
print("hit or stand?")
|
||||
case "hit":
|
||||
self.client.send(option)
|
||||
data = self.client.receive()
|
||||
if(data.get('error') != None):
|
||||
print(data['error'])
|
||||
continue
|
||||
print("\nPlayer hand:")
|
||||
for card in data['playerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nPlayer score:", data['playerScore'])
|
||||
|
||||
print("\nDealer hand:")
|
||||
for card in data['dealerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nDealer score:", data['dealerScore'])
|
||||
if(data.get('winner') != None):
|
||||
print("Winner: " + data['winner'])
|
||||
print(self.client.receive_string())
|
||||
else:
|
||||
print("hit or stand?")
|
||||
case "h":
|
||||
self.client.send(option)
|
||||
data = self.client.receive()
|
||||
if(data.get('error') != None):
|
||||
print(data['error'])
|
||||
continue
|
||||
print("\nPlayer hand:")
|
||||
for card in data['playerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nPlayer score:", data['playerScore'])
|
||||
|
||||
print("\nDealer hand:")
|
||||
for card in data['dealerHand']:
|
||||
print(card, end=" ")
|
||||
print("\nDealer score:", data['dealerScore'])
|
||||
if(data.get('winner') != None):
|
||||
print("Winner: " + data['winner'])
|
||||
print(self.client.receive_string())
|
||||
else:
|
||||
print("hit or stand?")
|
||||
|
||||
case _:
|
||||
print("Invalid option")
|
||||
|
||||
|
||||
|
||||
ui=UI()
|
||||
@@ -0,0 +1,85 @@
|
||||
const net = require('net');
|
||||
|
||||
const BlackjackGame = require('./blackjack_game.js');
|
||||
|
||||
const server = net.createServer((socket) => {
|
||||
// This callback function will be called every time a new client connects to the server
|
||||
console.log('Client connected');
|
||||
const game = new BlackjackGame();
|
||||
// send Start game message to client
|
||||
socket.write('Welcome to Blackjack!\nCommands: \n1. New game\n2. Exit\n');
|
||||
|
||||
// Handle incoming data from the client
|
||||
socket.on('data', (data) => {
|
||||
console.log(`Received data from client: ${data}`);
|
||||
console.log(`Type of data: ${typeof data}`)
|
||||
console.log(`Data to string: ${data.toString()}`)
|
||||
|
||||
// expected data: 1.(start/play again) 1.exit 2.hit 2.stand
|
||||
if (data.toString() === '1') {
|
||||
game.dealInitialHands();
|
||||
const dict = {
|
||||
playerHand: game.playerHand,
|
||||
playerScore: game.getHandValue(game.playerHand),
|
||||
dealerHand: [game.dealerHand[0],'??'],
|
||||
dealerScore: game.getHandValue([game.dealerHand[0]]),
|
||||
winner: null
|
||||
};
|
||||
socket.write(JSON.stringify(dict));
|
||||
}
|
||||
else if (data.toString() === '2') {
|
||||
socket.write('Thank you for playing!');
|
||||
socket.end();
|
||||
}
|
||||
else if (["hit","h"].includes(data.toString()) && game.hasStarted) {
|
||||
game.playerHit();
|
||||
// check if player busts
|
||||
if (game.getHandValue(game.playerHand) > 21) {
|
||||
const json = {
|
||||
playerHand: game.playerHand,
|
||||
playerScore: game.getHandValue(game.playerHand),
|
||||
dealerHand: game.dealerHand,
|
||||
dealerScore: game.getHandValue(game.dealerHand),
|
||||
winner: 'Dealer',
|
||||
};
|
||||
socket.write(JSON.stringify(json));
|
||||
socket.write('Wanna play again?\n1. Yes\n2. No\n');
|
||||
}
|
||||
else{
|
||||
const dict = {
|
||||
playerHand: game.playerHand,
|
||||
playerScore: game.getHandValue(game.playerHand),
|
||||
dealerHand: [game.dealerHand[0],'??'],
|
||||
dealerScore: game.getHandValue([game.dealerHand[0]]),
|
||||
winner: null
|
||||
};
|
||||
socket.write(JSON.stringify(dict));
|
||||
}
|
||||
}
|
||||
else if (["stand","s"].includes(data.toString()) && game.hasStarted) {
|
||||
game.playerStand();
|
||||
const dict = {
|
||||
playerHand: game.playerHand,
|
||||
playerScore: game.getHandValue(game.playerHand),
|
||||
dealerHand: game.dealerHand,
|
||||
dealerScore: game.getHandValue(game.dealerHand),
|
||||
winner: game.determineWinner()
|
||||
};
|
||||
socket.write(JSON.stringify(dict));
|
||||
socket.write('Wanna play again?\n1. Yes\n2. No\n');
|
||||
}
|
||||
else{
|
||||
socket.write(JSON.stringify({error:"Invalid command"}));
|
||||
}
|
||||
});
|
||||
|
||||
// Handle client disconnection
|
||||
socket.on('end', () => {
|
||||
console.log('Client disconnected');
|
||||
});
|
||||
});
|
||||
|
||||
// Start the server and listen on port 3000
|
||||
server.listen(3000, () => {
|
||||
console.log('Server started on port 3000');
|
||||
});
|
||||
@@ -0,0 +1 @@
|
||||
seq 10000 | xargs -I{} -P 10000 bash -c "echo -e '1\nhit\n2' | python3 client.py" > /dev/null
|
||||
@@ -0,0 +1,6 @@
|
||||
import socket
|
||||
s=socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
|
||||
msg="hey"
|
||||
s.sendto(str.encode(msg),("127.0.0.1",5555))
|
||||
msg,adr=s.recvfrom(10)
|
||||
print (msg.decode())
|
||||
@@ -0,0 +1,9 @@
|
||||
import socket
|
||||
|
||||
# Create a socket object
|
||||
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
||||
# Send message to server 172 30 0 4 57777
|
||||
s.connect(("172.19.66.240",2222))
|
||||
|
||||
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 80 KiB |
Binary file not shown.
@@ -0,0 +1,9 @@
|
||||
import socket
|
||||
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
|
||||
s.bind(("0.0.0.0",5555))
|
||||
|
||||
s.listen(5)
|
||||
while True:
|
||||
clientsocket, address = s.accept()
|
||||
print(f"Connection from {address} has been established!")
|
||||
s.listen(5)
|
||||
Reference in New Issue
Block a user