branch_name
stringclasses
149 values
text
stringlengths
23
89.3M
directory_id
stringlengths
40
40
languages
listlengths
1
19
num_files
int64
1
11.8k
repo_language
stringclasses
38 values
repo_name
stringlengths
6
114
revision_id
stringlengths
40
40
snapshot_id
stringlengths
40
40
refs/heads/main
<repo_name>macmowl/CLI-nager<file_sep>/index.js #!/usr/bin/env node const { getCode } = require('country-list') const chalk = require('chalk') const axios = require('axios').default; const figlet = require('figlet'); const myArgs = process.argv.slice(2); let year; if (myArgs[1]) { year = myArgs[1] } else { year = new Date().getFullYear(); } axios.get(`https://date.nager.at/api/v2/publicholidays/${year}/${getCode(myArgs[0])}`) .then(function (response) { figlet(`${myArgs[0]}'s holidays`, (err, data) => { if (err) { console.log('Oups'); console.dir(err); return; } console.log(data); console.log(chalk.blue('-----------------------')); response.data.forEach(holiday => { console.log(`${chalk.green.bold(holiday.date)} => ${holiday.name}`); }); console.log(chalk.blue('-----------------------')); }); }) .catch(function (error) { console.log(`An error occured: ${error.response.status} - ${error.response.statusText}`); });<file_sep>/README.md # Holidates Display annual holidays of any country. ![Holidates screen](https://github.com/macmowl/CLI-nager/blob/main/Holidates.png) ## Install `$ npm i @macmowl/holidates` ## Usage In the Command Terminal, just type: `holidates <country>` to get annual holidays for this country and the current year. Holidates is able to add a specific year: `holidates <country> <year>` Some examples: `holidates Belgium 2022` `holidates italy 2019` ## Maintainer [<NAME>](https://github.com/macmowl/)
de79a71780ad6d230ee6e495614269e164161eeb
[ "JavaScript", "Markdown" ]
2
JavaScript
macmowl/CLI-nager
b5816d8ed22cf84182d0982765181e783e821b5d
29522604132a286e2d7d9339d49d42dd0adff1d6
refs/heads/master
<repo_name>Kamilo020/NuevasTec<file_sep>/formulario contactenos/hoja de vida html/pages/elScript.js document.querySelector('html').onclick = function(){ alert('el mensaje que debe salir') }
a4ffe60b5177071992fb89da0237fc95d6a74145
[ "JavaScript" ]
1
JavaScript
Kamilo020/NuevasTec
69bc2471602a1ec51412818e2959108ef6cdc11c
d330ed11b2cf0b5be46ab90e2666d1fc7dca59b9
refs/heads/main
<file_sep>//action constants export const SET_PROJECT = "SET_PROJECT"; //action creator export const setProject = (project) => ({ type: SET_PROJECT, project, }); //initial State const initialState = { project: {}, }; //reducer export default function projectReducer(state = initialState, action) { switch (action.type) { case SET_PROJECT: return action.project; default: return state; } } <file_sep>import React, { Component } from 'react'; import { ViroARSceneNavigator } from 'react-viro'; import { connect } from 'react-redux'; //components import Login from './Login'; import Profile from './Profile'; import Explore from './Explore'; import ARNav from './ARNav'; import ARAuto from './ARAuto'; import ARPlaneSelector from './ARPlaneSelector'; import ARImageMarker from './ARImageMarker'; //nav types import { PROFILE_TYPE, EXPLORE_TYPE, AR_NAVIGATOR_TYPE, AUTO_AR, AR_PLANE_SELECTOR, AR_IMAGE_MARKER, } from './redux/navigation'; export class FullNav extends Component { render() { switch (this.props.navType) { case PROFILE_TYPE: return <Profile />; case EXPLORE_TYPE: return <Explore />; case AR_NAVIGATOR_TYPE: return <ARNav />; case AUTO_AR: return <ViroARSceneNavigator initialScene={{ scene: ARAuto }} />; case AR_PLANE_SELECTOR: return ( <ViroARSceneNavigator initialScene={{ scene: ARPlaneSelector }} /> ); case AR_IMAGE_MARKER: return <ViroARSceneNavigator initialScene={{ scene: ARImageMarker }} />; default: return <Login />; } } } const mapState = (state) => ({ navType: state.navigation.navigationType, }); export default connect(mapState)(FullNav); <file_sep>import React, { Component } from 'react'; import { Text, View, Image, TouchableHighlight, TextInput } from 'react-native'; import { connect } from 'react-redux'; import styles from './Stylesheet'; import { setNavigation, PROFILE_TYPE } from './redux/navigation'; import firebase from 'firebase'; import 'firebase/firestore'; export class Login extends Component { constructor(props) { super(props); this.state = { email: '', password: '', }; this.onLogin = this.onLogin.bind(this); } onLogin() { const { email, password } = this.state; firebase .auth() .signInWithEmailAndPassword(email, password) .then((result) => { // console.log(result); this.props.setNavType(PROFILE_TYPE); }) .catch((error) => { console.log(error); }); } render() { return ( <View style={styles.outer}> <View style={styles.inner}> <Image style={styles.largeLogo} source={require('./res/earthLogo.png')} /> <Text style={styles.titleText}>Welcome home</Text> <Text style={styles.titleText}>Please prove your humanity</Text> <TextInput style={styles.input} placeholder='email' onChangeText={(email) => this.setState({ email })} /> <TextInput style={styles.input} placeholder='password' secureTextEntry={true} onChangeText={(password) => this.setState({ password })} /> <TouchableHighlight style={styles.buttons} onPress={() => this.onLogin()} underlayColor={'#68A0FF'} > <Text style={styles.buttonText}>Login</Text> </TouchableHighlight> </View> </View> ); } } const mapDispatch = (dispatch) => ({ setNavType: (type) => dispatch(setNavigation(type)), }); export default connect(null, mapDispatch)(Login); <file_sep>import React, { Component } from 'react'; import { Text, View, TouchableHighlight } from 'react-native'; import { connect } from 'react-redux'; import styles from './Stylesheet'; import { setNavigation, AUTO_AR, AR_PLANE_SELECTOR, AR_IMAGE_MARKER, } from './redux/navigation'; export class ARNav extends Component { render() { return ( <View style={styles.outer}> <View style={styles.inner}> <Text style={styles.titleText}>Choose your viewing method:</Text> <TouchableHighlight style={styles.buttons} onPress={() => this.props.setNavType(AUTO_AR)} underlayColor={'#68a0ff'} > <Text style={styles.buttonText}>AUTOMATIC</Text> </TouchableHighlight> <TouchableHighlight style={styles.buttons} onPress={() => this.props.setNavType(AR_PLANE_SELECTOR)} underlayColor={'#68a0ff'} > <Text style={styles.buttonText}>CHOOSE BASE</Text> </TouchableHighlight> <TouchableHighlight style={styles.buttons} onPress={() => this.props.setNavType(AR_IMAGE_MARKER)} underlayColor={'#68a0ff'} > <Text style={styles.buttonText}>FIND IMAGE</Text> </TouchableHighlight> </View> </View> ); } } const mapState = (state) => ({ navType: state.navigation.navigationType, }); const mapDispatch = (dispatch) => ({ setNavType: (type) => dispatch(setNavigation(type)), }); export default connect(mapState, mapDispatch)(ARNav); <file_sep>import React, { Component } from "react"; import firebase from "firebase"; import "firebase/firestore"; import { v4 as uuidv4 } from "uuid"; import { withRouter } from "react-router"; import { SketchPicker } from "react-color"; import { Cube } from "../3DFolder/Cube"; import { Sphere } from "../3DFolder/Sphere"; import { Button } from "react-bootstrap"; export class Shape extends Component { constructor(props) { super(props); this.state = { name: "", shape: "sphere", colorSelected: "#d3d3d3", animation: "no", animate: "rotate", shapeScaleX: 0.25, shapeScaleY: 0.25, shapeScaleZ: 0.25, lightingModel: "Blinn", diffuseTexture: "", sound: "", view: "shape", material: "https://threejsfundamentals.org/threejs/resources/images/wall.jpg", colorOrTexture: "color", imageMarker: "no", targetImage: "", }; this.handleChange = this.handleChange.bind(this); this.handleChangeColor = this.handleChangeColor.bind(this); this.handleFileChange = this.handleFileChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e) { this.setState({ [e.target.name]: e.target.value, }); } handleChangeColor = (color) => { this.setState({ colorSelected: color.hex }); }; handleFileChange(e) { if (e.target.files[0]) { const targetImageFile = e.target.files[0]; const uploadTask = firebase .storage() .ref(`targetImages/${targetImageFile.name}`) .put(targetImageFile); uploadTask.on( "state_changed", (snapshot) => {}, (error) => { console.log(error); }, () => { firebase .storage() .ref("targetImages") .child(targetImageFile.name) .getDownloadURL() .then((url) => { this.setState({ targetImage: url, }); }); } ); } } handleSubmit(e) { e.preventDefault(); firebase .firestore() .collection("users") .doc(firebase.auth().currentUser.uid) .update({ projects: firebase.firestore.FieldValue.arrayUnion({ id: uuidv4(), name: this.state.name, shape: this.state.shape, colorSelected: this.state.colorSelected, animation: this.state.animation, animate: this.state.animate, shapeScaleX: this.state.shapeScaleX, shapeScaleY: this.state.shapeScaleY, shapeScaleZ: this.state.shapeScaleZ, lightingModel: this.state.lightingModel, diffuseTexture: this.state.diffuseTexture, sound: this.state.sound, view: this.state.view, material: this.state.material, colorOrTexture: this.state.colorOrTexture, imageMarker: this.state.imageMarker, targetImage: this.state.targetImage, }), }); this.props.history.push("/projects"); } render() { const { handleChange, handleChangeColor, handleFileChange, handleSubmit } = this; const { animation, shape, colorSelected, animate, name, shapeScaleX, shapeScaleY, shapeScaleZ, sound, colorOrTexture, material, imageMarker, } = this.state; return ( <div> {shape === "sphere" ? ( <Sphere data={this.state} /> ) : ( <div> <Cube data={this.state} /> </div> )} <div className="App"> <header className="App-header"> <div className="container"> <form onSubmit={handleSubmit}> <h1>Create 3D Model </h1> <div className="names"> <label htmlFor="name"> Model Name: <input name="name" onChange={handleChange} value={name} /> </label> </div> <div className="shapes"> <h3>Display Shape:</h3> <label htmlFor="shape"> Shape: <select className="shapes" id="dropbown" name="shape" onChange={handleChange} value={shape} > <option value="sphere">Sphere</option> <option value="cube">Cube</option> </select> </label> <h5>Shape Scale: </h5> <label htmlFor="shapeScale"> <label> X: {shapeScaleX}</label> <input name="shapeScaleX" type="range" min="0.05" max="1" step="0.05" onChange={handleChange} value={shapeScaleX} /> <label>Y: {shapeScaleY}</label> <input name="shapeScaleY" type="range" min="0.05" max="1" step="0.05" onChange={handleChange} value={shapeScaleY} /> <label>Z: {shapeScaleZ}</label> <input name="shapeScaleZ" type="range" min="0.05" max="1" step="0.05" onChange={handleChange} value={shapeScaleZ} /> </label> </div> <div className="colorOrTexture"> <h5> Would you like your model to have a color or a specific image material wrapped over it?{" "} </h5> <select id="dropbown" name="colorOrTexture" onChange={handleChange} value={colorOrTexture} > <option value="color">Color</option> <option value="material">Material</option> </select> </div> {this.state.colorOrTexture === "color" ? ( <div className="colors"> <h3>Select A Color:</h3> <label htmlFor="color"> Color: {colorSelected} <SketchPicker color={this.state.colorSelected} onChangeComplete={handleChangeColor} /> </label> </div> ) : ( <div className="materials"> <label htmlFor="material"> <label> {" "} Insert an image URL to wrap over your object:{" "} </label> <input name="material" type="text" onChange={handleChange} value={material} /> </label> </div> )} <div className="sound"> <label htmlFor="sound"> <label> {" "} Insert a URL to a MP3 for a song to be attached to your model:{" "} </label> <input name="sound" type="text" onChange={handleChange} value={sound} /> </label> </div> <div className="animations"> <h5>Would you like to animate your model?</h5> <select id="dropbown" name="animation" onChange={handleChange} value={animation} > <option value="yes">Yes</option> <option value="no">No</option> </select> </div> {this.state.animation === "yes" ? ( <div> <label htmlFor="animate"> <small>Animate options</small> </label> <select id="dropbown" name="animate" onChange={handleChange} value={animate} > <option value="spin">Spin</option> <option value="jump">Jump</option> <option value="flip">Flip</option> <option value="forward">Forward</option> <option value="backward">Backward</option> </select> </div> ) : ( <div> <p>Your model will be static.</p> </div> )} <div className="imageMarker"> <h5> Would you like an image marker which you can scan to render your model? </h5> <select id="dropbown" name="imageMarker" onChange={handleChange} value={imageMarker} > <option value="yes">Yes</option> <option value="no">No</option> </select> </div> {this.state.imageMarker === "yes" ? ( <div> <label htmlFor="targetImage"> <label> {" "} Upload a target image which will render your 3D model once scanned:{" "} </label> <input name="targetImage" type="file" accept=".jpg, .jpeg, .png" onChange={handleFileChange} /> </label> </div> ) : ( <div> <small> You will be presented with three ways to render your model on our mobile app. </small> </div> )} <div> <Button variant="light" type="submit"> Submit </Button> </div> </form> </div> </header> </div> </div> ); } } export default withRouter(Shape); <file_sep>import {React, Component } from "react"; import * as THREE from "three"; const loader = new THREE.FontLoader(); const imageLoader = new THREE.TextureLoader(); let word; let changeColor; let mesh; let scene; let camera; let renderer; let Xscale; let Yscale; let material; let colorOrTexture export class Word extends Component { componentDidUpdate(prevProps){ if(this.props.data !== prevProps.data) { scene.remove(mesh) word = this.props.data.text changeColor = this.props.data.colorSelected Xscale = this.props.data.textScaleX Yscale = this.props.data.textScaleY colorOrTexture = this.props.data.colorOrTexture material = this.props.data.material loader.load('https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( font ) { var geometry = new THREE.TextGeometry( word, { font: font, size: Xscale, height: Yscale } ); geometry.center(); if (colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: changeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: imageLoader.load(material), }); } mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); }) } } componentDidMount() { word = this.props.data.text; changeColor = this.props.data.colorSelected colorOrTexture = this.props.data.colorOrTexture material = this.props.data.material scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 150 ); renderer = new THREE.WebGLRenderer(); renderer.setSize( 1000, 500 ); this.mount.appendChild( renderer.domElement ); loader.load('https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( font ) { var geometry = new THREE.TextGeometry( word, { font: font, size: 0.6, height: 0.1, } ); geometry.center(); if (colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: changeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: imageLoader.load(material), }); } mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); scene.add( light ); camera.position.z = 2; var animate = function () { requestAnimationFrame( animate ); mesh.rotation.x += 0.01; mesh.rotation.y += 0.01; mesh.rotation.z += 0.01; renderer.render( scene, camera ); }; animate(); }) } render() { return ( <div><h1>Text</h1> <div ref={ref => (this.mount = ref)} /> </div> ) } }<file_sep>import React, { Component } from "react"; import { BrowserRouter as Router, Switch, Route } from "react-router-dom"; import firebase from "firebase"; import Home from "./components/Home"; import Signup from "./components/Signup"; import Login from "./components/Login"; import Logout from "./components/Logout"; import Create from "./components/Create"; import Welcome from "./components/Welcome"; import Projects from "./components/Projects"; import logo from "./assets/earthLogo.png"; import gif from "./assets/loading.gif"; import "bootstrap/dist/css/bootstrap.min.css"; import { Navbar, Nav } from "react-bootstrap"; // Firebase API key is public const firebaseConfig = { apiKey: "<KEY>", authDomain: "earth-a2ce0.firebaseapp.com", projectId: "earth-a2ce0", storageBucket: "earth-a2ce0.appspot.com", messagingSenderId: "33112054293", appId: "1:33112054293:web:801afc5e9473c7ba050c1c", measurementId: "G-6V50YYJBS2", }; if (firebase.apps.length === 0) { firebase.initializeApp(firebaseConfig); } class App extends Component { constructor() { super(); this.state = { loaded: false, }; } componentDidMount() { firebase.auth().onAuthStateChanged((user) => { if (!user) { this.setState({ loggedIn: false, loaded: true, }); } else { this.setState({ loggedIn: true, loaded: true, }); } }); } render() { const { loggedIn, loaded } = this.state; if (!loaded) { return ( <div style={{ textAlign: "center" }}> <h1>Loading</h1> <img src={gif} alt="loading" width="200" /> </div> ); } if (!loggedIn) { return ( <Router> <div> <Navbar bg="light"> <Navbar.Brand href="/"> <img src={logo} width="50" className="d-inlline-block align-top" alt="logo" /> </Navbar.Brand> <Nav.Link href="/signup">Sign Up</Nav.Link> <Nav.Link href="/login">Login</Nav.Link> </Navbar> <nav> <Switch> <Route path="/signup" component={Signup} /> <Route path="/login" component={Login} /> <Route exact path="/" component={Home} /> </Switch> </nav> </div> </Router> ); } return ( <Router> <div> <Navbar bg="light"> <Navbar.Brand href="/"> <img src={logo} width="50" className="d-inlline-block align-top" alt="logo" /> </Navbar.Brand> <Nav.Link href="/projects">Projects</Nav.Link> <Nav.Link href="/logout">Logout</Nav.Link> </Navbar> <Switch> <Route path="/projects" component={Projects} /> <Route path="/create" component={Create} /> <Route exact path="/logout" component={Logout} /> <Route exact path="/" component={Welcome} /> </Switch> </div> </Router> ); } } export default App; <file_sep>'use strict'; import React, { Component } from 'react'; import { StyleSheet } from 'react-native'; import { ViroARScene, ViroNode, ViroARPlaneSelector, preloadSounds, ViroSound, ViroSpatialSound, ViroText, ViroConstants, ViroBox, ViroSphere, ViroMaterials, ViroAmbientLight, ViroDirectionalLight, ViroAnimations, } from 'react-viro'; export default class ARTesting extends Component { constructor() { super(); // Set initial state here this.state = { text: 'Initializing AR...', }; // bind 'this' to functions this._onInitialized = this._onInitialized.bind(this); } render() { const { projects } = this.props; console.dir(ViroSound); return ( <ViroARScene onTrackingUpdated={this._onInitialized}> <ViroAmbientLight color='#ffffff' intensity={150} /> <ViroDirectionalLight color='#ffffff' direction={[0.5, -1, 0.5]} castsShadow={true} /> <ViroText text={this.state.text} scale={[0.25, 0.25, 0.25]} position={[0, 0, -1]} style={styles.helloWorldTextStyle} /> <ViroBox position={[0, -0.5, -1]} scale={[0.3, 0.3, 0.3]} materials={'takashi'} animation={{ name: 'jump', run: true, loop: true }} /> <ViroSound paused={false} muted={false} source={'takashiSoundTest'} // onError={(error) => { // console.log(error); // }} loop={true} volume={1.0} /> </ViroARScene> ); } _onInitialized(state, reason) { if (state == ViroConstants.TRACKING_NORMAL) { this.setState({ text: '', }); } else if (state == ViroConstants.TRACKING_NONE) { // Handle loss of tracking } } } ViroMaterials.createMaterials({ takashi: { diffuseTexture: require('./res/takashiZen2.png'), lightingModel: 'Blinn', }, }); ViroAnimations.registerAnimations({ spin: { properties: { rotateY: '+=45', }, duration: 2000, }, forward: { properties: { rotateX: '+=45', }, duration: 2000, }, backward: { properties: { rotateX: '-=45', }, duration: 2000, }, frontFlip: { properties: { rotateX: '+=360', }, easing: 'EaseInEaseOut', duration: 1000, }, sit: { properties: { positionY: -0.5, }, duration: 1000, }, jumpUp: { properties: { positionY: '+=1', }, duration: 1000, }, delayAnimation: { delay: 4000, }, jump: [['sit', 'jumpUp', 'sit'], ['delayAnimation']], flip: [['frontFlip'], ['delayAnimation']], }); ViroSound.preloadSounds({ takashiSoundTest: 'https://firebasestorage.googleapis.com/v0/b/earth-a2ce0.appspot.com/o/sounds%2FLong%20Distance%20Groove%20-%20Blue%20-%2003%20Indigo.mp3?alt=media&lol=.mp3', takashiWorking: 'http://www.kozco.com/tech/32.mp3', }).then(console.log); var styles = StyleSheet.create({ helloWorldTextStyle: { fontFamily: 'Arial', fontSize: 30, color: '#ffffff', textAlignVertical: 'center', textAlign: 'center', }, }); module.exports = ARTesting; <file_sep>import React, { Component } from "react"; import Both from "./Both"; import Text from "./Text"; import Shape from "./Shape"; class Create extends Component { constructor(props) { super(props); this.state = { view: "both", }; this.handleChange = this.handleChange.bind(this); } handleChange(e) { this.setState({ [e.target.name]: e.target.value, }); } render() { const { handleChange } = this; const { view } = this.state; return ( <div className="page"> <form className="views"> <div> <h1>Create 3D Model</h1> <h5> Would you like to create a 3D Text model, Shape Model, or Both?{" "} </h5> <label> Text: </label> <input type="radio" id="text" name="view" onChange={handleChange} value="text" />{" "} |<label> Shape: </label> <input type="radio" id="shape" name="view" onChange={handleChange} value="shape" />{" "} |<label> Both: </label> <input defaultChecked type="radio" id="both" name="view" onChange={handleChange} value="both" /> </div> </form> {view === "both" ? <Both /> : <div></div>} {view === "shape" ? <Shape /> : <div></div>} {view === "text" ? <Text /> : <div></div>} </div> ); } } export default Create; <file_sep>//action constants export const UNSET = 'UNSET'; export const LOGIN_TYPE = 'LG'; export const PROFILE_TYPE = 'PROF'; export const EXPLORE_TYPE = 'EX'; export const AR_NAVIGATOR_TYPE = 'AR NAV'; export const AUTO_AR = 'AUTO AR'; export const AR_PLANE_SELECTOR = 'AR PLANE SELECTOR'; export const AR_IMAGE_MARKER = 'AR IMAGE MARKER'; //action creator export const setNavigation = (type) => { return { type: type, }; }; //initial State const initialState = { navigationType: UNSET, }; //reducer export default function navigationReducer(state = initialState, action) { switch (action.type) { case action.type: return { ...state, navigationType: action.type }; default: return state; } } <file_sep>'use strict'; import React, { Component } from 'react'; // import { connect } from "react-redux"; import { StyleSheet, TouchableHighlight, Text } from 'react-native'; import { connect } from 'react-redux'; import { ViroARScene, ViroARImageMarker, ViroText, ViroConstants, ViroBox, preloadSounds, ViroSound, ViroSphere, ViroMaterials, ViroARTrackingTargets, ViroAmbientLight, ViroDirectionalLight, ViroAnimations, } from 'react-viro'; // import styles from "./Stylesheet"; // converts model scales data type from string to integer function convertToNumber(string) { return parseFloat(string, 10); } export class FindImage extends Component { constructor() { super(); // Set initial state here this.state = { text: 'Loading...', }; // bind 'this' to functions this.myColorKey = `myColor${Date.now().toString().slice(-3)}`; this.myTextureKey = `myTexture${Date.now().toString().slice(-3)}`; this.mySoundKey = `mySound${Date.now().toString().slice(-3)}`; this.myTargetKey = `myTarget${Date.now().toString().slice(-3)}`; this._onInitialized = this._onInitialized.bind(this); } componentDidMount() { const { project } = this.props; if (project.colorSelected) { ViroMaterials.createMaterials({ [this.myColorKey]: { diffuseColor: project.colorSelected, lightingModel: 'Blinn', }, }); } else { ViroMaterials.createMaterials({ [this.myTextureKey]: { diffuseTexture: { uri: project.material, }, lightingModel: 'Blinn', }, }); } if (project.sound) { ViroSound.preloadSounds({ [this.mySoundKey]: project.sound, }); ViroARTrackingTargets.createTargets({ [this.myTargetKey]: { source: { uri: project.targetImage }, orientation: 'Up', physicalWidth: 0.1, }, }); } // console.log(JSON.stringify(project, null, 4)); // // this.myTextureKey = `myTexture ${Date.now()}`; // if (project.colorSelected) { // ViroMaterials.createMaterials({ // [this.myColorKey]: { // diffuseColor: '#eac07a', // lightingModel: 'Blinn', // }, // }); // } else { // ViroMaterials.createMaterials({ // [this.myTextureKey]: { // diffuseTexture: project.diffuseTexture, // lightingModel: 'Blinn', // }, // }); // } } render() { const { project } = this.props; return ( <ViroARScene> <ViroARImageMarker target={this.myTargetKey}> <ViroAmbientLight color='#ffffff' intensity={150} /> <ViroDirectionalLight color='#ffffff' direction={[0.5, -1, 0.5]} castsShadow={true} /> {project.text ? ( <ViroText text={this.state.text} scale={[ 0.25, 0.25, 0.25, // convertToNumber(project.textScaleX), // convertToNumber(project.textScaleY), // convertToNumber(project.textScaleZ), ]} position={[0, 0, -1]} style={styles.helloWorldTextStyle} /> ) : null} {project.shape === 'cube' ? ( <ViroBox position={[0, -0.5, -1]} scale={[ convertToNumber(project.shapeScaleX), convertToNumber(project.shapeScaleY), convertToNumber(project.shapeScaleZ), ]} materials={[ project.colorOrTexture === 'color' ? this.myColorKey : this.myTextureKey, ]} animation={{ name: project.animate, run: true, loop: true }} /> ) : ( <ViroSphere position={[0, -0.5, -1]} scale={[ convertToNumber(project.shapeScaleX), convertToNumber(project.shapeScaleY), convertToNumber(project.shapeScaleZ), ]} materials={[ project.colorOrTexture === 'color' ? this.myColorKey : this.myTextureKey, ]} animation={{ name: project.animate, run: true, loop: true, }} /> )} <ViroSound paused={false} muted={false} // if audioUrl isn't working will have to use project.sound as source for audio files source={this.mySoundKey} loop={true} // onError={(error) => { // console.log(error); // }} volume={1.0} /> </ViroARImageMarker> </ViroARScene> ); } _onInitialized(state, reason) { if (state == ViroConstants.TRACKING_NORMAL) { this.setState({ text: 'Champloo', }); } else if (state == ViroConstants.TRACKING_NONE) { // Handle loss of tracking } } } ViroAnimations.registerAnimations({ spin: { properties: { rotateY: '+=45', }, duration: 2000, }, forward: { properties: { rotateX: '+=45', }, duration: 2000, }, backward: { properties: { rotateX: '-=45', }, duration: 2000, }, frontFlip: { properties: { rotateX: '+=360', }, easing: 'EaseInEaseOut', duration: 1000, }, sit: { properties: { positionY: -0.5, }, duration: 1000, }, jumpUp: { properties: { positionY: '+=1', }, duration: 1000, }, delayAnimation: { delay: 4000, }, jump: [['sit', 'jumpUp', 'sit'], ['delayAnimation']], flip: [['frontFlip'], ['delayAnimation']], }); var styles = StyleSheet.create({ helloWorldTextStyle: { fontFamily: 'Arial', fontSize: 30, color: '#ffffff', textAlignVertical: 'center', textAlign: 'center', }, }); const mapState = (state) => ({ project: state.project, }); // module.exports = FindImage; export default connect(mapState)(FindImage); <file_sep>import React, { Component } from 'react'; import { Text, View, TouchableHighlight, TouchableOpacity, ScrollView, Image, } from 'react-native'; import { connect } from 'react-redux'; import styles from './Stylesheet'; import { setNavigation, AR_NAVIGATOR_TYPE, EXPLORE_TYPE, } from './redux/navigation'; import { setProject } from './redux/project'; import firebase from 'firebase'; import 'firebase/firestore'; export class Profile extends Component { constructor() { super(); this.state = { projects: [], }; this.handleProjectPress = this.handleProjectPress.bind(this); } componentDidMount() { firebase .firestore() .collection('users') .doc(firebase.auth().currentUser.uid) .get() .then((snapshot) => { this.setState({ projects: snapshot.data().projects, }); }); this.setState({ state: this.state, }); } handleProjectPress(project) { this.props.setProject(project); this.props.setNavType(AR_NAVIGATOR_TYPE); } render() { return ( <View style={styles.inner}> <Image style={styles.tinyLogo} source={require('./res/eARth.png')} /> <Text style={styles.titleText}>My Projects</Text> <Text style={styles.titleText}>Select a project to render:</Text> {this.state.projects.length === 0 ? ( <Text> You do not currently have any projects. Please visit our website to create a 3D model. </Text> ) : ( <ScrollView> {this.state.projects.map((project) => ( <TouchableOpacity key={project.id} style={styles.card} onPress={() => this.handleProjectPress(project)} > <Text>{project.name}</Text> <Text>View: {project.view}</Text> {project.shape ? <Text>Shape: {project.shape}</Text> : null} {project.colorSelected ? ( <Text>Color: {project.colorSelected}</Text> ) : null} {project.animation ? ( <Text>Animation: {project.animation}</Text> ) : null} {project.animate ? ( <Text>Animate: {project.animate}</Text> ) : null} {project.text ? <Text>Text: {project.text}</Text> : null} {project.textScaleX ? ( <Text>Text Scale X: {project.textScaleX}</Text> ) : null} {project.textScaleY ? ( <Text>Text Scale Y: {project.textScaleY}</Text> ) : null} {project.textScaleZ ? ( <Text>Text Scale Z: {project.textScaleZ}</Text> ) : null} {project.shapeScaleX ? ( <Text>Shape Scale X: {project.shapeScaleX}</Text> ) : null} {project.shapeScaleY ? ( <Text>Shape Scale Y: {project.shapeScaleY}</Text> ) : null} {project.shapeScaleZ ? ( <Text>Shape Scale Z: {project.shapeScaleZ}</Text> ) : null} {project.fontSize ? ( <Text>Font Size: {project.fontSize}</Text> ) : null} {project.textColor ? ( <Text>Text Color: {project.textColor}</Text> ) : null} {project.sound ? <Text>Sound: {project.sound}</Text> : null} </TouchableOpacity> ))} </ScrollView> )} <TouchableHighlight style={styles.buttons} onPress={() => this.props.setNavType(EXPLORE_TYPE)} > <Text style={styles.buttonText}>Explore </Text> </TouchableHighlight> </View> ); } } const mapState = (state) => ({ navType: state.navigation.navigationType, }); const mapDispatch = (dispatch) => ({ setNavType: (type) => dispatch(setNavigation(type)), setProject: (project) => dispatch(setProject(project)), }); export default connect(mapState, mapDispatch)(Profile); <file_sep>import React, { Component } from "react"; import "../App.css"; import logo from "../assets/earthLogo.png"; import { Button, Image } from "react-bootstrap"; class Welcome extends Component { render() { return ( <div className="App"> <header className="App-header"> <Image src={logo} alt="logo" width="200" fluid /> <h3 style={{ margin: "0 10rem 5rem 10rem" }}> Welcome back to eARth. Here, you can create your very own 3D AR (augmented reality) models, and then use them in our AR app. </h3> <div> <Button style={{ margin: "2rem" }} variant="light" href="/create"> Create New Project </Button> </div> </header> </div> ); } } export default Welcome; <file_sep>import {React, Component} from "react"; import * as THREE from "three"; const loader = new THREE.TextureLoader(); let changeColor; let cube; let scene; let camera; let renderer; let material; export class Cube extends Component { componentDidUpdate(prevProps) { if(this.props.data !== prevProps.data) { scene.remove(cube) changeColor = this.props.data.colorSelected let geometry = new THREE.BoxGeometry( 0.1, 0.1, 0.1 ); if (this.props.data.colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: changeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: loader.load(this.props.data.material), }); } cube = new THREE.Mesh( geometry, material ); scene.add( cube ); } } componentDidMount() { changeColor = this.props.data.colorSelected scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 10, window.innerWidth/window.innerHeight, 0.1, 20 ); renderer = new THREE.WebGLRenderer(); renderer.setSize( 1000, 500 ); this.mount.appendChild( renderer.domElement ); let geometry = new THREE.BoxGeometry( 0.1, 0.1, 0.1 ); if (this.props.data.colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: changeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: loader.load(this.props.data.material), }); } cube = new THREE.Mesh( geometry, material ); scene.add( cube ); const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); scene.add( light ); camera.position.z = 2; var animate = function () { requestAnimationFrame( animate ); cube.rotation.x += 0.01; cube.rotation.y += 0.01; cube.rotation.z += 0.01; renderer.render( scene, camera ); }; animate(); } render() { return ( <div><h1>Shape: Box</h1> <div ref={ref => (this.mount = ref)} /> </div> ) } }<file_sep>import {React, Component} from "react"; import * as THREE from "three"; const loader = new THREE.TextureLoader(); let sphereChangeColor; let sphere; let scene; let camera; let renderer; let material; export class Sphere extends Component { componentDidUpdate(prevProps) { if(this.props.data !== prevProps.data) { scene.remove(sphere) sphereChangeColor = this.props.data.colorSelected let geometry = new THREE.SphereGeometry( 0.7, 12, 8 ); if (this.props.data.colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: sphereChangeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: loader.load(this.props.data.material), }); } sphere = new THREE.Mesh( geometry, material ); scene.add( sphere ); } } componentDidMount() { sphereChangeColor = this.props.data.colorSelected scene = new THREE.Scene(); camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 20 ); renderer = new THREE.WebGLRenderer(); renderer.setSize( 1000, 500 ); this.mount.appendChild( renderer.domElement ); let geometry = new THREE.SphereGeometry( 0.7, 12, 8 ); if (this.props.data.colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: sphereChangeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: loader.load(this.props.data.material), }); } sphere = new THREE.Mesh( geometry, material ); scene.add( sphere ); const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); scene.add( light ); camera.position.z = 2; let animate = function () { requestAnimationFrame( animate ); sphere.rotation.x += 0.01; sphere.rotation.y += 0.01; sphere.rotation.z += 0.01; renderer.render( scene, camera ); }; animate(); } render() { return ( <div><h1>Shape: Sphere</h1> <div ref={ref => (this.mount = ref)} /> </div> ) } }<file_sep>import React, { Component } from "react"; import "../App.css"; import logo from "../assets/earthLogo.png"; import { Button, Image } from "react-bootstrap"; class Home extends Component { render() { return ( <div className="page"> <div className="logo-ann"> <h1>Welcome to</h1> </div> <Image src={logo} alt="logo" width="200" fluid /> <h3 style={{ fontStyle: "italic", margin: "0 10rem" }}> Create your very own 3D AR (augmented reality) models, add music to them, and then place them in the world. </h3> <p>login or sign up for an account to start creating your projects</p> <div> <Button variant="light" href="/login"> Login </Button> <p>Or</p> <Button variant="light" href="/signup"> Signup </Button> </div> </div> ); } } export default Home; <file_sep>import React, { Component } from "react"; import { withRouter } from "react-router"; import firebase from "firebase"; import "firebase/firestore"; import { Button, OverlayTrigger, Popover } from "react-bootstrap"; class Signup extends Component { constructor() { super(); this.state = { username: "", email: "", password: "", }; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } handleChange(e) { this.setState({ [e.target.name]: e.target.value, }); } handleSubmit(e) { e.preventDefault(); const { username, email, password } = this.state; firebase .auth() .createUserWithEmailAndPassword(email, password) .then((result) => { firebase .firestore() .collection("users") .doc(firebase.auth().currentUser.uid) .set({ username, email, projects: [], }); // console.log(result); }) .catch((error) => { console.log(error); }); this.props.history.push("/"); } render() { return ( <div className="page"> <div className="container"> <h1>Sign Up</h1> <form onSubmit={this.handleSubmit}> <div> <label htmlFor="username"> <small>Username: </small> </label> <input name="username" onChange={this.handleChange} value={this.state.username} /> </div> <div> <label htmlFor="email"> <small>Email: </small> </label> <input name="email" onChange={this.handleChange} value={this.state.email} /> </div> <OverlayTrigger trigger="focus" placement="top" overlay={ <Popover id={"popover - positioned - top"}> <Popover.Title as="h4">Pro Tip:</Popover.Title> <Popover.Content> Please ensure that your password is at least{" "} <strong>6</strong> characters in length and includes at least one letter and number </Popover.Content> </Popover> } > <div> <label htmlFor="password"> <small>Password: </small> </label> <input name="password" type="<PASSWORD>" onChange={this.handleChange} value={this.state.password} /> </div> </OverlayTrigger> <div className="enter"> <Button variant="light" type="submit"> Sign Up </Button> </div> </form> </div> </div> ); } } export default withRouter(Signup); <file_sep>![earthLogo](https://user-images.githubusercontent.com/74827423/119892884-ae4f2c80-bf08-11eb-8ee9-4f25f85f0e41.png) # eARTh eARTh is a platform for artists to create interactive 3D models and place them in various places around the world using location-based AR. Models may contain an mp3 audio file that can be listened to once the model has been placed. eARTh’s goal is to empower artists and create a new way for people to appreciate art around the world. Overview and about us: https://youtu.be/_0bYUqzYg6o Preview video of an animated model with audio: [takashiVidTest.mov.zip](https://github.com/2103-team-Earth/eARth2/files/6540655/takashiVidTest.mov.zip) ### Instructions ### Link to the site https://earth-a2ce0.firebaseapp.com/ ### Preview video of an animated model with audio: [takashiVidTest.mov.zip](https://github.com/2103-team-Earth/eARth2/files/6540655/takashiVidTest.mov.zip) ### Clone Repo ``` git clone https://github.com/2103-team-Earth/eARth2.git cd app ``` ### Installation ``` npm install ``` ### Running the App ``` npm start download Viro Media app Open the app, tap the dropdown, and select enter testbed enter the ngrok endpoint generated from your terminal or use your machine's IP address once connected login to continue ``` <file_sep>import React, { Component } from "react"; import firebase from "firebase"; import "firebase/firestore"; import logo from "../assets/earthLogo.png"; import { Button, Image } from "react-bootstrap"; class Logout extends Component { render() { return ( <div className="page"> <Image src={logo} alt="logo" width="200" fluid /> <h4>Would you like to log out of your account?</h4> <Button variant="light" type="submit" href="/" onClick={() => firebase.auth().signOut()} > Logout </Button> </div> ); } } export default Logout; <file_sep>import React, { Component } from "react"; import { Provider } from "react-redux"; import store from "./js/redux/store"; import FullNav from "./js/FullNav"; import { UNSET } from "./js/redux/navigation"; import firebase from "firebase"; // Firebase API key is public const firebaseConfig = { apiKey: "<KEY>", authDomain: "earth-a2ce0.firebaseapp.com", projectId: "earth-a2ce0", storageBucket: "earth-a2ce0.appspot.com", messagingSenderId: "33112054293", appId: "1:33112054293:web:801afc5e9473c7ba050c1c", measurementId: "G-6V50YYJBS2" }; if (firebase.apps.length === 0) { firebase.initializeApp(firebaseConfig); }; export default class ViroSample extends Component { constructor() { super(); this._exitViro = this._exitViro.bind(this); } render() { return ( <Provider store={store}> <FullNav /> </Provider> ); } // This function "exits" Viro by setting the navigatorType to UNSET. // not 100% this is needed _exitViro() { this.props.setNavType(UNSET); } } <file_sep>import {React, Component} from "react"; import * as THREE from "three"; const loader = new THREE.FontLoader(); const imageLoader = new THREE.TextureLoader(); let word; let mesh; let sphere; let cube; let changeColor; let scene; let Xscale; let Yscale; let geometry let BoxGeometry let shape; let currShape; let material; let colorOrTexture; export class Dual extends Component { componentDidUpdate(prevProps){ if(this.props.data !== prevProps.data) { scene.remove(mesh) if(shape === 'sphere') { scene.remove(sphere) } else { scene.remove(cube) } shape = this.props.data.shape word = this.props.data.text changeColor = this.props.data.colorSelected Xscale = this.props.data.textScaleX Yscale = this.props.data.textScaleY colorOrTexture = this.props.data.colorOrTexture material = this.props.data.material loader.load('https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( font ) { var geometry = new THREE.TextGeometry( word, { font: font, size: Xscale, height: Yscale } ); geometry.center(); if (colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: changeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: imageLoader.load(material), }); } mesh = new THREE.Mesh( geometry, material ); scene.add( mesh ); mesh.position.set(-1, -0.04, -0.01) if (shape === 'sphere') { geometry = new THREE.SphereGeometry( 0.7, 12, 8 ); sphere = new THREE.Mesh( geometry, material ); scene.add( sphere ); sphere.position.set(1.3, 0.20, 0.01); currShape = sphere } else { BoxGeometry = new THREE.BoxGeometry(1, 1, 1); cube = new THREE.Mesh( BoxGeometry, material ); scene.add( cube ); cube.position.set(1.3, 0.20, 0.01); currShape = cube } }) } } componentDidMount() { word = this.props.data.text; changeColor = this.props.data.colorSelected colorOrTexture = this.props.data.colorOrTexture material = this.props.data.material shape = this.props.data.shape scene = new THREE.Scene(); let camera = new THREE.PerspectiveCamera( 100, window.innerWidth/window.innerHeight, 0.1, 150 ); let renderer = new THREE.WebGLRenderer(); renderer.setSize( 1000, 500 ); this.mount.appendChild( renderer.domElement ); loader.load('https://threejs.org/examples/fonts/helvetiker_regular.typeface.json', function ( font ) { let textGeometry = new THREE.TextGeometry( word, { font: font, size: 0.6, height: 0.1, } ); textGeometry.center(); if (colorOrTexture === 'color') { material = new THREE.MeshStandardMaterial( { color: changeColor } ); } else { material = new THREE.MeshBasicMaterial({ map: imageLoader.load(material), }); } mesh = new THREE.Mesh( textGeometry, material ); scene.add( mesh ); mesh.position.set(-1, -0.04, -0.01) if (shape === 'sphere') { geometry = new THREE.SphereGeometry( 0.7, 12, 8 ); sphere = new THREE.Mesh( geometry, material ); scene.add( sphere ); sphere.position.set(1.3, 0.20, 0.01); currShape = sphere } else { BoxGeometry = new THREE.BoxGeometry(1, 1, 1); cube = new THREE.Mesh( BoxGeometry, material ); scene.add( cube ); cube.position.set(1.3, 0.20, 0.01); currShape = cube } const light = new THREE.HemisphereLight( 0xffffbb, 0x080820, 1 ); scene.add( light ); camera.position.z = 2; let animate = function () { requestAnimationFrame( animate ); mesh.rotation.x += 0.01; mesh.rotation.y += 0.01; mesh.rotation.z += 0.01; currShape.rotation.x += 0.01; currShape.rotation.y += 0.01; currShape.rotation.z += 0.01; renderer.render( scene, camera ); }; animate(); }) } render() { return ( <div><h1>Both Text & Shape </h1> <div ref={ref => (this.mount = ref)} /> </div> ) } }<file_sep>import React, { Component } from 'react'; import { Text, View, TouchableHighlight, TouchableOpacity, ScrollView, Image, } from 'react-native'; import { connect } from 'react-redux'; import styles from './Stylesheet'; import { setNavigation, AR_NAVIGATOR_TYPE, PROFILE_TYPE, } from './redux/navigation'; import { setProject } from './redux/project'; import firebase from 'firebase'; import 'firebase/firestore'; export class Explore extends Component { constructor() { super(); this.state = { users: [], }; this.handleProjectPress = this.handleProjectPress.bind(this); } componentDidMount() { firebase .firestore() .collection('users') .get() .then((snapshot) => { const users = []; snapshot.docs.map((doc) => users.push(doc.data())); const usersWithProjects = users.filter( (user) => user.projects.length > 0 ); console.log(usersWithProjects); this.setState({ users: usersWithProjects, }); }); this.setState({ state: this.state, }); } handleProjectPress(project) { this.props.setProject(project); this.props.setNavType(AR_NAVIGATOR_TYPE); } render() { console.log(this.props); return ( <View style={styles.outer}> <View style={styles.inner}> <Image style={styles.tinyLogo} source={require('./res/eARth.png')} /> <Text style={styles.titleText}>All Projects</Text> <Text style={styles.titleText}> Explore projects from other Earthlings: </Text> {this.state.users.length === 0 ? ( <Text>There are currently no users with projects.</Text> ) : ( <ScrollView> {this.state.users.map((user) => ( <View key={user.email} style={styles.card}> <Text>{user.username}</Text> {user.projects.map((project) => ( <TouchableOpacity key={project.id} style={styles.projectCard} onPress={() => this.handleProjectPress(project)} > <Text>{project.name}</Text> </TouchableOpacity> ))} </View> ))} </ScrollView> )} <TouchableHighlight style={styles.buttons} onPress={() => this.props.setNavType(PROFILE_TYPE)} > <Text style={styles.buttonText}>Profile </Text> </TouchableHighlight> </View> </View> ); } } const mapState = (state) => ({ navType: state.navigation.navigationType, }); const mapDispatch = (dispatch) => ({ setNavType: (type) => dispatch(setNavigation(type)), setProject: (project) => dispatch(setProject(project)), }); export default connect(mapState, mapDispatch)(Explore); <file_sep>import React, { Component } from "react"; import firebase from "firebase"; import "firebase/firestore"; import { Button } from "react-bootstrap"; class Projects extends Component { constructor() { super(); this.state = { projects: [], }; this.handleDelete = this.handleDelete.bind(this); } componentDidMount() { firebase .firestore() .collection("users") .doc(firebase.auth().currentUser.uid) .get() .then((snapshot) => { this.setState({ projects: snapshot.data().projects, }); }); this.setState({ state: this.state, }); } handleDelete(e) { const projectToDelete = JSON.parse(e.target.name); firebase .firestore() .collection("users") .doc(firebase.auth().currentUser.uid) .update({ projects: firebase.firestore.FieldValue.arrayRemove(projectToDelete), }); firebase .firestore() .collection("users") .doc(firebase.auth().currentUser.uid) .get() .then((snapshot) => { this.setState({ projects: snapshot.data().projects, }); }); } render() { return ( <div className="page"> <h1>Projects</h1> <Button variant="light" href="/create"> Create New Project </Button> <br /> <br /> <h3>My Projects</h3> {this.state.projects.length === 0 ? ( <p> You do not currently have any projects. Click the button above to create a project. </p> ) : ( <div className="user-projects-list"> {this.state.projects.map((project) => { return ( <div className="user-project-div" key={project.id}> <h4>{project.name}</h4> <h5>View: {project.view}</h5> {project.shape ? <h6>Shape: {project.shape}</h6> : null} {project.colorSelected ? ( <h6>Color: {project.colorSelected}</h6> ) : null} {project.animation ? ( <h6>Animation: {project.animation}</h6> ) : null} {project.animate ? <h6>Animate: {project.animate}</h6> : null} {project.text ? <h6>Text: {project.text}</h6> : null} {project.textScaleX ? ( <h6>Text Scale X: {project.textScaleX}</h6> ) : null} {project.textScaleY ? ( <h6>Text Scale Y: {project.textScaleY}</h6> ) : null} {project.textScaleZ ? ( <h6>Text Scale Z: {project.textScaleZ}</h6> ) : null} {project.shapeScaleX ? ( <h6>Shape Scale X: {project.shapeScaleX}</h6> ) : null} {project.shapeScaleY ? ( <h6>Shape Scale Y: {project.shapeScaleY}</h6> ) : null} {project.shapeScaleZ ? ( <h6>Shape Scale Z: {project.shapeScaleZ}</h6> ) : null} {project.fontSize ? ( <h6>Font Size: {project.fontSize}</h6> ) : null} {project.textColor ? ( <h6>Text Color: {project.textColor}</h6> ) : null} {project.sound ? <h6>Sound: {project.sound}</h6> : null} <Button variant="light" name={JSON.stringify(project)} onClick={this.handleDelete} > Delete this Project </Button> </div> ); })} </div> )} </div> ); } } export default Projects;
1147317040380ace202b6d5f975d50034cbcda12
[ "JavaScript", "Markdown" ]
23
JavaScript
2103-team-Earth/eARth2
5f300c8281c1571fb00a7c52e51490f93de9c190
579ea2d5f5f9280911719b28b82ad79a2461979e
refs/heads/master
<repo_name>msw1998/Car-Game<file_sep>/game.py import pygame import time, random pygame.init() pygame.mixer.init() #initializing mixer for music display_width = 1200 #setting up window width and height display_height = 700 black = (0, 0, 0) white = (255, 255, 255) red = (255, 0, 0) light_red = (200,0,0) light_green = (0,200,0) blue = (0,0,255) green = (0,255 ,0) car_width = 100 dodges = 0 crash_sound = pygame.mixer.Sound('Crash.ogg') #Loading sound for crash pygame.mixer.music.load('Jazz_in_Paris.ogg') gamedisplay = pygame.display.set_mode((display_width, display_height)) pygame.display.set_caption('Car') #Window title clock = pygame.time.Clock() carImage = pygame.image.load('car.jpg') objectimage = pygame.image.load('rocky.png') Fill = pygame.image.load('road.png') def dodged(count): font = pygame.font.SysFont(None , 25) text = font.render('Dodged: ' + str(count), True, blue ) gamedisplay.blit(text, (0,0)) def car(x, y): # displaying the car gamedisplay.blit(carImage, (x, y)) # drawing the background or can draw image on window def objects(objectx, objecty, objecth, objectw, color): # pygame.draw.rect(gamedisplay, color, [objectx, objecty , objecth, objectw] ) #we can use this code to draw a rect shaped object gamedisplay.blit(objectimage, (objectx, objecty)) #loading rock's image def text_objects(text, font): textSurface = font.render(text, True, white) return textSurface, textSurface.get_rect() def msg(t): largetext = pygame.font.Font('freesansbold.ttf', 50) textsurf, textrect = text_objects(t, largetext) textrect.center = (600, 540) gamedisplay.blit(textsurf, textrect) # display the msg pygame.display.update() time.sleep(2) gameloop() def msg_display(text): largetext = pygame.font.Font('freesansbold.ttf', 100) textsurf, textrect = text_objects(text, largetext) textrect.center = ((display_width * 0.5), (display_height * 0.5)) gamedisplay.blit(textsurf, textrect) # display the msg pygame.display.update() #time.sleep(2) #gameloop() def crash(): msg_display('You crashed') pygame.mixer.music.stop() pygame.mixer.Sound.play(crash_sound) #msg('Your score: ' + str(dodges)) def button(): mouse = pygame.mouse.get_pos() click = pygame.mouse.get_pressed() if 150 + 150 > mouse[0] > 150 and 500 + 70 > mouse[1] > 500: pygame.draw.rect(gamedisplay, green, (150, 500, 150, 70)) pygame.draw.rect(gamedisplay, light_red, (900, 500, 150, 70)) if click[0]== 1: gameloop() elif 900 + 150 > mouse[0] > 900 and 500 + 70 > mouse[1] > 500: pygame.draw.rect(gamedisplay, light_green, (150, 500, 150, 70)) pygame.draw.rect(gamedisplay, red, (900, 500, 150, 70)) if click[0] == 1: pygame.quit() quit() else: pygame.draw.rect(gamedisplay, light_green, (150, 500, 150, 70)) pygame.draw.rect(gamedisplay, light_red, (900, 500, 150, 70)) smalltext = pygame.font.Font('freesansbold.ttf', 25) textsurf, textrect = text_objects("Start", smalltext) textrect.center = (225, 535) Textsurf, Textrect = text_objects("Quit", smalltext) Textrect.center = (900+75, 500+35) gamedisplay.blit(Textsurf, Textrect) gamedisplay.blit(textsurf, textrect) pygame.display.update() def game_title(): title = True while title: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() #gamedisplay.blit(Fill, (-160, -50)) gamedisplay.fill(black) largetext = pygame.font.Font('freesansbold.ttf', 100) textsurf, textrect = text_objects("Rock Dodge", largetext) textrect.center = ((display_width * 0.5), (display_height * 0.5)) gamedisplay.blit(textsurf, textrect) #position of mouse button() clock.tick(15) def gameloop(): pygame.mixer.music.play(-1) x = (display_width * 0.45) y = (display_height * 0.709) x_change = 0 object_startx = random.randrange(0, display_width) object_starty = -10 object_speed = 7 object_width = 200 object_height = 140 dodges =0 file = open("High Score.txt", "w") exit_game = False while not exit_game: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() if event.type == pygame.KEYDOWN: # when key is pressed if event.key == pygame.K_LEFT: x_change = -7 elif event.key == pygame.K_RIGHT: x_change = 7 if event.type == pygame.KEYUP: if event.key == pygame.K_LEFT or event.key == pygame.K_RIGHT: x_change = 0 x += x_change gamedisplay.blit(Fill,(-160,-50)) # objects(objectx, objecty, objecth, objectw, color) objects(object_startx, object_starty, object_height, object_width, black) object_starty += object_speed car(x, y) dodged(dodges) if x > display_width - car_width or x < 0: crash() score() if object_starty > display_height: object_starty = 0 - object_height object_startx = random.randrange(0, (display_width - object_width)) dodges += 1 object_speed += 0.5 # object_width += (dodged * 1.2) if y < object_starty + object_height: if x < object_startx + object_width and x > object_startx or x + car_width > object_startx and x + car_width < object_startx + object_width: crash() score() dodged(dodges) pygame.display.update() # we can use flip() instead of update clock.tick(100) # adjusting frames per second def score(): msg('Your score: ' + str(dodges)) file.write("\nHigh score: " + str(dodges)) # file.close() game_title() gameloop() pygame.quit() quit()
34734fa11acd65674105861e9928b7ac67027ff0
[ "Python" ]
1
Python
msw1998/Car-Game
bbcdfd1c4fbd0db5b55f4ecd8b29be7c69affea7
a02d4b845d5ad102e7eb5b6cde75f53d33040a73
refs/heads/main
<repo_name>shubhamkumarsinha25/Array<file_sep>/count_no_of_uniqu_element.cpp class Solution{ public: //Complete this function //Function to return the count of non-repeated elements in the array. int countNonRepeated(int arr[], int n) { //Your code here unordered_map <int,int>m; for(int x=0;x<n;x++) { m[arr[x]]++; } int count=0; for(auto e:m) { if(e.second==1) { count++; } } return count; } }; <file_sep>/Max_Consecutive_one_in_binary array.cpp class Solution { public: int findMaxConsecutiveOnes(vector<int>& nums) { int res=0; int cur=0; for(int i=0;i<nums.size();i++) { if(nums[i]==0) { cur=0; } else { cur++; res=max(res,cur); } } return res; } };<file_sep>/First_Repeating_Element.cpp int firstRepeated(int arr[], int n) { //code here unordered_map<int,int>m; for(int i=0;i<n;i++) { m[arr[i]]++; } for(int i=0;i<n;i++) { if(m[arr[i]]>1) { return i+1; } } return -1; } <file_sep>/Equilibrium_Point.cpp int equilibriumPoint(long long a[], int n) { // Your code here int rsum=0; int lsum=0; int i=0; int j=n-1; if(n==1) { return 1; } while(i<j) { lsum+=a[j]; rsum+=a[i]; i++; j--; if(rsum<lsum) { rsum+=a[i]; i++; } if(lsum<rsum) { lsum+=a[j]; j--; } if(rsum==lsum && i==j) { return i+1; } } return -1; }<file_sep>/Check_if_two_arrays_are_equal_or_not.cpp bool check(vector<ll> arr, vector<ll> brr, int n) { //code here unordered_map<long long,long long>s; for(long long i=0;i<n;i++) { s[arr[i]]++; } for(long long i=0;i<n;i++) { s[brr[i]]--; if(s[brr[i]]==0){ s.erase(brr[i]); } } return s.size()==0; <file_sep>/Leader_in_an_array.cpp vector<int> Solution::solve(vector<int> &A) { int n=A.size(); vector<int>a; int current_leader=A[n-1]; a.push_back(current_leader); for(int i=n-2;i>=0;i--) { if(current_leader<A[i]) { current_leader=A[i]; a.push_back(current_leader); } } return a; } <file_sep>/Kth_smallest_element.cpp int lpartition(int arr[],int l,int h){ int p=arr[h]; int i=l-1; for(int j=l;j<=h-1;j++) { if(arr[j]<p) { i++; swap(arr[i],arr[j]); } } swap(arr[i+1],arr[h]); return i+1; } int kthSmallest(int arr[], int n, int k){ // Your code here int l=0; int h=n-1; while(l<=h){ int p=lpartition(arr,l,h); if(p==k-1){ return arr[p]; } else if(p>k-1) { h=p-1; } else{ l=p+1; } } return -1; }<file_sep>/Hashing_for_pair.cpp int sumExists(int arr[], int N, int sum) { unordered_set<int>s; for(int i=0;i<N;i++) { if(s.find((sum-arr[i]))!=s.end()) { return true; } s.insert(arr[i]); } return false; }<file_sep>/Rotate_Array_k_time.cpp void revers(int arr[],int s,int e) { while(s<e) { swap(arr[s++],arr[e--]); } } void rotateArr(int arr[], int d, int n){ // code here revers(arr,0,d-1); revers(arr,d,n-1); revers(arr,0,n-1); } <file_sep>/Trapping_of_rain_water.cpp int trappingWater(int arr[], int n){ int lmax[n]; int rmax[n]; int res=0; lmax[0]=arr[0]; rmax[n-1]=arr[n-1]; if(n==0) { return 0; } //find left max and store in lmax array for(int i=1;i<n;i++) { lmax[i]=max(lmax[i-1],arr[i]); } //find right max and store in right max array for(int i=n-2;i>=0;i--) { rmax[i]=max(rmax[i+1],arr[i]); } for(int i=1;i<n-1;i++) { res+=(min(rmax[i],lmax[i])-arr[i]); } return res; }<file_sep>/Intersection_of_two_sorted_arrays.cpp vector<int> printIntersection(int arr1[], int arr2[], int N, int M) { int i=0; int j=0; vector<int>v; while(i<N && j<M) { if(i>0&&arr1[i-1]==arr1[i]) { i++; continue; } if(arr1[i]<arr2[j]) { i++; } else if(arr1[i]>arr2[j]) { j++; } else{ v.push_back(arr1[i]); i++;j++; } } return v; }<file_sep>/Print_Non_Repeated_Elements.cpp class Solution{ public: // arr[]: input array // n: size of array //Function to return non-repeated elements in the array. vector<int> printNonRepeated(int arr[],int n) { //Your code here unordered_map <int,int>m; vector<int>v; for(int x=0;x<n;x++) { m[arr[x]]++; } for(auto i=0;i<n;i++) { if(m[arr[i]]==1) { v.push_back(arr[i]); } } return v; } };<file_sep>/Maximum_sum_SubArray.cpp class Solution { public: int maxSubArray(vector<int>& nums) { int res=nums[0]; int temp=nums[0]; int n=nums.size(); if(n==0) { return 0; } for(int i=1;i<n;i++) { temp=max(temp+nums[i],nums[i]); res=max(temp,res); } return res; } };<file_sep>/Intersection_of_two_arrays.cpp int NumberofElementsInIntersection (int a[], int b[], int n, int m ) { unordered_map<int,int>h; int c=0; for(int i=0;i<n;i++) { h[a[i]]++; } for(int i=0;i<m;i++) { if(h.count(b[i])) { c++; h.erase(b[i]); } } return c; } <file_sep>/Maximum_Product_subarray.cpp class Solution { public: int maxProduct(vector<int>& nums) { int res=nums[0]; int maxtemp=nums[0]; int mintemp=nums[0]; if(nums.size()==0) { return 0; } for(int i=1;i<nums.size();i++) { if(nums[i]<0) { swap(maxtemp,mintemp); } maxtemp=max(maxtemp*nums[i],nums[i]); mintemp=min(mintemp*nums[i],nums[i]); res=max(maxtemp,res); } return res; } };<file_sep>/Rearrange_Array_Alternately.cpp void rearrange(long long *arr, int n) { // Your code here int Max=arr[n-1]+1; int max_i=n-1; int min_i=0; for(int i=0;i<n;i++) { if(i%2==0){ arr[i]+=(arr[max_i]%Max)*Max; max_i--; } else{ arr[i]+=(arr[min_i]%Max)*Max; min_i++; } } for(int i=0;i<n;i++) { arr[i]/=Max; } }<file_sep>/Rotate_Array.cpp class Solution { public: vector<int> revers(vector<int>a,int l,int h) { while(l<h) { int temp=a[l]; a[l]=a[h]; a[h]=temp; l++; h--; } return a; } void rotate(vector<int>& nums, int k) { int n=nums.size(); k=k%n; nums=revers(nums,0,n-1); nums=revers(nums,k,n-1); nums=revers(nums,0,k-1); } };<file_sep>/Find_max1_&max2.cpp vector<int> largestAndSecondLargest(int sizeOfArray, int arr[]){ int max = INT_MIN, max2= INT_MIN; for(int i=0;i<sizeOfArray;i++){ if(max<arr[i]){ max2=max; max=arr[i]; } else if(max2<arr[i]&&max!=arr[i]) { max2=arr[i]; } } if(max2<0){ max2=-1; } vector<int>ans; ans.push_back(max); ans.push_back(max2); return ans; }
1a4cf3d16ce7f295a96bb751802695198c9103c5
[ "C++" ]
18
C++
shubhamkumarsinha25/Array
d0d1215613b0606cd778bf8e046270aae8e3fb05
0e24f1d70d12c9e38b571f74dc5ad093cc605493
refs/heads/master
<file_sep>const generateQuotationHtml = ({ title }: { title: string }) => ` <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>${title} PDF</title> <style> html, body { background-color: #fff; font-size: 16px; font-family: "Roboto", sans-serif; max-width: 80vw; margin: 0 auto; } table, th, td { border-collapse: collapse; text-align: center; } p { margin: 0; } a { color: #3277c8; text-decoration-skip-ink: none; display: inline-block; } .logo { width: 300px; position: relative; left: -30px; } .title { font-family: TimesNewRoman, "Times New Roman", Times, Baskerville, Georgia, serif; font-size: 36px; font-weight: 700; } .billing-content { margin: auto; border: 1px solid; width: 100%; } .billing-content > tbody > tr:first-child { border: 1px solid; } .billing-content > tbody > tr > th { height: 25px; } .billing-content > tbody > tr > td { height: 30px; } .block { display: block; } .inline-block { display: inline-block; } .float-right { float: right; } .text-right { text-align: right; } .mt-1 { margin-top: 4px; } .mt-2 { margin-top: 8px; } .mt-3 { margin-top: 12px; } .mt-5 { margin-top: 20px; } .mt-15 { margin-top: 60px; } .mb-1 { margin-bottom: 4px; } .mb-2 { margin-bottom: 8px; } .mx-auto { margin: 0 auto; } .pos-relative { position: relative; } .pos-absolute { position: absolute; } .right { right: 0; } .bottom { bottom: 0; } .wd-150px { width: 150px; } .with-divider { position: relative; } .with-divider::after { content: ""; display: block; width: 100px; position: absolute; padding-top: 2px; right: 0; border-bottom: 1px solid; } .text-center { text-align: center; } </style> </head> <body> <div class="mt-15"> <span class="title block text-center">${title}</span> </div> <span class="block mt-5 text-right"> Date: 2021/8/1 </span> <span class="block mt-2 mb-1 text-right"> Currency: NTD </span> <table class="billing-content"> <tbody> <tr> <th style="width: 50%" colspan="2">Item</th> <th style="width: 10%">Quantity</th> <th style="width: 20%">Unit Price</th> <th style="width: 20%">Total</th> </tr> <tr> <td style="width: 30%"> Nanny & Housekeeper </td> <td style="width: 20%"> /month</td> <td style="width: 10%"> 1 </td> <td style="width: 20%"> 95,000 </td> <td style="width: 20%"> 95,000 </td> </tr> <tr> <td style="width: 30%"> Consultant Service Fee </td> <td style="width: 20%"> - </td> <td style="width: 10%"> 1 </td> <td style="width: 20%"> 18,000 </td> <td style="width: 20%"> 18,000 </td> </tr> </tbody> </table> <div class="mt-15 float-right"> <div class="text-right"> <span class="inline-block">Subtotal:</span> <span class="inline-block wd-150px text-right with-divider"> 113,000 </span> </div> <div class="text-right"> <span class="inline-block">Total:</span> <span class="inline-block wd-150px mt-2 text-right"> 113,000 </span> </div> </div> </body> </html> `; export default generateQuotationHtml; <file_sep># Next.js Html-to-Pdf ## Demo https://next-html-to-pdf.vercel.app/ ## API ### Host Name https://next-html-to-pdf.vercel.app/ ### `/api/pdf` * **Method:** `GET` * **Query Parameters:** | Field | Type | Description | | :---: | :---: | :--- | | title | String | Title of the PDF | * **Request Example:** `https://[HOST_NAME]/api/pdf?title=abc` * **Success Response: 200** | Field | Type | Description | | :---: | :---: | :--- | | - | Buffer | PDF in binary | * **Error Response: 500** | Field | Type | Description | | :---: | :---: | :--- | | message | String | Error message. | * **Error Response Example:** ```json { "message": "Unexpected server error" } ``` ## Installation 1. `$ npm install` 2. Install VSCode extensions: [ESLint](https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint), [Prettier](https://marketplace.visualstudio.com/items?itemName=esbenp.prettier-vscode) ## Usage 1. `$ npm run dev`: starts a Next.js server in development mode 2. `$ npm run build`: builds the application for production usage 3. `$ npm run start`: starts a Next.js server in production mode 4. `$ npm run lint`: manually checks files inside src folder ## Deploy to cloud platform [Vercel](https://vercel.com/) support the deployment of `Next.js` ## Notes: 1. Fix format error automatically on save 2. Use Aribnb lint rule ## Refs: 1. [Origial idea about local server pdf generation](https://www.npmjs.com/package/html-pdf-node-ts) 2. [About Solving Bugs while running CI/CD: Run "PUPPETEER_PRODUCT=firefox npm install" or "PUPPETEER_PRODUCT=firefox yarn install"](https://github.com/vercel/vercel/discussions/4903) 3. [next-typescript-boilerplate](https://github.com/andy770921/next-typescript-boilerplate) 4. [PDF file download using Axios](https://stackoverflow.com/questions/41938718/how-to-download-files-using-axios)<file_sep>import type { NextApiRequest, NextApiResponse } from 'next'; import { PDFOptions } from 'puppeteer'; import { Promise as PromiseBluebird } from 'bluebird'; import hb from 'handlebars'; import chromium from 'chrome-aws-lambda'; import generateQuotationHtml from '@templates/quotation'; type CallBackType = (pdf: any) => void; interface OptionsProps extends PDFOptions { args?: string[]; } interface FileWithUrl { url: string; content?: never; } interface FileWithContent { url?: never; content: string; } type FileType = FileWithUrl | FileWithContent; async function generatePdf(file: FileType, options?: OptionsProps, callback?: CallBackType) { const browser = await chromium.puppeteer.launch({ args: [...chromium.args, '--hide-scrollbars', '--disable-web-security'], defaultViewport: chromium.defaultViewport, executablePath: await chromium.executablePath, headless: true, ignoreHTTPSErrors: true, }); const page = await browser.newPage(); if (file.content) { const template = hb.compile(file.content, { strict: true }); const result = template(file.content); const html = result; await page.setContent(html); } else { await page.goto(file.url as string, { waitUntil: 'networkidle0', }); } return PromiseBluebird.props(page.pdf(options)) .then(async (data) => { await browser.close(); return Buffer.from(Object.values(data)); }) .asCallback(callback); } export default async function handler(req: NextApiRequest, res: NextApiResponse) { return new Promise<void>((resolve) => { if (req.method !== 'GET' || !req.query.title) { res.status(400).json({ message: 'Invalid request' }); resolve(); return; } const html = generateQuotationHtml({ title: req.query.title as string }); generatePdf({ content: html }, { format: 'a4' }) .then((pdfBuffer) => { res.setHeader('Content-Type', 'application/pdf'); res.setHeader('Content-Disposition', `attachment; filename=${req.query.title}.pdf`); res.status(200).send(pdfBuffer); resolve(); }) .catch(() => { res.status(500).json({ message: 'Unexpected server error' }); resolve(); }); }); } <file_sep>export interface TransListResponse { CN: string; EN: string; TW: string; id: string; key: string; pages: string[]; } <file_sep>/* eslint-disable import/prefer-default-export */ import axios, { AxiosResponse, AxiosError } from 'axios'; // Ref: https://github.com/axios/axios/issues/815#issuecomment-453963910 axios.interceptors.response.use( (response) => { return response; }, (error) => { if ( error.request.responseType === 'blob' && error.response.data instanceof Blob && error.response.data.type?.toLowerCase().includes('json') ) { return new Promise((resolve, reject) => { const reader = new FileReader(); reader.onload = () => { // eslint-disable-next-line no-param-reassign error.response.data = JSON.parse(reader.result as string); resolve(Promise.reject(error)); }; reader.onerror = () => { reject(error); }; reader.readAsText(error.response.data); }); } return Promise.reject(error); } ); const handleAxiosResponse = <T, U = { message: string }>(fn: (...params: any[]) => Promise<AxiosResponse>) => (...params: any[]) => fn(...params) .then((res: AxiosResponse) => res.data as T) .catch((error: AxiosError<U>) => { const errorData = error.response?.data; // eslint-disable-next-line @typescript-eslint/no-throw-literal if (errorData) throw errorData; throw error; }); export const apiGetPdf = (params: { title: string }) => handleAxiosResponse<Blob>(axios.get)('/api/pdf', { responseType: 'blob', params });
5cede4f3c14ffa2d2c2ad3e3443587016f52a7f5
[ "Markdown", "TypeScript" ]
5
TypeScript
andy770921/next-html-to-pdf
30146c3a167082bc63a4102054c72f0140a649bd
986cbbf108fde8346c96ede160d8ed226f820952
refs/heads/main
<file_sep>import card_data from '../data/card-data.json' import bg_desktop from '../assets/bg_desktop.jpg' import bg_mobile from '../assets/bg_mobile.jpg' import React from "react"; import Card from "../components/Card"; import Grid from "@material-ui/core/Grid"; import {useStyles} from "./landing_styles"; import { BrowserView, MobileView, isBrowser, isMobile } from "react-device-detect"; const LandingPage = () => { const classes = useStyles() return ( <div> {isBrowser ? <div className={classes.background_image_cnt} style={{height: '15rem'}}> <img src={bg_desktop} alt={'pikachu'} className={classes.background_image}/> </div> : <div className={classes.background_image_cnt} style={{height: '100%'}}> <img src={bg_mobile} alt={'pikachu'} className={classes.background_image}/> </div> } <Grid container style={{padding: '3rem'}}> <Grid container justify="center" spacing={4} className={classes.card_container}> {card_data.pokemon.map(item => { return ( <Grid item xs={12} sm={6} md={4} lg={3}> <Card name={item.name} moves={item.moves} image={item.image} stats={item.stats} /> </Grid> ) })} </Grid> </Grid> </div> ) } export default LandingPage <file_sep>import {Paper, Grid, Typography} from "@material-ui/core"; import React from "react"; import {Divider} from '@material-ui/core'; import {useStyles} from "./styles"; const Card = (props) => { const classes = useStyles() return ( <Grid container direction={'column'} alignItems={'center'} className={classes.container}> <Grid item xs={12}> <Paper className={classes.paper_img}> <img src={props.image} alt={props.name}/> </Paper> </Grid> <Typography className={classes.name}>{props.name}</Typography> <Grid container xs={12} justify={'center'} style={{marginBottom: 15}}> <Grid container xs={5} direction='column' alignItems={'center'}> <Typography style={{marginBottom: 10}}>Moves</Typography> <Grid item> {props.moves.map(move => <Typography style={{fontSize: 14}}>‣ {move}</Typography>)} </Grid> </Grid> <Grid item> <Divider orientation="vertical"/> </Grid> <Grid container xs={5} direction='column' alignItems={'center'}> <Typography style={{marginBottom: 10}}>Stats</Typography> <Grid container direction={'row'} justify={'center'}> <Typography className={classes.stats_text}>speed:</Typography> <Typography className={classes.stats_number}>{props.stats.speed}</Typography> </Grid> <Grid container direction={'row'} justify={'center'}> <Typography className={classes.stats_text}>attack:</Typography> <Typography className={classes.stats_number}>{props.stats.attack}</Typography> </Grid> <Grid container direction={'row'} justify={'center'}> <Typography className={classes.stats_text}>defense:</Typography> <Typography className={classes.stats_number}>{props.stats.defense}</Typography> </Grid> </Grid> </Grid> </Grid> ) } export default Card <file_sep>import {makeStyles} from "@material-ui/core/styles"; const useStyles = makeStyles({ container: { border: '1px solid gray', borderRadius: '5px', padding: '10px', transition: "transform 0.15s ease-in-out", "&:hover": { transform: "scale3d(1.05, 1.05, 1)" }, }, paper_img: { display: 'flex', alignItems: 'center', justifyContent: 'center', border: '1px solid gray', borderRadius: '2px', width: '10rem', height: '10rem', marginTop: '15px' }, name: { fontSize: '2rem', marginTop: 10, fontFamily: 'Pokemon-Hollow', marginBottom: 10 }, stats_text: { fontSize: 14, fontWeight: 'bold', marginRight: 5, width: 55 }, stats_number: { fontSize: 14, } }); export {useStyles}
1f9b8f15debe5a1038027de86561330738273859
[ "JavaScript" ]
3
JavaScript
danpoletaev/test_task
e522c6138963f014e5923bffd953f778ef0ae934
f2f2fb887e368ee59d8b95df8f8bb2a290eb9342
refs/heads/master
<file_sep>package com.yitu.sturnus; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class SturnusApplication { public static void main(String[] args) { SpringApplication.run(SturnusApplication.class, args); } } <file_sep>package com.yitu.sturnus.service; import org.springframework.stereotype.Service; public class RedisService { /** * ZSET中的key */ public static final String MILLS_KEY = "mills_key"; /** * 取ZSET时间范围,即[ts-300s, ts] */ public static final long DURATION = 5 * 60 * 1000; /** * 每次往set里面插入的数据量 */ public static final int SET_SIZE = 3; /** * 从set中取数数量 */ public static final int SET_RANGE_SIZE = 1; } <file_sep># RedisTimeOutResearch (doing) redis time out 调研 # 打包并且打镜像 以下均在`RedisTimeOutResearch`目录下执行 - `cd sturnus && mvn clean package -DskipTests=true` - `cd sturnus && docker build --build-arg JAR_FILE=sturnus-v0.1.jar -t sturnus .` - 修改 `develop/docker-compose.yml`里面的`${redis_ip}`为您的本机ip - `cd develop && docker-compose up -f develop/docker-compose.yml -d` # 问题进展 线上用的redis,在压力大的会出现`RedisTimeOut`的异常,但我们的系统要求高可用 && 高性能嘛,就想着尽量避免这种情况,现在也做了本地cache,但是还是会有`RedisTimeOut`的问题存在。 分析了一个星期,把经历梳理了一下,并且做一个分享。 - Spring版本: `2.1.7.RELEASE` - Redis版本: `6.0.7` - Java的redis-client: Lettuce 我自己又单独写了一个小project来测试。redis相关的配置如下 ``` spring: redis: database: 0 host: ${REDIS_HOST:127.0.0.1} port: ${REDIS_PORT:6379} lettuce: pool: max-active: 300 max-wait: -1 max-idle: 100 min-idle: 10 timeout: 1000 ``` 然后用的`docker-compose`进行的部署 ``` CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 3ed653397fd8 sturnus "java -jar /usr/shar…" 3 hours ago Up 3 hours sturnus-redis-app 6e1e63a9eb34 redis:6.0.7 "docker-entrypoint.s…" 3 hours ago Up 3 hours 0.0.0.0:12300->6379/tcp redis ``` 然后用到了`blade`模拟`redis`处理慢的问题 ``` blade create docker network delay --time 930 --interface eth0 --local-port 6379 --container-id 6e1e63a9eb34 ``` 然后application侧打印的log如下 ``` 2020-09-04 20:43:17.101 WARN 1 --- [nio-8080-exec-3] o.s.d.r.c.l.LettuceConnectionFactory : Validation of shared connection failed. Creating a new connection. 2020-09-04 20:43:17.101 ERROR 1 --- [nio-8080-exec-4] c.y.s.w.RedisController : add ts: 1599223394768 error, errMsg: org.springframework.dao.QueryTimeoutException: Redis command timed out; nested exception is io.lettuce.core.RedisCommandTimeoutException: io.lettuce.core.RedisCommandTimeoutException: Command timed out after 1 second(s) at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:70) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.connection.lettuce.LettuceExceptionConverter.convert(LettuceExceptionConverter.java:41) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.PassThroughExceptionTranslationStrategy.translate(PassThroughExceptionTranslationStrategy.java:44) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.FallbackExceptionTranslationStrategy.translate(FallbackExceptionTranslationStrategy.java:42) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.connection.lettuce.LettuceConnection.convertLettuceAccessException(LettuceConnection.java:268) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.connection.lettuce.LettuceZSetCommands.convertLettuceAccessException(LettuceZSetCommands.java:903) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.connection.lettuce.LettuceZSetCommands.zAdd(LettuceZSetCommands.java:72) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.connection.DefaultedRedisConnection.zAdd(DefaultedRedisConnection.java:679) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.core.DefaultZSetOperations.lambda$add$0(DefaultZSetOperations.java:53) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:224) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.core.RedisTemplate.execute(RedisTemplate.java:184) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.core.AbstractOperations.execute(AbstractOperations.java:95) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.core.DefaultZSetOperations.add(DefaultZSetOperations.java:53) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at org.springframework.data.redis.core.DefaultBoundZSetOperations.add(DefaultBoundZSetOperations.java:59) ~[spring-data-redis-2.1.10.RELEASE.jar!/:2.1.10.RELEASE] at com.yitu.sturnus.web.RedisController.addZSet(RedisController.java:80) [classes!/:?] at jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[?:?] at jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[?:?] at jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[?:?] at java.lang.reflect.Method.invoke(Method.java:566) ~[?:?] at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:190) [spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE] at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:138) [spring-web-5.1.9.RELEASE.jar!/:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:104) [spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:892) [spring-webmvc-5.1.9.RELEASE.jar!/:5.1.9.RELEASE] at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:797) [spring-webmvc-5.1.9.RELEASE.jar!/:5 ``` 整个链路是 redis-client发送请求 -> 建立connection(从connectionPools取) -> 网络传输 -> redis中命令排队 -> redis命令执行 -> 网络传输 -> redis-client拿到响应 现在可以通过[`blade`](https://github.com/chaosblade-io/chaosblade)工具排查应该不是client连接池的问题。 感谢 @weiyinfu 提供的思路 1. slowlog_len 大一些, 去看slowlog里面执行较慢的命令的耗时 2. 取高峰的qps, 预估命令排队的时间 3. 分析redis的大object的大小, 看是不是网络传输的时延长 接下来的排查工作,围绕网络延迟,丢包,cpu打满三个情况去测试的 - 目前的应用设置的redis的timeout是 1000ms - 请求"/add"共执行了三种操作 1. zadd 当前时间戳 2. zrangebyscore 取出[ts-2000, ts]的所有时间 3. incrby 对取得的所有的时间size进行increment mock线上的docker容器有 ``` CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 1e94b191cdbf sturnus "java -jar /usr/shar…" 20 minutes ago Up 20 minutes sturnus-redis-app 3c331867f63f redis:6.0.7 "docker-entrypoint.s…" 20 minutes ago Up 20 minutes 0.0.0.0:6379->6379/tcp redis 38a904d034b3 grafana/grafana:latest "/run.sh" 20 minutes ago Up 20 minutes 0.0.0.0:3000->3000/tcp grafana ``` - 网络延时实验 ``` mock线上对redis进行延时 800ms blade create docker network delay --time 800 --interface eth0 --local-port 6379 --container-id 3c331867f63f {"code":200,"success":true,"result":"98f83fcb20fe2e1d"} 发送请求"http://server_ip:8080/add" 查看后台log同真实线上的情况 监控截图如下图 1.1 为了进一步mock真实场景,需要减少延时试一下 先删除之前的延时 blade destroy 98f83fcb20fe2e1d 对redis创建延时600ms blade create docker network delay --time 600 --interface eth0 --local-port 6379 --container-id 3c331867f63f 同样用sturnus进行脚本发送 得到的log同真实线上的情况 监控截图如图 1.2 继续降低时延为 500ms, redis-client还会报time out blade create docker network delay --time 500 --interface eth0 --local-port 6379 --container-id 3c331867f63f 继续降低时延为100ms, redis-client还会报time out blade create docker network delay --time 100 --interface eth0 --local-port 6379 --container-id 3c331867f63f 继续降低时延为5ms, redis-client还是会报time out blade create docker network delay --time 5 --interface eth0 --local-port 6379 --container-id 3c331867f63f 继续降低时延为1ms, redis-client还是会报time out blade create docker network delay --time 1 --interface eth0 --local-port 6379 --container-id 3c331867f63f 销毁时延后,发送请求,仅仅需要 8ms 到 12ms, 怀疑这个blade无法精确控制时延 ``` - 图1.1 ![图1.1](./imgs/img1.png) - 图1.2 ![图1.2](./imgs/img2.png) - 网络丢包实验 ``` 丢包率80% blade create docker network loss --interface eth0 --percent 80 --container-id 3c331867f63f 丢包情况下,也会得到同样的线上的log ``` - <del> cpu打满实验 </del> ``` blade create docker cpu fullload --cpu-percent 100 --container-id 3c331867f63f cpu打满情况下,app能成功拿到redis的数据. 去除此种情况 ``` - key信息获取 ``` redis-cli --bigkeys # Scanning the entire keyspace to find biggest keys as well as # average sizes per key type. You can use -i 0.1 to sleep 0.1 sec # per 100 SCAN commands (not usually needed). [00.00%] Biggest set found so far '"1599132285379:mills"' with 1 members [00.07%] Biggest set found so far '"1599137644259:mills"' with 2 members [00.14%] Biggest set found so far '"1599131702663:mills"' with 4 members [01.53%] Biggest set found so far '"1599139819737:mills"' with 5 members [11.42%] Biggest set found so far '"1599139809653:mills"' with 6 members [31.79%] Biggest string found so far '"zsetSize"' with 3 bytes [64.79%] Biggest zset found so far '"mills_key"' with 1541289 members [64.89%] Sampled 1000000 keys so far [88.58%] Biggest string found so far '"listSize"' with 7 bytes -------- summary ------- Sampled 1541062 keys in the keyspace! Total key length in bytes is 29280146 (avg len 19.00) Biggest string found '"listSize"' has 7 bytes Biggest set found '"1599139809653:mills"' has 6 members Biggest zset found '"mills_key"' has 1541289 members 0 lists with 0 items (00.00% of keys, avg size 0.00) 0 hashs with 0 fields (00.00% of keys, avg size 0.00) 2 strings with 10 bytes (00.00% of keys, avg size 5.00) 0 streams with 0 entries (00.00% of keys, avg size 0.00) 1541059 sets with 1542417 members (100.00% of keys, avg size 1.00) 1 zsets with 1541289 members (00.00% of keys, avg size 1541289.00) ``` - debug object ``` redis-cli> debug object mill_keys Value at:0x7f3656ef9840 refcount:1 encoding:skiplist serializedlength:33908363 lru:5442738 lru_seconds_idle:389 ``` ## Useful Link - [grafana redis monitor](https://github.com/RedisTimeSeries/grafana-redis-datasource) - [分析redis的key](https://blog.csdn.net/qmhball/article/details/86063466)<file_sep>version: "3" services: redis: image: redis:6.0.7 restart: always container_name: redis ports: - 6379:6379 command: redis-server /usr/local/etc/redis/redis.conf volumes: - /root/yubing/redis-data/:/data/ - /root/yubing/redis-6.0.7.conf:/usr/local/etc/redis/redis.conf - /etc/localtime:/etc/localtime - /etc/timezone:/etc/timezone sturnus-app: image: sturnus ports: - 8080:8080 container_name: sturnus environment: - REDIS_HOST=${redis_ip} - REDIS_PORT=6379 depends_on: - redis grafana: container_name: grafana image: grafana/grafana:latest ports: - '3000:3000' environment: - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin - GF_AUTH_ANONYMOUS_ENABLED=true - GF_AUTH_BASIC_ENABLED=false - GF_ENABLE_GZIP=true - GF_INSTALL_PLUGINS=redis-datasource volumes: - ./provisioning/datasources:/etc/grafana/provisioning/datasources <file_sep>package com.yitu.sturnus; import org.junit.Test; import org.springframework.boot.test.context.SpringBootTest; @SpringBootTest class SturnusApplicationTests { @Test void contextLoads() { } } <file_sep>package com.yitu.sturnus.web; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ResponseBody; /** * 简单调用redis 排查 */ @Slf4j @Controller public class RedisSampleController { @Autowired private RedisTemplate redisTemplate; private static final String REDIS_KEY = "TEST_REDIS"; private static final String PREFIEX_LIST = "LIST:"; private static final String PREFIEX_VALUE = "VALUE:"; @GetMapping("/exec-redis-cmd") @ResponseBody public String redisExecSample() { try { redisTemplate.boundListOps(PREFIEX_LIST + REDIS_KEY).rightPush("2333"); redisTemplate.boundValueOps(PREFIEX_VALUE + REDIS_KEY).set("2333"); return "redis exec cmd success"; } catch (Exception e) { log.error("exec redis cmd error, timestamp: " + System.currentTimeMillis(), e); return "redis exec cmd error"; } } } <file_sep>FROM adoptopenjdk/openjdk8:alpine-slim VOLUME /tmp ENV TimeZone=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TimeZone /etc/localtime && echo $TimeZone > /etc/timezone EXPOSE 8080 ENTRYPOINT ["java", "-jar", "/usr/share/redis-time-out-research/sturnus.jar"] ARG JAR_FILE ADD target/${JAR_FILE} /usr/share/redis-time-out-research/sturnus.jar<file_sep>package com.yitu.sturnus.demo; import java.util.ArrayList; import java.util.List; import java.util.stream.IntStream; public class SyncRetry { private final Object monitor = new Object(); private Object connection = new Object(); private synchronized void validateConnection(int id) { System.out.println("id: " + id + " enter"); synchronized (this.monitor) { System.out.println("id: " + id + " try to reset connection"); if (this.connection != null) { resetConnection(id); } } } private synchronized void resetConnection(int id) { synchronized (this.monitor) { if (this.connection != null) { this.connection = null; System.out.println("id: " + id + " reset the connection"); } } } private synchronized void loopEnter(int id, int cnt) { if (cnt > 10) { return; } System.out.println("id: " + id + " loop cnt: " + cnt); loopEnter(id, cnt + 1); } public static void main(String[] args) throws InterruptedException { List<Thread> threads = new ArrayList<>(); SyncRetry syncRetry = new SyncRetry(); IntStream.range(0, 5).forEach(id -> { threads.add(new Thread(() -> { // syncRetry.validateConnection(id); syncRetry.loopEnter(id, 0); })); }); for (Thread thread : threads) { thread.start(); } for (Thread thread : threads) { thread.join(); } } } <file_sep>mvn clean package -DskipTests=true docker build --build-arg JAR_FILE=sturnus-v0.1.jar -t sturnus . docker save sturnus > sturnus.tar scp ./sturnus.tar root@10.40.58.64:/root/yubing/ # 1 # 停掉 sturnus, 删除服务 docker load < sturnus.tar
3197b19eb0dc1472494be2d25c297731bb22f579
[ "YAML", "Markdown", "Java", "Dockerfile", "Shell" ]
9
Java
Draymonders/RedisTimeOutResearch
8b97abf3e9501af6991f277b97630d93d642dc82
d0e1cea0696e56f9985da2ff983b52317b448988
refs/heads/master
<file_sep>using UAHub; namespace UAHub.Views { public sealed partial class Section1ListPage : PageBase { } } <file_sep>using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AppStudio.Common; using AppStudio.Common.Actions; using AppStudio.Common.Commands; using AppStudio.Common.Navigation; using AppStudio.DataProviders; using AppStudio.DataProviders.Menu; using AppStudio.DataProviders.Html; using AppStudio.DataProviders.LocalStorage; using UAHub.Sections; namespace UAHub.ViewModels { public class MainViewModel : ObservableBase { public MainViewModel(int visibleItems) { PageTitle = "UA Hub"; Section1 = new ListViewModel<LocalStorageDataConfig, MenuSchema>(new Section1Config()); Section11 = new ListViewModel<LocalStorageDataConfig, MenuSchema>(new Section11Config()); Section18 = new ListViewModel<LocalStorageDataConfig, MenuSchema>(new Section18Config()); Section24 = new ListViewModel<LocalStorageDataConfig, MenuSchema>(new Section24Config()); Section26 = new ListViewModel<LocalStorageDataConfig, HtmlSchema>(new Section26Config(), visibleItems); Actions = new List<ActionInfo>(); if (GetViewModels().Any(vm => !vm.HasLocalData)) { Actions.Add(new ActionInfo { Command = new RelayCommand(Refresh), Style = ActionKnownStyles.Refresh, Name = "RefreshButton", ActionType = ActionType.Primary }); } } public string PageTitle { get; set; } public ListViewModel<LocalStorageDataConfig, MenuSchema> Section1 { get; private set; } public ListViewModel<LocalStorageDataConfig, MenuSchema> Section11 { get; private set; } public ListViewModel<LocalStorageDataConfig, MenuSchema> Section18 { get; private set; } public ListViewModel<LocalStorageDataConfig, MenuSchema> Section24 { get; private set; } public ListViewModel<LocalStorageDataConfig, HtmlSchema> Section26 { get; private set; } public RelayCommand<INavigable> SectionHeaderClickCommand { get { return new RelayCommand<INavigable>(item => { NavigationService.NavigateTo(item); }); } } public DateTime? LastUpdated { get { return GetViewModels().Select(vm => vm.LastUpdated) .OrderByDescending(d => d).FirstOrDefault(); } } public List<ActionInfo> Actions { get; private set; } public bool HasActions { get { return Actions != null && Actions.Count > 0; } } public async Task LoadDataAsync() { var loadDataTasks = GetViewModels().Select(vm => vm.LoadDataAsync()); await Task.WhenAll(loadDataTasks); OnPropertyChanged("LastUpdated"); } private async void Refresh() { var refreshDataTasks = GetViewModels() .Where(vm => !vm.HasLocalData) .Select(vm => vm.LoadDataAsync(true)); await Task.WhenAll(refreshDataTasks); OnPropertyChanged("LastUpdated"); } private IEnumerable<DataViewModelBase> GetViewModels() { yield return Section1; yield return Section11; yield return Section18; yield return Section24; yield return Section26; } } } <file_sep>using Windows.UI.Xaml.Navigation; using AppStudio.Common; using AppStudio.DataProviders.LocalStorage; using AppStudio.DataProviders.Menu; using UAHub; using UAHub.Sections; using UAHub.ViewModels; namespace UAHub.Views { public sealed partial class Section1ListPage : PageBase { public ListViewModel<LocalStorageDataConfig, MenuSchema> ViewModel { get; set; } public Section1ListPage() { this.ViewModel = new ListViewModel<LocalStorageDataConfig, MenuSchema>(new Section1Config()); this.InitializeComponent(); } protected async override void LoadState(object navParameter) { await this.ViewModel.LoadDataAsync(); } } } <file_sep>using UAHub; namespace UAHub.Views { public sealed partial class Section25ListPage : PageBase { } } <file_sep>using UAHub; namespace UAHub.Views { public sealed partial class Section8ListPage : PageBase { } } <file_sep>using UAHub; namespace UAHub.Views { public sealed partial class Section2ListPage : PageBase { } } <file_sep># ua-hub-windows UA Hub Win8.1 app I don't own the content inside the app. All rights reserved by their respective owners. You need VS 2013 to compile the app for Win 8.1. (or VS 2015 to compile the Win 10 version) <file_sep>using UAHub; namespace UAHub.Views { public sealed partial class Section20ListPage : PageBase { } }
7390496a3db9dae1ad28cfa656e6c643ce7e541b
[ "Markdown", "C#" ]
8
C#
glebanych/ua-hub-windows
e1ee0b1aab3be37902c6c1489dfcf31f5aa61ca8
30e5b56e248290ef4d33994cc2bd6e24280e5dbc
refs/heads/master
<repo_name>WildcatGames/FirstGame<file_sep>/Block.cs using System; using System.Drawing; namespace FirstGame{ class Block{ //Static Variables readonly private static int EdgeSize = 100; //Properties public Color Col{ get; private set; } public int Value{ get; private set; } public int XLocation{ get; set; } public int YLocation{ get; set; } //Constructor(s) public Block(int val, int xLoc, int yLoc){ this.Value = val; this.XLocation = xLoc; this.YLocation = yLoc; if(val == 2){ this.Col = Color.Tan; } else { this.Col = Color.Yellow; } } //Methods public void changeColor(){ switch(this.Col.ToString){ case "Tan": this.Col = Color.Yellow; case "Yellow": this.Col = Color.Gold; case "Gold": this.Col = Color.Orange; case "Orange": this.Col = Color.OrangeRed; case "OrangeRed": this.Col = Color.Red; case "Red": this.Col = Color.LightBlue; case "LightBlue": this.Col = Color.SkyBlue; case "SkyBlue": this.Col = Color.RoyalBlue; case "RoyalBlue": this.Col = Color.Blue; case "Blue": this.Col = Color.Gray; default: } } public void doubleValue(){ this.Value *= 2; } } }
9021925bd431bc185858d6e1282ebbd9beb53676
[ "C#" ]
1
C#
WildcatGames/FirstGame
1757fd598e0191124f77ac06add873ea438be8de
5bd474cac7b2397cf63aa9d8e7026d00c184cd65
refs/heads/master
<repo_name>PunchGrey/4kube<file_sep>/fortune/Dockerfile FROM alpine:latest RUN apk add fortune ADD start.sh /bin/start.sh ENTRYPOINT /bin/start.sh<file_sep>/test/note.sh # переключение namespace sudo kubectl config set-context $(sudo kubectl config current-context) --namespace NAME_SPACE # удаление pod используя label sudo kubectl delete po -l creation_method=manual # создаёт согласно файлу в определённом namespace sudo kubectl create -f kubia-manual.yaml -n custom-namespace #Переадресация локального сетевого порта на порт в модуле kubectl port-forward kubia-manual 8888:8080 # обновляет ресурс тем, что указано в файле. kubectl apply -f kubia-ingress-tls.yaml #--generator=run-pod / v1 , который по- ручает команде kubectl создать модуль напрямую, без какого-либо контроллера репликации или аналогичного ему kubectl run dnsutils --image=tutum/dnsutils --generator=run-pod/v1 # help sudo kubectl explain pods.spec.volumes.nfs<file_sep>/aid/Dockerfile FROM alpine RUN apk add curl bind-tools ENTRYPOINT ["top", "-b"]
bb50b790337e3747a6e4031abca8792b795be36f
[ "Dockerfile", "Shell" ]
3
Dockerfile
PunchGrey/4kube
614e67091236a079661d93529e9b3258f35a5bea
4a291e38af24cc3ff357b9be481ca2a5267fbae1
refs/heads/master
<file_sep>// // recentMessageViewController.swift // Text Back App (Free) // // Created by <NAME> on 2/25/18. // Copyright © 2018 Hackintosh. All rights reserved. // import UIKit var userMessages: [String] = ["this is message 1", "this is message 2","this is message 3","this is message 4","this is message 5","this is message 6","this is message 7","this is message 8","this is message 9","this is message 10","this is message 11","this is message 12","this is message 13","this is message 14"] var messageIndex = 0; class recentMessageViewController: UIViewController,UITableViewDataSource, UITableViewDelegate{ @IBOutlet weak var tableView: UITableView! var myString = String() override func viewDidLoad() { super.viewDidLoad() let indexPath = IndexPath(row: userMessages.count - 1, section: 0) tableView.beginUpdates() tableView.insertRows(at: [indexPath], with: .automatic) tableView.endUpdates() } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return (userMessages.count) //counts the messages from userMassages } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{//displays cells //UserDefaults.standard.set(userMessages[indexPath.row], forKey: "myName") let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) cell.textLabel?.text = userMessages[indexPath.row] return(cell) } func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCellEditingStyle, forRowAt indexPath: IndexPath) {//deletes rows if (editingStyle == .delete){ userMessages.remove(at: indexPath.item) //removes message tableView.deleteRows(at: [indexPath], with: .automatic) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { messageIndex = indexPath.row //cell that was selected } } <file_sep>// // helpViewController.swift // Text Back App (Free) // // Created by <NAME> on 2/26/18. // Copyright © 2018 Hackintosh. All rights reserved. // import UIKit class helpViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func rightSwipe(_ sender: UISwipeGestureRecognizer) { } @IBAction func leftSwipe(_ sender: UISwipeGestureRecognizer) { } } <file_sep>// // ViewController.swift // Text Back App (Free) // // Created by Hackintosh on 2/8/18. // Copyright © 2018 Hackintosh. All rights reserved. // import UIKit class ViewController: UIViewController, UITextFieldDelegate { @IBOutlet weak var enterNewMessage: UITextField! //Enter message text field @IBOutlet weak var company: UILabel! //comapny label @IBOutlet weak var overlay: UIView! //overlay for active/inactive @IBOutlet weak var viewNewMessage: UITextView! //Message display area @IBOutlet weak var ubeView: UIView! //holds main view for user @IBOutlet weak var leadingC: NSLayoutConstraint!//constraint for left side of view @IBOutlet weak var trailingC: NSLayoutConstraint! //constraint for right side of view @IBOutlet weak var mainBackgroundView: UIView! /******** variables ***********/ var hamburgerMenusIsVisible = false//sets menu to close /******** Buttons/Switch functions ***********/ override func viewDidLoad() { super.viewDidLoad() enterNewMessage.layer.shadowOffset = CGSize(width:0, height:4) enterNewMessage.layer.shadowRadius = 4 enterNewMessage.layer.shadowOpacity = 0.4 self.overlay.isHidden = true //Hide overlay on setup enterNewMessage.layer.shadowRadius = 4 enterNewMessage.layer.shadowOpacity = 0.4 self.overlay.isHidden = true //Hide overlay on setup self.enterNewMessage.delegate = self } /******** Buttons/Switch functions ***********/ @IBAction func activeSwitch(_ sender: UISwitch) { if (sender.isOn == true){ self.company.textColor = UIColor.black //change company text color to black self.overlay.isHidden = true //hide overlay when switch toggled }else{ self.overlay.isHidden = false //shows overlay self.overlay.backgroundColor = UIColor.black.withAlphaComponent(0.8) //change background overlay color to black self.company.textColor = UIColor.white //change company text color to white } } @IBAction func newMessageButton(_ sender: Any) { insertNewMessage() //Run insertNewMessage function enterNewMessage.resignFirstResponder()//Hides keyboard } @IBAction func hamburgerBtnTapped(_ sender: Any) {//hamburger menu button if !hamburgerMenusIsVisible{ //If menu is not visible, display menu leadingC.constant = 350 trailingC.constant = -350 hamburgerMenusIsVisible = true }else{//if menu is visible move the menu back leadingC.constant = 0 trailingC.constant = 0 hamburgerMenusIsVisible = false } UIView.animate(withDuration: 0.2, delay: 0.0, options: .curveEaseIn, animations: {//animation for menu self.view.layoutIfNeeded() }){(animationComplete) in print("The animation is complete!")// verify manu is called and displayed } } func insertNewMessage(){ if (enterNewMessage.text != ""){ //Check if text field is empty let updatedMessage = enterNewMessage.text self.enterNewMessage.textColor = UIColor.black //change company text color to gray enterNewMessage.text = ""//dclears text field viewNewMessage.text = updatedMessage //displays new message userMessages.append(updatedMessage!) //userMessages[messageIndex] = updatedMessage! } //enterNewMessage.attributedPlaceholder = NSAttributedString(string:updatedMessage!, attributes: [NSAttributedStringKey.foregroundColor: UIColor.lightGray]) //Changes the placeholder text } //Hide keyboard when the users touches outside keyboard override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?){ self.view.endEditing(true) } //presses the return key func textFieldShouldReturn(_ textField: UITextField) -> Bool { enterNewMessage.resignFirstResponder()//hides keyboard insertNewMessage() //Run insertNewMessage function return(true) } }
1f4e99459907bc768c88dc570825ef3268a8a0c0
[ "Swift" ]
3
Swift
kendallryanlewis/Text-Back-App-Free-
786faa0d3ecd264366df47064b58badee343df71
3531e67e67f23082f0153b20bf2762034a6034af
refs/heads/main
<file_sep># This code is made by using the on-line library for Ultrasonic sensor and servo motor. # For the Ultrasonic senor, it is modified by using the pigpio library. import time import pigpio import subprocess import math import numpy as np class Ultraservo: """ This class encapsulates a type of acoustic ranger. In particular the type of ranger with separate trigger and echo pins. A pulse on the trigger initiates the sonar ping and shortly afterwards a sonar pulse is transmitted and the echo pin goes high. The echo pins stays high until a sonar echo is received (or the response times-out). The time between the high and low edges indicates the sonar round trip time. """ def __init__(self, pi, servo, trigger, echo, OFFSET=0, MIN_ANGLE = 10, MAX_ANGLE = 160, STEP = 10, TooLong=23509): """ The class is instantiated with the Pi to use and the gpios connected to the trigger and echo pins. If the echo is longer than toolong it is assumed to be an outlier and is ignored. """ self.pi = pi self.trigger = trigger self.echo = echo self.TooLong = TooLong self.OFFSET = OFFSET self.STEP = STEP self.MIN_ANGLE = MIN_ANGLE self.MAX_ANGLE = MAX_ANGLE self.servoPin = servo self.high_tick = None self.echo_time = TooLong self.echo_tick = pi.get_current_tick() self.trigger_mode = pi.get_mode(trigger) self.echo_mode = pi.get_mode(echo) pi.set_PWM_frequency(self.servoPin, 50) pi.set_PWM_range(self.servoPin, 40000) self.initPosition(1500) pi.set_mode(trigger, pigpio.OUTPUT) pi.set_mode(echo, pigpio.INPUT) self.cb = pi.callback(echo, pigpio.EITHER_EDGE, self._cbf) self.inited = True def _cbf(self, gpio, level, tick): if level == 1: self.high_tick = tick elif level == 0: if self.high_tick is not None: echo_time = tick - self.high_tick if echo_time < self.TooLong: self.echo_time = echo_time self.echo_tick = tick else: self.echo_time = self.TooLong self.high_tick = None def initPosition(self, init_duty=1500): self.pi.set_PWM_dutycycle(self.servoPin,init_duty) def read(self): """ The returned reading is the number of microseconds for the sonar round-trip. round trip cms = round trip time / 1000000.0 * 34030 """ if self.inited: return self.echo_time else: return None def readAngleRange(self, startAngle, endAngle, STEP = 0): startAngle = int(startAngle) endAngle = int(endAngle) if STEP == 0: step = self.STEP else: step = STEP if(startAngle > endAngle): step = self.STEP * -1 startAngle = max(startAngle, self.MAX_ANGLE) endAngle = min(endAngle, self.MIN_ANGLE) else: startAngle = min(startAngle, self.MIN_ANGLE) endAngle = max(endAngle, self.MAX_ANGLE) def trig(self): """ Triggers a reading. """ if self.inited: self.pi.gpio_trigger(self.trigger) def readAngle(self, angle, sample = 1): self.moveServo(angle) distance = [] for i in range(0, sample, 1): self.trig() distance.append(self.read()) time.sleep(0.03) # for sound travel 0.03 seconds, to detect obstacles 5 meters away report_angle = self.OFFSET - angle if(report_angle>360): report_angle -= 360 if(report_angle<=0): report_angle += 360 return ( report_angle, np.mean(distance) / pow(10,6) * 34330 / 2 / 100) def moveServo(self, angle): if angle < self.MIN_ANGLE: angle = self.MIN_ANGLE if angle > self.MAX_ANGLE: angle = self.MAX_ANGLE duty = 1500 + (angle * 22.2) self.pi.set_PWM_dutycycle(self.servoPin,duty) def cancel(self): if self.inited: self.inited = False self.cb.cancel() self.pi.set_mode(self.trigger, self.trigger_mode) self.pi.set_mode(self.echo, self.echo_mode) if __name__ == "__main__": pi = pigpio.pi() while pi.connected == False: subprocess.run("sudo pigpiod", shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) pi = pigpio.pi() us_front_left = Ultraservo(pi, 12, 24, 25,360) us_front_right = Ultraservo(pi, 13, 5, 4, 120) #180 us_back = Ultraservo(pi, 20, 6, 18, 240) #270 us_back.moveServo(90) us_front_left.moveServo(90) us_front_right.moveServo(90) ''' text = None while text != '': text = input("Please confirm that all servo are set to 90 degree \nthen Press enter key:") while True: for angle in range(0,160, 10): print('front_left : ', angle, us_front_left.readAngle(angle)) print('front_right: ', angle, us_front_right.readAngle(angle)) print(' back: ', angle, us_back.readAngle(angle)) for angle in range(160,0, -10): print('front_left : ',us_front_left.readAngle(angle)) print('front_right: ',us_front_right.readAngle(angle)) print(' back: ',us_back.readAngle(angle)) ''' <file_sep># This code is based on the pigpio library example code. (http://abyz.me.uk/rpi/pigpio/examples.html#Python%20code) # Modified by <NAME> (<EMAIL>) for using the Multiplexer with the nine Ultrasonic sensors. import time import pigpio class ranger: """ This class encapsulates a type of acoustic ranger. In particular the type of ranger with separate trigger and echo pins. A pulse on the trigger initiates the sonar ping and shortly afterwards a sonar pulse is transmitted and the echo pin goes high. The echo pins stays high until a sonar echo is received (or the response times-out). The time between the high and low edges indicates the sonar round trip time. """ def __init__(self, pi, trigger, echo, Mux_S0, Mux_S1, Mux_S2, Mux_S3): """ The class is instantiated with the Pi to use and the gpios connected to the trigger and echo pins. """ self.pi = pi self._trig = trigger self._echo = echo self._s0 = Mux_S0 self._s1 = Mux_S1 self._s2 = Mux_S2 self._s3 = Mux_S3 self._ping = False self._high = None self._time = None self._triggered = False self._trig_mode = pi.get_mode(self._trig) self._echo_mode = pi.get_mode(self._echo) self._muxS0_mode = pi.get_mode(self._s0) self._muxS1_mode = pi.get_mode(self._s1) self._muxS2_mode = pi.get_mode(self._s2) self._muxS3_mode = pi.get_mode(self._s3) pi.set_mode(self._trig, pigpio.OUTPUT) pi.set_mode(self._echo, pigpio.INPUT) pi.set_mode(self._s0, pigpio.OUTPUT) pi.set_mode(self._s1, pigpio.OUTPUT) pi.set_mode(self._s2, pigpio.OUTPUT) pi.set_mode(self._s3, pigpio.OUTPUT) self._cb = pi.callback(self._trig, pigpio.EITHER_EDGE, self._cbf) self._cb = pi.callback(self._echo, pigpio.EITHER_EDGE, self._cbf) self._inited = True def _cbf(self, gpio, level, tick): if gpio == self._trig: if level == 0: # trigger sent self._triggered = True self._high = None else: if self._triggered: if level == 1: self._high = tick else: if self._high is not None: self._time = tick - self._high self._high = None self._ping = True def read(self): """ Triggers a reading. The returned reading is the number of microseconds for the sonar round-trip. round trip cms = round trip time / 1000000.0 * 34030 """ if self._inited: self._ping = False self.pi.gpio_trigger(self._trig) start = time.time() while not self._ping: if (time.time()-start) > 5.0: return 20000 time.sleep(0.001) return self._time else: return None def cancel(self): """ Cancels the ranger and returns the gpios to their original mode. """ if self._inited: self._inited = False self._cb.cancel() self.pi.set_mode(self._trig, self._trig_mode) self.pi.set_mode(self._echo, self._echo_mode) self.pi.set_mode(self._s0, self._muxS0_mode) self.pi.set_mode(self._s1, self._muxS1_mode) self.pi.set_mode(self._s2, self._muxS2-mode) self.pi.set_mode(self._s3, self._muxS3-mode) def mux(self, SENSORS): COUNT = 0 results = [0,0,0,0,0,0,0,0,0] for counter in range(0, SENSORS): if COUNT == 8: self.pi.write(self._s0, 0) self.pi.write(self._s1, 0) self.pi.write(self._s2, 0) self.pi.write(self._s3, 1) elif COUNT == 7: self.pi.write(self._s0, 1) self.pi.write(self._s1, 1) self.pi.write(self._s2, 1) self.pi.write(self._s3, 0) elif COUNT == 6: self.pi.write(self._s0, 0) self.pi.write(self._s1, 1) self.pi.write(self._s2, 1) self.pi.write(self._s3, 0) elif COUNT == 5: self.pi.write(self._s0, 1) self.pi.write(self._s1, 0) self.pi.write(self._s2, 1) self.pi.write(self._s3, 0) elif COUNT == 4: self.pi.write(self._s0, 0) self.pi.write(self._s1, 0) self.pi.write(self._s2, 1) self.pi.write(self._s3, 0) elif COUNT == 3: self.pi.write(self._s0, 1) self.pi.write(self._s1, 1) self.pi.write(self._s2, 0) elif COUNT == 2: self.pi.write(self._s0, 0) self.pi.write(self._s1, 1) self.pi.write(self._s2, 0) self.pi.write(self._s3, 0) elif COUNT == 1: self.pi.write(self._s0, 1) self.pi.write(self._s1, 0) self.pi.write(self._s2, 0) self.pi.write(self._s3, 0) else: self.pi.write(self._s0, 0) self.pi.write(self._s1, 0) self.pi.write(self._s2, 0) self.pi.write(self._s3, 0) time.sleep(0.01) # 0.06, 0.03 trip = self.read() result = ((trip/2)/ 1000000.0 *34330) / 100 # change unit cm to m results[COUNT] = result COUNT += 1 time.sleep(0.01) # 0.06, 0.03 return results if __name__ == "__main__": import time import pigpio import Mux_sonar pi = pigpio.pi() sonar = Mux_sonar.ranger(pi, 18, 24, 20, 21, 19, 16) end = time.time() + 600.0 SENSORS = 9 r = 1 while time.time() < end: print (str(r)+'._______________________') sonar.mux(SENSORS) r += 1 time.sleep(0.03) sonar.cancel() pi.stop() <file_sep># This code is made by using the VL53L0X refference example code. # Modified by <NAME> (<EMAIL>) for using the pigpio libraty. import pigpio import time import VL53L0X # GPIO for Sensor 1 shutdown pin sensor1_shutdown = 6 # GPIO for Sensor 2 shutdown pin sensor2_shutdown = 5 pi = pigpio.pi() shutdown1_mode = pi.get_mode(sensor1_shutdown) shutdown2_mode = pi.get_mode(sensor2_shutdown) # Setup GPIO for shutdown pins on each VL53L0X pi.set_mode(sensor1_shutdown, pigpio.OUTPUT) pi.set_mode(sensor2_shutdown, pigpio.OUTPUT) # Set all shutdown pins low to turn off each VL53L0X pi.set_mode(sensor1_shutdown, shutdown1_mode) pi.set_mode(sensor2_shutdown, shutdown2_mode) pi.write(sensor1_shutdown, 0) pi.write(sensor2_shutdown, 0) # Keep all low for 500 ms or so to make sure they reset time.sleep(0.50) # Create one object per VL53L0X passing the address to give to each. tof = VL53L0X.VL53L0X(address=0x2B) tof1 = VL53L0X.VL53L0X(address=0x2D) # Set shutdown pin high for the first VL53L0X then # call to start ranging pi.write(sensor1_shutdown, 1) time.sleep(0.50) tof.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE) # Set shutdown pin high for the second VL53L0X then # call to start ranging pi.write(sensor2_shutdown, 1) time.sleep(0.50) tof1.start_ranging(VL53L0X.VL53L0X_BETTER_ACCURACY_MODE) ''' timing = tof.get_timing() if (timing < 20000): timing = 20000 # To get a distance data, you can call "tof.get_distance()" function. distance = tof.get_distance() distance1 = tof1.get_distance() time.sleep(timing/1000000.00) tof1.stop_ranging() pi.write(sensor2_shutdown, 0) tof.stop_ranging() pi.write(sensor1_shutdown, 0) pi.stop() '''
f06d29238ae2b95cfedf0d999caf1c482fed0c5a
[ "Python" ]
3
Python
hjw0903/Obstacle_Detection
423d38baddd4441d2afd6b7100d088b542a0e785
e8ce36eb7dae772bf0a54b3431ad0fd3d95fe3a2
refs/heads/master
<file_sep>const express = require('express'); const bodyParser = require('body-parser'); const cookieParser = require('cookie-parser'); const mongoose = require('mongoose'); const config = require('./config/key'); const { User } = require('./models/user'); const user = require('./models/user'); const auth = require('./middleware/auth'); const app = express(); mongoose.connect(config.mongoURI, {useNewUrlParser:true, useUnifiedTopology:true, useCreateIndex:true, useFindAndModify:false}) .then(()=>console.log('DB connected')) .catch(error=> console.log(error)); app.use(bodyParser.urlencoded({extended:true})); app.use(bodyParser.json()) app.use(cookieParser()); // app.get('/', (req, res)=>{ // res.send("hello server here"); // }) app.get('/api/user/auth',auth, (req, res)=>{ //console.log(req.user); res.status(200).json({ _id: req.user._id, isAuth: true, email: req.user.email, name: req.user.name, lastname: req.user.lastname, role:req.user.role }) }) app.post('/api/users/register', (req, res)=>{ //console.log(req.body); const user = new User(req.body); user.save((err, doc)=>{ if(err) return res.json({success:false, err}); res.status(200).json({success:true, userData:doc}); }); }) app.post('/api/users/login', (req, res)=>{ //find the email User.findOne({email: req.body.email}, (err, user)=>{ if(!user){ return res.json({ loginSuccess: false, message: 'Auth failed! email not found.' }); } //check password is same as the original user.comparePassword(req.body.password, (err, isMatch)=>{ if(!isMatch){ return res.json({loginSuccess:false, message:"Wrong Password"}) } }) user.generateToken((err, user)=>{ if(err) return res.status(400).send(err); res.cookie("x_auth", user.token) .status(200) .json({ loginSuccess: true }); }) }) }) app.get('/api/user/logout',auth, (req, res)=>{ User.findOneAndUpdate({_id:req.user._id}, {token:""}, (err, doc)=>{ if(err) return res.json({success:false, err}) return res.status(200).json({success:true}) }) }) const PORT = process.env.PORT || 5000; app.listen(PORT, ()=>{ console.log("server running on port ", PORT); });
3cf0234a0639ba8db9d841a66c5ca33338af6458
[ "JavaScript" ]
1
JavaScript
AhsanRaza007/react-blog
bddec7d1bcecea296b64d91e50133ca3f879f5ff
a257a0935af15f604cb52e8371182f5441283494
refs/heads/master
<file_sep>module.exports = { publicPath: './', pages: { index: { entry: 'src/main.js', title: '设计', //放要改的title名 }, }, css: { loaderOptions: { postcss: { plugins: [ require('postcss-pxtorem')({ // 换算的基数 默认为37.5,一般不建议修改它,使用vant ui框架中也是默认37.5 rootValue: 37.5, // 忽略转换正则匹配项,插件会转化所有的样式的px。比如引入了三方UI,也会被转化. //项目中有不需要自动转换成PX的样式,就在此添加,如: .vant 表示 .vant 开头的都不会转换 selectorBlackList: [], propList: ['*'], //属性的选择器,*表示通用 }), ] } } }, devServer: { port: '80', open: true, proxy: { '/api': { target: 'http://192.168.1.85:9090', changeOrigin: true, pathRewrite: { '^/api': '/' } } } }, }
948501a3556be06cf2319c339ae2a09604480786
[ "JavaScript" ]
1
JavaScript
x-y-c-king/st
5f38c2047fea1fa4480403d9b0110ec6b0d6012e
86c7b3e996c0b64fd417550446f7f7af4868ea07
refs/heads/master
<repo_name>JohanBeekers/video-library<file_sep>/src/app/providers/settings.service.ts import { Injectable } from "@angular/core"; import { ElectronService } from "./electron.service"; import * as path from "path"; interface Settings { movieDirectory: string; seriesDirectory: string; theme: string; movieExtentions: string[]; omdbApiKey: string; } @Injectable({ providedIn: "root" }) export class SettingsService { private static SETTINGS_FILE = "settings.json"; static INITIAL_SETTINGS: Settings = { movieDirectory: "movies/", seriesDirectory: "series/", theme: "dark", movieExtentions: [".avi", ".mkv", ".mp4", ".wmv", "VIDEO_TS.IFO"], omdbApiKey: "2e3f3f5a" }; public settings: Settings; constructor(private electronService: ElectronService) { this.loadApplicationSettings(); } public loadApplicationSettings() { if (this.electronService.isElectron()) { if (!this.electronService.fs.existsSync(SettingsService.SETTINGS_FILE)) { this.resetSettingsToFactoryAndSave(); } else { try { this.settings = JSON.parse(<any>this.electronService.fs.readFileSync(SettingsService.SETTINGS_FILE)); } catch (error) { console.error(error); this.settings = SettingsService.INITIAL_SETTINGS; } } } } public saveApplicationSettings() { if (this.electronService.isElectron()) { this.electronService.fs.writeFileSync(SettingsService.SETTINGS_FILE, JSON.stringify(this.settings, null, 4)); } } public resetSettingsToFactoryAndSave() { this.settings = JSON.parse(JSON.stringify(SettingsService.INITIAL_SETTINGS)); this.saveApplicationSettings(); } public resetSettingsToFactory() { this.settings = JSON.parse(JSON.stringify(SettingsService.INITIAL_SETTINGS)); } } <file_sep>/src/app/models/media-group.ts import * as path from "path"; import { ElectronService } from "../providers/electron.service"; import { MediaEntity } from "./media-entity"; export class MediaGroup extends MediaEntity { public children: MediaEntity[]; constructor(groupPath: string, electronService: ElectronService, children: MediaEntity[] = []) { super(groupPath, electronService); this._name = groupPath.split(path.sep).pop(); this._infoPath = `${groupPath}${path.sep}groupinfo.json`; this._imagePath = `${groupPath}${path.sep}poster.jpg`; this._type = "group"; this.children = children; this.load(); } } <file_sep>/src/app/components/header/header.component.ts import { Component, OnInit, Output, EventEmitter, Input } from "@angular/core"; import { ViewMode } from "../media-list/media-list.component"; import { ElectronService } from "../../providers/electron.service"; import { MediaType } from "../home/home.component"; @Component({ selector: "app-header", templateUrl: "./header.component.html", styleUrls: ["./header.component.scss"] }) export class HeaderComponent implements OnInit { private static VIEW_MODE_STORAGE_KEY = "viewMode"; private static VIEW_MODE_DEFAULT_VALUE: ViewMode = "grid"; private static SHOW_GROUPS_STORAGE_KEY = "showGroups"; private static SHOW_GROUPS_DEFAULT_VALUE: boolean = true; private static GRID_SCALE_STORAGE_KEY = "gridScale"; private static GRID_SCALE_DEFAULT_VALUE: number = 1; private static LIST_SCALE_STORAGE_KEY = "listScale"; private static LIST_SCALE_DEFAULT_VALUE: number = 1; private static SYNC_SCALE_STORAGE_KEY = "syncScale"; private static SYNC_SCALE_DEFAULT_VALUE: boolean = false; @Output() public openSettingsClick: EventEmitter<void> = new EventEmitter(); @Output() public scaleChange: EventEmitter<number> = new EventEmitter(); @Output() public triggerSearch: EventEmitter<string> = new EventEmitter(); public get scale(): number { return this._scale; } public set scale(value: number) { this._scale = value; this.storeScaleValue(); this.scaleChange.emit(value); } private _scale: number; @Output() public viewModeChange: EventEmitter<ViewMode> = new EventEmitter(); public get viewMode(): ViewMode { return this._viewMode; } public set viewMode(value: ViewMode) { this._viewMode = value; localStorage.setItem(HeaderComponent.VIEW_MODE_STORAGE_KEY, value); this.updateScaleValue(); this.viewModeChange.emit(value); } private _viewMode: ViewMode; public get syncScale(): boolean { return this._syncScale; } public set syncScale(value: boolean) { this._syncScale = value; localStorage.setItem(HeaderComponent.SYNC_SCALE_STORAGE_KEY, value.toString()); this.storeScaleValue(); } private _syncScale: boolean; @Output() public activeTabChange: EventEmitter<MediaType> = new EventEmitter(); private _activeTab: MediaType; public get activeTab(): MediaType { return this._activeTab; } public set activeTab(value: MediaType) { this._activeTab = value; this.activeTabChange.emit(value); } @Output() public showGroupsChange: EventEmitter<boolean> = new EventEmitter(); public get showGroups(): boolean { return this._showGroups; } public set showGroups(value: boolean) { this._showGroups = value; localStorage.setItem(HeaderComponent.SHOW_GROUPS_STORAGE_KEY, value.toString()); if (value === true) { this.searchText = ""; } this.showGroupsChange.emit(value); } private _showGroups: boolean; public searchText: string; constructor(private electronService: ElectronService) { } ngOnInit(): void { const viewMode: ViewMode = <ViewMode>localStorage.getItem(HeaderComponent.VIEW_MODE_STORAGE_KEY); const syncScale: string = localStorage.getItem(HeaderComponent.SYNC_SCALE_STORAGE_KEY); const showGroups: string = localStorage.getItem(HeaderComponent.SHOW_GROUPS_STORAGE_KEY); this.activeTab = "movies"; this.viewMode = viewMode ? viewMode : HeaderComponent.VIEW_MODE_DEFAULT_VALUE; this.syncScale = syncScale ? syncScale === "true" : HeaderComponent.SYNC_SCALE_DEFAULT_VALUE; this.showGroups = showGroups ? showGroups === "true" : HeaderComponent.SHOW_GROUPS_DEFAULT_VALUE; } /** * Stores the current value of the scale for the current viewMode in local storage. */ private storeScaleValue() { if (this.syncScale) { localStorage.setItem(HeaderComponent.GRID_SCALE_STORAGE_KEY, this.scale.toString()); localStorage.setItem(HeaderComponent.LIST_SCALE_STORAGE_KEY, this.scale.toString()); } else { switch (this.viewMode) { case "grid": localStorage.setItem(HeaderComponent.GRID_SCALE_STORAGE_KEY, this.scale.toString()); break; case "list": localStorage.setItem(HeaderComponent.LIST_SCALE_STORAGE_KEY, this.scale.toString()); break; } } } /** * Updates the scale value to the value stored in local storage. * Used after changing between view modes. */ private updateScaleValue() { switch (this.viewMode) { case "grid": const gridScale: string = localStorage.getItem(HeaderComponent.GRID_SCALE_STORAGE_KEY); this.scale = gridScale ? parseFloat(gridScale) : HeaderComponent.GRID_SCALE_DEFAULT_VALUE; break; case "list": const listScale: string = localStorage.getItem(HeaderComponent.LIST_SCALE_STORAGE_KEY); this.scale = listScale ? parseFloat(listScale) : HeaderComponent.LIST_SCALE_DEFAULT_VALUE; break; } } public search() { if (this.searchText) { this.showGroups = false; } this.triggerSearch.emit(this.searchText); } public minimize() { if (this.electronService.remote.BrowserWindow.getFocusedWindow()) { this.electronService.remote.BrowserWindow.getFocusedWindow().minimize(); } } public isMaximized(): boolean { if (this.electronService.remote.BrowserWindow.getFocusedWindow()) { return this.electronService.remote.BrowserWindow.getFocusedWindow().isMaximized(); } else { return false; } } public maximize() { if (this.electronService.remote.BrowserWindow.getFocusedWindow()) { if (this.isMaximized()) { this.electronService.remote.BrowserWindow.getFocusedWindow().unmaximize(); } else { this.electronService.remote.BrowserWindow.getFocusedWindow().maximize(); } } } public close() { if (this.electronService.remote.BrowserWindow.getFocusedWindow()) { this.electronService.remote.BrowserWindow.getFocusedWindow().close(); } } public reload() { if (this.electronService.remote.BrowserWindow.getFocusedWindow()) { this.electronService.remote.BrowserWindow.getFocusedWindow().reload(); } } public openDevTools() { if (this.electronService.remote.BrowserWindow.getFocusedWindow()) { this.electronService.remote.BrowserWindow.getFocusedWindow().webContents.openDevTools(); } } } <file_sep>/src/app/models/movie.ts import { MediaEntity, MediaEntitySaveData } from "./media-entity"; import { ElectronService } from "../providers/electron.service"; import * as path from "path"; export interface MovieSaveData extends MediaEntitySaveData { year: string; runtime: string; genre: string; actors: string; } export class Movie extends MediaEntity<MovieSaveData> { private _fileName: string; public get fileName(): string { return this._fileName; } constructor(dirName: string, fileName: string, electronService: ElectronService) { super(dirName, electronService); this._fileName = fileName; this._name = this.path.split(path.sep).pop(); this._infoPath = `${this.path}${path.sep}movieinfo.json`; this._imagePath = `${this.path}${path.sep}poster.jpg`; this._type = "movie"; this.load(); } } <file_sep>/CHANGELOG.md ### Changelog All notable changes to this project will be documented in this file. Dates are in day-month-year format. #### 1.0.0 (8-10-2018) - Initial release <file_sep>/src/app/components/media-details/media-details.component.ts import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { MediaEntity, MediaEntitySaveData } from "../../models/media-entity"; import { MovieSaveData, Movie } from "../../models/movie"; import { MediaGroup } from "../../models/media-group"; import { FieldClickEvent } from "../omdb-suggestions/omdb-suggestions.component"; import { ElectronService } from "../../providers/electron.service"; import * as path from "path"; import { Season } from "../../models/season"; import { Series, SeriesSaveData } from "../../models/series"; @Component({ selector: "app-media-details", templateUrl: "./media-details.component.html", styleUrls: ["./media-details.component.scss"] }) export class MediaDetailsComponent implements OnInit { @Output() public closeClick: EventEmitter<void> = new EventEmitter(); @Input() public get media(): MediaEntity { return this._media; } public set media(value: MediaEntity) { this._media = value; this.initForm(); if (value instanceof Series) { this.selectedSeasonIndex = value.seasons.findIndex(season => season !== undefined); } else { this.selectedSeasonIndex = null; } } private _media: MediaEntity; public formData: MovieSaveData; public posterPath: string; private _editMode: boolean = false; public get editMode(): boolean { return this._editMode; } public set editMode(v: boolean) { this._editMode = v; this.showSuggestions = false; } public selectedSeasonIndex: number; public showSuggestions: boolean = false; constructor(private electronService: ElectronService) { } ngOnInit() { } private initForm() { this.clearForm(); this.formData.name = this.media.name; this.formData.description = this.media.saveData.description; this.posterPath = `file:///${this.media.imagePath}`; if (this.media instanceof Movie) { this.formData.year = this.media.saveData.year; this.formData.runtime = this.media.saveData.runtime; this.formData.genre = this.media.saveData.genre; this.formData.actors = this.media.saveData.actors; } else if (this.media instanceof Series) { this.formData.year = this.media.saveData.year; this.formData.genre = this.media.saveData.genre; this.formData.actors = this.media.saveData.actors; } } private clearForm() { this.formData = { name: "", year: "", runtime: "", genre: "", actors: "", description: "" }; this.posterPath = ""; } public closeClicked() { if (this.editMode) { this.editMode = false; this.initForm(); } else { this.closeClick.emit(); } } public finishEdit() { this.editMode = false; if (this.media instanceof Movie) { const movieSaveData: MovieSaveData = { name: this.formData.name, description: this.formData.description, year: this.formData.year, runtime: this.formData.runtime, genre: this.formData.genre, actors: this.formData.actors }; this.media.save(movieSaveData); } else if (this.media instanceof Series) { const seriesSaveData: SeriesSaveData = { name: this.formData.name, description: this.formData.description, year: this.formData.year, genre: this.formData.genre, actors: this.formData.actors, markedSeason: this.media.saveData.markedSeason, markedEpisode: this.media.saveData.markedEpisode }; this.media.save(seriesSaveData); } else if (this.media instanceof MediaGroup) { const groupSaveData: MediaEntitySaveData = { name: this.formData.name, description: this.formData.description }; this.media.save(groupSaveData); } else { console.error("Error saving media data. Unknown media type."); } // Save new poster image. if (!this.posterPath.includes(this.media.imagePath)) { this.electronService.ipcRenderer.send("saveUrl", { targetDir: this.media.path, targetFileName: "poster.jpg", source: this.posterPath }); } } public playClicked() { if (this.media instanceof Movie) { this.electronService.ipcRenderer.send("openFile", path.join(this.media.path, this.media.fileName)); } } public playEpisode(index: number) { if (this.media instanceof Series && this.selectedSeasonIndex != null) { const selectedSeason: Season = this.media.seasons[this.selectedSeasonIndex]; if (selectedSeason.episodes[index]) { this.electronService.ipcRenderer.send("openFile", path.join(selectedSeason.path, selectedSeason.episodes[index])); } } } public markEpisode(index: number) { if (this.media instanceof Series) { if (this.media.saveData.markedSeason === this.selectedSeasonIndex && this.media.saveData.markedEpisode === index) { this.media.saveData.markedSeason = null; this.media.saveData.markedEpisode = null; } else { this.media.saveData.markedSeason = this.selectedSeasonIndex; this.media.saveData.markedEpisode = index; } this.media.save(); } } public openFolder() { this.electronService.ipcRenderer.send("openFile", this.media.path); } public suggestionClicked(fieldClick: FieldClickEvent) { switch (fieldClick.field) { case "title": this.formData.name = fieldClick.value; break; case "year": this.formData.year = fieldClick.value; break; case "runtime": this.formData.runtime = fieldClick.value; break; case "genre": this.formData.genre = fieldClick.value; break; case "plot": this.formData.description = fieldClick.value; break; case "actors": this.formData.actors = fieldClick.value; break; case "poster": this.posterPath = fieldClick.value; break; } } public showMissingPoster() { this.posterPath = "../../../assets/poster-missing.png"; } } <file_sep>/src/app/components/omdb-suggestions/omdb-suggestions.component.ts import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core"; import { HttpClient } from "@angular/common/http"; import { SettingsService } from "../../providers/settings.service"; interface OmdbSearchResults { Response: string; Search: OmdbSearchResult[]; totalResults: string; Error: string; } interface OmdbSearchResult { imdbID: string; Title: string; Poster: string; Year: string; } interface OmdbResult { imdbID: string; Title: string; Actors: string; Genre: string; Plot: string; Poster: string; Runtime: string; Year: string; } export interface FieldClickEvent { field: FieldName; value: string; } type FieldName = "poster" | "title" | "year" | "runtime" | "genre" | "plot" | "actors"; @Component({ selector: "app-omdb-suggestions", templateUrl: "./omdb-suggestions.component.html", styleUrls: ["./omdb-suggestions.component.scss"] }) export class OmdbSuggestionsComponent implements OnInit { @Output() public fieldClick: EventEmitter<FieldClickEvent> = new EventEmitter(); @Input() public name: string = ""; @Input() public type: "movie" | "series" = "movie"; public results: OmdbSearchResult[] = []; private _selectedSearchResult: OmdbSearchResult; public get selectedSearchResult(): OmdbSearchResult { return this._selectedSearchResult; } public set selectedSearchResult(value: OmdbSearchResult) { this._selectedSearchResult = value; this.retrieveRecord(); } public resultDetails: OmdbResult; constructor(private http: HttpClient, private settingsService: SettingsService) { } ngOnInit() { this.searchRecords(); } public searchRecords() { if (this.name) { this.http.get<OmdbSearchResults>(`http://www.omdbapi.com/?apikey=${this.settingsService.settings.omdbApiKey}`, { params: { s: this.name, type: this.type } }).subscribe(response => { if (response.Error) { console.error(`${response.Error} Trying to retrieve single record.`); this.retrieveRecordByName(); } else { this.results = response.Search ? response.Search : []; this.selectedSearchResult = this.results.length > 0 ? this.results[0] : null; } }, error => { console.error(error); }); } } public retrieveRecord() { if (this.selectedSearchResult && this.selectedSearchResult.imdbID) { this.http.get<OmdbResult>(`http://www.omdbapi.com/?apikey=${this.settingsService.settings.omdbApiKey}`, { params: { i: this.selectedSearchResult.imdbID, plot: "short" } }).subscribe(response => { this.resultDetails = response; }, error => { console.error(error); }); } } private retrieveRecordByName() { if (this.name) { this.http.get<OmdbResult>(`http://www.omdbapi.com/?apikey=${this.settingsService.settings.omdbApiKey}`, { params: { t: this.name, plot: "short" } }).subscribe(response => { this.resultDetails = response; }, error => { console.error(error); }); } } public fieldClicked(field: FieldName, value: string) { this.fieldClick.emit({ field: field, value: value }); } } <file_sep>/src/app/components/media-list/media-list.component.ts import { Component, EventEmitter, Input, Output } from "@angular/core"; import { MediaEntity } from "../../models/media-entity"; import { MediaGroup } from "../../models/media-group"; import { Movie } from "../../models/movie"; import { MediaService } from "../../providers/media.service"; import { Series } from "../../models/series"; export type ViewMode = "list" | "grid"; export interface SortOrder { fields: ("name" | "year")[]; orders: ("asc" | "desc")[]; } @Component({ selector: "app-media-list", templateUrl: "./media-list.component.html", styleUrls: ["./media-list.component.scss"] }) export class MediaListComponent { @Output() selectedMediaChange: EventEmitter<MediaEntity> = new EventEmitter(); @Input() public get selectedMedia(): MediaEntity { return this._selectedMedia; } public set selectedMedia(value: MediaEntity) { this._selectedMedia = value; this.selectedMediaChange.emit(value); } private _selectedMedia: MediaEntity; @Input() viewMode: ViewMode = "grid"; @Input() public get media(): MediaEntity[] { return this._media; } public set media(value: MediaEntity[]) { this._media = value; this.sortMedia(); } private _media: MediaEntity[]; @Input() public get scale(): number { return this._scale; } public set scale(value: number) { this._scale = value; this.negateScale = 1 / value; } private _scale: number = 1; @Input() public get sortOrder(): SortOrder { return this._sort; } public set sortOrder(value: SortOrder) { this._sort = value; } private _sort: SortOrder = { fields: ["name", "year"], orders: ["asc", "asc"] }; public sortedMedia: MediaEntity[]; public negateScale: number = 1; public openedGroup: MediaGroup; /** * Click handler for media entities. * @param media - The media that has been clicked on. */ public mediaClick(media: MediaEntity, force: boolean): void { if (!force && media instanceof MediaGroup) { this.openedGroup = this.openedGroup === media ? null : media; } else { this.selectedMedia = this.selectedMedia === media ? null : media; } } /** * Returns true if the {@link MediaEntity} is a {@link Movie}. * @param media - The MediaEntity to check. */ public isMovie(media: MediaEntity): boolean { return media instanceof Movie; } /** * Returns true if the {@link MediaEntity} is a {@link Series}. * @param media - The MediaEntity to check. */ public isSeries(media: MediaEntity): boolean { return media instanceof Series; } /** * Returns true if the {@link MediaEntity} is a {@link MediaGroup}. * @param media - The {@link MediaEntity} to check. */ public isGroup(media: MediaEntity): boolean { return media instanceof MediaGroup; } /** * Sorts the provided media using the provided sorting order. */ private sortMedia() { if (!this.media) { this.sortedMedia = []; return; } if (this.sortOrder) { this.sortedMedia = [...this.media].sort((a, b) => { let sortDirection: number; for (let i = 0; i < this.sortOrder.fields.length; i++) { const fieldName = this.sortOrder.fields[i]; switch (fieldName) { case "name": const nameA = a.name.toLowerCase().startsWith("the ") ? a.name.toLowerCase().slice(4) : a.name.toLowerCase(); const nameB = b.name.toLowerCase().startsWith("the ") ? b.name.toLowerCase().slice(4) : b.name.toLowerCase(); sortDirection = nameA.localeCompare(nameB); break; case "year": const yearA = parseInt(a.saveData["year"], 10); const yearB = parseInt(b.saveData["year"], 10); if (yearA === yearB || (isNaN(yearA) && isNaN(yearB))) { sortDirection = 0; } else if (isNaN(yearB) || yearA < yearB) { sortDirection = -1; } else if (isNaN(yearA) || yearA > yearB) { sortDirection = 1; } break; default: continue; } if (sortDirection) { return this.sortOrder.orders[i] === "desc" ? -sortDirection : sortDirection; } else { continue; } } return 0; }); } } } <file_sep>/src/app/models/media-entity.ts import { ElectronService } from "../providers/electron.service"; export interface MediaEntitySaveData { name: string; description: string; } export abstract class MediaEntity<T = MediaEntitySaveData> { protected _type: string; public get type(): string { return this._type; } protected _path: string; public get path(): string { return this._path; } protected _name: string; public get name(): string { return this.saveData["name"] ? this.saveData["name"] : this._name; } protected _imagePath: string; public get imagePath(): string { return this._imagePath; } protected _infoPath: string; public get infoPath(): string { return this._infoPath; } protected _saveData: T; public get saveData(): T { return this._saveData; } protected electronService: ElectronService; constructor(entityPath: string, electronService: ElectronService) { this._path = entityPath; this.electronService = electronService; } public load() { if (!this.electronService.fs.existsSync(this.infoPath)) { this.electronService.fs.writeFileSync(this.infoPath, "{}"); } try { this._saveData = JSON.parse(<any>this.electronService.fs.readFileSync(this.infoPath)); } catch (error) { this._saveData = null; } } public save(saveData: T = this.saveData) { const saveDataString = JSON.stringify(saveData); this.electronService.fs.writeFileSync(this.infoPath, saveDataString); this._saveData = JSON.parse(saveDataString); } } <file_sep>/src/app/components/home/home.component.ts import { Component } from "@angular/core"; import { MediaEntity } from "../../models/media-entity"; import { MediaService } from "../../providers/media.service"; import { ViewMode } from "../media-list/media-list.component"; import { Movie } from "../../models/movie"; import { Series } from "../../models/series"; export type MediaType = "movies" | "series"; @Component({ selector: "app-home", templateUrl: "./home.component.html", styleUrls: ["./home.component.scss"] }) export class HomeComponent { public selectedMedia: MediaEntity; public scale: number; public viewMode: ViewMode; public showSettings: boolean = false; public loadedMedia: MediaEntity[]; public displayedMedia: MediaEntity[]; private _displayedMediaType: MediaType; public get displayedMediaType(): MediaType { return this._displayedMediaType; } public set displayedMediaType(value: MediaType) { this._displayedMediaType = value; this.loadMedia(); } private _showGroups: boolean; public get showGroups(): boolean { return this._showGroups; } public set showGroups(value: boolean) { this._showGroups = value; this.loadMedia(); } private _searchText: string; public get searchText(): string { return this._searchText; } public set searchText(value: string) { this._searchText = value.toLocaleLowerCase(); this.filterMedia(); } constructor(public mediaService: MediaService) {} public async loadMedia() { this.loadedMedia = []; if (this.displayedMediaType && this.showGroups != null) { switch (this.displayedMediaType) { case "movies": if (this.showGroups) { this.loadedMedia = await this.mediaService.getGroupedMovies(); this.filterMedia(); } else { this.loadedMedia = await this.mediaService.getMovies(); this.filterMedia(); } break; case "series": if (this.showGroups) { this.loadedMedia = await this.mediaService.getGroupedSeries(); this.filterMedia(); } else { this.loadedMedia = await this.mediaService.getSeries(); this.filterMedia(); } break; default: break; } } } public closeSettings() { this.showSettings = false; this.mediaService.clearData(); this.loadMedia(); } private filterMedia() { if (this.searchText != null && !this.showGroups) { this.displayedMedia = this.loadedMedia.filter(value => { if ( (value.name && value.name.toLocaleLowerCase().includes(this.searchText)) || (value.saveData.description && value.saveData.description.toLocaleLowerCase().includes(this.searchText)) ) { return true; } if (value instanceof Movie || value instanceof Series) { if ( (value.saveData.actors && value.saveData.actors.toLocaleLowerCase().includes(this.searchText)) || (value.saveData.genre && value.saveData.genre.toLocaleLowerCase().includes(this.searchText)) || (value.saveData.year && value.saveData.year.toLocaleLowerCase().includes(this.searchText)) ) { return true; } } }); } else { this.displayedMedia = this.loadedMedia; } } } <file_sep>/src/app/providers/media.service.ts import { Injectable } from "@angular/core"; import * as path from "path"; import { Observable } from "rxjs"; import { MediaEntity } from "../models/media-entity"; import { MediaGroup } from "../models/media-group"; import { Movie } from "../models/movie"; import { Season } from "../models/season"; import { Series } from "../models/series"; import { ElectronService } from "./electron.service"; import { SettingsService } from "./settings.service"; @Injectable({ providedIn: "root" }) export class MediaService { private groupedMovies: MediaEntity[]; private allMovies: Movie[]; private groupedSeries: MediaEntity[]; private allSeries: Series[]; private _loadError: string; public get loadError(): string { return this._loadError; } constructor(private electronService: ElectronService, private settingsService: SettingsService) {} /** * Loads all movies in a directory asynchronously. * @param dir - The directory to load movies from. */ private loadMoviesInDirAsync(dir: string): Promise<MediaEntity[]> { return new Promise((resolve, reject) => { const media: MediaEntity[] = []; this.electronService.fs.readdir(dir, (err, files) => { if (err) { return reject(err); } media.push(...this.handleMovieFiles(dir, files)); resolve(media); }); }); } /** * Loads all movies in a directory. * @param dir - The directory to load movies from. */ private loadMoviesInDir(dir: string): MediaEntity[] { const media: MediaEntity[] = []; const files = this.electronService.fs.readdirSync(dir); media.push(...this.handleMovieFiles(dir, files)); return media; } /** * Converts movie files to media entities and continues recursive search in folders. * @param dir - The directory of the files. * @param files - The file names. */ private handleMovieFiles(dir: string, files: string[]): MediaEntity[] { const media: MediaEntity[] = []; files.forEach(file => { const fullPath = path.join(dir, file); if (this.electronService.fs.statSync(fullPath).isDirectory()) { const children = this.loadMoviesInDir(fullPath); if (children.length > 1) { media.push(new MediaGroup(fullPath, this.electronService, children)); } else { media.push(...children); } } else if (this.isVideo(file)) { const movie = new Movie(dir, file, this.electronService); media.push(movie); this.allMovies.push(movie); } }); return media; } /** * Loads all series in a directory asynchronously. * @param dir - The directory to load movies from. */ private loadSeriesInDirAsync(dir: string): Promise<MediaEntity[]> { return new Promise((resolve, reject) => { const media: MediaEntity[] = []; this.electronService.fs.readdir(dir, (err, files) => { if (err) { return reject(err); } media.push(...this.handleSerieFiles(dir, files)); resolve(media); }); }); } /** * Loads all series in a directory. * @param dir - The directory to load series from. */ private loadSeriesInDir(dir: string): MediaEntity[] { const media: MediaEntity[] = []; const files = this.electronService.fs.readdirSync(dir); media.push(...this.handleSerieFiles(dir, files)); return media; } /** * Converts serie files to media entities and continues recursive search in folders. * @param dir - The directory of the files. * @param files - The file names. */ private handleSerieFiles(dir: string, files: string[]): MediaEntity[] { const media: MediaEntity[] = []; files.forEach(file => { const fullPath = path.join(dir, file); if (this.electronService.fs.statSync(fullPath).isDirectory()) { const seasonMatch = file.match(/^season\s(\d+)$/i); if (seasonMatch) { const episodes: string[] = []; const seasonFiles = this.electronService.fs.readdirSync(fullPath); seasonFiles.forEach(seasonFile => { const episodeMatch = seasonFile.match(/e(\d+)/i) || seasonFile.match(/episode\s?(\d+)/i); if (episodeMatch) { episodes[parseInt(episodeMatch[1], 10) - 1] = seasonFile; } }); media[parseInt(seasonMatch[1], 10) - 1] = new Season(fullPath, episodes, this.electronService); } else { const children = this.loadSeriesInDir(fullPath); if (children.length > 0 && children.find(child => child instanceof Season)) { const series = new Series(fullPath, <Season[]>children, this.electronService); media.push(series); this.allSeries.push(series); } else if (children.length > 1) { media.push(new MediaGroup(fullPath, this.electronService, children)); } else { media.push(...children); } } } }); return media; } /** * Returns true if a specified file is a movie. * @param file - File to check. */ private isVideo(file: string): boolean { for (const extention of this.settingsService.settings.movieExtentions) { if (file.toLowerCase().endsWith(`${extention.toLowerCase()}`)) { return true; } } return false; } /** * Load movies from the drive. */ public async loadMovies() { this.allMovies = []; this.groupedMovies = []; this._loadError = ""; if (!this.electronService.isElectron()) { this._loadError = "This is not an Electron application."; } else { let movieDir = this.settingsService.settings.movieDirectory; movieDir = path.isAbsolute(movieDir) ? movieDir : path.resolve(movieDir); if (!this.electronService.fs.existsSync(movieDir)) { this._loadError = `Could not find configured movie directory: '${this.settingsService.settings.movieDirectory}'`; } else { this.groupedMovies = await this.loadMoviesInDirAsync(movieDir); } } } /** * Load series from the drive. */ public async loadSeries() { this.allSeries = []; this.groupedSeries = []; this._loadError = ""; if (!this.electronService.isElectron()) { this._loadError = "This is not an Electron application."; } else { let seriesDir = this.settingsService.settings.seriesDirectory; seriesDir = path.isAbsolute(seriesDir) ? seriesDir : path.resolve(seriesDir); if (!this.electronService.fs.existsSync(seriesDir)) { this._loadError = `Could not find configured series directory: '${this.settingsService.settings.seriesDirectory}'`; } else { this.groupedSeries = await this.loadSeriesInDirAsync(seriesDir); } } } /** * Get all the loaded groups and movies. */ public async getGroupedMovies(): Promise<MediaEntity[]> { if (!this.groupedMovies) { await this.loadMovies(); } return this.groupedMovies; } /** * Get only the loaded movies. No groups or series. * This includes movies that where otherwise in a group. */ public async getMovies(): Promise<Movie[]> { if (!this.allMovies) { await this.loadMovies(); } return this.allMovies; } /** * Get all the loaded groups and series. */ public async getGroupedSeries(): Promise<MediaEntity[]> { if (!this.groupedSeries) { await this.loadSeries(); } return this.groupedSeries; } /** * Get only the loaded series. No groups or movies. * This includes series that where otherwise in a group. */ public async getSeries(): Promise<Series[]> { if (!this.allSeries) { await this.loadSeries(); } return this.allSeries; } /** * Clears the loaded data so it will be reloaded the next time you try to access it. */ public clearData(): void { this.groupedMovies = null; this.allMovies = null; this.groupedSeries = null; this.allSeries = null; } } <file_sep>/src/app/models/series.ts import { MediaEntity, MediaEntitySaveData } from "./media-entity"; import { ElectronService } from "../providers/electron.service"; import * as path from "path"; import { Season } from "./season"; export interface SeriesSaveData extends MediaEntitySaveData { year: string; genre: string; actors: string; markedSeason?: number; markedEpisode?: number; } export class Series extends MediaEntity<SeriesSaveData> { private _seasons: Season[]; public get seasons(): Season[] { return this._seasons; } constructor(dirName: string, seasons: Season[], electronService: ElectronService) { super(dirName, electronService); this._name = this.path.split(path.sep).pop(); this._infoPath = `${this.path}${path.sep}seriesinfo.json`; this._imagePath = `${this.path}${path.sep}poster.jpg`; this._type = "series"; this._seasons = seasons; this.load(); } } <file_sep>/src/app/components/settings/settings.component.ts import { Component, OnInit, Output, EventEmitter } from "@angular/core"; import { SettingsService } from "../../providers/settings.service"; import { MediaService } from "../../providers/media.service"; import * as path from "path"; @Component({ selector: "app-settings", templateUrl: "./settings.component.html", styleUrls: ["./settings.component.scss"] }) export class SettingsComponent implements OnInit { @Output() public closeClick: EventEmitter<void> = new EventEmitter(); constructor(public settingsService: SettingsService, private mediaService: MediaService) { // this.settingsService.settings. } ngOnInit() { } public close() { this.closeClick.emit(); } public resetSettings() { this.settingsService.resetSettingsToFactory(); } public reloadSettings() { this.settingsService.loadApplicationSettings(); } public save() { this.settingsService.saveApplicationSettings(); } public arrayTrackByFn(index: number, extention: string) { return index; } public movieDirChanged(event: Event) { if ((<HTMLInputElement>event.srcElement).files.length === 1) { let movieDir: string = (<HTMLInputElement>event.srcElement).files[0].path; movieDir = path.relative("", movieDir); this.settingsService.settings.movieDirectory = movieDir; } } public seriesDirChanged(event: any) { if ((<HTMLInputElement>event.srcElement).files.length === 1) { let seriesDir: string = (<HTMLInputElement>event.srcElement).files[0].path; seriesDir = path.relative("", seriesDir); this.settingsService.settings.seriesDirectory = seriesDir; } } } <file_sep>/src/app/models/season.ts import { MediaEntity, MediaEntitySaveData } from "./media-entity"; import { ElectronService } from "../providers/electron.service"; import * as path from "path"; export class Season extends MediaEntity { private _episodes: string[]; public get episodes(): string[] { return this._episodes; } constructor(dirName: string, episodes: string[], electronService: ElectronService) { super(dirName, electronService); this._name = this.path.split(path.sep).pop(); this._infoPath = `${this.path}${path.sep}seasoninfo.json`; this._type = "season"; this._episodes = episodes; this.load(); } } <file_sep>/README.md # video-library Video library for locally stored movies and series. ## Getting Started Clone this repository locally : ```bash git clone https://github.com/JohanBeekers/video-library.git ``` Install dependencies with npm : ```bash npm install ``` If you want to generate Angular components with Angular-cli , you **MUST** install `@angular/cli` in npm global context. Please follow [Angular-cli documentation](https://github.com/angular/angular-cli) if you had installed a previous version of `angular-cli`. ```bash npm install -g @angular/cli ``` ## To build for development - **in a terminal window** -> npm start ## Included Commands | Command | Description | | -------------------------- | ----------------------------------------------------------------------------------------------------------- | | `npm run ng:serve:web` | Execute the app in the browser | | `npm run build` | Build the app. Your built files are in the /dist folder. | | `npm run build:prod` | Build the app with Angular aot. Your built files are in the /dist folder. | | `npm run electron:local` | Builds your application and start electron | | `npm run electron:linux` | Builds your application and creates an app consumable on linux system | | `npm run electron:windows` | On a Windows OS, builds your application and creates an app consumable in windows 32/64 bit systems | | `npm run electron:mac` | On a MAC OS, builds your application and generates a `.app` file of your application that can be run on Mac | **Note:** Only windows builds have been tested.
f51f5a28749b88ddd106e12df45736786f186f51
[ "Markdown", "TypeScript" ]
15
TypeScript
JohanBeekers/video-library
875f60481e18a012165372a31618137abb198c6a
1b837130b477a417d07fb4e6944b510167af250b
refs/heads/master
<repo_name>Kailneg/juego2d<file_sep>/Juego2D/src/graficos/HojaSprites.java package graficos; import java.awt.image.BufferedImage; import java.io.IOException; import javax.imageio.ImageIO; public class HojaSprites { //Atributos private final int ANCHO; private final int ALTO; private final String RUTA; private BufferedImage imagen; public final int[] pixeles; //Constructor Se pone final por buena costumbre, así se le ayuda a JVM a interpretar el código public HojaSprites(final String ruta, final int ancho, final int alto) { this.ANCHO = ancho; this.ALTO = alto; this.RUTA = ruta; //El array tiene que tener el mismo tamaño que píxeles tenga el SpriteSheet pixeles = new int[ancho*alto]; cargar(); } private void cargar(){ //Cargar el spritesheet como imagen y cargarlo en el array de int como píxeles individuales try { imagen = ImageIO.read(HojaSprites.class.getResource(RUTA)); imagen.getRGB(0, 0, ANCHO, ALTO, pixeles, 0, ANCHO); } catch (IOException e) { e.printStackTrace(); } } //Getter public int getAncho(){ return ANCHO; } } <file_sep>/Juego2D/src/graficos/Sprite.java package graficos; import java.awt.image.BufferedImage; public final class Sprite { //Atributos private final int lado; //Tamaño de un lado del sprite. Normalmente es 32, 64... private final HojaSprites hoja; private int x, y; private BufferedImage imagen; public int pixeles[]; //Constructor public Sprite (final int lado, final int columna, final int fila, final HojaSprites hoja) { this.lado = lado; this.hoja = hoja; this.x = columna * lado; this.y = fila * lado; //El array tiene que tener el mismo tamaño que píxeles tenga el Sprite pixeles = new int[lado*lado]; for (int y = 0; y < lado; y++){ for (int x = 0; x < lado; x++) { pixeles[x + y * lado] = hoja.pixeles[(x + this.x) + (y + this.y) * hoja.getAncho()]; } } } } <file_sep>/Juego2D/src/core/Juego.java package core; import java.awt.Canvas; import control.Teclado; public class Juego extends Canvas implements Runnable { //Atributos private static final long serialVersionUID = -1308273005477917009L; private static volatile boolean enFuncionamiento = false; private static Ventana ventana; private static Thread thread; private static Teclado teclado; private static int aps = 0; private static int fps = 0; //Constructor private Juego() { ventana = new Ventana(this); teclado = new Teclado(); addKeyListener(teclado); requestFocus(); } private void actualizar() { teclado.actualizar(); accionTeclado(); aps++; } private void accionTeclado() { if (teclado.arriba) System.out.println("Arriba"); if (teclado.abajo) System.out.println("Abajo"); if (teclado.izquierda) System.out.println("Izquierda"); if (teclado.derecha) System.out.println("Derecha"); } private void mostrar() { fps++; } private synchronized void iniciar() { enFuncionamiento = true; thread = new Thread(this, "Thread Gráficos"); thread.start(); } private synchronized void detener() { enFuncionamiento = false; try { thread.join(); } catch (InterruptedException e) { e.printStackTrace(); } } public void run() { // Anotaciones final int NS_POR_SEGUNDO = 1000000000; final byte APS_OBJETIVO = 30; final double NS_POR_ACTUALIZACION = NS_POR_SEGUNDO / APS_OBJETIVO; long referenciaActualizacion = System.nanoTime(); long referenciaContador = System.nanoTime(); double tiempoTranscurrido; double delta = 0; while (enFuncionamiento) { final long inicioBucle = System.nanoTime(); tiempoTranscurrido = inicioBucle - referenciaActualizacion; referenciaActualizacion = inicioBucle; delta += tiempoTranscurrido / NS_POR_ACTUALIZACION; while (delta >= 1) { actualizar(); delta--; } mostrar(); if (System.nanoTime() - referenciaContador > NS_POR_SEGUNDO) { ventana.setTitle(Ventana.getNombreVentana() + " -||- APS: " + aps + " || FPS: " + fps); aps = 0; fps = 0; referenciaContador = System.nanoTime(); } } } //Main public static void main(String[] args) { Juego juego = new Juego(); juego.iniciar(); } }
2547c72dca31e9af8f424467d5e8e8bdad54e906
[ "Java" ]
3
Java
Kailneg/juego2d
eecbd26dbdbf1a09d90649f20b20aff61f0118ba
97a58410c311f88ef84efe61d0ee231b4dafcc9b
refs/heads/master
<repo_name>gucchi43/kaosouou<file_sep>/KaoSouou/TOP/SplashViewController.swift // // SplashViewController.swift // KaoSouou // // Created by <NAME> on 2018/05/20. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Firebase class SplashViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(_ animated: Bool) { super.dismiss(animated: animated, completion: nil) rootCheck() } func rootCheck() { //ユーザーがいない場合サインイン画面に遷移 if let authUser = Auth.auth().currentUser { User.get(authUser.uid, block: { (user, error) in if let user = user { AccountManager.shared.currentUser = user DispatchQueue.main.async { DispatchQueue.main.async { if user.allowedFlag == true { AppDelegate.shared.rootViewController.switchToMainScreen() } else { AppDelegate.shared.rootViewController.switchToFinalCheckScreen() } } } } else { DispatchQueue.main.async { // ユーザーがなかったらログアウトしてトップへ。 try? Auth.auth().signOut() DispatchQueue.main.async { AppDelegate.shared.rootViewController.showLoginScreen() } } } }) } else { DispatchQueue.main.async { AppDelegate.shared.rootViewController.showLoginScreen() } } } } <file_sep>/KaoSouou/Mypage/NotificationListViewController.swift // // NotificationListViewController.swift // KaoSouou // // Created by <NAME> on 2018/06/20. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Pring import DZNEmptyDataSet class NotificationListViewController: UIViewController, Storyboardable { @IBOutlet weak var tableView: UITableView! var dataSource: DataSource<NotificationItem>? override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.emptyDataSetSource = self tableView.emptyDataSetDelegate = self tableView.rowHeight = 68 tableView.register(NotificationTableViewCell.self) tableView.tableFooterView = UIView() fetchNotifications() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) resetBadgeNum() } func fetchNotifications() { guard let currentUser = AccountManager.shared.currentUser else { return } let sortDescriptor: NSSortDescriptor = NSSortDescriptor(key: "updatedAt", ascending: false) let options: Options = Options() options.sortDescriptors = [sortDescriptor] dataSource = currentUser.notificationItems .order(by: "updatedAt") .dataSource(options: options) .on({ [weak self] (snapshot, changes) in guard let tableView = self?.tableView else { return } switch changes { case .initial: tableView.reloadData() case .update(let deletions, let insertions, let modifications): tableView.beginUpdates() tableView.insertRows(at: insertions.map { IndexPath(row: $0, section: 0) }, with: .automatic) tableView.deleteRows(at: deletions.map { IndexPath(row: $0, section: 0) }, with: .automatic) tableView.reloadRows(at: modifications.map { IndexPath(row: $0, section: 0) }, with: .automatic) tableView.endUpdates() case .error(let error): print(error) } }).listen() } func resetBadgeNum() { guard let currentUser = AccountManager.shared.currentUser else { return } if currentUser.badgeNum > 0 { currentUser.badgeNum = 0 currentUser.update { (error) in if let error = error { print(error.localizedDescription) } else { print("succes reset badgeNum") } } UIApplication.shared.applicationIconBadgeNumber = 0 } } @IBAction func tapCloseButton(_ sender: Any) { dismiss(animated: true, completion: nil) } } extension NotificationListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataSource?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(with: NotificationTableViewCell.self, for: indexPath) cell.configure(with: dataSource![indexPath.row]) return cell } } extension NotificationListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) let notificationItem = dataSource![indexPath.row] let resultSB = UIStoryboard(name: "ResultList", bundle: nil) let resultNC = resultSB.instantiateInitialViewController() as! UINavigationController let resultVC = resultNC.topViewController as! ResultListViewController resultVC.notificationItem = notificationItem self.present(resultNC, animated: true, completion: nil) } } extension NotificationListViewController: DZNEmptyDataSetDelegate, DZNEmptyDataSetSource { // func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! { // return #imageLiteral(resourceName: "empty_main_2") // } func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let titleText = "まだ評価されてません" let titleAttributes = [.font: UIFont.boldSystemFont(ofSize: 16), .foregroundColor: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)] as [NSAttributedStringKey : Any] return NSMutableAttributedString(string: titleText, attributes: titleAttributes) } func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! { let descText = "他の人を評価することで自分も評価されやすくなるよ!" let descAttributes = [.font: UIFont.systemFont(ofSize: 14), .foregroundColor: #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)] as [NSAttributedStringKey : Any] return NSAttributedString(string: descText, attributes: descAttributes) } func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool { return true } } <file_sep>/KaoSouou/Mypage/LoveUserListViewController.swift // // LoveUserListViewController.swift // KaoSouou // // Created by <NAME> on 2018/09/20. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Kingfisher import Pring import Firebase import SVProgressHUD class LoveUserListViewController: UIViewController { // var kaoUserArray: [User] = [] var userDataSourse: DataSource<User>? @IBOutlet weak var closeButton: UIBarButtonItem! @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() collectionView.dataSource = self collectionView.delegate = self collectionView.register(LovedUserCell.self) guard let currentUser = AccountManager.shared.currentUser else { return } getUserArray(with: currentUser) } func getUserArray(with user: User) { // kaoUserArray.removeAll() userDataSourse = user .loveUsers .order(by: \User.updatedAt) .dataSource() .on({ [weak self] (snapshot, changes) in guard let collectionView: UICollectionView = self?.collectionView else { return } switch changes { case .initial: collectionView.reloadData() case .update(let deletions, let insertions, let modifications): collectionView.reloadData() case .error(let error): print(error) } }).listen() } @IBAction func tapCloseButton(_ sender: Any) { dismiss(animated: true) { print("close loveList") } } } extension LoveUserListViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { guard let userDataSourse = userDataSourse else { return 0 } print("userDataSourse.count : ", userDataSourse.count) return userDataSourse.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(with: LovedUserCell.self, for: indexPath) cell.configure(with: userDataSourse![indexPath.row]) return cell } } extension LoveUserListViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let space = 1 let wlength = (Int(UIScreen.main.bounds.width) - space) / 2 let hlength = (Int(UIScreen.main.bounds.height) - space) / 2 return CGSize(width: wlength, height: hlength) } } extension LoveUserListViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) print("indexPath.row : ", indexPath.row) let cell = collectionView.cellForItem(at: indexPath) as! LovedUserCell // ??? 何する? とりあえず写真を全画面表示する } } <file_sep>/KaoSouou/Main/PrintFacePowerViewController.swift // // PrintFacePowerViewController.swift // KaoSouou // // Created by <NAME> on 2018/02/19. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Kingfisher import Pring import FontAwesome_swift class PrintFacePowerViewController: UIViewController { @IBOutlet weak var imageView: UIImageView! // @IBOutlet weak var firstUserImageView: UIImageView! // @IBOutlet weak var SecondUserImageView: UIImageView! // @IBOutlet weak var ThirdUserImageView: UIImageView! @IBOutlet weak var titileLabel: UILabel! @IBOutlet weak var powerLabel: UILabel! @IBOutlet weak var nextButton: UIButton! var faceImage: UIImage? var faceImageUrl: URL? var dataSourse: DataSource<User>? override func viewDidLoad() { super.viewDidLoad() setButton() setImageLayout() imageView.image = faceImage guard let currentUser = AccountManager.shared.currentUser else { return powerLabel.text = "I love you~~~"} if currentUser.gender == 2 { powerLabel.text = "So coooool!!!" } else { powerLabel.text = "So cuuuute!!!" } // setImageViews() // getLoveUsers() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) // getLoveUsers() } // func getLoveUsers() { // guard let user = AccountManager.shared.currentUser else { return } // // let sortDescriptor: NSSortDescriptor = NSSortDescriptor(key: "updatedAt", ascending: false) // let options: Options = Options() // options.sortDescirptors = [sortDescriptor] // // dataSourse = user.loveUsers // .order(by: \User.updatedAt) // .limit(to: 4) // .dataSource(options: options) // .onCompleted({ (snapshot, users) in // self.setUsersImage(users: users) // }) // .listen() // } func setImageLayout() { imageView.layer.cornerRadius = imageView.frame.width / 10 imageView.clipsToBounds = true } func setButton() { nextButton.layer.cornerRadius = nextButton.bounds.height / 2 nextButton.layer.borderWidth = 1 nextButton.layer.borderColor = UIColor.white.cgColor nextButton.clipsToBounds = true titileLabel.lblShadow(radius: 0.5, opacity: 0.5) powerLabel.lblShadow(radius: 0.5, opacity: 0.5) nextButton.btnShadow(radius: 0.5, opacity: 0.5) } // func setImageViews() { // imageView.backgroundColor = UIColor.boyBrandColor() // firstUserImageView.backgroundColor = UIColor.boyBrandColor() // SecondUserImageView.backgroundColor = UIColor.boyBrandColor() // ThirdUserImageView.backgroundColor = UIColor.imageBGColor() // } // // func setUsersImage(users: [User]) { // if let user = users[safe: 0] { // firstUserImageView.loadUserImageView(with: user) // } else { // firstUserImageView.setEmptyUserImage() // } // if let user = users[safe: 1] { // SecondUserImageView.loadUserImageView(with: user) // } else { // SecondUserImageView.setEmptyUserImage() // } // if let user = users[safe: 2] { // ThirdUserImageView.loadUserImageView(with: user) // } else { // ThirdUserImageView.setEmptyUserImage() // } // } // @IBAction func tapBackButton(_ sender: Any) { dismiss(animated: true, completion: nil) } } <file_sep>/KaoSouou/TOP/RootViewController.swift // // RootViewController.swift // KaoSouou // // Created by <NAME> on 2018/06/13. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit final class RootViewController: UIViewController { var current: UIViewController init() { let storyboard = UIStoryboard(name: "Splash", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! SplashViewController current = viewController super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() addChildViewController(current) view.addSubview(current.view) current.didMove(toParentViewController: self) } func showLoginScreen() { let storyboard = UIStoryboard(name: "Login", bundle: nil) let new = storyboard.instantiateInitialViewController() as! LoginViewController addChildViewController(new) view.addSubview(new.view) new.didMove(toParentViewController: self) current.willMove(toParentViewController: nil) current.view.removeFromSuperview() current.removeFromParentViewController() current = new } func showMainScreen() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let new = storyboard.instantiateInitialViewController() as! ViewController addChildViewController(new) view.addSubview(new.view) new.didMove(toParentViewController: self) current.willMove(toParentViewController: nil) current.view.removeFromSuperview() current.removeFromParentViewController() current = new } func showOnboardScreen() { let storyboard = UIStoryboard(name: "Onboard", bundle: nil) let new = storyboard.instantiateInitialViewController() as! OnboardViewController addChildViewController(new) view.addSubview(new.view) new.didMove(toParentViewController: self) current.willMove(toParentViewController: nil) current.view.removeFromSuperview() current.removeFromParentViewController() current = new } func showFinalCheckScreen() { let storyboard = UIStoryboard(name: "FinalCheck", bundle: nil) let new = storyboard.instantiateInitialViewController() as! FinalCheckViewController addChildViewController(new) view.addSubview(new.view) new.didMove(toParentViewController: self) current.willMove(toParentViewController: nil) current.view.removeFromSuperview() current.removeFromParentViewController() current = new } func showBirthdaySelectScreen() { let storyboard = UIStoryboard(name: "BirthdaySelect", bundle: nil) let new = storyboard.instantiateInitialViewController() as! BirthdaySelectViewController addChildViewController(new) view.addSubview(new.view) new.didMove(toParentViewController: self) current.willMove(toParentViewController: nil) current.view.removeFromSuperview() current.removeFromParentViewController() current = new } func switchToLogin() { let storyboard = UIStoryboard(name: "Login", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! LoginViewController animateFadeTransition(to: viewController) } func switchToSetProfile(with photoUrl: URL?) { let storyboard = UIStoryboard(name: "SetProfile", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! SetProfileViewController viewController.currentType = .initial if let photoUrl = photoUrl { viewController.photoUrl = photoUrl } animateFadeTransition(to: viewController) } func switchToGenderSelect() { let storyboard = UIStoryboard(name: "GenderSelect", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! GenderSelectViewController animateFadeTransition(to: viewController) } func switchToMainScreen() { let storyboard = UIStoryboard(name: "Main", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! ViewController animateFadeTransition(to: viewController) } func switchToOnboardScreen() { let storyboard = UIStoryboard(name: "Onboard", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! OnboardViewController animateFadeTransition(to: viewController) } func switchToBirthdaySelectScreen() { let storyboard = UIStoryboard(name: "BirthdaySelect", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! BirthdaySelectViewController animateFadeTransition(to: viewController) } func switchToFinalCheckScreen() { let storyboard = UIStoryboard(name: "FinalCheck", bundle: nil) let viewController = storyboard.instantiateInitialViewController() as! FinalCheckViewController animateFadeTransition(to: viewController) } private func animateFadeTransition(to new: UIViewController, completion: (() -> Void)? = nil) { current.willMove(toParentViewController: nil) addChildViewController(new) transition(from: current, to: new, duration: 0.3, options: [.transitionCrossDissolve, .curveEaseOut], animations: { }) { completed in self.current.removeFromParentViewController() new.didMove(toParentViewController: self) self.current = new completion?() } } } <file_sep>/KaoSouou/TOP/BirthdaySelectViewController.swift // // BirthdaySelectViewController.swift // KaoSouou // // Created by <NAME> on 2018/12/12. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import ADDatePicker class BirthdaySelectViewController: UIViewController { @IBOutlet weak var datePicker: ADDatePicker! override func viewDidLoad() { super.viewDidLoad() customDatePicker1() } func customDatePicker1(){ datePicker.yearRange(inBetween: 1890, end: 2022) datePicker.selectionType = .circle datePicker.bgColor = .black datePicker.deselectTextColor = .white datePicker.deselectedBgColor = .clear datePicker.selectedBgColor = .white datePicker.selectedTextColor = selectedKeyColor() datePicker.intialDate = Calendar.current.date(byAdding: .day, value: -1, to: Date())! } func selectedKeyColor() -> UIColor { var selectColor: UIColor! if let currentUser = AccountManager.shared.currentUser { if currentUser.gender == 2{ selectColor = UIColor.girlBrandColor() } else { selectColor = UIColor.boyBrandColor() } // return selectColor } else { selectColor = UIColor.girlBrandColor() } return selectColor } func getBirthdayString() -> String { let dateformatter = DateFormatter() dateformatter.dateFormat = "yyyy/MM/dd" let birthdayString = dateformatter.string(from: datePicker.getSelectedDate()) print("birthdayString",birthdayString) return birthdayString } @IBAction func tapNextButton(_ sender: Any) { next() } func next() { let birthdayString = getBirthdayString() if let currentUser = AccountManager.shared.currentUser { currentUser.birthday = birthdayString currentUser.update({ (error) in if let error = error { print(error.localizedDescription) } else { print("birthday設定成功") AppDelegate.shared.rootViewController.showOnboardScreen() } }) } else { print("currentUser ") } } } <file_sep>/KaoSouou/TOP/LoginViewController.swift // // LoginViewController.swift // KaoSouou // // Created by <NAME> on 2018/03/15. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Foundation import UserNotifications import FacebookLogin import FacebookCore import Firebase import Pring import SwiftyJSON import SVProgressHUD import TwitterKit class LoginViewController: UIViewController{ @IBOutlet weak var fbLoginButton: UIButton! @IBOutlet weak var twLoginButton: UIButton! @IBOutlet weak var textView: UITextView! var backgroundTaskID : UIBackgroundTaskIdentifier = 0 override func viewDidLoad() { super.viewDidLoad() setTextView() } @IBAction func tapFBLoginButton(_ sender: Any) { fbLogin() } @IBAction func tapTWLoginButton(_ sender: Any) { twLogin() } func twLogin() { self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil) TWTRTwitter.sharedInstance().logIn { (session, error) in UIApplication.shared.endBackgroundTask(self.backgroundTaskID) SVProgressHUD.show() guard let session = session else { print(error?.localizedDescription ?? "") self.signUpErrorAlert() return } let credential = TwitterAuthProvider.credential(withToken: session.authToken, secret: session.authTokenSecret) Auth.auth().signIn(with: credential, completion: { (authUser, error) in if let error = error { let castedError = error as NSError let firebaseError = AuthErrorCode(rawValue: castedError.code) print("firebaseError : ", firebaseError) return } guard let authUser = authUser else { print(error?.localizedDescription ?? "") SVProgressHUD.dismiss() return } User.get(authUser.uid, block: { (user, error) in if let user = user { // すでにユーザーがある場合はそのままログイン user.fcmToken = Messaging.messaging().fcmToken! AccountManager.shared.currentUser = user AccountManager.shared.currentUser!.update({ (error) in if let error = error { print(error.localizedDescription) SVProgressHUD.dismiss() return } else { SVProgressHUD.dismiss() DispatchQueue.main.async { if user.allowedFlag { AppDelegate.shared.rootViewController.switchToMainScreen() } else { AppDelegate.shared.rootViewController.switchToFinalCheckScreen() } } } }) } else { // ない場合はユーザーを作る self.twSignUpNewUser(newUserId: authUser.uid, session: session, success: { photoUrl in // 新規登録成功 SVProgressHUD.dismiss() DispatchQueue.main.async { AppDelegate.shared.rootViewController.switchToSetProfile(with: photoUrl) } }, failure: { // 新規登録失敗 self.signUpErrorAlert() }) } }) }) } } func twSignUpNewUser(newUserId: String, session: TWTRSession, success: @escaping(URL?) -> Void, failure: @escaping() -> Void) { let client = TWTRAPIClient.withCurrentUser() client.loadUser(withID: session.userID, completion: { (user, error) in if let error = error { print(error.localizedDescription) SVProgressHUD.dismiss() failure() } if let user = user { let newUser = User(id: newUserId) newUser.originId = user.userID newUser.displayName = user.screenName newUser.hensachi = 50 newUser.fcmToken = Messaging.messaging().fcmToken! newUser.save { (reference, error) in if let error = error { print(error) failure() } else { print(reference) AccountManager.shared.currentUser = newUser UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { (granted, error) in if let error = error { print(error.localizedDescription) } if granted { print("プッシュ通知ダイアログ 許可") UIApplication.shared.registerForRemoteNotifications() } else { print("プッシュ通知ダイアログ 拒否") } success(URL(string: user.profileImageLargeURL)) }) } } } }) } func fbLogin() { self.backgroundTaskID = UIApplication.shared.beginBackgroundTask(expirationHandler: nil) let loginManeger = LoginManager() loginManeger.logIn(readPermissions: [.email, .publicProfile, .userFriends], viewController: self) { (result) in UIApplication.shared.endBackgroundTask(self.backgroundTaskID) SVProgressHUD.show() switch result { case .success(let permission, let declinePemisson, let token): print("success!!!") let credential = FacebookAuthProvider.credential(withAccessToken: token.authenticationToken) Auth.auth().signIn(with: credential, completion: { (authUser, error) in if let error = error { print("error", error) self.signUpErrorAlert() } else { guard let authUser = authUser else { self.signUpErrorAlert() return } User.get(authUser.uid, block: { (user, error) in if let user = user { print("ログイン済み user info: ", user) user.fcmToken = Messaging.messaging().fcmToken! AccountManager.shared.currentUser = user AccountManager.shared.currentUser!.update({ (error) in if let error = error { print(error.localizedDescription) SVProgressHUD.dismiss() return } else { SVProgressHUD.dismiss() DispatchQueue.main.async { if user.allowedFlag { AppDelegate.shared.rootViewController.switchToMainScreen() } else { AppDelegate.shared.rootViewController.switchToFinalCheckScreen() } } } }) } else { self.fbSignUpNewUser(newUserId: authUser.uid, success: { photoUrl in // 新規登録成功 SVProgressHUD.dismiss() DispatchQueue.main.async { AppDelegate.shared.rootViewController.switchToSetProfile(with: photoUrl) } }, failure: { // 新規登録失敗 self.signUpErrorAlert() }) } }) } }) case .failed(let error): print("error...", error) self.signUpErrorAlert() case .cancelled: print("cancelled") self.signUpErrorAlert() } } } func fbSignUpNewUser(newUserId: String, success: @escaping(URL?) -> Void, failure: @escaping() -> Void) { // userInfo parametars // var parameters: [String : Any]? = ["fields": "id, name, picture.width(480).height(480), gender"] let connection = GraphRequestConnection() var graphPath = "/me" var parameters: [String : Any]? = ["fields": "id, name, email, picture.width(480).height(480), gender"] var accessToken = AccessToken.current var httpMethod: GraphRequestHTTPMethod = .GET var apiVersion: GraphAPIVersion = .defaultVersion let userInfoGraphRequest = GraphRequest(graphPath: graphPath, parameters: parameters!, accessToken: accessToken, httpMethod: httpMethod, apiVersion: apiVersion) connection.add(userInfoGraphRequest) { httpResponse, result in switch result { case .success(let response): print("Graph Request Succeeded: \(response)") if let userInfo = response.dictionaryValue { let json = JSON(userInfo) print("newUserId: ", newUserId) let newUser = User(id: newUserId) if let id = json["id"].string { newUser.originId = id } if let name = json["name"].string { newUser.displayName = name } if let email = json["email"].string { newUser.email = email } newUser.hensachi = 50 newUser.fcmToken = Messaging.messaging().fcmToken! newUser.save { (reference, error) in if let error = error { print(error) failure() } else { print(reference) AccountManager.shared.currentUser = newUser UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { (granted, error) in if let error = error { print(error.localizedDescription) } if granted { print("プッシュ通知ダイアログ 許可") UIApplication.shared.registerForRemoteNotifications() } else { print("プッシュ通知ダイアログ 拒否") } if let pictureUrl = json["picture"]["data"]["url"].url{ success(pictureUrl) } else { success(nil) } }) } } } else { failure() } case .failed(let error): print("Graph Request Failed: \(error)") failure() } } connection.start() } func signUpErrorAlert() { SVProgressHUD.dismiss() let alert = UIAlertController(title: "サインインに失敗しました", message: "もう一度お試しください", preferredStyle: .alert) let deleteAction = UIAlertAction(title: "OK", style: .destructive) { (action) in // TODO: 写真削除実装 } let ok = UIAlertAction(title: "OK", style: .default, handler: nil) alert.addAction(ok) present(alert, animated: true, completion: nil) } func setTextView() { let baseString = "利用規約とプライバシーポリシーに同意の上お進みください。" let attributedString = NSMutableAttributedString(string: baseString) attributedString.addAttribute(.link, value: "https://faceislife.studio.design/support/terms", range: NSString(string: baseString).range(of: "利用規約")) attributedString.addAttribute(.link, value: "https://faceislife.studio.design/support/privacy", range: NSString(string: baseString).range(of: "プライバシーポリシー")) textView.attributedText = attributedString textView.textColor = .white textView.isSelectable = true textView.isEditable = false textView.delegate = self } override func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { UIApplication.shared.open(URL) return false } } <file_sep>/KaoSouou/Extention/Extention.swift // // Extention.swift // KaoSouou // // Created by <NAME> on 2018/06/14. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import UIKit extension UITextField { func addUnderline(width: CGFloat, color: UIColor) { let border = CALayer() border.frame = CGRect(x: 0, y: self.frame.height - width, width: self.frame.width, height: width) border.backgroundColor = color.cgColor self.layer.addSublayer(border) } } extension UILabel { func lblShadow(radius: CGFloat, opacity: Float){ self.layer.masksToBounds = false self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowOffset = CGSize(width: 1, height: 1) self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale } } extension UIButton { func btnShadow(radius: CGFloat, opacity: Float){ self.layer.masksToBounds = false self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowOffset = CGSize(width: 1, height: 1) self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale } } extension UIView { func viewShadow(radius: CGFloat, opacity: Float, color: UIColor){ self.layer.masksToBounds = false self.layer.shadowRadius = radius self.layer.shadowOpacity = opacity self.layer.shadowColor = color.cgColor self.layer.shadowOffset = CGSize(width: 6, height: 6) self.layer.shouldRasterize = true self.layer.rasterizationScale = UIScreen.main.scale } } extension Double { mutating func shisyagonyu() -> Double{ print("変更前 : ", self) let output = Darwin.round(self * 10) / 10 print("変更後 : ", output) return output } } extension String { // ex) 1995/12/09 -> 23 func getAge() -> String { let arr:[String] = self.components(separatedBy: "/") let year = Int(arr[0]) let month = Int(arr[1]) let day = Int(arr[2]) let calendar = Calendar(identifier: .gregorian) let birthDate = DateComponents(calendar: calendar, year: year, month: month, day: day).date! let age = String(calendar.dateComponents([.year], from: birthDate, to: Date()).year!) print("age :", age) return age } } extension UIColor { class func twitterColor() -> UIColor{ return UIColor.rgbColor(rgbValue: 0x00ACED) } class func facebookColor() -> UIColor{ return UIColor.rgbColor(rgbValue: 0x305097) } class func lineColor() -> UIColor{ return UIColor.rgbColor(rgbValue: 0x5AE628) } class func imageBGColor() -> UIColor{ return UIColor.lightGray } class func boyBrandColor() -> UIColor{ return UIColor.rgbColor(rgbValue: 0x00FF92) } class func girlBrandColor() -> UIColor{ return UIColor.rgbColor(rgbValue: 0xF743BC) } class func rgbColor(rgbValue: UInt) -> UIColor{ return UIColor( red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, blue: CGFloat( rgbValue & 0x0000FF) / 255.0, alpha: CGFloat(1.0) ) } class func randomColor() -> UIColor { let r: CGFloat = CGFloat(arc4random_uniform(255)+1) / 255.0 let g: CGFloat = CGFloat(arc4random_uniform(255)+1) / 255.0 let b: CGFloat = CGFloat(arc4random_uniform(255)+1) / 255.0 let color: UIColor = UIColor(red: r, green: g, blue: b, alpha: 1.0) return color } } extension UIViewController: UITextViewDelegate { public func textView(_ textView: UITextView, shouldInteractWith URL: URL, in characterRange: NSRange, interaction: UITextItemInteraction) -> Bool { let urlString = URL.absoluteString if urlString == "TermOfUseLink" { print("利用規約のリンクがタップされました") // ログ送信処理 // 利用規約画面を開く処理 } if urlString == "PrivacyPolicyLink" { print("プライバシーポリシーのリンクがタップされました") // ログ送信処理 // プライバシーポリシー画面を開く処理 } return false } } extension UIApplication { // 表示中の一番上のViewControllerを取得 class func topViewController(controller: UIViewController? = UIApplication.shared.keyWindow?.rootViewController) -> UIViewController? { if let navigationController = controller as? UINavigationController { return topViewController(controller: navigationController.visibleViewController) } if let tabController = controller as? UITabBarController { if let selected = tabController.selectedViewController { return topViewController(controller: selected) } } if let presented = controller?.presentedViewController { return topViewController(controller: presented) } return controller } } <file_sep>/KaoSouou/Mypage/NotificationTableViewCell.swift // // NotificationTableViewCell.swift // KaoSouou // // Created by <NAME> on 2018/06/20. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit class NotificationTableViewCell: UITableViewCell, Nibable { @IBOutlet weak var voderImageView: UIImageView! @IBOutlet weak var messageLabel: UILabel! @IBOutlet weak var agoLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() voderImageView.setEmptyUserImage() voderImageView.layer.cornerRadius = voderImageView.bounds.width / 2 voderImageView.clipsToBounds = true } func configure(with notificationItem: NotificationItem) { messageLabel.text = notificationItem.num + "位に選ばれました" agoLabel.text = notificationItem.createdAt.convertAgoText() notificationItem.from.get { (fromUser, error) in if let fromUser = fromUser { self.voderImageView.loadUserImageView(with: fromUser) } else { self.voderImageView.setEmptyUserImage() } } } } <file_sep>/KaoSouou/On/CustomFirstView.swift // // CustomFirstView.swift // KaoSouou // // Created by <NAME> on 2019/01/11. // Copyright © 2019年 <NAME>. All rights reserved. // import UIKit import SwiftyOnboard class CustomFirstView: SwiftyOnboardPage { // @IBOutlet weak var titleLabel: UILabel! // @IBOutlet weak var image: UIImageView! // @IBOutlet weak var subTitleLabel: UILabel! // @IBOutlet weak var neonBarView: UIView! override func awakeFromNib() { super.awakeFromNib() } class func instanceFromNib() -> UIView { return UINib(nibName: "CustomFirstView", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView } } <file_sep>/Podfile # Uncomment the next line to define a global platform for your project # platform :ios, '9.0' target 'KaoSouou' do # Comment the next line if you're not using Swift and don't want to use dynamic frameworks use_frameworks! pod 'Firebase/Core' pod 'Firebase/Firestore' pod 'Firebase/Auth' pod 'Firebase/Messaging' pod 'Pring' pod 'FacebookCore' pod 'FacebookLogin' pod 'FacebookShare' pod 'Kingfisher', '~> 4.0' pod 'SwiftyJSON' pod 'SVProgressHUD' pod 'FontAwesome.swift' pod 'DZNEmptyDataSet' pod 'SwiftDate' pod "MIBadgeButton-Swift", :git => 'https://github.com/mustafaibrahim989/MIBadgeButton-Swift.git', :branch => 'master' pod 'RSKImageCropper' pod 'TTTAttributedLabel' pod 'SwiftyOnboard' pod 'ADDatePicker' pod "Device", '~> 3.1.2' pod 'M13Checkbox' pod 'TwitterKit' pod 'Fabric' pod 'Crashlytics' target 'KaoSououTests' do inherit! :search_paths # Pods for testing end target 'KaoSououUITests' do inherit! :search_paths # Pods for testing end end <file_sep>/KaoSouou/Models/User.swift // // User.swift // KaoSouou // // Created by <NAME> on 2018/03/15. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import Firebase import Pring @objcMembers class User : Object{ dynamic var allowedFlag: Bool = false dynamic var originId: String = "" dynamic var displayName: String = "" dynamic var email: String = "" dynamic var photoFile: File? dynamic var hensachi: Double = 0 dynamic var gender: Int = 0 dynamic var birthday: String = "" dynamic var kaisu: Int = 0 dynamic var loveUsers: ReferenceCollection<User> = [] dynamic var notificationItems: ReferenceCollection<NotificationItem> = [] dynamic var results: ReferenceCollection<Result> = [] dynamic var fcmToken: String = "" dynamic var badgeNum: Int = 0 } <file_sep>/KaoSouou/Extention/Date+Extension.swift // // Date+Extension.swift // KaoSouou // // Created by <NAME> on 2018/06/21. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import SwiftDate extension Date { func convertAgoText() -> String { var agoText: String! let agodate = self.timeIntervalSinceNow * -1 if agodate.toUnit(.minute)! < 60 { agoText = String(agodate.toUnit(.minute)!) + "分前" } else if agodate.toUnit(.hour)! < 24 { agoText = String(agodate.toUnit(.hour)!) + "時間前" } else if agodate.toUnit(.day)! < 7 { agoText = String(agodate.toUnit(.day)!) + "日前" } else if agodate.toUnit(.month)! < 1 { agoText = String(agodate.toUnit(.day)! / 7) + "週間前" } else { agoText = String(agodate.toUnit(.month)!) + "ヶ月前" } print("変換Date before", self) print("変換Date after", agoText) return agoText } } <file_sep>/KaoSouou/Mypage/ResultListViewController.swift // // ResultListViewController.swift // KaoSouou // // Created by <NAME> on 2018/06/21. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Pring import DZNEmptyDataSet class ResultListViewController: UIViewController, Storyboardable { @IBOutlet weak var tableView: UITableView! @IBOutlet weak var closeButton: UIBarButtonItem! var notificationItem: NotificationItem? var currentResult: Result? override func viewDidLoad() { super.viewDidLoad() tableView.delegate = self tableView.dataSource = self tableView.register(ResultTableViewCell.self) tableView.isScrollEnabled = false tableView.separatorStyle = .none tableView.allowsSelection = false } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) fetchResults() } func fetchResults() { guard let notificationItem = notificationItem else { return } notificationItem.result.get { (result, error) in if let result = result { self.currentResult = result self.fetchVoter(result: result) self.tableView.reloadData() } } } func fetchVoter(result: Result) { result.voter.get { (user, error) in if let user = user { let name = user.displayName self.navigationItem.title = name + "のチェック" } } } @IBAction func tapCloseButton(_ sender: Any) { dismiss(animated: true, completion: nil) } } extension ResultListViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 9 } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { let navigationController: UINavigationController = UINavigationController() let navigationBarHeight = navigationController.navigationBar.frame.size.height let statusbarHeight = UIApplication.shared.statusBarFrame.size.height let contentHeight = UIScreen.main.bounds.size.height - (navigationBarHeight + statusbarHeight) let headerHeight = (contentHeight / 7) * 3 let bottomHeight = (contentHeight / 7) * 4 if indexPath.row < 3 { let height = headerHeight / 3 print("height : ", indexPath.row, "→", height) return height } else { let height = bottomHeight / 6 print("height : ", indexPath.row, "→", height) return height } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(with: ResultTableViewCell.self, for: indexPath) switch indexPath.row { case 0: currentResult?.first.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 1: currentResult?.second.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 2: currentResult?.third.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 3: currentResult?.fource.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 4: currentResult?.fifth.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 5: currentResult?.sixth.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 6: currentResult?.seventh.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 7: currentResult?.eighth.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) case 8: currentResult?.ninth.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) default: currentResult?.ninth.get({ (user, error) in cell.configure(with: indexPath.row + 1, user: user) }) } return cell } } extension ResultListViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // 他のユーザー表示する // tableView.deselectRow(at: indexPath, animated: true) // let viewController = OtherUserProfileViewController.instantiate() // viewController.user = cell.user // present(viewController, animated: true, completion: nil) } } <file_sep>/KaoSouou/On/CustomOverlay.swift // // CustomOverlay.swift // SwiftyOnboardExample // // Created by Jay on 3/27/17. // Copyright © 2017 <NAME>. All rights reserved. // import UIKit import SwiftyOnboard import TTTAttributedLabel import SafariServices class CustomOverlay: SwiftyOnboardOverlay { @IBOutlet weak var skip: UIButton! @IBOutlet weak var buttonContinue: UIButton! @IBOutlet weak var contentControl: UIPageControl! override func awakeFromNib() { super.awakeFromNib() buttonContinue.layer.borderColor = UIColor.white.cgColor buttonContinue.layer.borderWidth = 1 buttonContinue.layer.cornerRadius = buttonContinue.bounds.height / 2 } class func instanceFromNib() -> UIView { return UINib(nibName: "CustomOverlay", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView } // func configure(noticeLabel: TTTAttributedLabel) { // noticeLabel.delegate = self // noticeLabel.linkAttributes = [kCTForegroundColorAttributeName as AnyHashable: #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1), // NSAttributedStringKey.underlineStyle: NSUnderlineStyle.styleSingle.rawValue] // noticeLabel.activeLinkAttributes = [kCTForegroundColorAttributeName as AnyHashable: #colorLiteral(red: 0, green: 0.4784313725, blue: 1, alpha: 1)] // // if let text = noticeLabel.text { //// noticeLabel.addLink(to: URL(string: "https://yolo-app-tos.pagedemo.co/"), with: NSString(string: text).range(of: "利用規約")) //// noticeLabel.addLink(to: URL(string: "https://yolo-app-privacy.pagedemo.co/"), with: NSString(string: text).range(of: "プライバシーポリシー")) // } // } } extension CustomOverlay: TTTAttributedLabelDelegate { func attributedLabel(_ label: TTTAttributedLabel!, didSelectLinkWith url: URL!) { let safariViewController = SFSafariViewController(url: url) let currentViewController = parentViewController() currentViewController?.present(safariViewController, animated: true, completion: nil) } } extension UIView { func parentViewController() -> UIViewController? { var parentResponder: UIResponder? = self while true { guard let nextResponder = parentResponder?.next else { return nil } if let viewController = nextResponder as? UIViewController { return viewController } parentResponder = nextResponder } } } <file_sep>/KaoSouou/Models/AccountManager.swift // // AccountManager.swift // KaoSouou // // Created by <NAME> on 2018/03/15. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit class AccountManager: NSObject { static let shared = AccountManager() var currentUser: User? } <file_sep>/KaoSouou/Extention/Array+Extention.swift // // Array+Extention.swift // KaoSouou // // Created by <NAME> on 2018/05/17. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import UIKit extension Array { subscript (safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } } <file_sep>/KaoSouou/Main/humanCell.swift // // humanCell.swift // KaoSouou // // Created by <NAME> on 2018/02/19. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit class humanCell: UICollectionViewCell, Nibable { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var numLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() numLabel.isHidden = true numLabel.lblShadow(radius: 3, opacity: 0.25) numLabel.textColor = UIColor.white } func configure(with user: User, num: Int) { imageView.loadUserImageView(with: user) if num == 0 { numLabel.isHidden = true } else { numLabel.isHidden = false numLabel.text = String(num) } } func configure(with image: UIImage, num: Int) { imageView.image = image if num == 0 { numLabel.isHidden = true } else { numLabel.isHidden = false numLabel.text = String(num) } } func emptyConfigure() { numLabel.text = "" imageView.image = nil imageView.backgroundColor = UIColor.black } func check(with num: Int) { numLabel.text = String(num) numLabel.isHidden = false // isUserInteractionEnabled = false } func uncheck() { numLabel.text = "" numLabel.isHidden = true // isUserInteractionEnabled = true } } <file_sep>/KaoSouou/Models/Result.swift // // Result.swift // KaoSouou // // Created by <NAME> on 2018/06/20. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import Firebase import Pring @objcMembers class Result : Object{ dynamic var voter: Reference<User> = .init() dynamic var first: Reference<User> = .init() dynamic var second: Reference<User> = .init() dynamic var third: Reference<User> = .init() dynamic var fource: Reference<User> = .init() dynamic var fifth: Reference<User> = .init() dynamic var sixth: Reference<User> = .init() dynamic var seventh: Reference<User> = .init() dynamic var eighth: Reference<User> = .init() dynamic var ninth: Reference<User> = .init() } <file_sep>/KaoSouou/Mypage/MyPageViewController.swift // // MyPageViewController.swift // KaoSouou // // Created by <NAME> on 2018/05/07. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Pring import Firebase import Kingfisher import MIBadgeButton_Swift import FontAwesome_swift class MyPageViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var faceImageView: UIImageView! @IBOutlet weak var effectView: UIVisualEffectView! @IBOutlet weak var hensachiLabel: UILabel! @IBOutlet weak var kaisuLabel: UILabel! @IBOutlet weak var closeButton: UIButton! @IBOutlet weak var settingButton: UIButton! @IBOutlet weak var bellButton: MIBadgeButton! @IBOutlet weak var firstNumImageView: UIImageView! @IBOutlet weak var secondNumImageView: UIImageView! @IBOutlet weak var thirdNumImageView: UIImageView! @IBOutlet weak var dotImageView: UIImageView! var userDataSourse: DataSource<User>? override func viewDidLoad() { super.viewDidLoad() faceImageView.clipsToBounds = true faceImageView.contentMode = .scaleAspectFill setLongPress() getUserDataSource() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) setButton() loadBadge() } func setButton() { closeButton.layer.cornerRadius = closeButton.bounds.height / 2 closeButton.layer.borderWidth = 1 closeButton.layer.borderColor = UIColor.white.cgColor closeButton.clipsToBounds = true closeButton.btnShadow(radius: 0.5, opacity: 0.5) } func getUserDataSource() { guard let currentUser = AccountManager.shared.currentUser else { return } userDataSourse = User.where(\User.originId, isEqualTo: currentUser.originId).limit(to: 1).dataSource().on({ (snapShot, changes) in switch changes { case .initial: self.loadData() case .update(let deletions, let insertions, let modifications): self.loadData() case .error(let error): print(error) } }).listen() } func loadData() { guard let userDataSourse = userDataSourse else { return } let currentUser = userDataSourse.first! if currentUser.gender == 2 { self.self.userNameLabel.text = "💁‍♀️ \(currentUser.displayName)" } else { self.self.userNameLabel.text = "💁‍♂️ \(currentUser.displayName)" } self.faceImageView.loadUserImageView(with: currentUser) self.hensachiLabel.text = String(currentUser.hensachi.shisyagonyu()) self.kaisuLabel.text = String(currentUser.kaisu) setNeon(hensachi: currentUser.hensachi.shisyagonyu()) } func loadBadge() { guard let currentUser = AccountManager.shared.currentUser else { return } print("badgeの生存確認 : ",currentUser.badgeNum) if currentUser.badgeNum > 0{ bellButton.badgeString = String(currentUser.badgeNum) } } @IBAction func tapSettingButton(_ sender: Any) { let alert = UIAlertController(title: "設定", message: nil, preferredStyle: .actionSheet) let terms = UIAlertAction(title: "利用規約", style: .default) { (action) in print("利用規約") let postUrl = URL(string:"https://faceislife.studio.design/support/terms") UIApplication.shared.open(postUrl!) } let privacy = UIAlertAction(title: "プライバシーポリシー", style: .default) { (action) in print("プライバシーポリシー") let postUrl = URL(string:"https://faceislife.studio.design/support/privacy") UIApplication.shared.open(postUrl!) } let questoin = UIAlertAction(title: "Twitterで問い合わせ", style: .default) { (action) in print("問い合わせ") let postUrl = URL(string: "http://twitter.com/faceislife") UIApplication.shared.open(postUrl!, options: [:], completionHandler: nil) // if UIApplication.shared.canOpenURL(URL(string: "twitter://")!) { // // // //// let postUrl = URL(string: "http://twitter.com/faceislife") //// UIApplication.shared.open(postUrl!, options: [:], completionHandler: nil) // //// let postUrl = URL(string: "twitter:@faceislife") //// print("Twitter インストール済み") //// UIApplication.shared.open(postUrl!, options: [:], completionHandler: nil) // } else { //// let postUrl = URL(string: "http://twitter.com/%@faceislife") //// UIApplication.shared.open(postUrl!, options: [:], completionHandler: nil) // } } let logOut = UIAlertAction(title: "ログアウト", style: .destructive) { (action) in print("ログアウト") self.logout { print("ログアウト成功") DispatchQueue.main.async { self.dismiss(animated: false, completion: { AccountManager.shared.currentUser = nil AppDelegate.shared.rootViewController.switchToLogin() }) } } } let profileEdit = UIAlertAction(title: "プロフィール編集", style: .default) { (action) in print("プロフィール編集") let sb = UIStoryboard(name: "SetProfile", bundle: nil) let vc = sb.instantiateInitialViewController() as! SetProfileViewController vc.currentType = .edit self.show(vc, sender: nil) } let tutorial = UIAlertAction(title: "使い方", style: .default) { (action) in print("使い方") let sb = UIStoryboard(name: "Onboard", bundle: nil) let vc = sb.instantiateInitialViewController() as! OnboardViewController vc.fromAppHelp = true self.present(vc, animated: true) { print("go to loveUserList") } } let otherMenu = UIAlertAction(title: "その他", style: .default) { (action) in print("その他") } let cancel = UIAlertAction(title: "キャンセル", style: .cancel) { (actiona) in print("キャンセル") } alert.addAction(profileEdit) alert.addAction(questoin) alert.addAction(tutorial) alert.addAction(terms) alert.addAction(privacy) alert.addAction(logOut) alert.addAction(cancel) self.present(alert, animated: true, completion: nil) } func logout(_ completion: @escaping () -> Void) { let user = AccountManager.shared.currentUser user?.update({ (error) in if let error = error { print(error.localizedDescription) return } else { try? Auth.auth().signOut() // AccountManager.shared.currentUser = nil completion() } }) } func setNeon(hensachi: Double) { guard let user = AccountManager.shared.currentUser else { return } let firstNum = hensachi / 10 let secondNum = hensachi.truncatingRemainder(dividingBy: 10) / 1 let thirdNum = hensachi.truncatingRemainder(dividingBy: 1) var key = "j" if user.gender == 2 { //女子 key = "j" } else { //男子 key = "d" } firstNumImageView.image = UIImage(named: key + String(firstNum)) secondNumImageView.image = UIImage(named: key + String(secondNum)) thirdNumImageView.image = UIImage(named: key + String(thirdNum)) dotImageView.image = UIImage(named: key + "dot") } @IBAction func tapCloseButton(_ sender: Any) { self.dismiss(animated: true) { print("Mypage Close") } } @IBAction func tapLovesButton(_ sender: Any) { print("プロフィール編集") let sb = UIStoryboard(name: "LoveUserList", bundle: nil) let nc = sb.instantiateInitialViewController() as! UINavigationController self.present(nc, animated: true) { print("go to loveUserList") } } @IBAction func tapBellButton(_ sender: Any) { bellButton.badgeString = "" let sb = UIStoryboard(name: "NotificationList", bundle: nil) let nc = sb.instantiateInitialViewController() as! UINavigationController present(nc, animated: true) { print("go to notification") } } func setLongPress() { let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(MyPageViewController.longPress(_:))) longPressGesture.delegate = self effectView.addGestureRecognizer(longPressGesture) } // Long Press イベント @objc func longPress(_ sender: UILongPressGestureRecognizer){ if sender.state == .began { print("LongPress began") effectView.isHidden = true } else if sender.state == .ended { effectView.isHidden = false } } } <file_sep>/KaoSouou/TOP/GenderSelectViewController.swift // // GenderSelectViewController.swift // KaoSouou // // Created by <NAME> on 2018/05/21. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import SVProgressHUD class GenderSelectViewController: UIViewController { @IBOutlet weak var boyButton: UIButton! @IBOutlet weak var girlButton: UIButton! @IBOutlet weak var nextButton: UIButton! var gender: genderType? enum genderType: Int { case boy = 1 case girl } override func viewDidLoad() { super.viewDidLoad() setButton() nextButton.isHidden = true nextButton.isEnabled = false } func setButton() { nextButton.layer.cornerRadius = nextButton.bounds.height / 2 nextButton.layer.borderWidth = 1 nextButton.layer.borderColor = UIColor.white.cgColor nextButton.clipsToBounds = true } @IBAction func tapBoyButton(_ sender: Any) { gender = genderType.boy nextButton.isHidden = false nextButton.isEnabled = true boyButton.titleLabel?.font = UIFont.systemFont(ofSize: 80) girlButton.titleLabel?.font = UIFont.systemFont(ofSize: 48) } @IBAction func tapGirlButton(_ sender: Any) { gender = genderType.girl nextButton.isHidden = false nextButton.isEnabled = true boyButton.titleLabel?.font = UIFont.systemFont(ofSize: 48) girlButton.titleLabel?.font = UIFont.systemFont(ofSize: 80) } @IBAction func tapNextButton(_ sender: Any) { next() } func next() { if let gender = gender { let currentUser = AccountManager.shared.currentUser currentUser?.gender = gender.rawValue currentUser?.update({ (error) in if let error = error { print(error.localizedDescription) } else { print("gender設定成功") AppDelegate.shared.rootViewController.showBirthdaySelectScreen() } }) } else { print("gender設定してない") } } } <file_sep>/KaoSouou/TOP/SetProfileViewController.swift // // SetProfileViewController.swift // KaoSouou // // Created by <NAME> on 2018/06/13. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Pring import Kingfisher import SVProgressHUD import RSKImageCropper enum stateType { case initial, edit } class SetProfileViewController: UIViewController { @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var profileBaseImageView: UIImageView! @IBOutlet weak var nameTextField: UITextField! @IBOutlet weak var nextButton: UIButton! @IBOutlet weak var scrollView: UIScrollView! var photoUrl: URL? var currentType = stateType.initial var newImage: UIImage? @IBOutlet weak var profileImageWidth: NSLayoutConstraint! @IBOutlet weak var profileImageHeight: NSLayoutConstraint! override func viewDidLoad() { super.viewDidLoad() nameTextField.delegate = self scrollView.delegate = self configure() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) let notificationCenter = NotificationCenter.default notificationCenter.addObserver(self, selector: #selector(SetProfileViewController.handleKeyboardWillShowNotification(_:)), name: NSNotification.Name.UIKeyboardWillShow, object: nil) notificationCenter.addObserver(self, selector: #selector(SetProfileViewController.handleKeyboardWillHideNotification(_:)), name: NSNotification.Name.UIKeyboardWillHide, object: nil) setData() } func configure() { profileImageView.contentMode = .scaleAspectFill profileImageView.clipsToBounds = true profileBaseImageView.contentMode = .scaleAspectFill profileBaseImageView.clipsToBounds = true profileImageHeight.constant = UIScreen.main.bounds.size.height / 3 profileImageWidth.constant = UIScreen.main.bounds.size.width / 3 nameTextField.addUnderline(width: 1.0, color: UIColor.white) nextButton.layer.cornerRadius = nextButton.bounds.height / 2 nextButton.layer.borderWidth = 1 nextButton.layer.borderColor = UIColor.white.cgColor nextButton.clipsToBounds = true scrollView.isScrollEnabled = false } func setData() { guard let user = AccountManager.shared.currentUser else { return } nameTextField.text = user.displayName if let photoUrl = photoUrl { // 最初のユーザー登録時 if let newImage = newImage { self.profileImageView.image = newImage self.profileBaseImageView.image = newImage } else { self.profileImageView.loadUrlImageView(url: photoUrl) self.profileBaseImageView.loadUrlImageView(url: photoUrl) } } else { if let newImage = newImage { self.profileImageView.image = newImage self.profileBaseImageView.image = newImage } else { self.profileImageView.loadUserImageView(with: user) self.profileBaseImageView.loadUserImageView(with: user) } } } @IBAction func tapUserProfileImageView(_ sender: Any) { showImagePickerController() } @objc func handleKeyboardWillShowNotification(_ notification: Notification) { let userInfo = notification.userInfo! let keyboardScreenEndFrame = (userInfo[UIKeyboardFrameEndUserInfoKey] as! NSValue).cgRectValue let myBoundSize: CGSize = UIScreen.main.bounds.size var txtLimit = nameTextField.frame.origin.y + nameTextField.frame.height + 12.0 let kbdLimit = myBoundSize.height - keyboardScreenEndFrame.size.height print("テキストフィールドの下辺:(\(txtLimit))") print("キーボードの上辺:(\(kbdLimit))") if txtLimit >= kbdLimit { scrollView.contentOffset.y = txtLimit - kbdLimit } } @objc func handleKeyboardWillHideNotification(_ notification: Notification) { scrollView.contentOffset.y = 0 } func showImagePickerController() { let imagePickerController = UIImagePickerController() imagePickerController.delegate = self imagePickerController.sourceType = .photoLibrary present(imagePickerController, animated: true, completion: nil) } @IBAction func tapCloseButton(_ sender: Any) { dismiss(animated: true, completion: nil) } @IBAction func tapNextButton(_ sender: Any) { guard let user = AccountManager.shared.currentUser else { return } SVProgressHUD.show() user.displayName = nameTextField.text ?? "" if let image = profileImageView.image, let photoData = UIImageJPEGRepresentation(image, 0.5) { user.photoFile = File(data: photoData) } user.update { (error) in SVProgressHUD.dismiss() if let error = error { print(error.localizedDescription) } else { DispatchQueue.main.async { switch self.currentType { case .initial: AppDelegate.shared.rootViewController.switchToGenderSelect() case .edit: self.dismiss(animated: true, completion: nil) } } } } } } extension SetProfileViewController : UITextFieldDelegate { func textFieldShouldReturn(_ textField: UITextField) -> Bool { if textField == nameTextField { nameTextField.resignFirstResponder() } return true } } extension SetProfileViewController : UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage let imageCropVC = RSKImageCropViewController(image: image, cropMode: RSKImageCropMode.custom) imageCropVC.delegate = self imageCropVC.dataSource = self picker.show(imageCropVC, sender: nil) } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } extension SetProfileViewController : RSKImageCropViewControllerDelegate { func imageCropViewControllerDidCancelCrop(_ controller: RSKImageCropViewController) { controller.dismiss(animated: true, completion: nil) } func imageCropViewController(_ controller: RSKImageCropViewController!, willCropImage originalImage: UIImage!) { } func imageCropViewController(_ controller: RSKImageCropViewController, didCropImage croppedImage: UIImage, usingCropRect cropRect: CGRect, rotationAngle: CGFloat) { newImage = croppedImage self.dismiss(animated: true, completion: nil) } } extension SetProfileViewController : RSKImageCropViewControllerDataSource { func imageCropViewControllerCustomMaskRect(_ controller: RSKImageCropViewController) -> CGRect { var maskSize: CGSize var width, height: CGFloat! width = UIScreen.main.bounds.size.width height = UIScreen.main.bounds.size.height maskSize = CGSize(width: width, height: height) var maskRect: CGRect = CGRect(x: 48, y: 48, width: maskSize.width - 96, height: maskSize.height - 96) return maskRect } // トリミングしたい領域を描画(今回は四角な領域です・・・) func imageCropViewControllerCustomMaskPath(_ controller: RSKImageCropViewController) -> UIBezierPath! { var rect: CGRect = controller.maskRect var point1: CGPoint = CGPoint(x: rect.minX, y: rect.maxY) var point2: CGPoint = CGPoint(x: rect.maxX, y: rect.maxY) var point3: CGPoint = CGPoint(x: rect.maxX, y: rect.minY) var point4: CGPoint = CGPoint(x: rect.minX, y: rect.minY) var square: UIBezierPath = UIBezierPath() square.move(to: point1) square.addLine(to: point2) square.addLine(to: point3) square.addLine(to: point4) square.close() return square } func imageCropViewControllerCustomMovementRect(_ controller: RSKImageCropViewController) -> CGRect { return controller.maskRect } } <file_sep>/KaoSouou/Extention/UICollectionView+Extension.swift // // UICollectionView+Extension.swift // KaoSouou // // Created by <NAME> on 2018/02/19. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import UIKit extension UICollectionView { func register<T: UICollectionViewCell>(_ cellType: T.Type) where T: Nibable { register(T.nib, forCellWithReuseIdentifier: T.identifier) } func register<T: UICollectionViewCell>(_ cellType: T.Type) { register(T.self, forCellWithReuseIdentifier: T.identifier) } func dequeueReusableCell<T: UICollectionViewCell>(with cellType: T.Type, for indexPath: IndexPath) -> T { return dequeueReusableCell(withReuseIdentifier: T.identifier, for: indexPath) as! T } public func reloadData(_ completion: @escaping () -> Void) { UIView.animate(withDuration: 0, animations: { self.reloadData() }, completion: { _ in completion() }) } } extension UICollectionViewCell { static var identifier: String { return className } } <file_sep>/KaoSouou/Mypage/ResultTableViewCell.swift // // ResultTableViewCell.swift // KaoSouou // // Created by <NAME> on 2018/06/21. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit class ResultTableViewCell: UITableViewCell, Nibable { @IBOutlet weak var numlabel: UILabel! @IBOutlet weak var profileImageView: UIImageView! @IBOutlet weak var nameLabel: UILabel! @IBOutlet weak var hensachiLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() profileImageView.setEmptyUserImage() } func configure(with num: Int, user: User?) { profileImageView.layer.cornerRadius = profileImageView.bounds.width / 2 profileImageView.clipsToBounds = true switch num { case 1: numlabel.text = "🥇" case 2: numlabel.text = "🥈" case 3: numlabel.text = "🥉" default: numlabel.text = String(num) } if let user = user { profileImageView.loadUserImageView(with: user) nameLabel.text = user.displayName hensachiLabel.text = String(user.hensachi.shisyagonyu()) } else { profileImageView.setEmptyUserImage() nameLabel.text = "???" hensachiLabel.text = "???" } guard let currentUser = AccountManager.shared.currentUser else { return } guard let user = user else { return } if currentUser.id == user.id { if currentUser.gender == 2 { self.contentView.backgroundColor = UIColor.girlBrandColor() } else { self.contentView.backgroundColor = UIColor.boyBrandColor() } } } } <file_sep>/KaoSouou/Extention/UIImageView+Extension.swift // // UIImageView+Extension.swift // KaoSouou // // Created by <NAME> on 2018/06/16. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import UIKit import Kingfisher import Pring import FontAwesome_swift extension UIImageView { func loadUserImageView(with user: User) { self.contentMode = .scaleAspectFill self.clipsToBounds = true self.kf.indicatorType = .activity var loadUrl: URL? if let photoFile = user.photoFile { loadUrl = photoFile.downloadURL self.kf.setImage(with: loadUrl, placeholder: nil, options: [.transition(ImageTransition.fade(1))], progressBlock: { (receivedSize, totalSize) in print("\(receivedSize)/\(totalSize)") }) { (image, error, cacheType, imageURL) in if let imageURL = imageURL { print("\(imageURL): Finished") } else { self.setErrorImage() } } } else { self.setErrorImage() } } func loadUrlImageView(url: URL) { self.contentMode = .scaleAspectFill self.clipsToBounds = true self.kf.indicatorType = .activity self.kf.setImage(with: url, placeholder: nil, options: [.transition(ImageTransition.fade(1))], progressBlock: { (receivedSize, totalSize) in print("\(receivedSize)/\(totalSize)") }) { (image, error, cacheType, imageURL) in if let imageURL = imageURL { print("\(imageURL): Finished") } else { self.setErrorImage() } } } func setErrorImage() { let size = CGSize(width: self.frame.size.height / 3, height: self.frame.size.height / 3) let errorImage = UIImage.fontAwesomeIcon(name: .image , style: .brands, textColor: UIColor.white, size: size) self.image = errorImage } func setEmptyUserImage() { let size = CGSize(width: self.frame.size.height / 3, height: self.frame.size.height / 3) let errorImage = UIImage.fontAwesomeIcon(name: .user , style: .brands, textColor: UIColor.white, size: size) self.image = errorImage } } <file_sep>/KaoSouou/AppDelegate.swift // // AppDelegate.swift // KaoSouou // // Created by <NAME> on 2018/02/19. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import UserNotifications import Firebase import FirebaseMessaging import FacebookCore import FacebookLogin import TwitterKit import Fabric import Crashlytics @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { FirebaseApp.configure() SDKApplicationDelegate.shared.application(application, didFinishLaunchingWithOptions: launchOptions) TWTRTwitter.sharedInstance().start(withConsumerKey: "<KEY>", consumerSecret: "<KEY>") Fabric.with([Crashlytics.self]) UNUserNotificationCenter.current().delegate = self self.window = UIWindow(frame: UIScreen.main.bounds) self.window?.rootViewController = RootViewController() self.window?.makeKeyAndVisible() //ナビゲーションアイテムの色を変更 UINavigationBar.appearance().tintColor = UIColor.white //ナビゲーションバーの背景を変更 UINavigationBar.appearance().barTintColor = UIColor.black //ナビゲーションのタイトル文字列の色を変更 let attrs = [ NSAttributedStringKey.foregroundColor: UIColor.white ] UINavigationBar.appearance().titleTextAttributes = attrs UIApplication.shared.applicationIconBadgeNumber = 0 return true } func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool { // if TWTRTwitter.sharedInstance().application(app, open: url, options: options) { // return true // } else { // return SDKApplicationDelegate.shared.application(app, open: url, options: options) // } // if TWTRTwitter.sharedInstance().application(app, open: url, options: options) { return true } if SDKApplicationDelegate.shared.application(app, open: url, options: options) { return true } return false } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) { print("userInfo : ", userInfo) // アプリが起動している間に通知を受け取った場合の処理を行う。 } func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) { // アプリがバックグラウンド状態の時に通知を受け取った場合の処理を行う。 print("userInfo : ", userInfo) completionHandler(UIBackgroundFetchResult.newData) } func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { print("プッシュ通知登録失敗 : ", error) // システムへのプッシュ通知の登録が失敗した時の処理を行う。 } func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // Device Token を取得した時の処理を行う。 print("APNs token retrieved: \(deviceToken)") } } extension AppDelegate : UNUserNotificationCenterDelegate { // iOS 10 以降では通知を受け取るとこちらのデリゲートメソッドが呼ばれる。 // foreground で受信 func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) { let content = notification.request.content // Push Notifications のmessageを取得 let badge = content.badge let body = notification.request.content.body let toOriginId = content.userInfo["toUserOriginId"] as! String print("content : ", content) print("userNotificationCenterのwillPresentから: \(body), \(badge)") // ログインしてるユーザーのみ通す if let currentUser = AccountManager.shared.currentUser { if currentUser.originId == toOriginId { // iphone7 haptic feedback let feedbackGenerator = UINotificationFeedbackGenerator() feedbackGenerator.notificationOccurred(.success) // audio & vibrater AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil) showNotificationAlert() } } completionHandler([]) } // background で受信してアプリを起動 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) { // Push Notifications のmessageを取得 let content = response.notification.request.content let badge = content.badge let body = response.notification.request.content.body let toOriginId = content.userInfo["toUserOriginId"] as! String print("userNotificationCenterのdidReceiveから: \(body), \(badge)") print("content : ", content) // ログインしてるユーザーのみ通す if let currentUser = AccountManager.shared.currentUser { if currentUser.originId == toOriginId { showNotificationAlert() } } completionHandler() } } extension AppDelegate: MessagingDelegate { func messaging(_ messaging: Messaging, didReceiveRegistrationToken fcmToken: String) { print("Firebase registration token: \(fcmToken)") } } extension AppDelegate { static var shared: AppDelegate { return UIApplication.shared.delegate as! AppDelegate } var rootViewController: RootViewController { return window!.rootViewController as! RootViewController } } extension AppDelegate { func showNotificationAlert() { let alert = UIAlertController(title: "新しくチョイスされたよ!", message: "何位だったか確認してみよう!", preferredStyle: .alert) let defaultAction: UIAlertAction = UIAlertAction(title: "チェケラ!", style: .default) { (action) in print("画面遷移") let notificationSB = UIStoryboard(name: "NotificationList", bundle: nil) let notificationVC = notificationSB.instantiateInitialViewController() as! UINavigationController if let topController = UIApplication.topViewController() { topController.show(notificationVC, sender: nil) } } let cancelAction: UIAlertAction = UIAlertAction(title: "やめとく", style: .destructive) { (action) in print("Cancel") } alert.addAction(defaultAction) alert.addAction(cancelAction) if let topController = UIApplication.topViewController() { topController.present(alert, animated: true, completion: nil) } } } <file_sep>/KaoSouou/Main/ViewController.swift // // ViewController.swift // KaoSouou // // Created by <NAME> on 2018/02/19. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import Kingfisher import Pring import UserNotifications import Firebase import SVProgressHUD class ViewController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! @IBOutlet weak var mypageButton: UIButton! @IBOutlet weak var resetButton: UIButton! //ローディングで使う要素 @IBOutlet weak var coverView: UIView! @IBOutlet weak var oneLabel: UILabel! @IBOutlet weak var twoLabel: UILabel! @IBOutlet weak var threeLabel: UILabel! @IBOutlet weak var loadLabel: UILabel! // TEST データがない時用の仮データ var humanArray = [UIImage]() var girlsArray = [#imageLiteral(resourceName: "g2"),#imageLiteral(resourceName: "g3"),#imageLiteral(resourceName: "g8"),#imageLiteral(resourceName: "g0"),#imageLiteral(resourceName: "g5"),#imageLiteral(resourceName: "g4"),#imageLiteral(resourceName: "g6"),#imageLiteral(resourceName: "g7"),#imageLiteral(resourceName: "g1")] var mensArray = [#imageLiteral(resourceName: "m3"),#imageLiteral(resourceName: "m0"),#imageLiteral(resourceName: "m4"),#imageLiteral(resourceName: "m6"),#imageLiteral(resourceName: "m2"),#imageLiteral(resourceName: "m1"),#imageLiteral(resourceName: "m5"),#imageLiteral(resourceName: "m7"),#imageLiteral(resourceName: "m8")] var kaoUserArray = [User]() var currentKaoUserArray = [User]() var numArray = [0,0,0,0,0,0,0,0,0] //9人の順位が入っていく 例) [9,1,2,3,6,4,7,5,8] var selectNum = 0 var firstUser: User? var firstFace: UIImage? var disEnabledCellArray = [humanCell]() var selectCell: humanCell? var oldSelectCell: humanCell? var timer = Timer() var finishFlag = false var userDataSourse: DataSource<User>? override func viewDidLoad() { super.viewDidLoad() setButton() collectionView.dataSource = self collectionView.delegate = self requestPush() } func requestPush() { UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .sound, .badge], completionHandler: { (granted, error) in if let error = error { print(error.localizedDescription) } if granted { print("プッシュ通知ダイアログ 許可") UIApplication.shared.registerForRemoteNotifications() } else { print("プッシュ通知ダイアログ 拒否") } }) } func setButton() { mypageButton.layer.cornerRadius = mypageButton.bounds.height / 2 mypageButton.layer.borderWidth = 1 mypageButton.layer.borderColor = UIColor.white.cgColor mypageButton.clipsToBounds = true mypageButton.btnShadow(radius: 0.5, opacity: 0.5) resetButton.layer.cornerRadius = resetButton.bounds.height / 2 resetButton.layer.borderWidth = 1 resetButton.layer.borderColor = UIColor.white.cgColor resetButton.clipsToBounds = true resetButton.btnShadow(radius: 0.5, opacity: 0.5) } func startLoding() { coverView.isHidden = false oneLabel.isHidden = false twoLabel.isHidden = false threeLabel.isHidden = false loadLabel.isHighlighted = false loading() } func stopLoading() { coverView.isHidden = true oneLabel.isHidden = true twoLabel.isHidden = true threeLabel.isHidden = true loadLabel.isHighlighted = true timer.invalidate() } func loading() { var count = 0 timer = Timer.scheduledTimer(withTimeInterval: 0.3, repeats: true, block: { (timer) in count += 1 self.changeLoadView(count: count) }) } func changeLoadView(count: Int) { let key = count % 3 switch key { case 0: oneLabel.text = "🦄" twoLabel.text = "🐴" threeLabel.text = "🐴" case 1: oneLabel.text = "🐴" twoLabel.text = "🦄" threeLabel.text = "🐴" case 2: oneLabel.text = "🐴" twoLabel.text = "🐴" threeLabel.text = "🦄" default: oneLabel.text = "🐴" twoLabel.text = "🐴" threeLabel.text = "🦄" } } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) finishFlag = false collectionView.reloadData() // ローカルのUserのArray(kaoUserArray)がまだ9あればそのまま使う。なければまた取ってくる。 // 本番は一日あたりに選択できる回数を制限する場合はここに何かしらの追記が必要 self.startLoding() guard let currentUser = AccountManager.shared.currentUser else { return } // TODO: elseの時のアラート出す if kaoUserArray.count >= 9 { createCurrentKaoUserArray() self.collectionView.reloadData { DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { self.stopLoading() } } } else { if currentUser.gender == 2 { humanArray = mensArray getUserArray(with: 1) } else { humanArray = girlsArray getUserArray(with: 2) } } } // 全Userを性別でwhereかけて取ってくる // 取ってきた後、arrayをshuffleしてcollectionViewをリロード func getUserArray(with genderNum: Int) { kaoUserArray.removeAll() userDataSourse = User .where(\User.gender, isEqualTo: genderNum) .where(\User.allowedFlag, isEqualTo: true) .order(by: \User.createdAt) .dataSource() .onCompleted({ (snapshot, userArray) in print("userArray : ", userArray) if userArray.count >= 9 { self.kaoUserArray = userArray self.shuffleArray() self.createCurrentKaoUserArray() } else { self.kaoUserArray = userArray self.shuffleArray() self.createCurrentKaoUserArray() } self.collectionView.reloadData { DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) { self.stopLoading() } } }) .get() } func shuffleArray() { for i in 0 ..< kaoUserArray.count{ let r = Int(arc4random_uniform(UInt32(kaoUserArray.count - i))) + i kaoUserArray.swapAt(i, r) } } func createCurrentKaoUserArray() { self.currentKaoUserArray = Array(self.kaoUserArray.prefix(9)) self.kaoUserArray = Array(self.kaoUserArray.suffix(self.kaoUserArray.count - self.currentKaoUserArray.count)) finishFlag = true print("currentKaoUserArray :", currentKaoUserArray) print("kaoUserArray :", kaoUserArray) } func getHensachi(with num: Int) -> Double { let juni = numArray[num] let tensu = Double(8 - juni) * 12.5 let heikin = Double(45) let hensachi = 50 + (tensu - heikin) / 2 print("num : ", num) print("juni : ", juni) return hensachi } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if segue.identifier == "presentPrintFacePower" { // リセット selectNum = 0 numArray = [0,0,0,0,0,0,0,0,0] let vc = segue.destination as! PrintFacePowerViewController vc.faceImage = firstFace } } @IBAction func tapResetButton(_ sender: Any) { selectNum = 0 firstUser = nil firstFace = nil numArray = [0,0,0,0,0,0,0,0,0] collectionView.reloadData() } @IBAction func tapMypageButton(_ sender: Any) { let sb = UIStoryboard(name: "MyPage", bundle: nil) let vc = sb.instantiateInitialViewController() as! MyPageViewController self.show(vc, sender: nil) } } extension ViewController: UICollectionViewDelegateFlowLayout { func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let space = 1 let wlength = (Int(UIScreen.main.bounds.width) - space) / 3 let hlength = (Int(UIScreen.main.bounds.height) - space) / 3 return CGSize(width: wlength, height: hlength) } } extension ViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 9 } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // let cell = collectionView.dequeueReusableCell(with: humanCell.self, for: indexPath) // if let user = kaoUserArray[safe: indexPath.row] { // cell.configure(with: user, num: self.numArray[indexPath.row]) // } else { // cell.configure(with: humanArray[indexPath.row], num: numArray[indexPath.row]) // } // return cell // kaoUserArrayをローカルで使い回すパターン // currentKaoUserArrayに分けてそれを使う let cell = collectionView.dequeueReusableCell(with: humanCell.self, for: indexPath) if finishFlag { if let user = currentKaoUserArray[safe: indexPath.row] { cell.configure(with: user, num: self.numArray[indexPath.row]) } else { cell.configure(with: humanArray[indexPath.row], num: numArray[indexPath.row]) } } else { cell.emptyConfigure() } return cell } } extension ViewController: UICollectionViewDelegate { func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) print("indexPath.row : ", indexPath.row) let cell = collectionView.cellForItem(at: indexPath) as! humanCell let currentNum = selectNum if numArray[indexPath.row] == 0 { //選択されてない cell.check(with: currentNum + 1) numArray[indexPath.row] = currentNum + 1 selectNum = currentNum + 1 } else { // 選択されてる cell.uncheck() let uncheckNum = numArray[indexPath.row] numArray[indexPath.row] = 0 selectNum = currentNum - 1 // く解除された数字より上の数字を繰り下げる print("before numArray : ", numArray) for (index, num) in numArray.enumerated() { print("index, num : ", index, num) if num > uncheckNum { let newValue = num - 1 numArray[index] = newValue } } print("after numArray : ", numArray) } if selectNum == 1 { if let user = currentKaoUserArray[safe: indexPath.row] { self.firstUser = user } self.firstFace = cell.imageView.image } print("selectNum", selectNum) print("numArray", numArray) collectionView.reloadData() if selectNum == 9 { print("numArray : ", numArray) SVProgressHUD.show(withStatus: "マイリスト更新中") addLoveList(success: { SVProgressHUD.show(withStatus: "facepower更新中") self.createResult() SVProgressHUD.dismiss() let sb = UIStoryboard(name: "PrintFacePower", bundle: nil) let vc = sb.instantiateInitialViewController() as! PrintFacePowerViewController vc.modalTransitionStyle = .crossDissolve // リセット self.selectNum = 0 self.numArray = [0,0,0,0,0,0,0,0,0] vc.faceImage = self.firstFace print("採点!") self.present(vc, animated: true, completion: nil) }) { (error) in SVProgressHUD.showError(withStatus: "データ送信に失敗しました") print(error) } } } } // POST部分 extension ViewController { func addLoveList(success: @escaping() -> Void, failure: @escaping(Error) -> Void) { guard let user = AccountManager.shared.currentUser else { return } if let firstUser = firstUser { user.loveUsers.insert(firstUser) user.update { (error) in if let error = error { failure(error) } else { success() } } } else { success() } } func createResult() { let result = Result() result.voter.set(AccountManager.shared.currentUser!) for (index, user) in currentKaoUserArray.enumerated() { print("index : ", index) print("user : ", user) updateUserHensachi(user: user, index: index) let num = numArray[index] switch num{ case 1: result.first.set(user) case 2: result.second.set(user) case 3: result.third.set(user) case 4: result.fource.set(user) case 5: result.fifth.set(user) case 6: result.sixth.set(user) case 7: result.seventh.set(user) case 8: result.eighth.set(user) case 9: result.ninth.set(user) default: result.ninth.set(user) } } createNotification(result: result) } func updateUserHensachi(user: User, index: Int) { let oldHensachi = user.hensachi let updateHensachi = getHensachi(with: index) let newHensachi = (oldHensachi + updateHensachi) / 2 user.hensachi = newHensachi let oldKaisu = user.kaisu let newKaisu = oldKaisu + 1 user.kaisu = newKaisu user.update { (error) in if let error = error { print("hensachi update error! : ",error) } else { print("oldHensachi : ", oldHensachi) print("updateHensachi : ", updateHensachi) print("newHensachi : ", newHensachi) print("更新後 currentUser.hensachi : ", user.hensachi) } } } func createNotification(result: Result) { for (index, user) in currentKaoUserArray.enumerated() { print("index: ", index) print("result: ", result) let notificationItem = NotificationItem() notificationItem.from.set(AccountManager.shared.currentUser!) notificationItem.to.set(user) notificationItem.num = String(numArray[index]) notificationItem.result.set(result) user.results.insert(result) user.notificationItems.insert(notificationItem) user.badgeNum += 1 user.update { (error) in if let error = error { print(error) } else { print("user update succses") } } } } } <file_sep>/KaoSouou/Extention/UITableView+Extension.swift // // UITableView+Extension.swift // KaoSouou // // Created by <NAME> on 2018/06/20. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import UIKit extension UITableView { func register<T: UITableViewCell>(_ cellType: T.Type) where T: Nibable { register(T.nib, forCellReuseIdentifier: T.identifier) } func register<T: UITableViewCell>(_ cellType: T.Type) { register(T.self, forCellReuseIdentifier: T.identifier) } func dequeueReusableCell<T: UITableViewCell>(with cellType: T.Type, for indexPath: IndexPath) -> T { return dequeueReusableCell(withIdentifier: T.identifier, for: indexPath) as! T } } extension UITableViewCell { static var identifier: String { return className } } <file_sep>/KaoSouou/On/OnboardViewController.swift // // ViewController.swift // OnboradSet // // Created by <NAME> on 2018/02/17. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit import SwiftyOnboard import TTTAttributedLabel import Device class OnboardViewController: UIViewController { var fromAppHelp = false var xDvieceFlag = true @IBOutlet weak var swiftyOnboard: SwiftyOnboard! let titleArray = ["ワクワク", "プルルンッ", "ドクン、ドクン", "ズキュウゥゥン"] let boyTextArray = ["表示される異性を\n好きな顔の順に\nタップしよう", "お、誰かが君を\nタップしたようだね\n今すぐ結果をチェックしよう", "バトル結果がわかるよ\nメンタルブレイクに\n気をつけてね", "バトルを繰り返すことで\n点数がどんどん正確になっていくよ\n君の顔は何点かな?"] let girlTextArray = ["表示される異性を\n好きな顔の順に\nタップしよう", "お、誰かが君を\nタップしたようだね\n今すぐ結果をチェックしよう", "バトル結果がわかるよ\nメンタルブレイクに\n気をつけてね", "バトルを繰り返すことで\n点数がどんどん正確になっていくよ\n君の顔は何点かな?"] override func viewDidLoad() { super.viewDidLoad() swiftyOnboard.style = .light swiftyOnboard.delegate = self swiftyOnboard.dataSource = self swiftyOnboard.backgroundColor = UIColor.black checkDeviceType() } func checkDeviceType() { if Device.version() == .iPhoneX || Device.version() == .iPhoneXR || Device.version() == .iPhoneXS || Device.version() == .iPhoneXS_Max { self.xDvieceFlag = true } else { self.xDvieceFlag = false } } @objc func handleSkip() { swiftyOnboard?.goToPage(index: 4, animated: true) } @objc func handleContinue(sender: UIButton) { let index = sender.tag if index == 4 { if fromAppHelp { self.dismiss(animated: true, completion: nil) } else { // 本番はこっちへ let currentUser = AccountManager.shared.currentUser! if currentUser.allowedFlag == true { AppDelegate.shared.rootViewController.showMainScreen() } else { AppDelegate.shared.rootViewController.showFinalCheckScreen() } // テスト用 // AppDelegate.shared.rootViewController.showLoginScreen() } fromAppHelp = false } else { swiftyOnboard?.goToPage(index: index + 1, animated: true) } } } extension OnboardViewController: SwiftyOnboardDelegate, SwiftyOnboardDataSource { func swiftyOnboardNumberOfPages(_ swiftyOnboard: SwiftyOnboard) -> Int { return 5 } func swiftyOnboardPageForIndex(_ swiftyOnboard: SwiftyOnboard, index: Int) -> SwiftyOnboardPage? { if index == 0 { let view = CustomFirstView.instanceFromNib() as? CustomFirstView return view } else { let view = CustomPage.instanceFromNib() as? CustomPage var selectColor: UIColor! var selectTextArray: [String]! var imageKey: String! if let currentUser = AccountManager.shared.currentUser { if currentUser.gender == 2{ selectColor = UIColor.girlBrandColor() selectTextArray = girlTextArray if xDvieceFlag { imageKey = "tg" } else { imageKey = "tgo" } } else { selectColor = UIColor.boyBrandColor() selectTextArray = boyTextArray if xDvieceFlag { imageKey = "tm" } else { imageKey = "tmo" } } } else { selectColor = UIColor.girlBrandColor() selectTextArray = girlTextArray if xDvieceFlag { imageKey = "tg" } else { imageKey = "tgo" } } view?.titleLabel.adjustsFontSizeToFitWidth = true view?.neonBarView.layer.borderWidth = 1 view?.neonBarView.backgroundColor = selectColor view?.neonBarView.layer.borderColor = selectColor.cgColor view?.neonBarView.viewShadow(radius: 0.5, opacity: 0.5, color: selectColor) view?.image.image = UIImage(named: imageKey + String(index - 1)) view?.titleLabel.text = titleArray[index - 1] view?.subTitleLabel.text = selectTextArray[index - 1] return view } } func swiftyOnboardViewForOverlay(_ swiftyOnboard: SwiftyOnboard) -> SwiftyOnboardOverlay? { let overlay = CustomOverlay.instanceFromNib() as? CustomOverlay overlay?.skip.addTarget(self, action: #selector(handleSkip), for: .touchUpInside) overlay?.buttonContinue.addTarget(self, action: #selector(handleContinue), for: .touchUpInside) return overlay } func swiftyOnboardOverlayForPosition(_ swiftyOnboard: SwiftyOnboard, overlay: SwiftyOnboardOverlay, for position: Double) { let overlay = overlay as! CustomOverlay let currentPage = round(position) overlay.contentControl.currentPage = Int(currentPage) overlay.buttonContinue.tag = Int(position) if currentPage == 0.0 { overlay.buttonContinue.setTitle("使い方へ", for: .normal) overlay.skip.setTitle("Skip", for: .normal) overlay.skip.isHidden = false } else if currentPage == 1.0 || currentPage == 2.0 || currentPage == 3.0{ overlay.buttonContinue.setTitle("次へ", for: .normal) overlay.skip.setTitle("Skip", for: .normal) overlay.skip.isHidden = false } else { overlay.buttonContinue.setTitle("OK!!!", for: .normal) overlay.skip.isHidden = true } } } <file_sep>/KaoSouou/FinalCheckViewController.swift // // FinalCheckViewController.swift // KaoSouou // // Created by <NAME> on 2019/01/22. // Copyright © 2019年 <NAME>. All rights reserved. // import UIKit import M13Checkbox class FinalCheckViewController: UIViewController { @IBOutlet weak var check1Box: M13Checkbox! @IBOutlet weak var check2Box: M13Checkbox! @IBOutlet weak var buttonContinue: UIButton! override func viewDidLoad() { super.viewDidLoad() configure() } func configure() { buttonContinue.layer.borderColor = UIColor.lightGray.cgColor buttonContinue.titleLabel?.textColor = .lightGray buttonContinue.layer.borderWidth = 1 buttonContinue.layer.cornerRadius = buttonContinue.bounds.height / 2 buttonContinue.clipsToBounds = true buttonContinue.isEnabled = false buttonContinue.isHidden = true if AccountManager.shared.currentUser!.gender == 2 { check1Box.tintColor = UIColor.girlBrandColor() } else { check1Box.tintColor = UIColor.boyBrandColor() } } @IBAction func changeValued1Box(_ sender: M13Checkbox) { switch sender.checkState { case .unchecked: break case .checked: break case .mixed: break } checkAllAllowed() } @IBAction func chengeValued2Box(_ sender: M13Checkbox) { switch sender.checkState { case .unchecked: break case .checked: break case .mixed: break } checkAllAllowed() } func checkAllAllowed() { // とりあえずチェック項目1つでを本番とする // if check1Box.checkState == .checked && check2Box.checkState == .checked { if check1Box.checkState == .checked { // ボタンをアクティブに buttonContinue.isEnabled = true buttonContinue.layer.borderColor = UIColor.white.cgColor buttonContinue.titleLabel?.textColor = .white buttonContinue.isHidden = false } else { //ボタンは非アクティブに buttonContinue.isEnabled = false buttonContinue.layer.borderColor = UIColor.lightGray.cgColor buttonContinue.titleLabel?.textColor = .lightGray buttonContinue.isHidden = true } } @IBAction func tapNextButton(_ sender: Any) { next() } func next() { let currentUser = AccountManager.shared.currentUser! currentUser.allowedFlag = true currentUser.update({ (error) in if let error = error { print(error.localizedDescription) } else { print("allowedFlag設定成功") AppDelegate.shared.rootViewController.showMainScreen() } }) } } <file_sep>/KaoSouou/Models/NotificationItem.swift // // NotificationItem.swift // KaoSouou // // Created by <NAME> on 2018/06/20. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import Pring @objcMembers class NotificationItem: Object { dynamic var to: Reference<User> = .init() dynamic var from: Reference<User> = .init() dynamic var result: Reference<Result> = .init() dynamic var num: String = "0" func setNotification(with fromUser: User, toUser: User, numInt: Int) { let notificationItem = NotificationItem() notificationItem.from.set(fromUser) notificationItem.to.set(toUser) notificationItem.num = String(numInt) toUser.update { (error) in if let error = error { print("toUser.notificationItems : ", error.localizedDescription) } else { print("toUser.notificationItems success") } } } } <file_sep>/KaoSouou/Mypage/LovedUserCell.swift // // LovedUserCell.swift // KaoSouou // // Created by <NAME> on 2018/09/21. // Copyright © 2018年 <NAME>. All rights reserved. // import UIKit class LovedUserCell: UICollectionViewCell, Nibable { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var userNameLabel: UILabel! @IBOutlet weak var pointLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } func configure(with user: User?) { guard let user = user else { return } imageView.loadUserImageView(with: user) userNameLabel.text = user.displayName pointLabel.text = String(user.hensachi.shisyagonyu()) } } <file_sep>/KaoSouou/Extention/NSObjectProtocol+Extension.swift // // NSObjectProtocol+Extension.swift // KaoSouou // // Created by <NAME> on 2018/02/19. // Copyright © 2018年 <NAME>. All rights reserved. // import Foundation import UIKit extension NSObjectProtocol { static var className: String { return String(describing: self) } } protocol Storyboardable: NSObjectProtocol { static var storyboardName: String { get } static func instantiate() -> Self } extension Storyboardable where Self: UIViewController { static var storyboardName: String { return className } static func instantiate() -> Self { return UIStoryboard(name: storyboardName, bundle: Bundle(for: self)).instantiateInitialViewController() as! Self } } protocol Nibable: NSObjectProtocol { static var nibName: String { get } static var nib: UINib { get } } extension Nibable { static var nibName: String { return className } static var nib: UINib { return UINib(nibName: nibName, bundle: Bundle(for: self)) } }
efa08a054809f34988cc0d0415244a65d53a1e24
[ "Swift", "Ruby" ]
33
Swift
gucchi43/kaosouou
e9d9af12aca80ad5e8dfc5d0148998dbfcf9f694
a74d572dea447b6c939d3d6feb29d90b4c0168bf
refs/heads/master
<repo_name>lutzkuen/cfdCarryInterest<file_sep>/app/src/main/java/com/example/interestcalculator/MainActivity.kt package com.example.interestcalculator import android.os.Bundle import com.google.android.material.tabs.TabLayout import androidx.viewpager.widget.ViewPager import androidx.appcompat.app.AppCompatActivity import androidx.preference.PreferenceManager import com.example.interestcalculator.content.RatesContent import com.example.interestcalculator.ui.main.SectionsPagerAdapter import kotlinx.android.synthetic.main.activity_main.* class MainActivity : ratesFragment.OnListFragmentInteractionListener, PortfolioFragment.OnListFragmentInteractionListener, AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) val sectionsPagerAdapter = SectionsPagerAdapter(this, supportFragmentManager) val viewPager: ViewPager = findViewById(R.id.view_pager) viewPager.adapter = sectionsPagerAdapter val tabs: TabLayout = findViewById(R.id.tabs) tabs.addTab(tabs.newTab().setText(R.string.rates_fragment)) tabs.addTab(tabs.newTab().setText(R.string.portfolio_fragment)) tabs.addTab(tabs.newTab().setText(R.string.title_activity_settings)) tabs.setupWithViewPager(viewPager) fab.setOnClickListener { view -> run { val preferences = PreferenceManager.getDefaultSharedPreferences(view.context) RatesContent.refresh(preferences) } } } override fun onListFragmentInteraction(item: RatesListItem?) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } override fun onListFragmentInteraction(item: PortfolioListItem?) { // TODO("not implemented") //To change body of created functions use File | Settings | File Templates. } }<file_sep>/app/src/main/java/com/example/interestcalculator/RatesRecyclerViewAdapter.kt package com.example.interestcalculator import android.content.SharedPreferences import android.graphics.Color import android.graphics.drawable.Drawable import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.preference.PreferenceManager import com.example.interestcalculator.content.RatesContent import com.example.interestcalculator.ratesFragment.OnListFragmentInteractionListener import kotlinx.android.synthetic.main.fragment_rates.view.* import java.lang.String.format class RatesRecyclerViewAdapter( private var mValues: MutableList<RatesListItem>, private val mListener: OnListFragmentInteractionListener?, val preferences: SharedPreferences? ) : RecyclerView.Adapter<RatesRecyclerViewAdapter.ViewHolder>() { private val mOnClickListener: View.OnClickListener init { mOnClickListener = View.OnClickListener { v -> val item = v.tag as RatesListItem // Notify the active callbacks interface (the activity, if the fragment is attached to // one) that an item has been selected. mListener?.onListFragmentInteraction(item) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.fragment_rates, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { if ( position >= mValues.size ) { return } val item = mValues[position] val digits = 2 holder.mIdView.text = item.instrument.padEnd(10) holder.mContentView.text = """ Side: ${item.side} Units: ${format("%.${digits}f", item.units)} Interest: ${format("%.${digits}f", item.interest)} Price: ${format("%.5f", item.price)} """.trimIndent() //item.units.toString() + " " + item.interest.toString() with(holder.mView) { tag = item setOnClickListener(mOnClickListener) } /* if ( instrumentFilter != null ) { if ( item.instrument.contains(instrumentFilter) ) { holder.mView.visibility = View.VISIBLE } else { holder.mIdView.text = "" holder.mContentView.text = "" } } */ } override fun getItemCount(): Int = mValues.size inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) { val mIdView: TextView = mView.item_number val mContentView: TextView = mView.content override fun toString(): String { return super.toString() + " '" + mContentView.text + "'" } } } <file_sep>/app/src/main/java/com/example/interestcalculator/ratesFragment.kt package com.example.interestcalculator import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import androidx.preference.PreferenceManager import com.example.interestcalculator.content.RatesContent /** * A fragment representing a list of Items. * Activities containing this fragment MUST implement the * [ratesFragment.OnListFragmentInteractionListener] interface. */ class RatesListItem { var instrument: String = "N/A" var units: Float? = 0.toFloat() var interest: Float? = 0.toFloat() var side: String? = "N/A" var price: Float? = 0.toFloat() } class ratesFragment : LifecycleOwner, Fragment() { private var columnCount = 1 // var swipeRefreshLayout: SwipeRefreshLayout? = null private var listener: OnListFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { columnCount = it.getInt(ARG_COLUMN_COUNT) } // swipeRefreshLayout = findViewById(R.id.simpleSwipeRefreshLayout); } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_rates_list, container, false) // Set the adapter val fragment = this if (view is RecyclerView) { with(view) { layoutManager = when { columnCount <= 1 -> LinearLayoutManager(context) else -> GridLayoutManager(context, columnCount) } val preferences = PreferenceManager.getDefaultSharedPreferences(context) view.adapter = RatesRecyclerViewAdapter(RatesContent.ITEMS, listener, preferences) val readyObserver = Observer<String> {_ -> view.post({ view.adapter!!.notifyDataSetChanged() }) } RatesContent.ratesready.observe(fragment, readyObserver) // if ( RatesContent.ratesready.value != "running" ) { // RatesContent.refresh(preferences) // } } } return view } override fun onResume() { super.onResume() /* val preferences = PreferenceManager.getDefaultSharedPreferences(context) if ( RatesContent.ratesready.value != "running" ) { RatesContent.refresh(preferences) } */ } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnListFragmentInteractionListener) { listener = context } else { throw RuntimeException("$context must implement OnListFragmentInteractionListener") } } override fun onDetach() { super.onDetach() listener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson * [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) * for more information. */ interface OnListFragmentInteractionListener { fun onListFragmentInteraction(item: RatesListItem?) } companion object { const val ARG_COLUMN_COUNT = "column-count" @JvmStatic fun newInstance(columnCount: Int) = ratesFragment().apply { arguments = Bundle().apply { putInt(ARG_COLUMN_COUNT, columnCount) } } } } <file_sep>/app/src/main/java/com/example/interestcalculator/PortfolioFragment.kt package com.example.interestcalculator import android.content.Context import android.os.Bundle import androidx.fragment.app.Fragment import androidx.recyclerview.widget.GridLayoutManager import androidx.recyclerview.widget.LinearLayoutManager import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import androidx.lifecycle.LifecycleOwner import androidx.lifecycle.Observer import androidx.preference.PreferenceManager import com.example.interestcalculator.content.RatesContent /** * A fragment representing a list of Items. * Activities containing this fragment MUST implement the * [PortfolioFragment.OnListFragmentInteractionListener] interface. */ class PortfolioListItem { var instrument: String = "N/A" var units: Int? = 0 var interest: Float? = 0.toFloat() var side: String? = "N/A" var recommend: String? = "Hold" } class PortfolioFragment : LifecycleOwner, Fragment() { private var columnCount = 1 private var listener: OnListFragmentInteractionListener? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) arguments?.let { columnCount = it.getInt(ARG_COLUMN_COUNT) } } override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { val view = inflater.inflate(R.layout.fragment_portfolio_list, container, false) var fragment = this if (view is RecyclerView) { with(view) { layoutManager = when { columnCount <= 1 -> LinearLayoutManager(context) else -> GridLayoutManager(context, columnCount) } view.adapter = PortfolioRecyclerViewAdapter(RatesContent.PORTFOLIO_ITEMS, listener) val readyObserver = Observer<String> { _ -> view.post({ view.adapter!!.notifyDataSetChanged() }) } RatesContent.portfolioready.observe(fragment, readyObserver) val preferences = PreferenceManager.getDefaultSharedPreferences(fragment.context) if ( RatesContent.ratesready.value != "running" ) { RatesContent.refresh(preferences) } } } return view } override fun onResume() { super.onResume() /* val preferences = PreferenceManager.getDefaultSharedPreferences(context) if ( RatesContent.ratesready.value != "running" ) { RatesContent.refresh(preferences) } */ } override fun onAttach(context: Context) { super.onAttach(context) if (context is OnListFragmentInteractionListener) { listener = context } else { throw RuntimeException(context.toString() + " must implement OnListFragmentInteractionListener") } } override fun onDetach() { super.onDetach() listener = null } /** * This interface must be implemented by activities that contain this * fragment to allow an interaction in this fragment to be communicated * to the activity and potentially other fragments contained in that * activity. * * * See the Android Training lesson * [Communicating with Other Fragments](http://developer.android.com/training/basics/fragments/communicating.html) * for more information. */ interface OnListFragmentInteractionListener { fun onListFragmentInteraction(item: PortfolioListItem?) } companion object { const val ARG_COLUMN_COUNT = "column-count" @JvmStatic fun newInstance(columnCount: Int) = PortfolioFragment().apply { arguments = Bundle().apply { putInt(ARG_COLUMN_COUNT, columnCount) } } } } <file_sep>/app/src/main/java/com/example/interestcalculator/content/RatesContent.kt package com.example.interestcalculator.content import android.content.SharedPreferences import com.example.interestcalculator.RatesListItem import java.util.ArrayList import java.util.HashMap import androidx.lifecycle.MutableLiveData import com.beust.klaxon.Klaxon import com.beust.klaxon.KlaxonException import com.example.interestcalculator.PortfolioListItem import okhttp3.* import java.io.IOException import java.lang.Math.abs import java.time.LocalDateTime import java.time.LocalDateTime.now import java.util.concurrent.locks.ReentrantLock /** * Helper class for providing sample content for user interfaces created by * Android template wizards. */ class InstrumentTag( var type: String?, var name: String? ) class Instrument( var displayName: String?, var displayPrecision: Int?, var marginRate: String?, var maximumOrderUnits: String?, var maximumPositionSize: String?, var maximumTrailingStopDistance: String?, var minimumTradeSize: String?, var minimumTrailingStopDistance: String?, var name: String?, var pipLocation: Int?, var tradeUnitsPrecision: Int?, var type: String? // var tags: List<InstrumentTag>? ) class InstrumentsResponse( var lastTransactionID: String?, var instruments: List<Instrument>? ) class PriceResponse( var prices: List<ClientPrice>? ) class ClientPrice( var instrument: String, var closeoutAsk: String, var closeoutBid: String ) class PositionSide( var pl: String, var resettablePL: String, var units: String, var unrealizedPL: String ) class Position( var instrument: String, var long: PositionSide, var pl: String, var resettablePL: String, var short: PositionSide, var unrealizedPL: String ) class PositionResponse( var lastTransactionID: String, var positions: List<Position> ) object RatesContent { private val arrPairs = ArrayList<String>() private val arrRates = ArrayList<Float>() private val arrInterestCode = ArrayList<String>() private val arrInterestBorrow = ArrayList<Float>() private val client = OkHttpClient() private var allowedInstruments: InstrumentsResponse? = null private var positions: PositionResponse? = null private val arrInterestLend = ArrayList<Float>() val ITEMS: MutableList<RatesListItem> = ArrayList<RatesListItem>() val PORTFOLIO_ITEMS: MutableList<PortfolioListItem> = ArrayList() val PORTFOLIO_ITEM_MAP: MutableMap<String, PortfolioListItem> = HashMap() val ITEM_MAP: MutableMap<String, RatesListItem> = HashMap() var ratesready: MutableLiveData<String> = MutableLiveData<String>() var portfolioready: MutableLiveData<String> = MutableLiveData<String>() private const val durationNormalization = 24.0 * 365.25 private val lock = ReentrantLock() private val items_lock = ReentrantLock() private val portfolio_lock = ReentrantLock() init { ratesready.value = "none" portfolioready.value = "none" } fun refresh(preferences: SharedPreferences) { lock.lock() ratesready.value = "running" portfolioready.value = "running" initArrays() filter(preferences) lock.unlock() } private fun privatePortfolio(preferences: SharedPreferences) { val accessToken: String? = preferences.getString("access_token", "") val accountId: String? = preferences.getString("account_id", "") val host: String? = preferences.getString("host", "") val duration: String? = preferences.getString("duration", "24") // val port: String? = preferences!!.getString("port", "443") val urlString = "https://$host/v3/accounts/$accountId/openPositions" val request = Request.Builder() .url(urlString) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer ${accessToken}") .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) {} override fun onResponse(call: Call, response: Response) { val responseString = response.body()!!.string() try { positions = Klaxon().parse<PositionResponse>(responseString) } catch (e: KlaxonException) { println(responseString) println(e) portfolioready.postValue("ready") return } val orderedList = ArrayList<PortfolioListItem>() var totalInterest: Float = 0.toFloat() var totalUnits = 0 for (posi in positions!!.positions) { val newItem = PortfolioListItem() newItem.instrument = posi.instrument.replace("_", "/") newItem.units = posi.long.units.toInt() + posi.short.units.toInt() totalUnits += newItem.units!! if (newItem.units!! > 0) { newItem.side = "long" } else { newItem.side = "short" } newItem.interest = getInterest(posi.instrument.replace("_", "/"), newItem.units!!, duration!!.toFloat()) totalInterest += newItem.interest!! orderedList.add(newItem) } orderedList.sortByDescending { it.interest } for (i in 0 until orderedList.size) { try { val position = orderedList[i] for (i_before in 0..i) { val posBefore = orderedList[i_before] if (ITEM_MAP[posBefore.instrument]!!.interest!! < RatesContent.ITEM_MAP[position.instrument]!!.interest!!) { position.recommend = "Increase Position" } } for (i_after in i until orderedList.size) { val posAfter = orderedList[i_after] if (ITEM_MAP[posAfter.instrument]!!.interest!! > RatesContent.ITEM_MAP[position.instrument]!!.interest!!) { position.recommend = "Decrease Position" } } if (position.interest!! < 0) { position.recommend = "Close Position" } addPortfolioItem(position) } catch (e: KotlinNullPointerException) { print(e) } } val summary = PortfolioListItem() summary.instrument = "Total Interest" summary.interest = totalInterest summary.side = "" summary.units = totalUnits addPortfolioItem(summary) portfolioready.postValue("ready") } }) } private fun initArrays() { arrPairs.clear() arrRates.clear() arrInterestCode.clear() arrInterestBorrow.clear() arrInterestLend.clear() } private fun parseLine(_line: String): List<String> { var line = _line.replace(");", "") line = line.replace("\"", "") val lineSplit = line.split("(") val instrumentArray = lineSplit[1].split(",") return instrumentArray } private fun getArrays(preferences: SharedPreferences) { val duration = preferences.getString("duration", "24") val urlString = "https://www1.oanda.com/tools/fxcalculators/fxmath.js" val request = Request.Builder() .url(urlString) .build() val callback = object : Callback { override fun onResponse(call: Call?, response: Response) { val responseData = response.body()?.string() parseFxmath(responseData!!) // filter(preferences) getRates(duration!!.toFloat()) } override fun onFailure(call: Call?, e: IOException?) { println("Request Failure.") } } val client = OkHttpClient() val call = client.newCall(request) call.enqueue(callback) } fun parseFxmath(fxmath_text: String) { val parts = fxmath_text.split('\n') for (part in parts) { /*if (part.indexOf("arrPairs") > 0) { val insArr = parseLine(part) for (ins in insArr) { arrPairs.add(ins) } } if (part.indexOf("arrRates") > 0) { val insArr = parseLine(part) for (ins in insArr) { println(part) arrRates.add(ins.toFloat()) } }*/ if (part.indexOf("arrInterestCode") > 0) { val insArr = parseLine(part) for (ins in insArr) { arrInterestCode.add(ins) } } if (part.indexOf("arrInterestBorrow") > 0) { val insArr = parseLine(part) for (ins in insArr) { arrInterestBorrow.add(ins.toFloat()) } } if (part.indexOf("arrInterestLend") > 0) { val insArr = parseLine(part) for (ins in insArr) { arrInterestLend.add(ins.toFloat()) } } } } private fun getPrice(ins: String): Float { val idx: Int = arrPairs.indexOf(ins) return arrRates[idx] } private fun getConversion(leading_currency: String): Float { val accountCurrency = "EUR" if (leading_currency == accountCurrency) { return 1.0.toFloat() } for (i_ins in 0 until arrPairs.size) { val ins = arrPairs[i_ins] if (arrPairs[i_ins] == null) { continue } if ((ins.indexOf(leading_currency) >= 0) and (ins.indexOf(accountCurrency) >= 0)) { // try { val price = getPrice(ins) if (ins.split("/")[0] == accountCurrency) { return price } else { return 1.0.toFloat() / price } /* } catch (e: IllegalStateException) { println("Failed to get Price for ${ins}") } */ } } val euroUSDollar = getPrice("EUR/USD") for (ins in arrPairs) { if ((ins.indexOf(leading_currency) >= 0) and (ins.indexOf("USD") >= 0)) { val price = getPrice(ins) if (ins.split("_")[0] == "USD") { return price / euroUSDollar } else { return 1.0.toFloat() / (price * euroUSDollar) } } } return (-1.0).toFloat() } fun getInterest(instrument: String, units: Int, duration: Float): Float { // lock.lock() // try { val interest = getInterestInternal(instrument, units, duration) // } finally { // lock.unlock() return interest // } } private fun getInterestInternal(instrument: String, units: Int, duration: Float): Float { val components = instrument.split("/") val base = components[0] val quote = components[1] val idx = arrPairs.indexOf(instrument) if ( idx >= arrRates.size || idx < 0 ) { return 0.toFloat() } val price = arrRates[idx] val idxBase = arrInterestCode.indexOf(base) val idxQuote = arrInterestCode.indexOf(quote) var conversionBase: Float = getConversion(base) if (conversionBase <= 0) { conversionBase = getConversion(quote) conversionBase = price / conversionBase } var conversionQuote: Float = getConversion(quote) if (conversionQuote <= 0) { conversionQuote = getConversion(base) conversionQuote = price / conversionQuote } val interestTotal: Float if (units > 0) { val baseInt = abs(units) * (arrInterestBorrow[idxBase] / 100.0) * duration / (conversionBase * durationNormalization) val quoteInt = abs(units) * price * (arrInterestLend[idxQuote] / 100.0) * duration / (conversionQuote * durationNormalization) interestTotal = baseInt.toFloat() - quoteInt.toFloat() } else { val baseInt = abs(units) * (arrInterestLend[idxBase] / 100.0) * duration / (conversionBase * durationNormalization) val quoteInt = abs(units) * price * (arrInterestBorrow[idxQuote] / 100.0) * duration / (conversionQuote * durationNormalization) interestTotal = quoteInt.toFloat() - baseInt.toFloat() /* if ( instrument == "WTICO/USD" ) { println("$units ${arrInterestLend[idxBase]} $duration $conversionBase $conversionQuote $baseInt $quoteInt $interestTotal") } */ } return interestTotal } private fun getRates(inputDuration: Float) { // now all the array should be in place to calculate the rates val units: Float = 1000.toFloat() val prelimList = ArrayList<RatesListItem>() val duration = inputDuration / 8766.toFloat() for (i_ins in 0 until arrPairs.size) { if (arrPairs[i_ins] == null) { continue } val ins = arrPairs[i_ins] val components = ins.split("/") if (components.size < 2) { println("Received weird instrument $ins") continue } val base = components[0] val quote = components[1] val idx = arrPairs.indexOf(ins) if (idx < 0) { continue } if (idx > arrRates.size - 1) { continue } if (idx == null) { continue } if (arrRates[idx] == null) { continue } val price = arrRates[idx] // println("$ins $price") val idxBase = arrInterestCode.indexOf(base) val idxQuote = arrInterestCode.indexOf(quote) var conversionBase: Float = getConversion(base) if (conversionBase <= 0) { continue // conversionBase = getConversion(quote) // conversionBase = price / conversionBase } var conversionQuote: Float = getConversion(quote) if (conversionQuote <= 0) { conversionQuote = conversionBase conversionQuote = price / conversionQuote } // long side var baseInt = units * (arrInterestBorrow[idxBase] / 100.0) * duration var quoteInt = (units * conversionBase) * price * (arrInterestLend[idxQuote] / 100.0) * duration / conversionQuote var interestTotal = baseInt - quoteInt if (interestTotal > 0) { val longItem = RatesListItem() longItem.instrument = ins longItem.interest = interestTotal.toFloat() longItem.side = "long" longItem.units = units * conversionBase longItem.price = price // addItem(long_item) prelimList.add(longItem) } // short side baseInt = units * (arrInterestLend[idxBase] / 100.0) * duration quoteInt = (units * conversionBase) * price * (arrInterestBorrow[idxQuote] / 100.0) * duration / conversionQuote interestTotal = quoteInt - baseInt if (interestTotal > 0) { val short_item = RatesListItem() short_item.instrument = ins short_item.interest = interestTotal.toFloat() short_item.side = "short" short_item.units = units * conversionBase short_item.price = price // addItem(short_item) prelimList.add(short_item) } } prelimList.sortByDescending({ it.interest }) ITEMS.clear() for (it in prelimList) { addItem(it) } ratesready.postValue("ready") } fun filter(preferences: SharedPreferences) { val client = OkHttpClient() val accessToken: String? = preferences.getString("access_token", "") val accountId: String? = preferences.getString("account_id", "") val host: String? = preferences.getString("host", "") val urlString = "https://$host/v3/accounts/$accountId/instruments" val request = Request.Builder() .url(urlString) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer ${accessToken}") .build() client.newCall(request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) {} override fun onResponse(call: Call, response: Response) { val responseString = response.body()!!.string() try { allowedInstruments = Klaxon().parse<InstrumentsResponse>(responseString) } catch (e: KlaxonException) { for (line in responseString.split("]")) { println(line) } println(e) ratesready.postValue("ready") // privatePortfolio(preferences) return } val instrumentFilter = preferences.getString("allowed_ins", "") val side = preferences.getString("side", "") var is_allowed = true var instrumentAgg = "" for (ins in allowedInstruments!!.instruments!!) { if ( instrumentAgg == "" ) { instrumentAgg += ins.name!! } else { instrumentAgg += "%2C${ins.name}" } } val priceUrlString = "https://$host/v3/accounts/$accountId/pricing?instruments=$instrumentAgg" val price_request = Request.Builder() .url(priceUrlString) .addHeader("Content-Type", "application/json") .addHeader("Authorization", "Bearer ${accessToken}") .build() // println(priceUrlString) client.newCall(price_request).enqueue(object : Callback { override fun onFailure(call: Call, e: IOException) {} override fun onResponse(call: Call, response: Response) { val priceResponseString = response.body()!!.string() var pricesResponse: PriceResponse? try { pricesResponse = Klaxon().parse<PriceResponse>(priceResponseString) } catch (e: KlaxonException) { for (line in priceResponseString.split("]")) { println(line) } println(e) ratesready.postValue("ready") privatePortfolio(preferences) return } for ( price in pricesResponse!!.prices!! ) { arrPairs.add(price.instrument!!.replace("_", "/")) arrRates.add( ( price!!.closeoutAsk.toFloat() + price!!.closeoutBid.toFloat() ) / 2.toFloat() ) } getArrays(preferences) privatePortfolio(preferences) } }) } }) } private fun addItem(item: RatesListItem) { if (item.instrument == null) { return } if (item.interest == null) { return } if (item.price == null) { return } if (item.side == null) { return } if (item.units == null) { return } items_lock.lock() // try { if (ITEMS.contains(item).not()) { // try { ITEMS.remove(ITEMS.find { it.instrument == item.instrument }) ITEMS.add(item) // ITEM_MAP.remove(item.instrument) ITEM_MAP[item.instrument] = item /* } catch (e: IndexOutOfBoundsException) { println("Error while adding new rates item ${item.instrument}") println(e) } */ } // } finally { items_lock.unlock() // } } private fun addPortfolioItem(item: PortfolioListItem) { portfolio_lock.lock() if (PORTFOLIO_ITEMS.contains(item).not()) { PORTFOLIO_ITEMS.remove(PORTFOLIO_ITEMS.find( { it.instrument == item.instrument })) PORTFOLIO_ITEMS.add(item) PORTFOLIO_ITEM_MAP[item.instrument] = item } portfolio_lock.unlock() } } <file_sep>/README.md # cfdCarryInterest Small kotlin app to access the cfd interest rates published from OANDA. Will provide an estimate for your daily interest if you enter your v20 account id and access token. <file_sep>/app/src/main/java/com/example/interestcalculator/PortfolioRecyclerViewAdapter.kt package com.example.interestcalculator import android.graphics.Color import android.view.Gravity import androidx.recyclerview.widget.RecyclerView import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.TextView import com.example.interestcalculator.PortfolioFragment.OnListFragmentInteractionListener import kotlinx.android.synthetic.main.fragment_portfolio.view.* import java.lang.Math.abs import java.lang.String.format class PortfolioRecyclerViewAdapter( private val mValues: MutableList<PortfolioListItem>, private val mListener: OnListFragmentInteractionListener? ) : RecyclerView.Adapter<PortfolioRecyclerViewAdapter.ViewHolder>() { private val mOnClickListener: View.OnClickListener init { mOnClickListener = View.OnClickListener { v -> val item = v.tag as PortfolioListItem // Notify the active callbacks interface (the activity, if the fragment is attached to // one) that an item has been selected. mListener?.onListFragmentInteraction(item) } } override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val view = LayoutInflater.from(parent.context) .inflate(R.layout.fragment_portfolio, parent, false) return ViewHolder(view) } override fun onBindViewHolder(holder: ViewHolder, position: Int) { val item = mValues[position] inflate_view(holder, item) with(holder.mView) { tag = item setOnClickListener(mOnClickListener) } } private fun inflate_view(holder: ViewHolder, item: PortfolioListItem) { if (item.instrument == "Total Interest" ) { holder.mIdView.text = item.instrument.padEnd(10) holder.mContentView.text = item.interest.toString() } else { holder.mIdView.text = item.instrument.padEnd(10) holder.mContentView.text = """ Side: ${item.side} Units: ${abs(item.units!!)} Interest: ${item.interest} ${item.recommend} """.trimIndent() } } override fun getItemCount(): Int = mValues.size inner class ViewHolder(val mView: View) : RecyclerView.ViewHolder(mView) { val mIdView: TextView = mView.item_number val mContentView: TextView = mView.content override fun toString(): String { return super.toString() + " '" + mContentView.text + "'" } } }
7a9d78fb43a97f0bcef212abf59b0e5391142154
[ "Markdown", "Kotlin" ]
7
Kotlin
lutzkuen/cfdCarryInterest
c4310b583cc9ab9a914045769e5a1588b45bba57
3a12e393bc49b36c3034e3fdfcf2ca0cafdccffc
refs/heads/main
<repo_name>SnowyCocoon/AI_ML_Math_Projects<file_sep>/2. Monte Carlo Sock Prediction/Stock.py #Based on https://www.youtube.com/watch?v=_T0l015ecK4 import pandas_datareader.data as web import pandas as pd import datetime as dt import numpy as np import matplotlib.pyplot as plt from matplotlib import style style.use('ggplot') start = dt.datetime(2020,1,1) end = dt.datetime(2021,1,1) prices = web.DataReader('^NKX', 'stooq', start, end)['Close'] returns = prices.pct_change() last_price = prices[-1] #Numbers of simulations num_simulations = 100 num_days = 500 simulations_df = pd.DataFrame() for x in range(num_simulations): count = 0 daily_vol = returns.std() price_series = [] price = last_price * (1 + np.random.normal(0, daily_vol)) price_series.append(price) for y in range(num_days): if count == 499: break price = price_series[count] * (1 + np.random.normal(0, daily_vol)) price_series.append(price) count += 1 simulations_df[x] = price_series fig = plt.figure() fig.suptitle('Monte Carlo simulation: ^NKX (Nikkei 225)') plt.plot(simulations_df) plt.axhline(y = last_price, color = 'r', linestyle = '-') plt.xlabel('Day starting from 01.01.2021') plt.ylabel('Price in $') plt.show()<file_sep>/5. Pygames Neural Network/Code/pipe.py import pygame import random from defs import * class Pipe(): def __init__(self, gameDisplay, x, y, pipe_type) -> None: self.gameDisplay = gameDisplay self.state = PIPE_MOVING self.pipe_type = pipe_type self.img = pygame.image.load(PIPE_FILENAME) self.rect = self.img.get_rect() self.set_position(x,y) def set_position(self,x,y): self.rect.left = x self.rect.top = y def move_position(self, dx, dy): self.rect.centerx += dx self.rect.centery += dy def draw(self): self.gameDisplay.blit(self.img, self.rect) def check_status(self): if self.rect.right < 0: self.state = PIPE_DONE print('Pipe_Done') def update(self, dt): if self.state == PIPE_MOVING: self.move_position(-(PIPE_SPEED * dt), 0) self.check_status() <file_sep>/5. Pygames Neural Network/Code/main.py #Inspired by https://www.youtube.com/playlist?list=PLZ1QII7yudbebDQ1Kiqdh1LNz6PavcptO import pygame from game import Game pygame.init() game = Game() game.run_game_loop() pygame.quit() quit() <file_sep>/5. Pygames Neural Network/Code/game.py import pygame from pipe import Pipe from defs import * class Game: def __init__(self) -> None: self.clock = pygame.time.Clock() self.gameDisplay = pygame.display.set_mode((DISPLAY_W,DISPLAY_H)) pygame.display.set_caption('Learn to fly') self.bgImg = pygame.image.load(BG_FILENAME) #Loading the background self.label_font = pygame.font.SysFont("monospace", DATA_FONT_SIZE) self.dt = 0 self.game_time = 0 self.pi = Pipe(self.gameDisplay, DISPLAY_W, 300, PIPE_LOWER) def update_label(self, data, title, font, x, y, gameDisplay): label = font.render('{} {}'.format(title, data), 1, DATA_FONT_COLOR) gameDisplay.blit(label, (x, y)) return y def update_data_labels(self, gameDisplay, dt, game_time, font): y_pos = 10 gap = 20 x_pos = 10 y_pos = self.update_label(round(1000/dt,2), 'FPS', font, x_pos, y_pos + gap, gameDisplay) y_pos = self.update_label(round(game_time/1000,2),'Game time', font, x_pos, y_pos + gap, gameDisplay) def draw_objects(self): self.gameDisplay.blit(self.bgImg, (0, 0)) self.update_data_labels(self.gameDisplay, self.dt, self.game_time, self.label_font) self.pi.draw() pygame.display.update() # Update/Render window def run_game_loop(self): while True: self.dt = self.clock.tick(FPS) self.game_time += self.dt #Handle Events events = pygame.event.get() for event in events: if event.type == pygame.QUIT: return elif event.type == pygame.KEYDOWN: return #Update Display self.draw_objects() self.pi.update(self.dt)<file_sep>/README.md ML Projects (+ Math) <file_sep>/5. Pygames Neural Network/Code/defs.py DISPLAY_W = 960 DISPLAY_H = 540 FPS = 30 DATA_FONT_SIZE = 18 DATA_FONT_COLOR = (40,40,40) BG_FILENAME = 'Assets/BG.png' PIPE_FILENAME = 'Assets/Pipe.png' PIPE_SPEED = 70/1000 PIPE_DONE = 1 PIPE_MOVING = 0 PIPE_UPPER = 1 PIPE_LOWER = 0
7d5eb321fba2eb5c399da032f1a26750ee989c0b
[ "Markdown", "Python" ]
6
Python
SnowyCocoon/AI_ML_Math_Projects
632c0272fd3a4ecda4e70dee4993587c3d0ce139
6c6c948f332aff58f1c5351dd300982b4e8fad98
refs/heads/master
<file_sep>#!/bin/bash INSTALLDIR="$HOME/.bin" BINARYPATH="$INSTALLDIR/caddy" VERSION=$1 if [ -z $VERSION ]; then >&2 echo "usage: $0 VERSION" exit 1 fi URL="https://github.com/caddyserver/caddy/releases/download" URL+="/v${VERSION}/caddy_${VERSION}_linux_amd64.tar.gz" curl --location --silent $URL -o caddy.tgz if [ -f $BINARYPATH ]; then rm $BINARYPATH fi tar -C $INSTALLDIR -xf caddy.tgz caddy rm caddy.tgz $BINARYPATH version <file_sep>#!/bin/bash set -e echo "generate SSH key..." ssh-keygen -t ed25519 echo "add SSH key to Github..." echo .ssh/id_ed25519.pub read -p "press [enter] to continue" echo "setup dotfiles..." git init git remote add origin <EMAIL>:aitva/dotfiles.git git fetch git checkout -f master echo "install missing packages..." sudo apt install tmux gcc xz-utils echo "install Go compiler..." echo -n "Go version: " read version sudo ./scripts/update-go-arm.sh $version echo "install Node..." echo -n "Node version: " read version sudo ./scripts/update-node-arm.sh $version <file_sep>#!/bin/bash go install golang.org/x/tools/gopls@latest go install golang.org/x/tools/cmd/goimports@latest go install github.com/sqlc-dev/sqlc/cmd/sqlc@latest go install github.com/valyala/quicktemplate/qtc@latest go install github.com/swaggo/swag/cmd/swag@v1.7.1 curl -sSfL https://raw.githubusercontent.com/golangci/golangci-lint/master/install.sh \ | sh -s -- -b $(go env GOPATH)/bin v1.54.2 golangci-lint version <file_sep>#!/bin/bash INSTALLDIR="$HOME/.bin" BINARYPATH="$INSTALLDIR/qrcp" VERSION=$1 if [ -z $VERSION ]; then >&2 echo "usage: $0 VERSION" exit 1 fi URL="https://github.com/claudiodangelis/qrcp/releases/download" URL+="/${VERSION}/qrcp_${VERSION}_linux_arm64.tar.gz" curl --location --silent $URL -o qrcp.tgz if [ -f $BINARYPATH ]; then rm $BINARYPATH fi tar -C $INSTALLDIR -xf qrcp.tgz qrcp rm qrcp.tgz $BINARYPATH version <file_sep>#!/bin/sh set -e npm i -g eslint eslint-plugin-vue vls <file_sep>#!/bin/bash INSTALLDIR="/usr/local" GOROOT="$INSTALLDIR/go" VERSION=$1 if [ -z $VERSION ]; then >&2 echo "usage: $0 VERSION" exit 1 fi if [ "$EUID" -ne 0 ]; then echo "this script should be run as root" exit 1 fi curl --location --silent "https://dl.google.com/go/go$VERSION.linux-amd64.tar.gz" -o go.tgz if [ -d $GOROOT ]; then rm -rf $GOROOT fi tar -C $INSTALLDIR -xf go.tgz rm go.tgz $GOROOT/bin/go version <file_sep>#!/bin/bash set -e INSTALLDIR="/usr/local" NODEROOT="$INSTALLDIR/node" VERSION=$1 if [ -z $VERSION ]; then >&2 echo "usage: $0 VERSION" exit 1 fi if [ "$EUID" -ne 0 ]; then echo "this script should be run as root" exit 1 fi curl --location --silent \ "https://nodejs.org/dist/v${VERSION}/node-v${VERSION}-linux-arm64.tar.xz" \ -o node.tgz if [ -d $NODEROOT ]; then rm -rf $NODEROOT fi # If it fails xz-utils might not be install on your system. tar -C $INSTALLDIR -xf node.tgz mv $INSTALLDIR/node* $NODEROOT rm node.tgz echo "node version" `$NODEROOT/bin/node --version` <file_sep># dotfiles This repo contains my dotfiles. I use it to share configs between my computers. I have created the repo using the advice at: https://news.ycombinator.com/item?id=11071754 But later updated to a simpler workflow presented by <NAME> on his blog: https://drewdevault.com/2019/12/30/dotfiles.html ## Initialization Create a new repository: ```bash git init git remote add origin <EMAIL>:aitva/dotfiles.git git fetch git checkout -f master ``` Add this incredible `.gitignore` file: ``` * ``` To add any new file you need to use `git add -f FILE` forcing git to override the `.gitignore`. ## Replicate onto a new machine ```bash git init git remote add origin <EMAIL>:aitva/dotfiles.git git fetch git checkout -f master ``` ## Other To import file from `.bashrc.d` edit `.bashrc` and add: ```bash . ~/.bashrc.d/default . ~/.bashrc.d/go ``` To import all files under `.bashrc.d` edit `.bashrc` and add: ```bash if [ -d "$HOME/.bashrc.d" ]; then for f in $HOME/.bashrc.d/*; do . $f done fi ``` <file_sep>#!/bin/bash INSTALLDIR="/usr/local" GOROOT="$INSTALLDIR/go" VERSION=$1 if [ -z $VERSION ]; then >&2 echo "usage: $0 VERSION" exit 1 fi #URL="https://dl.google.com/go/go$VERSION.linux-arm64.tar.gz" URL="https://golang.org/dl/go$VERSION.linux-arm64.tar.gz" if [ "$EUID" -ne 0 ]; then echo "this script should be run as root" exit 1 fi curl --location $URL -o go.tgz if [ -d $GOROOT ]; then rm -rf $GOROOT fi tar -C $INSTALLDIR -xf go.tgz rm go.tgz $GOROOT/bin/go version <file_sep>#!/bin/bash INSTALLDIR="$HOME/.bin" BINARYPATH="$INSTALLDIR/hugo" VERSION=$1 if [ -z $VERSION ]; then >&2 echo "usage: $0 VERSION" exit 1 fi curl --location --silent \ "https://github.com/gohugoio/hugo/releases/download/v${VERSION}/hugo_${VERSION}_Linux-ARM64.tar.gz" \ -o hugo.tgz if [ -f $BINARYPATH ]; then rm $BINARYPATH fi tar -C $INSTALLDIR -xf hugo.tgz hugo rm hugo.tgz $BINARYPATH version
1e969dc46c6ca0f2c8c044b561d19a67b9bc6fae
[ "Markdown", "Shell" ]
10
Shell
aitva/dotfiles
59f4671650578e75d2f14fd1600646e78a29f2c5
c8a33a7af6203a33b19f0f753897395132f28eae
refs/heads/master
<file_sep># Gramener-Case-Study To understand how consumer attributes and loan attributes influence the tendency of default. <file_sep>#Loading the Required packages library(dplyr) library(tidyr) library(ggplot2) library(scales) #Loading the data file to be analysed loan<-read.csv("loan.csv",stringsAsFactors = F, na.strings=c("", " ", "NA", "N/A")) #Structure of loan data file str(loan) #View loan data file View(loan) #Cleaning the data #There are many columns with only NA,0 or 1 which are not required.Removing the columns with NA,0 or 1 loan <-loan[vapply(loan, function(x) length(unique(x)) > 1, logical(1L))] #Url,desc,title columns are not required for analysis,hence removing those loan <- select(loan,-c(url,desc,title)) #Removing columns with only 0 and NA as it cannot be used for any analysis #1.collections_12_mths_ex_med #2.chargeoff_within_12_mths #3.tax_liens loan <- select(loan,-c(collections_12_mths_ex_med,chargeoff_within_12_mths,tax_liens)) #Checking for duplicate entries loan$id[duplicated(loan$id)] #As all loans in the data base are induvidual,memberid can be removed.Also Id is not required #in the analysis,hence removing this also loan <-select(loan,-c(id,member_id)) #Attributes selected for analysis #Categorical Variable #1.term 2.grade 3.emp_length #4.home_ownership 5.verification status #6.loan_status 7.purpose #Continuous Variable #1.loan_amnt 2.funded_amnt 3.funded_amnt_inv #4.dti 5.revol_bal 6.annual_inc loan_final<-select(loan,c(loan_amnt,funded_amnt,funded_amnt_inv,term,grade,emp_length,home_ownership,verification_status,annual_inc,loan_status,purpose,dti,revol_bal)) str(loan_final) #summary of data set summary(loan_final) #character varaible, we will first convert them into factor variable for better analysis chr_to_factor <- function(x) { for (i in 1:ncol(x)) { if (typeof(x[, i]) == "character") { x[, i] <- as.factor(x[, i]) } } return(x) } loan_final <- chr_to_factor(loan_final) #loan_status have three options: #1.Fully paid #2.Charged Off #3.Current # We are only interested in fully paid and charged off #for our analysis,hence remove current #Converting the loan_status contents to uppercase for uniformity in data loan_final$loan_status<-toupper(loan$loan_status) #Removing loan_status=CURRENT loan_final<-filter(loan_final,loan_status!="CURRENT") #Filtering Charged off data loan_final_ch<-filter(loan_final,loan_status=="CHARGED OFF") #Uni-variate analysis #Chargedoff Applicants #Categorical Variable #1.Home-OWnership ggplot(loan_final_ch, aes(x= home_ownership, group=loan_status)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes( label = scales::percent(..prop..), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="Home Ownership",y = "Percentage", title="Home Ownership of Applicants") + facet_grid(~loan_status) + scale_y_continuous(labels = scales::percent) #2.Grade ggplot(loan_final_ch, aes(x=grade, group=loan_status)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes( label = scales::percent(..prop..), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="Grade",y = "Percentage", title="Grade of Applicants") + facet_grid(~loan_status) + scale_y_continuous(labels = scales::percent) #3.Purpose ggplot(loan_final_ch, aes(x=purpose, group=loan_status)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes( label = scales::percent(..prop..), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="Loan purpose",y = "Percentage", title="Loan Purpose of Applicants") + facet_grid(~loan_status) + scale_y_continuous(labels = scales::percent) #4.Verification Status ggplot(loan_final_ch, aes(x=verification_status, group=loan_status)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes( label = scales::percent(..prop..), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="Verification Status",y = "Percentage", title="Verification status of Applicants") + facet_grid(~loan_status) + scale_y_continuous(labels = scales::percent) #5.term ggplot(loan_final_ch, aes(x=term, group=loan_status)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes( label = scales::percent(..prop..), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="Loan Term",y = "Percentage", title="Loan term of Applicants") + facet_grid(~loan_status) + scale_y_continuous(labels = scales::percent) #Derived Matrices #6.Employment Length #Deriving metrices: emp_length_grp from emp #Grouping the employment length as #1. 0 to 4 years "Junior" #2. 5 to 8 years "Mid-Level" #3. 9 years and above "Senior loan_final_ch$emp_len_grp <- ifelse( loan_final_ch$emp_length %in% c("< 1 year", "1 year", "2 years", "3 years", "4 years"), "Junior", ifelse( loan_final_ch$emp_length %in% c("5 years", "6 years", "7 years", "8 years") , "Mid-Level", ifelse( loan_final_ch$emp_length %in% c("9 years", "10+ years"), "Senior", "NA" ) ) ) ggplot(loan_final_ch, aes(x=emp_len_grp, group=loan_status)) + geom_bar(aes(y = ..prop.., fill = factor(..x..)), stat="count") + geom_text(aes( label = scales::percent(..prop..), y= ..prop.. ), stat= "count", vjust = -.5) + labs(x="Length of Employment",y = "Percentage", title="Length of Employment of Applicants") + facet_grid(~loan_status) + scale_y_continuous(labels = scales::percent) #Continuous variable #1.Loan Amount ggplot(loan_final_ch, aes(x=loan_amnt,fill=loan_status)) +geom_density() #2.funded Amount ggplot(loan_final_ch, aes(x=funded_amnt,fill=loan_status)) +geom_density() #3.funded Amount_inv ggplot(loan_final_ch, aes(x=funded_amnt_inv,fill=loan_status)) +geom_density() #4.Annual Income ggplot(loan_final_ch, aes(x=annual_inc,fill=loan_status)) +geom_dotplot()+facet_grid(~loan_status) #Bivariate Analysis #Derived Metrices # Derived Dti # Dti is Debt to Income Ratio.Revolving balance is the portion # that goes unpaid at the end of a billing cycle.so including revol_bal in dti # derived_dti=(revol_bal/annual_inc)+dti # Checking for NAs which(is.na(loan_final$dti)) which(is.na(loan_final$annual_inc)) which(is.na(loan_final$revol_bal)) loan_final$derived_dti=(loan_final$revol_bal/loan_final$annual_inc)+loan_final$dti ggplot(loan_final, aes(x=derived_dti,fill=loan_status)) +geom_density()
13f338d84a42779318b81900ce7127f3b2931efe
[ "Markdown", "R" ]
2
Markdown
kumshivam1/Gramener-Case-Study
33d2d15d9e6ee31cc3206b43398f6df2644737e1
cb1206f472b615f6070668f95daede50a6f8dc89
refs/heads/master
<file_sep>var LodashModuleReplacementPlugin = require('lodash-webpack-plugin'); var webpack = require('webpack'); module.exports = { 'module': { 'loaders': [{ 'loader': 'babel', 'test': /\.js$/, 'exclude': /node_modules/, 'query': { 'plugins': ['lodash'], 'presets': ['es2015'] } }] }, 'plugins': [ new LodashModuleReplacementPlugin, new webpack.optimize.OccurrenceOrderPlugin, new webpack.optimize.UglifyJsPlugin ] }; <file_sep>'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); function plus(a) { console.log('plus a:' + a); return ++a; } function muti(a) { console.log('muti a:' + a); return a * a; } exports.plus = plus; exports.muti = muti; exports.default = { plus: plus, muti: muti };<file_sep>#空闲时间练习 ##babel 注意babel的presets需要安装上对应的插件如`es2015`就需要安装`babel-preset-es2015` ##eslint - extends:“eslint:recommended”表示使用eslint推荐的代码风格 - parser:“babel-eslint”表示使用babel-eslint作为代码识别器? - ecmaVersion:6,识别ES6 - sourceType:"module",模块化的代码 - rules:自定义规则 - globals:全局变量,方法 ##es6-babel `npm run es6-babel` - es6的`export`和`import` ##lodash和webpack - lodash支持使用webpack打包使用中的内容,需要用到插件`lodash-webpack-plugin` <file_sep>'use strict'; var _operation = require('./operation'); var _operation2 = _interopRequireDefault(_operation); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var a = (0, _operation.plus)(1); var b = _operation2.default.muti(2); // let b = muti(2); console.log(a); console.log(b);<file_sep>import {clone,merge} from 'lodash' let user = { name:'xutao', friends:['amy','anyi','hebi'] } let age = { birthday:'2016年08月08日15:44:15' } let newUser = clone(user); let oldUser = merge(user,age); console.log(newUser.name); console.log(oldUser);
8c489b1ad96ed5b9e3a4698d400a0d8bce68210f
[ "JavaScript", "Markdown" ]
5
JavaScript
towersxu/self-practce
071dd9eae142c94f7ea06f8edd6b4e46c08ba43c
10af6b7c9cfc8d624515db956451704448a506ef
refs/heads/master
<file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) require 'faker' fruits = ["apple", "peach", "sloeberry", "pineapple", "kiwi", "lemon", "lime", "kiwano", "cucumber", "strawberry"] fruits.each do |fruit| ingredient = Ingredient.new(name: fruit) ingredient.save! end
1ac3dec4ba1e24a40cd8549fa56802676e8c485e
[ "Ruby" ]
1
Ruby
michaellim92/rails-mister-cocktail
f6ce26edc77f5cf5d980d147089370b4bf123432
8d74f9e281620ee3e360320af3cacf65287c2dc5
refs/heads/master
<file_sep>""" Weather API configuration details """ PORT = 8088 # Weather Underground API key # https://www.wunderground.com/weather/api/ WU_API_URL_BASE = 'http://api.wunderground.com/api/' WU_API_KEY = # TODO: add your API key here # Open Weather Map API key # https://openweathermap.org/api OWM_API_URL_BASE = 'http://api.openweathermap.org/data/2.5/weather?' OWM_API_KEY = # TODO: add your API key here <file_sep># Music API configuration from pygn import Pygn # Service port number PORT = 8089 # Music API username and password clientID = # TODO: Enter your Client ID from developer.gracenote.com here userID = Pygn.register(clientID) # Get a User ID from pygn.register() - Only register once per end-user
f18d3a9d04a7a6fe2a41006653c356170e50490f
[ "Python" ]
2
Python
AniFichadia/lucida
9c19cbdfbd103bd224755258fef09b18c5f4ea4a
88b11635b2863ed4f0229c2e3a58319b87762966
refs/heads/master
<file_sep>require 'rho/rhocontroller' require 'helpers/browser_helper' class ThemepageController < Rho::RhoController include BrowserHelper # GET /Themepage def index @themepages = Themepage.find(:all) render :back => '/app' end # GET /Themepage/{1} def show @themepage = Themepage.find(@params['id']) if @themepage render :action => :show, :back => url_for(:action => :index) else redirect :action => :index end end # GET /Themepage/new def new @themepage = Themepage.new render :action => :new, :back => url_for(:action => :index) end # GET /Themepage/{1}/edit def edit @themepage = Themepage.find(@params['id']) if @themepage render :action => :edit, :back => url_for(:action => :index) else redirect :action => :index end end # POST /Themepage/create def create @themepage = Themepage.create(@params['themepage']) redirect :action => :index end # POST /Themepage/{1}/update def update @themepage = Themepage.find(@params['id']) @themepage.update_attributes(@params['themepage']) if @themepage redirect :action => :index end # POST /Themepage/{1}/delete def delete @themepage = Themepage.find(@params['id']) @themepage.destroy if @themepage redirect :action => :index end def theme_a end def theme_b end def theme_c end def theme_d end def theme_e end end <file_sep>require 'rho/rhocontroller' require 'helpers/browser_helper' class ListViewController < Rho::RhoController include BrowserHelper # GET /ListView def index @list_views = ListView.find(:all) render :back => '/app' end # GET /ListView/{1} def show @list_view = ListView.find(@params['id']) if @list_view render :action => :show, :back => url_for(:action => :index) else redirect :action => :index end end # GET /ListView/new def new @list_view = ListView.new render :action => :new, :back => url_for(:action => :index) end # GET /ListView/{1}/edit def edit @list_view = ListView.find(@params['id']) if @list_view render :action => :edit, :back => url_for(:action => :index) else redirect :action => :index end end # POST /ListView/create def create @list_view = ListView.create(@params['list_view']) redirect :action => :index end # POST /ListView/{1}/update def update @list_view = ListView.find(@params['id']) @list_view.update_attributes(@params['list_view']) if @list_view redirect :action => :index end # POST /ListView/{1}/delete def delete @list_view = ListView.find(@params['id']) @list_view.destroy if @list_view redirect :action => :index end end <file_sep>require 'rho/rhocontroller' require 'helpers/browser_helper' class OverviewPageController < Rho::RhoController include BrowserHelper # GET /OverviewPage def index @overview_pages = OverviewPage.find(:all) render :back => '/app' end # GET /OverviewPage/{1} def show @overview_page = OverviewPage.find(@params['id']) if @overview_page render :action => :show, :back => url_for(:action => :index) else redirect :action => :index end end # GET /OverviewPage/new def new @overview_page = OverviewPage.new render :action => :new, :back => url_for(:action => :index) end # GET /OverviewPage/{1}/edit def edit @overview_page = OverviewPage.find(@params['id']) if @overview_page render :action => :edit, :back => url_for(:action => :index) else redirect :action => :index end end # POST /OverviewPage/create def create @overview_page = OverviewPage.create(@params['overview_page']) redirect :action => :index end # POST /OverviewPage/{1}/update def update @overview_page = OverviewPage.find(@params['id']) @overview_page.update_attributes(@params['overview_page']) if @overview_page redirect :action => :index end # POST /OverviewPage/{1}/delete def delete @overview_page = OverviewPage.find(@params['id']) @overview_page.destroy if @overview_page redirect :action => :index end end <file_sep>require 'rho/rhocontroller' require 'helpers/browser_helper' class PageTransitionsController < Rho::RhoController include BrowserHelper # GET /PageTransitions def dialog_page end end
ad5ddaa885bad9442665885613a3da92533d5d0b
[ "Ruby" ]
4
Ruby
spritle/rhodes_samples
1d9a1d758f37b7d93a3074f221a782c847323144
2a504c50fa40e765379b5e0828bfe1dba51dfdb7
refs/heads/master
<file_sep>console.log("akash"); function check(){ var isEmpty = false; var fname = document.getElementById("validationCustom01").value, lname = document.getElementById("validationCustom02").value, email = document.getElementById("validationCustomUsername").value, city = document.getElementById("City").value, state = document.getElementById("validationCustom04").value, gender = document.getElementById("gender").value, // gender = document.getElementById("inlineCheckbox2").value, // favcolor = document.getElementById("favcolor").value, message = document.getElementById("textarea").value; if(fname==""){ alert("enter your firstname"); isEmpty=true; } else if (lname==""){ alert("enter your last name"); isEmpty=true; } else if (email==""){ alert("enter your last email"); isEmpty=true; } else if (city==""){ alert("enter your last city"); isEmpty=true; } else if (state==""){ alert("enter your last state"); isEmpty=true; } else if (message==""){ alert("enter your last message"); isEmpty=true; } else if (gender==""){ alert("enter your last message"); isEmpty=true; } return isEmpty; } function submitkro(){ if (!check()){ var table = document.getElementById("table"); var newrow = table.insertRow(table.length); cell1 = newrow.insertCell(0), cell2 = newrow.insertCell(1), cell3 = newrow.insertCell(2), cell4 = newrow.insertCell(3), cell5 = newrow.insertCell(4), cell6 = newrow.insertCell(5), cell7 = newrow.insertCell(6), cell8 = newrow.insertCell(7); var fname = document.getElementById("validationCustom01").value, lname = document.getElementById("validationCustom02").value, email = document.getElementById("validationCustomUsername").value, city = document.getElementById("City").value, state = document.getElementById("validationCustom04").value, // gender = document.getElementById("inlineCheckbox1").value, // gender = document.getElementById("inlineCheckbox2").value, // favcolor = document.getElementById("favcolor").value, message = document.getElementById("textarea").value; cell1.innerHTML = fname; console.log(cell1); cell2.innerHTML= lname; cell3.innerHTML= email; cell4.innerHTML= city; cell5.innerHTML= state; cell8.innerHTML= message; // console.log("works"); var typeg= document.getElementsByName("typeg"); if(typeg[0].checked) { cell6.innerHTML="male"; } else if (typeg[1].checked) { cell6.innerHTML="female"; } var typec= document.getElementsByName("typec"); if(typec[0].checked) { cell7.innerHTML="red"; } else if (typec[1].checked) { cell7.innerHTML="blue"; } document.getElementById("form").reset(); } // var reset = document.getElementById("subBtn"); // reset.addEventListener("click",function(e){ // var form= document.getElementById("form"); // form.reset(); } // function submitkro(){ // console.log("yeh gender ke liye hai"); // }
f210b68ddf066d2e1493712b8454e3b59fd534d6
[ "JavaScript" ]
1
JavaScript
akashgarg1999/open
60310eece070c72b928e328d658f872ef6f5bb93
d48e18128b4b887792a483a579d27b9d6fd3959d
refs/heads/master
<repo_name>LucaMantani/UFO_models<file_sep>/DMsimp_t/DMsimp_t_f3_LO/parameters.py # This file was automatically created by FeynRules 2.3.29 # Mathematica version: 11.2.0 for Mac OS X x86 (64-bit) (September 11, 2017) # Date: Tue 12 Mar 2019 11:12:13 from object_library import all_parameters, Parameter from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot # This is a default parameter object representing 0. ZERO = Parameter(name = 'ZERO', nature = 'internal', type = 'real', value = '0.0', texname = '0') # User-defined parameters. gF3dR1x1 = Parameter(name = 'gF3dR1x1', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3dR1x1}', lhablock = 'DMINPUTSDR', lhacode = [ 1, 1 ]) gF3dR2x2 = Parameter(name = 'gF3dR2x2', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3dR2x2}', lhablock = 'DMINPUTSDR', lhacode = [ 2, 2 ]) gF3dR3x3 = Parameter(name = 'gF3dR3x3', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3dR3x3}', lhablock = 'DMINPUTSDR', lhacode = [ 3, 3 ]) gF3L1x1 = Parameter(name = 'gF3L1x1', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3L1x1}', lhablock = 'DMINPUTSQL', lhacode = [ 1, 1 ]) gF3L2x2 = Parameter(name = 'gF3L2x2', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3L2x2}', lhablock = 'DMINPUTSQL', lhacode = [ 2, 2 ]) gF3L3x3 = Parameter(name = 'gF3L3x3', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3L3x3}', lhablock = 'DMINPUTSQL', lhacode = [ 3, 3 ]) gF3uR1x1 = Parameter(name = 'gF3uR1x1', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3uR1x1}', lhablock = 'DMINPUTSUR', lhacode = [ 1, 1 ]) gF3uR2x2 = Parameter(name = 'gF3uR2x2', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3uR2x2}', lhablock = 'DMINPUTSUR', lhacode = [ 2, 2 ]) gF3uR3x3 = Parameter(name = 'gF3uR3x3', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gF3uR3x3}', lhablock = 'DMINPUTSUR', lhacode = [ 3, 3 ]) aEWM1 = Parameter(name = 'aEWM1', nature = 'external', type = 'real', value = 127.9, texname = '\\text{aEWM1}', lhablock = 'SMINPUTS', lhacode = [ 1 ]) Gf = Parameter(name = 'Gf', nature = 'external', type = 'real', value = 0.0000116637, texname = 'G_f', lhablock = 'SMINPUTS', lhacode = [ 2 ]) aS = Parameter(name = 'aS', nature = 'external', type = 'real', value = 0.1184, texname = '\\alpha _s', lhablock = 'SMINPUTS', lhacode = [ 3 ]) ymb = Parameter(name = 'ymb', nature = 'external', type = 'real', value = 4.7, texname = '\\text{ymb}', lhablock = 'YUKAWA', lhacode = [ 5 ]) ymt = Parameter(name = 'ymt', nature = 'external', type = 'real', value = 172, texname = '\\text{ymt}', lhablock = 'YUKAWA', lhacode = [ 6 ]) ymtau = Parameter(name = 'ymtau', nature = 'external', type = 'real', value = 1.777, texname = '\\text{ymtau}', lhablock = 'YUKAWA', lhacode = [ 15 ]) MZ = Parameter(name = 'MZ', nature = 'external', type = 'real', value = 91.1876, texname = '\\text{MZ}', lhablock = 'MASS', lhacode = [ 23 ]) MTA = Parameter(name = 'MTA', nature = 'external', type = 'real', value = 1.777, texname = '\\text{MTA}', lhablock = 'MASS', lhacode = [ 15 ]) MT = Parameter(name = 'MT', nature = 'external', type = 'real', value = 172, texname = '\\text{MT}', lhablock = 'MASS', lhacode = [ 6 ]) MB = Parameter(name = 'MB', nature = 'external', type = 'real', value = 4.7, texname = '\\text{MB}', lhablock = 'MASS', lhacode = [ 5 ]) MH = Parameter(name = 'MH', nature = 'external', type = 'real', value = 125, texname = '\\text{MH}', lhablock = 'MASS', lhacode = [ 25 ]) MXr = Parameter(name = 'MXr', nature = 'external', type = 'real', value = 10., texname = '\\text{MXr}', lhablock = 'MASS', lhacode = [ 51 ]) MXv = Parameter(name = 'MXv', nature = 'external', type = 'real', value = 10., texname = '\\text{MXv}', lhablock = 'MASS', lhacode = [ 53 ]) MF3uL1 = Parameter(name = 'MF3uL1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3uL1}', lhablock = 'MASS', lhacode = [ 3000002 ]) MF3uL2 = Parameter(name = 'MF3uL2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3uL2}', lhablock = 'MASS', lhacode = [ 3000004 ]) MF3uL3 = Parameter(name = 'MF3uL3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3uL3}', lhablock = 'MASS', lhacode = [ 3000006 ]) MF3dL1 = Parameter(name = 'MF3dL1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3dL1}', lhablock = 'MASS', lhacode = [ 3000001 ]) MF3dL2 = Parameter(name = 'MF3dL2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3dL2}', lhablock = 'MASS', lhacode = [ 3000003 ]) MF3dL3 = Parameter(name = 'MF3dL3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3dL3}', lhablock = 'MASS', lhacode = [ 3000005 ]) MF3uR1 = Parameter(name = 'MF3uR1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3uR1}', lhablock = 'MASS', lhacode = [ 4000002 ]) MF3uR2 = Parameter(name = 'MF3uR2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3uR2}', lhablock = 'MASS', lhacode = [ 4000004 ]) MF3uR3 = Parameter(name = 'MF3uR3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3uR3}', lhablock = 'MASS', lhacode = [ 4000006 ]) MF3dR1 = Parameter(name = 'MF3dR1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3dR1}', lhablock = 'MASS', lhacode = [ 4000001 ]) MF3dR2 = Parameter(name = 'MF3dR2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3dR2}', lhablock = 'MASS', lhacode = [ 4000003 ]) MF3dR3 = Parameter(name = 'MF3dR3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MF3dR3}', lhablock = 'MASS', lhacode = [ 4000005 ]) WZ = Parameter(name = 'WZ', nature = 'external', type = 'real', value = 2.4952, texname = '\\text{WZ}', lhablock = 'DECAY', lhacode = [ 23 ]) WW = Parameter(name = 'WW', nature = 'external', type = 'real', value = 2.085, texname = '\\text{WW}', lhablock = 'DECAY', lhacode = [ 24 ]) WT = Parameter(name = 'WT', nature = 'external', type = 'real', value = 1.50833649, texname = '\\text{WT}', lhablock = 'DECAY', lhacode = [ 6 ]) WH = Parameter(name = 'WH', nature = 'external', type = 'real', value = 0.00407, texname = '\\text{WH}', lhablock = 'DECAY', lhacode = [ 25 ]) WF3uL1 = Parameter(name = 'WF3uL1', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3uL1}', lhablock = 'DECAY', lhacode = [ 3000002 ]) WF3uL2 = Parameter(name = 'WF3uL2', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3uL2}', lhablock = 'DECAY', lhacode = [ 3000004 ]) WF3uL3 = Parameter(name = 'WF3uL3', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3uL3}', lhablock = 'DECAY', lhacode = [ 3000006 ]) WF3dL1 = Parameter(name = 'WF3dL1', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3dL1}', lhablock = 'DECAY', lhacode = [ 3000001 ]) WF3dL2 = Parameter(name = 'WF3dL2', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3dL2}', lhablock = 'DECAY', lhacode = [ 3000003 ]) WF3dL3 = Parameter(name = 'WF3dL3', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3dL3}', lhablock = 'DECAY', lhacode = [ 3000005 ]) WF3uR1 = Parameter(name = 'WF3uR1', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3uR1}', lhablock = 'DECAY', lhacode = [ 4000002 ]) WF3uR2 = Parameter(name = 'WF3uR2', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3uR2}', lhablock = 'DECAY', lhacode = [ 4000004 ]) WF3uR3 = Parameter(name = 'WF3uR3', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3uR3}', lhablock = 'DECAY', lhacode = [ 4000006 ]) WF3dR1 = Parameter(name = 'WF3dR1', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3dR1}', lhablock = 'DECAY', lhacode = [ 4000001 ]) WF3dR2 = Parameter(name = 'WF3dR2', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3dR2}', lhablock = 'DECAY', lhacode = [ 4000003 ]) WF3dR3 = Parameter(name = 'WF3dR3', nature = 'external', type = 'real', value = 10., texname = '\\text{WF3dR3}', lhablock = 'DECAY', lhacode = [ 4000005 ]) aEW = Parameter(name = 'aEW', nature = 'internal', type = 'real', value = '1/aEWM1', texname = '\\alpha _{\\text{EW}}') G = Parameter(name = 'G', nature = 'internal', type = 'real', value = '2*cmath.sqrt(aS)*cmath.sqrt(cmath.pi)', texname = 'G') MW = Parameter(name = 'MW', nature = 'internal', type = 'real', value = 'cmath.sqrt(MZ**2/2. + cmath.sqrt(MZ**4/4. - (aEW*cmath.pi*MZ**2)/(Gf*cmath.sqrt(2))))', texname = 'M_W') ee = Parameter(name = 'ee', nature = 'internal', type = 'real', value = '2*cmath.sqrt(aEW)*cmath.sqrt(cmath.pi)', texname = 'e') sw2 = Parameter(name = 'sw2', nature = 'internal', type = 'real', value = '1 - MW**2/MZ**2', texname = '\\text{sw2}') cw = Parameter(name = 'cw', nature = 'internal', type = 'real', value = 'cmath.sqrt(1 - sw2)', texname = 'c_w') sw = Parameter(name = 'sw', nature = 'internal', type = 'real', value = 'cmath.sqrt(sw2)', texname = 's_w') g1 = Parameter(name = 'g1', nature = 'internal', type = 'real', value = 'ee/cw', texname = 'g_1') gw = Parameter(name = 'gw', nature = 'internal', type = 'real', value = 'ee/sw', texname = 'g_w') vev = Parameter(name = 'vev', nature = 'internal', type = 'real', value = '(2*MW*sw)/ee', texname = '\\text{vev}') lam = Parameter(name = 'lam', nature = 'internal', type = 'real', value = 'MH**2/(2.*vev**2)', texname = '\\text{lam}') yb = Parameter(name = 'yb', nature = 'internal', type = 'real', value = '(ymb*cmath.sqrt(2))/vev', texname = '\\text{yb}') yt = Parameter(name = 'yt', nature = 'internal', type = 'real', value = '(ymt*cmath.sqrt(2))/vev', texname = '\\text{yt}') ytau = Parameter(name = 'ytau', nature = 'internal', type = 'real', value = '(ymtau*cmath.sqrt(2))/vev', texname = '\\text{ytau}') muH = Parameter(name = 'muH', nature = 'internal', type = 'real', value = 'cmath.sqrt(lam*vev**2)', texname = '\\mu') <file_sep>/DMsimp_t/DMsimp_t_f3_LO/particles.py # This file was automatically created by FeynRules 2.3.29 # Mathematica version: 11.2.0 for Mac OS X x86 (64-bit) (September 11, 2017) # Date: Tue 12 Mar 2019 11:12:13 from __future__ import division from object_library import all_particles, Particle import parameters as Param import propagators as Prop a = Particle(pdg_code = 22, name = 'a', antiname = 'a', spin = 3, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'a', antitexname = 'a', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) Z = Particle(pdg_code = 23, name = 'Z', antiname = 'Z', spin = 3, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'Z', antitexname = 'Z', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) W__plus__ = Particle(pdg_code = 24, name = 'W+', antiname = 'W-', spin = 3, color = 1, mass = Param.MW, width = Param.WW, texname = 'W+', antitexname = 'W-', charge = 1, GhostNumber = 0, LeptonNumber = 0, Y = 0) W__minus__ = W__plus__.anti() g = Particle(pdg_code = 21, name = 'g', antiname = 'g', spin = 3, color = 8, mass = Param.ZERO, width = Param.ZERO, texname = 'g', antitexname = 'g', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) ghA = Particle(pdg_code = 9000001, name = 'ghA', antiname = 'ghA~', spin = -1, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'ghA', antitexname = 'ghA~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghA__tilde__ = ghA.anti() ghZ = Particle(pdg_code = 9000002, name = 'ghZ', antiname = 'ghZ~', spin = -1, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'ghZ', antitexname = 'ghZ~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghZ__tilde__ = ghZ.anti() ghWp = Particle(pdg_code = 9000003, name = 'ghWp', antiname = 'ghWp~', spin = -1, color = 1, mass = Param.MW, width = Param.WW, texname = 'ghWp', antitexname = 'ghWp~', charge = 1, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghWp__tilde__ = ghWp.anti() ghWm = Particle(pdg_code = 9000004, name = 'ghWm', antiname = 'ghWm~', spin = -1, color = 1, mass = Param.MW, width = Param.WW, texname = 'ghWm', antitexname = 'ghWm~', charge = -1, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghWm__tilde__ = ghWm.anti() ghG = Particle(pdg_code = 82, name = 'ghG', antiname = 'ghG~', spin = -1, color = 8, mass = Param.ZERO, width = Param.ZERO, texname = 'ghG', antitexname = 'ghG~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghG__tilde__ = ghG.anti() ve = Particle(pdg_code = 12, name = 've', antiname = 've~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 've', antitexname = 've~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) ve__tilde__ = ve.anti() vm = Particle(pdg_code = 14, name = 'vm', antiname = 'vm~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'vm', antitexname = 'vm~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) vm__tilde__ = vm.anti() vt = Particle(pdg_code = 16, name = 'vt', antiname = 'vt~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'vt', antitexname = 'vt~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) vt__tilde__ = vt.anti() e__minus__ = Particle(pdg_code = 11, name = 'e-', antiname = 'e+', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'e-', antitexname = 'e+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) e__plus__ = e__minus__.anti() mu__minus__ = Particle(pdg_code = 13, name = 'mu-', antiname = 'mu+', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'mu-', antitexname = 'mu+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) mu__plus__ = mu__minus__.anti() ta__minus__ = Particle(pdg_code = 15, name = 'ta-', antiname = 'ta+', spin = 2, color = 1, mass = Param.MTA, width = Param.ZERO, texname = 'ta-', antitexname = 'ta+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) ta__plus__ = ta__minus__.anti() u = Particle(pdg_code = 2, name = 'u', antiname = 'u~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'u', antitexname = 'u~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) u__tilde__ = u.anti() c = Particle(pdg_code = 4, name = 'c', antiname = 'c~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'c', antitexname = 'c~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) c__tilde__ = c.anti() t = Particle(pdg_code = 6, name = 't', antiname = 't~', spin = 2, color = 3, mass = Param.MT, width = Param.WT, texname = 't', antitexname = 't~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) t__tilde__ = t.anti() d = Particle(pdg_code = 1, name = 'd', antiname = 'd~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'd', antitexname = 'd~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) d__tilde__ = d.anti() s = Particle(pdg_code = 3, name = 's', antiname = 's~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 's', antitexname = 's~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) s__tilde__ = s.anti() b = Particle(pdg_code = 5, name = 'b', antiname = 'b~', spin = 2, color = 3, mass = Param.MB, width = Param.ZERO, texname = 'b', antitexname = 'b~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) b__tilde__ = b.anti() H = Particle(pdg_code = 25, name = 'H', antiname = 'H', spin = 1, color = 1, mass = Param.MH, width = Param.WH, texname = 'H', antitexname = 'H', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) G0 = Particle(pdg_code = 250, name = 'G0', antiname = 'G0', spin = 1, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'G0', antitexname = 'G0', goldstone = True, charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) G__plus__ = Particle(pdg_code = 251, name = 'G+', antiname = 'G-', spin = 1, color = 1, mass = Param.MW, width = Param.WW, texname = 'G+', antitexname = 'G-', goldstone = True, charge = 1, GhostNumber = 0, LeptonNumber = 0, Y = 0) G__minus__ = G__plus__.anti() Xr = Particle(pdg_code = 51, name = 'Xr', antiname = 'Xr', spin = 1, color = 1, mass = Param.MXr, width = Param.ZERO, texname = 'Xr', antitexname = 'Xr', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) Xv = Particle(pdg_code = 53, name = 'Xv', antiname = 'Xv', spin = 3, color = 1, mass = Param.MXv, width = Param.ZERO, texname = 'Xv', antitexname = 'Xv', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uL1 = Particle(pdg_code = 3000002, name = 'F3uL1', antiname = 'F3uL1~', spin = 2, color = 3, mass = Param.MF3uL1, width = Param.WF3uL1, texname = 'F3uL1', antitexname = 'F3uL1~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uL1__tilde__ = F3uL1.anti() F3uL2 = Particle(pdg_code = 3000004, name = 'F3uL2', antiname = 'F3uL2~', spin = 2, color = 3, mass = Param.MF3uL2, width = Param.WF3uL2, texname = 'F3uL2', antitexname = 'F3uL2~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uL2__tilde__ = F3uL2.anti() F3uL3 = Particle(pdg_code = 3000006, name = 'F3uL3', antiname = 'F3uL3~', spin = 2, color = 3, mass = Param.MF3uL3, width = Param.WF3uL3, texname = 'F3uL3', antitexname = 'F3uL3~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uL3__tilde__ = F3uL3.anti() F3dL1 = Particle(pdg_code = 3000001, name = 'F3dL1', antiname = 'F3dL1~', spin = 2, color = 3, mass = Param.MF3dL1, width = Param.WF3dL1, texname = 'F3dL1', antitexname = 'F3dL1~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3dL1__tilde__ = F3dL1.anti() F3dL2 = Particle(pdg_code = 3000003, name = 'F3dL2', antiname = 'F3dL2~', spin = 2, color = 3, mass = Param.MF3dL2, width = Param.WF3dL2, texname = 'F3dL2', antitexname = 'F3dL2~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3dL2__tilde__ = F3dL2.anti() F3dL3 = Particle(pdg_code = 3000005, name = 'F3dL3', antiname = 'F3dL3~', spin = 2, color = 3, mass = Param.MF3dL3, width = Param.WF3dL3, texname = 'F3dL3', antitexname = 'F3dL3~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3dL3__tilde__ = F3dL3.anti() F3uR1 = Particle(pdg_code = 4000002, name = 'F3uR1', antiname = 'F3uR1~', spin = 2, color = 3, mass = Param.MF3uR1, width = Param.WF3uR1, texname = 'F3uR1', antitexname = 'F3uR1~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uR1__tilde__ = F3uR1.anti() F3uR2 = Particle(pdg_code = 4000004, name = 'F3uR2', antiname = 'F3uR2~', spin = 2, color = 3, mass = Param.MF3uR2, width = Param.WF3uR2, texname = 'F3uR2', antitexname = 'F3uR2~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uR2__tilde__ = F3uR2.anti() F3uR3 = Particle(pdg_code = 4000006, name = 'F3uR3', antiname = 'F3uR3~', spin = 2, color = 3, mass = Param.MF3uR3, width = Param.WF3uR3, texname = 'F3uR3', antitexname = 'F3uR3~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3uR3__tilde__ = F3uR3.anti() F3dR1 = Particle(pdg_code = 4000001, name = 'F3dR1', antiname = 'F3dR1~', spin = 2, color = 3, mass = Param.MF3dR1, width = Param.WF3dR1, texname = 'F3dR1', antitexname = 'F3dR1~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3dR1__tilde__ = F3dR1.anti() F3dR2 = Particle(pdg_code = 4000003, name = 'F3dR2', antiname = 'F3dR2~', spin = 2, color = 3, mass = Param.MF3dR2, width = Param.WF3dR2, texname = 'F3dR2', antitexname = 'F3dR2~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3dR2__tilde__ = F3dR2.anti() F3dR3 = Particle(pdg_code = 4000005, name = 'F3dR3', antiname = 'F3dR3~', spin = 2, color = 3, mass = Param.MF3dR3, width = Param.WF3dR3, texname = 'F3dR3', antitexname = 'F3dR3~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) F3dR3__tilde__ = F3dR3.anti() <file_sep>/DMsimp_t/DMsimp_t_f3_LO/coupling_orders.py # This file was automatically created by FeynRules 2.3.29 # Mathematica version: 11.2.0 for Mac OS X x86 (64-bit) (September 11, 2017) # Date: Tue 12 Mar 2019 11:12:13 from object_library import all_orders, CouplingOrder DMT = CouplingOrder(name = 'DMT', expansion_order = 2, hierarchy = 2) QCD = CouplingOrder(name = 'QCD', expansion_order = 99, hierarchy = 1) QED = CouplingOrder(name = 'QED', expansion_order = 99, hierarchy = 2) <file_sep>/H_k-framework/H_k_framework_LO/coupling_orders.py # This file was automatically created by FeynRules 2.3.36 # Mathematica version: 12.1.1 for Mac OS X x86 (64-bit) (June 19, 2020) # Date: Mon 9 Nov 2020 16:49:03 from object_library import all_orders, CouplingOrder NPH3 = CouplingOrder(name = 'NPH3', expansion_order = 2, hierarchy = 2) NPH4 = CouplingOrder(name = 'NPH4', expansion_order = 2, hierarchy = 2) NPVVH = CouplingOrder(name = 'NPVVH', expansion_order = 2, hierarchy = 2) NPVVHH = CouplingOrder(name = 'NPVVHH', expansion_order = 2, hierarchy = 2) NPVVHHH = CouplingOrder(name = 'NPVVHHH', expansion_order = 2, hierarchy = 2) QCD = CouplingOrder(name = 'QCD', expansion_order = 99, hierarchy = 1) QED = CouplingOrder(name = 'QED', expansion_order = 99, hierarchy = 2) <file_sep>/DMsimp_t/DMsimp_t_s3_LO/parameters.py # This file was automatically created by FeynRules 2.3.29 # Mathematica version: 11.2.0 for Mac OS X x86 (64-bit) (September 11, 2017) # Date: Tue 12 Mar 2019 11:10:19 from object_library import all_parameters, Parameter from function_library import complexconjugate, re, im, csc, sec, acsc, asec, cot # This is a default parameter object representing 0. ZERO = Parameter(name = 'ZERO', nature = 'internal', type = 'real', value = '0.0', texname = '0') # User-defined parameters. gS3dR1x1 = Parameter(name = 'gS3dR1x1', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3dR1x1}', lhablock = 'DMINPUTSDR', lhacode = [ 1, 1 ]) gS3dR2x2 = Parameter(name = 'gS3dR2x2', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3dR2x2}', lhablock = 'DMINPUTSDR', lhacode = [ 2, 2 ]) gS3dR3x3 = Parameter(name = 'gS3dR3x3', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3dR3x3}', lhablock = 'DMINPUTSDR', lhacode = [ 3, 3 ]) gS3L1x1 = Parameter(name = 'gS3L1x1', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3L1x1}', lhablock = 'DMINPUTSQL', lhacode = [ 1, 1 ]) gS3L2x2 = Parameter(name = 'gS3L2x2', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3L2x2}', lhablock = 'DMINPUTSQL', lhacode = [ 2, 2 ]) gS3L3x3 = Parameter(name = 'gS3L3x3', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3L3x3}', lhablock = 'DMINPUTSQL', lhacode = [ 3, 3 ]) gS3uR1x1 = Parameter(name = 'gS3uR1x1', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3uR1x1}', lhablock = 'DMINPUTSUR', lhacode = [ 1, 1 ]) gS3uR2x2 = Parameter(name = 'gS3uR2x2', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3uR2x2}', lhablock = 'DMINPUTSUR', lhacode = [ 2, 2 ]) gS3uR3x3 = Parameter(name = 'gS3uR3x3', nature = 'external', type = 'complex', value = 1.1, texname = '\\text{gS3uR3x3}', lhablock = 'DMINPUTSUR', lhacode = [ 3, 3 ]) aEWM1 = Parameter(name = 'aEWM1', nature = 'external', type = 'real', value = 127.9, texname = '\\text{aEWM1}', lhablock = 'SMINPUTS', lhacode = [ 1 ]) Gf = Parameter(name = 'Gf', nature = 'external', type = 'real', value = 0.0000116637, texname = 'G_f', lhablock = 'SMINPUTS', lhacode = [ 2 ]) aS = Parameter(name = 'aS', nature = 'external', type = 'real', value = 0.1184, texname = '\\alpha _s', lhablock = 'SMINPUTS', lhacode = [ 3 ]) ymb = Parameter(name = 'ymb', nature = 'external', type = 'real', value = 4.7, texname = '\\text{ymb}', lhablock = 'YUKAWA', lhacode = [ 5 ]) ymt = Parameter(name = 'ymt', nature = 'external', type = 'real', value = 172, texname = '\\text{ymt}', lhablock = 'YUKAWA', lhacode = [ 6 ]) ymtau = Parameter(name = 'ymtau', nature = 'external', type = 'real', value = 1.777, texname = '\\text{ymtau}', lhablock = 'YUKAWA', lhacode = [ 15 ]) MZ = Parameter(name = 'MZ', nature = 'external', type = 'real', value = 91.1876, texname = '\\text{MZ}', lhablock = 'MASS', lhacode = [ 23 ]) MTA = Parameter(name = 'MTA', nature = 'external', type = 'real', value = 1.777, texname = '\\text{MTA}', lhablock = 'MASS', lhacode = [ 15 ]) MT = Parameter(name = 'MT', nature = 'external', type = 'real', value = 172, texname = '\\text{MT}', lhablock = 'MASS', lhacode = [ 6 ]) MB = Parameter(name = 'MB', nature = 'external', type = 'real', value = 4.7, texname = '\\text{MB}', lhablock = 'MASS', lhacode = [ 5 ]) MH = Parameter(name = 'MH', nature = 'external', type = 'real', value = 125, texname = '\\text{MH}', lhablock = 'MASS', lhacode = [ 25 ]) MXd = Parameter(name = 'MXd', nature = 'external', type = 'real', value = 10., texname = '\\text{MXd}', lhablock = 'MASS', lhacode = [ 52 ]) MXm = Parameter(name = 'MXm', nature = 'external', type = 'real', value = 100000., texname = '\\text{MXm}', lhablock = 'MASS', lhacode = [ 522 ]) MS3uL1 = Parameter(name = 'MS3uL1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3uL1}', lhablock = 'MASS', lhacode = [ 1000002 ]) MS3uL2 = Parameter(name = 'MS3uL2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3uL2}', lhablock = 'MASS', lhacode = [ 1000004 ]) MS3uL3 = Parameter(name = 'MS3uL3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3uL3}', lhablock = 'MASS', lhacode = [ 1000006 ]) MS3dL1 = Parameter(name = 'MS3dL1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3dL1}', lhablock = 'MASS', lhacode = [ 1000001 ]) MS3dL2 = Parameter(name = 'MS3dL2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3dL2}', lhablock = 'MASS', lhacode = [ 1000003 ]) MS3dL3 = Parameter(name = 'MS3dL3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3dL3}', lhablock = 'MASS', lhacode = [ 1000005 ]) MS3uR1 = Parameter(name = 'MS3uR1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3uR1}', lhablock = 'MASS', lhacode = [ 2000002 ]) MS3uR2 = Parameter(name = 'MS3uR2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3uR2}', lhablock = 'MASS', lhacode = [ 2000004 ]) MS3uR3 = Parameter(name = 'MS3uR3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3uR3}', lhablock = 'MASS', lhacode = [ 2000006 ]) MS3dR1 = Parameter(name = 'MS3dR1', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3dR1}', lhablock = 'MASS', lhacode = [ 2000001 ]) MS3dR2 = Parameter(name = 'MS3dR2', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3dR2}', lhablock = 'MASS', lhacode = [ 2000003 ]) MS3dR3 = Parameter(name = 'MS3dR3', nature = 'external', type = 'real', value = 1000., texname = '\\text{MS3dR3}', lhablock = 'MASS', lhacode = [ 2000005 ]) WZ = Parameter(name = 'WZ', nature = 'external', type = 'real', value = 2.4952, texname = '\\text{WZ}', lhablock = 'DECAY', lhacode = [ 23 ]) WW = Parameter(name = 'WW', nature = 'external', type = 'real', value = 2.085, texname = '\\text{WW}', lhablock = 'DECAY', lhacode = [ 24 ]) WT = Parameter(name = 'WT', nature = 'external', type = 'real', value = 1.50833649, texname = '\\text{WT}', lhablock = 'DECAY', lhacode = [ 6 ]) WH = Parameter(name = 'WH', nature = 'external', type = 'real', value = 0.00407, texname = '\\text{WH}', lhablock = 'DECAY', lhacode = [ 25 ]) WS3uL1 = Parameter(name = 'WS3uL1', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3uL1}', lhablock = 'DECAY', lhacode = [ 1000002 ]) WS3uL2 = Parameter(name = 'WS3uL2', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3uL2}', lhablock = 'DECAY', lhacode = [ 1000004 ]) WS3uL3 = Parameter(name = 'WS3uL3', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3uL3}', lhablock = 'DECAY', lhacode = [ 1000006 ]) WS3dL1 = Parameter(name = 'WS3dL1', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3dL1}', lhablock = 'DECAY', lhacode = [ 1000001 ]) WS3dL2 = Parameter(name = 'WS3dL2', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3dL2}', lhablock = 'DECAY', lhacode = [ 1000003 ]) WS3dL3 = Parameter(name = 'WS3dL3', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3dL3}', lhablock = 'DECAY', lhacode = [ 1000005 ]) WS3uR1 = Parameter(name = 'WS3uR1', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3uR1}', lhablock = 'DECAY', lhacode = [ 2000002 ]) WS3uR2 = Parameter(name = 'WS3uR2', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3uR2}', lhablock = 'DECAY', lhacode = [ 2000004 ]) WS3uR3 = Parameter(name = 'WS3uR3', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3uR3}', lhablock = 'DECAY', lhacode = [ 2000006 ]) WS3dR1 = Parameter(name = 'WS3dR1', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3dR1}', lhablock = 'DECAY', lhacode = [ 2000001 ]) WS3dR2 = Parameter(name = 'WS3dR2', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3dR2}', lhablock = 'DECAY', lhacode = [ 2000003 ]) WS3dR3 = Parameter(name = 'WS3dR3', nature = 'external', type = 'real', value = 10., texname = '\\text{WS3dR3}', lhablock = 'DECAY', lhacode = [ 2000005 ]) aEW = Parameter(name = 'aEW', nature = 'internal', type = 'real', value = '1/aEWM1', texname = '\\alpha _{\\text{EW}}') G = Parameter(name = 'G', nature = 'internal', type = 'real', value = '2*cmath.sqrt(aS)*cmath.sqrt(cmath.pi)', texname = 'G') MW = Parameter(name = 'MW', nature = 'internal', type = 'real', value = 'cmath.sqrt(MZ**2/2. + cmath.sqrt(MZ**4/4. - (aEW*cmath.pi*MZ**2)/(Gf*cmath.sqrt(2))))', texname = 'M_W') ee = Parameter(name = 'ee', nature = 'internal', type = 'real', value = '2*cmath.sqrt(aEW)*cmath.sqrt(cmath.pi)', texname = 'e') sw2 = Parameter(name = 'sw2', nature = 'internal', type = 'real', value = '1 - MW**2/MZ**2', texname = '\\text{sw2}') cw = Parameter(name = 'cw', nature = 'internal', type = 'real', value = 'cmath.sqrt(1 - sw2)', texname = 'c_w') sw = Parameter(name = 'sw', nature = 'internal', type = 'real', value = 'cmath.sqrt(sw2)', texname = 's_w') g1 = Parameter(name = 'g1', nature = 'internal', type = 'real', value = 'ee/cw', texname = 'g_1') gw = Parameter(name = 'gw', nature = 'internal', type = 'real', value = 'ee/sw', texname = 'g_w') vev = Parameter(name = 'vev', nature = 'internal', type = 'real', value = '(2*MW*sw)/ee', texname = '\\text{vev}') lam = Parameter(name = 'lam', nature = 'internal', type = 'real', value = 'MH**2/(2.*vev**2)', texname = '\\text{lam}') yb = Parameter(name = 'yb', nature = 'internal', type = 'real', value = '(ymb*cmath.sqrt(2))/vev', texname = '\\text{yb}') yt = Parameter(name = 'yt', nature = 'internal', type = 'real', value = '(ymt*cmath.sqrt(2))/vev', texname = '\\text{yt}') ytau = Parameter(name = 'ytau', nature = 'internal', type = 'real', value = '(ymtau*cmath.sqrt(2))/vev', texname = '\\text{ytau}') muH = Parameter(name = 'muH', nature = 'internal', type = 'real', value = 'cmath.sqrt(lam*vev**2)', texname = '\\mu') <file_sep>/DMsimp_t/DMsimp_t_s3_LO/particles.py # This file was automatically created by FeynRules 2.3.29 # Mathematica version: 11.2.0 for Mac OS X x86 (64-bit) (September 11, 2017) # Date: Tue 12 Mar 2019 11:10:19 from __future__ import division from object_library import all_particles, Particle import parameters as Param import propagators as Prop a = Particle(pdg_code = 22, name = 'a', antiname = 'a', spin = 3, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'a', antitexname = 'a', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) Z = Particle(pdg_code = 23, name = 'Z', antiname = 'Z', spin = 3, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'Z', antitexname = 'Z', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) W__plus__ = Particle(pdg_code = 24, name = 'W+', antiname = 'W-', spin = 3, color = 1, mass = Param.MW, width = Param.WW, texname = 'W+', antitexname = 'W-', charge = 1, GhostNumber = 0, LeptonNumber = 0, Y = 0) W__minus__ = W__plus__.anti() g = Particle(pdg_code = 21, name = 'g', antiname = 'g', spin = 3, color = 8, mass = Param.ZERO, width = Param.ZERO, texname = 'g', antitexname = 'g', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) ghA = Particle(pdg_code = 9000001, name = 'ghA', antiname = 'ghA~', spin = -1, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'ghA', antitexname = 'ghA~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghA__tilde__ = ghA.anti() ghZ = Particle(pdg_code = 9000002, name = 'ghZ', antiname = 'ghZ~', spin = -1, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'ghZ', antitexname = 'ghZ~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghZ__tilde__ = ghZ.anti() ghWp = Particle(pdg_code = 9000003, name = 'ghWp', antiname = 'ghWp~', spin = -1, color = 1, mass = Param.MW, width = Param.WW, texname = 'ghWp', antitexname = 'ghWp~', charge = 1, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghWp__tilde__ = ghWp.anti() ghWm = Particle(pdg_code = 9000004, name = 'ghWm', antiname = 'ghWm~', spin = -1, color = 1, mass = Param.MW, width = Param.WW, texname = 'ghWm', antitexname = 'ghWm~', charge = -1, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghWm__tilde__ = ghWm.anti() ghG = Particle(pdg_code = 82, name = 'ghG', antiname = 'ghG~', spin = -1, color = 8, mass = Param.ZERO, width = Param.ZERO, texname = 'ghG', antitexname = 'ghG~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghG__tilde__ = ghG.anti() ve = Particle(pdg_code = 12, name = 've', antiname = 've~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 've', antitexname = 've~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) ve__tilde__ = ve.anti() vm = Particle(pdg_code = 14, name = 'vm', antiname = 'vm~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'vm', antitexname = 'vm~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) vm__tilde__ = vm.anti() vt = Particle(pdg_code = 16, name = 'vt', antiname = 'vt~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'vt', antitexname = 'vt~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) vt__tilde__ = vt.anti() e__minus__ = Particle(pdg_code = 11, name = 'e-', antiname = 'e+', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'e-', antitexname = 'e+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) e__plus__ = e__minus__.anti() mu__minus__ = Particle(pdg_code = 13, name = 'mu-', antiname = 'mu+', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'mu-', antitexname = 'mu+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) mu__plus__ = mu__minus__.anti() ta__minus__ = Particle(pdg_code = 15, name = 'ta-', antiname = 'ta+', spin = 2, color = 1, mass = Param.MTA, width = Param.ZERO, texname = 'ta-', antitexname = 'ta+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) ta__plus__ = ta__minus__.anti() u = Particle(pdg_code = 2, name = 'u', antiname = 'u~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'u', antitexname = 'u~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) u__tilde__ = u.anti() c = Particle(pdg_code = 4, name = 'c', antiname = 'c~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'c', antitexname = 'c~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) c__tilde__ = c.anti() t = Particle(pdg_code = 6, name = 't', antiname = 't~', spin = 2, color = 3, mass = Param.MT, width = Param.WT, texname = 't', antitexname = 't~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) t__tilde__ = t.anti() d = Particle(pdg_code = 1, name = 'd', antiname = 'd~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'd', antitexname = 'd~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) d__tilde__ = d.anti() s = Particle(pdg_code = 3, name = 's', antiname = 's~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 's', antitexname = 's~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) s__tilde__ = s.anti() b = Particle(pdg_code = 5, name = 'b', antiname = 'b~', spin = 2, color = 3, mass = Param.MB, width = Param.ZERO, texname = 'b', antitexname = 'b~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) b__tilde__ = b.anti() H = Particle(pdg_code = 25, name = 'H', antiname = 'H', spin = 1, color = 1, mass = Param.MH, width = Param.WH, texname = 'H', antitexname = 'H', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) G0 = Particle(pdg_code = 250, name = 'G0', antiname = 'G0', spin = 1, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'G0', antitexname = 'G0', goldstone = True, charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) G__plus__ = Particle(pdg_code = 251, name = 'G+', antiname = 'G-', spin = 1, color = 1, mass = Param.MW, width = Param.WW, texname = 'G+', antitexname = 'G-', goldstone = True, charge = 1, GhostNumber = 0, LeptonNumber = 0, Y = 0) G__minus__ = G__plus__.anti() Xd = Particle(pdg_code = 52, name = 'Xd', antiname = 'Xd~', spin = 2, color = 1, mass = Param.MXd, width = Param.ZERO, texname = 'Xd', antitexname = 'Xd~', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) Xd__tilde__ = Xd.anti() Xm = Particle(pdg_code = 522, name = 'Xm', antiname = 'Xm', spin = 2, color = 1, mass = Param.MXm, width = Param.ZERO, texname = 'Xm', antitexname = 'Xm', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uL1 = Particle(pdg_code = 1000002, name = 'S3uL1', antiname = 'S3uL1~', spin = 1, color = 3, mass = Param.MS3uL1, width = Param.WS3uL1, texname = 'S3uL1', antitexname = 'S3uL1~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uL1__tilde__ = S3uL1.anti() S3uL2 = Particle(pdg_code = 1000004, name = 'S3uL2', antiname = 'S3uL2~', spin = 1, color = 3, mass = Param.MS3uL2, width = Param.WS3uL2, texname = 'S3uL2', antitexname = 'S3uL2~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uL2__tilde__ = S3uL2.anti() S3uL3 = Particle(pdg_code = 1000006, name = 'S3uL3', antiname = 'S3uL3~', spin = 1, color = 3, mass = Param.MS3uL3, width = Param.WS3uL3, texname = 'S3uL3', antitexname = 'S3uL3~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uL3__tilde__ = S3uL3.anti() S3dL1 = Particle(pdg_code = 1000001, name = 'S3dL1', antiname = 'S3dL1~', spin = 1, color = 3, mass = Param.MS3dL1, width = Param.WS3dL1, texname = 'S3dL1', antitexname = 'S3dL1~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3dL1__tilde__ = S3dL1.anti() S3dL2 = Particle(pdg_code = 1000003, name = 'S3dL2', antiname = 'S3dL2~', spin = 1, color = 3, mass = Param.MS3dL2, width = Param.WS3dL2, texname = 'S3dL2', antitexname = 'S3dL2~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3dL2__tilde__ = S3dL2.anti() S3dL3 = Particle(pdg_code = 1000005, name = 'S3dL3', antiname = 'S3dL3~', spin = 1, color = 3, mass = Param.MS3dL3, width = Param.WS3dL3, texname = 'S3dL3', antitexname = 'S3dL3~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3dL3__tilde__ = S3dL3.anti() S3uR1 = Particle(pdg_code = 2000002, name = 'S3uR1', antiname = 'S3uR1~', spin = 1, color = 3, mass = Param.MS3uR1, width = Param.WS3uR1, texname = 'S3uR1', antitexname = 'S3uR1~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uR1__tilde__ = S3uR1.anti() S3uR2 = Particle(pdg_code = 2000004, name = 'S3uR2', antiname = 'S3uR2~', spin = 1, color = 3, mass = Param.MS3uR2, width = Param.WS3uR2, texname = 'S3uR2', antitexname = 'S3uR2~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uR2__tilde__ = S3uR2.anti() S3uR3 = Particle(pdg_code = 2000006, name = 'S3uR3', antiname = 'S3uR3~', spin = 1, color = 3, mass = Param.MS3uR3, width = Param.WS3uR3, texname = 'S3uR3', antitexname = 'S3uR3~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3uR3__tilde__ = S3uR3.anti() S3dR1 = Particle(pdg_code = 2000001, name = 'S3dR1', antiname = 'S3dR1~', spin = 1, color = 3, mass = Param.MS3dR1, width = Param.WS3dR1, texname = 'S3dR1', antitexname = 'S3dR1~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3dR1__tilde__ = S3dR1.anti() S3dR2 = Particle(pdg_code = 2000003, name = 'S3dR2', antiname = 'S3dR2~', spin = 1, color = 3, mass = Param.MS3dR2, width = Param.WS3dR2, texname = 'S3dR2', antitexname = 'S3dR2~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3dR2__tilde__ = S3dR2.anti() S3dR3 = Particle(pdg_code = 2000005, name = 'S3dR3', antiname = 'S3dR3~', spin = 1, color = 3, mass = Param.MS3dR3, width = Param.WS3dR3, texname = 'S3dR3', antitexname = 'S3dR3~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) S3dR3__tilde__ = S3dR3.anti() <file_sep>/DMsimp_t/DMsimp_t_v3_LO/particles.py # This file was automatically created by FeynRules 2.3.29 # Mathematica version: 11.2.0 for Mac OS X x86 (64-bit) (September 11, 2017) # Date: Tue 12 Mar 2019 11:14:42 from __future__ import division from object_library import all_particles, Particle import parameters as Param import propagators as Prop a = Particle(pdg_code = 22, name = 'a', antiname = 'a', spin = 3, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'a', antitexname = 'a', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) Z = Particle(pdg_code = 23, name = 'Z', antiname = 'Z', spin = 3, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'Z', antitexname = 'Z', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) W__plus__ = Particle(pdg_code = 24, name = 'W+', antiname = 'W-', spin = 3, color = 1, mass = Param.MW, width = Param.WW, texname = 'W+', antitexname = 'W-', charge = 1, GhostNumber = 0, LeptonNumber = 0, Y = 0) W__minus__ = W__plus__.anti() g = Particle(pdg_code = 21, name = 'g', antiname = 'g', spin = 3, color = 8, mass = Param.ZERO, width = Param.ZERO, texname = 'g', antitexname = 'g', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) ghA = Particle(pdg_code = 9000001, name = 'ghA', antiname = 'ghA~', spin = -1, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'ghA', antitexname = 'ghA~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghA__tilde__ = ghA.anti() ghZ = Particle(pdg_code = 9000002, name = 'ghZ', antiname = 'ghZ~', spin = -1, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'ghZ', antitexname = 'ghZ~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghZ__tilde__ = ghZ.anti() ghWp = Particle(pdg_code = 9000003, name = 'ghWp', antiname = 'ghWp~', spin = -1, color = 1, mass = Param.MW, width = Param.WW, texname = 'ghWp', antitexname = 'ghWp~', charge = 1, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghWp__tilde__ = ghWp.anti() ghWm = Particle(pdg_code = 9000004, name = 'ghWm', antiname = 'ghWm~', spin = -1, color = 1, mass = Param.MW, width = Param.WW, texname = 'ghWm', antitexname = 'ghWm~', charge = -1, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghWm__tilde__ = ghWm.anti() ghG = Particle(pdg_code = 82, name = 'ghG', antiname = 'ghG~', spin = -1, color = 8, mass = Param.ZERO, width = Param.ZERO, texname = 'ghG', antitexname = 'ghG~', charge = 0, GhostNumber = 1, LeptonNumber = 0, Y = 0) ghG__tilde__ = ghG.anti() ve = Particle(pdg_code = 12, name = 've', antiname = 've~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 've', antitexname = 've~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) ve__tilde__ = ve.anti() vm = Particle(pdg_code = 14, name = 'vm', antiname = 'vm~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'vm', antitexname = 'vm~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) vm__tilde__ = vm.anti() vt = Particle(pdg_code = 16, name = 'vt', antiname = 'vt~', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'vt', antitexname = 'vt~', charge = 0, GhostNumber = 0, LeptonNumber = 1, Y = 0) vt__tilde__ = vt.anti() e__minus__ = Particle(pdg_code = 11, name = 'e-', antiname = 'e+', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'e-', antitexname = 'e+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) e__plus__ = e__minus__.anti() mu__minus__ = Particle(pdg_code = 13, name = 'mu-', antiname = 'mu+', spin = 2, color = 1, mass = Param.ZERO, width = Param.ZERO, texname = 'mu-', antitexname = 'mu+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) mu__plus__ = mu__minus__.anti() ta__minus__ = Particle(pdg_code = 15, name = 'ta-', antiname = 'ta+', spin = 2, color = 1, mass = Param.MTA, width = Param.ZERO, texname = 'ta-', antitexname = 'ta+', charge = -1, GhostNumber = 0, LeptonNumber = 1, Y = 0) ta__plus__ = ta__minus__.anti() u = Particle(pdg_code = 2, name = 'u', antiname = 'u~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'u', antitexname = 'u~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) u__tilde__ = u.anti() c = Particle(pdg_code = 4, name = 'c', antiname = 'c~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'c', antitexname = 'c~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) c__tilde__ = c.anti() t = Particle(pdg_code = 6, name = 't', antiname = 't~', spin = 2, color = 3, mass = Param.MT, width = Param.WT, texname = 't', antitexname = 't~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) t__tilde__ = t.anti() d = Particle(pdg_code = 1, name = 'd', antiname = 'd~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 'd', antitexname = 'd~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) d__tilde__ = d.anti() s = Particle(pdg_code = 3, name = 's', antiname = 's~', spin = 2, color = 3, mass = Param.ZERO, width = Param.ZERO, texname = 's', antitexname = 's~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) s__tilde__ = s.anti() b = Particle(pdg_code = 5, name = 'b', antiname = 'b~', spin = 2, color = 3, mass = Param.MB, width = Param.ZERO, texname = 'b', antitexname = 'b~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) b__tilde__ = b.anti() H = Particle(pdg_code = 25, name = 'H', antiname = 'H', spin = 1, color = 1, mass = Param.MH, width = Param.WH, texname = 'H', antitexname = 'H', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) G0 = Particle(pdg_code = 250, name = 'G0', antiname = 'G0', spin = 1, color = 1, mass = Param.MZ, width = Param.WZ, texname = 'G0', antitexname = 'G0', goldstone = True, charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) G__plus__ = Particle(pdg_code = 251, name = 'G+', antiname = 'G-', spin = 1, color = 1, mass = Param.MW, width = Param.WW, texname = 'G+', antitexname = 'G-', goldstone = True, charge = 1, GhostNumber = 0, LeptonNumber = 0, Y = 0) G__minus__ = G__plus__.anti() Xd = Particle(pdg_code = 52, name = 'Xd', antiname = 'Xd~', spin = 2, color = 1, mass = Param.MXd, width = Param.ZERO, texname = 'Xd', antitexname = 'Xd~', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) Xd__tilde__ = Xd.anti() Xm = Particle(pdg_code = 522, name = 'Xm', antiname = 'Xm', spin = 2, color = 1, mass = Param.MXm, width = Param.ZERO, texname = 'Xm', antitexname = 'Xm', charge = 0, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uL1 = Particle(pdg_code = 3000002, name = 'V3uL1', antiname = 'V3uL1~', spin = 3, color = 3, mass = Param.MV3uL1, width = Param.WV3uL1, texname = 'V3uL1', antitexname = 'V3uL1~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uL1__tilde__ = V3uL1.anti() V3uL2 = Particle(pdg_code = 3000004, name = 'V3uL2', antiname = 'V3uL2~', spin = 3, color = 3, mass = Param.MV3uL2, width = Param.WV3uL2, texname = 'V3uL2', antitexname = 'V3uL2~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uL2__tilde__ = V3uL2.anti() V3uL3 = Particle(pdg_code = 3000006, name = 'V3uL3', antiname = 'V3uL3~', spin = 3, color = 3, mass = Param.MV3uL3, width = Param.WV3uL3, texname = 'V3uL3', antitexname = 'V3uL3~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uL3__tilde__ = V3uL3.anti() V3dL1 = Particle(pdg_code = 3000001, name = 'V3dL1', antiname = 'V3dL1~', spin = 3, color = 3, mass = Param.MV3dL1, width = Param.WV3dL1, texname = 'V3dL1', antitexname = 'V3dL1~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3dL1__tilde__ = V3dL1.anti() V3dL2 = Particle(pdg_code = 3000003, name = 'V3dL2', antiname = 'V3dL2~', spin = 3, color = 3, mass = Param.MV3dL2, width = Param.WV3dL2, texname = 'V3dL2', antitexname = 'V3dL2~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3dL2__tilde__ = V3dL2.anti() V3dL3 = Particle(pdg_code = 3000005, name = 'V3dL3', antiname = 'V3dL3~', spin = 3, color = 3, mass = Param.MV3dL3, width = Param.WV3dL3, texname = 'V3dL3', antitexname = 'V3dL3~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3dL3__tilde__ = V3dL3.anti() V3uR1 = Particle(pdg_code = 4000002, name = 'V3uR1', antiname = 'V3uR1~', spin = 3, color = 3, mass = Param.MV3uR1, width = Param.WV3uR1, texname = 'V3uR1', antitexname = 'V3uR1~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uR1__tilde__ = V3uR1.anti() V3uR2 = Particle(pdg_code = 4000004, name = 'V3uR2', antiname = 'V3uR2~', spin = 3, color = 3, mass = Param.MV3uR2, width = Param.WV3uR2, texname = 'V3uR2', antitexname = 'V3uR2~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uR2__tilde__ = V3uR2.anti() V3uR3 = Particle(pdg_code = 4000006, name = 'V3uR3', antiname = 'V3uR3~', spin = 3, color = 3, mass = Param.MV3uR3, width = Param.WV3uR3, texname = 'V3uR3', antitexname = 'V3uR3~', charge = 2/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3uR3__tilde__ = V3uR3.anti() V3dR1 = Particle(pdg_code = 4000001, name = 'V3dR1', antiname = 'V3dR1~', spin = 3, color = 3, mass = Param.MV3dR1, width = Param.WV3dR1, texname = 'V3dR1', antitexname = 'V3dR1~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3dR1__tilde__ = V3dR1.anti() V3dR2 = Particle(pdg_code = 4000003, name = 'V3dR2', antiname = 'V3dR2~', spin = 3, color = 3, mass = Param.MV3dR2, width = Param.WV3dR2, texname = 'V3dR2', antitexname = 'V3dR2~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3dR2__tilde__ = V3dR2.anti() V3dR3 = Particle(pdg_code = 4000005, name = 'V3dR3', antiname = 'V3dR3~', spin = 3, color = 3, mass = Param.MV3dR3, width = Param.WV3dR3, texname = 'V3dR3', antitexname = 'V3dR3~', charge = -1/3, GhostNumber = 0, LeptonNumber = 0, Y = 0) V3dR3__tilde__ = V3dR3.anti()
c8ff93320787dadcde159556464133c8829c0137
[ "Python" ]
7
Python
LucaMantani/UFO_models
cd43c88afc32a85ebd1eaa82942079d2a5a9564b
13c1216b663ad437847407699a32f9af6e0463ae
refs/heads/main
<repo_name>Darkvod/JAVA-Multithread-Echo-Client-Server<file_sep>/Procesory.java /** * Klasa Procesory - Klasa przechowująca dane dotyczące Procesorów CPU i GPU. * @author <NAME>, <NAME> */ public class Procesory extends Podzespoly_Komputerowe { /** Zmienna która będzie przechowywać czestotliwość zegara procesra */ private double czestotliwosc_zegara; /** * Konstruktor domyślny klasy Procesory * @throws DataException Wyjątki obsługuje klasa DataException */ public Procesory() throws DataException {} /** * Konstruktor klasy Procesory * @param s_data string wczytany z pliku, wyciągamy z niego konkretne pola klasy * @throws DataException Wyjatki obsluguje klasa DataException */ public Procesory(String s_data) throws DataException { super(s_data); String[] st = s_data.split(","); if (st.length == 6) { this.czestotliwosc_zegara = Integer.parseInt(st[4]); } } /** * Konstruktor klasy Procesory * @param cn Parametr ustawiający wartość ceny * @param dataprodukcji Parametr ustawiający wartość dataprodukcji * @param gwarancja Parametr ustawiający wartość gwarancja * @param czestotliwosc_zegara Parametr ustawiający wartość pola czestotliwosc_zegara * @throws DataException Wyjatki obsluguje klasa DataException */ public Procesory (double cn, String dataprodukcji, int gwarancja, double czestotliwosc_zegara) throws DataException { super(cn,dataprodukcji,gwarancja); this.czestotliwosc_zegara=czestotliwosc_zegara; } /** * Funkcja toString * @return Funkcja zwaraca String sformatowany w linijce return */ public String toString(){ return super.toString() + "Czestotliwość zegara procesora: "+this.czestotliwosc_zegara + "Ghz "; } /** * Funkcja getCzestotliwosc_zegara zwraca wartośc pola czestotliwość_zegara * @return Funkcja zwraca wartość pola czestotliwość_zegara */ public double getCzestotliwosc_zegara(){return this.czestotliwosc_zegara;} /** * Funkcja setCzestotliwosc_zegara ustawia wartość pola czestotliwosc_zegara * @param czest Przekazany argument ustawia wartość pola czestotliwosc_zegara */ public void setCzestotliwosc_zegara(int czest){this.czestotliwosc_zegara=czestotliwosc_zegara;} } <file_sep>/Procesory_Graficzne.java /** * Klasa Procesory_Graficzne - Klasa przechowująca dane dotyczące Procesorów GPU. * @author <NAME>, <NAME> */ public class Procesory_Graficzne extends Procesory { /** Zmienna która będzie przechowywać ilość rdzeni CUDA */ private int rdzenie_CUDA; /** * Konstruktor domyślny klasy Procesory_Graficzne * @throws DataException Wyjątki obsługuje klasa DataException */ public Procesory_Graficzne () throws DataException { } /** * Konstruktor klasy Procesory_Graficzne * @param s_data string wczytany z pliku, wyciągamy z niego konkretne pola klasy * @throws DataException Wyjatki obsluguje klasa DataException */ public Procesory_Graficzne(String s_data) throws DataException { super(s_data); String[] st = s_data.split(","); if (st.length == 6) { this.rdzenie_CUDA = Integer.parseInt(st[5]); } } /** * Konstruktor klasy Procesory_Graficzne * @param cn Parametr ustawiający wartość ceny * @param dataprodukcji Parametr ustawiający wartość dataprodukcji * @param gwarancja Parametr ustawiający wartość gwarancja * @param czestotliwosc_zegara Parametr ustawiający wartość pola czestotliwosc_zegara * @param model Parametr określający model * @param rdzenie_CUDA Parametr określający ilość rdzeni * @throws DataException Wyjatki obsluguje klasa DataException */ public Procesory_Graficzne(double cn, String dataprodukcji, int gwarancja, double czestotliwosc_zegara,String model, int rdzenie_CUDA) throws DataException{ super(cn,dataprodukcji,gwarancja,czestotliwosc_zegara); this.rdzenie_CUDA=rdzenie_CUDA; } /** * Funkcja toString * @return Funkcja zwaraca String sformatowany w linijce return */ public String toString() { return super.toString() + " Ilość rdzeni CUDA procesora graficznego: " + this.rdzenie_CUDA; } /** * Funkcja getrdzenie_CUDA zwraca wartośc pola rdzenie_CUDA * @return Funkcja zwraca wartość pola rdzenie_CUDA */ public int getrdzenie_CUDA(){return this.rdzenie_CUDA;} /** * Funkcja setrdzenie_CUDA ustawia wartość pola rdzenie_CUDA * @param cuda Przekazany argument ustawia wartość pola rdzenie_CUDA */ public void setrdzenie_CUDA(int cuda){this.rdzenie_CUDA=rdzenie_CUDA;} } <file_sep>/README.md # JAVA-Simple-Echo-Client-Server # Simple Multithread Java echo client-server with additional classes which creates objects by using data from file dane.txt # Comments and javadoc in polish. <file_sep>/ESerwer.java import java.io.*; import java.net.*; import java.util.*; import java.lang.*; /** * Klasa ESerwer - Serwer wielowątkowy obsługujący zapytania klienta, odpowiedzi wczytywane są z magazynu danych. * @author <NAME>, <NAME> */ public class ESerwer{ /** Zmienna PORT przechowująca wartość która reprezentuje port na którym będzie działać serwer */ public static final int PORT=7; public static void main(String[] args){ ServerSocket gniazdoSerwera = null; try{ InetAddress addr = InetAddress.getByName("localhost"); gniazdoSerwera = new ServerSocket(PORT,50,addr); gniazdoSerwera.setReuseAddress(true); System.out.println("\u001B[32m" + "Uruchomiono serwer: " + gniazdoSerwera); while(true){ Socket gniazdo = gniazdoSerwera.accept(); System.out.println( "\u001B[31m" + "Nowy klient polaczony:" + gniazdo.getInetAddress().getHostAddress()); ClientHandler clientSock = new ClientHandler(gniazdo); new Thread(clientSock).start(); } } catch(IOException e){e.printStackTrace(); } finally{ if(gniazdoSerwera != null){ try { gniazdoSerwera.close(); }catch (IOException e){e.printStackTrace();} } } } /** * Klasa ClientHandler - Klasa obsługująca każdego klienta który połączy się z serwerem. * @author <NAME>, <NAME> */ private static class ClientHandler implements Runnable { /** Zmienna która będzie Socketem serwera */ private final Socket clientsocket; /** * Konstruktor klasy ClientHandler * @param socket przekazywany jest socket który będzie używany do połączenia */ public ClientHandler(Socket socket){ this.clientsocket=socket; } /** * Funkcja run będzie uruchamiała się za każdym razem gdy połączy się nowy klient */ @Override public void run(){ LinkedList<Procesor_CPU> cpu = new LinkedList<Procesor_CPU>(); LinkedList<Procesory_Graficzne> gpu = new LinkedList<Procesory_Graficzne>(); LinkedList<Pamiec_Operacyjna> ram = new LinkedList<Pamiec_Operacyjna>(); LinkedList<Dyski_Twarde> dysk = new LinkedList<Dyski_Twarde>(); LinkedList<Dyski_Twarde> ssd = new LinkedList<Dyski_Twarde>(); try { String s; BufferedReader plik = new BufferedReader(new FileReader("dane.txt")); while ((s = plik.readLine()) != null) { switch (s.charAt(0)) { case 'P': s = s.substring(2); cpu.add(new Procesor_CPU(s)); break; case 'G': s = s.substring(2); gpu.add(new Procesory_Graficzne(s)); break; case 'R': s = s.substring(2); ram.add(new Pamiec_Operacyjna(s)); break; case 'H': s = s.substring(2); dysk.add(new Dyski_Twarde(s)); break; case 'S': s = s.substring(2); ssd.add(new Dyski_Twarde(s)); break; default: break; } } plik.close(); } catch(Exception e){} cpu.sort(Comparator.comparing(Procesor_CPU::getCena)); gpu.sort(Comparator.comparing(Procesory_Graficzne::getCena)); ram.sort(Comparator.comparing(Pamiec_Operacyjna::getCena)); dysk.sort(Comparator.comparing(Dyski_Twarde::getCena)); ssd.sort(Comparator.comparing(Dyski_Twarde::getCena)); PrintWriter net_out=null; BufferedReader net_in = null; try{ net_out = new PrintWriter(clientsocket.getOutputStream(),true); net_in = new BufferedReader(new InputStreamReader(clientsocket.getInputStream())); while(true){ String dane_we = net_in.readLine(); if (dane_we.equals("END")) break; switch(dane_we.charAt(0)) { case 'p': case 'P': net_out.println(cpu.get(0) + "*" + cpu.get(1) + "*" + cpu.get(2)); break; case 'g': case 'G': net_out.println(gpu.get(0) + "*" + gpu.get(1) + "*" + gpu.get(2)); break; case 'r': case 'R': net_out.println(ram.get(0) + "*" + ram.get(1)); break; case 'h': case 'H': net_out.println(dysk.get(0)); break; case 's': case 'S': net_out.println(ssd.get(0)); break; default: net_out.println("Zla literka "); break; } System.out.println("\u001B[37m"+"Sent from client: " + dane_we); } } catch(IOException e){e.printStackTrace(); } finally { try { if (net_in !=null) net_in.close(); if (net_out !=null) net_out.close(); } catch (IOException e){e.printStackTrace(); } } } } }<file_sep>/Dyski_Twarde.java /** * Klasa Dyski_Twarde - Klasa przechowująca dane dotyczące dysków twardych. * @author <NAME>, <NAME> */ public class Dyski_Twarde extends Pamiec{ /** Zmienna która będzie przechowywać rodzaj_dysku */ private String rodzaj_dysku; /** Zmienna która będzie przechowywać predkosc_odczytu */ private int predkosc_odczytu; /** Zmienna która będzie przechowywać predkosc_zapisu */ private int predkosc_zapisu; /** * Konstruktor domyślny klasy Dyski_Twarde * @throws DataException Wyjątki obsługuje klasa DataException */ public Dyski_Twarde() throws DataException {} /** * Konstruktor klasy Dyski_Twarde * @param s_data string wczytany z pliku, wyciągamy z niego konkretne pola klasy * @throws DataException Wyjatki obsluguje klasa DataException */ public Dyski_Twarde(String s_data) throws DataException { super(s_data); String[] st = s_data.split(","); if (st.length <= 8) { this.rodzaj_dysku = st[5]; this.predkosc_odczytu = Integer.parseInt(st[6]); this.predkosc_zapisu = Integer.parseInt(st[7]); } } /** * Konstruktor klasy Dyski_Twarde * @param cn Parametr ustawiający wartość ceny * @param dataprodukcji Parametr ustawiający wartość dataprodukcji * @param gwarancja Parametr ustawiający wartość gwarancja * @param rodzaj_pamieci Parametr ustawiający wartość pola rodzaj_pamięci * @param rodzaj_dysku Parametr ustawiający wartość pola rodzaj_dysku * @param predkosc_odczytu Parametr ustawiający wartość pola predkosc_odczytu * @param predkosc_zapisu Parametr ustawiający wartość pola predkosc_zapisu * @throws DataException Wyjatki obsluguje klasa DataException */ public Dyski_Twarde(double cn, String dataprodukcji, int gwarancja, int rodzaj_pamieci,String rodzaj_dysku,int predkosc_odczytu,int predkosc_zapisu) throws DataException { super(cn,dataprodukcji,gwarancja,rodzaj_pamieci); this.rodzaj_dysku=rodzaj_dysku; this.predkosc_odczytu=predkosc_odczytu; this.predkosc_zapisu=predkosc_zapisu; } /** * Funkcja toString * @return Funkcja zwaraca String sformatowany w linijce return */ public String toString() { return super.toString() + " Rodzaj dysku: " + this.rodzaj_dysku + " Predkość zapisu: " + this.predkosc_zapisu + "mb/s Prędkość odczytu: " + this.predkosc_odczytu +"mb/s" ; } /** * Funkcja getrodzaj_dysku zwraca wartośc pola rodzaj_dysku * @return Funkcja zwraca wartość rodzaj_dysku */ public String getrodzaj_dysku(){return this.rodzaj_dysku;} /** * Funkcja getrodzaj_dysku zwraca wartośc pola predkosc_odczytu * @return Funkcja zwraca wartość predkosc_odczytu */ public int getpredkosc_odczytu(){return this.predkosc_odczytu;} /** * Funkcja setrodzaj_dysku zwraca wartośc pola rodzaj dysku * @param rodzaj przekazany String określa rodzaj dysku */ public void setrodzaj_dysku(String rodzaj){this.rodzaj_dysku=rodzaj_dysku;} /** * Funkcja setpredkosc_odczytu ustawia wartość pola predkosc_odczytu * @param pre Przekazana wartość określa prędkość odczytu komponentu */ public void setpredkosc_odczytu(int pre){this.predkosc_odczytu=predkosc_odczytu;} /** * Funkcja getpredkosc_zapisu ustawia wartość pola predkosc_zapisu * @return Funkcja zwraca wartość predkosc_zapisu */ public int getpredkosc_zapisu(){return this.predkosc_zapisu;} /** * Funkcja setpredkosc_zapisu ustawia wartość pola predkosc_zapisu * @param zap Przekazana wartość określa prędkość zapisu komponentu */ public void setpredkosc_zapisu(int zap){this.predkosc_zapisu=predkosc_zapisu;} } <file_sep>/Pamiec_Operacyjna.java /** * Klasa Pamiec_Operacyjna - Klasa przechowująca dane dotyczące Pamięci RAM. * @author <NAME>, <NAME> */ public class Pamiec_Operacyjna extends Pamiec{ /** Zmienna która będzie przechowywać wersję dram */ private String wersja_dram; /** Zmienna która będzie przechowywać czestotliwosc_pamieci */ private int czestotliwosc_pamieci; /** * Konstruktor domyślny klasy Pamiec_Operacyjna * @throws DataException Wyjątki obsługuje klasa DataException */ public Pamiec_Operacyjna() throws DataException {} /** * Konstruktor klasy Pamiec * @param s_data string wczytany z pliku, wyciągamy z niego konkretne pola klasy * @throws DataException Wyjatki obsluguje klasa DataException */ public Pamiec_Operacyjna(String s_data) throws DataException { super(s_data); String[] st = s_data.split(","); if (st.length <= 8) { this.wersja_dram = st[5]; this.czestotliwosc_pamieci = Integer.parseInt(st[6]); } } /** * * @param cn Parametr ustawiający wartość ceny * @param dataprodukcji Parametr ustawiający wartość dataprodukcji * @param gwarancja Parametr ustawiający wartość gwarancja * @param rodzaj_pamieci Parametr ustawiający wartość pola rodzaj_pamięci * @param wersja_dram Parametr ustawiający wartość pola wersja_dram * @param czestotliwosc_pamieci Parametr ustawiający wartość pola czestotliwosc_pamieci * @throws DataException Wyjatki obsluguje klasa DataException */ public Pamiec_Operacyjna(double cn, String dataprodukcji, int gwarancja, int rodzaj_pamieci, String wersja_dram, int czestotliwosc_pamieci) throws DataException { super(cn,dataprodukcji,gwarancja,rodzaj_pamieci); this.wersja_dram=wersja_dram; this.czestotliwosc_pamieci=czestotliwosc_pamieci; } /** * Funkcja toString * @return Funkcja zwaraca String sformatowany w linijce return */ public String toString() { return super.toString() + "Typ Pamięci RAM: " + this.wersja_dram + " Częstotliwość pamięci RAM: " + this.czestotliwosc_pamieci; } /** * Funkcja getwersja_dram zwraca wartośc pola wersja_dram * @return Funkcja zwraca wartość pola wersja_dram */ public String getwersja_dram(){return this.wersja_dram;} /** * Funkcja getczestotliwosc_pamieci zwraca wartośc pola czestotliwosc_pamieci * @return Funkcja zwraca wartość pola czestotliwosc_pamieci */ public int getczestotliwosc_pamieci(){return this.czestotliwosc_pamieci;} /** * Funkcja setwersja_dram ustawia wartość pola wersja_dram * @param ss Przekazana wartość określa wersję pamięci RAM */ public void setwersja_dram(String ss){this.wersja_dram=wersja_dram;} /** * Funkcja setczestotliwosc_pamieci ustawia wartość pola czestotliwosc_pamieci * @param pm Przekazana wartość określa czestotliwosc pamieci */ public void setczestotliwosc_pamieci(int pm){this.czestotliwosc_pamieci=czestotliwosc_pamieci;} }
156bd44bcdabd18dcfaa72dc4ae305bafd517456
[ "Markdown", "Java" ]
6
Java
Darkvod/JAVA-Multithread-Echo-Client-Server
a93a9731582d83c506d3fb2d6898bb51bff35168
8e549d5683160f26da36fc4add1f7125bf71ac57
refs/heads/master
<file_sep># cppSimpleWindow A basic window application in C++ <file_sep>#include <windows.h> //Store the name of the window class const char className[] = "windowClass"; //The Window Procedure //This is where the messages are received from the message loop LRESULT CALLBACK WndProc(HWND windowHandler, UINT msg, WPARAM wParam, LPARAM lParam) { switch(msg) { case WM_CLOSE: //In the event that its the close button (or presses Alt+f4), destroy the window DestroyWindow(windowHandler); //The destroy message is sent to the message loop and brought back to the switch statement break; case WM_DESTROY: PostQuitMessage(0); //Sends WM_Quit (0) to message loop break; default: return DefWindowProc(windowHandler, msg, wParam, lParam); } return 0; } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { WNDCLASSEX windowClass; HWND windowHandler; MSG Msg; //Registering the Window Class windowClass.cbSize = sizeof(WNDCLASSEX); //The size of the structure. windowClass.style = 0; //Class Styles (CS_*), not to be confused with Window Styles (WS_*) This can usually be set to 0. windowClass.lpfnWndProc = WndProc; //Pointer to the window procedure for this window class. windowClass.cbClsExtra = 0; //Amount of extra data allocated for this class in memory. Usually 0. windowClass.cbWndExtra = 0; //Amount of extra data allocated in memory per window of this type. Usually 0. windowClass.hInstance = hInstance; //Handle to application instance (that we got in the first parameter of WinMain()). windowClass.hIcon = LoadIcon(NULL, IDI_APPLICATION); //Large (usually 32x32) icon shown when the user presses Alt+Tab. windowClass.hCursor = LoadCursor(NULL, IDC_ARROW); //Cursor that will be displayed over our window. windowClass.hbrBackground = (HBRUSH)(COLOR_WINDOW+1); //Background Brush to set the color of our window. windowClass.lpszMenuName = NULL; //Name of a menu resource to use for the windows with this class. windowClass.lpszClassName = className; //Name to identify the class with. windowClass.hIconSm = LoadIcon(NULL, IDI_APPLICATION); //Small (usually 16x16) icon to show in the taskbar and in the top left corner of the window. //Check return values for error if(!RegisterClassEx(&windowClass)) { MessageBox(NULL, "Window Registration Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } //Creating the Window windowHandler = CreateWindowEx( WS_EX_CLIENTEDGE, //Dictates the extended window style, this is going to have a sunken border. see: https://docs.microsoft.com/en-us/windows/desktop/winmsg/extended-window-styles className, //The class name stored earlier "A simple window program", //The title of the window WS_OVERLAPPEDWINDOW, //Dictates the window style. See: https://docs.microsoft.com/en-us/windows/desktop/winmsg/window-styles CW_USEDEFAULT, CW_USEDEFAULT, 240, 120, //The starting coordinates of the top left, and the width and height of the window NULL, NULL, hInstance, NULL); //Parent Window, Menu Handle, application instance, and window creation data //Check return values for error if(windowHandler == NULL) { MessageBox(NULL, "Window Creation Failed!", "Error!", MB_ICONEXCLAMATION | MB_OK); return 0; } //Show and update the window ShowWindow(windowHandler, nCmdShow); UpdateWindow(windowHandler); //The Message Loop while(GetMessage(&Msg, NULL, 0, 0) > 0) //Any activity from the user is a message that the window received in the GetMessage queue { TranslateMessage(&Msg); //Processes the message DispatchMessage(&Msg); //Sends the message to the window that the activity was in } return Msg.wParam; }
0e8170bdb1ea6cc05ec9740f720f66c61867bc03
[ "Markdown", "C++" ]
2
Markdown
Code-Diamond/cppSimpleWindow
db697090773a7c715eddc2575e428f8ad67dfb94
41d03f39a72a217bc4294ed88a9c20c1e946d0e7
refs/heads/main
<file_sep>kubectl get nodes curl -O https://raw.githubusercontent.com/Azure-Samples/azure-voting-app-redis/master/azure-vote-all-in-one-redis.yaml kubectl create -f azure-vote-all-in-one-redis.yaml kubectl get pods kubectl get svc<file_sep># Parcial 2 Iniciar el cluster ``` az aks start --name parcial2 --resource-group computacion ``` Parar el cluster ``` az aks stop --name parcial2 --resource-group computacion ``` * [Comandos punto 1](https://github.com/groloboy/parcial2/blob/main/comands_vagrant.sh) * [Comandos punto 2](https://github.com/groloboy/parcial2/blob/main/punto2/comands.sh) * [Comandos punto 3](https://github.com/groloboy/parcial2/blob/main/punto3/comands.sh) * [Comandos punto extra](https://github.com/groloboy/parcial2/blob/main/extra/comands.sh) <file_sep>https://kubernetes.io/docs/tasks/run-application/horizontal-pod-autoscale-walkthrough/ kubectl apply -f php-apache.yaml kubectl autoscale deployment php-apache --cpu-percent=50 --min=1 --max=10 kubectl get hpa kubectl run -i --tty load-generator --rm --image=busybox --restart=Never -- /bin/sh -c "while sleep 0.01; do wget -q -O- http://php-apache; done" kubectl get hpa kubectl get deployment php-apache<file_sep>kubectl apply -f redis-master-deployment.yaml kubectl get pods #Revisar el nombre del pod creado kubectl logs -f POD-NAME kubectl apply -f redis-master-service.yaml kubectl get service kubectl apply -f redis-slave-deployment.yaml kubectl get pods kubectl apply -f redis-slave-service.yaml kubectl get services kubectl apply -f frontend-deployment.yaml kubectl get pods -l app=guestbook -l tier=frontend kubectl apply -f frontend-service.yaml kubectl get services kubectl scale deployment frontend --replicas=5 kubectl get pods kubectl scale deployment frontend --replicas=2 kubectl get pods #Cleaning up kubectl delete deployment -l app=redis kubectl delete service -l app=redis kubectl delete deployment -l app=guestbook kubectl delete service -l app=guestbook #no muestra nada kubectl get pods # para crear todo con un solo archivo kubectl apply -f guestbook-all-in-one.yaml <file_sep>sudo apt-get install curl apt-transport-https lsb-release gnupg -y curl -sL https://packages.microsoft.com/keys/microsoft.asc | gpg --dearmor | sudo tee /etc/apt/trusted.gpg.d/microsoft.asc.gpg > /dev/null AZ_REPO=$(lsb_release -cs) echo "deb [arch=amd64] https://packages.microsoft.com/repos/azure-cli/ $AZ_REPO main" | sudo tee /etc/apt/sources.list.d/azure-cli.list sudo apt-get install azure-cli az login sudo az aks install-cli
1d8e36867e54f803dca71ed41fb907da9da55ce7
[ "Markdown", "Shell" ]
5
Shell
groloboy/parcial2
3fe5bc2e1e58aea6ab2420ba112a8a873306517c
840750af51a8cc63eb0b443bebf3339a4217922c
refs/heads/master
<repo_name>Emilana/group_project<file_sep>/index.html <!doctype html> <html> <head> <script async src="https://www.googletagmanager.com/gtag/js?id=UA-136071988-1"></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'UA-136071988-1'); </script> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="<KEY>" crossorigin="anonymous"> <link href="css/styles.css" rel="stylesheet"> <link href="js/scripts.js" rel="javascript"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> <title>Brummie</title> </head> <body> <!--navigation bar--> <nav class="navbar navbar-expand-lg navbar-light fixed-top bg-light" style="background-color:black;"> <a class="navbar-brand" <a class="navbar-brand js-scroll-trigger" href="index.html"><img src="https://image.flaticon.com/icons/svg/36/36474.svg" height="42" width="42"> Brummie. </a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarNavAltMarkup" aria-controls="navbarNavAltMarkup" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNavAltMarkup"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link js-scroll-trigger active" href="#">Home <span class="sr-only">(current)</span></a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#second">Why Birmingham</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#third">Top Picks</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="map.html">Map</a> </li> <li class="nav-item"> <a class="nav-link js-scroll-trigger" href="#fourth">Contact Us</a> </li> </ul> </div> </div> </nav> <!-- end of navigation bar--> <!--section 1--> <section class="jumbotron" id="main"> <div class="container"> <h1 id="main-title">Do you want to be a Brummie?</h1> <div class="buttons"> <a href="map.html"><button id="yes-button" class="btn btn-primary" href="map.html"><strong>YES</strong></button></a> <button id="no-button" class="btn btn-secondary" data-toggle="modal" data-target=#errormessage><strong>NO</strong></button> </div> <!-- Modal --> <div class="modal fade" id="errormessage" tabindex="-1" role="dialog" aria-labelledby="errormessagelabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="errormessagelabel">Error</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p id="errorparagraph">I think you clicked on the wrong button... Did you mean <strong>YES</strong> by any chance?</p> </div> <div class="modal-footer"> <button id="closebutton" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> </section> <!--end of section 1--> <!--section 2 Why Birmingham--> <section class="whybirmingham" id="second"> <div class="container"> <h1>Why "Birmingham?"</h1> <p id="information"> Birmingham is just one of those places, where you don't think to visit "randomly". I have always said Birmingham is a construction site full of rocks, but if you look carefully you will be able to find diamonds. Our main goal is to convince you to visit Birmingham, and venture into our ends to find the inner brummie within you all. Here you can see the top picks of what to do during your stay here, and how people have rated that place. We won't disappoint you. </p> </div> </section> <!--end of section 2 Why Birmingham--> <!--section 3 Top Picks--> <section class="top-picks" id="third"> <div class="container"> <h1>Top Picks</h1> <h2>The top spots in Birmingham chosen by official Brummies</h2> </div> <div class="gallery"> <div id="carousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#carousel" data-slide-to="0" class="active"></li> <li data-target="#carousel" data-slide-to="1"></li> <li data-target="#carousel" data-slide-to="2"></li> <li data-target="#carousel" data-slide-to="3"></li> <li data-target="#carousel" data-slide-to="4"></li> <li data-target="#carousel" data-slide-to="5"></li> <li data-target="#carousel" data-slide-to="6"></li> </ol> <div class="carousel-inner"> <div class="carousel-item active"> <img class="img-responsive" src="http://www.custardfactory.co.uk/wp-content/uploads/2013/10/about1-1200x460.jpg" alt="The Custard Factory"> <div class="carousel-caption"> <h3><strong>The Custard Factory</strong></h3> <h4>The Custard Factory is the UK's leading destination for creative and digital businesses, independent shops and alternate culture outside London.</h4> </div> </div> <div class="carousel-item"> <img class="img-responsive" src="http://www.bqlive.co.uk/resizer/-1/-1/true/1517220170266.jpg--.jpg?1517220170000" alt="Vic Square"> <div class="carousel-caption"> <h3><strong>Victoria Square</strong></h3> <h4>Victoria Square is a pedestrianised public square in Birmingham, England. <br> It is home to both the Town Hall and the Council House, and directly adjacent to Chamberlain Square.</br></h4> </div> </div> <div class="carousel-item"> <img class="img-responsive" src="https://a.jtcstatic.com/upload/auto/flights/cities/600x315/bhx.jpg" alt="Canals"> <div class="carousel-caption"> <h3><strong>The Canals</strong></h3> <h4>Birmingham has 35 miles of canals, which is said to be more than Venice. <br>They're enjoyed by walkers, cyclists, and narrowboat owners and they are a reminder of a unique industrial history.</br> </h4> </div> </div> <div class="carousel-item"> <img class="img-responsive" src="https://spectator.imgix.net/content/uploads/2013/06/status-anxiety.jpg?auto=compress,enhance,format&crop=faces,entropy,edges&fit=crop&w=611&h=400" alt="Canals"> <div class="carousel-caption"> <h3><strong>Cadbury World</strong></h3> <h4>Cadbury World is located in the grounds of the original Cadbury factory, but isn't a tour of the factory itself. <br> Instead, you'll discover the history, the making and the magic of Cadbury confectionery as you journey through our chocolatey zones.</br></h4> </div> </div> <div class="carousel-item"> <img class="img-responsive" src="https://i2-prod.birminghammail.co.uk/incoming/article7927416.ece/ALTERNATES/s1227b/The-Library-of-Birmingham-4.jpg" alt="Canals"> <div class="carousel-caption"> <h3><strong>The Library of Birmingham</strong></h3> <h4>The ten-level Library shares a spacious entrance and foyer as well as a flexible studio theatre seating 300 people with the Birmingham Repertory Theatre. <br>Sited in Centenary Square it, along with The REP and Symphony Hall, forms a new cultural heart for the city.</br></h4> </div> </div> <div class="carousel-item"> <img class="img-responsive" src="https://media.timeout.com/images/102044087/image.jpg" alt="Museum"> <div class="carousel-caption"> <h3><strong>Birmingham Museum & Art Gallery</strong></h3> <h4>Birmingham Museum and Art Gallery (BMAG) first opened in 1885. It is housed in a Grade II* listed city centre landmark building. <br>There are over 40 galleries to explore that display art, applied art, social history, archaeology and ethnography. </br></h4> </div> </div> <div class="carousel-item"> <img class="img-responsive" src="https://upload.wikimedia.org/wikipedia/commons/c/c0/Bull_sculpture_at_the_Bull_Ring%2C_Birmingham_-_DSCF0527.JPG" alt="Bull"> <div class="carousel-caption"> <h3><strong>The Bullring</strong></h3> <h4>The Bull Ring is a major commercial area of central Birmingham. <br> It has been an important feature of Birmingham since the Middle Ages, when its market was first held. </br></h4> </div> </div> </div> <!--slider buttons--> <div class="carousel-controls"> <a id="prev" href="#carousel" role="button" data-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="sr-only">Previous</span> </a> <a id="next" href="#carousel" role="button" data-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="sr-only">Next</span> </a> </div> </div> </div> </section> <!--end of section 3 Top Picks--> <!--section 4 contact us--> <section class="contact" id="fourth"> <div class="container"> <h1>Contact Us</h2> <p id="contactparagraph">If you would like to find out about personal tours get in touch through &nbsp <em id="phonenumber"><strong>+4407882939</em></strong>&nbsp or on our social media:</p> <!--social media--> <div class="row"> <div class="col-lg-4 mr-auto text-right "> <p> <a href="https://facebook.com" target="_blank"><i class="fa fa-facebook-f fa-3x mb-3 sr-contact" data-sr-id="5" style="; visibility: visible; -webkit-transform: scale(1); opacity: 1;transform: scale(1); opacity: 1;-webkit-transition: -webkit-transform 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s, opacity 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s; transition: transform 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s, opacity 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s; "></i></a> </p> </div> <div class="col-lg-4 mr-auto text-center"> <p> <a href="https://www.instagram.com" target="_blank"><i class="fa fa-instagram fa-3x mb-3 sr-contact" data-sr-id="6" style="; visibility: visible; -webkit-transform: scale(1); opacity: 1;transform: scale(1); opacity: 1;-webkit-transition: -webkit-transform 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s, opacity 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s; transition: transform 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s, opacity 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s; "></i></a> </p> </div> <div class="col-lg-4 mr-auto text-left"> <p> <a href="https://www.twitter.com" target="_blank"><i class="fa fa-twitter fa-3x mb-3 sr-contact" data-sr-id="7" style="; visibility: visible; -webkit-transform: scale(1); opacity: 1;transform: scale(1); opacity: 1;-webkit-transition: -webkit-transform 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s, opacity 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s; transition: transform 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s, opacity 0.6s cubic-bezier(0.6, 0.2, 0.1, 1) 0s; "></i></a> </p> </div> </div> <!--subscribe to newsletter--> <form action="action_page.php"> <div class="subscribe"> <h2>Subscribe to our Newsletter</h2> <div class="container"> <input type="text" placeholder="Name" name="name" required> <input type="text" placeholder="Email address" name="mail" required> <label> <input type="checkbox" checked="checked" name="subscribe"> Daily Newsletter &nbsp <input type="checkbox" name="subscribe">Weekly Newsletter </label> </div> <div class="container"> <input type="submit" value="Subscribe"> </div> </form> <!--end of subscribe section--> </div> </section> <!--end of section 4--> <!--footer--> <footer> <p><strong>Website created by:</strong> <NAME> and Em</p> <p><strong>Copyright @ 2019</strong> </p> </footer> <!--end of footer--> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="<KEY>" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="<KEY>" crossorigin="anonymous"></script> </body> </html> <file_sep>/js/scripts.js $('.gallery').gallery({ interval: 100 })
3f1ceaf748f73640c2d458987b401bd2b8053d53
[ "JavaScript", "HTML" ]
2
HTML
Emilana/group_project
01268cc782c78413ad5ffe11ae366aafb9fbeec0
22d2742ca1320123eb6de1b8854c37bc484f77b2
refs/heads/master
<file_sep> //Global let comedy = ['<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>', '<NAME>']; let stillImg = ""; let animateImg = ""; let stillGif = ""; let animateGif = ""; //Create buttons from comedy array using for loop let createButtons = function () { for (let i = 0; i < comedy.length; i++) { let btnDiv = $("<button>"); btnDiv.addClass("btn btn-outline-secondary searchBtn"); btnDiv.attr("data-person", comedy[i]); btnDiv.text(comedy[i]); $(".btn-area").append(btnDiv); } } //Submit Button $("#user-input").on("click", function (event) { submit(); $('.form-control').val(""); return false }) //When Enter is pressed..... $(".form-control").keydown(function(event){ if(event.keyCode == 13){ console.log("working"); submit(); $('.form-control').val(""); return false } }); //Submit Function let submit = function () { event.preventDefault(); let userInput = $(".form-control").val(); comedy.push(userInput); $(".btn-area").empty(); createButtons(); console.log("BUTTON INFO: ", userInput); console.log(event); return false } //Create on click function $(".searchBtn").on("click", function() { $(".instructions").empty(); let btnName = $(this).attr("data-person"); console.log(this); console.log("button name: ", btnName); //Query url + Click + API Key let queryUrl = "https://api.giphy.com/v1/gifs/search?q=" + btnName + "&api_key=<KEY>&limit=10"; //Ajax call to Giphy API $.ajax({ url: queryUrl, method: "GET" }) //Waits for the data to arrive .then(function (response) { //Storing the results let results = response.data; // console.log("results: ", results); //For loop to grab each gif from the object for (let j = 0; j < results.length; j++) { //Still Image stillImg = results[j].images.fixed_height_still.url; //Animated Gif animateGif = results[j].images.fixed_height.url; //Ratings let ratings = results[j].rating; //Create Elements let gifDiv = $("<div>"); let p = $("<h3>").text("Rating: " + ratings); let gifImg = $("<img>"); //Add class to P tag for styling purposes p.addClass("imdb") //Giving GIFS settings gifImg.addClass("gif"); // gifDiv.attr("data-state", "still"); gifImg.attr("src", stillImg,); gifImg.attr("data-state", "still"); // gifImg.attr("data-animate", animateGif); gifDiv.append(gifImg, p); // gifDiv.append(gifImg); $(".gif-area").prepend(gifDiv); console.log("animate GIF: ", animateGif); console.log("Still GIF: ", stillImg); } $(document).on("click", ".gif", function () { let state = $(this).attr("data-state"); console.log("Atribute: ", state); console.log("this: ", this); if (state === "still") { $(this).attr("src", animateGif); $(this).attr("data-state", "animate"); console.log("this in If statement: ", this); } else { $(this).attr("src", stillImg); $(this).attr("data-state", "still"); } }) }); }); createButtons();
2efd1d4553cbace4556cc818fa143a4b48cdc72e
[ "JavaScript" ]
1
JavaScript
cliftonbnoble/GifTastic
71e13877ba2467b7a7569744663267e8e0c5f461
32a9566cae31daad1ab7ae8bffb8e1cfd1cb1088
refs/heads/master
<file_sep>package com.konzil.intelligence.deploy.config.web; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; /** * @ClassName: IntelligenceDeployViewConfig * @Author: KONZIL * @description: web配置 * @date: 2019-03-28 */ @Configuration public class IntelligenceDeployViewConfig implements WebMvcConfigurer { /** * 静态资源映射1 * @param registry */ @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { } }
48151bb0a38a893b2ac500e1d72f5feb982020a8
[ "Java" ]
1
Java
konzilmxp/intelligence-deploy
0f51bf1318cf36fd4d8b4a929bbd2976d0197849
8454d9f5e03959955ff3a72cb8d33f36b6a95907
refs/heads/master
<repo_name>jhpfraser/fu_raid_tool<file_sep>/RaidUpload/FuEQ.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Diagnostics; using System.Windows; namespace RaidUtil { // this class contains stuff to do with eq, like the default eq social button setup and the functions that get or set the social buttons class FuEQ { public static Dictionary<string, string> GetDefaultSettings() { Dictionary<string, string> d = new Dictionary<string, string>(); d.Add("HttpLoginURL", "http://fuworldorder.net/forum/login.php"); d.Add("HttpUploadURL", "http://fuworldorder.net/hava/testraidupload.php"); d.Add("EqGuildName", "Fu World Order"); d.Add("LootMinutes", "30"); d.Add("LootLookupMinutes", "3"); d.Add("LogFileScanSize", "20"); return d; } public static List<string> GetToons() { return Cfg.get("_toons").Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries).ToList(); } public static void SetToons(List<string> toons) { Cfg.set("_toons", String.Join(",", toons)); } public static string GetEQFolderForToon(string toon, string server) { Dictionary<string, string> section = Cfg.getList(String.Format("{0}-{1}", toon, server)); if (section.ContainsKey("EqFolder")) { return section["EqFolder"]; } return ""; } public static void SetEQFolderForToon(string toon, string server, string folder) { Cfg.setList(String.Format("{0}-{1}", toon, server), new Dictionary<string, string> { ["EqFolder"] = folder }); } public static List<List<SocialButton>> GetSocials(string toon, string server, string eqFolder) { string fileName = Path.Combine(eqFolder, String.Format("{0}_{1}.ini", toon, server)); if (!File.Exists(fileName)) { throw new FileNotFoundException(); } Ini ini = new Ini(fileName); List<List<SocialButton>> pages = new List<List<SocialButton>>(); for (int i = 1; i <= 10; i++) // 10 pages { List<SocialButton> socs = new List<SocialButton>(); for (int j = 1; j <= 12; j++) // 12 buttons/page { string id = String.Format("Page{0}Button{1}", i, j); socs.Add( new SocialButton { Title = ini.GetValue(id + "Name", "Socials"), Color = ini.GetValue(id + "Color", "Socials"), Page = i, Button = j, Lines = new List<string>( new String[] { ini.GetValue(id + "Line1", "Socials"), ini.GetValue(id + "Line2", "Socials"), ini.GetValue(id + "Line3", "Socials"), ini.GetValue(id + "Line4", "Socials"), ini.GetValue(id + "Line5", "Socials") } ) } ); } pages.Add(socs); } return pages; } public static void SaveSocial(string eqFolder, string toonName, string serverShortName, SocialButton soc) { string fileName = Path.Combine(eqFolder, String.Format("{0}_{1}.ini", toonName, serverShortName)); if (!File.Exists(fileName)) { throw new FileNotFoundException(); } Ini ini = new Ini(fileName); string id = String.Format("Page{0}Button{1}", soc.Page, soc.Button); ini.WriteValue(id + "Name", "Socials", soc.Title); ini.WriteValue(id + "Color", "Socials", soc.Color); ini.WriteValue(id + "Line1", "Socials", soc.Lines[0]); ini.WriteValue(id + "Line2", "Socials", soc.Lines[1]); ini.WriteValue(id + "Line3", "Socials", soc.Lines[2]); ini.WriteValue(id + "Line4", "Socials", soc.Lines[3]); ini.WriteValue(id + "Line5", "Socials", soc.Lines[4]); ini.Save(); } } class SocialButton { public string Title; public string Color; public int Page; public int Button; public List<string> Lines; public SocialButton() { this.Title = ""; this.Color = ""; this.Page = 0; this.Button = 0; this.Lines = new List<string>(new string[] { "", "", "", "", "" }); } } class LootButton : SocialButton { public LootButton(string appPath, string toonName, string serverName) { this.Title = "FU-LootDump"; this.Color = ""; this.Lines = new List<string>(new string[]{ String.Format("/system \"{0}\" Loot {1} {2}", appPath, toonName, serverName), "", "", "", "" }); } } class LootLookupButton : SocialButton { public LootLookupButton(string appPath, string toonName, string serverName) { this.Title = "FU-LootLookup"; this.Color = ""; this.Lines = new List<string>(new string[] { String.Format("/system \"{0}\" LootLookup {1} {2}", appPath, toonName, serverName), "", "", "", "" }); } } class RaidAttendanceButton : SocialButton { public RaidAttendanceButton(string appPath, string toonName, string serverName) { this.Title = "FU-Attendance"; this.Color = ""; this.Lines = new List<string>(new string[] { "/out raid", "/out guild", String.Format("/gu Taking Attendance -- tells to me for bench (IF NOT IN RAID)"), String.Format("/gu Taking Attendance -- tells to me for bench (IF NOT IN RAID)"), String.Format("/system \"{0}\" Attendance {1} {2}", appPath, toonName, serverName) }); } } class GuildRosterButton : SocialButton { public GuildRosterButton(string appPath, string toonName, string serverName) { this.Title = "FU-GuildDump"; this.Color = ""; this.Lines = new List<string>(new string[] { "/out guild", String.Format("/system \"{0}\" GuildRoster {1} {2}", appPath, toonName, serverName), "", "", "" }); } } } <file_sep>/RaidUpload/FuParse.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Text.RegularExpressions; using System.IO; using System.Globalization; namespace RaidUtil { // this class contains the stuff that handles log file reading and parsing class FuParse { // fast read the last x megs of a file as a string array (of lines in that file) private static string[] ReadLog(string filePath, float megs) { // this function will break if you ask for more than 2GB at once // all of the FileStream method parameters we use are INT - with a cap of 2GB (fs.Seek, fs.Read) if (megs > 2048) megs = 2048; FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read); int readLength = int.MaxValue; byte linefeed = Convert.ToByte('\n'); int lf = (int)linefeed; int test; // if more megs were requested than exist, read the whole file // also if we do read the whole file, no need to delete the first entry if (fs.Length < readLength) { readLength = (int)fs.Length; } if (readLength > megs * 1024 * 1024) { readLength = (int) (megs * 1024 * 1024); fs.Seek(-readLength, SeekOrigin.End); // this chops off the first probably partial line of text do { test = fs.ReadByte(); readLength--; } while (test != lf); } if (readLength == 0) return new string[0]; byte[] buffer = new byte[readLength]; int count; int sum = 0; while ((count = fs.Read(buffer, sum, readLength - sum)) > 0) { sum += count; } fs.Close(); // this might be non optimal string[] lineList = Encoding.ASCII.GetString(buffer).Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries); return lineList; } public static MemoryStream ParseLoot(string toon, string server, float minutes) { float m = minutes / 2; if (m < 1) m = 1; // 1 meg min float c; if (float.TryParse(Cfg.get("LogFileScanSize"), out c)) { if (m > c) m = c; //logfilescansize limit } else { if (m > 20) m = 20; // 20 meg limit } return ParseLoot(toon, server, minutes, DateTime.Now, m); } public static MemoryStream ParseLoot(string toon, string server, float minutes, DateTime when, float megs) { // rather than writing the output to a file we'll use a memory stream MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms,Encoding.ASCII); // load the log file string logPath = Path.Combine(FuEQ.GetEQFolderForToon(toon, server), "Logs", String.Format("eqlog_{0}_{1}.txt", toon, server)); // datetime format that EQ uses in log file string dateFormat = "ddd MMM dd HH:mm:ss yyyy"; // "before" is a datetime after which we start caring about the log entries. RaidHours is configurable in config file DateTime before = when.AddMinutes(-minutes); string[] partFile = ReadLog(logPath, megs); DateTime d; foreach (string l in partFile) { // if the line doesnt contain at least the length of the date, ignore it if (l.Length < dateFormat.Length + 1) continue; // get a DateTime out of the log for this line, ignore the line if it didnt work if (DateTime.TryParseExact(l.Substring(1, dateFormat.Length), dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out d) != false) { // if the line is after the "before" date and contains stuff we want, write it to the stream if ( d >= before && ( l.Contains("You say to your guild") // potential grats message from me || l.Contains("tells the guild") // potential grats message from other || l.Contains("] --") // potential looted message ) ) { sw.WriteLine(l); } } } sw.Flush(); ms.Position = 0; return ms; } private static string GetLastFile(string folder, string filespec) { IEnumerable<string> dir = Directory.EnumerateFiles(folder, filespec); if (dir.Count() == 0) { return ""; // file not found } string lastFile = dir.OrderByDescending(s => s).First(); if (lastFile.Length == 0) return ""; // check that the last file date is reasonably close to now FileInfo fi = new FileInfo(lastFile); int minutesDiff = (DateTime.Now - fi.LastWriteTime).Minutes; if (minutesDiff > 15) { System.Windows.Forms.DialogResult choice = System.Windows.Forms.MessageBox.Show( String.Format("The file {0} is more than 15 minutes old, continue?", lastFile), "Warning, that might be an old file", System.Windows.Forms.MessageBoxButtons.YesNo ); if (choice == System.Windows.Forms.DialogResult.Yes) { return lastFile; } return ""; } return lastFile; } public static MemoryStream ParseRoster(string toon, string server) { // get the guild dump // looking for last file of format fu world order-<datetime>.txt in eq\Fu World Order-20161226-090424.txt MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms, Encoding.ASCII); string lastdumpfile = GetLastFile(FuEQ.GetEQFolderForToon(toon, server), String.Format("{0}_{1}-*.txt", Cfg.get("EqGuildName"), server)); if (String.IsNullOrEmpty(lastdumpfile)) return ms; try { sw.Write(File.ReadAllText(lastdumpfile)); } catch (Exception e) { return ms; // failure reading file } sw.Flush(); ms.Position = 0; return ms; } public static MemoryStream ParseAttendance(string toon, string server) { MemoryStream ms = new MemoryStream(); StreamWriter sw = new StreamWriter(ms, Encoding.ASCII); string lastdumpfile = GetLastFile(FuEQ.GetEQFolderForToon(toon, server), String.Format("RaidRoster_{0}-*.txt", server)); if (String.IsNullOrEmpty(lastdumpfile)) { System.Windows.Forms.MessageBox.Show(String.Format("There were no files matching {0} in the {1} folder", "RaidRoster-*.txt", FuEQ.GetEQFolderForToon(toon, server))); return ms; } try { string dump = File.ReadAllText(lastdumpfile); if (dump.Length > 0) { sw.Write(dump); } else { System.Windows.Forms.MessageBox.Show(String.Format("The file {0} was empty", lastdumpfile)); } } catch (Exception e) { System.Windows.Forms.MessageBox.Show(String.Format("An exception occurred - {0}", e.Message)); return ms; // failure reading file } sw.Flush(); ms.Position = 0; return ms; } public static string ParseLootLookup(string toon, string server, float minutes) { float m = minutes / 2; if (m < 1) m = 1; // 1 meg min float c; if (float.TryParse(Cfg.get("LogFileScanSize"), out c)) { if (m > c) m = c; //logfilescansize limit } else { if (m > 20) m = 20; // 20 meg limit } return ParseLootLookup(toon, server, minutes, DateTime.Now, m); } public static string ParseLootLookup(string toon, string server, float minutes, DateTime when, float megs) { // load the log file string logPath = Path.Combine(FuEQ.GetEQFolderForToon(toon, server), "Logs", String.Format("eqlog_{0}_{1}.txt", toon, server)); // datetime format that EQ uses in log file string dateFormat = "ddd MMM dd HH:mm:ss yyyy"; // "before" is a datetime after which we start caring about the log entries. DateTime before = when.AddMinutes(-minutes); string[] partFile = ReadLog(logPath, megs); // list of names List<string> names = new List<string>(); DateTime d; foreach (string l in partFile) { // if the line doesnt contain at least the length of the date, ignore it if (l.Length < dateFormat.Length + 1) continue; // get a DateTime out of the log for this line, ignore the line if it didnt work if (DateTime.TryParseExact(l.Substring(1, dateFormat.Length), dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, out d) != false) { // if the line is after the "before" date and contains a tell if ( d >= before && (l.Contains("tells you") || l.Contains("told you")) ) { // extract the name and add it to the list Regex re = new Regex(@"(\w+)\s+((tells)|(told))\s+you", RegexOptions.IgnoreCase); Match m = re.Match(l); if (m.Success && !names.Contains(m.Groups[1].Value)) { names.Add(m.Groups[1].Value); } } } } // stick list together with commas return String.Join(",", names); } } } <file_sep>/RaidUpload/Program.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.IO; using System.Windows.Forms; using System.Net; using IWshRuntimeLibrary; using System.Diagnostics; namespace RaidUtil { class Program { private static string appFolder = ""; private static string command; private static string toon; private static string server; public static string LogFolder = "FuRaidTool Logs"; [STAThread] static void Main(string[] args) { bool debug = false; if (IsInstalled() || debug) { if (!HasConfig() && !debug) { // make an empty config file BuildEmptyConfigFile(); command = "config"; } } else { // install and create config file if (MessageBox.Show("About to install", "FuRaidTool", MessageBoxButtons.OKCancel) == DialogResult.OK) { Install(); } return; // probably wont get hit because install kills this process } appFolder = Path.GetDirectoryName(Application.ExecutablePath); float minutes = -1; if (command == "config" || args.Length == 0) { command = "config"; //command = "loot"; } else if (args.Length == 1) { command = args[0]; } else { command = args[0].ToLower(); toon = args[1]; if (args.Length > 2) { server = args[2]; } else { server = "bristle"; } } switch (command) { case "config": FuHttp f = new FuHttp(); ConfigForm cf = new ConfigForm(); cf.AppPath = Application.ExecutablePath; cf.ShowDialog(); break; case "loot": if (minutes == -1) { if (!float.TryParse(Cfg.get("LootMinutes"), out minutes)) { minutes = 10; } } if (UpdateLoot(toon, server, minutes)) { SendLogsToServer(); Process.Start("http://fuworldorder.net/admin/loot/loot_assignments.php"); } break; case "lootlookup": if (minutes == -1) { if (!float.TryParse(Cfg.get("LootLookupMinutes"), out minutes)) { minutes = 3; } } DoLootLookup(toon,server,minutes); break; case "attendance": if (UpdateRaidAttendance(toon,server)) { SendLogsToServer(); Process.Start("http://fuworldorder.net/admin/raid/attendance.php"); } break; case "guildroster": if (UpdateGuildRoster(toon,server)) { SendLogsToServer(); Process.Start("http://fuworldorder.net/admin/raid/attendance.php"); } break; case "sendlogs": SendLogsToServer(); break; } } public static string GetAppFolder() { return Path.GetDirectoryName(Application.ExecutablePath); } private static bool IsInstalled() { string fupath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FuEQ"); string exepath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName); if (fupath == exepath) return true; return false; } private static bool HasConfig() { return System.IO.File.Exists(Application.ExecutablePath + ".config"); } private static void Install() { string fupath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FuEQ"); string exeName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName); if (!Directory.Exists(fupath)) { Directory.CreateDirectory(fupath); if (!Directory.Exists(fupath)) { MessageBox.Show("Unable to create FuEQ folder, install failed"); return; } } else { if (fupath != Environment.CurrentDirectory) { System.IO.File.Delete(Path.Combine(fupath, exeName)); } } // copy self to fupath System.IO.File.Copy(Path.Combine(Environment.CurrentDirectory, exeName), Path.Combine(fupath, exeName)); // setup logs folder Directory.CreateDirectory(Path.Combine(fupath, LogFolder)); // create desktop shortcut string shortcutpath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "FuEQ.lnk"); WshShell shell = new WshShell(); IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutpath); shortcut.Description = "FU Raid Tool Config"; // The description of the shortcut //shortcut.IconLocation = Path.Combine(fupath, exeName); // The icon of the shortcut (doesnt seem needed) shortcut.TargetPath = Path.Combine(fupath, exeName); // The path of the file that will launch when the shortcut is run shortcut.Save(); // if no existing config file make one if (!System.IO.File.Exists(Path.Combine(fupath, exeName + ".config"))) { BuildEmptyConfigFile(Path.Combine(fupath, exeName + ".config")); } // start a new instance of this app out of the new folder (no params) Process.Start(Path.Combine(fupath, exeName)); // close the current instance Process.GetCurrentProcess().Kill(); } public static string GetLatestVersionNumber() { string version = "Unknown"; return version; } public static bool UpdateLoot(string toon, string server, float minutes) { // parse and build upload logs MemoryStream loot = FuParse.ParseLoot(toon, server, minutes); if (loot.Length < 10) { MessageBox.Show("The loot log is empty :("); return false; } else { string lootFilename = String.Format("loot_{0}_{1}_{2}.txt", server, toon, DateTime.Now.ToString("yyyyMMdd-hhmmss")); string lootPath = Path.Combine(GetAppFolder(), LogFolder, lootFilename); FileStream fs = new FileStream(lootPath, FileMode.Append); loot.Position = 0; loot.CopyTo(fs); fs.Close(); return true; } } public static bool UpdateRaidAttendance(string toon, string server) { // parse and build upload logs MemoryStream part1 = FuParse.ParseRoster(toon, server); // I picked 10 because "empty" ones seem to have a length of 3, so yeah if (part1.Length < 10) { MessageBox.Show("Problem with the Guild Roster."); return false; } else { MemoryStream part2 = FuParse.ParseAttendance(toon, server); if (part2.Length < 10) { MessageBox.Show("Unable to locate or process your raid dump file."); return false; } else { string raidFilename = String.Format("raid_{0}_{1}_{2}.txt", server, toon, DateTime.Now.ToString("yyyyMMdd-hhmmss")); string raidPath = Path.Combine(GetAppFolder(), LogFolder, raidFilename); FileStream fs = new FileStream(raidPath, FileMode.Append); part1.CopyTo(fs); new MemoryStream(Encoding.ASCII.GetBytes("FU-DEMILITER-THINGER")).CopyTo(fs); part2.CopyTo(fs); fs.Close(); return true; } } } public static bool UpdateGuildRoster(string toon, string server) { MemoryStream rost = FuParse.ParseRoster(toon, server); if (rost.Length < 10) { MessageBox.Show("Guild Roster is Empty :("); return false; } else { // parse and build upload logs string guildFilename = String.Format("guild_{0}_{1}_{2}.txt", server, toon, DateTime.Now.ToString("yyyyMMdd-hhmmss")); string guildPath = Path.Combine(GetAppFolder(), LogFolder, guildFilename); FileStream fs = new FileStream(guildPath, FileMode.Append); rost.CopyTo(fs); fs.Close(); return true; } } public static bool DoLootLookup(string toon, string server, float minutes, string defaultName = "") { string namelist = FuParse.ParseLootLookup(toon, server, minutes); if (namelist.Length == 0) { if (defaultName.Length > 0) { namelist = defaultName; } else { MessageBox.Show("Unable to find any tells in the last " + minutes + " minutes."); return false; } } Process.Start("http://fuworldorder.net/admin/lootlookup?userlist=" + Uri.EscapeDataString(namelist)); return true; } private static void BuildEmptyConfigFile(string path) { System.Text.StringBuilder sb = new StringBuilder(); sb.AppendLine("<?xml version=\"1.0\" encoding=\"utf-8\" ?>"); sb.AppendLine("<configuration>"); sb.AppendLine("<appSettings>"); foreach (KeyValuePair<string, string> kvp in FuEQ.GetDefaultSettings()) { sb.AppendLine(String.Format("<add key=\"{0}\" value=\"{1}\" />", kvp.Key, kvp.Value)); } sb.AppendLine("</appSettings>"); sb.AppendLine("</configuration>"); System.IO.File.WriteAllText(path, sb.ToString()); } private static void BuildEmptyConfigFile() { BuildEmptyConfigFile(String.Concat(Application.ExecutablePath, ".config")); } public static void SendLogsToServer() { // check for logs that didnt make it (either new or failed last time) string logPath = Path.Combine(GetAppFolder(), LogFolder); // should do them in the right order var logs = Directory.EnumerateFiles(logPath); List<string> failures = new List<string>(); FuHttp h = new FuHttp(); if (!h.Login(Cfg.getEncrypted("HttpUsername"), Cfg.getEncrypted("HttpPassword"))) { //MessageBox.Show("There was a problem with your Fu Website credentials"); return; } foreach (string log in logs) { string fname = log; string logFile = Path.GetFileName(log); if (logFile.StartsWith("COMPLETE_") || logFile.StartsWith("INCOMPLETE_")) { // already finished, skip } else { try { string response = h.UploadLog(fname); if (response.ToLower() == "success") { string newFilePath = Path.Combine(Path.GetDirectoryName(fname), String.Format("COMPLETE_{0}", Path.GetFileName(fname))); System.IO.File.Move(fname, newFilePath); } else { string newFilePath = Path.Combine(Path.GetDirectoryName(fname), String.Format("INCOMPLETE_{0}", Path.GetFileName(fname))); System.IO.File.Move(fname, newFilePath); failures.Add(response); } } catch (Exception e) { string newFilePath = Path.Combine(Path.GetDirectoryName(fname), String.Format("INCOMPLETE_{0}", Path.GetFileName(fname))); System.IO.File.Move(fname, newFilePath); failures.Add(e.Message); } } } if (failures.Count > 0) { MessageBox.Show("Transmission error(s)!" + Environment.NewLine + String.Join(Environment.NewLine, failures.ToArray())); } } } } <file_sep>/RaidUpload/notes.txt DONE - option to make social buttons in eq automatically SORTA, USED TO VALIDATE - read eq characters by enumerating charname_servername.ini files DONE - validate fu username and passwords via http configs by character DONE - add enable system command (eqclient.ini -> enablesystemcommand=1) DONE - use a folder to store logs and ability to resend if failed check if config file from a diff user fucks everything up how it works Running vanilla (no params) - checks to see if its in the correct FuEQ folder, if not assume new install or upgrade depending on existence of FuEQ folder and config file. New install creates log folder and config file from default config file (found in FuEQ class) upgrade just copies the exe assuming there might be shit in the log folder to process yet, and assuming the config file is okay in either case a desktop icon is created, it doesnt seem to care if it already exists the installer then spawns the exe in the correct folder as a new process the installer exits (leaving the new process running) - opens config screen eq folder is checked to contain eqclient.ini or its invalid username / server name are checked vs <username>_<servername>.ini in eq folder (some subfolder) else invalid once those 2 things are checked you can get into the socials screen lootminutes = how long to check for loot tells once the dump button is pressed to be considered part of this event's loot lootlookupminutes = how long to check for tells to you before adding them to the loot lookup that opens in a browser fu username/password = for the web site. Test button checks (vs the website). When you hit save it won't let you save unless you have a valid logon. These two values are encrypted before being stored in config file using "this fucking computer/this user" can only decrypt. - socials screen upon load this reads the socials from your toon_server.ini file and makes a mockup of the eq socials thing CLICK A SOCIAL to edit it the edits allowed are - change this social to one of the 4 needed Buttons - clear (delete) this social When the changes are made to toon_server.ini, the user is annoyingly prompted to not fuck this up As advertised, don't be in eq when you change this stuff (maybe at server select is ok?) the buttons are in the same format as piyper's buttons, ie /system "<path to this executable>" command yourtoon param1 the 4 buttons are currently stored, perhaps awkwardly, as subclasses of FuEQ.SocialButton the parameters and username for the commands come from the current config(?) when an edit/delete button is pressed Running with params When this app is called with command line params, it is usually being run by EQ in response to a click on a social The only configurable settings used during this part come from the command line (so, the config file is not used) except for eqfolder (eqlogfolder) and the http username/password Theoretically you could set up 2 toons as long as they had the same eq folder - I have not yet added support for multiple eq folders the commands are - config (the default when run with no params, opens config screen blah blah) - loot - builds a parsed log out of guild tells relevant to loot - saves it in log folder - send update is called which: - looks for incomplete and new logs in folder - tries to send all of them (to a service that I havent written yet. Version 1 will be "copy the uploaded stuff to the ftp folder and call the php that updates out of the ftp folder") via form POST - marks them as complete or incomplete again - loot lookup - grabs the last x minutes of tells, where x is a param that was passed by the button - makes a list of the names - opens a browser to fublahblah/lootlookup w the names on the querystring - attendance - doesnt work yet - guildroster - doesnt work yet <file_sep>/RaidUpload/FuHttp.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; using System.IO; using System.Text.RegularExpressions; using System.Windows.Forms; namespace RaidUtil { // this class contains the stuff that sends data from the client to the web site class FuHttp { private CookieAwareWebClient m_WebClient; private bool m_Authorized = false; public FuHttp() { m_WebClient = new CookieAwareWebClient(); } private void PreparePost(string url) { m_WebClient.Headers.Add("Referer:" + url); m_WebClient.Headers.Add("Accept:text/html"); m_WebClient.Headers.Add("User-Agent:FuRaidTool"); m_WebClient.Headers.Add("Content-Type:application/x-www-form-urlencoded"); } public bool Login(string username, string password) { Dictionary<string, string> d = new Dictionary<string, string> { ["username"] = username, ["password"] = <PASSWORD>, ["redirect"] = "../index.php", ["login"] = "Log in" }; byte[] result; PreparePost(Cfg.get("HttpLoginUrl")); try { result = m_WebClient.UploadData(Cfg.get("HttpLoginUrl"), FormBytes(d)); } catch (WebException e) { MessageBox.Show(e.Message, "Error connecting to FU Website"); m_Authorized = false; return false; } string html = Encoding.UTF8.GetString(result).ToLower(); if (html.Contains(String.Format("welcome, {0}!", username.ToLower()))) { m_Authorized = true; return true; } MessageBox.Show("Invalid FU Website Username/Password"); m_Authorized = false; return false; } /* // update thing public bool IsUpdateAvailable() { Dictionary<string, string> d = new Dictionary<string, string> { ["command"] = "GetLatestVersion" }; try { String url = Cfg.get("HttpUploadUrl"); PreparePost(Cfg.get("EndpointURL")); byte[] toSend = FormBytes(d); byte[] respB = m_WebClient.UploadData(url, "POST", toSend); string response = Encoding.UTF8.GetString(respB); // check the response for success if (response.ToLower().Contains("success")) { return "success"; } return response; } catch (Exception e) { return e.Message; } } */ // written as a test for the http system // send a PM to a user // might come in handy public void SendPM(string toUser, string subject, string message) { if (m_Authorized) { // In case you can only post a message from the message screen (cookie or form field), load this page to store the cookies in m_WebClient's auto-cookie manager m_WebClient.DownloadData("http://fuworldorder.net/forum/privmsg.php?folder=inbox"); // build the "form" Dictionary<string, string> d = new Dictionary<string, string> { ["sid"] = m_WebClient.SID, ["username"] = toUser, ["subject"] = subject, ["message"] = message, ["folder"] = "inbox", ["mode"] = "post", ["post"] = "Submit" }; // add the required "form sending" headers to m_WebClient PreparePost("http://fuworldorder.net/forum/privmsg.php?folder=inbox"); m_WebClient.UploadData("http://fuworldorder.net/forum/privmsg.php", FormBytes(d)); } } public string UploadLog(string filePath) { if (!m_Authorized) { return "Bad username/password"; } string fileName = Path.GetFileName(filePath); string[] bits = fileName.Split('_'); if (bits.Length != 4) { return "Something did not compute"; } Dictionary<string, string> d = new Dictionary<string, string> { ["sid"] = m_WebClient.SID, ["toon"] = bits[2], ["type"] = bits[0], ["server"] = bits[1], ["file"] = File.ReadAllText(filePath, Encoding.UTF8) }; try { String url = Cfg.get("HttpUploadUrl"); //m_WebClient.DownloadData(u); PreparePost(url); byte[] toSend = FormBytes(d); byte[] respB = m_WebClient.UploadData(url, "POST", toSend); string response = Encoding.UTF8.GetString(respB); // check the response for success if (response.ToLower().Contains("success")) { return "success"; } return response; } catch (Exception e) { return e.Message; } } // convert a dictionary of form items into upload-ready byte array // also gets rid of windows line endings and replaces w linux private byte[] FormBytes(Dictionary<string, string> formItems) { List<string> data = new List<string>(); foreach (KeyValuePair<string, string> kvp in formItems) { data.Add(String.Format("{0}={1}", kvp.Key, EscapeFormString(kvp.Value))); } return Encoding.UTF8.GetBytes(String.Join("&", data)); } private string EscapeFormString(string toEscape) { // this encodes the form data // the provided Uri.Escapedatastring has a limit of 32k and our log files can easily exceed it so it must be split up int limit = 32000; StringBuilder sb = new StringBuilder(); int loops = toEscape.Length / limit; for (int i = 0; i <= loops; i++) { if (i < loops) { sb.Append(Uri.EscapeDataString(toEscape.Substring(limit * i, limit))); } else { sb.Append(Uri.EscapeDataString(toEscape.Substring(limit * i))); } } return sb.ToString(); } } } <file_sep>/RaidUpload/CookieAwareWebClient.cs using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Net; namespace RaidUtil { class CookieAwareWebClient : WebClient { public readonly CookieContainer m_container = new CookieContainer(); // some forms require the session id (mod_security), so it's exposed here for that reason public string SID = ""; protected override WebRequest GetWebRequest(Uri address) { WebRequest request = base.GetWebRequest(address); HttpWebRequest webRequest = request as HttpWebRequest; if (webRequest != null) { webRequest.CookieContainer = m_container; } CookieCollection cc = webRequest.CookieContainer.GetCookies(request.RequestUri); foreach (Cookie c in cc) { if (c.Name.ToLower() == "phpbb2mysql_sid") { SID = c.Value; } } return request; } } } <file_sep>/RaidUpload/Cfg.cs using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; using System.Configuration; using System.Collections; // a simple helper class to read/store/increment values in the .config file namespace RaidUtil { public class Cfg { private static byte[] entropy = System.Text.Encoding.Unicode.GetBytes("FuFuSaltySaltyFuDogSaltyFu"); public static List<string> getSections() { List<string> ret = new List<string>(); Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = config.AppSettings.Settings; foreach (KeyValueConfigurationElement e in settings) { if (e.Key.Contains("_")) { ret.Add(e.Key.Split('_')[0]); } } return ret; } public static Dictionary<string, string> getList(string partKey) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = config.AppSettings.Settings; Dictionary<string, string> d = new Dictionary<string, string>(); foreach (KeyValueConfigurationElement e in settings) { if (e.Key.StartsWith(partKey)) { d.Add(e.Key.Substring(partKey.Length + 1), e.Value); } } return d; } public static void setList(string partKey, Dictionary<string,string> values) { foreach (KeyValuePair<string,string> kvp in values) { set(partKey + "_" + kvp.Key, kvp.Value); } } public static string get(string key) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = config.AppSettings.Settings; string v; try { v = settings[key].Value; return v; } catch (Exception e) { return String.Empty; } } public static string getEncrypted(string key) { var eVal = get(key); if (String.IsNullOrEmpty(eVal)) { return String.Empty; } try { byte[] decrypted = System.Security.Cryptography.ProtectedData.Unprotect( Convert.FromBase64String(eVal), entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser ); return System.Text.Encoding.UTF8.GetString(decrypted); } catch (System.Security.Cryptography.CryptographicException e) { return String.Empty; } } public static void delete(string key) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = config.AppSettings.Settings; if (settings[key] != null) { settings.Remove(key); } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); } public static void set(string key, object value) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = config.AppSettings.Settings; if (config.AppSettings.Settings[key] == null) { settings.Add(key, value.ToString()); } else { settings[key].Value = value.ToString(); } config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); } public static void setEncrypted(string key, object value) { byte[] bVal = System.Text.Encoding.UTF8.GetBytes(value.ToString()); byte[] encrypted = System.Security.Cryptography.ProtectedData.Protect( bVal, entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser ); set(key, Convert.ToBase64String(encrypted)); } public static int increment(string key, int startFrom = 0) { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); KeyValueConfigurationCollection settings = config.AppSettings.Settings; string v = settings[key].Value; int test; try { test = int.Parse(v); } catch (Exception e) { if (String.IsNullOrEmpty(v)) { test = startFrom - 1; } else { return -1; } } test++; settings[key].Value = test.ToString(); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection(config.AppSettings.SectionInformation.Name); return test; } } } <file_sep>/RaidUpload/Socials.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace RaidUtil { public partial class Socials : Form { private List<List<SocialButton>> pages; private int curPage = 2; private const int minPage = 1; private const int maxPage = 10; private int selBtn = 0; private int selPage = 0; private string m_toonName; private string m_serverName; private string m_eqFolder; public string AppPath; public Socials() { InitializeComponent(); } private void Socials_Load(object sender, EventArgs e) { } public void LoadSocialsForToon(string toonName, string server, string eqfolder) { m_toonName = toonName; m_serverName = server; m_eqFolder = eqfolder; try { pages = FuEQ.GetSocials(m_toonName, m_serverName, m_eqFolder); } catch (Exception e) { MessageBox.Show("Unable to find your eq ini files, please check your eq folder is correct"); return; } LoadPage(curPage); } private void LoadPage(int pageNo) { List<SocialButton> p = pages[pageNo - 1]; btnSocial1.Text = p[0].Title; btnSocial2.Text = p[1].Title; btnSocial3.Text = p[2].Title; btnSocial4.Text = p[3].Title; btnSocial5.Text = p[4].Title; btnSocial6.Text = p[5].Title; btnSocial7.Text = p[6].Title; btnSocial8.Text = p[7].Title; btnSocial9.Text = p[8].Title; btnSocial10.Text = p[9].Title; btnSocial11.Text = p[10].Title; btnSocial12.Text = p[11].Title; txtPage.Text = "Page " + pageNo.ToString(); } private void LoadPage() { LoadPage(curPage); } private void btnNext_Click(object sender, EventArgs e) { if (curPage < maxPage) { curPage++; LoadPage(); } else { } } private void btnPrev_Click(object sender, EventArgs e) { if (curPage > minPage) { curPage--; LoadPage(); } } private void btnSocial1_Click(object sender, EventArgs e) { LoadSocialButton(1); } private void btnSocial2_Click(object sender, EventArgs e) { LoadSocialButton(2); } private void btnSocial3_Click(object sender, EventArgs e) { LoadSocialButton(3); } private void btnSocial4_Click(object sender, EventArgs e) { LoadSocialButton(4); } private void btnSocial5_Click(object sender, EventArgs e) { LoadSocialButton(5); } private void btnSocial6_Click(object sender, EventArgs e) { LoadSocialButton(6); } private void btnSocial7_Click(object sender, EventArgs e) { LoadSocialButton(7); } private void btnSocial8_Click(object sender, EventArgs e) { LoadSocialButton(8); } private void btnSocial9_Click(object sender, EventArgs e) { LoadSocialButton(9); } private void btnSocial10_Click(object sender, EventArgs e) { LoadSocialButton(10); } private void btnSocial11_Click(object sender, EventArgs e) { LoadSocialButton(11); } private void btnSocial12_Click(object sender, EventArgs e) { LoadSocialButton(12); } private void LoadSocialButton(int which) { selBtn = which; selPage = curPage; SocialButton s = pages[selPage - 1][selBtn - 1]; txtSelectedButton.Text = String.Format("[Pg{0} Bt{1}] - {2}", selPage, selBtn, (s.Title.Length > 0 ? s.Title : "<No Button>")); txtCommands.Text = String.Join(Environment.NewLine, s.Lines); EnableEdit(); } private void EnableEdit() { } private void DisableEdit() { } private void textBox1_TextChanged(object sender, EventArgs e) { } private void button1_Click(object sender, EventArgs e) { if (selPage != 0 && selBtn != 0) AssignButton(new LootButton(AppPath, m_toonName, m_serverName), selPage, selBtn); } private void button2_Click(object sender, EventArgs e) { if (selPage != 0 && selBtn != 0) AssignButton(new RaidAttendanceButton(AppPath, m_toonName, m_serverName), selPage, selBtn); } private void button3_Click(object sender, EventArgs e) { if (selPage != 0 && selBtn != 0) AssignButton(new LootLookupButton(AppPath, m_toonName, m_serverName), selPage, selBtn); } private void button5_Click(object sender, EventArgs e) { if (selPage != 0 && selBtn != 0) AssignButton(new GuildRosterButton(AppPath, m_toonName, m_serverName), selPage, selBtn); } private void AssignButton(SocialButton which, int pageNo, int btnNo) { which.Page = pageNo; which.Button = btnNo; if ( MessageBox.Show( "You are about to modify your live EQ ini files!\r\nIf your toon is logged in to EQ this won't work!", "Warning", MessageBoxButtons.OKCancel ) == DialogResult.OK) { FuEQ.SaveSocial(m_eqFolder, m_toonName, m_serverName, which); pages[pageNo - 1][btnNo - 1] = which; LoadSocialButton(btnNo); LoadPage(); } } private void button4_Click(object sender, EventArgs e) { if (selPage != 0 && selBtn != 0) AssignButton(new SocialButton(), selPage, selBtn); } private void label1_Click(object sender, EventArgs e) { } } } <file_sep>/RaidUpload/ConfigForm.cs using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.IO; using System.Diagnostics; namespace RaidUtil { public partial class ConfigForm : Form { public string AppPath; private string m_currentToon = ""; private string m_currentServer = ""; public ConfigForm() { InitializeComponent(); eqFolderFinder.RootFolder = Environment.SpecialFolder.MyComputer; UpgradeOld(); LoadConfig(); } private void UpgradeOld() { string toon = Cfg.get("EqToon"); if (toon.Length > 0) { string server = Cfg.get("EqServerShortName"); string folder = Cfg.get("EqFolder"); FuEQ.SetToons(new List<string> { String.Format("{0} - {1}", server, toon) }); FuEQ.SetEQFolderForToon(toon, server, folder); Cfg.delete("EqToon"); Cfg.delete("EqServerShortName"); Cfg.delete("EqFolder"); Cfg.delete("EqLogFolder"); } } private void button1_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(txtEqFolder.Text)) { eqFolderFinder.SelectedPath = txtEqFolder.Text; } if (eqFolderFinder.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtEqFolder.Text = eqFolderFinder.SelectedPath; } if (!IsEQFolderValid()) { MessageBox.Show("EQ folder seems invalid."); } } private void btnSave_Click(object sender, EventArgs e) { if (IsFormValid()) { SaveConfig(); MessageBox.Show("Save Successful."); } } private bool IsFormValid() { if (!IsEQValid()) { return false; } // loot minutes if (String.IsNullOrEmpty(txtLootMinutes.Text)) { MessageBox.Show("Invalid Loot Minutes"); return false; } // loot lookup minutes if (String.IsNullOrEmpty(txtLootLookupMinutes.Text)) { MessageBox.Show("Invalid Loot Lookup Minutes"); return false; } // website username/pass FuHttp h = new FuHttp(); if (!h.Login(txtFuUsername.Text, txtFuPassword.Text)) { return false; } return true; } private void SaveConfig() { FuEQ.SetEQFolderForToon(m_currentToon, m_currentServer, txtEqFolder.Text); Cfg.set("LootMinutes", txtLootMinutes.Text); Cfg.set("LootLookupMinutes", txtLootLookupMinutes.Text); Cfg.setEncrypted("HttpUsername", txtFuUsername.Text); Cfg.setEncrypted("HttpPassword", txtFuPassword.Text); } private void DisableRestOfUI() { groupBox2.Enabled = false; groupBox3.Enabled = false; gbTesting.Enabled = false; txtEqFolder.Enabled = false; btnBrowseEqFolder.Enabled = false; btnSocials.Enabled = false; button9.Enabled = false; btnSave.Enabled = false; } private void EnableRestOfUI() { groupBox2.Enabled = true; groupBox3.Enabled = true; gbTesting.Enabled = true; txtEqFolder.Enabled = true; btnBrowseEqFolder.Enabled = true; btnSocials.Enabled = true; button9.Enabled = true; btnSave.Enabled = true; } private void LoadConfig() { cmbToons.Items.Clear(); cmbToons.Items.AddRange(FuEQ.GetToons().ToArray()); if (cmbToons.Items.Count > 0) { cmbToons.Enabled = true; if (m_currentToon.Length > 0 && m_currentServer.Length > 0) { int i = cmbToons.Items.IndexOf(String.Format("{0} - {1}", m_currentServer, m_currentToon)); if (i > -1) { cmbToons.SelectedIndex = i; } } else if (cmbToons.Items.Count > 0) { cmbToons.SelectedIndex = 0; } string[] toonBits = cmbToons.Items[cmbToons.SelectedIndex].ToString().Split(new string[] { " - " }, StringSplitOptions.None); if (toonBits.Length == 2) { m_currentToon = toonBits[1]; m_currentServer = toonBits[0]; EnableRestOfUI(); } } else { cmbToons.Enabled = false; // force them to add a toon DisableRestOfUI(); } txtEqFolder.Text = FuEQ.GetEQFolderForToon(m_currentToon, m_currentServer); // txtEqFolder.Text = Cfg.get("EqFolder"); txtLootMinutes.Text = Cfg.get("LootMinutes"); txtLootLookupMinutes.Text = Cfg.get("LootLookupMinutes"); txtEqCharacter.Text = ""; txtEqServer.Text = "bristle"; txtFuUsername.Text = Cfg.getEncrypted("HttpUsername"); txtFuPassword.Text = Cfg.getEncrypted("HttpPassword"); } private void btnCancel_Click(object sender, EventArgs e) { this.Close(); } private void button1_Click_1(object sender, EventArgs e) { FuHttp h = new FuHttp(); if (h.Login(txtFuUsername.Text, txtFuPassword.Text)) { MessageBox.Show("Login Succeeded"); } //else // { // MessageBox.Show("Login Failed!"); ///} } private void btnSocials_Click(object sender, EventArgs e) { if (IsEQValid()) { if (!HasSystemCommandEnabled()) { if (MessageBox.Show("In order for this program to function, enablesystemcommand=1 must be set in eqclient.ini.\r\nDon't do this if you're in EQ.\r\nProceed with change to ini file?", "Warning", MessageBoxButtons.YesNo) == System.Windows.Forms.DialogResult.Yes) { SetSystemCommandEnabled(); } else { // user didnt want to set ini return; } } Socials socForm = new Socials(); socForm.AppPath = this.AppPath; socForm.LoadSocialsForToon(m_currentToon, m_currentServer, txtEqFolder.Text); socForm.ShowDialog(); } } private bool HasSystemCommandEnabled() { Ini ini = new Ini(Path.Combine(txtEqFolder.Text, "eqclient.ini")); if (ini.GetSections().Contains("Defaults")) { if (ini.GetValue("EnableSystemCommand", "Defaults", "0") == "1") { return true; } } return false; } private void SetSystemCommandEnabled() { Ini ini = new Ini(Path.Combine(txtEqFolder.Text, "eqclient.ini")); ini.WriteValue("EnableSystemCommand", "Defaults", "1"); ini.Save(); } private bool IsEQFolderValid() { return File.Exists(Path.Combine(txtEqFolder.Text, "eqclient.ini")); } private bool IsEQValid() { // check eq folder if (String.IsNullOrEmpty(txtEqFolder.Text)) { MessageBox.Show("Pick your EQ folder first"); return false; } if (!IsEQFolderValid()) { MessageBox.Show("Unable to locate your EQ files, please check EQ folder"); return false; } // check toon/server for empty // check that a suitable toon/server combo exists if (!File.Exists(Path.Combine(txtEqFolder.Text, String.Format("{0}_{1}.ini", m_currentToon, m_currentServer)))) { MessageBox.Show("There is no ini file for that toon/server. Please check that the toon/server names are correct"); return false; } return true; } private void button1_Click_3(object sender, EventArgs e) { Program.SendLogsToServer(); } private void button2_Click_1(object sender, EventArgs e) { if (Program.UpdateGuildRoster(m_currentToon, m_currentServer)) { Program.SendLogsToServer(); Process.Start("http://fuworldorder.net/admin/raid/attendance.php"); } } private void button3_Click_1(object sender, EventArgs e) { if (Program.UpdateRaidAttendance(m_currentToon, m_currentServer)) { Program.SendLogsToServer(); Process.Start("http://fuworldorder.net/admin/raid/attendance.php"); } } private void button4_Click_1(object sender, EventArgs e) { float minutes; if (!float.TryParse(txtLootMinutes.Text, out minutes)) { MessageBox.Show("Bad loot minutes"); return; } if (Program.UpdateLoot(m_currentToon, m_currentServer, minutes)) { Program.SendLogsToServer(); Process.Start("http://fuworldorder.net/admin/loot/loot_assignments.php"); } } private void button5_Click_1(object sender, EventArgs e) { float minutes; if (!float.TryParse(txtLootLookupMinutes.Text, out minutes)) { MessageBox.Show("Bad loot minutes"); return; } Program.DoLootLookup(m_currentToon, m_currentServer, minutes, txtEqCharacter.Text); } private void button6_Click_1(object sender, EventArgs e) { Process.Start("explorer.exe", Path.Combine(Path.GetDirectoryName(AppPath), Program.LogFolder)); } private void btnBrowseEqFolder_Click(object sender, EventArgs e) { if (!String.IsNullOrEmpty(txtEqFolder.Text)) { eqFolderFinder.SelectedPath = txtEqFolder.Text; } if (eqFolderFinder.ShowDialog() == System.Windows.Forms.DialogResult.OK) { txtEqFolder.Text = eqFolderFinder.SelectedPath; } if (!IsEQFolderValid()) { MessageBox.Show("EQ folder seems invalid."); } } private void button7_Click(object sender, EventArgs e) { Process.Start("http://fuworldorder.net/admin/raid/attendance.php"); } private void button8_Click(object sender, EventArgs e) { Process.Start("http://fuworldorder.net/admin/loot/loot_assignments.php"); } private void button9_Click(object sender, EventArgs e) { Button showControls = (Button)sender; if (showControls.Text == "Show Test Buttons") { showControls.Text = "Hide Test Buttons"; this.Size = new Size(this.Size.Width, this.Size.Height + gbTesting.Height + gbTesting.Margin.Bottom + gbTesting.Margin.Top); } else { showControls.Text = "Show Test Buttons"; this.Size = new Size(this.Size.Width, this.Size.Height - gbTesting.Height - gbTesting.Margin.Bottom - gbTesting.Margin.Top); } } private void label1_Click(object sender, EventArgs e) { } private void button10_Click(object sender, EventArgs e) { string toonList = String.Join(",", FuEQ.GetToons()); MessageBox.Show(toonList); //MessageBox.Show(FuEQ.GetEQFolderForToon("havanap")); //FuEQ.SetEQFolderForToon(txtEqCharacter.Text, txtEqFolder.Text); } private void ConfigForm_Load(object sender, EventArgs e) { } private void button11_Click(object sender, EventArgs e) { List<string> toons = FuEQ.GetToons(); m_currentToon = txtEqCharacter.Text; m_currentServer = txtEqServer.Text; toons.Add(String.Format("{0} - {1}", m_currentServer, m_currentToon)); FuEQ.SetToons(toons); LoadConfig(); } private void label8_Click(object sender, EventArgs e) { } private void cmbToons_SelectedIndexChanged(object sender, EventArgs e) { ComboBox cmb = (ComboBox)sender; string[] toonBits = cmb.Items[cmb.SelectedIndex].ToString().Split(new string[] { " - " }, StringSplitOptions.None); if (toonBits.Length == 2) { if (m_currentServer != toonBits[0] || m_currentToon != toonBits[1]) { m_currentServer = toonBits[0]; m_currentToon = toonBits[1]; LoadConfig(); } } } } }
3c7f757cc65d7113e3a047bea5ea91de3e0f2b9b
[ "C#", "Text" ]
9
C#
jhpfraser/fu_raid_tool
65ffe30ddb760e780e8e40d27a9308a376474fb5
6a3c088c5698764de825341f589b358e799ee790
refs/heads/master
<file_sep>import { SecureStore } from "expo"; const auth0ClientId = "<KEY>"; const auth0Domain = "https://zombie-qr.auth0.com"; const audience = "https://www.zombie-qr-api.com"; const auth0ClientSecret = "<KEY>"; const login = async (username, password) => { const data = { method: "POST", body: JSON.stringify({ grant_type: "password", client_id: auth0ClientId, username, password, scope: "offline_access, openid", audience }), headers: { Accept: "application/json", "Content-Type": "application/json" } }; let res = await fetch(auth0Domain.concat("/oauth/token"), data); res = await res.json(); if (!res.error) { console.log(res.access_token); await SecureStore.setItemAsync("userToken", res.access_token); // await SecureStore.setItemAsync("refreshToken", res.refresh_token); } return res; }; const getUserToken = async () => { try { // Below function is used to retrieve token from asyncstorage, it returns a promise // const value = await AsyncStorage.getItem('userToken'); const value = await SecureStore.getItemAsync("userToken"); if (value !== null) { return value; } } catch (error) { console.log(error); } }; const logOut = async () => { try { await SecureStore.deleteItemAsync("userToken"); // await SecureStore.deleteItemAsync("refreshToken"); return true; } catch (error) { console.log(error); } }; const refreshUserToken = async () => { const refreshToken = await SecureStore.getItemAsync("refreshToken"); const data = { method: "POST", body: JSON.stringify({ grant_type: "refresh_token", client_id: auth0ClientId, client_secret: auth0ClientSecret, refresh_token: refreshToken }), headers: { Accept: "application/json", "Content-Type": "application/json" } }; let res = await fetch(auth0Domain.concat("/oauth/token"), data); res = await res.json(); if (!res.error) { console.log(res); await SecureStore.setItemAsync("userToken", res.access_token); } return res; }; export { login, getUserToken, logOut }; <file_sep>import React from "react"; import { Text, View, StyleSheet, TouchableOpacity } from "react-native"; export default class PlayedBeforeScreen extends React.Component { constructor(props) { super(props); } render() { return ( <View style={styles.container}> <Text style={styles.header}>Are you familliar with the concept of Z-QR</Text> <Text style={styles.header}>and would like to skip the information screen?</Text> <TouchableOpacity onPress={() => { this.props.navigation.navigate("App")}} style={styles.touchable}> <Text style={{color: 'white'}}>Yes</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { this.props.navigation.navigate("Info")}} style={styles.touchable}> <Text style={{color: 'white'}}>No</Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#221F1F" }, title: { fontSize: 24, color: "green" }, header: { fontSize: 18, color: "red" }, text: { fontSize: 12, color: "white" }, touchable: { padding: 10, margin: 10, backgroundColor: "#21AC1D", borderRadius: 5, width: 150, alignItems: "center", } });<file_sep>import React, { Component } from "react"; import PropTypes from "prop-types"; import { Text, View, StyleSheet, FlatList, Image } from "react-native"; import fetch from "react-native-fetch-polyfill"; import BodyTouchable from "./BodyTouchable"; import BodyModal from "./BodyModal"; import { getUserToken } from "../authorization/authorization"; export default class BodiesScreen extends Component { constructor() { super(); this.state = { bodies: null, display: false, selectedBody: null, token: null }; this.triggerModal = this.triggerModal.bind(this); this.showBodyDetail = this.showBodyDetail.bind(this); this.requestBody = this.requestBody.bind(this); } async componentDidMount() { this._sub = this.props.navigation.addListener("didFocus", () => { this.updateBodies(); }); this.setState({ token: await getUserToken() }); } componentDidUpdate() { if (this.state.bodies == null) { this.updateBodies(); } } triggerModal() { this.setState(prevState => { return { display: !prevState.display }; }); } async requestBody() { this.triggerModal(); this.props.navigation.navigate("Portfolio", { request: true, bodyId: this.state.selectedBody.id }); } updateBodies = async () => { console.log("updating bodies"); let token = this.state.token || (await getUserToken()); const reqSetting = { headers: new Headers({ Authorization: `Bearer ${token}` }), timeout: 1500 }; fetch("http://18.236.60.81/bodies", reqSetting) .then(res => res.json()) .then(data => { console.log(data); this.setState({ bodies: data }); }) .catch(err => { console.log(err); }); }; showBodyDetail(index) { this.setState({ selectedBody: this.state.bodies[index] }); this.triggerModal(); } render() { return ( <View style={styles.container}> <Image style={{ width: 100, height: 70, margin: 20 }} source={require("../assets/logo.png")} /> <Text style={styles.text}>Bodies:</Text> {this.state.bodies && ( <FlatList style={styles.text} data={this.state.bodies} keyExtractor={(item, index) => item.id} renderItem={({ item, index }) => ( <BodyTouchable name={item.name} onpress={this.showBodyDetail} bodyIndex={index} /> )} /> )} {this.state.selectedBody && ( <BodyModal body={this.state.selectedBody} display={this.state.display} onClose={this.triggerModal} onRequest={this.requestBody} /> )} </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#221F1F", paddingTop: "20%" }, text: { color: "white", fontSize: 30, marginBottom: 20 } }); <file_sep>import React, { Component } from "react"; import { Text, View, StyleSheet, TouchableOpacity } from "react-native"; export default class OpponentTouchable extends Component { constructor(props) { super(props); } render() { return ( <View style={styles.container}> <Text style={styles.text}>{this.props.name}</Text> <TouchableOpacity style={styles.touch} onPress={() => this.props.onpress(this.props.opponentIndex)}> <Text style={styles.text}> Attack </Text> </TouchableOpacity> </View> ); } } const styles = StyleSheet.create({ container: { flexDirection: "row", justifyContent: "flex-end" }, touch: { backgroundColor: "#21AC1D", width: 80, alignItems: "center", borderRadius: 5, marginBottom: 20, marginLeft: 20 }, text: { color: "white", fontSize: 23 } }); <file_sep>import React from "react"; import { StyleSheet, Text, View, ScrollView, Image, ListView, TouchableOpacity, Alert, AsyncStorage } from "react-native"; import { SecureStore } from "expo"; import QRCodeScannerModal from "./QRCodeScannerModal"; import { getUserToken, logOut } from "../authorization/authorization"; export default class AccountScreen extends React.Component { constructor(props) { super(props); this.state = { display: false, qrId: null }; this.triggerModal = this.triggerModal.bind(this); this.requestBody = this.requestBody.bind(this); } showJwt = async () => { const value = await getUserToken(); if (value !== null) { Alert.alert("User token", value); } }; triggerModal() { this.setState(prevState => { return { display: !prevState.display }; }); } onLogOut = async () => { try { await logOut(); this.props.navigation.navigate("Auth"); } catch (error) { console.log(error); } }; onRefreshToken = async () => { refreshUserToken(); }; async requestBody(bodyId) { console.log(bodyId); this.triggerModal(); this.props.navigation.navigate("Portfolio", { request: true, bodyId: bodyId }); } render() { return ( <View style={styles.container}> <Image style={{ width: 200, height: 120, margin: 40 }} source={require('../assets/logo.png')} /> <TouchableOpacity onPress={this.triggerModal} style={styles.touchable}> <Text style={{color: 'white'}}>Scan QR Code</Text> </TouchableOpacity> <TouchableOpacity onPress={this.onLogOut} style={styles.touchable}> <Text style={{color: 'white'}}>Log Out</Text> </TouchableOpacity> <TouchableOpacity onPress={() => { this.props.navigation.navigate("Info")}} style={styles.touchable}> <Text style={{color: 'white'}}>Guide</Text> </TouchableOpacity> <QRCodeScannerModal display={this.state.display} onClose={this.triggerModal} onScanned={this.requestBody} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, alignItems: "center", justifyContent: "center", backgroundColor: "#221F1F" }, touchable: { padding: 10, margin: 10, backgroundColor: "#21AC1D", borderRadius: 5, width: 150, alignItems: "center", } }); <file_sep>import React, { Component } from "react"; import PropTypes from "prop-types"; import { Text, View, StyleSheet, Alert, Image } from "react-native"; import fetch from "react-native-fetch-polyfill"; import ClaimBodyModal from "./ClaimBodyModal"; import { getUserToken } from "../authorization/authorization"; export default class PortfolioScreen extends Component { constructor() { super(); this.state = { userZombie: null, requestBody: null, display: false, token: null }; this.triggerModal = this.triggerModal.bind(this); this.confirmClaim = this.confirmClaim.bind(this); } async componentDidMount() { this._sub = this.props.navigation.addListener("didFocus", () => { // console.log(this.props.navigation.getParam("bodyId", null)); if (this.props.navigation.getParam("bodyId", null) != null) { this.getBodyInfo(this.props.navigation.getParam("bodyId", null)); this.props.navigation.state.params = null; } else { this.updateZombie(); } }); this.setState({ token: await getUserToken() }); } componentDidUpdate() { if (this.state.userZombie == null) { this.updateZombie(); } } triggerModal() { this.setState(prevState => { return { display: !prevState.display }; }); } getBodyInfo = async id => { let token = this.state.token || (await getUserToken()); console.log("getbodyinfo", id); const reqSetting = { headers: new Headers({ Authorization: `Bearer ${token}` }), timeout: 1500 }; fetch(`http://18.236.60.81/body/${id}`, reqSetting) .then(res => res.json()) .then(data => { console.log("bodyinfoget", JSON.stringify(data)); if (!data.err) { this.setState({ requestBody: data }); this.triggerModal(); } else { console.log("failed"); Alert.alert("Failed", data.err); } }) .catch(err => { console.log(err); }); }; updateZombie = async () => { let token = this.state.token || (await getUserToken()); console.log(token); const reqSetting = { headers: new Headers({ Authorization: `Bearer ${token}` }), timeout: 1500 }; fetch("http://18.236.60.81", reqSetting) .then(res => res.json()) .then(data => { console.log(data); this.setState({ userZombie: data }); }) .catch(err => { console.log(err); }); }; async confirmClaim() { let token = this.state.token || (await getUserToken()); console.log(this.state.requestBody.id); const reqSetting = { method: "post", body: JSON.stringify({ bodyId: this.state.requestBody.id }), headers: new Headers({ Authorization: `Bearer ${token}`, "Content-Type": "application/json" }), timeout: 1500 }; fetch(`http://18.236.60.81/body`, reqSetting) .then(res => res.json()) .then(data => { console.log("confirm", JSON.stringify(data)); this.triggerModal(); this.setState({ requestBody: null, userZombie: null }); }) .catch(err => { console.log(err); }); } render() { return ( <View style={styles.container}> {this.state.userZombie && ( <View> <Text style={styles.text}>Name: {this.state.userZombie.name}</Text> <Text style={styles.hp}>HP: {this.state.userZombie.health}</Text> <Text style={styles.attack}> Attack: {this.state.userZombie.attack} </Text> <Text style={styles.defense}> Defense: {this.state.userZombie.defense} </Text> <Text style={styles.speed}> Speed: {this.state.userZombie.speed} </Text> </View> )} {this.state.requestBody && ( <ClaimBodyModal body={this.state.requestBody} display={this.state.display} onClose={this.triggerModal} onConfirm={this.confirmClaim} /> )} <Image style={styles.zombie} source={require("../assets/zombie.png")} /> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", backgroundColor: "#221F1F" }, text: { color: "white", fontSize: 20, margin: 10, fontWeight: "bold", backgroundColor: "#4A4D50", height: 50, textAlignVertical: "center", borderRadius: 10, padding: 5 }, hp: { color: "#21AC1D", fontSize: 30, margin: 10, fontWeight: "bold" }, attack: { color: "#E50914", fontSize: 30, margin: 10, fontWeight: "bold" }, defense: { color: "#F6F603", fontSize: 30, margin: 10, fontWeight: "bold" }, speed: { color: "#2586E8", fontSize: 30, margin: 10, fontWeight: "bold" }, zombie: { position: "absolute", width: 100, height: 300, right: 0, top: 100 } }); <file_sep>import React from "react"; import { Modal, View, Image, Text, StyleSheet, TouchableOpacity } from "react-native"; const ClaimBodyModal = props => ( <Modal visible={props.display} animationType='slide' onRequestClose={() => console.log("closed")}> <View style={styles.modal}> <Text style={styles.text}>Name: {props.body.name}</Text> <Text style={styles.hp}>HP: {props.body.health}</Text> <Text style={styles.attack}>Attack: {props.body.attack}</Text> <Text style={styles.defense}>Defense: {props.body.defense}</Text> <Text style={styles.speed}>Speed: {props.body.speed}</Text> <View style={styles.buttonsContainer}> <TouchableOpacity style={styles.touch} onPress={props.onConfirm}> <Text style={styles.buttonText}>Take Over</Text> </TouchableOpacity> <TouchableOpacity style={styles.touch} onPress={props.onClose}> <Text style={styles.buttonText}>Close</Text> </TouchableOpacity> </View> </View> </Modal> ); const styles = StyleSheet.create({ modal: { flex: 1, justifyContent: "center", backgroundColor: "#221F1F", paddingTop: 40 }, text: { color: "white", fontSize: 20, margin: 10, fontWeight: "bold", backgroundColor: "#4A4D50", height: 50, textAlignVertical: "center", borderRadius: 10, padding: 5 }, hp: { color: "#21AC1D", fontSize: 30, margin: 10, fontWeight: "bold" }, attack: { color: "#E50914", fontSize: 30, margin: 10, fontWeight: "bold" }, defense: { color: "#F6F603", fontSize: 30, margin: 10, fontWeight: "bold" }, speed: { color: "#2586E8", fontSize: 30, margin: 10, fontWeight: "bold" }, zombie: { position: "absolute", width: 100, height: 300, right: 0, top: 100 }, button: { margin: 20 }, touch: { backgroundColor: "#21AC1D", width: 160, alignItems: "center", borderRadius: 5, marginBottom: 20, padding: 5 }, buttonText: { color: "white", fontSize: 25 }, buttonsContainer: { flex: 1, justifyContent: "center", alignItems: "center" } }); export default ClaimBodyModal; <file_sep>import React from "react"; import { createSwitchNavigator, createBottomTabNavigator, createStackNavigator, createAppContainer } from "react-navigation"; import TabIcon from "./components/TabIcon"; import PortfolioScreen from "./components/PortfolioScreen"; import BattleScreen from "./components/BattleScreen"; import BodiesScreen from "./components/BodiesScreen"; import LoginScreen from "./components/LoginScreen"; import SignUpScreen from "./components/SignUpScreen"; import AccountScreen from "./components/AccountScreen"; import PlayedBeforeScreen from "./components/PlayedBeforeScreen"; import InformationScreen from "./components/InformationScreen"; const tabNavigatorSettings = { Portfolio: { screen: PortfolioScreen }, Battle: { screen: BattleScreen }, Bodies: { screen: BodiesScreen }, Account: { screen: AccountScreen } }; const TabNavigator = createBottomTabNavigator(tabNavigatorSettings, { defaultNavigationOptions: ({ navigation }) => ({ tabBarIcon: ({ focused, horizontal, tintColor }) => { const { routeName } = navigation.state; let iconName; if (routeName === "Portfolio") { iconName = "portfolio"; } else if (routeName === "Battle") { iconName = "battle"; } else if (routeName === "Bodies") { iconName = "bodies"; } else if (routeName === "Account") { iconName = "account"; } return <TabIcon icon={iconName} />; } }), tabBarOptions: { activeTintColor: "red", inactiveTintColor: "white", style: { backgroundColor: "green" } } }); const AppNavigator = createStackNavigator( { App: TabNavigator }, { headerMode: "none", navigationOptions: { headerVisible: false } } ); const AuthNavigator = createStackNavigator( { SignIn: LoginScreen, SignUp: SignUpScreen }, { headerMode: "none", navigationOptions: { headerVisible: false } } ); const SwitchNavigator = createSwitchNavigator( { Auth: AuthNavigator, App: AppNavigator, Ask: PlayedBeforeScreen, Info: InformationScreen }, { initialRouteName: "Auth" } ); const Contain = createAppContainer(SwitchNavigator); export default class App extends React.Component { static navigationOptions = { headerStyle: { backgroundColor: "#f4511e" }, headerTintColor: "#fff", headerTitleStyle: { fontWeight: "bold" } }; render() { return <Contain />; } } <file_sep>import React, { Component } from "react"; import PropTypes from "prop-types"; import { Dimensions, Modal, View, StyleSheet, Image, Text } from "react-native"; import * as Animatable from "react-native-animatable"; const WIDTH = Dimensions.get("window").width; const HEIGHT = Dimensions.get("window").height; export default class ZQRAnimate extends Component { constructor(props) { super(props); this.state = {}; } componentDidMount() { let timer = setTimeout(() => { this.props.onClose(); }, 15000); } render() { let props = this.props; return ( <Modal visible={props.display} animationType='none' onRequestClose={() => console.log("closed")}> <View style={styles.container}> <Animatable.View style={styles.blackground} animation={"fadeIn"} /> <Animatable.Image delay={1500} animation={{ from: { translateY: 800 }, to: { translateY: 0 } }} style={styles.fire} source={{ uri: "https://i.pinimg.com/originals/f3/ff/b2/f3ffb2d584f09068aee6e9360dc13b34.gif" }} /> <Animatable.View style={styles.fight} animation='fadeOutUp' delay={1500}> <Animatable.Image animation='lightSpeedIn' source={require("../assets/fight.png")} /> </Animatable.View> <Animatable.View animation={{ from: { translateX: -100 }, to: { translateX: 0 } }} style={styles.bZombie} delay={1500}> <Animatable.Image animation={{ 0: { translateX: 0, translateY: 20, rotate: "0deg" }, 0.5: { translateX: 80, translateY: 0, rotate: "35deg" }, 1: { translateX: 0, translateY: 20, rotate: "0deg" } }} iterationCount='infinite' useNativeDriver direction='alternate' style={styles.zombie} delay={3500} source={{ uri: "https://i.pinimg.com/originals/c9/3c/1a/c93c1a497abc17384fd5996ca7a671a5.gif" }} /> </Animatable.View> <Animatable.View style={styles.bHuman} animation={{ from: { translateX: 200 }, to: { translateX: 0 } }} delay={1500}> <Animatable.Image animation={{ 0: { translateX: 0, translateY: 20, rotate: "0deg" }, 0.33: { translateX: -80, translateY: 0, rotate: "-35deg" }, 0.66: { translateX: 80, translateY: 0, rotate: "35deg" }, 1: { translateX: 0, translateY: 20, rotate: "0deg" } }} iterationCount='infinite' useNativeDriver direction='alternate' style={styles.zombie} delay={3500} style={styles.human} source={{ uri: "https://cdn.vox-cdn.com/uploads/chorus_asset/file/3691834/terry-2x.0.gif" }} /> </Animatable.View> <Animatable.View style={styles.HZombie} animation='fadeIn' delay={1500}> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={15000} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={9500} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={8000} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={7500} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={6000} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={5000} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={4000} /> </Animatable.View> <Animatable.View style={styles.HHuman} animation='fadeIn' delay={1500}> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={15000} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={9800} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={8500} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={7500} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={6300} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={5200} /> <Animatable.View style={styles.HZbar} animation='fadeIn' delay={4100} /> </Animatable.View> <Animatable.View style={{ position: "absolute", top: 0, left: 0 }} animation='fadeIn' delay={11500}> <Animatable.View style={styles.bang} animation={{ from: { width: 100, height: 100, translateX: 110, translateY: 280 }, to: { width: WIDTH, height: HEIGHT, translateX: 0, translateY: 0 } }} duration={500} delay={10000}> <Image style={{ flex: 1 }} source={{ uri: "https://data.whicdn.com/images/298116765/original.gif" }} /> </Animatable.View> </Animatable.View> <Animatable.View style={{ position: "absolute", width: WIDTH, height: HEIGHT, top: 0, backgroundColor: "black" }} animation='bounceIn' delay={13800} /> </View> </Modal> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: "center", alignItems: "center" }, fight: { paddingTop: 500 }, fire: { width: "100%", height: 700, position: "absolute", top: 0, left: 0 }, blackground: { position: "absolute", top: 0, left: 0, backgroundColor: "black", width: 400, height: 1000 }, zombie: { width: 150, height: 200 }, human: { width: 150, height: 200 }, bZombie: { position: "absolute", left: -30, top: 200 }, bHuman: { position: "absolute", right: 0, top: 200 }, HZombie: { flexDirection: "row", position: "absolute", top: 150, left: 10, width: 150, height: 30, backgroundColor: "green", borderWidth: 1, borderColor: "white" }, HHuman: { flexDirection: "row", position: "absolute", top: 150, right: 10, width: 150, height: 30, backgroundColor: "green", borderWidth: 1, borderColor: "white" }, HZbar: { flex: 1, backgroundColor: "red" }, bang: { position: "absolute", top: 0, left: 0, width: 0, height: 0, borderRadius: 20 } }); <file_sep>import React from "react"; import { StyleSheet, Text, View, Dimensions, Alert, StatusBar, Modal } from "react-native"; import { BarCodeScanner, Permissions } from "expo"; export default class QRCodeScannerModal extends React.Component { state = { hasCameraPermission: null, scanSuccess: false }; async componentDidMount() { const { status } = await Permissions.askAsync(Permissions.CAMERA); this.setState({ hasCameraPermission: status === "granted" }); } cancelAlert() { Alert.alert("Would you like to finish scanning?"); } render() { const { hasCameraPermission } = this.state; return ( <Modal visible={this.props.display} animationType='slide' onRequestClose={() => console.log("closed")}> <BarCodeScanner onBarCodeRead={e => { if (this.scanSuccess) { return; } else { this.props.onScanned(e.data); } }} style={[StyleSheet.absoluteFill, styles.container]}> <StatusBar barStyle='light-content' /> <View style={styles.layerTop}> <Text style={styles.description}>Scan QR code</Text> </View> <View style={styles.layerCenter}> <View style={styles.layerLeft} /> <View style={styles.focused} /> <View style={styles.layerRight} /> </View> <View style={styles.layerBottom}> <Text onPress={() => this.props.onClose()} style={styles.cancel}> Cancel </Text> </View> </BarCodeScanner> </Modal> ); } handleBarCodeScanned = ({ data }) => { Alert.alert("data: " + data); }; } const bgColor = "rgba(0, 0, 0, .6)"; const styles = StyleSheet.create({ container: { flex: 1, flexDirection: "column" }, layerTop: { flex: 1, backgroundColor: bgColor }, layerCenter: { flex: 1, flexDirection: "row" }, layerLeft: { flex: 1, backgroundColor: bgColor }, focused: { flex: 3 }, layerRight: { flex: 1, backgroundColor: bgColor }, layerBottom: { flex: 1, backgroundColor: bgColor }, description: { fontSize: 25, marginTop: "40%", textAlign: "center", color: "#fff" }, cancel: { fontSize: 20, textAlign: "center", color: "#fff", marginTop: "30%" } }); <file_sep>import React from "react"; import { Image, StyleSheet, Text, View } from "react-native"; const icons = { portfolio: { imgName: "portfolio", uri: require("../assets/icons/portfolio.png") }, battle: { imgName: "battle", uri: require("../assets/icons/battle.png") }, bodies: { imgName: "bodies", uri: require("../assets/icons/bodies.png") }, account: { imgName: "account", uri: require("../assets/icons/account.png") } }; export default class TabIcon extends React.Component { constructor(props) { super(props); } render() { const iconName = this.props.icon; return ( <Image style={{ marginTop: 5, width: 26, height: 30 }} source={icons[iconName].uri} /> ); } }
2207e1be3a08e30b505a3595977334a8994126a3
[ "JavaScript" ]
11
JavaScript
Team-z-url/zqr
2f139b21087fa5d4b5e2e06ffb170a4e5d7487ee
4c12f18d5151740bf451f007eacaca0553e0ef73
refs/heads/master
<file_sep>//We're going to create the JS for a basic quiz application. //Let's think about the nature of this quiz app first. We're going to be creating lots of user objects, and we're //also going to be creating lots of Question objects. Those would make two perfectly good constructors. //Create a User constructor that accepts name, email, password, and totalScore parameters and set them appropriatly //code here var User = function(name, email, password, totalScore){ this.name = name; this.email = email; this.password = <PASSWORD>; this.totalScore = totalScore; } //Create a Question constructor that accepts title, answersArray, rightAnswer, and difficulty parameters //code here var Question = function(title, answersArray, rightAnswer, difficulty){ this.title = title; this.answersArray = answersArray; this.rightAnswer = rightAnswer; this.difficulty = difficulty; } //Create a users Array which is going to hold all of our users. //code here var users = []; //Let's say three people signed up for our service, create 3 instances of User and add each to the users Array //code here users.push(new User('jason', '<EMAIL>', '1234', 4), new User('Brian', '<EMAIL>', '5678', 5), new User('Spanky', '<EMAIL>', '9876', 7)); //Create a questions Array which is going to hold all of our questions //code here var questions = []; //Now, let's say we wanted to create a quiz about JavaScript. Create three instances of Question which contain the following data //title: 'T/F: Inheritance is achieved in JavaScript through Prototypes?' //title: 'T/F: JavaScript is just a scripting version of Java' //title: "T/F: In Javascript, == doesn't check 'type' but just the value - where === checks type and value" //Fill in the rest of the required data as you see appropriate. //code here questions.push(new Question('T/F', 'Inheritance is achieved in JavaScript through Prototypes?', 'T', 'Hard'), new Question('T/F', 'JavaScript is just a scripting version of Java', 'F', 'medium'), new Question('T/F', 'In Javascript, == doesn\'t check \'type\' but just the value - where === checks type and value', 'T', 'easy')); //Now push all of your instances of Question into the questions Array //done above console.log('My users Array and my questions array are ...'); //Now loop console.log your users array and your questions array and verify that they're both holding the right data. //code here for (var i = 0; i < users.length; i++){ for (var key in users[i]){ console.log(key + ': ' + users[i][key]); } } for (var i = 0; i < questions.length; i++){ for (var key in questions[i]){ console.log(key + ': ' + questions[i][key]); } }<file_sep>//Create a Person constructor that accepts name and age as parameters and sets those properties accordingly in the Constructor. //code here var Person = function(name, age){ this.name = name; this.age = age; } //Now create three instances of Person with data you make up //code here var user1 = new Person('Brian', 43); var user2 = new Person('Homer', 45); var user3 = new Person('James', 24); //Now add a sayName method on your Person class that will alert the name of whatever Person instance called it. //code here Person.prototype.sayName = function(){ alert(this.name); }
305002ebb1f4b0acd660e7cc9206f22d9b1132f5
[ "JavaScript" ]
2
JavaScript
briknelson/ConstructorConductor
7fad93f18165713c0df30c42c3a5a2af49b2644f
d9becf40fca7870ed78f9ff54c1df26d37bb2bc9
refs/heads/master
<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VSModeManager : MonoBehaviour { byte win_or_lose = 0; //1이면 win, 2면 lose public static VSModeManager instance; byte loser_ID; public RawImage winner_image; public RawImage loser_image; public RawImage draw_image; public GameObject m_Option_UI; public GameObject[] m_turtle = new GameObject[4]; public GameObject m_Direction_Camera; public GameObject kick_notice; bool m_isClicked = false; public bool game_set; public Text time_Text; public Text m_GetItemText; public RawImage m_GetItemBackground; // 아이템 획득시 출력 이미지 public RawImage m_GetItemImage; // 아이템 획득시 출력 이미지 public Animator m_GetItem_Animator; // 아이템 획득 UI 애니메이터 public Texture m_Bomb_Icon; public Texture m_Fire_Icon; public Texture m_Speed_Icon; public Texture m_Kick_Icon; public Texture m_Throw_Icon; public Texture m_Glider_Icon; public Texture m_Airdrop_icon; float time; void Awake() { instance = this; } // Use this for initialization void Start() { Screen.SetResolution(1280, 720, true); m_Direction_Camera.GetComponentInChildren<Camera_Directing_Net>().Direction_Play(DIRECTION_NUMBER.INTRO_NORMAL_1); time = 60.0f; win_or_lose = 0; game_set = false; GetItemUI_Deactivate(); for (byte i = 0; i < 4; ++i) { if (i == VariableManager.instance.pos_inRoom - 1) { m_turtle[i].SetActive(true); } } m_turtle[0].transform.position = new Vector3(0.0f, -0.35f, 0.0f); m_turtle[1].transform.position = new Vector3(28.0f, -0.35f, 0.0f); m_turtle[2].transform.position = new Vector3(0.0f, -0.35f, 28.0f); m_turtle[3].transform.position = new Vector3(28.0f, -0.35f, 28.0f); } public void Kick_By_Server() { kick_notice.SetActive(true); } public void OutByServer() { SceneChange.instance.DisConnect(); } void GetItemUI_Deactivate() { m_GetItem_Animator.SetBool("is_Got_Item", false); m_GetItemBackground.gameObject.SetActive(false); m_GetItemText.gameObject.SetActive(false); m_GetItemImage.gameObject.SetActive(false); } public void isClicked() { m_isClicked = true; } public void isClickedOff() { m_isClicked = false; } public void OptionOn() { m_Option_UI.SetActive(true); } public void OptionOff() { m_Option_UI.SetActive(false); } public bool Get_isClicked() { return m_isClicked; } public void GameOver_Set(byte id, byte loserid) { if (Turtle_Move.instance.GetId() == id) { loser_ID = loserid; win_or_lose = 1; game_set = true; } else if (id == 4) { win_or_lose = 3; game_set = true; } else { win_or_lose = 2; game_set = true; } } void WinnerSet() { winner_image.gameObject.SetActive(true); } public void ChangeTime(float a) { time = a; //Debug.Log("Time" + (time)); } // Update is called once per frame void Update() { time = VariableManager.instance.m_time; if (time < 0) time = 0; if (time % 60 >= 10) time_Text.text = "0" + (int)time / 60 + ":" + (int)time % 60; else time_Text.text = "0" + (int)time / 60 + ":0" + (int)time % 60; if (win_or_lose == 1) { //Performance_Network.instance.DeadAnimation(loser_ID); Invoke("WinnerSet", 0.3f); win_or_lose = 0; //Debug.Log("Win!!!!!!"); //Time.timeScale = 0; } else if (win_or_lose == 2) { loser_image.gameObject.SetActive(true); win_or_lose = 0; //Debug.Log("Lose!!!!!!"); //Time.timeScale = 0; } else if (win_or_lose == 3) { draw_image.gameObject.SetActive(true); win_or_lose = 0; } } public void GetItemUI_Activate(int Item_Num) { switch (Item_Num) { case 0: m_GetItemText.text = "Bomb Up !"; m_GetItemImage.texture = m_Bomb_Icon; break; case 1: m_GetItemText.text = "Fire Up !"; m_GetItemImage.texture = m_Fire_Icon; break; case 2: m_GetItemText.text = "Speed Up !"; m_GetItemImage.texture = m_Speed_Icon; break; case 3: m_GetItemText.text = "Kick Activated !"; m_GetItemImage.texture = m_Kick_Icon; break; case 4: m_GetItemText.text = "Throw Activated !"; m_GetItemImage.texture = m_Throw_Icon; break; case 5: m_GetItemText.text = "Get Glider !!"; m_GetItemImage.texture = m_Glider_Icon; break; case 6: m_GetItemText.text = "You've Got AirDrop !!"; m_GetItemImage.texture = m_Airdrop_icon; break; } //Stat_UI_Management(); // 스탯 갱신 m_GetItemBackground.gameObject.SetActive(true); m_GetItemText.gameObject.SetActive(true); m_GetItemImage.gameObject.SetActive(true); m_GetItem_Animator.SetBool("is_Got_Item", true); Invoke("GetItemUI_Deactivate", 1.4f); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Image_Fade : MonoBehaviour { float m_Wait_Time_Before_Fade = 0.15f; float m_WaitTime = 0.0f; bool m_is_wait_Over = false; float m_FadeSpeed = 1200.0f; float m_Curr_Fading_Time = 0.0f; float m_Dest_Fading_Time = 1.0f; void Update() { if (m_is_wait_Over) { // 3. 슬라이더 이동 if (m_Curr_Fading_Time <= m_Dest_Fading_Time) { m_Curr_Fading_Time += Time.deltaTime; transform.GetComponent<RectTransform>().sizeDelta += new Vector2(m_FadeSpeed * m_Curr_Fading_Time, m_FadeSpeed * m_Curr_Fading_Time * 0.7f); } // 4. 이동이 끝나면 비활성화 else { gameObject.SetActive(false); } } else { // 1. 일정시간 대기 if (m_WaitTime < m_Wait_Time_Before_Fade) m_WaitTime += Time.deltaTime; // 2. 대기 종료 else m_is_wait_Over = true; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class GameOver_UI : MonoBehaviour { Animation m_Animations; void Start () { m_Animations = GetComponent<Animation>(); gameObject.SetActive(false); } public void GameOver_Direction_Play() { m_Animations.Play(m_Animations.GetClip("Game_Over_Direction").name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Rock : MonoBehaviour { int index; void Start() { // 최초 시작 시 자신의 위치의 isBlocked를 true로 갱신 index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); StageManager.GetInstance().Update_MCL_isBlocked(index, true); } void OnDestroy() { // MCL 갱신 StageManager.GetInstance().Update_MCL_isBlocked(index, false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Front_Collider : MonoBehaviour { Player m_Player; void Start() { m_Player = transform.parent.GetComponent<Player>(); } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Bomb")) { m_Player.Set_is_Able_to_Kick(true); } } void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("Box")) { Vector3 tmpPosition; tmpPosition = other.gameObject.transform.position + transform.forward * 1.2f; int index = StageManager.GetInstance().Find_Own_MCL_Index(tmpPosition.x, tmpPosition.z); if (index != -1) { if (StageManager.GetInstance().Get_MCL_index_is_Blocked(index) == false) { m_Player.Set_Front_Box(other.gameObject); if (other.GetComponent<Box>() == null) other.GetComponent<Box_None_Item>().Save_Player_Front_Collider(gameObject); other.GetComponent<Box>().Save_Player_Front_Collider(gameObject); m_Player.Set_is_Box_Selected(true); m_Player.Set_is_Able_to_Push(true); UI.GetInstance().Push_Button_Management(true); } else { m_Player.Set_Front_Box(null); other.GetComponent<Box>().Clear_Player_Front_Collider(); m_Player.Set_is_Box_Selected(false); m_Player.Set_is_Able_to_Push(false); UI.GetInstance().Push_Button_Management(false); } } } } void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Bomb")) { m_Player.Set_is_Able_to_Kick(false); } // 박스와 접촉 해제시 밀기 비활성화 if (m_Player.Get_is_Box_Selected() && other.gameObject.CompareTag("Box")) { m_Player.Set_is_Box_Selected(false); m_Player.Set_is_Able_to_Push(false); UI.GetInstance().Push_Button_Management(false); } } public void TriggerExit_Ver2() { m_Player.Set_is_Box_Selected(false); m_Player.Set_is_Able_to_Push(false); UI.GetInstance().Push_Button_Management(false); } } <file_sep>#pragma once #include "stdafx.h" class TB_Server { public: TB_Server(); ~TB_Server(); void err_quit(char*); void err_display(char*); void Bind_Server(); void Receive_User(); static DWORD WINAPI Process_ServerP(LPVOID param) { TB_Server* objs = new TB_Server(); return objs->Process_Server(param); }; DWORD WINAPI Process_Server(LPVOID); //void Destory_Sockets(); private: SOCKET start_sock; SOCKET accept_sock; SOCKET client_sock; int addrlen; SOCKADDR_IN server_addr; SOCKADDR_IN client_addr; HANDLE hThread; int user_count; }; <file_sep>using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI; public class MapManager : MonoBehaviour { public static MapManager instance; public GameObject m_bomb; public GameObject m_box; public GameObject m_rock; public GameObject m_flame_effect; public GameObject m_bush; public GameObject m_item_speed; public GameObject m_item_bomb; public GameObject m_item_fire; public Text g_text; public GameObject[] m_turtle = new GameObject[4]; byte[] bombexplode_list = new byte[225]; GameObject[] bomb_list = new GameObject[225]; GameObject[] box_list = new GameObject[225]; GameObject[] rock_list = new GameObject[225]; GameObject[] bush_list = new GameObject[225]; GameObject[] item_s_list = new GameObject[225]; GameObject[] item_f_list = new GameObject[225]; GameObject[] item_b_list = new GameObject[225]; byte[] copy_map_info = new byte[225]; private void Awake() { instance = this; } // Use this for initialization void Start () { for(byte i = 0; i < 4; ++i) { if (i==VariableManager.instance.pos_inRoom-1) m_turtle[i].SetActive(true); } for(int z = 0; z < 15; ++z) { for(int x = 0; x < 15; ++x) { bomb_list[(z * 15) + x] = Instantiate(m_bomb); bomb_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); bomb_list[(z * 15) + x].SetActive(false); box_list[(z * 15) + x] = Instantiate(m_box); box_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); box_list[(z * 15) + x].SetActive(false); rock_list[(z * 15) + x] = Instantiate(m_rock); rock_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); rock_list[(z * 15) + x].SetActive(false); bush_list[(z * 15) + x] = Instantiate(m_bush); bush_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); bush_list[(z * 15) + x].SetActive(false); item_s_list[(z * 15) + x] = Instantiate(m_item_speed); item_s_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); item_s_list[(z * 15) + x].SetActive(false); item_f_list[(z * 15) + x] = Instantiate(m_item_fire); item_f_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); item_f_list[(z * 15) + x].SetActive(false); item_b_list[(z * 15) + x] = Instantiate(m_item_bomb); item_b_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); item_b_list[(z * 15) + x].SetActive(false); bombexplode_list[(z * 15) + x] = 0; } } StartCoroutine("CheckMap_v2"); } public void Set_Bomb(int x, int z) { bomb_list[((z * 15) + x)].SetActive(true); } public void Check_Map(byte[] mapinfo) { Buffer.BlockCopy(mapinfo, 2, copy_map_info, 0, 225); } public void Initialize_Map(byte[] mapinfo) { for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { byte Tile_Info2 = mapinfo[(z * 15) + (x)]; switch (Tile_Info2) { case 1: //Bomb if (!bomb_list[(z * 15) + (x)].activeInHierarchy) bomb_list[(z * 15) + (x)].SetActive(true); break; case 2: //Nothing //Debug.Log("Nothing:" + x+","+y); break; case 3: //Cube(Box)로 if (!box_list[(z * 15) + (x)].activeInHierarchy) box_list[(z * 15) + (x)].SetActive(true); break; case 4: //Rock if (!rock_list[(z * 15) + (x)].activeInHierarchy) rock_list[(z * 15) + (x)].SetActive(true); break; case 5: //Item_Bomb if (!item_b_list[(z * 15) + (x)].activeInHierarchy) item_b_list[(z * 15) + (x)].SetActive(true); break; default: break; } } } } public void Explode_Bomb(int x, int z, byte f) { //Explode(f, bomb_list[((z * 15) + x)]); bombexplode_list[((z * 15) + x)] = f; } public bool Check_BombSet(int x, int z) { if(bomb_list[((z * 15) + x)].activeInHierarchy) return true; else return false; } void Explode(byte fire_power,GameObject bomb) { GameObject Instance_FlameDir_N; GameObject Instance_FlameDir_S; GameObject Instance_FlameDir_W; GameObject Instance_FlameDir_E; GameObject Instance_FlameDir_M; Instance_FlameDir_M = Instantiate(m_flame_effect); Instance_FlameDir_M.transform.position = new Vector3(bomb.transform.position.x, 0.0f, bomb.transform.position.z ); for (byte i = 0; i < fire_power; ++i) { Instance_FlameDir_N = Instantiate(m_flame_effect); Instance_FlameDir_N.transform.position = new Vector3(bomb.transform.position.x, 0.0f, bomb.transform.position.z + (2.0f * (i + 1))); Instance_FlameDir_S = Instantiate(m_flame_effect); Instance_FlameDir_S.transform.position = new Vector3(bomb.transform.position.x, 0.0f, bomb.transform.position.z - (2.0f * (i + 1))); Instance_FlameDir_W = Instantiate(m_flame_effect); Instance_FlameDir_W.transform.position = new Vector3(bomb.transform.position.x - (2.0f * (i + 1)), 0.0f, bomb.transform.position.z); Instance_FlameDir_E = Instantiate(m_flame_effect); Instance_FlameDir_E.transform.position = new Vector3(bomb.transform.position.x + (2.0f * (i + 1)), 0.0f, bomb.transform.position.z); } bomb.SetActive(false); } // Update is called once per frame void Update () { g_text.text = "Player1 x :" + NetTest.instance.GetNetPosx(0) + ", z :" + NetTest.instance.GetNetPosz(0) + "\nPlayer2 x :" + NetTest.instance.GetNetPosx(1) + ", z:" + NetTest.instance.GetNetPosz(1) + "\nPlayer3 x :" + NetTest.instance.GetNetPosx(2) + ", z:" + NetTest.instance.GetNetPosz(2) + "\nPlayer4 x :" + NetTest.instance.GetNetPosx(3) + ", z:" + NetTest.instance.GetNetPosz(3); } public void GotoRoom() { Time.timeScale = 1; Debug.Log("Go to Room"); SceneChange.instance.GoTo_ModeSelect_Scene(); } public void GotoLobby() { Time.timeScale = 1; Debug.Log("Go to GotoLobby"); NetTest.instance.SendOUTPacket(); SceneChange.instance.GoTo_Wait_Scene(); } IEnumerator CheckMap_v2() { for (;;) { for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { byte Tile_Info2 = VariableManager.instance.copy_map_info[(z * 15) + (x)]; switch (Tile_Info2) { case 1: //Bomb if(!bomb_list[(z * 15) + (x)].activeInHierarchy) { bomb_list[(z * 15) + (x)].SetActive(true); //Debug.Log("Made Bomb"); } else if (bombexplode_list[(z * 15) + (x)] != 0) { Explode(bombexplode_list[(z * 15) + (x)], bomb_list[((z * 15) + x)]); bombexplode_list[(z * 15) + (x)] = 0; } break; case 2: //Nothing //Debug.Log("Nothing:" + x+","+y); if (bombexplode_list[(z * 15) + (x)] != 0) { Explode(bombexplode_list[(z * 15) + (x)], bomb_list[((z * 15) + x)]); bombexplode_list[(z * 15) + (x)] = 0; } box_list[(z * 15) + (x)].SetActive(false); rock_list[(z * 15) + (x)].SetActive(false); item_b_list[(z * 15) + (x)].SetActive(false); bush_list[(z * 15) + (x)].SetActive(false); item_s_list[(z * 15) + (x)].SetActive(false); item_f_list[(z * 15) + (x)].SetActive(false); break; case 3: //Cube(Box)로 if (!box_list[(z * 15) + (x)].activeInHierarchy) box_list[(z * 15) + (x)].SetActive(true); break; case 4: //Rock if (!rock_list[(z * 15) + (x)].activeInHierarchy) rock_list[(z * 15) + (x)].SetActive(true); break; case 5: //Item_Bomb box_list[(z * 15) + (x)].SetActive(false); if (!item_b_list[(z * 15) + (x)].activeInHierarchy) item_b_list[(z * 15) + (x)].SetActive(true); break; case 6: if (!bush_list[(z * 15) + (x)].activeInHierarchy) bush_list[(z * 15) + (x)].SetActive(true); break; case 7: box_list[(z * 15) + (x)].SetActive(false); if (!item_f_list[(z * 15) + (x)].activeInHierarchy) item_f_list[(z * 15) + (x)].SetActive(true); break; case 8: box_list[(z * 15) + (x)].SetActive(false); if (!item_s_list[(z * 15) + (x)].activeInHierarchy) item_s_list[(z * 15) + (x)].SetActive(true); break; default: //rock_list[(z * 15) + (x)].SetActive(true); break; } } } yield return new WaitForSeconds(0.1f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Performance_Network : MonoBehaviour { public Camera m_PlayerView; public Camera m_PerformanceView; public Camera[] m_OtherPlayerView; public Animator[] m_OtherPlayerAnimator; public static Performance_Network instance; public Animator m_CameraAnimator; public bool ani_is_working; // Use this for initialization void Awake() { instance = this; } void Start () { ani_is_working = true; if (m_OtherPlayerView.Length>0) { for (int i = 0; i < 4; ++i) m_OtherPlayerView[i].enabled = false; } //Intro_Performance(Turtle_Move.instance.GetId()); } public void DeadAnimation(byte id){ m_PlayerView.enabled = false; m_OtherPlayerView[id].enabled = true; switch (id) { case 0: m_OtherPlayerAnimator[0].SetTrigger("GameOver"); ani_is_working = true; break; case 1: m_OtherPlayerAnimator[1].SetTrigger("GameOver"); ani_is_working = true; break; case 2: m_OtherPlayerAnimator[2].SetTrigger("GameOver"); ani_is_working = true; break; case 3: m_OtherPlayerAnimator[3].SetTrigger("GameOver"); ani_is_working = true; break; } Invoke("CameraSwitch", 4.0f); } void CameraSwitchIntro() { m_PlayerView.enabled = true; m_PerformanceView.enabled = false; if (m_OtherPlayerView.Length > 0) { for (int i = 0; i < 4; ++i) m_OtherPlayerView[i].enabled = false; } ani_is_working = false; NetManager_Coop.instance.SendReadyCoopPacket(); } void CameraSwitch() { m_PlayerView.enabled = true; m_PerformanceView.enabled = false; if (m_OtherPlayerView.Length > 0) { for (int i = 0; i < 4; ++i) m_OtherPlayerView[i].enabled = false; } ani_is_working = false; } // Update is called once per frame void Update () { } public void Intro_Performance(byte id) { m_PlayerView.enabled = false; m_PerformanceView.enabled = true; switch (id) { case 0: m_CameraAnimator.SetTrigger("Intro_Normal"); ani_is_working = true; break; case 1: m_CameraAnimator.SetTrigger("Intro_Normal2"); ani_is_working = true; break; case 2: m_CameraAnimator.SetTrigger("Intro_Normal3"); ani_is_working = true; break; case 3: m_CameraAnimator.SetTrigger("Intro_Normal4"); ani_is_working = true; break; } Invoke("CameraSwitchIntro", 5.9f); } } <file_sep>using System; public struct ClientID { public byte size; // 패킷 크기 public byte packetType; // 패킷 id public byte id; // 클라 id public byte clientType; // 클라 타입( 0 = PC / 1 = AR ) public char[] playerID; // 입력한 플레이어 id public byte firstClient; // 먼저 접속한 클라이언트인지 아닌지 ( 0 = 먼저 접속 / 1 = 나중에 접속) } public struct CharInfo { public byte size; public byte packet_Type; public byte id; public int ani_state; public float hp; public float x; public float z; public float rotateY; } public struct TB_Room { public byte size; //19 public byte type;//8 public byte roomID; public byte people_count; public byte game_start; public byte people_max; //최대 인원 수 public byte made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) public byte guardian_pos; public byte people1; public byte people2; public byte people3; public byte people4; public string password; }; public enum PacketInfo { CharPos = 1, // 캐릭터 좌표 및 스테이터스 BombPos, BombExplode, MapData,// 맵 데이터 ClientID, ItemData, // 아이템 데이터 DeadNotice, // 적 데이터 RoomData, RoomAccept, RoomCreate, ObjData, // 오브젝트 데이터 GameStart, OUTRoom, ForceOutRoom, GameOver, EnemyData, }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Flame_Crash : MonoBehaviour { float m_FlameLifeTime = 1.2f; float m_curr_time = 0.0f; bool m_is_adventure; // ParticleSystem m_ParticleSystem; /* void Start() { m_ParticleSystem = GetComponentInChildren<ParticleSystem>(); } */ void Update () { if (m_curr_time < m_FlameLifeTime) m_curr_time += Time.deltaTime; else { if(SceneManager.GetActiveScene().buildIndex==3) Destroy(gameObject); // 화염 소멸 if (SceneManager.GetActiveScene().buildIndex == 12) { m_curr_time = 0.0f; gameObject.SetActive(false); } } } void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("Player")) { if (SceneManager.GetActiveScene().buildIndex == 3) { other.gameObject.GetComponent<Player>().Set_Dead(); } if (SceneManager.GetActiveScene().buildIndex == 12) { Turtle_Move_Coop.instance.alive = 0; NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Fire_Effect_Net : MonoBehaviour { Collider m_Fire_Collider; //화염 지속시간- 다만 이펙트 이기 때문에 파티클은 사라지지 않을 수 있으므로 값을 조종하려면 파티클 inspector에서 조정 -R public float bombCountDown = 1.0f; void OnTriggerEnter(Collider other) { if (gameObject.activeInHierarchy) { if (other.gameObject.CompareTag("Player")) { if (SceneManager.GetActiveScene().buildIndex == 7 || SceneChange.instance.GetSceneState() == 13) { if (Turtle_Move.instance.alive != 0) { //Debug.Log("TTaGawa"); if (Turtle_Move.instance.glider_on) { Turtle_Move.instance.alive = 1; Turtle_Move.instance.glider_on = false; Turtle_Move.instance.overpower = true; } else { if (!Turtle_Move.instance.overpower) Turtle_Move.instance.alive = 0; } NetTest.instance.SetmoveTrue(); } } else { Turtle_Move_Coop.instance.alive = 0; NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } } } } // Update is called once per frame void Update () { if (gameObject.activeInHierarchy) { if (bombCountDown >= 0.0f) { bombCountDown -= Time.deltaTime; } else { bombCountDown = 1.0f; gameObject.SetActive(false); //Destroy(gameObject); } } } } <file_sep><PC 상에서의 작업> 0. "안드로이드 기기"를 PC와 연결한다. (USB 연결) 1. PC에서 기기를 인식했다면, 자신이 알기 쉬운 경로에 "APK 파일"을 복사해서 넣는다. <모바일 기기 상에서의 작업> 2. APK파일 복사가 완료되면 모바일 기기를 켜고, "내 파일"을 켠다. 3. APK파일이 "설치된 경로"를 찾아 들어가서 해당 파일을 누른다. 4-1. "설치 경고창"이 팝업될 경우, "설치" 버튼을 누른다. 4-2. 이후 "보안" 설정 창으로 이동 될 경우, "출처를 알 수 없는 앱"을 활성화 해야한다. 4-3. "출처를 알 수 없는 앱"을 누르면, 경고창이 팝업된다. 이때 "허용" 버튼을 누른다. 5. 설치가 진행되며, 완료 시 바탕화면에 앱 아이콘이 생성된다. 6. 앱 아이콘을 통해 게임을 즐길 수 있다.<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Mode_Select_Scene_Manager : MonoBehaviour { public Button m_Competition_Button; public Button m_Coop_Button; public RawImage m_Comp_CommingSoon; public RawImage m_Coop_CommingSoon; public static Mode_Select_Scene_Manager c_Mode_Select_manager; void Start () { c_Mode_Select_manager = this; } public void Open_Competition_Mode() { m_Comp_CommingSoon.gameObject.SetActive(false); m_Competition_Button.gameObject.SetActive(true); } public void Open_Coop_Mode() { m_Coop_CommingSoon.gameObject.SetActive(false); m_Coop_Button.gameObject.SetActive(true); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class WaitRoom : MonoBehaviour { int page = 1; //현재 내가 몇페이지에 있는지. public static WaitRoom instance; byte m_id; public GameObject forceouted; public GameObject[] cannotLogin; public Texture[] m_texture; public byte[] people_inRoom = new byte[4]; public Text m_text; Touch touch2; public GameObject pop; public RawImage[] uiBox; TB_Room[] roominfo = new TB_Room[20]; byte[] roomIDarray = new byte[20]; //0이면 안만들어짐 public Text[] room_numText; List<TB_Room> room_List = new List<TB_Room>(); public Text[] text_array; public Text[] room_enter_array; public Button[] room_enter_button; public GameObject ban_notice; public int cannotConnect; public bool ban_by_server; // Use this for initialization private void Awake() { instance = this; } void Start() { Screen.SetResolution(1280, 720, true); ban_by_server = false; ////Debug.Log("Started"); cannotConnect = 0; StartCoroutine("RoomCheck"); } public void Out() { //Debug.Log("Disconnect"); NetTest.instance.Disconnect(); SceneChange.instance.DisConnect(); } public void Out_By_Server() { //Debug.Log("Disconnect"); SceneChange.instance.DisConnect(); } public void PopMenu() { pop.transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); if (pop.activeInHierarchy) { } pop.SetActive(true); } public void CancelPopMenu() { ////Debug.Log("Clicked"); pop.SetActive(false); } public void ToLeftRoomPage() { //Debug.Log("Left Page"); if (page > 1) { page -= 1; } if (page <= 1) { page = 1; } } public void ToRightRoomPage() { if (page < 3) { page += 1; } if (page >= 3) { page = 3; } } public void SetRoomNum() { VariableManager.instance.m_roomid = roomIDarray[0 + ((page - 1) * 8)]; ////Debug.Log(m_roomid); } public void SetRoomNum1() { VariableManager.instance.m_roomid = roomIDarray[1 + ((page - 1) * 8)]; ////Debug.Log(m_roomid); } public void SetRoomNum2() { VariableManager.instance.m_roomid = roomIDarray[2 + ((page - 1) * 8)]; } public void SetRoomNum3() { VariableManager.instance.m_roomid = roomIDarray[3 + ((page - 1) * 8)]; } public void SetRoomNum4() { VariableManager.instance.m_roomid = roomIDarray[4 + ((page - 1) * 8)]; } public void SetRoomNum5() { VariableManager.instance.m_roomid = roomIDarray[5 + ((page - 1) * 8)]; } public void SetRoomNum6() { VariableManager.instance.m_roomid = roomIDarray[6 + ((page - 1) * 8)]; } public void SetRoomNum7() { VariableManager.instance.m_roomid = roomIDarray[7 + ((page - 1) * 8)]; } public void SendJCRoom(int a) { VariableManager.instance.m_roomid = (byte)((a) + ((page - 1) * 8)); if (roominfo[(a + ((page - 1) * 8)) - 1].made == 0) { NetTest.instance.SendCreatePacket(); } else NetTest.instance.SendJoinPacket(); } public void SendJoinRoom() { NetTest.instance.SendJoinPacket(); } public void SendCreateRoom() { NetTest.instance.SendCreatePacket(); } // Update is called once per frame void Update() { if (ban_by_server) ban_notice.SetActive(true); if (cannotConnect == 1) { cannotLogin[0].SetActive(true); } if (cannotConnect == 2) { cannotLogin[1].SetActive(true); } if (m_text != null) { //m_text.text = page + " / 3" ; m_text.text = VariableManager.instance.GetStringID(); } if (page < 3) { for (int i = 3; i < 8; ++i) { room_enter_button[i].interactable = true; } } //+"\nPeople : "+VariableManager.instance.roominfo //m_text.text = "Hi"; for (var i = 0; i < Input.touchCount; ++i) { Touch touch = Input.GetTouch(i); //Debug.Log("Hi3"); // Need to put .x //if (touch.position.x > (Screen.width / 2)) //{ Vector2 touchDeltaPosition = Input.GetTouch(i).deltaPosition; pop.transform.position = new Vector2(touchDeltaPosition.x, touchDeltaPosition.y); //} //m_text.text = "Touch Position : " + touch.position; } if (Input.touchCount > 0) { //Debug.Log("Hi"); touch2 = Input.GetTouch(0); //m_text.text = "Touch Position : " + touch2.position; } Vector3 nv = Input.mousePosition; if (VariableManager.instance.forceout) { forceouted.SetActive(true); VariableManager.instance.forceout = false; } } IEnumerator RoomCheck() { WaitForSeconds delay = new WaitForSeconds(0.2f); for (; ; ) { //room_List.Clear(); for (int i = 0; i < 20; ++i) { if (i < 8) room_numText[i].text = (i + ((page - 1) * 8) + 1) + "번"; TB_Room temp = VariableManager.instance.roominfo[i]; roominfo[i] = temp; //room_List.Add(temp); } int current_room = 0; foreach (TB_Room t in roominfo) { if (current_room < 8 * page) { // if (text_array[current_room] != null) { if (t.roomtype == 0) { //"Room No." + t.roomID + "\nPlayer : " + + "\nSurvival Mode"; text_array[current_room].text = t.people_count + "/" + t.people_max; uiBox[(current_room % 8)].texture = m_texture[1]; room_enter_array[(current_room % 8)].text = "입 장"; room_enter_button[(current_room % 8)].interactable = true; } else if (t.roomtype == 1) { text_array[current_room].text = t.people_count + "/" + t.people_max; uiBox[(current_room % 8)].texture = m_texture[1]; room_enter_array[(current_room % 8)].text = "입장"; room_enter_button[(current_room % 8)].interactable = true; } if (t.people_count == t.people_max) { uiBox[(current_room % 8)].texture = m_texture[2]; room_enter_array[(current_room % 8)].text = "X"; room_enter_button[(current_room % 8)].interactable = false; } if (t.made == 0) { text_array[current_room].text = "빈 방"; uiBox[(current_room % 8)].texture = m_texture[0]; room_enter_array[(current_room % 8)].text = "생성"; room_enter_button[(current_room % 8)].interactable = true; } if (t.game_start == 1) { text_array[current_room].text = ""; uiBox[(current_room % 8)].texture = m_texture[3]; room_enter_array[(current_room % 8)].text = "게임중"; room_enter_button[(current_room % 8)].interactable = false; } roomIDarray[current_room] = t.roomID; current_room++; } } for (int i = current_room; i < page * 8; ++i) { if (text_array[i] != null) text_array[i].text = "빈 방"; } } if (page == 3) { for (int i = 3; i < 8; ++i) { room_enter_button[i].interactable = false; room_enter_array[i].text = "생성 불가"; } } /* room_List.Clear(); for (int i = 0; i < 20; ++i) { if (i < 8) room_numText[i].text = (i+((page - 1)*8)+1) + "번"; if (VariableManager.instance.roominfo[i].made == 1 || VariableManager.instance.roominfo[i].made == 2) { TB_Room temp = VariableManager.instance.roominfo[i]; room_List.Add(temp); } } int current_room = 0; foreach(TB_Room t in room_List) { if (current_room < 8*page) { // if (text_array[current_room] != null) { if (t.roomtype == 0) { //"Room No." + t.roomID + "\nPlayer : " + + "\nSurvival Mode"; text_array[current_room].text = t.people_count + "/" + t.people_max ; uiBox[current_room].texture = m_texture[1]; } else if (t.roomtype == 1) { text_array[current_room].text = t.people_count + "/" + t.people_max; uiBox[current_room].texture = m_texture[1]; } else if (t.people_count == t.people_max) { uiBox[current_room].texture = m_texture[2]; } else if(t.made==0) uiBox[current_room].texture = m_texture[0]; if (t.game_start == 1) { text_array[current_room].text = "게임중"; uiBox[current_room].texture = m_texture[3]; } roomIDarray[current_room] = t.roomID; current_room++; } } for (int i= current_room;i<page*8;++i) { if (text_array[i] != null) text_array[i].text = "빈 방"; } } */ //for(int i = current_room; i < 8 * page; ++i) //{ // roomIDarray[current_room] = 0; //} yield return delay; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bush : MonoBehaviour { public GameObject[] m_Object_temp; public GameObject fire_Effect; MeshRenderer meshrenderer; public Material m; void Start() { StartCoroutine("BushCheck"); meshrenderer = gameObject.GetComponent<MeshRenderer>(); } //부쉬가 화염과 충돌하면 상태가 변경되는 함수 - 불타는 수풀이 되며, 화염이펙트가 추가된다. IEnumerator BushCheck() { int i = 0; for (; ; ) { m_Object_temp = GameObject.FindGameObjectsWithTag("Flame"); foreach (GameObject flame in m_Object_temp) { if (transform.position.x == flame.transform.position.x && transform.position.z == flame.transform.position.z && gameObject.tag == "Bush") { GameObject Instance_Flame_Remains = Instantiate(fire_Effect); Instance_Flame_Remains.transform.position = transform.position; gameObject.tag = "Flame_Bush"; meshrenderer.material = m; } } if (gameObject.CompareTag("Flame_Bush")) { i = (i + 1) % 11; meshrenderer.material.color = new Color(0.0f + (i * 0.1f), 1.0f - (i * 0.1f), 0, 1); } yield return new WaitForSeconds(0.05f); } } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Net.Sockets; using System.Net; using System.Threading; using System.Text; using UnityEngine; using UnityEngine.SceneManagement; public class NetTest : MonoBehaviour { public static NetTest instance = null; bool m_ingame = false; int bomb_posx; int bomb_posz; byte[] m_bomb_posx = new byte[4]; byte[] m_bomb_posz = new byte[4]; byte[] m_turtle_posx = new byte[4]; byte[] m_turtle_posz = new byte[4]; byte[] m_turtle_roty = new byte[4]; bool m_set_bomb = false; bool m_is_move = false; float deltaTime = 0.0f; public static float time_Second = 30.0f; private string m_address4 = "127.0.0.1"; private string m_address3 = "172.16.58.3"; private string m_address = "172.16.31.10"; private string m_address2 = "192.168.123.195"; bool out_by_server; private byte[] R_Map_Info = new byte[225]; private byte[] Receiveid = new byte[4]; WaitForSeconds delay = new WaitForSeconds(0.1f); byte access_id = 254; byte game_id = 254; private const int m_port = 9000; private const int m_packetSize = 4000; private Socket m_socket = null; private bool m_isConnected = false; public Thread m_thread = null; public bool m_threadLoop = false; public ClientID client_id; byte firepower; byte[] m_firepower = new byte[1]; // 송신 버퍼. private Queue m_sendQueue = new Queue(); int remain_size = 0; // 수신 버퍼. private Queue m_recvQueue = new Queue(); Byte[] temp_buffer = new Byte[m_packetSize]; // 수신한 데이터를 복사할 데이터 Byte[] copy_data = new Byte[m_packetSize]; // 수신 데이터 Byte[] recv_data = new Byte[m_packetSize]; CharInfo[] m_chardata = new CharInfo[4]; private void Awake() { instance = this; DontDestroyOnLoad(this); } // Use this for initialization void Start() { out_by_server = false; //m_address = Client_IP(); //////Debug.Log(m_address); InitializePos(); client_id.size = 15; Connect(); StartCoroutine("SendTester"); //어플리케이션 프레임레이트를 30으로 //Application.targetFrameRate = 30; //StartCoroutine("DebugTest"); } public void InitializePos() { m_chardata[0].x = 0; m_chardata[0].z = 0; m_chardata[0].rotateY = 0; m_chardata[1].x = 28; m_chardata[1].z = 0; m_chardata[1].rotateY = 0; m_chardata[2].x = 0; m_chardata[2].z = 28; m_chardata[2].rotateY = 180; m_chardata[3].x = 28; m_chardata[3].z = 28; m_chardata[3].rotateY = 180; } //ip값 받아오기 public string Client_IP() { //dns.gethostentry = 호스트ip주소를 확인 //dns.gethostname - 로컬컴퓨터의 호스트 이름을 return IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); //임시변수 초기화 string ClientIP = string.Empty; for (int i = 0; i < host.AddressList.Length; i++) { if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { ClientIP = host.AddressList[i].ToString(); } } return ClientIP; } public byte GetId() { return access_id; } public byte GetGameId() { return game_id; } public void Connect() { try { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); IPAddress serverIP = System.Net.IPAddress.Parse(m_address); IPEndPoint ipEndPoint = new System.Net.IPEndPoint(serverIP, m_port); //m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000); // m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000); m_socket.Connect(ipEndPoint); m_socket.NoDelay = true; m_isConnected = true; m_socket.SendBufferSize = 0; //byte[] recvBuffer = new byte[m_packetSize]; m_socket.BeginReceive(this.recv_data, 0, recv_data.Length, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), m_socket); SceneChange.instance.GoTo_Wait_Scene(); } catch (SocketException e) { m_socket = null; m_isConnected = false; Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode); ////Debug.Log("Socket Connect Error."); ////Debug.Log("End client communication."); } if (m_socket == null) { Disconnect(); } } public void Disconnect() { m_isConnected = false; if (m_socket != null) { // 소켓 닫기. m_socket.Shutdown(SocketShutdown.Both); m_socket.Close(); m_socket = null; //DestroyThread(); } } private void SendCallBack(IAsyncResult IAR) { string message = (string)IAR.AsyncState; } public void BeginSend(byte[] buffer) { try { // 연결 성공시 if (m_socket.Connected) { m_socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), buffer); } } catch (SocketException e) { ////Debug.Log("전송 에러 : " + e.Message); } } public void Receive() { //////Debug.Log("Recv!!"); ////Debug.Log("Receive Try"); m_socket.BeginReceive(this.recv_data, 0, recv_data.Length, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), m_socket); } private void OnReceiveCallBack(IAsyncResult IAR) { try { Socket tempSock = (Socket)IAR.AsyncState; int nReadSize = tempSock.EndReceive(IAR); Buffer.BlockCopy(recv_data, 0, copy_data, 0 + remain_size, nReadSize); remain_size = remain_size + nReadSize; if (nReadSize != 0) { ProcessPacket(copy_data); } if (remain_size >= 2) { ProcessPacket(copy_data); } this.Receive(); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.ConnectionReset) { //Debug.Log(se); //this.BeginConnect(); } } } //버퍼를 교체한다. void SwapBuffer(byte size) { int temp = size; ////Debug.Log("Delete Size: "+temp+ " "); Array.Clear(temp_buffer, 0, temp_buffer.Length); //////Debug.Log("Clear Temp Array"); remain_size = remain_size - temp; Buffer.BlockCopy(copy_data, temp, temp_buffer, 0, remain_size); //////Debug.Log("Copy to Temp Array"); Array.Clear(copy_data, 0, copy_data.Length); //////Debug.Log("Clear Copy Array"); Buffer.BlockCopy(temp_buffer, 0, copy_data, 0, temp_buffer.Length); //////Debug.Log("Swap Array"); ////Debug.Log("Remain_Size2 : " + remain_size); } void ProcessPacket(byte[] recv_buff) { ////Debug.Log("Process P"); while (remain_size >= 2) { //Debug.Log("This Data : " + copy_data[1] + "\nThis Size:" + copy_data[0]); switch (copy_data[1]) { case (byte)PacketInfo.Disconnect: out_by_server = true; //SceneChange.instance.GoTo_Select_Scene_ByServer(); SwapBuffer(copy_data[0]); //Disconnect(); break; case (byte)PacketInfo.ClientID: access_id = copy_data[2]; VariableManager.instance.SetID(copy_data[2]); //////Debug.Log("Get Id!! : " + (byte)access_id); SwapBuffer(copy_data[0]); //////Debug.Log("Remain_Size : " + remain_size); break; case (byte)PacketInfo.CharPos: //다른 유저 위치정보를 전송 byte tempid = copy_data[2]; m_chardata[tempid].ani_state = copy_data[3]; m_chardata[tempid].is_alive = copy_data[4]; if(SceneChange.instance.GetSceneState() == 7 || SceneChange.instance.GetSceneState() == 13) Turtle_Move.instance.Move_Case(tempid); m_chardata[tempid].x = BitConverter.ToSingle(recv_buff, 10); m_chardata[tempid].z = BitConverter.ToSingle(recv_buff, 14); m_chardata[tempid].rotateY = BitConverter.ToSingle(recv_buff, 18); SwapBuffer(copy_data[0]); //////Debug.Log("Remain_Size : " + remain_size); break; case (byte)PacketInfo.BombPos: //폭탄정보 전송(터지는 폭탄) byte tempid2 = copy_data[2]; MapManager.instance.Check_Map(recv_buff); //SetCharPos(recv_buff); SwapBuffer(copy_data[0]); //////Debug.Log("Remain_Size : " + remain_size); break; case (byte)PacketInfo.BombExplode: //폭탄정보 전송(터지는 폭탄) /* byte tempfirepower = copy_data[2]; int tempx = BitConverter.ToInt32(copy_data, 4); int tempz = BitConverter.ToInt32(copy_data, 8); //////Debug.Log("Start Explode Bomb : " + remain_size); MapManager.instance.Explode_Bomb(tempx, tempz, tempfirepower); */ byte reloadid = copy_data[6]; Turtle_Move.instance.ReloadBomb(reloadid); int tempx = BitConverter.ToInt32(copy_data, 7); int tempz = BitConverter.ToInt32(copy_data, 11); byte[] tempfire_array = new byte[4]; Buffer.BlockCopy(copy_data, 2, tempfire_array, 0, 4); //Debug.Log("UpFire : " + tempfire_array[0]); //Debug.Log("RightFire : " + tempfire_array[1]); //Debug.Log("DownFire : " + tempfire_array[2]); //Debug.Log("LeftFire : " + tempfire_array[3]); MapManager.instance.Explode_Bomb_v2(tempx, tempz, tempfire_array); SwapBuffer(copy_data[0]); ///////Debug.Log("Explode Bomb : " + remain_size); break; case (byte)PacketInfo.MapData: //////Debug.Log("Get MapData!! : "); VariableManager.instance.Check_Map(copy_data); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ItemData: byte tempidt = copy_data[2]; byte tempitemt = copy_data[3]; Turtle_Move.instance.SetItem_Ability(tempidt, tempitemt); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.DeadNotice: byte tempid_d = copy_data[2]; Turtle_Move.instance.Dead_Case(tempid_d); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.GameOver: //Debug.Log("Game Over!!!"); byte winnerid = copy_data[2]; byte loserid = copy_data[3]; VSModeManager.instance.GameOver_Set(winnerid, loserid); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ReadyData: GameRoom.instance.GetReadyState(copy_data[2], copy_data[3]); VariableManager.instance.GetReadyState(copy_data[4], copy_data[2], copy_data[3]); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.EnemyData: VariableManager.instance.SetTeamState(copy_data); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.RoomData: ////Debug.Log("Get Room data"); VariableManager.instance.SetRoomState(copy_data); ////Debug.Log("Room Info Set Complete"); SwapBuffer(copy_data[0]); ////Debug.Log("Buffer Changed"+remain_size); break; case (byte)PacketInfo.RoomAccept: //Debug.Log("Get Responce"); byte temp_bool = copy_data[2]; if (temp_bool == 1) { //Debug.Log("Get In"); //방으로 들어가는 함수 VariableManager.instance.SetRoomState_Respond(copy_data); SceneChange.instance.GoTo_ModeSelect_Scene(); } else { //Debug.Log("Rejected"); } SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.RoomCreate: byte temp_bool2 = copy_data[2]; if (temp_bool2 == 1) { ////Debug.Log("Get In"); //방으로 들어가는 함수 VariableManager.instance.SetRoomCreate_Respond(copy_data); SceneChange.instance.GoTo_ModeSelect_Scene(); } else { //Debug.Log("Cannot Create Room"); } SwapBuffer(copy_data[0]); ////Debug.Log("Swap Data"); break; case (byte)PacketInfo.GameStart: //Debug.Log("Get Game Start Data"); byte temp_boolG_S = copy_data[2]; if (temp_boolG_S == 1) { //Debug.Log("Get In"); //방으로 들어가는 함수 //WaitRoom.instance.SetRoomCreate_Respond(copy_data); m_ingame = true; GameRoom.instance.load_on = true; if(VariableManager.instance.map_type ==0) SceneChange.instance.GoTo_Game_Scene(); else SceneChange.instance.GoTo_Ice_VS_Scene(); } else { ////Debug.Log("Cannot Start"); } SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.SetBomb: byte tempfp2 = copy_data[2]; int tempxBB = BitConverter.ToInt32(copy_data, 3); int tempzBB = BitConverter.ToInt32(copy_data, 7); VariableManager.instance.Check_BombMap(tempxBB, tempzBB, 5); VariableManager.instance.Check_FireMap(tempxBB, tempzBB, tempfp2); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.OUTRoom: VariableManager.instance.OutRoom(); GameRoom.instance.OutRoom(); SceneChange.instance.GoTo_Wait_Scene(); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ForceOutRoom: VariableManager.instance.F_OutRoom(); GameRoom.instance.OutRoom(); SceneChange.instance.GoTo_Wait_Scene(); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ThrowBomb: // MapManager.instance.Throw_BombSet(); //Debug.Log("Throw!!Get"); byte direction2 = copy_data[2]; byte tempthrowid = copy_data[3]; int tempx2 = BitConverter.ToInt32(copy_data, 4); int tempz2 = BitConverter.ToInt32(copy_data, 8); int tempdx2 = BitConverter.ToInt32(copy_data, 12); int tempdz2 = BitConverter.ToInt32(copy_data, 16); ////Debug.Log("Get convert complete"); MapManager.instance.Throw_BombSet(tempx2, tempz2, tempdx2, tempdz2, direction2); Turtle_Move.instance.Throw_Case(tempthrowid); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.KickBomb: byte kickornot = copy_data[2]; if (kickornot == 1) { byte kickid = copy_data[3]; byte directionPB = copy_data[4]; int tempxpb = BitConverter.ToInt32(copy_data, 5); int tempzpb = BitConverter.ToInt32(copy_data, 9); int tempxpbd = BitConverter.ToInt32(copy_data, 13); int tempzpbd = BitConverter.ToInt32(copy_data, 17); MapManager.instance.Kick_BombSet(tempxpb, tempzpb, tempxpbd, tempzpbd, directionPB); Turtle_Move.instance.Kick_Case(kickid); } SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.SetMap2: byte tiletype = copy_data[2]; int tempxB = BitConverter.ToInt32(copy_data, 3); int tempzB = BitConverter.ToInt32(copy_data, 7); VariableManager.instance.Check_BombMap(tempxB, tempzB, tiletype); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.PushBox: byte pushornot = copy_data[2]; if (pushornot == 1) { byte pushid = copy_data[3]; byte directionPB = copy_data[4]; int tempxpb = BitConverter.ToInt32(copy_data, 5); int tempzpb = BitConverter.ToInt32(copy_data, 9); int tempxpbd = BitConverter.ToInt32(copy_data, 13); int tempzpbd = BitConverter.ToInt32(copy_data, 17); MapManager.instance.Push_BoxSet(tempxpb, tempzpb, tempxpbd, tempzpbd, directionPB); Turtle_Move.instance.Push_Case(pushid); } SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.GetTime: float t_time = BitConverter.ToSingle(copy_data, 2); ////Debug.Log("I got Time"+t_time); VariableManager.instance.ChangeTime(t_time); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.AirDrop: Debug.Log("AirDrop!!!"); MapManager.instance.AirdropStart(); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ConnectSuccess: SendMyIDAndPassword(); //Debug.Log("Swag"); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.DBInfo1: { byte is_connected = copy_data[2]; if (is_connected == 1 || is_connected == 2) { VariableManager.instance.SetMyDBInfo(copy_data); //Debug.Log("Get DBDATA!!!"); } else { //Debug.Log("Rejected By DB"); if (is_connected == 0) WaitRoom.instance.cannotConnect = 1; else if (is_connected == 3) WaitRoom.instance.cannotConnect = 2; //연결 실패 } SwapBuffer(copy_data[0]); } break; default: //Debug.Log(copy_data[1] + "Unknown PacketType!"); if (copy_data[0] == 0) SwapBuffer(17); break; } } } public virtual void WorkerThread() { const int fps = (int)(1000 / 30); int frameTick = Environment.TickCount + fps; while (m_threadLoop) { // 초당 FPS 만큼만 송, 수신 처리 if (Environment.TickCount >= frameTick) { frameTick = Environment.TickCount + fps; } } } void DispatchReceive() { if (m_socket == null) { return; } // 수신처리. try { while (m_socket.Poll(0, SelectMode.SelectRead)) { byte[] buffer = new byte[m_packetSize]; int recvSize = m_socket.Receive(buffer, buffer.Length, SocketFlags.None); if (recvSize == 0) { // 연결 끊기. ////Debug.Log("Disconnect recv from other."); Disconnect(); } else if (recvSize > 0) { m_recvQueue.InputQueue(buffer, recvSize); } } } catch { return; } } void SetCharPos(CharInfo c) { switch (c.id) { case 1: if (Turtle_Move.instance.GetId() == 1) { break; } else { NetUser.instance.SetPos(c.x, c.rotateY, c.z); } break; case 2: if (Turtle_Move.instance.GetId() == 2) { break; } else { NetUser2.instance.SetPos(c.x, c.rotateY, c.z); } break; case 3: if (Turtle_Move.instance.GetId() == 3) { break; } else { NetUser3.instance.SetPos(c.x, c.rotateY, c.z); } break; case 4: if (Turtle_Move.instance.GetId() == 4) { break; } else { NetUser4.instance.SetPos(c.x, c.rotateY, c.z); } break; default: break; } } public void SetBombPos(int a, int b) { bomb_posx = a / 2; bomb_posz = b / 2; m_bomb_posx = BitConverter.GetBytes(bomb_posx); m_bomb_posz = BitConverter.GetBytes(bomb_posz); m_set_bomb = true; } public void SetBombPos(int a, int b, byte c) { bomb_posx = a / 2; bomb_posz = b / 2; firepower = c; m_bomb_posx = BitConverter.GetBytes(bomb_posx); m_bomb_posz = BitConverter.GetBytes(bomb_posz); m_set_bomb = true; } public void SetMyPos(float x, float y, float z) { m_turtle_posx = BitConverter.GetBytes(x); m_turtle_posz = BitConverter.GetBytes(z); m_turtle_roty = BitConverter.GetBytes(y); m_is_move = true; } public void SetmoveTrue() { m_is_move = true; } public float GetNetPosx(int i) { if (i >= 0 && i <= 3) return m_chardata[i].x; else return 0; } public byte GetNetAlive(int i) { return m_chardata[i].is_alive; } public float GetNetRoty(int i) { if (i >= 0 && i <= 3) return m_chardata[i].rotateY; else return 0; } public float GetNetPosz(int i) { if (i >= 0 && i <= 3) return m_chardata[i].z; else return 0; } void SendMyIDAndPassword() { byte[] myInfo = new byte[44]; byte t_size = 44; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 26; byte[] m_packet_type = BitConverter.GetBytes(t_type); // string a = byte t_id = VariableManager.instance.m_accessid; byte[] m_packet_id = BitConverter.GetBytes(t_id); byte t_login = GetID.instance.login_type; byte[] m_packet_login = BitConverter.GetBytes(t_login); byte[] m_idString = new byte[20]; //Debug.Log(t_login); //string a = GetID.instance.GetIDD(); //release string a = "test"; //Debug //Debug.Log(a); for (int i = 0; i < a.Length; ++i) { //Debug.Log(i); m_idString[i] = Convert.ToByte(a[i]); } //Debug.Log(m_idString); //m_idString = BitConverter.GetBytes(a); string b = GetID.instance.GETPW(); b = "123"; //Debug.Log(b); byte[] m_pwString = new byte[20]; for (int i = 0; i < b.Length; ++i) m_pwString[i] = Convert.ToByte(b[i]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_login, 0, myInfo, 3, m_packet_login.Length); Buffer.BlockCopy(m_idString, 0, myInfo, 4, m_idString.Length); Buffer.BlockCopy(m_pwString, 0, myInfo, 24, m_pwString.Length); m_socket.Send(myInfo); //Debug.Log("Send DBPacket"); } public void SendRoomStateChangePacket() { byte[] myInfo = new byte[6]; byte t_size = 6; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 15; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomid = VariableManager.instance.m_roomid; byte[] m_packet_roomid = BitConverter.GetBytes(t_roomid); byte t_gametype = VariableManager.instance.game_mode; byte[] m_gametype = BitConverter.GetBytes(t_gametype); byte t_maptype = VariableManager.instance.map_type; byte[] m_mapthema = BitConverter.GetBytes(t_maptype); byte t_mapnum = VariableManager.instance.map_num; byte[] m_mapnum = BitConverter.GetBytes(t_mapnum); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 2, m_packet_roomid.Length); Buffer.BlockCopy(m_gametype, 0, myInfo, 3, m_gametype.Length); Buffer.BlockCopy(m_mapthema, 0, myInfo, 4, m_mapthema.Length); Buffer.BlockCopy(m_mapnum, 0, myInfo, 5, 1); m_socket.Send(myInfo); } public void SendTeamChangePacket() { byte[] myInfo = new byte[5]; byte t_size = 5; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 16; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomid = VariableManager.instance.m_roomid; byte[] m_packet_roomid = BitConverter.GetBytes(t_roomid); byte t_id = (byte)((int)VariableManager.instance.pos_inRoom - 1); byte[] m_turtle_id = BitConverter.GetBytes(t_id); byte t_team = VariableManager.instance.myteam; byte[] m_team = BitConverter.GetBytes(t_team); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 2, m_packet_roomid.Length); Buffer.BlockCopy(m_turtle_id, 0, myInfo, 3, m_turtle_id.Length); Buffer.BlockCopy(m_team, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendItemPacket(int x, int z, byte t) { byte[] myInfo = new byte[13]; byte t_size = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 6; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomid = VariableManager.instance.m_roomid; byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_packet_roomid = BitConverter.GetBytes(t_roomid); byte[] m_packet_ingameid = BitConverter.GetBytes(t_ingameid); int tempx = x / 2; int tempz = z / 2; byte[] m_item_type = BitConverter.GetBytes(t); byte[] m_packet_x = BitConverter.GetBytes(tempx); byte[] m_packet_z = BitConverter.GetBytes(tempz); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 2, m_packet_roomid.Length); Buffer.BlockCopy(m_packet_ingameid, 0, myInfo, 3, m_packet_ingameid.Length); Buffer.BlockCopy(m_item_type, 0, myInfo, 4, m_item_type.Length); Buffer.BlockCopy(m_packet_x, 0, myInfo, 5, m_packet_x.Length); Buffer.BlockCopy(m_packet_z, 0, myInfo, 9, m_packet_z.Length); m_socket.Send(myInfo); } void SendTurtlePacket() { bool tempbool = m_is_move; if (tempbool) { byte[] ReceivebTurtles_Pos = new byte[22]; byte t_size = 22; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 1; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = (byte)((int)VariableManager.instance.pos_inRoom - 1); byte[] m_turtle_id = BitConverter.GetBytes(t_id); byte t_roomid = VariableManager.instance.m_roomid; byte t_alive = Turtle_Move.instance.alive; byte[] t_turtle_alive = BitConverter.GetBytes(t_alive); byte[] m_room_id = BitConverter.GetBytes(t_roomid); //m_Socket.Send(m_packet_type); //MemoryStream memStream = new MemoryStream(17); Buffer.BlockCopy(m_packet_size, 0, ReceivebTurtles_Pos, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, ReceivebTurtles_Pos, 1, m_packet_type.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 2, m_turtle_id.Length); Buffer.BlockCopy(m_packet_type, 0, ReceivebTurtles_Pos, 3, m_packet_type.Length);//애니메이션 상태지만 일단 보류 Buffer.BlockCopy(t_turtle_alive, 0, ReceivebTurtles_Pos, 4, t_turtle_alive.Length); Buffer.BlockCopy(m_room_id, 0, ReceivebTurtles_Pos, 5, m_room_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 6, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 7, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 8, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 9, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_posx, 0, ReceivebTurtles_Pos, 10, m_turtle_posx.Length); Buffer.BlockCopy(m_turtle_posz, 0, ReceivebTurtles_Pos, 14, m_turtle_posz.Length); Buffer.BlockCopy(m_turtle_roty, 0, ReceivebTurtles_Pos, 18, m_turtle_roty.Length); //////Debug.Log(n); m_socket.Send(ReceivebTurtles_Pos); //////Debug.Log("Send"); m_is_move = false; } } void SendMyInfo() { byte[] myInfo = new byte[12]; byte t_size = 12; byte t_type = 9; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = (byte)access_id; byte[] m_packet_id = BitConverter.GetBytes(t_id); byte t_gameid = (byte)game_id; byte[] m_packet_gameid = BitConverter.GetBytes(t_gameid); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_gameid, 0, myInfo, 3, m_packet_gameid.Length); m_socket.Send(myInfo); } public void SendJoinPacket() { byte[] myInfo = new byte[12]; byte t_size = 12; byte t_type = 9; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = VariableManager.instance.m_accessid; byte[] m_packet_id = BitConverter.GetBytes(t_id); byte t_roomid = VariableManager.instance.GetRoomNum(); byte[] m_packet_roomid = BitConverter.GetBytes(t_roomid); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 3, m_packet_roomid.Length); m_socket.Send(myInfo); } public void SendCreatePacket() { byte[] myInfo = new byte[12]; byte t_size = 12; byte t_type = 10; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = VariableManager.instance.m_accessid; byte[] m_packet_id = BitConverter.GetBytes(t_id); byte t_roomnum = VariableManager.instance.m_roomid; byte[] m_room_num = BitConverter.GetBytes(t_roomnum); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 3, m_room_num.Length); m_socket.Send(myInfo); } public void SendStartPacket() { byte[] myInfo = new byte[4]; byte t_size = 4; byte t_type = 12; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; ////Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); m_socket.Send(myInfo); } public void SendReadyPacket() { byte[] myInfo = new byte[11]; byte t_size = 11; byte t_type = 12; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = (byte)access_id; byte[] m_packet_id = BitConverter.GetBytes(t_id); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); m_socket.Send(myInfo); } public void SendReadyPacket_v2() { byte[] myInfo = new byte[5]; byte t_size = 5; byte t_type = 11; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); byte m_isready = GameRoom.instance.m_imready; byte[] m_packet_ready = BitConverter.GetBytes(m_isready); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, m_packet_my_pos.Length); Buffer.BlockCopy(m_packet_ready, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendOUTPacket() { byte[] myInfo = new byte[5]; byte t_size = 5; byte t_type = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; byte imwinner = 0; byte[] m_winner = BitConverter.GetBytes(imwinner); ////Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); Buffer.BlockCopy(m_winner, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendOUTPacket_lose() { byte[] myInfo = new byte[5]; byte t_size = 5; byte t_type = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; byte imwinner = 2; byte[] m_winner = BitConverter.GetBytes(imwinner); ////Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); Buffer.BlockCopy(m_winner, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendOUT_WinnerPacket() { byte[] myInfo = new byte[5]; byte t_size = 5; byte t_type = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; byte imwinner = 1; byte[] m_winner = BitConverter.GetBytes(imwinner); ////Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); Buffer.BlockCopy(m_winner, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendOUTPacket2() { byte[] myInfo = new byte[5]; byte t_size = 5; byte t_type = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = 0; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; byte imwinner = 2; byte[] m_winner = BitConverter.GetBytes(imwinner); ////Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); Buffer.BlockCopy(m_winner, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendOUTPacket2_Winner() { byte[] myInfo = new byte[5]; byte t_size = 5; byte t_type = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = 0; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; byte imwinner = 1; byte[] m_winner = BitConverter.GetBytes(imwinner); ////Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); Buffer.BlockCopy(m_winner, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendBanPacket(byte a) { byte[] myInfo = new byte[4]; byte t_size = 4; byte t_type = 14; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte t_pos = a; byte[] m_clicked_pos = BitConverter.GetBytes(t_pos); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_clicked_pos, 0, myInfo, 3, 1); m_socket.Send(myInfo); } public void SendBomb_TPacket(byte direction, int x, int z) { byte[] myInfo = new byte[13]; byte t_size = 13; byte t_type = 17; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_player_id = BitConverter.GetBytes(t_ingameid); byte[] m_direction = BitConverter.GetBytes(direction); byte[] m_bombx = BitConverter.GetBytes(x); byte[] m_bombz = BitConverter.GetBytes(z); //Debug.Log("Direction :" + direction); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_player_id, 0, myInfo, 3, m_player_id.Length); Buffer.BlockCopy(m_direction, 0, myInfo, 4, m_direction.Length); Buffer.BlockCopy(m_bombx, 0, myInfo, 5, m_bombx.Length); Buffer.BlockCopy(m_bombz, 0, myInfo, 9, m_bombz.Length); m_socket.Send(myInfo); } //발차기 패킷 public void SendBomb_KPacket(byte direction, int x, int z) { byte[] myInfo = new byte[13]; byte t_size = 13; byte t_type = 18; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_player_id = BitConverter.GetBytes(t_ingameid); byte[] m_direction = BitConverter.GetBytes(direction); byte[] m_bombx = BitConverter.GetBytes(x); byte[] m_bombz = BitConverter.GetBytes(z); //Debug.Log("Kick Direction :" + direction); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_player_id, 0, myInfo, 3, m_player_id.Length); Buffer.BlockCopy(m_direction, 0, myInfo, 4, m_direction.Length); Buffer.BlockCopy(m_bombx, 0, myInfo, 5, m_bombx.Length); Buffer.BlockCopy(m_bombz, 0, myInfo, 9, m_bombz.Length); m_socket.Send(myInfo); } public void PushBox_Packet(byte direction, int x, int z) { byte[] myInfo = new byte[13]; byte t_size = 13; byte t_type = 22; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_player_id = BitConverter.GetBytes(t_ingameid); byte[] m_direction = BitConverter.GetBytes(direction); byte[] m_bombx = BitConverter.GetBytes(x); byte[] m_bombz = BitConverter.GetBytes(z); //Debug.Log("Direction :" + direction); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_player_id, 0, myInfo, 3, m_player_id.Length); Buffer.BlockCopy(m_direction, 0, myInfo, 4, m_direction.Length); Buffer.BlockCopy(m_bombx, 0, myInfo, 5, m_bombx.Length); Buffer.BlockCopy(m_bombz, 0, myInfo, 9, m_bombz.Length); m_socket.Send(myInfo); } public void SendBomb_TCPacket(int x, int z) { byte[] myInfo = new byte[11]; byte t_size = 11; byte t_type = 19; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte[] m_bombx = BitConverter.GetBytes(x); byte[] m_bombz = BitConverter.GetBytes(z); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_bombx, 0, myInfo, 3, m_bombx.Length); Buffer.BlockCopy(m_bombz, 0, myInfo, 7, m_bombz.Length); m_socket.Send(myInfo); } public void SendBox_Packet(int x, int z) { byte[] myInfo = new byte[11]; byte t_size = 11; byte t_type = 23; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte[] m_bombx = BitConverter.GetBytes(x); byte[] m_bombz = BitConverter.GetBytes(z); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_bombx, 0, myInfo, 3, m_bombx.Length); Buffer.BlockCopy(m_bombz, 0, myInfo, 7, m_bombz.Length); m_socket.Send(myInfo); } public void SendKickCom_Packet(int x, int z) { byte[] myInfo = new byte[11]; byte t_size = 11; byte t_type = 20; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte[] m_bombx = BitConverter.GetBytes(x); byte[] m_bombz = BitConverter.GetBytes(z); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_bombx, 0, myInfo, 3, m_bombx.Length); Buffer.BlockCopy(m_bombz, 0, myInfo, 7, m_bombz.Length); m_socket.Send(myInfo); } public void SendReadyCoopPacket() { byte[] myInfo = new byte[5]; byte t_size = 5; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 28; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_ready = 1; byte[] m_packet_ready = BitConverter.GetBytes(t_ready); byte t_roomid = VariableManager.instance.m_roomid; byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_packet_roomid = BitConverter.GetBytes(t_roomid); byte[] m_packet_ingameid = BitConverter.GetBytes(t_ingameid); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_ready, 0, myInfo, 2, m_packet_ready.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 3, m_packet_roomid.Length); Buffer.BlockCopy(m_packet_ingameid, 0, myInfo, 4, 1); m_socket.Send(myInfo); } public void SendBombPacket() { bool tempbool = m_set_bomb; if (tempbool) { byte[] TurtleBomb_Bomb = new byte[13]; byte t_size = 13; byte t_type = 2; byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_player_id = BitConverter.GetBytes(t_ingameid); byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_room = VariableManager.instance.m_roomid; byte[] m_roomid = BitConverter.GetBytes(t_room); byte[] t_turtlefire = BitConverter.GetBytes(Turtle_Move.instance.GetFirePower()); Buffer.BlockCopy(m_packet_size, 0, TurtleBomb_Bomb, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, TurtleBomb_Bomb, 1, m_packet_type.Length); Buffer.BlockCopy(t_turtlefire, 0, TurtleBomb_Bomb, 2, t_turtlefire.Length); Buffer.BlockCopy(m_roomid, 0, TurtleBomb_Bomb, 3, m_roomid.Length); Buffer.BlockCopy(m_player_id, 0, TurtleBomb_Bomb, 4, m_player_id.Length); Buffer.BlockCopy(m_bomb_posx, 0, TurtleBomb_Bomb, 5, m_bomb_posx.Length); Buffer.BlockCopy(m_bomb_posz, 0, TurtleBomb_Bomb, 9, m_bomb_posz.Length); m_socket.Send(TurtleBomb_Bomb); m_set_bomb = false; //////Debug.Log("폭탄보냄"); } } IEnumerator SendTester() { for (; ; ) { if (m_ingame) { SendTurtlePacket(); //SendBombPacket(); m_is_move = false; } yield return delay; } } // FPS 출력 void OnGUI() { int w = Screen.width, h = Screen.height; GUIStyle style = new GUIStyle(); Rect rect = new Rect(0, 0, w, h * 2 / 100); // Rect rect2 = new Rect(0, h * 10 / 100, w, h * 20 / 100); style.alignment = TextAnchor.UpperLeft; style.fontSize = h * 2 / 100; style.normal.textColor = new Color(0.0f, 0.0f, 0.5f, 1.0f); float msec = deltaTime * 1000.0f; float fps = 1.0f / deltaTime; string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps); GUI.Label(rect, text, style); } public void GetOutRoom() { SceneChange.instance.GoTo_Select_Scene(); } void Update() { // 스테이지 클리어 후 별 갯수 적용 // 시간 경과 if (SceneManager.GetActiveScene().buildIndex == 1) { Destroy(this.gameObject); } if (out_by_server) { if (SceneManager.GetActiveScene().buildIndex == 5) { WaitRoom.instance.ban_by_server = true; out_by_server = false; } if (SceneManager.GetActiveScene().buildIndex == 6) { GameRoom.instance.Kick_By_Server(); out_by_server = false; } if (SceneManager.GetActiveScene().buildIndex == 7) { VSModeManager.instance.Kick_By_Server(); out_by_server = false; } } deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f; //time_Second = time_Second - deltaTime; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class VariableManager : MonoBehaviour { public static VariableManager instance; public byte m_accessid = 254; public byte m_roomid = 0; int win = 0; int lose = 0; string mystringID; int tier = 0; int exp = 0; int expmax = 0; public byte[] people_inRoom = new byte[4]; public byte pos_inRoom = 0; public byte pos_guardian = 0; public byte is_guardian = 0; public byte game_mode = 4; public byte map_type = 0; public byte map_num = 0; //MapManager의 변수 public byte[] copy_map_info = new byte[225]; public byte[] bombexplode_list = new byte[225]; public byte[] firepower_list = new byte[225]; byte[] roomIDarray = new byte[20]; //0이면 안만들어짐 public TB_Room[] roominfo = new TB_Room[20]; public byte[] team_Turtle = new byte[4]; public byte[] ready_Turtle = new byte[4]; public bool forceout = false; public float m_time = 60.0f; public byte myteam; private void Awake() { instance = this; DontDestroyOnLoad(this); } public void SetGameMode(int mode) { game_mode = (byte)mode; } public void SetMapMode(int mode) { map_type = (byte)mode; } public void SetMapNum(int num) { map_num = (byte)num; } public void SetTeam(byte mode) { myteam = (byte)mode; } public void SetID(byte a) { m_accessid = a; } public void SetMyDBInfo(byte[] a) { mystringID = BitConverter.ToString(a, 3, 20); mystringID = System.Text.Encoding.UTF8.GetString(a, 3, 20); //Debug.Log(mystringID); win = BitConverter.ToInt32(a, 23); lose = BitConverter.ToInt32(a, 27); tier = BitConverter.ToInt32(a, 31); exp = BitConverter.ToInt32(a, 35); expmax = BitConverter.ToInt32(a, 39); //mystringID; } public string GetStringID() { return mystringID; } public void OutRoom() { roominfo[m_roomid - 1].team1 = 0; roominfo[m_roomid - 1].team2 = 0; roominfo[m_roomid - 1].team3 = 0; roominfo[m_roomid - 1].team4 = 0; m_roomid = 0; pos_inRoom = 0; pos_guardian = 0; is_guardian = 0; m_time = 60.0f; for (int i = 0; i < 4; ++i) { team_Turtle[i] = 0; people_inRoom[i] = 0; ready_Turtle[i] = 0; } ////Debug.Log(is_guardian); } public void F_OutRoom() { roominfo[m_roomid - 1].team1 = 0; roominfo[m_roomid - 1].team2 = 0; roominfo[m_roomid - 1].team3 = 0; roominfo[m_roomid - 1].team4 = 0; forceout = true; m_roomid = 0; pos_inRoom = 0; pos_guardian = 0; is_guardian = 0; m_time = 60.0f; for (int i = 0; i < 4; ++i) { team_Turtle[i] = 0; people_inRoom[i] = 0; ready_Turtle[i] = 0; } } public void ChangeTime(float time) { m_time = time; } public void GetReadyState(byte roomid, byte pos, byte ready) { if (roomid == m_roomid) { ready_Turtle[pos - 1] = ready; } switch (pos) { case 1: roominfo[roomid - 1].ready1 = ready; break; case 2: roominfo[roomid - 1].ready2 = ready; break; case 3: roominfo[roomid - 1].ready3 = ready; break; case 4: roominfo[roomid - 1].ready4 = ready; break; } } public byte GetRoomNum() { return m_roomid; } public void Check_Map(byte[] mapinfo) { Buffer.BlockCopy(mapinfo, 2, copy_map_info, 0, 225); } public void Check_BombMap(int x, int z, byte a) { copy_map_info[(z * 15) + x] = a; } public void Check_FireMap(int x, int z, byte f) { firepower_list[(z * 15) + x] = f; } public void SetTeamState(byte[] b) { byte[] tempArray = new byte[6]; Buffer.BlockCopy(b, 0, tempArray, 0, 6); roominfo[m_roomid-1].team1 = tempArray[2]; roominfo[m_roomid - 1].team2 = tempArray[3]; roominfo[m_roomid - 1].team3 = tempArray[4]; roominfo[m_roomid - 1].team4 = tempArray[5]; } public void SetRoomState(byte[] b) { byte[] tempArray = new byte[26]; Buffer.BlockCopy(b, 0, tempArray, 0, 26); ////Debug.Log("BlockCopy Completed"); byte temproomID = tempArray[2]; roominfo[temproomID - 1].roomID = temproomID; roominfo[temproomID - 1].people_count = tempArray[3]; roominfo[temproomID - 1].game_start = tempArray[4]; roominfo[temproomID - 1].people_max = tempArray[5]; roominfo[temproomID - 1].made = tempArray[6]; roominfo[temproomID - 1].guardian_pos = tempArray[7]; roominfo[temproomID - 1].people1 = tempArray[8]; roominfo[temproomID - 1].people2 = tempArray[9]; roominfo[temproomID - 1].people3 = tempArray[10]; roominfo[temproomID - 1].people4 = tempArray[11]; byte tempmode = tempArray[5]; roominfo[temproomID - 1].roomtype = tempArray[12]; byte tempmap = tempArray[13]; byte tempmap_num = tempArray[14]; roominfo[temproomID - 1].team1 = tempArray[15]; roominfo[temproomID - 1].team2 = tempArray[16]; roominfo[temproomID - 1].team3 = tempArray[17]; roominfo[temproomID - 1].team4 = tempArray[18]; roominfo[temproomID - 1].ready1 = tempArray[19]; roominfo[temproomID - 1].ready2 = tempArray[20]; roominfo[temproomID - 1].ready3 = tempArray[21]; roominfo[temproomID - 1].ready4 = tempArray[22]; team_Turtle[0] = tempArray[15]; team_Turtle[1] = tempArray[16]; team_Turtle[2] = tempArray[17]; team_Turtle[3] = tempArray[18]; game_mode = tempmode; map_type = tempmap; map_num = tempmap_num; if (SceneChange.instance.GetSceneState() == 6 || SceneChange.instance.GetSceneState() == 7) { GameRoom.instance.SetMode_2(game_mode); GameRoom.instance.SetMap_2(map_type); GameRoom.instance.SetMapNum2(map_num); bool tempbool = temproomID == GameRoom.instance.GetRoomID(); if (tempbool) { pos_guardian = tempArray[7]; for (byte i = 0; i < 4; ++i) { people_inRoom[i] = tempArray[8 + i]; } } } ////Debug.Log("SEtRoomState Completed"); } public void SetRoomState_Respond(byte[] b) { byte[] tempArray = new byte[14]; Buffer.BlockCopy(b, 0, tempArray, 0, 10); m_roomid = tempArray[3]; pos_inRoom = tempArray[4]; //Debug.Log(pos_inRoom); pos_guardian = tempArray[5]; for (byte i = 0; i < 4; ++i) { people_inRoom[i] = tempArray[6 + i]; } for(byte i = 0; i < 4; ++i) { team_Turtle[i] = tempArray[10 + i]; } } public void SetRoomCreate_Respond(byte[] b) { byte[] tempArray = new byte[4]; people_inRoom[0] = NetTest.instance.GetId(); pos_inRoom = 1; is_guardian = 1; pos_guardian = 1; m_roomid = b[3]; } // Update is called once per frame void Update() { if (SceneManager.GetActiveScene().buildIndex == 1) { Destroy(this.gameObject); } } } <file_sep>#pragma once #include <iostream> #include <vector> #include <set> #include <thread> #include <mutex> #include <queue> #include <stack> #include <set> #include <map> #include <list> #include <thread> #include <string> #include <chrono> #include <WinSock2.h> #include <Windows.h> #include <random> #include <cmath> #include <atlstr.h> #include <windows.h> #include <wininet.h> #include <stdio.h> #include<fstream> #include<iterator> #include <math.h> #pragma warning(disable : 4996) //#pragma comment(linker,"/entry:WinMainCRTStartup /subsystem:console") #pragma comment(lib, "ws2_32") using namespace std; #define TB_SERVER_PORT 9000 #define MAX_BUFF_SIZE 4000 #define MAX_USER 4 #define MAX_NPC 50 #define CASE_POS 1 #define CASE_BOMB 2 #define CASE_BOMB_EX 3 #define CASE_MAP 4 #define CASE_ID 5 #define CASE_ITEM_GET 6 #define CASE_DEAD 7 #define CASE_ROOM 8 #define CASE_GAMESET 15 #define CASE_JOINROOM 9 #define CASE_CREATEROOM 10 #define CASE_READY 11 #define CASE_STARTGAME 12 #define CASE_OUTROOM 13 #define CASE_FORCEOUTROOM 14 #define CASE_ROOMSETTING 15 #define CASE_TEAMSETTING 16 #define CASE_THROWBOMB 17 #define CASE_KICKBOMB 18 #define CASE_THROWCOMPLETE 19 #define CASE_KICKCOMPLETE 20 #define CASE_MAPSET 21 #define CASE_BOXPUSH 22 #define CASE_BOXPUSHCOMPLETE 23 #define CASE_TIME 24 #define CASE_BOMBSET 25 #define SIZEOF_TB_CharPos 22 #define SIZEOF_TB_BombPos 17 #define SIZEOF_TB_BombExplode 13 #define SIZEOF_TB_BombExplodeRE 15 #define SIZEOF_TB_MAP 227 #define SIZEOF_TB_ID 3 #define SIZEOF_TB_ItemGet 13 #define SIZEOF_TB_GetItem 4 #define SIZEOF_TB_DEAD 3 #define SIZEOF_TB_GAMEEND 3 #define SIZEOF_TB_Room 31 #define SIZEOF_TB_join 12 #define SIZEOF_TB_joinRE 10 #define SIZEOF_TB_create 12 #define SIZEOF_TB_createRE 4 #define SIZEOF_TB_GameStart 4 #define SIZEOF_TB_GameStartRE 3 #define SIZEOF_CASE_READY 5 #define SIZEOF_TB_ReadyRE 5 #define SIZEOF_TB_RoomOut 4 #define SIZEOF_TB_RoomOutRE 3 #define SIZEOF_TB_GetOut 4 #define SIZEOF_TB_GetOutRE 2 #define SIZEOF_TB_RoomSetting 6 #define SIZEOF_TB_TeamSetting 5 #define SIZEOF_TB_ThrowBomb 13 #define SIZEOF_TB_ThrowBombRE 20 #define SIZEOF_TB_ThrowComplete 11 #define SIZEOF_TB_MapSetRE 11 #define SIZEOF_TB_BoxPush 13 #define SIZEOF_TB_BoxPushComplete 11 #define SIZEOF_TB_BoxPushRE 21 #define SIZEOF_TB_Time 6 #define MAX_EVENT_SIZE 64 #define MAP_NOTHING 0 #define MAP_BOX 1 #define MAP_ROCK 2 #define MAP_BUSH 3 #define MAP_ITEM 11 #define MAP_BOMB 5 #define MAP_ITEM_F 13 #define MAP_ITEM_S 12 #define MAP_FIREBUSH 10 #define MAP_KICKITEM 14 #define MAP_THROWITEM 15 #define MAP_CHAR 7 #define MAP_ENEMY 8 #define MAP_BOSS 9 #define BASIC_POSX_CHAR1 0 #define BASIC_POSZ_CHAR1 0 #define BASIC_POSX_CHAR2 0 #define BASIC_POSZ_CHAR2 0 #define BASIC_POSX_CHAR3 0 #define BASIC_POSZ_CHAR3 0 #define BASIC_POSX_CHAR4 0 #define BASIC_POSZ_CHAR4 0 #define TURTLE_ANI_IDLE 0 #define TURTLE_ANI_WALK 1 #define TURTLE_ANI_HIDE 2 #define TURTLE_ANI_DEAD 3 #define TURTLE_ANI_KICK 4 #define TURTLE_ANI_PUSH 5 #pragma pack(push,1) struct Socket_Info { SOCKET sock; bool m_connected; bool m_getpacket; char buf[MAX_BUFF_SIZE]; int type; int id; int recvbytes; int sendbytes; int remainbytes; BYTE roomID; //디폴트는 0. 안 들어갔다는 뜻 BYTE is_guardian; //방장인지 아닌지 BYTE is_ready; //추가 BYTE fire; BYTE bomb; BYTE speed; BYTE pos_inRoom; }; struct GameCharInfo { BYTE speed; BYTE fire; BYTE bomb; }; struct TB_CharPos {//type:1 BYTE size; //22 BYTE type; BYTE ingame_id; BYTE anistate; BYTE is_alive; BYTE room_id; BYTE fire; BYTE bomb; BYTE can_throw; BYTE can_kick; float posx; float posz; float rotY; }; struct TB_BombPos { //type:2 BYTE size;//17 BYTE type; BYTE ingame_id; BYTE firepower; //화력 //BYTE throwing; //던져지고 있는지 //BYTE kicking; //차여지고 있는지 BYTE room_num; int posx; int posz; float settime; }; struct TB_BombSetRE { BYTE size;//11 BYTE type;//25 BYTE f_power; int posx; int posz; }; struct TB_MapSetRE { BYTE size;//11 BYTE type;//21 BYTE m_type; int posx; int posz; }; struct TB_BombExplode { //type:3 BYTE size;//13 BYTE type; BYTE firepower; BYTE room_id; BYTE game_id; int posx; int posz; }; struct TB_BombExplodeRE { //type:3 BYTE size;//15 BYTE type; BYTE upfire; BYTE rightfire; BYTE downfire; BYTE leftfire; BYTE gameID; int posx; int posz; }; struct TB_ThrowBomb { BYTE size;//13 BYTE type;//17 BYTE roomid; BYTE ingame_id; BYTE direction; int posx; int posz; }; struct TB_ThrowBombRE { BYTE size;//20 BYTE type;//17 BYTE direction; BYTE ingame_id; int posx; int posz; int posx_re; int posz_re; }; struct TB_ThrowComplete { BYTE size;//11 BYTE type;//19 BYTE roomid; int posx; int posz; }; struct TB_KickBomb { BYTE size;//13 BYTE type;//18 BYTE roomid; BYTE ingame_id; BYTE direction; int posx; int posz; }; struct TB_KickComplete { BYTE size;//11 BYTE type;//20 BYTE roomid; int posx; int posz; }; struct TB_KickBombRE { BYTE size;//21 BYTE type;//18 BYTE kick; BYTE ingame_id; BYTE direction; int posx; int posz; int posx_re; int posz_re; }; struct TB_BoxPush { BYTE size;//13 BYTE type;//22 BYTE roomid; BYTE ingame_id; BYTE direction; int posx; int posz; }; struct TB_BoxPushRE { BYTE size;//21 BYTE type;//22 BYTE push; //0이면 안밀어, 1이면 밀어~! BYTE ingame_id; BYTE direction; int posx; int posz; int posx_d; int posz_d; }; struct TB_BoxPushComplete { BYTE size;//11 BYTE type;//19 BYTE roomid; int posx; int posz; }; struct TB_ReGame { }; struct TB_Map { //type:4 BYTE size;//227 BYTE type; BYTE mapInfo[15][15]; }; struct TB_ID {//type:5 BYTE size; //3 BYTE type; BYTE id; //0330 수정 int에서- BYTE로 수정 }; struct TB_ItemGet { //type:6 BYTE size; //13 BYTE type;//6 BYTE room_id; BYTE ingame_id; BYTE item_type; int posx; int posz; }; struct TB_GetItem { //send : type 6 서버 전송-> 클라 수신 BYTE size; //4 BYTE type;//6 BYTE ingame_id; BYTE itemType; //타입에 따라 다른 문구가 출력된다 + 능력이 오른다. }; struct TB_DEAD { //죽었을 때 알려주는 패킷 BYTE size; //3 BYTE type;//7 BYTE game_id; //누가 죽었나! }; struct TB_GAMEEND { BYTE size; //3 BYTE type;//15 BYTE winner_id; //누가 이겼나! }; struct TB_UserInfo { //유저정보 - type: 7 BYTE size; //9 BYTE type; BYTE id; //인게임 id와는 다르다. BYTE roomID; //디폴트는 0. 안 들어갔다는 뜻 BYTE is_guardian;//방장인지 아닌지 BYTE is_ready; //추가 BYTE fire; BYTE bomb; BYTE speed; }; //프로토콜이 아닌 구조체에 맵데이터를 넣은 방 구조체 작성 struct TB_Room { //방장 추가(완) BYTE size; //31 BYTE type;//8 BYTE roomID; BYTE people_count; BYTE game_start; //게임 시작 1 BYTE people_max; //최대 인원 수 BYTE made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) BYTE guardian_pos; //배열에 넣을 때 -1할 것 BYTE people_inroom[4]; BYTE roomstate; //팀전인가 개인전인가? 0-개인전 1-팀전 BYTE map_thema; BYTE map_mode; BYTE team_inroom[4]; BYTE ready[4]; char password[8]; }; struct TB_Ready { BYTE size; //5 BYTE type;//11 BYTE room_num; BYTE pos_in_room; BYTE will_ready; // 0이면 레디하겠다고 보내온 것, 1이면 레디를 해제하겠다고 보내온 것. }; struct TB_ReadyRE { BYTE size; //5 BYTE type;//11 BYTE pos_in_room; BYTE ready;//0이면 레디해제, 1이면 레디 BYTE roomid; }; struct TB_GameStart { BYTE size;//4 BYTE type;//12 BYTE roomID; BYTE my_pos; }; struct TB_GameStartRE { BYTE size; BYTE type; BYTE startTB;//1이면 시작,0이면 땡 }; struct TB_Refresh { //type:? BYTE size; BYTE type; BYTE id; BYTE roomID; }; struct TB_join { //들어갈 때 보내는 패킷 9 BYTE size; BYTE type;//9 BYTE id; BYTE roomID; char password[8]; }; struct TB_joinRE { //방장 추가 BYTE size;//10 BYTE type; BYTE respond; //0이면 no, 1이면 yes BYTE my_room_num; BYTE yourpos; //1,2,3,4 중 하나 BYTE guard_pos; //방장 위치 BYTE people_inroom[4]; }; struct TB_create { //type:10 BYTE size; BYTE type; BYTE id; BYTE roomid; char password[8]; }; struct TB_createRE { BYTE size; BYTE type; BYTE can; //가능하면 1, 불가능하면 0 BYTE roomid; }; struct TB_GetOut {//클라 전송->서버 수신, 서버 전송할 경우 받은 클라는 강퇴 결과 출력 BYTE size; BYTE type;//14 BYTE roomID; BYTE position; }; //받았을 경우 turtle_room.people_count-=1; turtle_waitroom.roodID = 0; struct TB_RoomOut {//방에서 나갈 때 BYTE size;//4 BYTE type;//13 BYTE roomID; BYTE my_pos; }; struct TB_GetOUTRE { BYTE size; BYTE type;//14 }; struct TB_RoomOutRE { BYTE size; BYTE type; BYTE can; //가능하면 1, 불가능하면 0 }; struct TB_RoomSetting { BYTE size;//6 BYTE type;//15 BYTE roomid; BYTE peoplemax; //인원수 BYTE mapthema; BYTE mapnum; }; struct TB_TeamSetting { BYTE size;//5 BYTE type;//16 BYTE roomid; BYTE pos_in_room; BYTE team; }; struct TB_Time { BYTE size;//6 BYTE type;//24 float time; }; struct TB_Room_Data { //방장 추가(완) BYTE roomID; BYTE people_count; BYTE game_start; BYTE people_max; //최대 인원 수 BYTE made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) BYTE guardian_pos; //배열에 넣을 때 -1할 것 BYTE people_inroom[4]; TB_Map map; char password[8]; }; struct Map_TB { BYTE mapTile[15][15]; }; #pragma pack(pop) class InGameCalculator { bool id[4]; float time; bool gameover; public: int deathcount; InGameCalculator() { deathcount = 0; id[0] = true; id[1] = true; id[2] = true; id[3] = true; time = 180.0f; gameover = false; } ~InGameCalculator() {} void InitClass() { deathcount = 0; gameover = false; id[0] = true; id[1] = true; id[2] = true; id[3] = true; time = 180.0f; } void PlayerDead(BYTE idd) { if (id[idd]) { id[idd] = false; deathcount++; } } void PlayerBlank(int id_p) { id[id_p] = false; } void SetGameOver() { gameover = true; } bool IsGameOver() { return gameover; } float GetTime() { return time; } void SetTime(DWORD a) { float temp = ((float)a) / 1000.0f; time = time - temp; } bool OneSec() { return ((int)(time * 10)%10)<1; } BYTE GetWinnerID() { for (BYTE i = 0; i < 4; ++i) { if (id[i]) return i; } return 4; //DRAW를 뜻한다. } }; template <class Iter,class Value> Iter myFind(Iter a, Iter b, Value val) { Iter p = a; while (a != b) { if (*a == val) return a; else ++a; } return b; } class Bomb_TB { public: int x, z; pair<int, int> xz; float time; bool is_throw; bool is_kicked; BYTE firepower; float explode_time; BYTE room_num; BYTE game_id; bool operator ==(const Bomb_TB& other) { return xz == other.xz; } Bomb_TB() { x = 0; z = 0; time = (float)GetTickCount() / 1000; explode_time = 2.0f; xz = make_pair(x, z); is_throw = false; is_kicked = false; } Bomb_TB(int a, int b) { x = a; z = b; time = (float)GetTickCount() / 1000; explode_time = 2.0f; xz = make_pair(a, b); is_throw = false; is_kicked = false; } Bomb_TB(int a, int b, BYTE r, BYTE f,BYTE g) { x = a; z = b; time = (float)GetTickCount() / 1000; explode_time = 2.0f; room_num = r; firepower = f; game_id = g; xz = make_pair(a, b); is_throw = false; is_kicked = false; } bool GetTime() { float temptime = (float)GetTickCount() / 1000; return (temptime - time >= explode_time) && !is_throw && !is_kicked; } void ResetExplodeTime() { float temptime = (float)GetTickCount() / 1000; temptime = temptime - time; explode_time = explode_time - temptime; } void ResetTime() { time = (float)GetTickCount() / 1000; } pair<int, int> GetXZ() { return xz; } };<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; static class DEFAULT_STATUS { public const int BOMB = 1; public const int FIRE = 1; public const int SPEED = 1; } static class MAX_STATUS { public const int BOMB = 5; public const int FIRE = 5; public const int SPEED = 5; } static class STATUS_CORRECTION { public const float SPEED = 1.1f; } public class Player : Bomb_Setter { Animator m_TurtleMan_Animator; Animator m_Camera_Animator; GameObject m_Front_Box; public void Set_Front_Box(GameObject g) { m_Front_Box = g; } GameObject m_Temp_Bomb; GameObject m_Selected_Bomb_For_Throwing; Player_Sound m_Player_Sound; SkinnedMeshRenderer[] m_Player_Mesh_Renderers; // 캐릭터 상태 bool m_isBoxSelected = false; public void Set_is_Box_Selected(bool b) { m_isBoxSelected = b; } public bool Get_is_Box_Selected() { return m_isBoxSelected; } bool m_isPushing = false; bool m_is_Hiden = false; public bool Get_is_Hiden() { return m_is_Hiden; } bool m_isGot_KickItem = false; bool m_isGot_ThrowItem = false; bool m_isAbleToPush = false; public void Set_is_Able_to_Push(bool b) { m_isAbleToPush = b; } public bool Get_is_Able_to_Push() { return m_isAbleToPush; } bool m_isAbleToKick = false; public void Set_is_Able_to_Kick(bool b) { m_isAbleToKick = b; } public bool Get_is_Able_to_Kick() { return m_isAbleToKick; } bool m_isAbleToThrow = false; public void Set_is_Able_to_Throw(bool b) { m_isAbleToThrow = b; } public bool Get_is_Able_to_Throw() { return m_isAbleToThrow; } int m_Touch_Num = 0; bool m_is_Touch_Started = false; // 이전 터치 지점 (x값) float m_Touch_PrevPoint_X; // 회전 감도 float m_RotateSensX = 120.0f; // 폭탄 배치를 위한 위치값 float m_BombLocX = 0.0f; float m_BombLocZ = 0.0f; // 폭탄 배치를 위한 인덱스값 int m_Bombindex_X = 0; int m_Bombindex_Z = 0; // 플레이어 생존 여부 bool m_isAlive = true; // 기본 속도 float m_BasicSpeed = 3.0f; // 아이템 속도 int m_Speed_Count; // 현재 속도 float m_Curr_Speed = 0.0f; // 박스 밀기 거리 float m_push_Distance = 0.0f; IEnumerator m_Wait_For_Intro; // ======== Functions ======== void Awake() { m_TurtleMan_Animator = transform.GetChild(0).GetComponent<Animator>(); m_Camera_Animator = transform.GetChild(1).GetComponent<Animator>(); m_Player_Mesh_Renderers = GetComponentsInChildren<SkinnedMeshRenderer>(); StageManager.GetInstance().Set_is_Player_Alive(true); m_Max_Bomb_Count = DEFAULT_STATUS.BOMB; m_Curr_Bomb_Count = m_Max_Bomb_Count; m_Fire_Count = DEFAULT_STATUS.FIRE; m_Speed_Count = DEFAULT_STATUS.SPEED; Curr_Move_Speed_Update(); m_Player_Sound = GetComponentInChildren<Player_Sound>(); m_Wait_For_Intro = Wait_For_Intro(); StartCoroutine(m_Wait_For_Intro); } public void Player_Set_Start_Point(Vector3 p) { transform.position = p; // 플레이어 위치를 시작지점으로 옮긴다. } IEnumerator Wait_For_Intro() { while (true) { if (StageManager.GetInstance().Get_is_Intro_Over()) StopCoroutine(m_Wait_For_Intro); yield return null; } } void Update() { if (StageManager.GetInstance().Get_is_Intro_Over() && !StageManager.GetInstance().Get_is_Pause()) { GetComponent<Rigidbody>().velocity = new Vector3(0.0f, 0.0f, 0.0f); if (!m_isPushing) Move(); else Pushing(); } } void OnTriggerEnter(Collider other) { if (m_isAlive) { // 아이템 획득 관련 if (other.gameObject.CompareTag("Bomb_Item")) { Destroy(other.gameObject); if (Get_Curr_Bomb_Count() < MAX_STATUS.BOMB) { m_Player_Sound.Play_Item_Get_Sound(); m_Max_Bomb_Count += 1; m_Curr_Bomb_Count += 1; UI.GetInstance().Stat_UI_Management(m_Curr_Bomb_Count, m_Max_Bomb_Count, m_Fire_Count, m_Speed_Count); UI.GetInstance().GetItemUI_Activate(0); } } if (other.gameObject.CompareTag("Fire_Item")) { Destroy(other.gameObject); if (Get_Fire_Count() < MAX_STATUS.FIRE) { m_Player_Sound.Play_Item_Get_Sound(); m_Fire_Count += 1; UI.GetInstance().Stat_UI_Management(m_Curr_Bomb_Count, m_Max_Bomb_Count, m_Fire_Count, m_Speed_Count); UI.GetInstance().GetItemUI_Activate(1); } } if (other.gameObject.CompareTag("Speed_Item")) { Destroy(other.gameObject); if (m_Speed_Count < MAX_STATUS.SPEED) { m_Player_Sound.Play_Item_Get_Sound(); m_Speed_Count += 1; Curr_Move_Speed_Update(); UI.GetInstance().Stat_UI_Management(m_Curr_Bomb_Count, m_Max_Bomb_Count, m_Fire_Count, m_Speed_Count); UI.GetInstance().GetItemUI_Activate(2); } } if (other.gameObject.CompareTag("Kick_Item")) { Destroy(other.gameObject); if (!m_isGot_KickItem) { m_Player_Sound.Play_Item_Get_Sound(); m_isGot_KickItem = true; UI.GetInstance().Kick_Icon_Activate(); UI.GetInstance().GetItemUI_Activate(3); } } if (other.gameObject.CompareTag("Throw_Item")) { Destroy(other.gameObject); if (!m_isGot_ThrowItem) { m_Player_Sound.Play_Item_Get_Sound(); m_isGot_ThrowItem = true; UI.GetInstance().Throw_Icon_Activate(); UI.GetInstance().GetItemUI_Activate(4); } } if (other.gameObject.CompareTag("Airdrop_Item")) { Destroy(other.gameObject); m_Player_Sound.Play_Item_Get_Sound(); //int temp = Random.Range(1, 3); m_Max_Bomb_Count += 1; //temp; m_Curr_Bomb_Count += 1; // temp; if (m_Max_Bomb_Count > MAX_STATUS.BOMB) { m_Max_Bomb_Count = MAX_STATUS.BOMB; m_Curr_Bomb_Count = MAX_STATUS.BOMB; } //temp = Random.Range(1, 3); m_Fire_Count += 1; // temp; if (m_Fire_Count > MAX_STATUS.FIRE) m_Fire_Count = MAX_STATUS.FIRE; //temp = Random.Range(1, 3); m_Speed_Count += 1; // temp; if (m_Speed_Count > MAX_STATUS.SPEED) m_Speed_Count = MAX_STATUS.SPEED; Curr_Move_Speed_Update(); UI.GetInstance().Stat_UI_Management(m_Curr_Bomb_Count, m_Max_Bomb_Count, m_Fire_Count, m_Speed_Count); UI.GetInstance().GetItemUI_Activate(5); } // ======================== // 사망 판정 // 스테이지 클리어시, 맵 이동시는 사망하지 않는다. if ((other.gameObject.tag == "Flame" || other.gameObject.tag == "Flame_Bush" || other.gameObject.tag == "Monster_Attack_Collider" || other.gameObject.tag == "icicle_Body") && !StageManager.GetInstance().Get_is_Stage_Clear()) { Set_Dead(); } // ======================== // 맵 전환 포탈 if (other.gameObject.CompareTag("Map_Portal")) { // 다음 맵을 로드한다. StageManager.GetInstance().Next_Map_Load(); } // =============================== // 목표 지점 도달 시 스테이지 클리어 if (other.gameObject.CompareTag("Goal")) { UI.GetInstance().Set_is_Goal(true); StageManager.GetInstance().SetGoalIn(true); StageManager.GetInstance().Stage_Clear(); } // =============================== } } void OnTriggerStay(Collider other) { if (other.gameObject.tag == "Bush") { foreach (SkinnedMeshRenderer pmr in m_Player_Mesh_Renderers) pmr.enabled = false; m_is_Hiden = true; UI.GetInstance().HideInBush_Management(true); } } void OnTriggerExit(Collider other) { // 폭탄 트리거 비활성 if (other.gameObject.tag == "Bomb") { if (!other.gameObject.GetComponent<Bomb_Remaster>().Get_is_Hardend()) { m_isAbleToThrow = false; other.isTrigger = false; m_Selected_Bomb_For_Throwing = null; other.gameObject.GetComponent<Bomb_Remaster>().Set_is_Hardend(true); UI.GetInstance().Throw_Button_Management(false); } } // ===================== // 부쉬를 벗어날 경우 if (other.gameObject.tag == "Bush") { foreach (SkinnedMeshRenderer pmr in m_Player_Mesh_Renderers) pmr.enabled = true; m_is_Hiden = false; UI.GetInstance().HideInBush_Management(false); } // ======================= } void OnCollisionEnter(Collision collision) { // 폭탄 발차기 if (m_isGot_KickItem && m_isAbleToKick) { // 현재 캐릭터가 발차기가 가능한 상태이면서, 폭탄은 던져진 상태가 아니어야 한다. if (collision.gameObject.CompareTag("Bomb")) { if (!collision.gameObject.GetComponent<Bomb_Remaster>().Get_is_Thrown()) { collision.gameObject.GetComponent<Bomb_Remaster>().Kick_Bomb(gameObject); m_isAbleToKick = false; m_TurtleMan_Animator.SetBool("TurtleMan_isKick", true); Invoke("Kick_Ani_False", 0.4f); } } } } // ======== UDF ========= void Move() { Body_MoveControl_ForMobile(); // 릴리즈용 //Body_MoveControl_ForPC(); // 디버그용 //Body_RotateControl_ForPC(); // 디버그용 Body_RotateControl_ForMobile(); // 릴리즈용 //OtherControl_ForPC(); // 디버그용 } void Body_MoveControl_ForPC() { if (Input.GetKey(KeyCode.W)) { transform.Translate(new Vector3(0.0f, 0.0f, (m_Curr_Speed * Time.deltaTime))); m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); //m_Player_Sound.Play_Move_Sound(); } if (Input.GetKey(KeyCode.S)) { transform.Translate(new Vector3(0.0f, 0.0f, -(m_Curr_Speed * Time.deltaTime))); m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); //m_Player_Sound.Play_Move_Sound(); } if (Input.GetKey(KeyCode.A)) { transform.Translate(new Vector3(-(m_Curr_Speed * Time.deltaTime), 0.0f, 0.0f)); m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); //m_Player_Sound.Play_Move_Sound(); } if (Input.GetKey(KeyCode.D)) { transform.Translate(new Vector3((m_Curr_Speed * Time.deltaTime), 0.0f, 0.0f)); m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); //m_Player_Sound.Play_Move_Sound(); } if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D)) { m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", false); } } void Body_MoveControl_ForMobile() { if (JoyStickMove.instance.Get_NormalizedVector() != Vector3.zero) { Vector3 normal = JoyStickMove.instance.Get_NormalizedVector(); normal.z = normal.y; normal.y = 0.0f; transform.Translate(m_Curr_Speed * normal * Time.deltaTime); m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); //m_Player_Sound.Play_Move_Sound(); } else { m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", false); } } void Body_RotateControl_ForPC() { if (Input.GetKey(KeyCode.LeftArrow)) { transform.Rotate(transform.up, -m_RotateSensX * Time.deltaTime); } if (Input.GetKey(KeyCode.RightArrow)) { transform.Rotate(transform.up, m_RotateSensX * Time.deltaTime); } } void Body_RotateControl_ForMobile() { if (Input.touchCount > 0 && UI.GetInstance().Get_isClicked()) // 회전 터치가 감지됨. { if (!m_is_Touch_Started) // 터치가 이제 막 시작됐다! (손을 모두 뗄 때 까지 더이상 수행하지 않음.) { if (JoyStickMove.instance.Get_is_Joystick_First_Touched()) m_Touch_Num = 1; // 조이스틱이 먼저다! else m_Touch_Num = 0; // 회전이 먼저다! m_is_Touch_Started = true; // OK. } switch (Input.GetTouch(m_Touch_Num).phase) // 회전 처리 { case TouchPhase.Began: m_Touch_PrevPoint_X = Input.GetTouch(m_Touch_Num).position.x; break; case TouchPhase.Moved: transform.Rotate(0, (Input.GetTouch(m_Touch_Num).position.x - m_Touch_PrevPoint_X) * 0.5f, 0); m_Touch_PrevPoint_X = Input.GetTouch(m_Touch_Num).position.x; break; } } else m_is_Touch_Started = false; } void OtherControl_ForPC() { if (Input.GetKeyDown(KeyCode.Space)) SetBomb(); if (m_isAbleToPush && !m_isPushing && Input.GetKeyDown(KeyCode.R)) { if (m_Front_Box != null) BoxPush(); } } void Curr_Move_Speed_Update() { m_Curr_Speed = m_BasicSpeed + (m_Speed_Count * STATUS_CORRECTION.SPEED); } public void SetBomb() // 폭탄 설치 { if (StageManager.GetInstance().Get_is_Intro_Over() && !StageManager.GetInstance().Get_is_Pause()) { if (m_Curr_Bomb_Count > 0 && !StageManager.GetInstance().Get_MCL_is_Blocked_With_Coord(transform.position.x, transform.position.z)) { m_Player_Sound.Play_Bomb_Set_Sound(); m_Temp_Bomb = Bomb_Set(CALL_BOMB_STATE.NORMAL); m_TurtleMan_Animator.SetBool("TurtleMan_isDrop", true); m_Camera_Animator.SetBool("Set_Bomb", true); Invoke("SetBomb_Ani_False", 0.3f); UI.GetInstance().Stat_UI_Management(m_Curr_Bomb_Count, m_Max_Bomb_Count, m_Fire_Count, m_Speed_Count); if (m_isGot_ThrowItem) { m_isAbleToThrow = true; m_Selected_Bomb_For_Throwing = m_Temp_Bomb; UI.GetInstance().Throw_Button_Management(true); } m_Temp_Bomb = null; } } } public void BoxPush() // 박스 밀기 시작 { if (m_isBoxSelected && m_isAbleToPush && StageManager.GetInstance().Get_is_Intro_Over() && !StageManager.GetInstance().Get_is_Pause()) { // 플레이어 위치 변환 // 플레이어의 현재 MCL 인덱스를 찾는다. int index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); // 플레이어의 위치를 MCL 내부 좌표로 이동시킨다. Vector3 Loc; Loc.x = StageManager.GetInstance().m_Map_Coordinate_List[index].x; Loc.y = transform.position.y; Loc.z = StageManager.GetInstance().m_Map_Coordinate_List[index].z; transform.position = Loc; // -------------------------------- // 플레이어 방향 변환 Vector3 dir = m_Front_Box.transform.position - transform.position; Vector3 dirXZ = new Vector3(dir.x, 0f, dir.z); if (dirXZ != Vector3.zero) { Quaternion targetRot = Quaternion.LookRotation(dirXZ); transform.rotation = targetRot; } //-------------------------------- // 밀기 애니메이션 실행 m_TurtleMan_Animator.SetBool("TurtleMan_isPush", true); m_Camera_Animator.SetBool("Push", true); // 원활한 밀기를 위해.. m_isPushing = true; m_isAbleToPush = false; // MCL 갱신 Vector3 pos = m_Front_Box.transform.position + transform.forward * 2.0f; index = StageManager.GetInstance().Find_Own_MCL_Index(pos.x, pos.z); m_Front_Box.GetComponent<Box>().Reset_MCL_index(index); } } void Pushing() // 박스를 미는 과정과 마무리 { if (m_Front_Box != null) { m_push_Distance += m_BasicSpeed * Time.deltaTime; if (m_push_Distance <= 2.0f) { m_Front_Box.transform.position += transform.forward * m_BasicSpeed * Time.deltaTime; transform.position += transform.forward * m_BasicSpeed * Time.deltaTime; } // 밀고난 뒤 박스가 정확한 자리로 가도록 조정해준다. else { int index = StageManager.GetInstance().Find_Own_MCL_Index(m_Front_Box.transform.position.x, m_Front_Box.transform.position.z); Vector3 Loc; Loc.x = StageManager.GetInstance().m_Map_Coordinate_List[index].x; Loc.y = m_Front_Box.transform.position.y; Loc.z = StageManager.GetInstance().m_Map_Coordinate_List[index].z; m_Front_Box.transform.position = Loc; StageManager.GetInstance().Update_MCL_isBlocked(index, true); m_push_Distance = 0.0f; m_isPushing = false; Push_Ani_False(); } } else { m_push_Distance = 0.0f; m_isPushing = false; Push_Ani_False(); } } public void Bomb_Throw() // 폭탄 던지기 { // 플레이어 위치 조정 및 애니메이션 수행 transform.position = new Vector3(m_Selected_Bomb_For_Throwing.transform.position.x, transform.position.y, m_Selected_Bomb_For_Throwing.transform.position.z); float PlayerAngleY = 0.0f; if (transform.localEulerAngles.y >= 315.0f && transform.localEulerAngles.y < 45.0f) PlayerAngleY = 0.0f; else if (transform.localEulerAngles.y >= 45.0f && transform.localEulerAngles.y < 135.0f) PlayerAngleY = 90.0f; else if (transform.localEulerAngles.y >= 135.0f && transform.localEulerAngles.y < 225.0f) PlayerAngleY = 180.0f; else if (transform.localEulerAngles.y >= 225.0f && transform.localEulerAngles.y < 315.0f) PlayerAngleY = 270.0f; transform.localEulerAngles = new Vector3(0.0f, PlayerAngleY, 0.0f); m_Selected_Bomb_For_Throwing.GetComponent<Bomb_Remaster>().Throw_Bomb(gameObject); m_TurtleMan_Animator.SetBool("TurtleMan_isThrow", true); m_Camera_Animator.SetTrigger("Throw"); Invoke("Throw_Ani_False", 0.3f); // 선택 폭탄 해제 m_Selected_Bomb_For_Throwing = null; m_isAbleToThrow = false; UI.GetInstance().Throw_Button_Management(false); } void Throw_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isThrow", false); } void Kick_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isKick", false); } void Push_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isPush", false); m_Camera_Animator.SetBool("Push", false); m_Front_Box = null; } public void SetBomb_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isDrop", false); m_Camera_Animator.SetBool("Set_Bomb", false); } //다른 스크립트에서 플레이어를 죽게 하는 함수 public void Set_Dead() { m_TurtleMan_Animator.SetBool("TurtleMan_isDead", true); m_Camera_Animator.SetTrigger("Dead"); m_isAlive = false; StageManager.GetInstance().Set_is_Player_Alive(false); } //살아있는지에 대한 여부를 다른 스크립트에서 get하는 함수-R public bool Get_IsAlive() { return m_isAlive; } //게임오버 애니메이션 함수 public void MakeGameOverAni() { m_Camera_Animator.SetTrigger("Dead"); } public void Camera_Wave() { Debug.Log("Ringing"); m_Camera_Animator.SetTrigger("Ring"); #if UNITY_ANDROID if (!Audio_Manager.GetInstance().Get_is_Vibration_Mute()) Handheld.Vibrate(); // 1초간 진동 #endif } public void UI_Status_Update() { UI.GetInstance().Stat_UI_Management(m_Curr_Bomb_Count, m_Max_Bomb_Count, m_Fire_Count, m_Speed_Count); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // #define SceneNumbers static class PlayerPrefs_Manager_Constants { public const int Title_Start_Scene = 9999; public const int Mode_Select_Scene = 0; public const int Mode_Adventure = 1; public const int Mode_Coop = 2; public const int Mode_Competition = 3; public const int MAX_STAGE_NUM = 9; } public class PlayerPrefs_Manager : MonoBehaviour { // 씬 넘버를 받아온다. // 빌드 세팅의 씬 넘버와는 다르니 주의! public int m_SceneNumber; static PlayerPrefs_Manager m_Instance; public static List<int> m_Stage_Stars_List; public Texture Activated_Star_Image; public Texture Activated_Bomb_Image; public Texture Activated_Boss_Image; void Start() { switch (m_SceneNumber) { case PlayerPrefs_Manager_Constants.Title_Start_Scene: // 타이틀 씬 입장 시 Pref_Debug_Mode(); // 디버깅용 //Pref_Init(); // 별, 스테이지 초기화용 //PlayerPrefs.SetInt("Have_you_been_Play", 0); // 기기 초기화를 한번 해야겠다 할때 쓰는 코드 // ★ 이하는 릴리즈 모드에서 반드시 활성화 해야함! ★ //if (!PlayerPrefs.HasKey("Have_you_been_Play")) // 기기상에서 한번도 실행한적이 없다면 // Pref_Init(); // 플레이 정보 초기화 break; case PlayerPrefs_Manager_Constants.Mode_Select_Scene: // 모드 선택 씬 입장 시 if (PlayerPrefs.GetInt("is_Open_Mode_Competition") == 1) { Mode_Select_Scene_Manager.c_Mode_Select_manager.Open_Competition_Mode(); } if (PlayerPrefs.GetInt("is_Open_Mode_Coop") == 1) { Mode_Select_Scene_Manager.c_Mode_Select_manager.Open_Coop_Mode(); } break; case PlayerPrefs_Manager_Constants.Mode_Adventure: // 모험모드 스테이지 선택 씬 입장 시 int[] mission_nums = new int[3]; string tempString; int tempStars = 0; // 1: 활성화, 0: 비활성화 // 플레이 가능한 최대 스테이지를 받아온다. int playable_max_stage = PlayerPrefs.GetInt("Mode_Adventure_Playable_Max_Stage"); // 1번부터 순차적으로 최대 스테이지 까지 수행한다. for (int i = 0; i <= playable_max_stage; ++i) { // 버튼을 활성화 시킨다. Mode_Adventure_Stage_Select_Scene_Manager.GetInstance().m_Stage_Button_List[i].interactable = true; // 버튼 이미지를 변경한다. if (i == 5 || i == 9 || i == 14 || i == 19) // 보스 스테이지 { Mode_Adventure_Stage_Select_Scene_Manager.GetInstance().m_Stage_Button_List[i].gameObject.GetComponent<RawImage>().texture = Activated_Boss_Image; } else // 일반 스테이지 { Mode_Adventure_Stage_Select_Scene_Manager.GetInstance().m_Stage_Button_List[i].gameObject.GetComponent<RawImage>().texture = Activated_Bomb_Image; // 텍스트도 활성화 시킨다. Mode_Adventure_Stage_Select_Scene_Manager.GetInstance().m_Stage_Button_List[i].transform.Find("Number").gameObject.SetActive(true); } // 획득했던 별을 받아온다. tempStars = 0; CSV_Manager.GetInstance().Get_Adv_Mission_Num_List(ref mission_nums, i); for (int j = 0; j < 3; ++j) { tempString = "Adventure_Stars_ID_" + mission_nums[j].ToString(); if (PlayerPrefs.GetInt(tempString) == 1) ++tempStars; } // 받아온 별만큼 활성화 시킨다. for (int j = 0; j < tempStars; ++j) Mode_Adventure_Stage_Select_Scene_Manager.GetInstance().m_Stage_Button_List[i].gameObject.GetComponentsInChildren<RawImage>()[j + 1].texture = Activated_Star_Image; } break; case PlayerPrefs_Manager_Constants.Mode_Competition: break; case PlayerPrefs_Manager_Constants.Mode_Coop: break; } } public static PlayerPrefs_Manager GetInstance() { return m_Instance; } // PlayerPrefs 초기화 함수 void Pref_Init() { PlayerPrefs.SetInt("Have_you_been_Play", 1); PlayerPrefs.SetInt("System_Option_BGM_ON", 1); // BGM ON PlayerPrefs.SetInt("System_Option_SE_ON", 1); // Sound Effect ON PlayerPrefs.SetInt("System_Option_Vib_ON", 1); // Vibration ON PlayerPrefs.SetInt("is_Opened_Mode_Competition", 0); // 대전모드 -> 1 : 열기, 0 : 닫기 PlayerPrefs.SetInt("is_Opened_Mode_Coop", 0); int max_Mission_Num = 0; CSV_Manager.GetInstance().Get_Adv_Max_Mission_Num(ref max_Mission_Num); string temp; for (int i = 1; i <= max_Mission_Num; ++i) { temp = "Adventure_Stars_ID_" + i.ToString(); PlayerPrefs.SetInt(temp, 0); } PlayerPrefs.SetInt("Mode_Adventure_Playable_Max_Stage", 0); // 튜토리얼로 설정 1 PlayerPrefs.SetInt("Mode_Adventure_Stage_ID_For_MapLoad", 18); // 튜토리얼로 설정 2 PlayerPrefs.SetInt("Mode_Adventure_Current_Stage_ID", 0); // 튜토리얼로 설정 3 PlayerPrefs.Save(); // 저장 } void Pref_Debug_Mode() { PlayerPrefs.SetInt("Have_you_been_Play", 1); if (!PlayerPrefs.HasKey("System_Option_BGM_ON")) PlayerPrefs.SetInt("System_Option_BGM_ON", 1); // BGM ON if (PlayerPrefs.GetInt("System_Option_BGM_ON") == 0) LobbySound.instanceLS.SoundStop(); else LobbySound.instanceLS.SoundStart(); if (!PlayerPrefs.HasKey("System_Option_SE_ON")) PlayerPrefs.SetInt("System_Option_SE_ON", 1); // Sound Effect ON if (!PlayerPrefs.HasKey("System_Option_Vib_ON")) PlayerPrefs.SetInt("System_Option_Vib_ON", 1); // Vibration ON if (!PlayerPrefs.HasKey("System_Option_Auto_Login_ON")) PlayerPrefs.SetInt("System_Option_Auto_Login_ON", 1); // Auto_Login ON PlayerPrefs.SetInt("is_Opened_Mode_Competition", 0); PlayerPrefs.SetInt("is_Opened_Mode_Coop", 0); int max_Mission_Num = 0; CSV_Manager.GetInstance().Get_Adv_Max_Mission_Num(ref max_Mission_Num); string temp; for (int i = 1; i <= max_Mission_Num; ++i) { temp = "Adventure_Stars_ID_" + i.ToString(); PlayerPrefs.SetInt(temp, 0); } int max_num = 0, max_num_for_load = 0; CSV_Manager.GetInstance().Get_Adv_Max_Stage_Num(ref max_num, ref max_num_for_load); PlayerPrefs.SetInt("Mode_Adventure_Playable_Max_Stage", max_num); // 최대로 설정 1 PlayerPrefs.SetInt("Mode_Adventure_Stage_ID_For_MapLoad", max_num_for_load); // 최대로 설정 2 PlayerPrefs.SetInt("Mode_Adventure_Current_Stage_ID", 0); // 초기화 PlayerPrefs.Save(); // 저장 } } // ========================================== // PlayerPref 내용물들 // ========================================== // Have_you_been_Play : 최초 플레이 여부 확인 // is_Opened_Mode_Competition : 대전모드 해제 여부 확인 // is_Opened_Mode_Coop : 협동모드 해제 여부 확인 // Adventure_Stars_ID_?? : 모험모드 퀘스트ID-?? 의 획득 별 개수 // Mode_Adventure_Playable_Max_Stage : 모험모드 최대 이용가능 스테이지 번호 // Mode_Adventure_Stage_ID_For_MapLoad : 모험모드 입장시 선택한 스테이지 번호 (맵로드를 위한..) // Mode_Adventure_Current_Stage_ID : 모험모드 입장시 선택한 스테이지 번호 // System_Option_BGM_ON : 시스템 옵션의 BGM 기능이 켜졌는가 // System_Option_SE_ON : 시스템 옵션의 효과음 기능이 켜졌는가 // System_Option_Vib_ON : 시스템 옵션의 진동 기능이 켜졌는가 // System_Option_Auto_Login_ON : 시스템 옵션의 자동로그인 기능이 켜졌는가<file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; public class Serial_Script { private MemoryStream m_buffer = null; private int m_offset = 0; //Class 생성자 public Serial_Script() { // 시리얼라이즈용 버퍼 생성 m_buffer = new MemoryStream(); int val = 1; byte[] conv = BitConverter.GetBytes(val); } public byte[] GetSerializedData() { return m_buffer.ToArray(); } public void Clear() { byte[] buffer = m_buffer.GetBuffer(); Array.Clear(buffer, 0, buffer.Length); m_buffer.Position = 0; m_buffer.SetLength(0); m_offset = 0; } // // 디시리얼라이즈할 데이터를 버퍼에 설정한다. // public bool SetDeserializedData(byte[] data) { // 설정할 버퍼를 클리어한다. Clear(); try { // 디시리얼라이즈할 데이터를 설정한다. m_buffer.Write(data, 0, data.Length); } catch { return false; } return true; } // // byte형 데이터를 시리얼라이즈 합니다. // protected bool Serialize(byte element) { byte[] data = BitConverter.GetBytes(element); return WriteBuffer(data, sizeof(byte)); } // // byte[]형 데이터를 시리얼라이즈한다. // protected bool Serialize(byte[] element, int length) { return WriteBuffer(element, length); } // // bool형 데이터를 시리얼라이즈한다. // protected bool Serialize(bool element) { byte[] data = BitConverter.GetBytes(element); return WriteBuffer(data, sizeof(bool)); } // // char형 데이터를 시리얼라이즈한다. // protected bool Serialize(char element) { byte[] data = BitConverter.GetBytes(element); return WriteBuffer(data, sizeof(char)); } // // string형 데이터를 시리얼라이즈한다. // protected bool Serialize(string element, int length) { byte[] data = new byte[length]; byte[] buffer = System.Text.Encoding.UTF8.GetBytes(element); int size = Math.Min(buffer.Length, data.Length); Buffer.BlockCopy(buffer, 0, data, 0, size); return WriteBuffer(data, data.Length); } // char[]형 데이터를 시리얼라이즈한다. // protected bool Serialize(char[] element, int length) { string temp = new string(element); return Serialize(temp, length); } // // float형 데이터를 시리얼라이즈한다. // protected bool Serialize(float element) { byte[] data = BitConverter.GetBytes(element); return WriteBuffer(data, sizeof(float)); } // // int형 데이터를 시리얼라이즈한다. // protected bool Serialize(int element) { byte[] data = BitConverter.GetBytes(element); return WriteBuffer(data, sizeof(int)); } // 데이터를 bool형으로 디시리얼라이즈한다. // protected bool Deserialize(ref bool element) { int size = sizeof(bool); byte[] data = new byte[size]; // bool ret = ReadBuffer(ref data, data.Length); if (ret == true) { element = BitConverter.ToBoolean(data, 0); return true; } return false; } // // 데이터를 char형으로 디시리얼라이즈한다. // protected bool Deserialize(ref char element) { int size = sizeof(char); byte[] data = new byte[size]; // bool ret = ReadBuffer(ref data, data.Length); if (ret == true) { element = BitConverter.ToChar(data, 0); return true; } return false; } // 데이터를 char[]형으로 디시리얼라이즈한다. // protected bool Deserialize(ref char[] element, int length) { //int size = sizeof(char); byte[] data = new byte[length]; bool ret = ReadBuffer(ref data, data.Length); if (ret == true) { element = System.Text.Encoding.UTF8.GetString(data).ToCharArray(); //element = BitConverter.ToChar(data, 0); return true; } return false; } // // 데이터를 float형으로 디시리얼라이즈한다. // protected bool Deserialize(ref float element) { int size = sizeof(float); byte[] data = new byte[size]; // bool ret = ReadBuffer(ref data, data.Length); if (ret == true) { element = BitConverter.ToSingle(data, 0); return true; } return false; } // 데이터를 int형으로 디시리얼라이즈한다. // protected bool Deserialize(ref int element) { int size = sizeof(int); byte[] data = new byte[size]; // bool ret = ReadBuffer(ref data, data.Length); if (ret == true) { element = BitConverter.ToInt32(data, 0); return true; } return false; } protected bool ReadBuffer(ref byte[] data, int size) { // 현재 오프셋에서 데이터를 읽어냄 try { m_buffer.Position = m_offset; m_buffer.Read(data, 0, size); m_offset += size; } catch { return false; } return true; } // byte형 데이터로 디시리얼라이즈한다. protected bool Deserialize(ref byte element, int length) { byte[] data = BitConverter.GetBytes(element); bool ret = ReadBuffer(ref data, length); element = data[0]; if (ret == true) { return true; } return false; } // // byte[]형 데이터로 디시리얼라이즈한다. // protected bool Deserialize(ref byte[] element, int length) { bool ret = ReadBuffer(ref element, length); if (ret == true) { return true; } return false; } protected bool WriteBuffer(byte[] data, int size) { // 현재 오프셋에서 데이터를 써넣음 try { m_buffer.Position = m_offset; m_buffer.Write(data, 0, size); m_offset += size; } catch { return false; } return true; } public long GetDataSize() { return m_buffer.Length; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.InteropServices; public class Queue { struct PacketInfo { public int offset; public int size; }; private MemoryStream m_streamBuffer; private Object lockObj = new Object(); private List<PacketInfo> m_offsetList; private int m_offset = 0; //class 생성자 public Queue() { m_streamBuffer = new MemoryStream(); m_offsetList = new List<PacketInfo>(); } public int InputQueue(byte[] d, int size) { PacketInfo info = new PacketInfo(); info.offset = m_offset; info.size = size; lock (lockObj) { // 패킷 저장 정보를 보존. m_offsetList.Add(info); // 패킷 데이터를 보존. m_streamBuffer.Position = m_offset; m_streamBuffer.Write(d, 0, size); m_streamBuffer.Flush(); m_offset = m_offset + size; } return size; } public bool IsPacket() { if (m_offsetList.Count != 0) return true; else return false; } public int Dequeue(ref byte[] buffer, int size) { if (m_offsetList.Count <= 0) { return -1; } int recvSize = 0; lock (lockObj) { PacketInfo info = m_offsetList[0]; // 버퍼에서 해당하는 패킷 데이터를 획득한다. int dataSize = Math.Min(size, info.size); m_streamBuffer.Position = info.offset; recvSize = m_streamBuffer.Read(buffer, 0, dataSize); // 큐 데이터를 추출했으므로 선두 요소를 삭제. if (recvSize > 0) { m_offsetList.RemoveAt(0); } // 모든 큐 데이터를 추출했을 때는 스트림을 클리어해서 메모리를 절약한다. if (m_offsetList.Count == 0) { Clear(); m_offset = 0; } } return recvSize; } //큐 비우기 public void Clear() { byte[] buffer = m_streamBuffer.GetBuffer(); Array.Clear(buffer, 0, buffer.Length); m_streamBuffer.Position = 0; m_streamBuffer.SetLength(0); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Performance_Camera : MonoBehaviour { public Camera m_PlayerView; public static Performance_Camera c_PerfCamera; public Animator m_CameraAnimator; IEnumerator m_Intro_Normal_Performance; void Start() { c_PerfCamera = this; m_Intro_Normal_Performance = WaitFor_EndOf_Intro_Normal_Performance(); // 코루틴 함수 등록 Player_To_Perf(); Intro_Performance(); // 인트로 수행 } IEnumerator WaitFor_EndOf_Intro_Normal_Performance() // 일반 인트로 모션 완료를 기다린다. { while (true) { if (m_CameraAnimator.GetCurrentAnimatorStateInfo(0).fullPathHash == Animator.StringToHash("Base Layer.Camera_Performance_Intro_Normal")) { if (m_CameraAnimator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.99f) // 완료되면 { StopCoroutine(m_Intro_Normal_Performance); // 코루틴 종료 Intro_Performance_Over(); // 인트로 모션 완료 알림 } } yield return null; } } public void Player_To_Perf() // 카메라 전환 (플레이어->퍼포먼스) { m_PlayerView.enabled = false; m_PlayerView.GetComponent<AudioListener>().enabled = false; gameObject.GetComponent<Camera>().enabled = true; gameObject.GetComponent<AudioListener>().enabled = true; } public void Perf_To_Player() // 카메라 전환 (퍼포먼스->플레이어) { m_PlayerView.enabled = true; m_PlayerView.GetComponent<AudioListener>().enabled = true; gameObject.GetComponent<Camera>().enabled = false; gameObject.GetComponent<AudioListener>().enabled = false; } public void Intro_Performance() { if (StageManager.GetInstance().Get_is_Boss_Stage()) { //m_CameraAnimator.SetTrigger("Intro_Boss"); Intro_Performance_Over(); } else { m_CameraAnimator.SetTrigger("Intro_Normal"); // 일반 인트로 모션 시작 StartCoroutine(m_Intro_Normal_Performance); // 일반 인트로 대기 코루틴 실행 } } public void Intro_Performance_Over() { StageManager.GetInstance().Set_is_Intro_Over(true); Perf_To_Player(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Icicle_Bottom : MonoBehaviour { void OnTriggerStay(Collider other) { if (other.CompareTag("Box")) { other.GetComponent<Box>().Save_Icicle_Bottom_Collider(gameObject); transform.parent.GetComponent<Icicle>().Icicle_Behavior_Stop(); } } void OnTriggerExit(Collider other) { if (other.CompareTag("Box")) { other.GetComponent<Box>().Clear_Icicle_Bottom_Collider(); transform.parent.GetComponent<Icicle>().Icicle_Behavior_Start(); } } public void TriggerExit_Ver2() { transform.parent.GetComponent<Icicle>().Icicle_Behavior_Start(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; static class Monster_AI_Constants { public const float Walk_Time = 3.0f; public const float Attack_Time = 1.0f; public const float Boss_Attack_Time = 0.3f; } public class MonsterAI : MonoBehaviour { Animator m_Goblman_Animator; Monster_Player_Detector m_Attack_Detector; Transform m_Attack_Collider; IEnumerator m_Current_Behavior; IEnumerator m_Behavior_Move; IEnumerator m_Behavior_Chase; IEnumerator m_Behavior_Attack; Vector3 m_V3_To_Find_my_rightObject; Vector3 m_V3_To_Find_my_leftObject; int m_My_MCL_Index = 0; int m_Right_Object_Index = 0; int m_Left_Object_Index = 0; bool m_isFound_Turtleman; float m_Monster_Basic_Speed; float m_WalkTimer; float m_AttackTimer; bool m_isDead; bool m_isAttacking; float m_escape_Time; void Start() { StageManager.GetInstance().Increase_Normal_Monster_Count(); // 몬스터 개수 증가 // 객체 자신이 가지고 있는 애니메이터를 찾아온다. m_Goblman_Animator = GetComponent<Animator>(); m_Attack_Detector = GetComponentInChildren<Monster_Player_Detector>(); m_Attack_Collider = transform.Find("Attack_Range"); m_Attack_Collider.gameObject.SetActive(false); m_WalkTimer = 0.0f; m_AttackTimer = 0.0f; m_escape_Time = 0.0f; m_Monster_Basic_Speed = 2.0f; m_isDead = false; m_isAttacking = false; m_isFound_Turtleman = false; // 몬스터의 행동 코루틴들을 설정 m_Behavior_Move = MonsterMove(); //m_Behavior_Chase = ; m_Behavior_Attack = MonsterAttack(); // 처음 실행할 행동 설정 m_Current_Behavior = MonsterMove(); StartCoroutine(Wait_For_Intro()); } void OnCollisionEnter(Collision collision) { // 아래 구문을 통해 몬스터가 막힌 길로 들어서지 않도록 한다. if (collision.gameObject.CompareTag("Box") || collision.gameObject.CompareTag("Wall") || collision.gameObject.CompareTag("Rock") || collision.gameObject.CompareTag("Bomb")) { // 올바른 위치로 이동 Set_Right_Position(); // 방향도 전환시킨다. Find_New_Way(); } if (collision.gameObject.CompareTag("Monster")) { Find_New_Way(); } // ============================== } void OnTriggerEnter(Collider other) { // 몬스터가 불에 닿으면 사망 판정 if (!m_isDead && (other.gameObject.tag == "Flame" || other.gameObject.CompareTag("Flame_Bush"))) { GetComponentInChildren<Normal_Goblin_Sound>().Play_DeadSound(); StageManager.GetInstance().Decrease_Normal_Monster_Count(); // 불에 닿아 죽는것만 카운팅. m_Goblman_Animator.SetBool("Goblman_isDead", true); m_isDead = true; StopCoroutine(MonsterBehavior()); Invoke("MonsterDead", 1.5f); } //=============================== } void Think() { // 플레이어가 감지범위 안에 들어왔고, 공격모션 중이 아니라면 // 공격 if (m_Attack_Detector.m_isInRange && !m_isAttacking) { if (m_Current_Behavior != m_Behavior_Attack) m_Current_Behavior = m_Behavior_Attack; //m_isAttacking = true; if (m_Attack_Detector.Get_Target()) { Vector3 dir = m_Attack_Detector.Get_Target().transform.position - transform.position; Vector3 dirXZ = new Vector3(dir.x, 0f, dir.z); if (dirXZ != Vector3.zero) { Quaternion targetRot = Quaternion.LookRotation(dirXZ); transform.rotation = targetRot; } } } // 플레이어가 감지범위 밖에 있고, 공격모션 중이 아니라면 // 걷기 else if (!m_Attack_Detector.m_isInRange && !m_isAttacking) { // 이전 행동이 "공격"이었다면 // 방향을 수정한다. if (m_Current_Behavior == m_Behavior_Attack) { float AngleY = 0.0f; if (transform.localEulerAngles.y >= 315.0f && transform.localEulerAngles.y < 45.0f) AngleY = 0.0f; else if (transform.localEulerAngles.y >= 45.0f && transform.localEulerAngles.y < 135.0f) AngleY = 90.0f; else if (transform.localEulerAngles.y >= 135.0f && transform.localEulerAngles.y < 225.0f) AngleY = 180.0f; else if (transform.localEulerAngles.y >= 225.0f && transform.localEulerAngles.y < 315.0f) AngleY = 270.0f; transform.localEulerAngles = new Vector3(0.0f, AngleY, 0.0f); Set_Right_Position(); } if (m_Current_Behavior != m_Behavior_Move) { m_Current_Behavior = m_Behavior_Move; } } } IEnumerator Wait_For_Intro() { while(true) { if (StageManager.GetInstance().Get_is_Intro_Over()) { StopAllCoroutines(); StartCoroutine(MonsterBehavior()); } yield return null; } } IEnumerator MonsterBehavior() { while (true) { Think(); if (!StageManager.GetInstance().Get_is_Pause() && !m_isDead && m_Current_Behavior != null && m_Current_Behavior.MoveNext()) { yield return m_Current_Behavior.Current; } else { yield return null; } } } IEnumerator MonsterMove() { while (true) { m_WalkTimer += Time.deltaTime; if (m_WalkTimer < Monster_AI_Constants.Walk_Time) { transform.Translate(new Vector3(0.0f, 0.0f, (m_Monster_Basic_Speed * Time.deltaTime))); m_Goblman_Animator.SetBool("Goblman_isWalk", true); m_Goblman_Animator.SetBool("Goblman_isIdle", false); Find_My_Coord(); } else { GetComponentInChildren<Normal_Goblin_Sound>().Play_IdleSound(); m_Goblman_Animator.SetBool("Goblman_isWalk", false); m_Goblman_Animator.SetBool("Goblman_isIdle", true); yield return new WaitForSeconds(2.0f); m_WalkTimer = 0.0f; } yield return null; } } IEnumerator MonsterAttack() { while (true) { m_AttackTimer += Time.deltaTime; if (m_AttackTimer < Monster_AI_Constants.Attack_Time) { if (!m_Goblman_Animator.GetBool("Goblman_isAttack")) { GetComponentInChildren<Normal_Goblin_Sound>().Play_AttackSound(); m_Attack_Collider.gameObject.SetActive(true); // 충돌체 활성화 m_Goblman_Animator.SetBool("Goblman_isAttack", true); m_Goblman_Animator.SetBool("Goblman_isIdle", false); m_isAttacking = true; } } else { m_Goblman_Animator.SetBool("Goblman_isAttack", false); m_Goblman_Animator.SetBool("Goblman_isIdle", true); m_Attack_Collider.gameObject.SetActive(false); m_isAttacking = false; m_AttackTimer = 0.0f; yield return new WaitForSeconds(0.5f); } yield return null; } } void MonsterDead() { Destroy(gameObject); } // 몬스터가 새로운 길을 찾도록 하는 함수 void Find_New_Way() { m_V3_To_Find_my_leftObject = transform.position - transform.right * 2.0f; m_V3_To_Find_my_rightObject = transform.position + transform.right * 2.0f; m_Right_Object_Index = Find_Objects_Coord(m_V3_To_Find_my_rightObject.x, m_V3_To_Find_my_rightObject.z); m_Left_Object_Index = Find_Objects_Coord(m_V3_To_Find_my_leftObject.x, m_V3_To_Find_my_leftObject.z); if (m_Left_Object_Index != -1 && StageManager.GetInstance().Get_MCL_index_is_Blocked(m_Left_Object_Index) == false) { transform.Rotate(-transform.up * 90.0f); } else if (m_Right_Object_Index != -1 && StageManager.GetInstance().Get_MCL_index_is_Blocked(m_Right_Object_Index) == false) { transform.Rotate(transform.up * 90.0f); } else transform.Rotate(transform.up * 180.0f); } // ============================== public void Set_Basic_Speed(float s) { m_Monster_Basic_Speed = s; } // 몬스터 자신의 MCL 인덱스를 받아오는 함수 void Find_My_Coord() { if (StageManager.GetInstance().Get_is_init_MCL()) { m_My_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); } } // ========================================= // 몬스터 자신의 MCL 인덱스에 해당하는 위치로 옮겨주는 함수 void Set_Right_Position() { if (StageManager.GetInstance().Get_is_init_MCL()) { m_My_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); if (m_My_MCL_Index != -1) { Vector3 Loc; Loc.x = StageManager.GetInstance().m_Map_Coordinate_List[m_My_MCL_Index].x; Loc.y = transform.position.y; Loc.z = StageManager.GetInstance().m_Map_Coordinate_List[m_My_MCL_Index].z; transform.position = Loc; } } } // ========================================= // 오브젝트의 좌표를 통하여 해당 MCL 인덱스를 반환한다. int Find_Objects_Coord(float x, float z) { if (StageManager.GetInstance().Get_is_init_MCL()) { return StageManager.GetInstance().Find_Own_MCL_Index(x, z); } return -1; } // ========================================= } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class Flame_Crash_Portal : MonoBehaviour { float m_FlameSpawnTime = 2.0f; float m_curr_time = 0.0f; bool is_adventure; public GameObject m_Flame_Crash; void Start() { is_adventure = true; if (SceneManager.GetActiveScene().buildIndex == 3) { is_adventure = true; } else if (SceneManager.GetActiveScene().buildIndex == 12) { is_adventure = false; } } void Update () { if (is_adventure) { if (m_curr_time < m_FlameSpawnTime) m_curr_time += Time.deltaTime; else { Vector3 pos = transform.position; pos.y = m_Flame_Crash.transform.position.y; Instantiate(m_Flame_Crash).transform.position = pos; // 화염생성. Destroy(gameObject); // 나는 사라진다. } } else { if (m_curr_time < m_FlameSpawnTime) { m_Flame_Crash.SetActive(false); m_curr_time += Time.deltaTime; } else { Vector3 pos = transform.position; pos.y = m_Flame_Crash.transform.position.y; m_Flame_Crash.SetActive(true); m_Flame_Crash.transform.position = pos; // 화염생성. m_curr_time = 0.0f; gameObject.SetActive(false); // 나는 사라진다. } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Jet_Goblin_Sound : Sound_Effect { public AudioClip m_AudioClips; public void Play_Bomb_Throw_Sound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bomb_Network : MonoBehaviour { public GameObject m_flame_effect; byte firepower; //방에서 포인트 설정 // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void ReLoad() { this.gameObject.SetActive(true); } void Explode(byte fire_power) { GameObject Instance_FlameDir_N; GameObject Instance_FlameDir_S; GameObject Instance_FlameDir_W; GameObject Instance_FlameDir_E; for (byte i = 0; i < firepower; ++i) { Instance_FlameDir_N = Instantiate(m_flame_effect); Instance_FlameDir_N.transform.position = new Vector3(gameObject.transform.position.x, 0.0f, gameObject.transform.position.z + (2.0f * (i + 1))); Instance_FlameDir_S = Instantiate(m_flame_effect); Instance_FlameDir_S.transform.position = new Vector3(gameObject.transform.position.x, 0.0f, gameObject.transform.position.z - (2.0f * (i + 1))); Instance_FlameDir_W = Instantiate(m_flame_effect); Instance_FlameDir_W.transform.position = new Vector3(gameObject.transform.position.x - (2.0f * (i + 1)), 0.0f, gameObject.transform.position.z); Instance_FlameDir_E = Instantiate(m_flame_effect); Instance_FlameDir_E.transform.position = new Vector3(gameObject.transform.position.x + (2.0f * (i + 1)), 0.0f, gameObject.transform.position.z); } this.gameObject.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Flame_Remains : MonoBehaviour { float Flame_Remains_LifeTime; IEnumerator m_Cycle_Checker; void Awake() { m_Cycle_Checker = Cycle_Check(); } public void Cycle_Start() { Flame_Remains_LifeTime = 1.0f; StartCoroutine(m_Cycle_Checker); } IEnumerator Cycle_Check() { while (true) { if (!StageManager.GetInstance().Get_is_Pause()) { if (Flame_Remains_LifeTime <= 0.0f) { StopCoroutine(m_Cycle_Checker); gameObject.SetActive(false); } else Flame_Remains_LifeTime -= Time.deltaTime; } yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.EventSystems; public class JoyStickMove : MonoBehaviour, IDragHandler, IPointerUpHandler, IPointerDownHandler { public static JoyStickMove instance; Vector3 inputVector; public RawImage joystick_HandleImage; private RawImage joystick_BackGroundImage; private Vector3 unNormalizedInput; // public int joystickHandleDistance = 2; private Vector3[] fourCornersArray = new Vector3[4]; // used to get the bottom right corner of the image in order to ensure that the pivot of the joystick's background image is always at the bottom right corner of the image (the pivot must always be placed on the bottom right corner of the joystick's background image in order to the script to work) private Vector2 bgImageStartPosition; bool touched = false; // void Awake() { instance = this; } void Start () { joystick_BackGroundImage = GetComponent<RawImage>(); joystick_BackGroundImage.rectTransform.GetWorldCorners(fourCornersArray); bgImageStartPosition = fourCornersArray[3]; joystick_BackGroundImage.rectTransform.pivot = new Vector2(1, 0); joystick_BackGroundImage.rectTransform.anchorMin = new Vector2(0, 0); joystick_BackGroundImage.rectTransform.anchorMax = new Vector2(0, 0); joystick_BackGroundImage.rectTransform.position = bgImageStartPosition; } public Vector3 Get_NormalizedVector() { return joystick_HandleImage.rectTransform.anchoredPosition.normalized; } public float GetJoyPosX() { return joystick_HandleImage.rectTransform.anchoredPosition.x; } public float GetJoyPosZ() { return joystick_HandleImage.rectTransform.anchoredPosition.y; } public virtual void OnDrag (PointerEventData ped) { Vector2 localP = Vector2.zero; if (RectTransformUtility.ScreenPointToLocalPointInRectangle(joystick_BackGroundImage.rectTransform, ped.position, ped.pressEventCamera, out localP)) { localP.x = (localP.x / joystick_BackGroundImage.rectTransform.sizeDelta.x); localP.y = (localP.y / joystick_BackGroundImage.rectTransform.sizeDelta.y); inputVector = new Vector3(localP.x * 2 + 1, localP.y * 2 - 1, 0); unNormalizedInput = inputVector; inputVector = (inputVector.magnitude > 1.0f) ? inputVector.normalized : inputVector; joystick_HandleImage.rectTransform.anchoredPosition = new Vector2(inputVector.x * (joystick_BackGroundImage.rectTransform.sizeDelta.x / joystickHandleDistance), inputVector.y * (joystick_BackGroundImage.rectTransform.sizeDelta.y / joystickHandleDistance)); } } public virtual void OnPointerDown(PointerEventData eventP) { touched = true; OnDrag(eventP); } public virtual void OnPointerUp(PointerEventData eventP) { inputVector = Vector3.zero; joystick_HandleImage.rectTransform.anchoredPosition = new Vector2(0,0); } public void Touched() { touched = true; } public void UnTouched() { touched = false; } public bool Get_is_Joystick_First_Touched() // 조이스틱이 먼저냐 회전이 먼저냐! { if (Input.GetTouch(0).phase == TouchPhase.Began) // 첫번째 터치가 시작될 때 { if (UI.GetInstance().Get_isClicked()) // 회전이 먼저면 return false; // false 리턴 } return true; // 조이스틱이 먼저면 true 리턴. } public bool Get_is_Joystick_First_Touched_Net() // 조이스틱이 먼저냐 회전이 먼저냐! { if (Input.GetTouch(0).phase == TouchPhase.Began) { // 이미 회전중이면 if (VSModeManager.instance.Get_isClicked()||CoOpManager.instance.Get_isClicked()) return false; // 회전이 먼저다! } return true; // 조이스틱이 먼저다! } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using UnityEngine.UI; public class NetUser4 : MonoBehaviour { public static NetUser4 instance; public Text m_TurtleTXT; public TextMesh m_TM; public GameObject p; bool textmesh_On = false; byte id = 254; byte color = 0; bool dead_ani = false; Animator m_animator; void Awake() { instance = this; } // Use this for initialization void Start() { m_animator = GetComponent<Animator>(); //p = GetComponent<GameObject>(); //Invoke("IDCheck", 2.0f); dead_ani = false; } void SetFalse() { gameObject.SetActive(false); } public void SetDeadMotion() { dead_ani = true; } public void SetText(byte itemtype) { textmesh_On = true; color = itemtype; } public void SetTextOff() { m_TM.gameObject.SetActive(false); } void IDCheck() { if (p != null) { if (Turtle_Move.instance.GetId() == 3 || Turtle_Move.instance.GetId() > 3) { } // else // StartCoroutine("NetworkCheck"); } } public void SetPos(float x, float y, float z) { float tempx = x - transform.position.x; float tempz = z - transform.position.z; float tempy = y - transform.rotation.y; for (int i = 0; i < 4; ++i) { //transform.position = new Vector3(transform.position.x+(tempx/4), transform.position.y, transform.position.z+(tempz/4)); transform.position = Vector3.MoveTowards(transform.position, new Vector3(transform.position.x + (tempx / 4), transform.position.y, transform.position.z + (tempz / 4)), 0.5f); transform.rotation = new Quaternion(transform.rotation.x, transform.rotation.y + (tempy / 4), transform.rotation.z, transform.rotation.w); //Thread.Sleep(125); //new WaitForSeconds(0.125f); //yield WaitForSeconds(0.125f); } } // Update is called once per frame void Update() { if (dead_ani) { m_TM.gameObject.SetActive(true); m_TM.text = "1P - Dead!!!"; m_animator.SetBool("death", true); Invoke("SetTextOff", 2.0f); Invoke("SetFalse", 1.1f); dead_ani = false; } if (VariableManager.instance.pos_inRoom - 1 == 3) { p.SetActive(false); } else { p.SetActive(true); } SetPos(NetTest.instance.GetNetPosx(3), NetTest.instance.GetNetRoty(3), NetTest.instance.GetNetPosz(3)); if (textmesh_On) { m_TM.gameObject.SetActive(true); switch (color) { case 0: m_TM.color = new Color(0, 0, 1); m_TM.text = "Bomb Up~"; break; case 1: m_TM.color = new Color(1, 0, 0); m_TM.text = "Fire Up~"; break; case 2: m_TM.color = new Color(1, 1, 0); m_TM.text = "Speed Up~"; break; default: break; } Invoke("SetTextOff", 2.0f); textmesh_On = false; } //m_TM.text = "X:" + transform.position.x; } IEnumerator NetworkCheck() { for (; ; ) { SetPos(NetTest.instance.GetNetPosx(3), NetTest.instance.GetNetRoty(3), NetTest.instance.GetNetPosz(3)); yield return new WaitForSeconds(0.05f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Shake_Checker : MonoBehaviour { public bool m_isInRange = false; GameObject m_Player; public GameObject Get_Target() { return m_Player; } void OnTriggerEnter(Collider other) { if(!m_isInRange && other.gameObject.CompareTag("Player")) { m_isInRange = true; m_Player = other.gameObject; } } void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Player")) Set_Out_of_Range(); } public void Set_Out_of_Range() { m_isInRange = false; m_Player = null; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TitleScript : MonoBehaviour { public Animator m_Animator; public GameObject m_Bomb_Sound; bool m_is_Clicked = false; public void MakeWave() { if (!m_is_Clicked) { m_Bomb_Sound.GetComponent<Bomb_Sound>().Play_ExplodeSound(); m_Animator.SetTrigger("Touched_Start"); m_is_Clicked = true; #if UNITY_ANDROID if (PlayerPrefs.HasKey("System_Option_Vib_ON") && PlayerPrefs.GetInt("System_Option_Vib_ON") == 1) Handheld.Vibrate(); // 1초간 진동 #endif } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; //타이틀 화면~스테이지선택까지 사운드 출력 함수 public class LobbySound : MonoBehaviour { // 인스턴스 public static LobbySound instanceLS; // 오디오소스 변수 AudioSource audioSource; // 인스턴싱+파괴하지 않음 설정 private void Awake() { audioSource = GetComponent<AudioSource>(); instanceLS = this; DontDestroyOnLoad(this); } public void SoundStop() // BGM Stop { audioSource.Stop(); } public void SoundStart() // BGM Replay { if (!audioSource.isPlaying) audioSource.Play(); } } <file_sep>#include "TB_Server.h" TB_Server::TB_Server() { WSADATA wsa; //콘솔에서 한글 출력 안될 때 해결방법 _wsetlocale(LC_ALL, L"korean"); if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return; user_count = 0; Bind_Server(); } TB_Server::~TB_Server() { closesocket(accept_sock); WSACleanup(); } void TB_Server::err_display(char *msg) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); printf("[%s] %s", msg, (char *)lpMsgBuf); LocalFree(lpMsgBuf); } void TB_Server::err_quit(char* msg) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); MessageBox(NULL, (LPCTSTR)lpMsgBuf, msg, MB_ICONERROR); LocalFree(lpMsgBuf); exit(1); } void TB_Server::Bind_Server() { int retval=0; accept_sock = socket(AF_INET, SOCK_STREAM, 0); if (accept_sock == INVALID_SOCKET) err_quit("socket()"); ZeroMemory(&server_addr, sizeof(server_addr)); server_addr.sin_family = AF_INET; server_addr.sin_addr.s_addr = htonl(INADDR_ANY); server_addr.sin_port = htons(TB_SERVER_PORT); ::bind(accept_sock, reinterpret_cast<SOCKADDR*>(&server_addr), sizeof(server_addr)); retval = listen(accept_sock, SOMAXCONN); if (retval == SOCKET_ERROR) err_quit("listen()"); } void TB_Server::Receive_User() { while (1) { addrlen = sizeof(client_addr); client_sock = accept(accept_sock, (SOCKADDR*)&client_addr, &addrlen); if (client_sock == INVALID_SOCKET) { err_display("accept()"); break; } user_count = user_count + 1; printf("\n[TCP 서버] 클라이언트 접속: IP 주소=%s, 포트 번호=%d\n", inet_ntoa(client_addr.sin_addr), ntohs(client_addr.sin_port)); switch (user_count) { case 1: hThread = CreateThread(NULL, 0, this->Process_ServerP, (LPVOID)client_sock, 0, NULL); break; case 2: break; case 3: break; case 4: break; default: break; } } } DWORD WINAPI TB_Server::Process_Server(LPVOID arg) { while (1) { } return 0; }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class System_Option : MonoBehaviour { public GameObject m_System_Option_Windows; public Button m_BGM_Switch; public Button m_SE_Switch; public Button m_Vib_Switch; public Button m_Auto_Login_Toggle; public Button m_Logout_Button; public Texture m_Switch_On; public Texture m_Switch_Off; public Texture m_Toggle_On; public Texture m_Toggle_Off; void Awake () { if (PlayerPrefs.GetInt("System_Option_BGM_ON") == 0) m_BGM_Switch.GetComponent<RawImage>().texture = m_Switch_Off; if (PlayerPrefs.GetInt("System_Option_SE_ON") == 0) m_SE_Switch.GetComponent<RawImage>().texture = m_Switch_Off; if (PlayerPrefs.GetInt("System_Option_Vib_ON") == 0) m_Vib_Switch.GetComponent<RawImage>().texture = m_Switch_Off; if (PlayerPrefs.GetInt("System_Option_Auto_Login_ON") == 0) m_Auto_Login_Toggle.GetComponent<RawImage>().texture = m_Toggle_Off; } public void Switch_BGM() { if (PlayerPrefs.GetInt("System_Option_BGM_ON") == 0) { m_BGM_Switch.GetComponent<RawImage>().texture = m_Switch_On; PlayerPrefs.SetInt("System_Option_BGM_ON", 1); } else { m_BGM_Switch.GetComponent<RawImage>().texture = m_Switch_Off; PlayerPrefs.SetInt("System_Option_BGM_ON", 0); } if (PlayerPrefs.GetInt("System_Option_BGM_ON") == 0) LobbySound.instanceLS.SoundStop(); else LobbySound.instanceLS.SoundStart(); } public void Switch_SoundEffect() { if (PlayerPrefs.GetInt("System_Option_SE_ON") == 0) { m_SE_Switch.GetComponent<RawImage>().texture = m_Switch_On; PlayerPrefs.SetInt("System_Option_SE_ON", 1); } else { m_SE_Switch.GetComponent<RawImage>().texture = m_Switch_Off; PlayerPrefs.SetInt("System_Option_SE_ON", 0); } } public void Switch_Vibration() { if (PlayerPrefs.GetInt("System_Option_Vib_ON") == 0) { m_Vib_Switch.GetComponent<RawImage>().texture = m_Switch_On; PlayerPrefs.SetInt("System_Option_Vib_ON", 1); } else { m_Vib_Switch.GetComponent<RawImage>().texture = m_Switch_Off; PlayerPrefs.SetInt("System_Option_Vib_ON", 0); } } public void Toggle_Auto_Login() { if (PlayerPrefs.GetInt("System_Option_Auto_Login_ON") == 0) { m_Auto_Login_Toggle.GetComponent<RawImage>().texture = m_Toggle_On; PlayerPrefs.SetInt("System_Option_Auto_Login_ON", 1); } else { m_Auto_Login_Toggle.GetComponent<RawImage>().texture = m_Toggle_Off; PlayerPrefs.SetInt("System_Option_Auto_Login_ON", 0); } } public void System_Option_Window_On() { m_System_Option_Windows.SetActive(true); if (PlayerPrefs.GetInt("System_Option_BGM_ON") == 0) m_BGM_Switch.GetComponent<RawImage>().texture = m_Switch_Off; else m_BGM_Switch.GetComponent<RawImage>().texture = m_Switch_On; if (PlayerPrefs.GetInt("System_Option_SE_ON") == 0) m_SE_Switch.GetComponent<RawImage>().texture = m_Switch_Off; else m_SE_Switch.GetComponent<RawImage>().texture = m_Switch_On; if (PlayerPrefs.GetInt("System_Option_Vib_ON") == 0) m_Vib_Switch.GetComponent<RawImage>().texture = m_Switch_Off; else m_Vib_Switch.GetComponent<RawImage>().texture = m_Switch_On; if (PlayerPrefs.GetInt("System_Option_Auto_Login_ON") == 0) m_Auto_Login_Toggle.GetComponent<RawImage>().texture = m_Toggle_Off; else m_Auto_Login_Toggle.GetComponent<RawImage>().texture = m_Toggle_On; } public void System_Option_Window_Off() { m_System_Option_Windows.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Turtle_Move : MonoBehaviour { public static Turtle_Move instance; int m_Bombindex_X = 0; int m_Bombindex_Z = 0; // 폭탄 배치를 위한 위치값 float m_BombLocX = 0.0f; float m_BombLocZ = 0.0f; public GameObject[] m_DropBomb; bool m_YouCanSetBomb=false; public byte id = 0; public Text state_text; public float m_PlayerSpeed; float m_RotateSensX = 150.0f; bool dead_ani=false; byte fire_power=2; byte bomb_power=2; byte speed_power=2; // 회전 각 public byte alive = 1; float m_RotationX = 0.0f; Animator m_animator; void Awake() { instance = this; } // Use this for initialization void Start () { m_animator = GetComponent<Animator>(); //Invoke("SetAnimation", 1.0f); fire_power = 2; bomb_power = 2; speed_power = 2; alive = 1; //Invoke("SetPosition", 2.0f); SetPosition(); } void OnTriggerEnter(Collider other) { } void SetFalse() { gameObject.SetActive(false); } public byte GetFirePower() { return fire_power; } public void Dead_Case(byte m_id) { if (id == m_id) { //죽음 dead_ani = true; } else { switch (m_id) { //상대방이 죽음 case 0: NetUser.instance.SetDeadMotion(); break; case 1: NetUser2.instance.SetDeadMotion(); break; case 2: NetUser3.instance.SetDeadMotion(); break; case 3: NetUser4.instance.SetDeadMotion(); break; default: break; } } } public void SetItem_Ability(byte m_id, byte type) { if(id == m_id) { switch (type) { case 0: bomb_power++; Debug.Log("Bomb Up~"); break; case 1: fire_power++; Debug.Log("Fire Up~"); break; case 2: speed_power++; Debug.Log("Speed Up~"); break; default: break; } } else { Debug.Log("Not Mine"); switch (m_id) { case 0: NetUser.instance.SetText(type); break; case 1: NetUser2.instance.SetText(type); break; case 2: NetUser3.instance.SetText(type); break; case 3: NetUser4.instance.SetText(type); break; default: break; } } } void SetPosition() { switch (VariableManager.instance.pos_inRoom) { case 1: id = 0; transform.position = new Vector3(0.0f, transform.position.y, 0.0f); break; case 2: id = 1; transform.position = new Vector3(28.0f, transform.position.y, 0.0f); break; case 3: id = 2; transform.position = new Vector3(0.0f, transform.position.y, 28.0f); break; case 4: id = 3; transform.position = new Vector3(28.0f, transform.position.y, 28.0f); break; default: break; } } void SetAnimation() { switch (GameRoom.instance.pos_inRoom) { case 1: id = 0; m_animator.SetTrigger("Jump01"); //transform.position = new Vector3(0.0f, transform.position.y, 0.0f); break; case 2: id = 1; m_animator.SetTrigger("Jump02"); //transform.position = new Vector3(28.0f, transform.position.y, 0.0f); break; case 3: id = 2; m_animator.SetTrigger("Jump03"); //transform.position = new Vector3(0.0f, transform.position.y, 28.0f); break; case 4: id = 3; m_animator.SetTrigger("Jump04"); //transform.position = new Vector3(28.0f, transform.position.y, 28.0f); break; default: break; } } // Update is called once per frame void Update () { state_text.text = "Bomb : " + bomb_power + "\nFire : " + fire_power + "\nSpeed: " + speed_power; if (dead_ani) { Debug.Log("Dead!!!"); m_animator.SetBool("death", true); Invoke("SetFalse", 2.1f); dead_ani = false; } if (Input.GetMouseButton(0)) { m_RotationX += Input.GetAxis("Mouse X") * m_RotateSensX * Time.deltaTime; transform.localEulerAngles = new Vector3(0.0f, m_RotationX, 0.0f); if(!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.W)) { transform.Translate(new Vector3(0.0f, 0.0f, m_PlayerSpeed * Time.deltaTime)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.S)) { transform.Translate(new Vector3(0.0f, 0.0f, -m_PlayerSpeed * Time.deltaTime)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.A)) { transform.Translate(new Vector3(-m_PlayerSpeed * Time.deltaTime, 0.0f, 0.0f)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.D)) { transform.Translate(new Vector3(m_PlayerSpeed * Time.deltaTime, 0.0f, 0.0f)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } KeyBoard_Move(); if (Input.GetKeyDown(KeyCode.Space)) { if (!VSModeManager.instance.game_set) SetBomb(); } } public byte GetId() { return id; } public void SetBomb() // 폭탄 설치 { m_YouCanSetBomb = true; // 폭탄 위치 설정 m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; if (MapManager.instance.Check_BombSet((int)(m_BombLocX / 2), (int)(m_BombLocZ / 2))) { Debug.Log("You can't set bomb"); m_YouCanSetBomb = false; } // 이미 놓인 폭탄 검사 // 폭탄 생성 if (m_YouCanSetBomb) { NetTest.instance.SetBombPos((int)m_BombLocX, (int)m_BombLocZ,fire_power); NetTest.instance.SendBombPacket(); //UI.m_bomb_count = UI.m_bomb_count - 1; } } public void KeyBoard_Move() // 플레이어 이동 및 회전 { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GetID : MonoBehaviour { public static GetID instance = null; public InputField[] m_inputfield; string myID = null; string password = null; public GameObject[] m_inputcase; public GameObject[] m_button; public Button[] m_loginButton; public byte login_type; bool inputID = false; bool inputPass=false; // Use this for initialization private void Awake() { instance = this; myID = "test"; password = "123"; DontDestroyOnLoad(this); login_type = 1; } public string GetIDD() { return myID; } public string GETPW() { return password; } void Start () { } // Update is called once per frame void Update () { if (SceneManager.GetActiveScene().buildIndex == 1) { Destroy(this.gameObject); } if (m_loginButton[0] != null) { if (login_type == 0) { m_loginButton[0].gameObject.SetActive(false); m_loginButton[1].gameObject.SetActive(false); inputID = false; inputPass = false; } else if (login_type != 0 && inputID && inputPass) { m_loginButton[0].gameObject.SetActive(true); m_loginButton[1].gameObject.SetActive(true); } } } public void openField() { m_inputcase[0].gameObject.SetActive(true); m_button[0].gameObject.SetActive(false); m_button[1].gameObject.SetActive(false); login_type = 1; } public void openField2() { m_inputcase[1].gameObject.SetActive(true); m_button[0].gameObject.SetActive(false); m_button[1].gameObject.SetActive(false); login_type = 2; } public void closeField() { m_inputcase[0].gameObject.SetActive(false); m_inputcase[1].gameObject.SetActive(false); m_button[0].gameObject.SetActive(true); m_button[1].gameObject.SetActive(true); login_type = 0; } public void SetId() { myID = m_inputfield[0].text; login_type = 1; //Debug.Log("MyID:" +myID); } public void SetId_Create() { myID = m_inputfield[2].text; login_type = 2; //Debug.Log(myID); } public void IDInput() { inputID = true; //Debug.Log("changed ID"); } public void PasswordInput() { inputPass = true; //Debug.Log("changed PW"); } public void SetPassword() { password = m_inputfield[1].text; //Debug.Log("MyPW:"+password); } public void SetPasswordJoin() { password = m_inputfield[3].text; } public void KeyBoardOpen() { TouchScreenKeyboard.Open("", TouchScreenKeyboardType.Default, false, false, true); //Debug.Log("Open!"); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Turtle_Move_Coop : MonoBehaviour { public static Turtle_Move_Coop instance; public Image fade_image; int m_Bombindex_X = 0; int m_Bombindex_Z = 0; int touchNum = 0; bool m_is_Touch_Started = false; // 폭탄 배치를 위한 위치값 float m_BombLocX = 0.0f; float m_BombLocZ = 0.0f; public GameObject[] m_DropBomb; bool m_YouCanSetBomb = false; byte id = 0; public Text[] state_text; public RawImage[] state_image; public GameObject m_gameover; public Button bombButton; public Button throwButton; float m_Touch_PrevPoint_X; bool fade = false; public float m_PlayerSpeed = 3.0f; float m_RotateSensX = 150.0f; bool dead_ani = false; bool throw_ani = false; bool walk_ani = false; bool push_ani = false; bool kick_ani = false; byte direction; byte fire_power = 1; byte bomb_power = 2; byte bomb_set = 2; byte speed_power = 1; public bool can_kick = false; public bool can_throw = false; Animator m_TurtleMan_Animator; int itemtype = 0; bool getItem = false; bool kick_bomb; // 회전 각 public byte alive = 1; float m_RotationX = 0.0f; public Animator animator_camera; void Awake() { instance = this; } // Use this for initialization void Start() { fade_image.gameObject.SetActive(false); m_TurtleMan_Animator = GetComponent<Animator>(); //Invoke("SetAnimation", 1.0f); fire_power = 1; bomb_power = 2; speed_power = 1; fade = false; kick_bomb = false; alive = 1; direction = 0; //Invoke("SetPosition", 2.0f); SetPosition(); } void Throw_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isThrow", false); } void Walk_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", false); } void Push_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isPush", false); } void Kick_Ani_False() { m_TurtleMan_Animator.SetBool("TurtleMan_isKick", false); } void OnCollisionEnter(Collision collision) { if (can_kick && collision.gameObject.CompareTag("Bomb")) { //kick_bomb = true; Bomb_Kick(); } } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Bomb")) { if (can_throw) { bombButton.gameObject.SetActive(false); throwButton.gameObject.SetActive(true); } } if (other.gameObject.CompareTag("Flame_Bush")) { alive = 0; NetManager_Coop.instance.SetmoveTrue(); } if (other.gameObject.CompareTag("Monster_Attack_Collider")) { alive = 0; NetManager_Coop.instance.SetmoveTrue(); } } private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Bomb")) { if (can_throw) { bombButton.gameObject.SetActive(true); throwButton.gameObject.SetActive(false); } other.isTrigger = false; } } void SetFalse() { fade_image.gameObject.SetActive(true); fade = true; gameObject.tag = "Untagged"; m_gameover.SetActive(true); //gameObject.SetActive(false); } public byte GetFirePower() { return fire_power; } public void Throw_Case(byte m_id) { if (id == m_id) { throw_ani = true; } else { } } public void Kick_Case(byte m_id) { if (id == m_id) { kick_ani = true; kick_bomb = false; } else { } } public void Push_Case(byte m_id) { if (id == m_id) { push_ani = true; } else { } } public void Move_Case(byte m_id) { } public void Dead_Case(byte m_id) { if (id == m_id) { //죽음 dead_ani = true; } } public void SetItem_Ability(byte m_id, byte type) { //getItem = true; /* switch (type) { case 0: bomb_power++; bomb_set++; //Debug.Log("Bomb Up~"); break; case 1: fire_power++; //Debug.Log("Fire Up~"); break; case 2: speed_power++; //Debug.Log("Speed Up~"); break; case 3: can_kick = true; break; case 4: can_throw = true; break; default: break; }*/ if (id == m_id) { getItem = true; switch (type) { case 0: bomb_power++; bomb_set++; itemtype = 0; //Debug.Log("Bomb Up~"); break; case 1: fire_power++; itemtype = 1; //Debug.Log("Fire Up~"); break; case 2: speed_power++; itemtype = 2; //Debug.Log("Speed Up~"); break; case 3: can_kick = true; itemtype = 3; break; case 4: can_throw = true; itemtype = 4; break; default: break; } } } void SetPosition() { switch (VariableManager_Coop.instance.pos_id) { case 1: id = 0; transform.position = new Vector3(0.0f, transform.position.y, 0.0f); Performance_Network.instance.Intro_Performance(id); break; case 2: id = 1; transform.position = new Vector3(28.0f, transform.position.y, 0.0f); Performance_Network.instance.Intro_Performance(id); break; case 3: id = 2; transform.position = new Vector3(0.0f, transform.position.y, 28.0f); transform.Rotate(new Vector3(0, 180.0f, 0)); Performance_Network.instance.Intro_Performance(id); break; case 4: id = 3; transform.position = new Vector3(28.0f, transform.position.y, 28.0f); transform.Rotate(new Vector3(0, 180.0f, 0)); Performance_Network.instance.Intro_Performance(id); break; default: break; } } // Update is called once per frame void Update() { GetComponent<Rigidbody>().velocity = new Vector3(0.0f, 0.0f, 0.0f); state_text[0].text = bomb_set + " / " + bomb_power; state_text[1].text = "" + fire_power; state_text[2].text = "" + speed_power; if (fade) { fade_image.color = new Color(0.0f, 0.0f, 0.0f, fade_image.color.a + (0.05f * Time.deltaTime)); } if (can_kick) { state_image[0].gameObject.SetActive(false); } if (can_throw) { state_image[1].gameObject.SetActive(false); } if (!Performance_Network.instance.ani_is_working && gameObject.CompareTag("Player")) { BodyRotation(); if (getItem) { CoOpManager.instance.GetItemUI_Activate(itemtype); MusicManager.manage_ESound.ItemGetSound2(); getItem = false; } if (dead_ani) { //Debug.Log("Dead!!!"); m_TurtleMan_Animator.SetBool("TurtleMan_isDead", true); Invoke("SetFalse", 2.1f); dead_ani = false; } if (push_ani) { m_TurtleMan_Animator.SetBool("TurtleMan_isPush", true); Invoke("Push_Ani_False", 1.0f); push_ani = false; } if (walk_ani) { m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); Invoke("Walk_Ani_False",0.1f); walk_ani = false; } if (throw_ani) { m_TurtleMan_Animator.SetBool("TurtleMan_isThrow", true); Invoke("Throw_Ani_False", 1.0f); throw_ani = false; } //키보드-마우스 움직임 /* if (Input.GetMouseButton(0)) { m_RotationX += Input.GetAxis("Mouse X") * m_RotateSensX * Time.deltaTime; transform.localEulerAngles = new Vector3(0.0f, m_RotationX, 0.0f); //if (!VSModeManager.instance.game_set) <-나중에 협동모드매니저를 만들어야 할듯 NetManager_Coop.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); } */ //스마트폰 용 조이스틱 조종 if (JoyStickMove.instance.Get_NormalizedVector() != Vector3.zero) { Vector3 normal = JoyStickMove.instance.Get_NormalizedVector(); normal.z = normal.y; normal.y = 0.0f; transform.Translate((m_PlayerSpeed + speed_power) * normal * Time.deltaTime); //if (!VSModeManager.instance.game_set) NetManager_Coop.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); } else { // 릴리즈 빌드할 때는 적용할 것! m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", false); } //Debug.Log(gameObject.transform.rotation.y); // ================== if (Input.GetKey(KeyCode.W)) { transform.Translate(new Vector3(0.0f, 0.0f, (m_PlayerSpeed + speed_power) * Time.deltaTime)); //if (!VSModeManager.instance.game_set) m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.S)) { transform.Translate(new Vector3(0.0f, 0.0f, -(m_PlayerSpeed + speed_power) * Time.deltaTime)); //if (!VSModeManager.instance.game_set) m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.A)) { transform.Translate(new Vector3(-(m_PlayerSpeed + speed_power) * Time.deltaTime, 0.0f, 0.0f)); //if (!VSModeManager.instance.game_set) m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKey(KeyCode.D)) { transform.Translate(new Vector3((m_PlayerSpeed + speed_power) * Time.deltaTime, 0.0f, 0.0f)); //if (!VSModeManager.instance.game_set) m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", true); NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } if (Input.GetKeyUp(KeyCode.W) || Input.GetKeyUp(KeyCode.S) || Input.GetKeyUp(KeyCode.A) || Input.GetKeyUp(KeyCode.D)) { m_TurtleMan_Animator.SetBool("TurtleMan_isWalk", false); } if (Input.GetKeyDown(KeyCode.Space)) { //if (!VSModeManager.instance.game_set) SetBomb(); } } } public void ReloadBomb(byte tID) { if (id == tID) { bomb_set++; } } public byte GetId() { return id; } public void SetBomb() // 폭탄 설치 { m_YouCanSetBomb = true; // 폭탄 위치 설정 m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; if (MapManager_COop.instance.Check_BombSet((int)(m_BombLocX / 2), (int)(m_BombLocZ / 2))) { //Debug.Log("You can't set bomb"); m_YouCanSetBomb = false; } // 이미 놓인 폭탄 검사 // 폭탄 생성 if (m_YouCanSetBomb && bomb_set > 0) { bomb_set--; NetManager_Coop.instance.SetBombPos((int)m_BombLocX, (int)m_BombLocZ, fire_power); NetManager_Coop.instance.SendBombPacket(); //UI.m_bomb_count = UI.m_bomb_count - 1; } } public void Box_Push() { float yRotation = gameObject.transform.eulerAngles.y; ////Debug.Log(yRotation); if (yRotation >= 315.0f || yRotation < 45.0f) direction = 3; else if (yRotation >= 45.0f && yRotation < 135.0f) direction = 1; else if (yRotation >= 135.0f && yRotation < 225.0f) direction = 4; else if (yRotation >= 225.0f && yRotation < 315.0f) direction = 2; m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; m_BombLocX = m_BombLocX / 2; m_BombLocZ = m_BombLocZ / 2; NetManager_Coop.instance.PushBox_Packet(direction, (int)m_BombLocX, (int)m_BombLocZ); } public void Bomb_Throw() // 폭탄 던지기 { float yRotation = gameObject.transform.eulerAngles.y; ////Debug.Log(yRotation); if (yRotation >= 315.0f || yRotation < 45.0f) direction = 3; else if (yRotation >= 45.0f && yRotation < 135.0f) direction = 1; else if (yRotation >= 135.0f && yRotation < 225.0f) direction = 4; else if (yRotation >= 225.0f && yRotation < 315.0f) direction = 2; m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; m_BombLocX = m_BombLocX / 2; m_BombLocZ = m_BombLocZ / 2; NetManager_Coop.instance.SendBomb_TPacket(direction, (int)m_BombLocX, (int)m_BombLocZ); bombButton.gameObject.SetActive(true); throwButton.gameObject.SetActive(false); } public void Bomb_Kick() { float yRotation = gameObject.transform.eulerAngles.y; ////Debug.Log(yRotation); if (yRotation >= 315.0f || yRotation < 45.0f) direction = 3; else if (yRotation >= 45.0f && yRotation < 135.0f) direction = 1; else if (yRotation >= 135.0f && yRotation < 225.0f) direction = 4; else if (yRotation >= 225.0f && yRotation < 315.0f) direction = 2; m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; m_BombLocX = m_BombLocX / 2; m_BombLocZ = m_BombLocZ / 2; NetManager_Coop.instance.SendBomb_KPacket(direction, (int)m_BombLocX, (int)m_BombLocZ); } void BodyRotation() { if (CoOpManager.instance.Get_isClicked()) // 조이스틱 + 회전 + ... { if (!m_is_Touch_Started) { if (JoyStickMove.instance.Get_is_Joystick_First_Touched_Net()) // 조이스틱이 먼저면 touchNum = 1; else touchNum = 0; // 회전이 먼저면 m_is_Touch_Started = true; } switch (Input.GetTouch(touchNum).phase) // 회전 처리 { case TouchPhase.Began: m_Touch_PrevPoint_X = Input.GetTouch(touchNum).position.x; break; case TouchPhase.Moved: transform.Rotate(0, (Input.GetTouch(touchNum).position.x - m_Touch_PrevPoint_X) * 0.5f, 0); m_Touch_PrevPoint_X = Input.GetTouch(touchNum).position.x; NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); break; } } else m_is_Touch_Started = false; } public void MakeGameOverAni() { animator_camera.SetTrigger("Dead"); } public void AniBomb_Start() { animator_camera.SetTrigger("Ring"); } public void KeyBoard_Move() // 플레이어 이동 및 회전 { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bomb_Setter : MonoBehaviour { protected int m_Max_Bomb_Count; public void Set_Max_Bomb_Count(int count) { m_Max_Bomb_Count = count; } public int Get_Max_Bomb_Count() { return m_Max_Bomb_Count; } protected int m_Curr_Bomb_Count; public void Set_Curr_Bomb_Count(int count) { m_Curr_Bomb_Count = count; } public int Get_Curr_Bomb_Count() { return m_Curr_Bomb_Count; } protected int m_Fire_Count; public void Set_Fire_Count(int count) { m_Fire_Count = count; } public int Get_Fire_Count() { return m_Fire_Count; } protected GameObject Bomb_Set(int state) { return Bomb_Pooling_Manager.GetInstance().Dequeue_Bomb(gameObject, state); } public void Decrease_Bomb_Count() { --m_Curr_Bomb_Count; } public void Bomb_Reload() { if (m_Curr_Bomb_Count + 1 <= m_Max_Bomb_Count) ++m_Curr_Bomb_Count; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using UnityEngine.SceneManagement; //씬 전환 함수 public class SceneChange : MonoBehaviour { public Canvas cv; public RawImage FadeSlider; static public SceneChange instance; int scene = 0; bool swap_scene = false; // Use this for initialization void Awake() { instance = this; DontDestroyOnLoad(this); } void Start () { if (cv != null) { cv.enabled = true; } StartCoroutine("SceneSwap"); } public int GetSceneState() { return scene; } // "타이틀 화면"으로 이동 public void GoTo_Wait_Scene() { //SceneManager.LoadScene(0); scene = 1; swap_scene = true; } // "모드 선택 화면"으로 이동 public void GoTo_ModeSelect_Scene() { Debug.Log("Clicked"); scene = 2; swap_scene = true; //SceneManager.LoadScene(1); } // "모험모드 스테이지 선택 화면"으로 이동 public void GoTo_Game_Scene() { scene = 3; swap_scene = true; //SceneManager.LoadScene(2); } // "선택한 해당 스테이지"로 이동 public void GoTo_Mode_Adventure_Selected_Stage(int stage_ID) { //if (LobbySound.instanceLS != null) // LobbySound.instanceLS.SoundStop(); // 선택한 스테이지가 몇번인지 PlayerPrefs에 기록! PlayerPrefs.SetInt("Mode_Adventure_Selected_Stage_ID", stage_ID); FadeSlider.gameObject.SetActive(true); // 모험모드 씬을 연다 //Invoke("WaitForFadeSlider", 2.0f); } void WaitForFadeSlider() { SceneManager.LoadScene(3); } IEnumerator SceneSwap() { for(; ; ) { if (swap_scene) { SceneManager.LoadScene(scene); swap_scene = false; Debug.Log("Go!!"); } yield return new WaitForSeconds(0.1f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item : MonoBehaviour { float m_Move_Speed = 0.3f; float m_Rotate_Speed = 50.0f; void Update () { if (!StageManager.GetInstance().Get_is_Pause()) { floating(); } } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Flame")) Destroy(gameObject); } void floating() { if (this.transform.position.y > 1.0f || this.transform.position.y < 0.6f) m_Move_Speed *= -1; this.transform.Translate(new Vector3(0.0f, m_Move_Speed * Time.deltaTime, 0.0f)); transform.Rotate (Vector3.up * m_Rotate_Speed * Time.deltaTime); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VSModeManager : MonoBehaviour { byte win_or_lose = 0; //1이면 win, 2면 lose public static VSModeManager instance; public RawImage winner_image; public RawImage loser_image; public bool game_set; void Awake() { instance = this; } // Use this for initialization void Start () { win_or_lose = 0; game_set = false; } public void GameOver_Set(byte id) { if (Turtle_Move.instance.GetId() == id) { win_or_lose = 1; game_set = true; } else { win_or_lose = 2; game_set = true; } } // Update is called once per frame void Update () { if (win_or_lose == 1) { winner_image.gameObject.SetActive(true); win_or_lose = 0; Debug.Log("Win!!!!!!"); Time.timeScale = 0; } if (win_or_lose == 2) { loser_image.gameObject.SetActive(true); win_or_lose = 0; Debug.Log("Lose!!!!!!"); Time.timeScale = 0; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Box_None_Item : Box { void OnTriggerEnter(Collider other) { if (!m_is_Destroyed && (other.gameObject.CompareTag("Flame_Remains") || other.gameObject.CompareTag("Flame_Crash"))) { m_is_Destroyed = true; // MCL 갱신 StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_index, false); Instantiate(m_Particle).transform.position = transform.position; // 파티클 발생 // 박스 파괴 Destroy(gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item_Network : MonoBehaviour { // Use this for initialization float m_Move_Speed = 0.3f; float m_Rotate_Speed = 50.0f; // Update is called once per frame void Update() { floating(); } void OnTriggerEnter(Collider other) { byte item_type = 0; if (gameObject.activeInHierarchy) { if (other.gameObject.CompareTag("Player")) { // 아이템 먹었다고 패킷을 보낸다 // 아이템 포지션 값을 보낸다. // 아이템 종류를 보낸다. int x = (int)transform.position.x; int z = (int)transform.position.z; if (gameObject.CompareTag("Bomb_Item")) { ////Debug.Log("Get Bomb Item"); item_type = 0; } if (gameObject.CompareTag("Fire_Item")) { ////Debug.Log("Get Fire Item"); item_type = 1; } if (gameObject.CompareTag("Speed_Item")) { ////Debug.Log("Get Speed Item"); item_type = 2; } if (gameObject.CompareTag("Kick_Item")) { item_type = 3; } if (gameObject.CompareTag("Throw_Item")) { item_type = 4; } if (gameObject.CompareTag("Glider_Item")) { item_type = 5; } ////Debug.Log("Send Item Log"); NetTest.instance.SendItemPacket(x, z, item_type); gameObject.SetActive(false); } } } public void floating() { if ((this.transform.position.y > 1.0f || this.transform.position.y < 0.6f) &&gameObject.activeInHierarchy) m_Move_Speed *= -1; this.transform.Translate(new Vector3(0.0f, m_Move_Speed * Time.deltaTime, 0.0f)); transform.Rotate(Vector3.up * m_Rotate_Speed * Time.deltaTime); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Sound_Effect : MonoBehaviour { static Sound_Effect m_Instance; public static Sound_Effect GetInstance() { return m_Instance; } protected static bool m_is_SE_Mute; public void Set_SE_Mute(bool b) { m_is_SE_Mute = b; } public void SetVolume(float v) { if (m_AudioSource != null) m_AudioSource.volume = v; } protected AudioSource m_AudioSource; void Awake () { m_Instance = this; m_AudioSource = GetComponent<AudioSource>(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Monster_Player_Detector : MonoBehaviour { public bool m_isInRange = false; Transform m_MainBody; GameObject m_Target; void Start() { m_MainBody = transform.parent; } void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("Player")) { if (!other.gameObject.GetComponent<Player>().Get_is_Hiden()) { m_isInRange = true; m_Target = other.gameObject; } else { m_isInRange = false; m_Target = null; } } } void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Player")) { m_isInRange = false; } } public GameObject Get_Target() { if (m_Target != null) return m_Target; else return null; } public void Set_Target(GameObject t) { m_Target = t; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Item_Network_Airdrop : Item_Network{ bool m_Droping = false; float m_Droping_Speed = 6.0f; // Use this for initialization void Droping() { if (m_Droping) { transform.Translate(new Vector3(0.0f, -m_Droping_Speed * Time.deltaTime, 0.0f)); if (transform.position.y < 0.4f) { //transform.Translate(new Vector3(0.0f, m_Droping_Speed * Time.deltaTime, 0.0f)); m_Droping = false; } } } public void IsGen() { Invoke("Gen_true", 2.0f); } void Gen_true() { m_Droping = true; } void OnTriggerEnter(Collider other) { byte item_type = 0; if (gameObject.activeInHierarchy) { if (other.gameObject.CompareTag("Player")) { int x = (int)transform.position.x; int z = (int)transform.position.z; item_type = 6; NetTest.instance.SendItemPacket(x, z, item_type); IsGen(); gameObject.SetActive(false); } } } // Update is called once per frame void Update () { if (gameObject.activeInHierarchy) { if (!m_Droping) floating(); else Droping(); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Start_Point : MonoBehaviour { void Start () { GameObject.FindGameObjectWithTag("Player").GetComponent<Player>().Player_Set_Start_Point(transform.position); Destroy(gameObject); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class NetTeam2 : MonoBehaviour { public Material[] team_material; //public GameObject[] team_turtle; Renderer rend; // Use this for initialization void Start() { rend = GetComponent<Renderer>(); // rend.sharedMaterial = team_material[VariableManager.instance.team_Turtle[1]]; rend.sharedMaterial = team_material[VariableManager.instance.roominfo[VariableManager.instance.m_roomid - 1].team2]; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class WaitRoom : MonoBehaviour { int page = 1; //현재 내가 몇페이지에 있는지. public static WaitRoom instance; byte m_id; public GameObject forceouted; public byte[] people_inRoom = new byte[4]; public Text m_text; Touch touch2; public GameObject pop; public GameObject[] uiBox; byte[] roomIDarray = new byte[20]; //0이면 안만들어짐 List<TB_Room> room_List = new List<TB_Room>(); public Text[] text_array; // Use this for initialization private void Awake() { instance = this; } void Start () { Debug.Log("Started"); StartCoroutine("RoomCheck"); } public void PopMenu() { pop.transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); if (pop.activeInHierarchy) { } pop.SetActive(true); } public void CancelPopMenu() { //Debug.Log("Clicked"); pop.SetActive(false); } public void ToLeftRoomPage() { Debug.Log("Left Page"); if (page > 1) { page -= 1; } if (page <= 1) { page = 1; } } public void ToRightRoomPage() { if (page < 3) { page += 1; } if (page >= 3) { page = 3; } } public void SetRoomNum() { VariableManager.instance.m_roomid = roomIDarray[0+((page-1)*8)]; //Debug.Log(m_roomid); } public void SetRoomNum1() { VariableManager.instance.m_roomid = roomIDarray[1 + ((page - 1) * 8)]; //Debug.Log(m_roomid); } public void SetRoomNum2() { VariableManager.instance.m_roomid = roomIDarray[2 + ((page-1) * 8)]; } public void SetRoomNum3() { VariableManager.instance.m_roomid = roomIDarray[3 + ((page-1) * 8)]; } public void SetRoomNum4() { VariableManager.instance.m_roomid = roomIDarray[4 + ((page-1) * 8)]; } public void SetRoomNum5() { VariableManager.instance.m_roomid = roomIDarray[5 + ((page-1) * 8)]; } public void SetRoomNum6() { VariableManager.instance.m_roomid = roomIDarray[6 + ((page-1) * 8)]; } public void SetRoomNum7() { VariableManager.instance.m_roomid = roomIDarray[7 + ((page-1) * 8)]; } public void SendJoinRoom() { NetTest.instance.SendJoinPacket(); } public void SendCreateRoom() { NetTest.instance.SendCreatePacket(); } // Update is called once per frame void Update () { if(m_text!=null) m_text.text = "" + VariableManager.instance.m_roomid; //m_text.text = "Hi"; for (var i = 0; i < Input.touchCount; ++i) { Touch touch = Input.GetTouch(i); Debug.Log("Hi3"); // Need to put .x //if (touch.position.x > (Screen.width / 2)) //{ Vector2 touchDeltaPosition = Input.GetTouch(i).deltaPosition; pop.transform.position = new Vector2(touchDeltaPosition.x,touchDeltaPosition.y); //} m_text.text = "Touch Position : " + touch.position; } if (Input.touchCount > 0) { Debug.Log("Hi"); touch2 = Input.GetTouch(0); m_text.text = "Touch Position : " + touch2.position; } Vector3 nv= Input.mousePosition; if (VariableManager.instance.forceout) { forceouted.SetActive(true); VariableManager.instance.forceout = false; } } IEnumerator RoomCheck() { for(; ; ) { room_List.Clear(); for (int i = 0; i < 20; ++i) { if (VariableManager.instance.roominfo[i].made == 1 || VariableManager.instance.roominfo[i].made == 2) { TB_Room temp = VariableManager.instance.roominfo[i]; room_List.Add(temp); } } int current_room = 0; foreach(TB_Room t in room_List) { if (current_room < 8*page) { if (text_array[current_room] != null) { text_array[current_room].text = "Room No." + t.roomID + "\nRoom Max : " + t.people_max; roomIDarray[current_room] = t.roomID; current_room++; } } } for(int i= current_room;i<page*8;++i) { if (text_array[i] != null) text_array[i].text = "Empty"; } //for(int i = current_room; i < 8 * page; ++i) //{ // roomIDarray[current_room] = 0; //} yield return new WaitForSeconds(0.2f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Boss_HP_Gauge : MonoBehaviour { static Boss_HP_Gauge m_Instance; public static Boss_HP_Gauge GetInstance() { return m_Instance; } Scrollbar m_HP_Gauge; float m_Prev_Gauge_Size; float m_Curr_HP; float m_Max_HP; float m_HP_Decrease_Speed = 2.0f; Animation m_Animations; Animation m_Child_Animations; bool m_is_Angry_Mode_On = false; IEnumerator m_Decrease_HP; IEnumerator m_Angry_Mode; void Awake() { m_Instance = this; } void Start () { m_HP_Gauge = GetComponent<Scrollbar>(); m_Animations = GetComponent<Animation>(); m_Child_Animations = GetComponentsInChildren<Animation>()[1]; m_Angry_Mode = AngryMode(); m_Decrease_HP = Decrease_Gauge(); StartCoroutine(Decrease_Gauge()); } IEnumerator AngryMode() { while(true) { m_Animations.Play(m_Animations.GetClip("Angry_Mode").name); yield return null; } } IEnumerator Decrease_Gauge() { while (true) { m_Prev_Gauge_Size = m_HP_Gauge.size; m_HP_Gauge.size = Mathf.Lerp(m_HP_Gauge.size, m_Curr_HP / m_Max_HP, Time.deltaTime * 1.2f); if (!m_is_Angry_Mode_On && m_Prev_Gauge_Size > m_HP_Gauge.size + 0.0005f) m_Child_Animations.Play(m_Child_Animations.GetClip("Gauge_Twinkle").name); yield return null; } } public void Set_Max_HP(float max) { m_Max_HP = max; m_Curr_HP = m_Max_HP; m_HP_Gauge.size = 1.0f; } public void Set_Curr_HP(int curr_HP) { m_Curr_HP = curr_HP; } public void Start_Angry_Mode_Gauge() { StartCoroutine(m_Angry_Mode); m_is_Angry_Mode_On = true; } public void Stop_Angry_Mode_Gauge() { StopCoroutine(m_Angry_Mode); } public void Dead_Mode_Gague_Play() { StopCoroutine(m_Angry_Mode); m_Animations.Play(m_Animations.GetClip("Dead_Mode").name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bush_Remaster : MonoBehaviour { public Material m_Material; ParticleSystem m_Fire_Effect; MeshRenderer m_MeshRenderer; bool m_is_Burning = false; float m_Red_Relv_Value = 2.0f; void Start() { m_MeshRenderer = gameObject.GetComponent<MeshRenderer>(); m_Fire_Effect = GetComponentInChildren<ParticleSystem>(); m_Fire_Effect.gameObject.SetActive(false); } void OnTriggerEnter(Collider other) { if (!m_is_Burning && other.gameObject.CompareTag("Flame")) { m_MeshRenderer.material = m_Material; m_Fire_Effect.gameObject.SetActive(true); m_Fire_Effect.Play(); gameObject.tag = "Flame_Bush"; StartCoroutine("Burning"); m_is_Burning = true; } } IEnumerator Burning() { while (true) { if (m_MeshRenderer.material.color.r >= 1.0f || m_MeshRenderer.material.color.r <= 0.0f) m_Red_Relv_Value *= -1; m_MeshRenderer.material.color = new Color(m_MeshRenderer.material.color.r + m_Red_Relv_Value * Time.deltaTime, 0.0f, 0.0f); yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.AI; using UnityEngine.UI; // #define 보스 모드 static class BOSS_MODE_LIST { public const int NORMAL_MODE = 0; public const int ANGRY_MODE = 1; public const int GROGGY_MODE = 2; } static class BOSS_ANIMATION_NUM { public const int IDLE = 0; public const int WALK = 1; public const int ATTACK = 2; public const int DEAD = 3; public const int SUMMON = 4; public const int HURT = 5; public const int RAGE = 6; } public class Big_Boss_Behavior : MonoBehaviour { NavMeshAgent m_NVAgent; // 내비에이전트 Animator m_Boss_Animator; // 애니메이터 GameObject m_Target; // 타겟 Monster_Player_Detector m_Attack_Detector; // 공격 감지기 Transform m_Attack_Collider; // 공격 충돌체 Detector_Box m_Target_Detector; // 타겟 감지기 Transform m_Attack_Range_UI; // 공격 범위 표시기 public GameObject m_Normal_Monster_Portal; // 일반몹 소환기 public GameObject m_Glider_Goblin; // 공중 몬스터 public GameObject m_Flame_Crash_Portal; // 화염폭발 소환기 // 행동들 IEnumerator m_Wait_For_Intro; IEnumerator m_Do_Behavior; IEnumerator m_Current_Behavior; IEnumerator m_Behavior_Find; IEnumerator m_Behavior_Chase; IEnumerator m_Behavior_Attack; IEnumerator m_Behavior_Return; IEnumerator m_Behavior_Skill_Normal_Monster_Summon; IEnumerator m_Behavior_Skill_Glider_Goblin_Summon; IEnumerator m_Behavior_Skill_Flame_Crash; IEnumerator m_Null_Behavior; // 빈 상태 IEnumerator m_Prev_Behavior; // 이전 행동 저장 bool m_is_Called_WakeUp = false; // 기본 위치 Vector3 Base_Position; // 스탯 int m_Boss_Number; // 어떤 보스인지 (애니메이션이 다르므로) int m_curr_Mode_Number; // 현재 모드 번호 int m_curr_Turn_Number; // 현재 스킬 턴 번호 int m_Health; // 체력 float m_Move_Speed; // 일반 이동속도 float m_Attack_Speed_Slow; // 슬로우모션 공격속도 float m_Attack_Speed; // 일반 공격속도 float m_Skill_Time; // 스킬 연출 시간 float m_curr_Skill_Time = 0.0f; // 현재 스킬 시간 int m_Curr_Skill = 0; float m_Turn_Duration; float m_curr_Turn_Duration = 0.0f; // 현재 턴의 경과된 지속시간 int m_Normal_Monster_Count; // 일반 몬스터 소환개수 int m_Glider_Monster_Count; // 공중 몬스터 소환개수 float m_Normal_Monster_Speed_Value; // 소환한 일반 몬스터 이동속도 (몬스터에게 넘겨주자) float m_Glider_Monster_Speed_Value; // 소환한 공중 몬스터 이동속도 (몬스터에게 넘겨주자) int m_Glider_Goblin_Bomb_Value; // 공중 몬스터 폭탄개수 (몬스터에게 넘겨주자) int m_Glider_Goblin_Fire_Value; // 공중 몬스터 화염크기 (몬스터에게 넘겨주자) int m_Flame_Crash_Range; // 화염폭발스킬 범위 int m_Flame_Crash_Count; // 화염폭발스킬 화염개수 Adventure_Boss_Data m_Boss_Data; // 보스 데이터 // 빅보스 AI 데이터들 Adventure_Big_Boss_Normal_Mode_AI_Data m_Adv_Big_Boss_Normal_AI = new Adventure_Big_Boss_Normal_Mode_AI_Data(); Adventure_Big_Boss_Angry_Mode_AI_Data m_Adv_Big_Boss_Angry_AI = new Adventure_Big_Boss_Angry_Mode_AI_Data(); Adventure_Big_Boss_Groggy_Mode_AI_Data m_Adv_Big_Boss_Groggy_AI = new Adventure_Big_Boss_Groggy_Mode_AI_Data(); float m_WalkTimer = 0.0f; float m_AttackTimer = 0.0f; bool m_isDead = false; // 죽었는가? bool m_is_First_Attack = true; // 첫 공격인가? bool m_Attack_is_Done = true; // 공격이 완료됐는가? bool m_is_Summonning = false; // 소환중인가? float m_Loss_Time = 0.0f; // 타겟을 놓친 후 경과 시간 float m_Forgot_Time = 4.0f; // 잊어버리게 되는 시간 float m_curr_Hurt_Time = 1.0f; // 데미지를 받지 않도록 float m_Hurt_CoolTime = 1.0f; // 데미지 쿨타임 float m_idle_sound_Timer = 0.0f; // idle상태 사운드 타이머 float m_idle_sound_Cooltime = 2.0f; // idle상태 사운드 쿨타임 List<string> m_AnimationList; // 애니메이션 이름을 담아놓은 리스트 string m_Attack_Motion_Checker; // 공격 모션 점검을 위한.. void Start() { // 내비게이터 등록 m_NVAgent = gameObject.GetComponent<NavMeshAgent>(); //m_NavPlane = GameObject.Find("Navigation_Plane"); // 애니메이션 등록 m_Boss_Animator = GetComponentInChildren<Animator>(); m_AnimationList = new List<string>(); m_AnimationList.Add("OrkBoss_isIdle"); m_AnimationList.Add("OrkBoss_isWalk"); m_AnimationList.Add("OrkBoss_isAttack"); m_AnimationList.Add("OrkBoss_isDead"); m_AnimationList.Add("OrkBoss_isSummon"); m_AnimationList.Add("OrkBoss_isHurt"); m_AnimationList.Add("OrkBoss_isRage"); m_Attack_Motion_Checker = "Base Layer.OrkBoss_Attack"; // 플레이어 감지기 등록 m_Target_Detector = GetComponentInChildren<Detector_Box>(); m_Attack_Detector = GetComponentInChildren<Monster_Player_Detector>(); // 공격 충돌박스 등록 m_Attack_Collider = transform.Find("Attack_Range"); // 비활성화 m_Attack_Collider.gameObject.SetActive(false); // 공격 범위 표시기 등록 m_Attack_Range_UI = transform.Find("Attack_Range_UI"); m_Attack_Range_UI.gameObject.SetActive(false); m_Boss_Data = StageManager.GetInstance().Get_Adventure_Boss_Data(); Base_Position = transform.position; // ========스탯설정========= m_Health = m_Boss_Data.Boss_HP; // 체력 설정 Boss_HP_Gauge.GetInstance().Set_Max_HP(m_Health); // 게이지 설정 Big_Boss_Data_Allocation(); // 보스 AI 데이터의 리스트들을 할당 CSV_Manager.GetInstance().Get_Adventure_Big_Boss_AI_Data(ref m_Adv_Big_Boss_Normal_AI, ref m_Adv_Big_Boss_Angry_AI, ref m_Adv_Big_Boss_Groggy_AI); // 보스 AI 테이블을 받아온다. // ========================= Camera_Directing.GetInstance().Set_Boss_Object(gameObject); // 몬스터의 행동 코루틴들을 설정 m_Do_Behavior = Do_Behavior(); //m_Behavior_Find = FindPlayer(); m_Behavior_Chase = Chase(); m_Behavior_Attack = Attack(); m_Behavior_Return = Return(); m_Behavior_Skill_Normal_Monster_Summon = Skill_Normal_Monster_Summon(); m_Behavior_Skill_Glider_Goblin_Summon = Skill_Glider_Goblin_Summon(); m_Behavior_Skill_Flame_Crash = Skill_Flame_Crash(); m_Null_Behavior = Null_Behavior(); m_Current_Behavior = m_Behavior_Return;// 처음 실행할 행동 설정 ModeChange(BOSS_MODE_LIST.NORMAL_MODE); // 최초 시작시 노말모드로 시작 m_Wait_For_Intro = Wait_For_Intro(); StartCoroutine(m_Wait_For_Intro); } IEnumerator Wait_For_Intro() { while(true) { if (StageManager.GetInstance().Get_is_Intro_Over()) { SetAnimation(BOSS_ANIMATION_NUM.RAGE); if (!m_is_Called_WakeUp) { m_is_Called_WakeUp = true; Invoke("WakeUp", 2.0f); } } yield return null; } } void WakeUp() { m_is_Called_WakeUp = false; m_Target_Detector.transform.localScale *= 3.0f; Invoke("Reset_Detector_Size", 3.0f); StopCoroutine(m_Wait_For_Intro); StartCoroutine(m_Do_Behavior); } void OnTriggerEnter(Collider other) { // 불에 닿을 시 데미지 판정 if (!m_isDead && (other.gameObject.CompareTag("Flame") || other.gameObject.CompareTag("Flame_Bush"))) { if (m_curr_Hurt_Time > m_Hurt_CoolTime) Hurt(); } //=============================== } void Think() // 어떤 행동을 할지 생각하는 함수 (추후 가중치를 두어 어떤 행동을 할지 더 상세하게 구분해야함.) { if (m_curr_Mode_Number != BOSS_MODE_LIST.GROGGY_MODE && (m_Current_Behavior == m_Behavior_Chase || m_Current_Behavior == m_Behavior_Return)/*(m_Curr_Skill != 0 && (m_curr_Skill_Time >= m_Skill_Time))*/) // 공격중이라면 공격이 끝나야 다른 행동을 할 수 있다. 또는 스킬 사용중이라면.. { if (m_Target_Detector.m_isInRange) // 감지 범위 안이라면 { m_Current_Behavior = m_Behavior_Chase; // 추격 상태로 전환 if (m_Target != null) { if (m_Attack_Detector.m_isInRange && !is_Blocked_Between_Target_And_Me()) // 그리고 공격 범위 안이라면 m_Current_Behavior = m_Behavior_Attack; } } } } IEnumerator Do_Behavior() // 모든 행동의 베이스가 되는 코루틴 { while (true) { if (!StageManager.GetInstance().Get_is_Pause()) { Think(); m_curr_Turn_Duration += Time.deltaTime; // 턴 지속시간을 잰다. m_curr_Hurt_Time += Time.deltaTime; if (m_curr_Turn_Duration > m_Turn_Duration && m_curr_Skill_Time >= m_Skill_Time) Set_Next_Turn_Skill(); if (m_Current_Behavior != null && m_Current_Behavior.MoveNext()) yield return m_Current_Behavior.Current; else yield return null; } else yield return null; } } /* IEnumerator FindPlayer() // 플레이어 찾기 (일단 뺌) { while (true) { if (m_WalkTimer < Monster_AI_Constants.Walk_Time) // 일정 시간동안 걸어다님. { transform.Translate(new Vector3(0.0f, 0.0f, (m_Move_Speed * Time.deltaTime))); SetAnimation(BOSS_ANIMATION_NUM.WALK); m_WalkTimer += Time.deltaTime; } else // idle 상태 진입 { if (MusicManager.manage_ESound != null) MusicManager.manage_ESound.Goblin_Idle_Sound(); SetAnimation(BOSS_ANIMATION_NUM.WALK); m_WalkTimer = 0.0f; yield return new WaitForSeconds(3.0f); // 3초간 idle 상태 유지 float AngleY = Random.Range(0.0f, 360.0f); transform.localEulerAngles = new Vector3(0.0f, AngleY, 0.0f); } yield return null; } } */ IEnumerator Chase() // 추격 { while(true) { if (m_Loss_Time < m_Forgot_Time) // 잊어버리기 까지 플레이어의 위치로 이동한다. { m_Loss_Time += Time.deltaTime; m_NVAgent.isStopped = false; m_Target = m_Target_Detector.GetComponent<Detector_Box>().Get_Target(); if (m_Target != null) m_NVAgent.destination = m_Target.transform.position; m_Loss_Time = 0.0f; SetAnimation(BOSS_ANIMATION_NUM.WALK); } else // 잊어버렸다면 기본 위치로 돌아간다. m_Current_Behavior = m_Behavior_Return; Save_Prev_Behavior(m_Behavior_Chase); yield return null; } } IEnumerator Attack() // 공격 { while (true) { if (!StageManager.GetInstance().Get_Game_Over()) { if (m_Attack_is_Done) { if (!m_Boss_Animator.GetBool(m_AnimationList[BOSS_ANIMATION_NUM.ATTACK])) // 공격할때 1번만 소리냄. GetComponentInChildren<Ork_Boss_Sound>().Play_AttackSound(); SetAnimation(BOSS_ANIMATION_NUM.ATTACK); m_Target = m_Attack_Detector.GetComponent<Monster_Player_Detector>().Get_Target(); if (m_Target != null) // 타겟을 향해 방향 전환 { Vector3 dir = m_Target.transform.position - transform.position; Vector3 dirXZ = new Vector3(dir.x, 0.0f, dir.z); if (dirXZ != Vector3.zero) { Quaternion targetRot = Quaternion.LookRotation(dirXZ); transform.rotation = targetRot; } } m_Attack_is_Done = false; } else { if (m_Boss_Animator.GetCurrentAnimatorStateInfo(0).fullPathHash == Animator.StringToHash(m_Attack_Motion_Checker)) { m_NVAgent.isStopped = true; if (m_Boss_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.99f) // 애니메이션이 끝나면 { m_Current_Behavior = m_Behavior_Return; m_Boss_Animator.SetFloat("Attack_Speed", m_Attack_Speed_Slow); // 공격속도를 슬로우모션으로 되돌린다. m_Attack_is_Done = true; // 공격 완료 알림 } else if (m_Boss_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.5f) // 중간 부분 { m_Attack_Collider.gameObject.SetActive(false); // 공격용 충돌체를 집어넣는다. m_Attack_Range_UI.gameObject.SetActive(false); // 범위 표시기도 집어넣는다. } else if (m_Boss_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.25f) m_Attack_Collider.gameObject.SetActive(true); // 공격용 충돌체를 꺼낸다. else if (m_Boss_Animator.GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.2f) // 초기 부분 m_Boss_Animator.SetFloat("Attack_Speed", m_Attack_Speed); // 슬로우모션 후 뒷부분은 빠르게하기 위해.. else m_Attack_Range_UI.gameObject.SetActive(true); // 범위 표시기를 꺼낸다. } else { m_Attack_Range_UI.gameObject.SetActive(false); // 범위 표시기를 끈다. m_Attack_Collider.gameObject.SetActive(false); // 공격용 충돌체를 끈다. } } } Save_Prev_Behavior(m_Behavior_Attack); yield return null; } } IEnumerator Return() // 복귀 { while(true) { Base_Position.y = transform.position.y; if (transform.position == Base_Position) { if (m_idle_sound_Timer >= m_idle_sound_Cooltime) { GetComponentInChildren<Ork_Boss_Sound>().Play_IdleSound(); m_idle_sound_Timer = 0.0f; } else m_idle_sound_Timer += Time.deltaTime; m_NVAgent.isStopped = true; SetAnimation(BOSS_ANIMATION_NUM.IDLE); } else { m_NVAgent.destination = Base_Position; m_NVAgent.isStopped = false; SetAnimation(BOSS_ANIMATION_NUM.WALK); } Save_Prev_Behavior(m_Behavior_Return); yield return null; } } void Reset_Detector_Size() { m_Target_Detector.transform.localScale *= 0.34f; } void Set_Next_Turn_Skill() // 다음 턴의 스킬을 설정하는 함수 { ++m_curr_Turn_Number; m_curr_Turn_Duration = 0.0f; // 턴 경과 시간 초기화 m_curr_Skill_Time = 0.0f; // 스킬 경과 시간 초기화 if (m_Prev_Behavior == m_Behavior_Attack) { m_Attack_is_Done = true; m_Attack_Collider.gameObject.SetActive(false); // 공격용 충돌체를 집어넣는다. m_Attack_Range_UI.gameObject.SetActive(false); // 범위 표시기도 집어넣는다. } int random = Random.Range(1, 100); switch (m_curr_Mode_Number) { case BOSS_MODE_LIST.NORMAL_MODE: if (m_curr_Turn_Number > m_Adv_Big_Boss_Normal_AI.Skill_Percentage.Count) m_curr_Turn_Number = 1; m_Turn_Duration = m_Adv_Big_Boss_Normal_AI.Skill_Duration[m_curr_Turn_Number - 1]; if (random <= m_Adv_Big_Boss_Normal_AI.Skill_Percentage[m_curr_Turn_Number - 1][0]) { // m_Behavior_Chase 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Normal_AI.Skill_Time[0]; m_Current_Behavior = m_Behavior_Chase; } else if (random <= m_Adv_Big_Boss_Normal_AI.Skill_Percentage[m_curr_Turn_Number - 1][0] + m_Adv_Big_Boss_Normal_AI.Skill_Percentage[m_curr_Turn_Number - 1][1]) { // m_Behavior_Skill_Normal_Monster_Summon 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Normal_AI.Skill_Time[1]; m_Normal_Monster_Count = Random.Range(m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Value_Min[0], m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Value_Max[0]); m_Normal_Monster_Speed_Value = m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Speed_Value[0]; m_Current_Behavior = m_Behavior_Skill_Normal_Monster_Summon; } else if (random <= m_Adv_Big_Boss_Normal_AI.Skill_Percentage[m_curr_Turn_Number - 1][0] + m_Adv_Big_Boss_Normal_AI.Skill_Percentage[m_curr_Turn_Number - 1][1] + m_Adv_Big_Boss_Normal_AI.Skill_Percentage[m_curr_Turn_Number - 1][2]) { // m_Behavior_Skill_Glider_Goblin_Summon 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Normal_AI.Skill_Time[2]; m_Glider_Monster_Count = Random.Range(m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Value_Min[1], m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Value_Max[1]); m_Glider_Monster_Speed_Value = m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Speed_Value[1]; m_Glider_Goblin_Bomb_Value = m_Adv_Big_Boss_Normal_AI.Glider_Goblin_Bomb_Value; m_Glider_Goblin_Fire_Value = m_Adv_Big_Boss_Normal_AI.Glider_Goblin_Fire_Value; m_Current_Behavior = m_Behavior_Skill_Glider_Goblin_Summon; } else { // m_Behavior_Skill_Flame_Crash 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Normal_AI.Skill_Time[3]; m_Flame_Crash_Range = Random.Range(m_Adv_Big_Boss_Normal_AI.Skill_Fire_Range_Min, m_Adv_Big_Boss_Normal_AI.Skill_Fire_Range_Max); m_Flame_Crash_Count = Random.Range(m_Adv_Big_Boss_Normal_AI.Fire_In_Range_Min, m_Adv_Big_Boss_Normal_AI.Fire_In_Range_Max); m_Current_Behavior = m_Behavior_Skill_Flame_Crash; } break; case BOSS_MODE_LIST.ANGRY_MODE: if (m_curr_Turn_Number > m_Adv_Big_Boss_Angry_AI.Skill_Percentage.Count) m_curr_Turn_Number = 1; m_Turn_Duration = m_Adv_Big_Boss_Angry_AI.Skill_Duration[m_curr_Turn_Number - 1]; if (random <= m_Adv_Big_Boss_Angry_AI.Skill_Percentage[m_curr_Turn_Number - 1][0]) { // m_Behavior_Chase 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Angry_AI.Skill_Time[0]; m_Target_Detector.transform.localScale *= 3.0f; Invoke("Reset_Detector_Size", 3.0f); m_Current_Behavior = m_Behavior_Chase; } else if (random <= m_Adv_Big_Boss_Angry_AI.Skill_Percentage[m_curr_Turn_Number - 1][0] + m_Adv_Big_Boss_Angry_AI.Skill_Percentage[m_curr_Turn_Number - 1][1]) { // m_Behavior_Skill_Normal_Monster_Summon 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Angry_AI.Skill_Time[1]; m_Normal_Monster_Count = Random.Range(m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Value_Min[0], m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Value_Max[0]); m_Normal_Monster_Speed_Value = m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Speed_Value[0]; m_Current_Behavior = m_Behavior_Skill_Normal_Monster_Summon; } else if (random <= m_Adv_Big_Boss_Angry_AI.Skill_Percentage[m_curr_Turn_Number - 1][0] + m_Adv_Big_Boss_Angry_AI.Skill_Percentage[m_curr_Turn_Number - 1][1] + m_Adv_Big_Boss_Angry_AI.Skill_Percentage[m_curr_Turn_Number - 1][2]) { // m_Behavior_Skill_Glider_Goblin_Summon 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Angry_AI.Skill_Time[2]; m_Glider_Monster_Count = Random.Range(m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Value_Min[1], m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Value_Max[1]); m_Glider_Monster_Speed_Value = m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Speed_Value[1]; m_Glider_Goblin_Bomb_Value = m_Adv_Big_Boss_Angry_AI.Glider_Goblin_Bomb_Value; m_Glider_Goblin_Fire_Value = m_Adv_Big_Boss_Angry_AI.Glider_Goblin_Fire_Value; m_Current_Behavior = m_Behavior_Skill_Glider_Goblin_Summon; } else { // m_Behavior_Skill_Flame_Crash 초기화 작업 m_Skill_Time = m_Adv_Big_Boss_Angry_AI.Skill_Time[3]; m_Flame_Crash_Range = Random.Range(m_Adv_Big_Boss_Angry_AI.Skill_Fire_Range_Min, m_Adv_Big_Boss_Angry_AI.Skill_Fire_Range_Max); m_Flame_Crash_Count = Random.Range(m_Adv_Big_Boss_Angry_AI.Fire_In_Range_Min, m_Adv_Big_Boss_Angry_AI.Fire_In_Range_Max); m_Current_Behavior = m_Behavior_Skill_Flame_Crash; } break; } } IEnumerator Skill_Normal_Monster_Summon() // 일반몹 소환 스킬 { while (true) { if (m_curr_Skill_Time < m_Skill_Time) { m_curr_Skill_Time += Time.deltaTime; m_NVAgent.isStopped = true; SetAnimation(BOSS_ANIMATION_NUM.SUMMON); if (!m_is_Summonning) // 소환중이 아니라면 { m_is_Summonning = true; // 소환중이라 알림 int index; // 소환 위치 (인덱스) Vector3 pos; pos.y = m_Normal_Monster_Portal.transform.position.y; for (int i = 0; i < m_Normal_Monster_Count; ++i) { while (true) // 루프를 돌면서 지형 탐색 { index = Random.Range(17, 271); // 맵 범위 if (!StageManager.GetInstance().Get_MCL_index_is_Blocked(index)) // 막혀있지 않으면 break; // 탈출 } pos.x = 0.0f; pos.z = 0.0f; StageManager.GetInstance().Get_MCL_Coordinate(index, ref pos.x, ref pos.z); GameObject temp = Instantiate(m_Normal_Monster_Portal); temp.transform.position = pos; // 설정한 위치에 포탈 소환 temp.GetComponent<Monster_Portal>().Set_Monster_Speed(m_Normal_Monster_Speed_Value); } } } else { m_is_Summonning = false; m_Current_Behavior = m_Behavior_Return; } Save_Prev_Behavior(m_Behavior_Skill_Normal_Monster_Summon); yield return null; } } IEnumerator Skill_Glider_Goblin_Summon() // 글라이더 고블린 소환 스킬 { while (true) { if (m_curr_Skill_Time < m_Skill_Time) { m_curr_Skill_Time += Time.deltaTime; m_NVAgent.isStopped = true; SetAnimation(BOSS_ANIMATION_NUM.SUMMON); if (!m_is_Summonning) // 소환중이 아니라면 { m_is_Summonning = true; // 소환중이라 알림 int index; Vector3 pos; pos.y = m_Glider_Goblin.transform.position.y; for (int i = 0; i < m_Glider_Monster_Count; ++i) { index = Random.Range(17, 271); // 소환 위치 (인덱스) pos.x = 0.0f; pos.z = 0.0f; StageManager.GetInstance().Get_MCL_Coordinate(index, ref pos.x, ref pos.z); GameObject temp = Instantiate(m_Glider_Goblin); temp.transform.position = pos; // 설정한 위치에 글라이더 소환 temp.GetComponent<Jet_Goblin>().Set_Bomb_info(m_Glider_Goblin_Bomb_Value, m_Glider_Goblin_Fire_Value, m_Glider_Monster_Speed_Value); } } } else { m_is_Summonning = false; m_Current_Behavior = m_Behavior_Return; } Save_Prev_Behavior(m_Behavior_Skill_Glider_Goblin_Summon); yield return null; } } IEnumerator Skill_Flame_Crash() // 화염폭발 스킬 { while (true) { if (m_curr_Skill_Time < m_Skill_Time) { m_curr_Skill_Time += Time.deltaTime; m_NVAgent.isStopped = true; SetAnimation(BOSS_ANIMATION_NUM.SUMMON); if (!m_is_Summonning) // 소환중이 아니라면 { m_is_Summonning = true; // 소환중이라 알림 float range_X; float range_Z; int index; Vector3 pos; pos.y = m_Flame_Crash_Portal.transform.position.y; for (int i = 0; i < m_Flame_Crash_Count; ++i) { while (true) { range_X = Random.Range(transform.position.x - m_Flame_Crash_Range, transform.position.x + m_Flame_Crash_Range); // 소환 위치 (X값) range_Z = Random.Range(transform.position.z - m_Flame_Crash_Range, transform.position.z + m_Flame_Crash_Range); // 소환 위치 (Z값) if (range_X < -1.0f || range_X > 29.0f || range_Z < 49.0f || range_Z > 79.0f) // 맵을 벗어나면 다시 continue; index = StageManager.GetInstance().Find_Own_MCL_Index(range_X, range_Z); if (!StageManager.GetInstance().Get_MCL_index_is_Blocked(index)) // 막혀있지 않으면 탈출 break; } pos.x = 0.0f; pos.z = 0.0f; StageManager.GetInstance().Get_MCL_Coordinate(index, ref pos.x, ref pos.z); Instantiate(m_Flame_Crash_Portal).transform.position = pos; // 설정한 위치에 화염 마법진 소환 } } } else { m_is_Summonning = false; m_Current_Behavior = m_Behavior_Return; } Save_Prev_Behavior(m_Behavior_Skill_Flame_Crash); yield return null; } } IEnumerator Null_Behavior() // 빈상태 (Hurt 같은 경우) { while(true) { yield return null; } } // 폭탄 피격 void Hurt() { GetComponentInChildren<Ork_Boss_Sound>().Play_HurtSound(); m_NVAgent.isStopped = true; if (m_Health - m_Boss_Data.Bomb_Damage <= 0) { GetComponentInChildren<Ork_Boss_Sound>().Play_DeadSound(); m_Health = 0; StopCoroutine(m_Do_Behavior); SetAnimation(BOSS_ANIMATION_NUM.DEAD); Boss_HP_Gauge.GetInstance().Dead_Mode_Gague_Play(); Invoke("Dead", 2.0f); } if (m_Health - m_Boss_Data.Bomb_Damage > 0) { m_Health -= m_Boss_Data.Bomb_Damage; SetAnimation(BOSS_ANIMATION_NUM.HURT); m_Current_Behavior = m_Null_Behavior; Invoke("HurtEnd", 1.0f); // 체력에 따른 모드 전환 if (m_Health <= m_Boss_Data.Angry_Condition_Start_HP && m_curr_Mode_Number == BOSS_MODE_LIST.NORMAL_MODE) ModeChange(BOSS_MODE_LIST.ANGRY_MODE); if (m_Health <= m_Boss_Data.Groggy_Condition_Start_HP && m_curr_Mode_Number == BOSS_MODE_LIST.ANGRY_MODE) ModeChange(BOSS_MODE_LIST.GROGGY_MODE); m_curr_Hurt_Time = 0.0f; if (m_Prev_Behavior == m_Behavior_Attack) return; } Boss_HP_Gauge.GetInstance().Set_Curr_HP(m_Health); // 게이지에 적용 } void HurtEnd() { m_Current_Behavior = m_Prev_Behavior; } // 죽음 void Dead() { UI.GetInstance().Set_is_Boss_Kill(true); StageManager.GetInstance().SetBossDead(true); Destroy(gameObject); StageManager.GetInstance().Stage_Clear(); // 보스를 잡으면 스테이지 클리어 } // 모드 전환 void ModeChange(int Mode_Number) { m_curr_Mode_Number = Mode_Number; m_curr_Turn_Number = 0; // 모드전환 시 초기화 switch (m_curr_Mode_Number) { case BOSS_MODE_LIST.NORMAL_MODE: m_Move_Speed = (float)m_Adv_Big_Boss_Normal_AI.Boss_Speed_Value; // 이동속도 설정 m_NVAgent.speed = m_Move_Speed; // 추격시 이동속도 설정 m_NVAgent.angularSpeed = 360.0f * m_Move_Speed; // 추격시 회전속도 설정 m_Attack_Speed_Slow = 0.2f; // 슬로우 모션 공격속도 설정 m_Attack_Speed = 1.5f; // 진짜 공격속도 설정 Boss_HP_Gauge.GetInstance().Stop_Angry_Mode_Gauge(); // 1. 버프 스킬 지속시간 설정 // 2. 피격 가능 시간 설정 break; case BOSS_MODE_LIST.ANGRY_MODE: m_Move_Speed = (float)m_Adv_Big_Boss_Angry_AI.Boss_Speed_Value; // 이동속도 설정 m_NVAgent.speed = m_Move_Speed; // 추격시 이동속도 설정 m_NVAgent.angularSpeed = 360.0f * m_Move_Speed; // 추격시 회전속도 설정 m_Attack_Speed_Slow = 0.4f; // 슬로우 모션 공격속도 설정 m_Attack_Speed = 2.5f; // 진짜 공격속도 설정 Boss_HP_Gauge.GetInstance().Start_Angry_Mode_Gauge(); // 1. 버프스킬 지속시간 증가 // 2. 피격 가능 시간 축소 break; case BOSS_MODE_LIST.GROGGY_MODE: // 아무것도 못하는 상태로 만들기 m_Move_Speed = (float)m_Adv_Big_Boss_Groggy_AI.Boss_Speed_Value; // 이동속도 설정 m_NVAgent.speed = m_Move_Speed; // 추격시 이동속도 설정 m_NVAgent.angularSpeed = 360.0f * m_Move_Speed; // 추격시 회전속도 설정 break; } m_Boss_Animator.SetFloat("Attack_Speed", m_Attack_Speed_Slow); // 설정한 공격속도 (슬로우)로 변경 Set_Next_Turn_Skill(); // 다음 턴 스킬 설정 } bool is_Blocked_Between_Target_And_Me() // 타겟과 나 사이에 장애물이 있는가? { return StageManager.GetInstance().Get_MCL_index_is_Blocked ( StageManager.GetInstance().Find_Own_MCL_Index ( (m_Target.transform.position.x + transform.position.x) / 2.0f, (m_Target.transform.position.z + transform.position.z) / 2.0f ) ); } void Save_Prev_Behavior(IEnumerator behavior) // 이전상태저장 { m_Prev_Behavior = behavior; } public void SetAnimation(int Animation_Num) { if (m_Prev_Behavior == m_Behavior_Attack) { m_Attack_Range_UI.gameObject.SetActive(false); // 범위 표시기를 끈다. m_Attack_Collider.gameObject.SetActive(false); // 공격용 충돌체를 끈다. } for (int i = 0; i < 7; ++i) m_Boss_Animator.SetBool(m_AnimationList[i], false); m_Boss_Animator.SetBool(m_AnimationList[Animation_Num], true); } void Big_Boss_Data_Allocation() // 빅보스 데이터 메모리 할당작업 { // Normal m_Adv_Big_Boss_Normal_AI.Skill_Time = new int[4]; m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Value_Min = new int[2]; m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Value_Max = new int[2]; m_Adv_Big_Boss_Normal_AI.Spawn_Monster_Speed_Value = new int[2]; m_Adv_Big_Boss_Normal_AI.Skill_Percentage = new List<int[]>(); m_Adv_Big_Boss_Normal_AI.Skill_Duration = new List<int>(); m_Adv_Big_Boss_Normal_AI.Link_Skill = new List<int>(); // =============================================================== // Angry m_Adv_Big_Boss_Angry_AI.Skill_Time = new int[4]; m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Value_Min = new int[2]; m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Value_Max = new int[2]; m_Adv_Big_Boss_Angry_AI.Spawn_Monster_Speed_Value = new int[2]; m_Adv_Big_Boss_Angry_AI.Skill_Percentage = new List<int[]>(); m_Adv_Big_Boss_Angry_AI.Skill_Duration = new List<int>(); m_Adv_Big_Boss_Angry_AI.Link_Skill = new List<int>(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Box : MonoBehaviour { public GameObject m_Object_FireItem; public GameObject m_Object_BombItem; public GameObject m_Object_SpeedItem; public GameObject m_Object_KickItem; public GameObject m_Object_ThrowItem; public GameObject m_Particle; GameObject m_PlayerCollider = null; // 플레이어의 밀기용 감지기 GameObject m_IcicleCollider = null; // 고드름 바닥 충돌체 protected bool m_is_Destroyed = false; protected int m_MCL_index; public int Get_MCL_index() { return m_MCL_index; } void Start() { m_MCL_index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); } public void Reset_MCL_index(int index) { StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_index, false); m_MCL_index = index; StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_index, true); } void OnDestroy() { if (m_PlayerCollider) // 충돌중인 감지기가 있으면 { m_PlayerCollider.GetComponent<Front_Collider>().TriggerExit_Ver2(); // 트리거아웃을 직접 수행해준다. } if (m_IcicleCollider) // 충돌중인 고드름바닥이 있으면 { m_IcicleCollider.GetComponent<Icicle_Bottom>().TriggerExit_Ver2(); // 트리거아웃을 직접 수행해준다. } } void OnTriggerEnter(Collider other) { if (!m_is_Destroyed && (other.gameObject.CompareTag("Flame_Remains") || other.gameObject.CompareTag("Flame_Crash") || other.gameObject.CompareTag("Flame"))) { m_is_Destroyed = true; // MCL 갱신 StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_index, false); SetItem(); // 아이템 생성 Instantiate(m_Particle).transform.position = transform.position; // 파티클 발생 Destroy(gameObject); // 박스 파괴 } } protected void SetItem() { if (Random.Range(0, 100) > 51) { GameObject Instance_Item; int dropRate = Random.Range(0, 100); if (dropRate < 25) { m_Object_FireItem.transform.position = new Vector3(transform.position.x, 0.6f, transform.position.z); Instance_Item = Instantiate(m_Object_FireItem); } else if (dropRate >= 25 && dropRate < 55) { m_Object_BombItem.transform.position = new Vector3(transform.position.x, 0.6f, transform.position.z); Instance_Item = Instantiate(m_Object_BombItem); } else if (dropRate >= 55 && dropRate < 80) { m_Object_SpeedItem.transform.position = new Vector3(transform.position.x, 0.6f, transform.position.z); Instance_Item = Instantiate(m_Object_SpeedItem); } else if (dropRate >= 80 && dropRate < 90) { m_Object_KickItem.transform.position = new Vector3(transform.position.x, 0.6f, transform.position.z); Instance_Item = Instantiate(m_Object_KickItem); } else { m_Object_ThrowItem.transform.position = new Vector3(transform.position.x, 0.6f, transform.position.z); Instance_Item = Instantiate(m_Object_ThrowItem); } } } public void Save_Player_Front_Collider(GameObject fc) { m_PlayerCollider = fc; } public void Clear_Player_Front_Collider() { m_PlayerCollider = null; } public void Save_Icicle_Bottom_Collider(GameObject ic) { m_IcicleCollider = ic; } public void Clear_Icicle_Bottom_Collider() { m_IcicleCollider = null; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class ICICLE_OFFSET_TIME { public const float ICICLE_1 = 0.0f; public const float ICICLE_2 = 2.0f; public const float WAIT_TIME = 3.0f; } public class Icicle : MonoBehaviour { Animation m_Animations; float m_Offset_Time; IEnumerator m_Behavior; IEnumerator m_Up_Checker; IEnumerator m_Down_Checker; int m_MCL_Index; void Start () { m_Animations = GetComponent<Animation>(); m_Behavior = Behavior(); m_Up_Checker = Perfectly_Up_Check(); m_Down_Checker = Perfectly_Down_Check(); m_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); // 인덱스 찾기 } public void Start_With_Offset_Time(float time) // 인자로 받은 시간만큼 대기 후 첫 시작. { Invoke("Icicle_Behavior_Start", time); } IEnumerator Behavior() { while(true) { Icicle_Up(); yield return new WaitForSeconds(ICICLE_OFFSET_TIME.WAIT_TIME); Icicle_Down(); yield return new WaitForSeconds(ICICLE_OFFSET_TIME.WAIT_TIME); } } IEnumerator Perfectly_Up_Check() { while (true) { if (m_Animations["icicle_Up"].normalizedTime >= 0.7f) // 어느정도 올라오면 { GetComponentInChildren<BoxCollider>().isTrigger = false; // 트리거를 꺼버린다. StopCoroutine(m_Up_Checker); // '올라가는 과정 체크' 일시정지 } yield return null; } } IEnumerator Perfectly_Down_Check() { while (true) { if (m_Animations["icicle_Down"].normalizedTime >= 0.9f) // 거의 완전히 내려가면 { StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_Index, false); // 열어줌. StopCoroutine(m_Down_Checker); // '완전히 내려갔는지 체크' 일시정지 } else if (m_Animations["icicle_Down"].normalizedTime >= 0.3f) // 어느정도 내려가면 { GetComponentInChildren<BoxCollider>().isTrigger = true; // 트리거를 켜준다. } yield return null; } } void Icicle_Up() { m_Animations.Play(m_Animations.GetClip("icicle_Up").name); StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_Index, true); // 고드름이 올라가기 시작하면 막아줌. StartCoroutine(m_Up_Checker); // '올라가는 과정 체크' 시작 } void Icicle_Down() { m_Animations.Play(m_Animations.GetClip("icicle_Down").name); StartCoroutine(m_Down_Checker); // '완전히 내려갔는지 체크' 시작 } public void Icicle_Behavior_Start() { StartCoroutine(m_Behavior); } public void Icicle_Behavior_Stop() { StopCoroutine(m_Behavior); } }<file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class VariableManager : MonoBehaviour { public static VariableManager instance; public byte m_accessid=254; public byte m_roomid = 0; public byte[] people_inRoom = new byte[4]; public byte pos_inRoom = 0; public byte pos_guardian = 0; public byte is_guardian = 0; //MapManager의 변수 public byte[] copy_map_info = new byte[225]; public byte[] bombexplode_list = new byte[225]; byte[] roomIDarray = new byte[20]; //0이면 안만들어짐 public TB_Room[] roominfo = new TB_Room[20]; public bool forceout = false; private void Awake() { instance = this; DontDestroyOnLoad(this); } // Use this for initialization void Start () { } public void SetID(byte a) { m_accessid = a; } public void OutRoom() { m_roomid = 0; pos_inRoom = 0; pos_guardian = 0; is_guardian = 0; } public void F_OutRoom() { forceout = true; m_roomid = 0; pos_inRoom = 0; pos_guardian = 0; is_guardian = 0; } public byte GetRoomNum() { return m_roomid; } public void Check_Map(byte[] mapinfo) { Buffer.BlockCopy(mapinfo, 2, copy_map_info, 0, 225); } public void SetRoomState(byte[] b) { byte[] tempArray = new byte[20]; Buffer.BlockCopy(b, 0, tempArray, 0, 20); //Debug.Log("BlockCopy Completed"); byte temproomID = tempArray[2]; roominfo[temproomID - 1].roomID = temproomID; roominfo[temproomID - 1].people_count = tempArray[3]; roominfo[temproomID - 1].game_start = tempArray[4]; roominfo[temproomID - 1].people_max = tempArray[5]; roominfo[temproomID - 1].made = tempArray[6]; roominfo[temproomID - 1].guardian_pos = tempArray[7]; roominfo[temproomID - 1].people1 = tempArray[8]; roominfo[temproomID - 1].people2 = tempArray[9]; roominfo[temproomID - 1].people3 = tempArray[10]; roominfo[temproomID - 1].people4 = tempArray[11]; if (SceneChange.instance.GetSceneState() == 2) { bool tempbool = temproomID == GameRoom.instance.GetRoomID(); if (tempbool) { pos_guardian = tempArray[7]; for (byte i = 0; i < 4; ++i) { people_inRoom[i] = tempArray[8 + i]; } } } //Debug.Log("SEtRoomState Completed"); } public void SetRoomState_Respond(byte[] b) { byte[] tempArray = new byte[12]; Buffer.BlockCopy(b, 0, tempArray, 0, 12); m_roomid = tempArray[3]; pos_inRoom = tempArray[4]; pos_guardian = tempArray[5]; for (byte i = 0; i < 4; ++i) { people_inRoom[i] = tempArray[6 + i]; } } public void SetRoomCreate_Respond(byte[] b) { byte[] tempArray = new byte[4]; people_inRoom[0] = NetTest.instance.GetId(); pos_inRoom = 1; is_guardian = 1; pos_guardian = 1; m_roomid = b[3]; } // Update is called once per frame void Update () { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class UI : MonoBehaviour { public Text m_FCT; public Text m_BCT; public Text m_SCT; public Text m_GIT; public Text m_TLT; public Animator ani; // UI에 표시될 변수 // 캐릭터 마다 다르게 설정해주어야한다. public static int m_fire_count = 2; public static int m_bomb_count = 2; public static int m_speed_count = 2; public static string m_getItemText; float m_GIT_CoolTime = 0.0f; float time_Second = 30.0f; void Start() { m_getItemText = ""; time_Second = 30.0f; } // Update is called once per frame void Update () { if(time_Second>0) time_Second = time_Second - Time.deltaTime; m_FCT.text = "Fire: " + m_fire_count.ToString(); m_BCT.text = "X: " + PlayerMove.C_PM.GetPosX(); m_SCT.text = "Z : " + PlayerMove.C_PM.GetPosZ(); m_GIT.text = m_getItemText; m_TLT.text = "Time: " +(int)time_Second/60 + ":"+(int)time_Second%60; //각 수치 맥스 설정 -R if (m_fire_count > 8) m_fire_count = 8; if (m_bomb_count > 8) m_bomb_count = 8; if (m_speed_count > 8) m_speed_count = 8; //시간촉박 애니매이션 출력, 초기에는 애니매이션을 꺼놨다가 발동 -R if (time_Second < 15.0f) { ani.enabled = true; } else { ani.enabled = false; } //시간 초과 시 게임오버 - 캐릭터를 죽게 함으로서 처리 -R if (time_Second <= 0) { time_Second = 0; PlayerMove.C_PM.Set_Dead(); } if (m_GIT.text != "") { m_GIT_CoolTime += Time.deltaTime; if (m_GIT_CoolTime >= 2.0f) { m_getItemText = ""; m_GIT_CoolTime = 0.0f; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Monster_Portal : MonoBehaviour { public GameObject m_Normal_Monster; float m_Summon_Timer = 0.0f; int m_MCL_Index; void Start() { m_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); } void Update () { if (m_Summon_Timer < 5.0f) m_Summon_Timer += Time.deltaTime; else { Vector3 pos = transform.position; if (!StageManager.GetInstance().Get_MCL_index_is_Blocked(m_MCL_Index)) pos.y = 0.0f; else pos.y = 1.5f; Instantiate(m_Normal_Monster).transform.position = pos; Destroy(gameObject); } } public void Set_Monster_Speed(float s) { m_Normal_Monster.GetComponent<MonsterAI>().Set_Basic_Speed(s); } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using System.Net.Sockets; using System.Net; using System.Threading; using System.Text; using UnityEngine; public class NetTest : MonoBehaviour { public static NetTest instance = null; bool m_ingame = false; int bomb_posx; int bomb_posz; byte[] m_bomb_posx = new byte[4]; byte[] m_bomb_posz = new byte[4]; byte[] m_turtle_posx = new byte[4]; byte[] m_turtle_posz = new byte[4]; byte[] m_turtle_roty = new byte[4]; bool m_set_bomb = false; bool m_is_move = false; private string m_address = "127.0.0.1"; private string m_address2 = "192.168.123.171"; private byte[] R_Map_Info = new byte[225]; private byte[] Receiveid = new byte[4]; byte access_id = 254; byte game_id = 254; private const int m_port = 9000; private const int m_packetSize = 4000; private Socket m_socket = null; private bool m_isConnected = false; public Thread m_thread = null; public bool m_threadLoop = false; public ClientID client_id; byte firepower; byte[] m_firepower = new byte[1]; // 송신 버퍼. private Queue m_sendQueue = new Queue(); int remain_size = 0; // 수신 버퍼. private Queue m_recvQueue = new Queue(); Byte[] temp_buffer = new Byte[m_packetSize]; // 수신한 데이터를 복사할 데이터 Byte[] copy_data = new Byte[m_packetSize]; // 수신 데이터 Byte[] recv_data = new Byte[m_packetSize]; CharInfo[] m_chardata = new CharInfo[4]; private void Awake() { instance = this; DontDestroyOnLoad(this); } // Use this for initialization void Start() { //m_address = Client_IP(); ////Debug.Log(m_address); InitializePos(); client_id.size = 15; Connect(); StartCoroutine("SendTester"); //StartCoroutine("DebugTest"); } void InitializePos() { m_chardata[0].x = 0; m_chardata[0].z = 0; m_chardata[0].rotateY = 0; m_chardata[1].x = 28; m_chardata[1].z = 0; m_chardata[1].rotateY = 0; m_chardata[2].x = 0; m_chardata[2].z = 28; m_chardata[2].rotateY = 180; m_chardata[3].x = 28; m_chardata[3].z = 28; m_chardata[3].rotateY = 180; } //ip값 받아오기 public string Client_IP() { //dns.gethostentry = 호스트ip주소를 확인 //dns.gethostname - 로컬컴퓨터의 호스트 이름을 return IPHostEntry host = Dns.GetHostEntry(Dns.GetHostName()); //임시변수 초기화 string ClientIP = string.Empty; for (int i = 0; i < host.AddressList.Length; i++) { if (host.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { ClientIP = host.AddressList[i].ToString(); } } return ClientIP; } public byte GetId() { return access_id; } public byte GetGameId() { return game_id; } public void Connect() { try { m_socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); m_socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.NoDelay, 1); IPAddress serverIP = System.Net.IPAddress.Parse(m_address); IPEndPoint ipEndPoint = new System.Net.IPEndPoint(serverIP, m_port); //m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.SendTimeout, 10000); // m_socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.ReceiveTimeout, 10000); m_socket.Connect(ipEndPoint); m_socket.NoDelay = true; m_isConnected = true; m_socket.SendBufferSize = 0; //byte[] recvBuffer = new byte[m_packetSize]; m_socket.BeginReceive(this.recv_data, 0, recv_data.Length, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), m_socket); SceneChange.instance.GoTo_Wait_Scene(); } catch (SocketException e) { m_socket = null; m_isConnected = false; Console.WriteLine("{0} Error code: {1}.", e.Message, e.ErrorCode); //Debug.Log("Socket Connect Error."); //Debug.Log("End client communication."); } if (m_socket == null) { Disconnect(); } } public void Disconnect() { m_isConnected = false; if (m_socket != null) { // 소켓 닫기. m_socket.Shutdown(SocketShutdown.Both); m_socket.Close(); m_socket = null; //DestroyThread(); } } private void SendCallBack(IAsyncResult IAR) { string message = (string)IAR.AsyncState; } public void BeginSend(byte[] buffer) { try { // 연결 성공시 if (m_socket.Connected) { m_socket.BeginSend(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(SendCallBack), buffer); } } catch (SocketException e) { //Debug.Log("전송 에러 : " + e.Message); } } public void Receive() { ////Debug.Log("Recv!!"); m_socket.BeginReceive(this.recv_data, 0, recv_data.Length, SocketFlags.None, new AsyncCallback(OnReceiveCallBack), m_socket); } private void OnReceiveCallBack(IAsyncResult IAR) { try { Socket tempSock = (Socket)IAR.AsyncState; int nReadSize = tempSock.EndReceive(IAR); Buffer.BlockCopy(recv_data,0,copy_data,0+ remain_size, nReadSize); remain_size = remain_size + nReadSize; if (nReadSize != 0) { ProcessPacket(copy_data); } if (remain_size>=3) { ProcessPacket(copy_data); } this.Receive(); } catch (SocketException se) { if (se.SocketErrorCode == SocketError.ConnectionReset) { //Debug.Log(se); //this.BeginConnect(); } } } //버퍼를 교체한다. void SwapBuffer(byte size) { int temp = size; ////Debug.Log("Temp int: "+temp+ " "); Array.Clear(temp_buffer, 0, temp_buffer.Length); ////Debug.Log("Clear Temp Array"); remain_size = remain_size - temp; Buffer.BlockCopy(copy_data, temp, temp_buffer, 0, remain_size); ////Debug.Log("Copy to Temp Array"); Array.Clear(copy_data, 0, copy_data.Length); ////Debug.Log("Clear Copy Array"); Buffer.BlockCopy(temp_buffer, 0, copy_data, 0, temp_buffer.Length); ////Debug.Log("Swap Array"); //Debug.Log("Remain_Size2 : " + remain_size); } void ProcessPacket(byte[] recv_buff) { while (remain_size >= 3) { //Debug.Log("This Data : " + copy_data[1] +"\nThis Size:"+ copy_data[0]); switch (copy_data[1]) { case (byte)PacketInfo.ClientID: access_id = copy_data[2]; VariableManager.instance.SetID(copy_data[2]); ////Debug.Log("Get Id!! : " + (byte)access_id); SwapBuffer(copy_data[0]); ////Debug.Log("Remain_Size : " + remain_size); break; case (byte)PacketInfo.CharPos: //다른 유저 위치정보를 전송 byte tempid = copy_data[2]; m_chardata[tempid].ani_state = copy_data[3]; m_chardata[tempid].x = BitConverter.ToSingle(recv_buff, 10); m_chardata[tempid].z = BitConverter.ToSingle(recv_buff, 14); m_chardata[tempid].rotateY = BitConverter.ToSingle(recv_buff, 18); SwapBuffer(copy_data[0]); ////Debug.Log("Remain_Size : " + remain_size); break; case (byte)PacketInfo.BombPos: //폭탄정보 전송(터지는 폭탄) byte tempid2 = copy_data[2]; MapManager.instance.Check_Map(recv_buff); //SetCharPos(recv_buff); SwapBuffer(copy_data[0]); ////Debug.Log("Remain_Size : " + remain_size); break; case (byte)PacketInfo.BombExplode: //폭탄정보 전송(터지는 폭탄) //byte tempid3 = copy_data[2]; byte tempfirepower = copy_data[2]; int tempx = BitConverter.ToInt32(copy_data, 4); int tempz = BitConverter.ToInt32(copy_data, 8); ////Debug.Log("Start Explode Bomb : " + remain_size); MapManager.instance.Explode_Bomb(tempx, tempz, tempfirepower); SwapBuffer(copy_data[0]); /////Debug.Log("Explode Bomb : " + remain_size); break; case (byte)PacketInfo.MapData: ////Debug.Log("Get MapData!! : "); VariableManager.instance.Check_Map(copy_data); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ItemData: byte tempidt = copy_data[2]; byte tempitemt = copy_data[3]; Turtle_Move.instance.SetItem_Ability(tempidt, tempitemt); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.DeadNotice: byte tempid_d = copy_data[2]; Turtle_Move.instance.Dead_Case(tempid_d); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.GameOver: Debug.Log("Game Over!!!"); byte winnerid = copy_data[2]; VSModeManager.instance.GameOver_Set(winnerid); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ObjData: break; case (byte)PacketInfo.EnemyData: break; case (byte)PacketInfo.RoomData: //Debug.Log("Get Room data"); VariableManager.instance.SetRoomState(copy_data); //Debug.Log("Room Info Set Complete"); SwapBuffer(copy_data[0]); //Debug.Log("Buffer Changed"+remain_size); break; case (byte)PacketInfo.RoomAccept: Debug.Log("Get Responce"); byte temp_bool = copy_data[2]; if (temp_bool == 1) { Debug.Log("Get In"); //방으로 들어가는 함수 VariableManager.instance.SetRoomState_Respond(copy_data); SceneChange.instance.GoTo_ModeSelect_Scene(); } else { Debug.Log("Rejected"); } SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.RoomCreate: byte temp_bool2 = copy_data[2]; if (temp_bool2 == 1) { Debug.Log("Get In"); //방으로 들어가는 함수 VariableManager.instance.SetRoomCreate_Respond(copy_data); SceneChange.instance.GoTo_ModeSelect_Scene(); } else { Debug.Log("Cannot Create Room"); } SwapBuffer(copy_data[0]); Debug.Log("Swap Data"); break; case (byte)PacketInfo.GameStart: Debug.Log("Get Game Start Data"); byte temp_boolG_S = copy_data[2]; if (temp_boolG_S == 1) { Debug.Log("Get In"); //방으로 들어가는 함수 //WaitRoom.instance.SetRoomCreate_Respond(copy_data); m_ingame = true; SceneChange.instance.GoTo_Game_Scene(); } else { Debug.Log("Cannot Start"); } SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.OUTRoom: VariableManager.instance.OutRoom(); SceneChange.instance.GoTo_Wait_Scene(); SwapBuffer(copy_data[0]); break; case (byte)PacketInfo.ForceOutRoom: VariableManager.instance.F_OutRoom(); SceneChange.instance.GoTo_Wait_Scene(); SwapBuffer(copy_data[0]); break; default: //Debug.Log(recv_buff[1] + "Unknown PacketType!"); if(copy_data[0]==0) SwapBuffer(17); break; } } } public virtual void WorkerThread() { const int fps = (int)(1000 / 30); int frameTick = Environment.TickCount + fps; while (m_threadLoop) { // 초당 FPS 만큼만 송, 수신 처리 if (Environment.TickCount >= frameTick) { frameTick = Environment.TickCount + fps; } } } void DispatchReceive() { if (m_socket == null) { return; } // 수신처리. try { while (m_socket.Poll(0, SelectMode.SelectRead)) { byte[] buffer = new byte[m_packetSize]; int recvSize = m_socket.Receive(buffer, buffer.Length, SocketFlags.None); if (recvSize == 0) { // 연결 끊기. //Debug.Log("Disconnect recv from other."); Disconnect(); } else if (recvSize > 0) { m_recvQueue.InputQueue(buffer, recvSize); } } } catch { return; } } void SetCharPos(CharInfo c) { switch (c.id) { case 1: if (Turtle_Move.instance.GetId() == 1) { break; } else { NetUser.instance.SetPos(c.x, c.rotateY, c.z); } break; case 2: if (Turtle_Move.instance.GetId() == 2) { break; } else { NetUser2.instance.SetPos(c.x, c.rotateY, c.z); } break; case 3: if (Turtle_Move.instance.GetId() == 3) { break; } else { NetUser3.instance.SetPos(c.x, c.rotateY, c.z); } break; case 4: if (Turtle_Move.instance.GetId() == 4) { break; } else { NetUser4.instance.SetPos(c.x, c.rotateY, c.z); } break; default: break; } } public void SetBombPos(int a, int b) { bomb_posx = a / 2; bomb_posz = b / 2; m_bomb_posx = BitConverter.GetBytes(bomb_posx); m_bomb_posz = BitConverter.GetBytes(bomb_posz); m_set_bomb = true; } public void SetBombPos(int a, int b, byte c) { bomb_posx = a / 2; bomb_posz = b / 2; firepower = c; m_bomb_posx = BitConverter.GetBytes(bomb_posx); m_bomb_posz = BitConverter.GetBytes(bomb_posz); m_set_bomb = true; } public void SetMyPos(float x, float y, float z) { m_turtle_posx = BitConverter.GetBytes(x); m_turtle_posz = BitConverter.GetBytes(z); m_turtle_roty = BitConverter.GetBytes(y); m_is_move = true; } public void SetmoveTrue() { m_is_move = true; } public float GetNetPosx(int i) { if (i >= 0 && i <= 3) return m_chardata[i].x; else return 0; } public float GetNetRoty(int i) { if (i >= 0 && i <= 3) return m_chardata[i].rotateY; else return 0; } public float GetNetPosz(int i) { if (i >= 0 && i <= 3) return m_chardata[i].z; else return 0; } public void SendItemPacket(int x, int z,byte t) { byte[] myInfo = new byte[13]; byte t_size = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 6; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomid = VariableManager.instance.m_roomid; byte t_ingameid = Turtle_Move.instance.GetId(); byte[] m_packet_roomid = BitConverter.GetBytes(t_roomid); byte[] m_packet_ingameid = BitConverter.GetBytes(t_ingameid); int tempx = x/2; int tempz = z/2; byte[] m_item_type = BitConverter.GetBytes(t); byte[] m_packet_x = BitConverter.GetBytes(tempx); byte[] m_packet_z = BitConverter.GetBytes(tempz); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 2, m_packet_roomid.Length); Buffer.BlockCopy(m_packet_ingameid, 0, myInfo, 3, m_packet_ingameid.Length); Buffer.BlockCopy(m_item_type, 0, myInfo, 4, m_item_type.Length); Buffer.BlockCopy(m_packet_x, 0, myInfo, 5, m_packet_x.Length); Buffer.BlockCopy(m_packet_z, 0, myInfo, 9, m_packet_z.Length); m_socket.Send(myInfo); } void SendTurtlePacket() { bool tempbool = m_is_move; if (tempbool) { byte[] ReceivebTurtles_Pos = new byte[22]; byte t_size = 22; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte t_type = 1; byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = VariableManager.instance.pos_inRoom; t_id--; byte t_roomid = VariableManager.instance.m_roomid; byte[] m_turtle_id = BitConverter.GetBytes(t_id); byte t_alive = Turtle_Move.instance.alive; byte[] t_turtle_alive = BitConverter.GetBytes(t_alive); byte[] m_room_id = BitConverter.GetBytes(t_roomid); //m_Socket.Send(m_packet_type); //MemoryStream memStream = new MemoryStream(17); Buffer.BlockCopy(m_packet_size, 0, ReceivebTurtles_Pos, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, ReceivebTurtles_Pos, 1, m_packet_type.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 2, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 3, m_turtle_id.Length);//애니메이션 상태지만 일단 보류 Buffer.BlockCopy(t_turtle_alive, 0, ReceivebTurtles_Pos, 4, t_turtle_alive.Length); Buffer.BlockCopy(m_room_id, 0, ReceivebTurtles_Pos, 5, m_room_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 6, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 7, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 8, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_id, 0, ReceivebTurtles_Pos, 9, m_turtle_id.Length); Buffer.BlockCopy(m_turtle_posx, 0, ReceivebTurtles_Pos, 10, m_turtle_posx.Length); Buffer.BlockCopy(m_turtle_posz, 0, ReceivebTurtles_Pos, 14, m_turtle_posz.Length); Buffer.BlockCopy(m_turtle_roty, 0, ReceivebTurtles_Pos, 18, m_turtle_roty.Length); ////Debug.Log(n); m_socket.Send(ReceivebTurtles_Pos); ////Debug.Log("Send"); m_is_move = false; } } void SendMyInfo() { byte[] myInfo = new byte[12]; byte t_size = 12; byte t_type = 9; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = (byte)access_id; byte[] m_packet_id = BitConverter.GetBytes(t_id); byte t_gameid = (byte)game_id; byte[] m_packet_gameid = BitConverter.GetBytes(t_gameid); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_gameid, 0, myInfo, 3, m_packet_gameid.Length); m_socket.Send(myInfo); } public void SendJoinPacket() { byte[] myInfo = new byte[12]; byte t_size = 12; byte t_type = 9; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = VariableManager.instance.m_accessid; byte[] m_packet_id = BitConverter.GetBytes(t_id); byte t_roomid = VariableManager.instance.GetRoomNum(); byte[] m_packet_roomid= BitConverter.GetBytes(t_roomid); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_roomid, 0, myInfo, 3, m_packet_roomid.Length); m_socket.Send(myInfo); } public void SendCreatePacket() { byte[] myInfo = new byte[11]; byte t_size = 11; byte t_type = 10; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = VariableManager.instance.m_accessid; byte[] m_packet_id = BitConverter.GetBytes(t_id); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); m_socket.Send(myInfo); } public void SendStartPacket() { byte[] myInfo = new byte[4]; byte t_size = 4; byte t_type = 12; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; //Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); m_socket.Send(myInfo); } public void SendReadyPacket() { byte[] myInfo = new byte[11]; byte t_size = 11; byte t_type = 12; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = (byte)access_id; byte[] m_packet_id = BitConverter.GetBytes(t_id); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); m_socket.Send(myInfo); } public void SendOUTPacket() { byte[] myInfo = new byte[4]; byte t_size = 4; byte t_type = 13; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_id = GameRoom.instance.GetRoomID(); byte[] m_packet_id = BitConverter.GetBytes(t_id); byte my_pos = GameRoom.instance.pos_inRoom; byte[] m_packet_my_pos = BitConverter.GetBytes(my_pos); myInfo[3] = my_pos; //Debug.Log(myInfo[3]); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_packet_id, 0, myInfo, 2, m_packet_id.Length); Buffer.BlockCopy(m_packet_my_pos, 0, myInfo, 3, 1); m_socket.Send(myInfo); } public void SendBanPacket(byte a) { byte[] myInfo = new byte[4]; byte t_size = 4; byte t_type = 14; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_roomnum = GameRoom.instance.GetRoomID(); byte[] m_room_num = BitConverter.GetBytes(t_roomnum); byte t_pos = a; byte[] m_clicked_pos = BitConverter.GetBytes(t_pos); Buffer.BlockCopy(m_packet_size, 0, myInfo, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, myInfo, 1, m_packet_type.Length); Buffer.BlockCopy(m_room_num, 0, myInfo, 2, m_room_num.Length); Buffer.BlockCopy(m_clicked_pos, 0, myInfo, 3, 1); m_socket.Send(myInfo); } public void SendBombPacket() { bool tempbool = m_set_bomb; if (tempbool) { byte[] TurtleBomb_Bomb = new byte[12]; byte t_size = 12; byte t_type = 2; byte t_id = VariableManager.instance.pos_inRoom; t_id--; byte[] m_packet_size = BitConverter.GetBytes(t_size); byte[] m_packet_type = BitConverter.GetBytes(t_type); byte t_room = VariableManager.instance.m_roomid; byte[] m_roomid = BitConverter.GetBytes(t_room); byte[] t_turtlefire = BitConverter.GetBytes(Turtle_Move.instance.GetFirePower()); Buffer.BlockCopy(m_packet_size, 0, TurtleBomb_Bomb, 0, m_packet_size.Length); Buffer.BlockCopy(m_packet_type, 0, TurtleBomb_Bomb, 1, m_packet_type.Length); Buffer.BlockCopy(t_turtlefire, 0, TurtleBomb_Bomb, 2, t_turtlefire.Length); Buffer.BlockCopy(m_roomid, 0, TurtleBomb_Bomb, 3, m_roomid.Length); Buffer.BlockCopy(m_bomb_posx, 0, TurtleBomb_Bomb, 4, m_bomb_posx.Length); Buffer.BlockCopy(m_bomb_posz, 0, TurtleBomb_Bomb, 8, m_bomb_posz.Length); m_socket.Send(TurtleBomb_Bomb); m_set_bomb = false; ////Debug.Log("폭탄보냄"); } } IEnumerator SendTester() { for (;;) { if (m_ingame) { SendTurtlePacket(); //SendBombPacket(); } yield return new WaitForSeconds(0.03f); } } IEnumerator DebugTest() { for (;;) { //Debug.Log(copy_data[1]); yield return new WaitForSeconds(3f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class TestNet : MonoBehaviour { public GameObject m_bomb; GameObject[] bomb_list = new GameObject[14]; // Use this for initialization bool m_is_Rising_Start = true; bool m_is_Done_Rising = false; bool[] m_is_rising_start = new bool[14]; bool[] m_is_donerising = new bool[14]; bool[] is_alive = new bool[14]; int[] dx = new int[14]; int[] sx = new int[14]; int[] sz = new int[14]; int a = 0; int[] dz=new int[14]; byte[] dirc = new byte[14]; void Start () { for(int i = 0; i < 14; ++i) { bomb_list[i] = Instantiate(m_bomb); bomb_list[i].transform.position = new Vector3(2*i, 0, 0); m_is_Rising_Start = true; m_is_donerising[i] = false; m_is_rising_start[i] = true; is_alive[i] = true; sx[i] = 2 * i; sz[i] = 0; dx[i] = 2 * i; dz[i] = 2 * i; dirc[i] = 3; //bomb_list[i].SetActive(false); } } public int GetGameObject2() { for(int i = 0; i < 14; ++i) { if (!bomb_list[i].activeInHierarchy) { return i; } } return -1; } public int GetGameObject() { for (int i = 0; i < 14; ++i) { if (!is_alive[i]) { is_alive[i] = true; return i; } } return -1; } void GetPacket(int x,int z, int x_d,int z_d,byte direction) { int b = GetGameObject(); if (b >= 0) { dirc[b] = direction; sx[b] = x; sz[b] = z; dx[b] = x_d; dz[b] = z_d; bomb_list[b].transform.position = new Vector3(x, 0.0f, z); bomb_list[b].gameObject.SetActive(true); } } //겜오브젝트로 받지 말고, 인트로 받아보자 public void Thrown_Bomb_Move(GameObject gBomb, int x, int z, int x_dest, int z_dest, byte direction) { //gBomb.gameObject.transform.position = new Vector3(x, 0, z); float m_Rising_Limit = 4.0f; float m_Down_Limit = 0.0f; float m_Thrown_Bomb_Speed = 10.0f; float m_Rising_Speed = 4.0f; if (m_is_Rising_Start) { // 폭탄 일정량 상승 gBomb.gameObject.transform.position = new Vector3(gBomb.gameObject.transform.position.x, (gBomb.gameObject.transform.position.y + (m_Rising_Speed * Time.deltaTime)), gBomb.gameObject.transform.position.z); ////Debug.Log("bombBombUp"); if (gBomb.gameObject.transform.position.y > 2.0f) { m_is_Rising_Start = false; //GetComponentInChildren<MeshRenderer>().enabled = true; } } else { ////Debug.Log("bombBombDown"); // 폭탄 전방 이동 switch (direction) { case 1: if (gBomb.gameObject.transform.position.x <= x_dest) gBomb.gameObject.transform.Translate(new Vector3((m_Thrown_Bomb_Speed * Time.deltaTime), 0.0f, 0.0f)); else gBomb.gameObject.transform.position = (new Vector3(x_dest, gBomb.gameObject.transform.position.y, gBomb.gameObject.transform.position.z)); break; case 2: if (gBomb.gameObject.transform.position.x >= x_dest) gBomb.gameObject.transform.Translate(new Vector3(-(m_Thrown_Bomb_Speed * Time.deltaTime), 0.0f, 0.0f)); else gBomb.gameObject.transform.position = (new Vector3(x_dest, gBomb.gameObject.transform.position.y, gBomb.gameObject.transform.position.z)); break; case 3: if (gBomb.gameObject.transform.position.z <= z_dest) gBomb.gameObject.transform.Translate(new Vector3(0.0f, 0.0f, (m_Thrown_Bomb_Speed * Time.deltaTime))); //else // gBomb.gameObject.transform.position = (new Vector3(gBomb.gameObject.transform.position.x, gBomb.gameObject.transform.position.y, z_dest)); break; case 4: if (gBomb.gameObject.transform.position.z >= z_dest) gBomb.gameObject.transform.Translate(new Vector3(0.0f, 0.0f, -(m_Thrown_Bomb_Speed * Time.deltaTime))); else gBomb.gameObject.transform.position = (new Vector3(gBomb.gameObject.transform.position.x, gBomb.gameObject.transform.position.y, z_dest)); break; } } if (!m_is_Done_Rising && gBomb.gameObject.transform.position.y < m_Rising_Limit) { // 폭탄 상승 //Debug.Log("올라간다"); gBomb.gameObject.transform.Translate(new Vector3(0.0f, (m_Rising_Speed * Time.deltaTime), 0.0f)); } if (gBomb.gameObject.transform.position.y >= m_Rising_Limit) { // 폭탄 상승 끝 m_is_Done_Rising = true; } //if (m_is_Done_Rising && transform.position.y > m_Down_Limit) if (m_is_Done_Rising && gBomb.gameObject.transform.position.y > m_Down_Limit) { // 폭탄 하강 //Debug.Log("떨어진다"); gBomb.gameObject.transform.Translate(new Vector3(0.0f, -(m_Rising_Speed * Time.deltaTime), 0.0f)); } if (gBomb.gameObject.transform.position.y < m_Down_Limit) { gBomb.gameObject.transform.position = new Vector3(gBomb.gameObject.transform.position.x,0.0f, gBomb.gameObject.transform.position.z); } if (transform.position.x < -0.5f || transform.position.x > 28.5f || transform.position.z < 49.5f || transform.position.z > 78.5f) { // 맵 범위 밖으로 나가면 제거 // StageManager.Update_MCL_isBlocked(m_My_MCL_Index, false); //Destroy(gBomb); } } //겜오브젝트로 받지 말고, 인트로 받아보자 public void Thrown_Bomb_Move(int g, int x, int z, int x_dest, int z_dest, byte direction) { //gBomb.gameObject.transform.position = new Vector3(x, 0, z); if (g >= 0) { float m_Rising_Limit = 4.0f; float m_Down_Limit = 0.0f; bool tempBool = false; float m_Thrown_Bomb_Speed = 15.0f; float m_Rising_Speed = 8.0f; if (bomb_list[g].gameObject.activeInHierarchy) { if (x_dest == (int)bomb_list[g].gameObject.transform.position.x && z_dest == (int)bomb_list[g].gameObject.transform.position.z&& bomb_list[g].gameObject.transform.position.y==0) { //Debug.Log(g + "번째 투척완료!!!"); bomb_list[g].gameObject.SetActive(false); m_is_rising_start[g] = true; m_is_donerising[g] = false; is_alive[g] = false; } if (m_is_rising_start[g]) { // 폭탄 일정량 상승 bomb_list[g].gameObject.transform.position = new Vector3(bomb_list[g].gameObject.transform.position.x, (bomb_list[g].gameObject.transform.position.y + (m_Rising_Speed * Time.deltaTime)), bomb_list[g].gameObject.transform.position.z); ////Debug.Log("bombBombUp"); if (bomb_list[g].gameObject.transform.position.y > 2.0f) { m_is_rising_start[g] = false; //GetComponentInChildren<MeshRenderer>().enabled = true; } } else { ////Debug.Log("bombBombDown"); // 폭탄 전방 이동 switch (direction) { case 1: tempBool = bomb_list[g].gameObject.transform.position.x >= x_dest - 3; if (bomb_list[g].gameObject.transform.position.x <= x_dest) bomb_list[g].gameObject.transform.Translate(new Vector3((m_Thrown_Bomb_Speed * Time.deltaTime), 0.0f, 0.0f)); else bomb_list[g].gameObject.transform.position = (new Vector3(x_dest, bomb_list[g].gameObject.transform.position.y, bomb_list[g].gameObject.transform.position.z)); break; case 2: tempBool = bomb_list[g].gameObject.transform.position.x <= x_dest + 3; if (bomb_list[g].gameObject.transform.position.x >= x_dest) bomb_list[g].gameObject.transform.Translate(new Vector3(-(m_Thrown_Bomb_Speed * Time.deltaTime), 0.0f, 0.0f)); else bomb_list[g].gameObject.transform.position = (new Vector3(x_dest, bomb_list[g].gameObject.transform.position.y, bomb_list[g].gameObject.transform.position.z)); break; case 3: tempBool = bomb_list[g].gameObject.transform.position.z >= z_dest - 3; if (bomb_list[g].gameObject.transform.position.z <= z_dest) bomb_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, (m_Thrown_Bomb_Speed * Time.deltaTime))); //else // bomb_list[g].gameObject.transform.position = (new Vector3(bomb_list[g].gameObject.transform.position.x, bomb_list[g].gameObject.transform.position.y, z_dest)); break; case 4: tempBool = bomb_list[g].gameObject.transform.position.z <= z_dest + 3; if (bomb_list[g].gameObject.transform.position.z >= z_dest) bomb_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, -(m_Thrown_Bomb_Speed * Time.deltaTime))); else bomb_list[g].gameObject.transform.position = (new Vector3(bomb_list[g].gameObject.transform.position.x, bomb_list[g].gameObject.transform.position.y, z_dest)); break; } } if (!m_is_donerising[g] && bomb_list[g].gameObject.transform.position.y < m_Rising_Limit) { // 폭탄 상승 ////Debug.Log("올라간다"); bomb_list[g].gameObject.transform.Translate(new Vector3(0.0f, (m_Rising_Speed * Time.deltaTime), 0.0f)); } if (bomb_list[g].gameObject.transform.position.y >= m_Rising_Limit) { // 폭탄 상승 끝 m_is_donerising[g] = true; } //if (m_is_Done_Rising && transform.position.y > m_Down_Limit) if (m_is_donerising[g] && bomb_list[g].gameObject.transform.position.y > m_Down_Limit && tempBool) { // 폭탄 하강 ////Debug.Log("떨어진다"); bomb_list[g].gameObject.transform.Translate(new Vector3(0.0f, -(m_Rising_Speed * Time.deltaTime), 0.0f)); } if (bomb_list[g].gameObject.transform.position.y < m_Down_Limit) { bomb_list[g].gameObject.transform.position = new Vector3(bomb_list[g].gameObject.transform.position.x, 0.0f, bomb_list[g].gameObject.transform.position.z); } if (transform.position.x < -0.5f || transform.position.x > 28.5f || transform.position.z < 49.5f || transform.position.z > 78.5f) { // 맵 범위 밖으로 나가면 제거 // StageManager.Update_MCL_isBlocked(m_My_MCL_Index, false); //Destroy(gBomb); } } } } // Update is called once per frame void Update () { if (Input.GetKey(KeyCode.W)) { GetPacket(0,0,0,10+a,3); a++; } // if (Input.GetKeyDown(KeyCode.Space)) //{ for (int i = 0; i < 14; ++i) { if(is_alive[i]) Thrown_Bomb_Move(i, sx[i], sz[i], dx[i], dz[i], dirc[i]); } //} } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Box_Particle_Manager : MonoBehaviour { void Update () { if (gameObject.GetComponentInChildren<ParticleSystem>().time >= gameObject.GetComponentInChildren<ParticleSystem>().main.duration) Destroy(gameObject); } } <file_sep>#pragma once #define WIN32_LEAN_AND_MEAN #define INITGUID #include <WinSock2.h> #include <windows.h> // include important windows stuff #pragma comment(lib, "ws2_32.lib") #include <thread> #include <vector> #include <array> #include <iostream> #include <unordered_set> #include <mutex> #include <vector> #include <set> #include <thread> #include <mutex> #include <queue> #include <stack> #include <set> #include <map> #include <list> #include <thread> #include <string> #include <chrono> #include <WinSock2.h> #include <Windows.h> #include <random> #include <cmath> #include <windows.h> #include <wininet.h> #include <stdio.h> #include<fstream> #include<iterator> #include <math.h> using namespace std; #define MAX_BUFF_SIZE 4000 // 작으면 성능이 떨어진다. #define MAX_PACKET_SIZE 255 #define BOARD_WIDTH 400 #define BOARD_HEIGHT 400 #define DB_PORT 3306 #define SHOW_PLAYER_POS_X 10 #define SHOW_PLAYER_POS_Y 10 #define VIEW_RADIUS 3 #define MAX_USER 500 #define NPC_START 1000 #define NUM_OF_NPC 10000 #define MY_SERVER_PORT 9000 // 포트는 서버/클라 동일해야함. #define MAX_STR_SIZE 100 #define CS_UP 1 #define CS_DOWN 2 #define CS_LEFT 3 #define CS_RIGHT 4 #define CS_CHAT 5 #define SC_POS 1 #define SC_PUT_PLAYER 2 #define SC_REMOVE_PLAYER 3 #define SC_CHAT 4 //TBServer #define MAX_USER_INROOM 4 #define MAX_NPC 50 #define CASE_POS 1 #define CASE_BOMB 2 #define CASE_BOMB_EX 3 #define CASE_MAP 4 #define CASE_ID 5 #define CASE_ITEM_GET 6 #define CASE_DEAD 7 #define CASE_ROOM 8 #define CASE_JOINROOM 9 #define CASE_CREATEROOM 10 #define CASE_READY 11 #define CASE_STARTGAME 12 #define CASE_OUTROOM 13 #define CASE_GAMESET 15 #define CASE_THROWBOMB 17 #define CASE_KICKBOMB 18 #define CASE_THROWCOMPLETE 19 #define CASE_KICKCOMPLETE 20 #define CASE_MAPSET 21 #define CASE_BOXPUSH 22 #define CASE_BOXPUSHCOMPLETE 23 #define CASE_TIME 24 #define CASE_BOMBSET 25 #define CASE_CONNECTSUCCESS 26 #define CASE_DB1 27 #define CASE_GAMEREADY 28 #define CASE_MATCH 14 #define CASE_BOSS 16 #define SIZEOF_TB_GameStartRE_Cop 84 #define SIZEOF_TB_CharPos 22 #define SIZEOF_TB_BossPos 18 #define SIZEOF_TB_GAMEReady 5 #define SIZEOF_TB_BombPos 17 #define SIZEOF_TB_BombExplode 13 #define SIZEOF_TB_BombExplodeRE 15 #define SIZEOF_TB_MAP 227 #define SIZEOF_TB_ID 3 #define SIZEOF_TB_ItemGet 13 #define SIZEOF_TB_GetItem 4 #define SIZEOF_TB_DEAD 3 #define SIZEOF_TB_GAMEEND 4 #define SIZEOF_TB_Room 31 #define SIZEOF_TB_join 12 #define SIZEOF_TB_joinRE 10 #define SIZEOF_TB_create 12 #define SIZEOF_TB_createRE 4 #define SIZEOF_TB_GameStart 4 #define SIZEOF_TB_GameStartRE 3 #define SIZEOF_CASE_READY 5 #define SIZEOF_TB_ReadyRE 5 #define SIZEOF_TB_RoomOut 5 #define SIZEOF_TB_RoomOutRE 3 #define SIZEOF_TB_GetOut 4 #define SIZEOF_TB_GetOutRE 2 #define SIZEOF_TB_RoomSetting 6 #define SIZEOF_TB_TeamSetting 5 #define SIZEOF_TB_ThrowBomb 13 #define SIZEOF_TB_ThrowBombRE 20 #define SIZEOF_TB_ThrowComplete 11 #define SIZEOF_TB_MapSetRE 11 #define SIZEOF_TB_BoxPush 13 #define SIZEOF_TB_BoxPushComplete 11 #define SIZEOF_TB_BoxPushRE 21 #define SIZEOF_TB_Time 6 #define MAX_EVENT_SIZE 64 #define SIZEOF_TB_Connect_Success 2 #define SIZEOF_TB_IDPW 44 #define SIZEOF_TB_DBInfo_1 43 #define MAP_NOTHING 0 #define MAP_BOX 1 #define MAP_ROCK 2 #define MAP_BUSH 3 #define MAP_ITEM 11 #define MAP_BOMB 5 #define MAP_ITEM_F 13 #define MAP_ITEM_S 12 #define MAP_FIREBUSH 10 #define MAP_KICKITEM 14 #define MAP_THROWITEM 15 #define MAP_CHAR 7 #define MAP_ENEMY 8 #define MAP_BOSS 9 #define BASIC_POSX_CHAR1 0 #define BASIC_POSZ_CHAR1 0 #define BASIC_POSX_CHAR2 0 #define BASIC_POSZ_CHAR2 0 #define BASIC_POSX_CHAR3 0 #define BASIC_POSZ_CHAR3 0 #define BASIC_POSX_CHAR4 0 #define BASIC_POSZ_CHAR4 0 #define TURTLE_ANI_IDLE 0 #define TURTLE_ANI_WALK 1 #define TURTLE_ANI_HIDE 2 #define TURTLE_ANI_DEAD 3 #define TURTLE_ANI_KICK 4 #define TURTLE_ANI_PUSH 5 #pragma pack (push, 1) struct cs_packet_up { unsigned char size; unsigned char type; }; struct cs_packet_down { unsigned char size; unsigned char type; }; struct cs_packet_left { unsigned char size; unsigned char type; }; struct cs_packet_right { unsigned char size; unsigned char type; }; struct cs_packet_chat { unsigned char size; unsigned char type; wchar_t message[MAX_STR_SIZE]; }; struct sc_packet_pos { unsigned char size; unsigned char type; unsigned short id; unsigned short x; unsigned short y; }; struct sc_packet_put_player { unsigned char size; unsigned char type; unsigned short id; unsigned short x; unsigned short y; }; struct sc_packet_remove_player { unsigned char size; unsigned char type; short id; }; struct sc_packet_chat { unsigned char size; unsigned char type; short id; wchar_t message[MAX_STR_SIZE]; }; struct Socket_Info { SOCKET sock; bool m_connected; bool m_getpacket; char buf[MAX_BUFF_SIZE]; int type; int id; int recvbytes; int sendbytes; int remainbytes; unsigned char roomID; //디폴트는 0. 안 들어갔다는 뜻 unsigned char is_guardian; //방장인지 아닌지 unsigned char is_ready; //추가 unsigned char fire; unsigned char bomb; unsigned char speed; unsigned char pos_inRoom; }; struct TB_MatchingInfo { unsigned char size; //7 unsigned char type; //14 unsigned char m_id; unsigned char difficulty; unsigned char boss_type; unsigned char map_type; unsigned char prefer_man; //몇명을 선호하는지 - 0 상관없음, 다른 숫자는 선호하는 명 수 - 최대 4 }; struct TB_MatchingInfo_RE { unsigned char size; //3 unsigned char type;//14 unsigned char match; }; struct TB_GAMEReady { unsigned char size; //5 unsigned char type; //28 unsigned char imready; //1이면 레디,0이면 noready unsigned char roomid; unsigned char myid; }; struct TB_DBInfo_1 { unsigned char size; //43 unsigned char type; //27 unsigned char connect; //2이면 아이디 생성완료, 1이면 아이디 인증 성공, 0면 아이디 인증 실패 char id_string[20]; int win; int lose; int tier; int exp; int exp_max; }; struct TB_Connect_Success { unsigned char size; //2 unsigned char type; //26 }; struct TB_IDPW { unsigned char size; //44 unsigned char type; //26] unsigned char m_id; //26] unsigned char m_type; //1이면 로그인, 2면 생성 char id[20]; char pw[20]; }; struct GameCharInfo { unsigned char speed; unsigned char fire; unsigned char bomb; }; struct TB_CharPos {//type:1 unsigned char size; //22 unsigned char type; unsigned char ingame_id; unsigned char anistate; unsigned char is_alive; unsigned char room_id; unsigned char fire; unsigned char bomb; unsigned char can_throw; unsigned char can_kick; float posx; float posz; float rotY; }; struct TB_BossPos {//type:1 unsigned char size; //18 unsigned char type;//16 unsigned char anistate; unsigned char is_alive; unsigned char targetid; unsigned char room_id; float posx; float posz; float rotY; }; struct TB_BombPos { //type:2 unsigned char size;//17 unsigned char type; unsigned char ingame_id; unsigned char firepower; //화력 //unsigned char throwing; //던져지고 있는지 //unsigned char kicking; //차여지고 있는지 unsigned char room_num; int posx; int posz; float settime; }; struct TB_BombSetRE { unsigned char size;//11 unsigned char type;//25 unsigned char f_power; int posx; int posz; }; struct TB_MapSetRE { unsigned char size;//11 unsigned char type;//21 unsigned char m_type; int posx; int posz; }; struct TB_BombExplode { //type:3 unsigned char size;//13 unsigned char type; unsigned char firepower; unsigned char room_id; unsigned char game_id; int posx; int posz; }; struct TB_BombExplodeRE { //type:3 unsigned char size;//15 unsigned char type; unsigned char upfire; unsigned char rightfire; unsigned char downfire; unsigned char leftfire; unsigned char gameID; int posx; int posz; }; struct TB_ThrowBomb { unsigned char size;//13 unsigned char type;//17 unsigned char roomid; unsigned char ingame_id; unsigned char direction; int posx; int posz; }; struct TB_ThrowBombRE { unsigned char size;//20 unsigned char type;//17 unsigned char direction; unsigned char ingame_id; int posx; int posz; int posx_re; int posz_re; }; struct TB_ThrowComplete { unsigned char size;//11 unsigned char type;//19 unsigned char roomid; int posx; int posz; }; struct TB_KickBomb { unsigned char size;//13 unsigned char type;//18 unsigned char roomid; unsigned char ingame_id; unsigned char direction; int posx; int posz; }; struct TB_KickComplete { unsigned char size;//11 unsigned char type;//20 unsigned char roomid; int posx; int posz; }; struct TB_KickBombRE { unsigned char size;//21 unsigned char type;//18 unsigned char kick; unsigned char ingame_id; unsigned char direction; int posx; int posz; int posx_re; int posz_re; }; struct TB_BoxPush { unsigned char size;//13 unsigned char type;//22 unsigned char roomid; unsigned char ingame_id; unsigned char direction; int posx; int posz; }; struct TB_BoxPushRE { unsigned char size;//21 unsigned char type;//22 unsigned char push; //0이면 안밀어, 1이면 밀어~! unsigned char ingame_id; unsigned char direction; int posx; int posz; int posx_d; int posz_d; }; struct TB_BoxPushComplete { unsigned char size;//11 unsigned char type;//19 unsigned char roomid; int posx; int posz; }; struct TB_ReGame { }; struct TB_Map { //type:4 unsigned char size;//227 unsigned char type; unsigned char mapInfo[15][15]; }; struct TB_ID {//type:5 unsigned char size; //3 unsigned char type; unsigned char id; //0330 수정 int에서- BYTE로 수정 }; struct TB_ItemGet { //type:6 unsigned char size; //13 unsigned char type;//6 unsigned char room_id; unsigned char ingame_id; unsigned char item_type; int posx; int posz; }; struct TB_GetItem { //send : type 6 서버 전송-> 클라 수신 unsigned char size; //4 unsigned char type;//6 unsigned char ingame_id; unsigned char itemType; //타입에 따라 다른 문구가 출력된다 + 능력이 오른다. }; struct TB_DEAD { //죽었을 때 알려주는 패킷 unsigned char size; //3 unsigned char type;//7 unsigned char game_id; //누가 죽었나! }; struct TB_GAMEEND { unsigned char size; //3 unsigned char type;//15 unsigned char winner_id; //누가 이겼나! unsigned char loser_id; }; struct TB_UserInfo { //유저정보 - type: 7 unsigned char size; //9 unsigned char type; unsigned char id; //인게임 id와는 다르다. unsigned char roomID; //디폴트는 0. 안 들어갔다는 뜻 unsigned char is_guardian;//방장인지 아닌지 unsigned char is_ready; //추가 unsigned char fire; unsigned char bomb; unsigned char speed; }; //프로토콜이 아닌 구조체에 맵데이터를 넣은 방 구조체 작성 struct TB_Room { //방장 추가(완) unsigned char size; //31 unsigned char type;//8 unsigned char roomID; unsigned char people_count; unsigned char game_start; //게임 시작 1 unsigned char people_max; //최대 인원 수 unsigned char made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) unsigned char guardian_pos; //배열에 넣을 때 -1할 것 unsigned char people_inroom[4]; unsigned char roomstate; //팀전인가 개인전인가? 0-개인전 1-팀전 unsigned char map_thema; unsigned char map_mode; unsigned char team_inroom[4]; unsigned char ready[4]; char password[8]; }; struct TB_RoomInfo { unsigned char room_num; unsigned char people_count; unsigned char people_max; unsigned char game_start; }; //없는 방입니다. //게임중입니다. struct TB_Ready { unsigned char size; //5 unsigned char type;//11 unsigned char room_num; unsigned char pos_in_room; unsigned char will_ready; // 0이면 레디하겠다고 보내온 것, 1이면 레디를 해제하겠다고 보내온 것. }; struct TB_ReadyRE { unsigned char size; //5 unsigned char type;//11 unsigned char pos_in_room; unsigned char ready;//0이면 레디해제, 1이면 레디 unsigned char roomid; }; struct TB_GameStart { unsigned char size;//4 unsigned char type;//12 unsigned char roomID; unsigned char my_pos; }; struct TB_GameStartRE { unsigned char size; unsigned char type; unsigned char startTB;//1이면 시작,0이면 땡 }; struct TB_GameStartRE_Cop { unsigned char size;//85 unsigned char type;//12 unsigned char startTB; //0이면 매칭 실패, 1이면 성공 unsigned char howmany; unsigned char roomid; char id1[20]; char id2[20]; char id3[20]; char id4[20]; }; struct TB_Refresh { //type:? unsigned char size; unsigned char type; unsigned char id; unsigned char roomID; }; struct TB_join { //들어갈 때 보내는 패킷 9 unsigned char size; unsigned char type;//9 unsigned char id; unsigned char roomID; char password[8]; }; struct TB_joinRE { //방장 추가 unsigned char size;//10 unsigned char type; unsigned char respond; //0이면 no, 1이면 yes unsigned char my_room_num; unsigned char yourpos; //1,2,3,4 중 하나 unsigned char guard_pos; //방장 위치 unsigned char people_inroom[4]; }; struct TB_create { //type:10 unsigned char size; unsigned char type; unsigned char id; unsigned char roomid; char password[8]; }; struct TB_createRE { unsigned char size; unsigned char type; unsigned char can; //가능하면 1, 불가능하면 0 unsigned char roomid; }; struct TB_GetOut {//클라 전송->서버 수신, 서버 전송할 경우 받은 클라는 강퇴 결과 출력 unsigned char size; unsigned char type;//14 unsigned char roomID; unsigned char position; }; //받았을 경우 turtle_room.people_count-=1; turtle_waitroom.roodID = 0; struct TB_RoomOut {//방에서 나갈 때 unsigned char size;//4 unsigned char type;//13 unsigned char roomID; unsigned char my_pos; unsigned char imwinner; //2일경우 lose }; struct TB_GetOUTRE { unsigned char size; unsigned char type;//14 }; struct TB_RoomOutRE { unsigned char size; unsigned char type; unsigned char can; //가능하면 1, 불가능하면 0 }; struct TB_RoomSetting { unsigned char size;//6 unsigned char type;//15 unsigned char roomid; unsigned char peoplemax; //인원수 unsigned char mapthema; unsigned char mapnum; }; struct TB_TeamSetting { unsigned char size;//5 unsigned char type;//16 unsigned char roomid; unsigned char pos_in_room; unsigned char team; }; struct TB_Time { unsigned char size;//6 unsigned char type;//24 float time; }; struct TB_Room_Data { //방장 추가(완) unsigned char roomID; unsigned char people_count; unsigned char game_start; unsigned char people_max; //최대 인원 수 unsigned char made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) unsigned char guardian_pos; //배열에 넣을 때 -1할 것 unsigned char people_inroom[4]; TB_Map map; char password[8]; }; struct Map_TB { unsigned char mapTile[15][15]; }; #pragma pack(pop) class Bomb_TB { public: pair<int, int> xz; float time; bool is_throw; bool is_kicked; unsigned char firepower; float explode_time; unsigned char room_num; unsigned char game_id; bool operator ==(const Bomb_TB& other) { return xz == other.xz; } Bomb_TB() { time = (float)GetTickCount() / 1000; explode_time = 2.0f; xz = make_pair(0, 0); is_throw = false; is_kicked = false; } Bomb_TB(int a, int b) { time = (float)GetTickCount() / 1000; explode_time = 2.0f; xz = make_pair(a, b); is_throw = false; is_kicked = false; } Bomb_TB(int a, int b, unsigned char r, unsigned char f, unsigned char g) { time = (float)GetTickCount() / 1000; explode_time = 2.0f; room_num = r; firepower = f; game_id = g; xz = make_pair(a, b); is_throw = false; is_kicked = false; } bool GetTime() { float temptime = (float)GetTickCount() / 1000; return (temptime - time >= explode_time) && !is_throw && !is_kicked; } void ResetExplodeTime() { float temptime = (float)GetTickCount() / 1000; temptime = temptime - time; explode_time = explode_time - temptime; } void ResetTime() { time = (float)GetTickCount() / 1000; } pair<int, int> GetXZ() { return xz; } }; class InGameCalculator { bool id[4]; float time; bool gameover; public: float start_time; float boss_speed; map<pair<int, int>, Bomb_TB> bomb_Map; vector<TB_BombExplodeRE> explode_List; bool ready_player[4]; bool is_start; TB_BossPos ingame_boss_Info; int boss_timestamp; int idList[4]; int howmany; TB_Map map; TB_CharPos ingame_Char_Info[4]; unsigned char fireMap[15][15]; int deathcount; InGameCalculator() { explode_List.clear(); deathcount = 0; boss_timestamp = 0; id[0] = true; id[1] = true; id[2] = true; id[3] = true; howmany = 2; time = 180.0f; boss_speed = 1.0f; gameover = false; map.size = SIZEOF_TB_MAP; map.type = CASE_MAP; ingame_boss_Info.size = SIZEOF_TB_BossPos; ingame_boss_Info.type = CASE_BOSS; ingame_boss_Info.posx = 14.0f; ingame_boss_Info.posz = 14.0f; ingame_boss_Info.rotY = 0.0f; ingame_boss_Info.is_alive = true; ingame_boss_Info.anistate = 0; for (int i = 0; i < 4; ++i) { ingame_Char_Info[i].size = SIZEOF_TB_CharPos; ingame_Char_Info[i].type = CASE_POS; idList[i] =-1; } for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { fireMap[i][j] = 0; } } ingame_Char_Info[0].ingame_id = 0; ingame_Char_Info[1].ingame_id = 1; ingame_Char_Info[2].ingame_id = 2; ingame_Char_Info[3].ingame_id = 3; ingame_Char_Info[0].posx = 0.0f; ingame_Char_Info[0].posz = 0.0f; ingame_Char_Info[0].is_alive = true; ingame_Char_Info[0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[1].posx = 28.0f; ingame_Char_Info[1].posz = 0.0f; ingame_Char_Info[1].is_alive = true; ingame_Char_Info[1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[2].posx = 0.0f; ingame_Char_Info[2].posz = 28.0f; ingame_Char_Info[2].is_alive = true; ingame_Char_Info[2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[3].posx = 28.0f; ingame_Char_Info[3].posz = 28.0f; ingame_Char_Info[3].is_alive = true; ingame_Char_Info[3].rotY = 180.0f; } ~InGameCalculator() {} void InitClass() { is_start = false; howmany = 2; boss_timestamp = 0; map.size = SIZEOF_TB_MAP; map.type = CASE_MAP; deathcount = 0; gameover = false; explode_List.clear(); ready_player[0] = false; ready_player[1] = false; ready_player[2] = false; ready_player[3] = false; id[0] = true; id[1] = true; id[2] = true; id[3] = true; start_time = GetTickCount(); time = 180.0f; ingame_boss_Info.size = SIZEOF_TB_BossPos; ingame_boss_Info.type = CASE_BOSS; ingame_boss_Info.posx = 14.0f; ingame_boss_Info.posz = 14.0f; ingame_boss_Info.rotY = 0.0f; ingame_boss_Info.is_alive = true; ingame_boss_Info.targetid = 1; ingame_boss_Info.anistate = 0; for (int i = 0; i < 4; ++i) { ingame_Char_Info[i].size = SIZEOF_TB_CharPos; ingame_Char_Info[i].type = CASE_POS; idList[i] = -1; } for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { fireMap[i][j] = 0; } } ingame_Char_Info[0].ingame_id = 0; ingame_Char_Info[1].ingame_id = 1; ingame_Char_Info[2].ingame_id = 2; ingame_Char_Info[3].ingame_id = 3; ingame_Char_Info[0].posx = 0.0f; ingame_Char_Info[0].posz = 0.0f; ingame_Char_Info[0].is_alive = true; ingame_Char_Info[0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[1].posx = 28.0f; ingame_Char_Info[1].posz = 0.0f; ingame_Char_Info[1].is_alive = true; ingame_Char_Info[1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[2].posx = 0.0f; ingame_Char_Info[2].posz = 28.0f; ingame_Char_Info[2].is_alive = true; ingame_Char_Info[2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[3].posx = 28.0f; ingame_Char_Info[3].posz = 28.0f; ingame_Char_Info[3].is_alive = true; ingame_Char_Info[3].rotY = 180.0f; } void PlayerDead(unsigned char idd) { if (id[idd]) { id[idd] = false; deathcount++; } } void GameStart() { is_start = true; } void ChangeID(int place, unsigned char id_p) { idList[place] = id_p; } void Start_AndSetTime() { } void PlayerBlank(int id_p) { id[id_p] = false; } void SetGameOver() { gameover = true; } bool IsGameOver() { return gameover; } float GetTime() { return time; } void SetTime(DWORD a) { float temp = ((float)a) / 1000.0f; time = time - temp; } bool OneSec() { return ((int)(time * 10) % 10)<1; } unsigned char GetWinnerID() { for (unsigned char i = 0; i < 4; ++i) { if (id[i]) return i; } return 4; //DRAW를 뜻한다. } void Boss_Target_Change(int id) { cout <<"Distance"<< abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posx - ingame_boss_Info.posx) << endl; if(abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posx - ingame_boss_Info.posx)>abs(ingame_Char_Info[id-1].posx - ingame_boss_Info.posx) && abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posz - ingame_boss_Info.posz)>abs(ingame_Char_Info[id - 1].posz - ingame_boss_Info.posz)) ingame_boss_Info.targetid = id; } void ChaseAI() { if(ingame_boss_Info.posx<ingame_Char_Info[ingame_boss_Info.targetid-1].posx) ingame_boss_Info.posx = ingame_boss_Info.posx + abs(boss_speed*sin(ingame_boss_Info.rotY)); else ingame_boss_Info.posx = ingame_boss_Info.posx - abs(boss_speed*sin(ingame_boss_Info.rotY)); if (ingame_boss_Info.posz<ingame_Char_Info[ingame_boss_Info.targetid - 1].posz) ingame_boss_Info.posz = ingame_boss_Info.posz + abs(boss_speed*cos(ingame_boss_Info.rotY)); else ingame_boss_Info.posz = ingame_boss_Info.posz - abs(boss_speed*cos(ingame_boss_Info.rotY)); } int Boss_Attack_Search() { cout << "Distance" << abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posx - ingame_boss_Info.posx) <<","<< abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posz - ingame_boss_Info.posz) << endl; if (abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posx - ingame_boss_Info.posx) < 4.0f&&abs(ingame_Char_Info[ingame_boss_Info.targetid - 1].posz - ingame_boss_Info.posz) < 4.0f) { cout << "Attack!!!" << endl; return 1; } else return 0; } int Boss_AI_Search() { //보스 AI_탐색 //시선 float distance_Char[4] = { 500000,500000,500000,500000 }; int ret_val=0; float rotation_angle = 0; for (int i = 0; i < howmany; ++i) { float angle_sight = cos(45.0f * 3.1416 / 180); float innerx = (ingame_Char_Info[i].posx - ingame_boss_Info.posx)* (20 * cos((ingame_boss_Info.rotY ))); float innerz = (ingame_Char_Info[i].posz - ingame_boss_Info.posz) *(20 * sin((ingame_boss_Info.rotY))); //* 3.1416 / 180 float inner_pro = abs(innerx) + abs(innerz); float innerx2 = (20 * cos(ingame_boss_Info.rotY))*(20 * cos(ingame_boss_Info.rotY)); float innerz2 = (20 * sin(ingame_boss_Info.rotY))*(20 * sin(ingame_boss_Info.rotY)); float innerx3 = (ingame_Char_Info[i].posx - ingame_boss_Info.posx)*(ingame_Char_Info[i].posx - ingame_boss_Info.posx); float innerz3 = (ingame_Char_Info[i].posz - ingame_boss_Info.posz)*(ingame_Char_Info[i].posz - ingame_boss_Info.posz); float par_getcos = sqrtf(abs(innerx2 + innerz2)) *sqrtf(abs(innerx3 + innerz3)); float target_angle = inner_pro / par_getcos; //cout << cos(0.5) << endl; if (angle_sight <= target_angle) { distance_Char[i] = abs(innerx3)+ abs(innerz3); if (distance_Char[ret_val] > distance_Char[i]) { ret_val = i; rotation_angle = acos(target_angle); cout << "Get" <<rotation_angle << endl; } } else { //cout << "No Get" << endl; } } if (distance_Char[ret_val] >= 500000) { //cout << "nothing better than you" << endl; return 0; } else { //ingame_boss_Info.rotY = rotation_angle; cout << "find you and rotate " << ingame_boss_Info.rotY << endl; return ret_val + 1; } } void CalculateMap(int x, int z, unsigned char f,unsigned char id_player) { bool l_UpBlock = false; bool l_DownBlock = false; bool l_LeftBlock = false; bool l_RightBlock = false; unsigned char uf = f; unsigned char df = f; unsigned char lf = f; unsigned char rf = f; unsigned char tempMap[15][15]; memcpy(tempMap, map.mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; for (unsigned char b = 1; b <= f; ++b) { if (!l_DownBlock) { if (z - b < 0) { l_DownBlock = true; df = b - 1; } else { if (tempMap[z - b][x] == MAP_BOMB) { tempMap[z - b][x] = MAP_NOTHING; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); if (bomb_Map[make_pair(x, z - b)].firepower != 0) { CalculateMap(x, z- b, fireMap[z - b][x], bomb_Map[make_pair(x, z - b)].game_id); auto a = bomb_Map.find(pair<int, int>(x, z - b)); bomb_Map.erase(a); } memcpy(tempMap, map.mapInfo, sizeof(tempMap)); l_DownBlock = true; df = b; } else if (tempMap[z - b][x] == MAP_BOX) { cout << "Box!!!" << endl; int temp_rand = (rand() % 14); if (temp_rand < 4) tempMap[z - b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z - b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z - b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z - b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z - b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z - b][x] = MAP_THROWITEM; l_DownBlock = true; df = b - 1; } else if (tempMap[z - b][x] == MAP_ITEM || tempMap[z - b][x] == MAP_ITEM_F || tempMap[z - b][x] == MAP_ITEM_S || tempMap[z - b][x] == MAP_KICKITEM || tempMap[z - b][x] == MAP_THROWITEM) { tempMap[z - b][x] = MAP_NOTHING; } else if (tempMap[z - b][x] == MAP_BUSH || tempMap[z - b][x] == MAP_FIREBUSH) { } else if (tempMap[z - b][x] == MAP_ROCK) { l_DownBlock = true; df = b - 1; } } } if (!l_UpBlock) { if (z + b > 14) { l_UpBlock = true; uf = b - 1; } else { if (tempMap[z + b][x] == MAP_BOMB) { tempMap[z + b][x] = MAP_NOTHING; l_UpBlock = true; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); if (bomb_Map[make_pair(x, z + b)].firepower != 0) { CalculateMap(x, z + b, fireMap[z + b][x], bomb_Map[make_pair(x, z + b)].game_id); auto a = bomb_Map.find(pair<int, int>(x, z+b)); bomb_Map.erase(a); } //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); memcpy(tempMap, map.mapInfo, sizeof(tempMap)); uf = b; } else if (tempMap[z + b][x] == MAP_BOX) { cout << "Box!!!" << endl; int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z + b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z + b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z + b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z + b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z + b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z + b][x] = MAP_THROWITEM; l_UpBlock = true; uf = b - 1; } else if (tempMap[z + b][x] == MAP_ITEM || tempMap[z + b][x] == MAP_ITEM_F || tempMap[z + b][x] == MAP_ITEM_S || tempMap[z + b][x] == MAP_KICKITEM || tempMap[z + b][x] == MAP_THROWITEM) { tempMap[z + b][x] = MAP_NOTHING; } else if (tempMap[z + b][x] == MAP_ROCK) { l_UpBlock = true; uf = b - 1; } } } if (!l_LeftBlock) { if (x - b < 0) { l_LeftBlock = true; lf = b - 1; } else { if (tempMap[z][x - b] == MAP_BOMB) { tempMap[z][x - b] = MAP_NOTHING; l_LeftBlock = true; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); if (bomb_Map[make_pair(x-b, z)].firepower != 0) { CalculateMap(x-b, z, fireMap[z][x-b], bomb_Map[make_pair(x-b, z)].game_id); auto a = bomb_Map.find(pair<int,int>(x - b, z)); bomb_Map.erase(a); } memcpy(tempMap, map.mapInfo, sizeof(tempMap)); lf = b; } else if (tempMap[z][x - b] == MAP_BOX) { cout << "Box!!!" << endl; int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z][x - b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x - b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x - b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x - b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x - b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x - b] = MAP_THROWITEM; l_LeftBlock = true; lf = b - 1; } else if (tempMap[z][x - b] == MAP_ITEM || tempMap[z][x - b] == MAP_KICKITEM || tempMap[z][x - b] == MAP_THROWITEM || tempMap[z][x - b] == MAP_ITEM_F || tempMap[z][x - b] == MAP_ITEM_S) { tempMap[z][x - b] = MAP_NOTHING; } else if (tempMap[z][x - b] == MAP_ROCK) { l_LeftBlock = true; lf = b - 1; } } } if (!l_RightBlock) { if (x + b > 14) { l_RightBlock = true; rf = b - 1; } else { if (tempMap[z][x + b] == MAP_BOMB) { tempMap[z][x + b] = MAP_NOTHING; l_RightBlock = true; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); if (bomb_Map[make_pair(x + b, z)].firepower != 0) { CalculateMap(x + b, z, fireMap[z][x + b], bomb_Map[make_pair(x + b, z)].game_id); auto a = bomb_Map.find(pair<int, int>(x+b, z )); bomb_Map.erase(a); } memcpy(tempMap, map.mapInfo, sizeof(tempMap)); rf = b; } else if (tempMap[z][x + b] == MAP_BOX) { cout << "Box!!!" << endl; int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z][x + b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x + b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x + b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x + b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x + b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x + b] = MAP_THROWITEM; l_RightBlock = true; rf = b - 1; } else if (tempMap[z][x + b] == MAP_ITEM || tempMap[z][x + b] == MAP_KICKITEM || tempMap[z][x + b] == MAP_THROWITEM || tempMap[z][x + b] == MAP_ITEM_F || tempMap[z][x + b] == MAP_ITEM_S) { tempMap[z][x + b] = MAP_NOTHING; } else if (tempMap[z][x + b] == MAP_ROCK) { l_RightBlock = true; rf = b - 1; } } } } TB_BombExplodeRE bomb = { SIZEOF_TB_BombExplodeRE,CASE_BOMB_EX,uf,rf,df,lf,id_player,x,z }; explode_List.emplace_back(bomb); //explode_List fireMap[z][x] = 0; tempMap[z][x] = MAP_NOTHING; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); } }; template <class Iter, class Value> Iter myFind(Iter a, Iter b, Value val) { Iter p = a; while (a != b) { if (*a == val) return a; else ++a; } return b; } struct EXOVER { WSAOVERLAPPED m_over; char m_iobuf[MAX_BUFF_SIZE]; WSABUF m_wsabuf; bool is_recv; }; class Client { public: SOCKET m_s; bool m_isconnected; unsigned char is_guardian; int m_x; int m_y; int m_scene; // 0 - 로비, 1- 방, 2- 게임중 EXOVER m_rxover; int m_packet_size; // 지금 조립하고 있는 패킷의 크기 int m_prev_packet_size; // 지난번 recv에서 완성되지 않아서 저장해 놓은 패킷의 앞부분의 크기 char m_packet[MAX_PACKET_SIZE]; int id; int roomNum; char stringID[20]; int win_vs; int lose_vs; int tier; int exp; int exp_max; int success_coop; int fail_coop; bool playing_game; InGameCalculator* link; // set<int> view_list; // 삽입/삭제가 자유로워야 한다. + 시간복잡도 상 가장 효율적인것이 set이다. (list는 삽입/삭제가 빠르지만 검색 성능이 느리다.) // multiset 은 중복가능 이기때문에 사용하지 않아야한다. unordered_set<int> m_view_list; // 정렬이 딱히 필요하지 않기 때문에 비정렬셋으로 성능 향상. mutex m_mVl; // 뷰리스트를 보호하기위해 Client() { m_isconnected = false; m_x = 4; m_y = 4; playing_game = false; ZeroMemory(&m_rxover.m_over, sizeof(WSAOVERLAPPED)); m_rxover.m_wsabuf.buf = m_rxover.m_iobuf; m_rxover.m_wsabuf.len = sizeof(m_rxover.m_wsabuf.buf); m_rxover.is_recv = true; m_prev_packet_size = 0; } }; struct MatchingSt { unsigned char boss_type; unsigned char map_type; unsigned char difficulty; unsigned char prefer_man; int id[4]; }; class Matching { unsigned char boss_type; unsigned char map_type; unsigned char difficulty; InGameCalculator game_cal; public: mutex mtx; int id[4]; unsigned char prefer_man; Matching() { for (int i = 0; i < 4; ++i) id[i] = -1; prefer_man = 0; boss_type = 0; map_type = 0; difficulty = 0; } Matching(unsigned char boss_t, unsigned char map_t, unsigned char diff_t, unsigned char how_many) { for (int i = 0; i < 4; ++i) id[i] = -1; prefer_man = how_many; boss_type = boss_t; map_type = map_t; difficulty = diff_t; } Matching(int id_t,unsigned char boss_t, unsigned char map_t, unsigned char diff_t, unsigned char how_many) { for (int i = 0; i < 4; ++i) id[i] = -1; id[0] = id_t; prefer_man = how_many; boss_type = boss_t; map_type = map_t; difficulty = diff_t; } ~Matching() {} bool IsAbleToJoin(int id_m) { for (int i = 0; i <= prefer_man; ++i) { mtx.lock(); if (id[i] < 0) { id[i] = id_m; mtx.unlock(); return true; } mtx.unlock(); } return false; } bool JoinMatch() { for (int i = 0; i <= prefer_man; ++i) { if (id[i] < 0) { return false; } } return true; } };<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; static class THEME_NUMBER { public const int FOREST = 1; public const int SNOWLAND = 2; //=================================== public const int MAX_THEME_NUMBER = 2; } public class Mode_Adventure_Stage_Select_Scene_Manager : MonoBehaviour { static Mode_Adventure_Stage_Select_Scene_Manager m_Instance; public GameObject m_Prev_Button; public GameObject m_Next_Button; public GameObject[] m_Theme_Buttons_Parents; public Button[] m_Theme_Forest_Buttons; public Button[] m_Theme_SnowLand_Buttons; [HideInInspector] public List<Button> m_Stage_Button_List; int m_Curr_Theme_Number; void Awake() { m_Instance = this; m_Stage_Button_List = new List<Button>(); Add_Buttons_in_List(ref m_Theme_Forest_Buttons); // 숲테마 추가 Add_Buttons_in_List(ref m_Theme_SnowLand_Buttons); // 설원테마 추가 // 이전에 선택한 스테이지를 보여주도록. switch (PlayerPrefs.GetInt("Mode_Adventure_Current_Stage_ID")) { case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7: case 8: case 9: m_Curr_Theme_Number = THEME_NUMBER.FOREST; break; case 10: case 11: case 12: case 13: case 14: case 15: case 16: case 17: case 18: case 19: m_Curr_Theme_Number = THEME_NUMBER.SNOWLAND; break; } Set_Stage_Buttons_with_Theme_Num(m_Curr_Theme_Number); } public static Mode_Adventure_Stage_Select_Scene_Manager GetInstance() { return m_Instance; } void Add_Buttons_in_List(ref Button[] buttons) { for (int i = 0; i < buttons.Length; ++i) { m_Stage_Button_List.Add(buttons[i]); } } void Set_Stage_Buttons_with_Theme_Num(int theme_num) // 선택한 테마의 버튼들 활성화 { for (int i = 0; i < m_Theme_Buttons_Parents.Length; ++i) // 다 끄고 m_Theme_Buttons_Parents[i].SetActive(false); m_Theme_Buttons_Parents[theme_num - 1].SetActive(true); // 현재 테마만 켠다. m_Prev_Button.SetActive(true); // 이전 테마 버튼 활성화 m_Next_Button.SetActive(true); // 다음 테마 버튼 활성화 if (0 == m_Curr_Theme_Number - 1) // 맨 처음 테마라면 "이전 버튼" 비활성화 { m_Prev_Button.SetActive(false); } if (THEME_NUMBER.MAX_THEME_NUMBER == m_Curr_Theme_Number) // 맨 마지막 테마라면 "다음 버튼" 비활성화 { m_Next_Button.SetActive(false); } } public void Set_Prev_Theme() { if (0 <= m_Curr_Theme_Number-1) { --m_Curr_Theme_Number; Set_Stage_Buttons_with_Theme_Num(m_Curr_Theme_Number); } } public void Set_Next_Theme() { if (THEME_NUMBER.MAX_THEME_NUMBER > m_Curr_Theme_Number) { ++m_Curr_Theme_Number; Set_Stage_Buttons_with_Theme_Num(m_Curr_Theme_Number); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class NetTeam1 : MonoBehaviour { public Material[] team_material; //public GameObject[] team_turtle; Renderer rend; // Use this for initialization void Start() { rend = GetComponent<Renderer>(); rend.sharedMaterial = team_material[VariableManager.instance.roominfo[VariableManager.instance.m_roomid - 1].team1]; //Debug.Log("My Team : "+ (int)VariableManager.instance.roominfo[VariableManager.instance.m_roomid - 1].team1); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Bomb_Sound : Sound_Effect { public AudioClip m_AudioClips; public void Play_ExplodeSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fire_Effect : MonoBehaviour { Collider m_Fire_Collider; //화염 지속시간- 다만 이펙트 이기 때문에 파티클은 사라지지 않을 수 있으므로 값을 조종하려면 파티클 inspector에서 조정 -R public float bombCountDown = 1.0f; void OnTriggerEnter(Collider other) { if (gameObject.activeInHierarchy) { if (other.gameObject.CompareTag("Player")) { Debug.Log("TTaGawa"); if (Turtle_Move.instance.alive != 0) { Turtle_Move.instance.alive = 0; NetTest.instance.SetmoveTrue(); } } } } // Update is called once per frame void Update () { if (bombCountDown >= 0.0f) { bombCountDown -= Time.deltaTime; } else { Destroy(gameObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; //게임씬에서의 사운드 조정 함수 public class MusicManager : MonoBehaviour { //인스턴스로 사용 public static MusicManager manage_ESound; //아이템 획득, 폭발사운드, 폭탄설치사운드 public AudioClip itemGetSound; public AudioClip explodeSound; public AudioClip bombSetSound; public AudioClip m_Goblin_Idle_Sound; public AudioClip m_Goblin_Attack_Sound; public AudioClip m_Goblin_Dead_Sound; public AudioClip m_Boss_Goblin_Throw_Sound; public AudioClip m_Boss_Goblin_Fall_Sound; public AudioClip m_Boss_Goblin_Dead_Sound; public AudioClip m_Boss_Goblin_Hurt_Sound; public AudioClip m_Boss_Goblin_Wall_Crush_Sound; //게임 씬에서의 bgm 오디오소스 public AudioSource bgmSource; //게임 씬에서의 효과음 오디오소스 AudioSource source; //시간 측정 변수 float deltatime; bool gameover = false; bool is_SE_Mute = false; bool is_Vib_Mute = false; void Awake() { manage_ESound = this; source = GetComponent<AudioSource>(); deltatime = 0.0f; if (PlayerPrefs.GetInt("System_Option_BGM_ON") == 0) bgmSource.Stop(); if (PlayerPrefs.GetInt("System_Option_SE_ON") == 0) is_SE_Mute = true; if (PlayerPrefs.GetInt("System_Option_Vib_ON") == 0) is_Vib_Mute = true; } void Update () { //게임오버 시 게임 씬 브금 서서히 감소 if (gameover) { deltatime = deltatime + (Time.deltaTime); bgmSource.volume = 1.0f - deltatime / 10; source = FindObjectOfType<AudioSource>(); source.volume = 1.0f - deltatime / 10; } } //폭탄 폭발 사운드 public void soundE() { if (!is_SE_Mute) source.PlayOneShot(explodeSound, 1.0f); if (!is_Vib_Mute) { #if UNITY_ANDROID Handheld.Vibrate(); // 1초간 진동 #endif } } public void soundE2() { if (!is_SE_Mute) bgmSource.PlayOneShot(explodeSound, 1.0f); if (!is_Vib_Mute) { #if UNITY_ANDROID Handheld.Vibrate(); // 1초간 진동 #endif } } public void TryMute() { gameover = true; } //아이템 획득 사운드 public void ItemGetSound() { if (!is_SE_Mute) source.PlayOneShot(itemGetSound,1.0f); //AudioSource.PlayClipAtPoint(itemGetSound, transform.position, 1.0f); } public void ItemGetSound2() { bgmSource.PlayOneShot(itemGetSound, 1.0f); //AudioSource.PlayClipAtPoint(itemGetSound, transform.position, 1.0f); } //폭탄 설치 사운드 public void BombSetSound() { if (!is_SE_Mute) source.PlayOneShot(bombSetSound); } public void BombSetSound2() { bgmSource.PlayOneShot(bombSetSound); } // 고블린 기본 public void Goblin_Idle_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Goblin_Idle_Sound, 0.6f); } // 고블린 공격 public void Goblin_Attack_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Goblin_Attack_Sound); } // 고블린 죽음 public void Goblin_Dead_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Goblin_Dead_Sound, 0.6f); } // 보스 고블린 폭탄 투척 public void Boss_Goblin_Throw_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Boss_Goblin_Throw_Sound, 0.7f); } // 보스 고블린 벽 충돌 public void Boss_Goblin_Wall_Crush_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Boss_Goblin_Wall_Crush_Sound, 0.5f); } // 보스 고블린 추락 public void Boss_Goblin_Fall_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Boss_Goblin_Fall_Sound, 0.5f); } // 보스 고블린 피격 public void Boss_Goblin_Hurt_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Boss_Goblin_Hurt_Sound); } // 보스 고블린 죽음 public void Boss_Goblin_Dead_Sound() { if (!is_SE_Mute) source.PlayOneShot(m_Boss_Goblin_Dead_Sound); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class IconTester : MonoBehaviour { public RawImage[] icon; int a = 5; float color_a = 0.5f; // Use this for initialization void Start () { } // Update is called once per frame void Update () { if (!Turtle_Move.instance.can_kick) { icon[0].gameObject.SetActive(true); } else { icon[0].gameObject.SetActive(false); } if (!Turtle_Move.instance.can_throw) { icon[1].gameObject.SetActive(true); } else icon[1].gameObject.SetActive(false); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Airdrop_Item : MonoBehaviour { float m_Move_Speed = 0.3f; float m_Rotate_Speed = 50.0f; bool m_Rising = false; float m_Rising_Speed = 0.5f; void Update() { if (!StageManager.GetInstance().Get_is_Pause()) { Rising(); floating(); } } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Flame")) Destroy(gameObject); } void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Land")) { gameObject.GetComponent<Rigidbody>().useGravity = false; gameObject.GetComponent<BoxCollider>().isTrigger = true; m_Rising = true; } } void Rising() { if (m_Rising) { transform.Translate(new Vector3(0.0f, m_Rising_Speed * Time.deltaTime, 0.0f)); if (transform.position.y > 1.0f) { transform.Translate(new Vector3(0.0f, -m_Rising_Speed * Time.deltaTime, 0.0f)); m_Rising = false; } } } void floating() { if (this.transform.position.y > 1.0f || this.transform.position.y < 0.6f) m_Move_Speed *= -1; this.transform.Translate(new Vector3(0.0f, m_Move_Speed * Time.deltaTime, 0.0f)); transform.Rotate(Vector3.up * m_Rotate_Speed * Time.deltaTime); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; // #define 보스 스탯 static class Boss_JetGoblin_Status { public const float JetGoblin__Base__Health = 10.0f; public const float JetGoblin__Base__Move_Speed = 5.0f; public const float JetGoblin__SuddenDeath__BombDrop_Cooltime = 1.5f; } public class Jet_Goblin : Bomb_Setter { // ===================================== // =============변수 선언부============= // ===================================== // 현재 진행중인 "행동" IEnumerator m_Current_Behavior; // "행동들" IEnumerator m_Behavior_Move; IEnumerator m_Behavior_Break; IEnumerator m_Behavior_WallCrash; IEnumerator m_Behavior_Landing; IEnumerator m_Intro_Moving; public GameObject m_Bomb; // 고블린이 사용할 폭탄 Rigidbody m_Rigidbody; Animator m_Boss_JetGoblin_Animator; // 애니메이터 float m_Health = Boss_JetGoblin_Status.JetGoblin__Base__Health; // 체력 float m_MaxHealth = Boss_JetGoblin_Status.JetGoblin__Base__Health; // 최대 체력 float m_Move_Speed = Boss_JetGoblin_Status.JetGoblin__Base__Move_Speed; // 이동속도 float m_Total_Moving_Cooltime; // 이동 쿨타임 float m_Current_Moving_Cooltime; // 이동 쿨타임 "체크" float m_Total_Bomb_Drop_Cooltime; // 폭탄 드랍 쿨타임 float m_Current_Bomb_Drop_Cooltime; // 폭탄 드랍 쿨타임 "체크" SkinnedMeshRenderer[] m_BossRenderer; MeshRenderer m_JetRenderer; Player m_Target; GameObject m_Temp_Bomb; int m_MCL_Index = 0; // MCL 인덱스 // ===================================== // 최초 소환 시 수행하는 메소드 void Start() { m_Rigidbody = GetComponent<Rigidbody>(); m_Boss_JetGoblin_Animator = GetComponent<Animator>(); m_Boss_JetGoblin_Animator.SetBool("Idle", true); // 몬스터의 행동 코루틴들을 설정 m_Behavior_Move = Behavior_Move(); m_Target = GameObject.FindGameObjectWithTag("Player").GetComponent<Player>(); m_Current_Behavior = Behavior_Move(); Mode_SuddenDeath(); StartCoroutine(Wait_For_Intro()); } IEnumerator Wait_For_Intro() { while (true) { StopAllCoroutines(); StartCoroutine(Do_Behavior()); yield return null; } } // ================================ // 이하는 "행동" 관련 메소드들이다. // ================================ // 모든 행동의 베이스가 되는 코루틴 IEnumerator Do_Behavior() { while (true) { if (!StageManager.GetInstance().Get_is_Pause() && m_Current_Behavior != null && m_Current_Behavior.MoveNext()) { yield return m_Current_Behavior.Current; } else { yield return null; } } } // 이동 IEnumerator Behavior_Move() { while (true) { Move(); // 이동 Drop_Bomb(); // 폭탄 투하 yield return null; } } // =============================== // 이하는 "모드" 관련 메소드들이다. // =============================== // 서든데스 모드 void Mode_SuddenDeath() { m_Health = 1.0f; m_MaxHealth = m_Health; m_Total_Bomb_Drop_Cooltime = Boss_JetGoblin_Status.JetGoblin__SuddenDeath__BombDrop_Cooltime; m_Current_Bomb_Drop_Cooltime = 0.0f; } // =============================== // ============================================= // 이하는 "행동 및 판정에 도움"을 줄 메소드들이다. // ============================================= // 몬스터 자신의 MCL 인덱스를 받아오는 함수 void Find_My_Coord() { if (StageManager.GetInstance().m_is_init_MCL) { m_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); } } // 자신의 MCL인덱스에 따른 올바른 위치로 이동 void Set_Right_Position() { if (StageManager.GetInstance().m_is_init_MCL) { m_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); if (m_MCL_Index != -1) { Vector3 Loc; Loc.x = StageManager.GetInstance().m_Map_Coordinate_List[m_MCL_Index].x; Loc.y = transform.position.y; Loc.z = StageManager.GetInstance().m_Map_Coordinate_List[m_MCL_Index].z; transform.position = Loc; } } } // 서든데스 모드에서 울타리 충돌체에 닿으면 // 새로운 위치/방향을 Set한다. void Set_New_Position_SuddenDeath() { // 위치 Vector3 newPosition; newPosition.x = Random.Range(0, 28); newPosition.x -= newPosition.x % 2; newPosition.y = transform.position.y; newPosition.z = Random.Range(50, 78); newPosition.z -= newPosition.z % 2; transform.position = newPosition; // 방향 transform.LookAt(m_Target.transform); float AngleY = 0.0f; if (transform.localEulerAngles.y >= 315.0f && transform.localEulerAngles.y < 45.0f) { AngleY = 0.0f; newPosition.z = 50.0f; } else if (transform.localEulerAngles.y >= 45.0f && transform.localEulerAngles.y < 135.0f) { AngleY = 90.0f; newPosition.x = 0.0f; } else if (transform.localEulerAngles.y >= 135.0f && transform.localEulerAngles.y < 225.0f) { AngleY = 180.0f; newPosition.z = 78.0f; } else if (transform.localEulerAngles.y >= 225.0f && transform.localEulerAngles.y < 315.0f) { AngleY = 270.0f; newPosition.x = 28.0f; } transform.position = newPosition; transform.localEulerAngles = new Vector3(0.0f, AngleY, 0.0f); } void Find_New_Direction() { int rand = Random.Range(0, 2); switch (rand) { case 0: transform.Rotate(transform.up, 90.0f); break; case 1: transform.Rotate(transform.up, 180.0f); break; case 2: transform.Rotate(transform.up, 270.0f); break; } } // 폭탄 투하 void Drop_Bomb() { if (m_Current_Bomb_Drop_Cooltime < m_Total_Bomb_Drop_Cooltime) m_Current_Bomb_Drop_Cooltime += Time.deltaTime; else { GetComponentInChildren<Jet_Goblin_Sound>().Play_Bomb_Throw_Sound(); Bomb_Set(CALL_BOMB_STATE.DROP); m_Current_Bomb_Drop_Cooltime = 0.0f; // 쿨타임 리셋 } } // 이동 void Move() { m_Boss_JetGoblin_Animator.SetBool("Move", true); m_Boss_JetGoblin_Animator.SetBool("Idle", false); m_Rigidbody.MovePosition(m_Rigidbody.position + transform.forward * m_Move_Speed * Time.deltaTime); } void OnTriggerEnter(Collider other) { // 울타리 밖으로 나가지 않도록 if (other.gameObject.CompareTag("Wall")) { Set_New_Position_SuddenDeath(); m_Current_Bomb_Drop_Cooltime = 0.0f; } } void OnTriggerExit(Collider other) { // 폭탄 투하를 매끄럽게 하기 위해 if (other.gameObject.CompareTag("Bomb")) other.isTrigger = false; } // ============================================= public void Set_Bomb_info(int bombcount, int firecount, float speed_value) { m_Max_Bomb_Count = bombcount; m_Curr_Bomb_Count = bombcount; m_Fire_Count = firecount; m_Move_Speed = speed_value; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.Threading; using UnityEngine.UI; public class NetUser2 : MonoBehaviour { public static NetUser2 instance; public Text m_TurtleTXT; public TextMesh m_TM; public GameObject p; float m_GliderfloatSpeed = 1.0f; bool textmesh_On = false; public GameObject parts; byte color = 0; byte id = 254; bool dead_ani = false; bool throw_ani = false; bool walk_ani = false; bool push_ani = false; bool kick_ani = false; bool get_glider = false; bool glider_on = false; public GameObject glider; public Material[] icon_material; Animator m_animator; public GameObject m_plane; public Renderer m_Rplane; void Awake() { instance = this; transform.position = new Vector3(28.0f, transform.position.y, 0.0f); // Debug.Log("Set Position2"); } // Use this for initialization void Start() { transform.position = new Vector3(28.0f, transform.position.y, 0.0f); dead_ani = false; //p = GetComponent<GameObject>(); //Invoke("IDCheck", 2.0f); m_animator = GetComponent<Animator>(); //Debug.Log("Start Position2"); throw_ani = false; walk_ani = false; push_ani = false; kick_ani = false; get_glider = false; glider_on = false; } private void OnTriggerEnter(Collider other) { if (other.CompareTag("Bush")) { if (!get_glider) parts.SetActive(false); } } private void OnTriggerStay(Collider other) { if (other.CompareTag("Bush")) { if (!get_glider) parts.SetActive(false); } } private void OnTriggerExit(Collider other) { if (other.CompareTag("Bush")) { parts.SetActive(true); } if (other.CompareTag("Bomb")) { other.isTrigger = false; } } public void SetKickMotion() { kick_ani = true; } public void SetMoveMotion() { walk_ani = true; } public void SetDeadMotion() { dead_ani = true; } public void SetThrowMotion() { throw_ani = true; } public void SetPushMotion() { push_ani = true; } public void GetGlider() { get_glider = true; } void Push_Ani_False() { m_animator.SetBool("TurtleMan_isPush", false); } void Throw_Ani_False() { m_animator.SetBool("TurtleMan_isThrow", false); } void Walk_Ani_False() { m_animator.SetBool("TurtleMan_isWalk", false); m_animator.SetBool("TurtleMan_GliderMove", false); } void Kick_Ani_False() { m_animator.SetBool("TurtleMan_isKick", false); } void Glider_False() { m_animator.SetBool("TurtleMan_GetGlider", false); } void SetFalse() { gameObject.SetActive(false); } void IDCheck() { if (p != null) { if (Turtle_Move.instance.GetId() == 1 || Turtle_Move.instance.GetId() > 3) { } //else //StartCoroutine("NetworkCheck"); } } public void SetText(byte itemtype) { textmesh_On = true; switch (itemtype) { case 11: color = 0; break; case 12: color = 2; break; case 13: color = 1; break; case 14: color = 3; break; case 15: color = 4; break; } color = itemtype; } public void SetTextOff() { m_TM.gameObject.SetActive(false); } public void SetPos(float x, float y, float z) { float tempx = x - transform.position.x; float tempz = z - transform.position.z; float tempy = y - transform.localEulerAngles.y; //transform.position = new Vector3(transform.position.x+(tempx/4), transform.position.y, transform.position.z+(tempz/4)); transform.position = Vector3.MoveTowards(transform.position, new Vector3(x, transform.position.y, z), 0.5f); transform.eulerAngles = new Vector3(0, y, 0); //Thread.Sleep(125); //new WaitForSeconds(0.125f); //yield WaitForSeconds(0.125f); } public void SetIconOff() { m_plane.gameObject.SetActive(false); } // Update is called once per frame void Update() { if (NetTest.instance.GetNetAlive(1) == 2) { glider_on = true; m_animator.SetBool("TurtleMan_GetGlider", true); } else if (NetTest.instance.GetNetAlive(1) == 1) { if (glider_on) { m_animator.SetBool("TurtleMan_GetGlider", false); glider_on = false; } } if (kick_ani) { m_animator.SetBool("TurtleMan_isKick", true); Invoke("Kick_Ani_False", 1.0f); kick_ani = false; } if (push_ani) { m_animator.SetBool("TurtleMan_isPush", true); Invoke("Push_Ani_False", 1.0f); push_ani = false; } if (walk_ani) { if (glider_on) { m_animator.SetBool("TurtleMan_GliderMove", true); } else { m_animator.SetBool("TurtleMan_isWalk", true); } Invoke("Walk_Ani_False", 1.0f); walk_ani = false; } //m_TM.transform.position = new Vector3(gameObject.transform.position.x, m_TM.transform.position.y, gameObject.transform.position.z); if (dead_ani) { m_TM.gameObject.SetActive(true); m_TM.text = "2P - Dead!!!"; m_animator.SetBool("TurtleMan_isDead", true); Invoke("SetTextOff", 2.0f); Invoke("SetFalse", 5.0f); dead_ani = false; } if (get_glider) { m_animator.SetBool("TurtleMan_GetGlider", true); gameObject.transform.position = new Vector3(gameObject.transform.position.x, 2.0f, gameObject.transform.position.z); get_glider = false; glider_on = true; } if (glider_on) { m_animator.SetBool("TurtleMan_GetGlider", true); glider.SetActive(true); if (gameObject.transform.position.y >= 3.0f) m_GliderfloatSpeed = -0.01f; else if (gameObject.transform.position.y <= 2.0f) m_GliderfloatSpeed = 0.01f; gameObject.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + (m_GliderfloatSpeed), gameObject.transform.position.z); } else { glider.SetActive(false); gameObject.transform.position = new Vector3(gameObject.transform.position.x, -0.5f, gameObject.transform.position.z); } if (throw_ani) { m_animator.SetBool("TurtleMan_isThrow", true); Invoke("Throw_Ani_False", 1.0f); throw_ani = false; } if (VariableManager.instance.people_inRoom[1] == 0) p.SetActive(false); else if (VariableManager.instance.pos_inRoom - 1 == 1) { p.SetActive(false); } else { p.SetActive(true); } SetPos(NetTest.instance.GetNetPosx(1), NetTest.instance.GetNetRoty(1), NetTest.instance.GetNetPosz(1)); //m_TurtleTXT.text = "X:" + transform.position.x+"\nZ:"+ transform.position.z; //m_TM.text = "X:" + transform.position.x; if (textmesh_On) { m_plane.gameObject.SetActive(true); switch (color) { case 0: m_Rplane.sharedMaterial = icon_material[0]; //m_TM.color = new Color(0, 0, 1); //m_TM.text = "Bomb Up~"; break; case 1: m_Rplane.sharedMaterial = icon_material[1]; //m_TM.color = new Color(1, 0, 0); //m_TM.text = "Fire Up~"; break; case 2: m_Rplane.sharedMaterial = icon_material[2]; //m_TM.color = new Color(1, 1, 0); //m_TM.text = "Speed Up~"; break; case 3: m_Rplane.sharedMaterial = icon_material[3]; break; case 4: m_Rplane.sharedMaterial = icon_material[4]; break; case 5: get_glider = true; m_Rplane.sharedMaterial = icon_material[5]; color = 100; break; case 6: m_Rplane.sharedMaterial = icon_material[6]; break; default: break; } Invoke("SetIconOff", 2.0f); textmesh_On = false; } } IEnumerator NetworkCheck() { WaitForSeconds delay = new WaitForSeconds(0.05f); for (; ; ) { SetPos(NetTest.instance.GetNetPosx(1), NetTest.instance.GetNetRoty(1), NetTest.instance.GetNetPosz(1)); yield return delay; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class CoOpManager : MonoBehaviour { public static CoOpManager instance; public GameObject myturtle; public GameObject[] m_net_user; public GameObject gameover_Image; public GameObject winner_Image; bool m_isClicked = false; public Text time_Text; bool win_game=false; bool lose_game = false; float time; public Text m_GetItemText; public RawImage m_GetItemBackground; // 아이템 획득시 출력 이미지 public RawImage m_GetItemImage; // 아이템 획득시 출력 이미지 public Animator m_GetItem_Animator; // 아이템 획득 UI 애니메이터 public Texture m_Bomb_Icon; public Texture m_Fire_Icon; public Texture m_Speed_Icon; public Texture m_Kick_Icon; public Texture m_Throw_Icon; public Text[] m_idtext; public Text[] m_damagepercent_text; // Use this for initialization void Awake() { instance = this; } void Start () { //m_Attack_Collider = transform.Find("Attack_Range"); // 비활성화 win_game = false; lose_game = false; time = 0; winner_Image.SetActive(false); gameover_Image.SetActive(false); m_net_user[0].transform.position = new Vector3(0.0f, -0.35f, 0.0f); m_net_user[1].transform.position = new Vector3(28.0f, -0.35f, 0.0f); m_net_user[2].transform.position = new Vector3(0.0f, -0.35f, 28.0f); m_net_user[3].transform.position = new Vector3(28.0f, -0.35f, 28.0f); for (int i=0;i< VariableManager_Coop.instance.howmany;i++) { m_net_user[i].SetActive(true); } switch (VariableManager_Coop.instance.pos_id) { case 1: m_net_user[0].SetActive(false); break; case 2: m_net_user[1].SetActive(false); break; case 3: m_net_user[2].SetActive(false); break; case 4: m_net_user[3].SetActive(false); break; default: break; } } public void isClicked() { m_isClicked = true; } public void isClickedOff() { m_isClicked = false; } public bool Get_isClicked() { return m_isClicked; } public void GetItemUI_Activate(int Item_Num) { switch (Item_Num) { case 0: m_GetItemText.text = "Bomb Up !"; m_GetItemImage.texture = m_Bomb_Icon; break; case 1: m_GetItemText.text = "Fire Up !"; m_GetItemImage.texture = m_Fire_Icon; break; case 2: m_GetItemText.text = "Speed Up !"; m_GetItemImage.texture = m_Speed_Icon; break; case 3: m_GetItemText.text = "Kick Activated !"; m_GetItemImage.texture = m_Kick_Icon; break; case 4: m_GetItemText.text = "Throw Activated !"; m_GetItemImage.texture = m_Throw_Icon; break; case 5: m_GetItemText.text = "You've Got AirDrop !!"; m_GetItemImage.texture = m_Bomb_Icon; break; } //Stat_UI_Management(); // 스탯 갱신 m_GetItemBackground.gameObject.SetActive(true); m_GetItemText.gameObject.SetActive(true); m_GetItemImage.gameObject.SetActive(true); m_GetItem_Animator.SetBool("is_Got_Item", true); Invoke("GetItemUI_Deactivate", 1.4f); } void GetItemUI_Deactivate() { m_GetItem_Animator.SetBool("is_Got_Item", false); m_GetItemBackground.gameObject.SetActive(false); m_GetItemText.gameObject.SetActive(false); m_GetItemImage.gameObject.SetActive(false); } void SetAniFalse(int char_id,int ani_state) { switch (ani_state) { case 1: //걷는 애니 구현 m_net_user[char_id].GetComponent<Animator>().SetBool("TurtleMan_isWalk", false); break; case 2: //던지는 애니 구현 m_net_user[char_id].GetComponent<Animator>().SetBool("TurtleMan_isThrow", false); break; case 3: //차는 애니 구현 m_net_user[char_id].GetComponent<Animator>().SetBool("TurtleMan_isKick", false); break; case 4: //미는 애니 구현 m_net_user[char_id].GetComponent<Animator>().SetBool("TurtleMan_isPush", false); break; case 5: //죽는 애니 구현 m_net_user[char_id].GetComponent<Animator>().SetBool("TurtleMan_isDead", false); break; } } public void GameOver_Set(byte win, byte winner) { if (win == 1) { win_game = true; } else{ lose_game = true; } } public void ExitRoom() { SceneChange.instance.GoTo_Matching_Scene(); } // Update is called once per frame void Update () { //Set_Boss_HP_Bar(); //m_damagepercent_text[0].text = "HP: "+Boss_AI_Coop.instance.hp; if (win_game) { winner_Image.SetActive(true); } if (lose_game) { gameover_Image.SetActive(true); } m_idtext[0].text = VariableManager_Coop.instance.id_list[0]; m_idtext[1].text = VariableManager_Coop.instance.id_list[1]; m_idtext[2].text = VariableManager_Coop.instance.id_list[2]; m_idtext[3].text = VariableManager_Coop.instance.id_list[3]; //Debug.Log(boss.transform.rotation.y); time = VariableManager_Coop.instance.m_time; if (time <= 0) { time_Text.text = "00:00"; time = 0; } else if (time % 60 >= 10) time_Text.text = "0" + (int)time / 60 + ":" + (int)time % 60; else { time_Text.text = "0" + (int)time / 60 + ":0" + (int)time % 60; } // Debug.Log("rotationY"+boss_rotY); //boss.transform.rotation= new Quaternion(boss.transform.rotation.x,boss_rotY, boss.transform.rotation.z, boss.transform.rotation.w); for (int i=0;i< VariableManager_Coop.instance.howmany; i++) { if (m_net_user[i].activeInHierarchy) { m_net_user[i].transform.position =new Vector3(NetManager_Coop.instance.m_chardata[i].x, -0.35f, NetManager_Coop.instance.m_chardata[i].z); //m_net_user[i].transform.rotation = new Quaternion(m_net_user[i].transform.rotation.x, NetManager_Coop.instance.m_chardata[i].rotateY, m_net_user[i].transform.rotation.z, m_net_user[i].transform.rotation.w); m_net_user[i].transform.eulerAngles = new Vector3(0, NetManager_Coop.instance.m_chardata[i].rotateY,0); switch (NetManager_Coop.instance.m_chardata[i].ani_state) { case 1: //걷는 애니 구현 m_net_user[i].GetComponent<Animator>().SetBool("TurtleMan_isWalk", true); NetManager_Coop.instance.m_chardata[i].ani_state = 0; //SetAniFalse(i, 1); break; case 2: //던지는 애니 구현 m_net_user[i].GetComponent<Animator>().SetBool("TurtleMan_isThrow", true); NetManager_Coop.instance.m_chardata[i].ani_state = 0; //SetAniFalse(i, 2); break; case 3: //차는 애니 구현 m_net_user[i].GetComponent<Animator>().SetBool("TurtleMan_isKick", true); NetManager_Coop.instance.m_chardata[i].ani_state = 0; //SetAniFalse(i, 3); break; case 4: //미는 애니 구현 m_net_user[i].GetComponent<Animator>().SetBool("TurtleMan_isPush", true); NetManager_Coop.instance.m_chardata[i].ani_state = 0; // SetAniFalse(i, 4); break; case 5: //죽는 애니 구현 m_net_user[i].GetComponent<Animator>().SetBool("TurtleMan_isDead", true); NetManager_Coop.instance.m_chardata[i].ani_state = 0; //SetAniFalse(i, 5); break; default: break; } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class NORMAL_GOBLIN_SOUND_NUMBER { public const int IDLE = 0; public const int ATTACK = 1; public const int DEAD = 2; } public class Normal_Goblin_Sound : Sound_Effect { public AudioClip[] m_AudioClips; public void Play_IdleSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[NORMAL_GOBLIN_SOUND_NUMBER.IDLE]); } public void Play_AttackSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[NORMAL_GOBLIN_SOUND_NUMBER.ATTACK]); } public void Play_DeadSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[NORMAL_GOBLIN_SOUND_NUMBER.DEAD]); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Camera_Directing_Net : MonoBehaviour { // StageManager가 시작할 때 Instance로 생성. // 생성 직후 포지션값을 맵 중앙으로 옮겨주도록 하자. static Camera_Directing_Net m_Instance; public static Camera_Directing_Net GetInstance() { return m_Instance; } Animation m_Animations; Animation m_Intro_Fade_Animations; public Camera m_Player_Camera; float m_Skip_Button_Activate_Time = 5.0f; int m_Curr_Direction_Number; string m_Curr_Animation_Name; string m_Curr_Fade_Animation_Name; IEnumerator m_Dir_Over_Checker; IEnumerator m_Go_to_Target; Transform m_Target; float m_Going_to_Target_Speed = 30.0f; float m_Going_to_Target_Rotate_Angle = 60.0f; public bool ani_is_working; bool m_is_in_Target = false; bool m_is_Debug_Mode = false; IEnumerator m_Boss_Intro_1_Checker; GameObject m_Boss_Object; void Awake() { m_Instance = this; m_Animations = GetComponent<Animation>(); m_Dir_Over_Checker = Directing_Over_Check(); m_Go_to_Target = Go_To_Target(); m_Target = transform.GetChild(1); } public void Direction_Play(int direction_num) { Camera_Switching(CAMERA_NUMBER.DIRECTION); // 연출용 카메라로 전환 //Invoke("Skip_Button_Activate", m_Skip_Button_Activate_Time); m_Curr_Direction_Number = direction_num; switch (m_Curr_Direction_Number) { case DIRECTION_NUMBER.INTRO_NORMAL_1: ani_is_working = true; m_Curr_Animation_Name = m_Animations.GetClip("Stage_Intro_Normal_1").name; // 재생할 애니메이션 이름을 등록! // Debug.Log("Damn"); break; case DIRECTION_NUMBER.INTRO_BOSS_1: m_Curr_Animation_Name = m_Animations.GetClip("Stage_Intro_Boss_1").name; Notice_UI.GetInstance().Notice_Play(NOTICE_NUMBER.BOSS_INTRO_1_DANGER); m_Boss_Intro_1_Checker = Boss_Intro_1_Check(); StartCoroutine(m_Boss_Intro_1_Checker); break; case DIRECTION_NUMBER.DEBUG_MODE: m_is_Debug_Mode = true; break; } if (!m_is_Debug_Mode) { //Debug.Log("Damn1_debug_mode"); m_Animations.Play(m_Curr_Animation_Name); // 연출 시작! StartCoroutine(m_Dir_Over_Checker); // 연출 종료 검사 시작! } else { // Debug.Log("Damn2_else"); StageManager.GetInstance().Set_is_Intro_Over(true); Camera_Switching(CAMERA_NUMBER.PLAYER); } } void Skip_Button_Activate() { //m_Intro_Fade_Animations = UI.GetInstance().m_Intro_Fade.GetComponent<Animation>(); //m_Curr_Fade_Animation_Name = m_Intro_Fade_Animations.GetClip("Intro_Fade").name; //UI.GetInstance().m_Direction_Skip_Button.SetActive(true); } IEnumerator Directing_Over_Check() { while (true) { if (m_Animations[m_Curr_Animation_Name].normalizedTime >= 0.95f) { // 연출이 끝나면 Debug.Log("Damn_End"); Direction_Over_Process(); // 연출 종료 처리 수행. } yield return null; } } void Direction_Over_Process() { switch (m_Curr_Direction_Number) { case DIRECTION_NUMBER.INTRO_NORMAL_1: StopCoroutine(m_Dir_Over_Checker); m_Target.position = m_Player_Camera.transform.position; // 타겟을 플레이어 위치로 옮기고 m_Target.rotation = m_Player_Camera.transform.rotation; // 회전도 시킨다. StartCoroutine(m_Go_to_Target); // 타겟에게 이동. break; case DIRECTION_NUMBER.INTRO_BOSS_1: if (m_Curr_Animation_Name == "Stage_Intro_Boss_1") // 첫번째 연출이 끝나면 { m_Curr_Animation_Name = m_Animations.GetClip("Stage_Intro_Boss_1_2").name; m_Animations.Play(m_Curr_Animation_Name); m_Boss_Object.GetComponent<Big_Boss_Behavior>().SetAnimation(BOSS_ANIMATION_NUM.HURT); // 만세모션 } else if (m_Curr_Animation_Name == "Stage_Intro_Boss_1_2") // 두번째 연출이 끝나면 { m_Curr_Animation_Name = m_Animations.GetClip("Stage_Intro_Boss_1_3").name; m_Animations.Play(m_Curr_Animation_Name); m_Boss_Object.GetComponent<Big_Boss_Behavior>().SetAnimation(BOSS_ANIMATION_NUM.IDLE); // 기본모션 } else if (m_Curr_Animation_Name == "Stage_Intro_Boss_1_3") // 세번째 연출이 끝나면 { Start_FadeOut(); // 페이드 아웃 후 게임시작 } break; } } IEnumerator Boss_Intro_1_Check() { while (true) { if (m_Curr_Animation_Name == "Stage_Intro_Boss_1") { if (m_Animations[m_Curr_Animation_Name].normalizedTime >= 0.3f) // 연출이 어느정도 진행되면 { // 1. 보스몹 모션 수행 m_Boss_Object.GetComponent<Big_Boss_Behavior>().SetAnimation(BOSS_ANIMATION_NUM.SUMMON); StopCoroutine(m_Boss_Intro_1_Checker); } } yield return null; } } public void Set_Boss_Object(GameObject boss) { m_Boss_Object = boss; } public void Direction_Skip() { Start_FadeOut(); } IEnumerator Fade_Check() { while (true) { if (m_Curr_Fade_Animation_Name == "Intro_Fade") // 페이드 아웃 { if (m_Intro_Fade_Animations[m_Curr_Fade_Animation_Name].normalizedTime >= 0.95f) { Camera_Switching(CAMERA_NUMBER.PLAYER); m_Curr_Fade_Animation_Name = "Intro_Fade_In"; m_Intro_Fade_Animations.Play(m_Intro_Fade_Animations.GetClip(m_Curr_Fade_Animation_Name).name); } } else if (m_Curr_Fade_Animation_Name == "Intro_Fade_In") { if (m_Intro_Fade_Animations[m_Curr_Fade_Animation_Name].normalizedTime >= 0.95f) { StageManager.GetInstance().Set_is_Intro_Over(true); //UI.GetInstance().m_Intro_Fade.SetActive(false); StopAllCoroutines(); } } yield return null; } } void Start_FadeOut() { // UI.GetInstance().m_Intro_Fade.SetActive(true); m_Intro_Fade_Animations.Play(m_Intro_Fade_Animations.GetClip(m_Curr_Fade_Animation_Name).name); StartCoroutine(Fade_Check()); } // ============================================= IEnumerator Go_To_Target() { while (true) { Going_Target(); yield return null; } } void Going_Target() { transform.GetChild(0).position = Vector3.MoveTowards(transform.GetChild(0).position, m_Target.position, m_Going_to_Target_Speed * Time.deltaTime); transform.GetChild(0).rotation = Quaternion.RotateTowards(transform.GetChild(0).rotation, m_Target.rotation, m_Going_to_Target_Rotate_Angle * Time.deltaTime); if (transform.GetChild(0).position == m_Target.position) { Going_Target_End(); StopCoroutine(m_Go_to_Target); } } void Going_Target_End() { switch (m_Curr_Direction_Number) { case DIRECTION_NUMBER.INTRO_NORMAL_1: // UI.GetInstance().m_Intro_Fade.SetActive(false); //StageManager.GetInstance().Set_is_Intro_Over(true); ani_is_working = false; Camera_Switching(CAMERA_NUMBER.PLAYER); // 플레이어 카메라로 전환! break; } } public void Camera_Switching(int camera_num) // 카메라 전환 { switch (camera_num) { case CAMERA_NUMBER.PLAYER: m_Player_Camera.enabled = true; m_Player_Camera.GetComponent<AudioListener>().enabled = true; gameObject.GetComponentInChildren<Camera>().enabled = false; gameObject.GetComponentInChildren<AudioListener>().enabled = false; NetTest.instance.SendReadyCoopPacket(); break; case CAMERA_NUMBER.DIRECTION: m_Player_Camera.enabled = false; m_Player_Camera.GetComponent<AudioListener>().enabled = false; gameObject.GetComponentInChildren<Camera>().enabled = true; gameObject.GetComponentInChildren<AudioListener>().enabled = true; break; } } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class GameRoom : MonoBehaviour { public static GameRoom instance; int ready_num = 0; byte my_room_num = 0; public byte pos_inRoom = 0; byte pos_guard = 0; byte amIguard = 0;//0일경우는 유저, 1일 경우 방장 byte myteam = 0; bool pop_loading = false; public RawImage loadingimage; int mode = 0; int map_mode = 0; int map_num = 0; byte[] people_inRoom = new byte[4]; public GameObject popup; public GameObject kick_notice; //서버에서 차였을 때 public Text m_text; public GameObject[] turtles; public byte m_imready; public bool load_on; //public TextMesh[] turtle_text; byte m_ready; //0일 경우 ready x, 1일 경우 ready o public GameObject[] crown; public GameObject[] readyimage; public Text Map_Num_Text; public Text m_count_text; public Button[] SRButton; public RawImage mapImage_now; public Texture[] mapImage; bool mode_changed = false; byte roomtype = 0; byte[] team = new byte[4]; byte clicked_position; // Use this for initialization void Awake() { instance = this; //Application.LoadLevel(Application.loadedLevel); //DontDestroyOnLoad(this); } void Start() { Screen.SetResolution(1280, 720, true); SetRoomState(); m_imready = 0; pop_loading = false; load_on = false; } public void OutRoom() { my_room_num = 0; pos_inRoom = 0; pos_guard = 0; amIguard = 0; for (int i = 0; i < 4; ++i) people_inRoom[i] = 0; } public byte GetRoomID() { return my_room_num; } public void GetReadyState(byte pos, byte ready) { if (pos_inRoom == pos) { m_ready = ready; } else { return; } } public void StartGame() { NetTest.instance.SendStartPacket(); //SceneChange.instance.GoTo_Game_Scene(); } public void Ready() { if (amIguard == 0) NetTest.instance.SendReadyPacket_v2(); else { } } public void ExitRoom() { //나간다고 패킷 보냄 NetTest.instance.SendOUTPacket(); } public void Kick_By_Server() { kick_notice.SetActive(true); } public void Popup() { popup.transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); popup.SetActive(true); } public void PopupCancel() { popup.SetActive(false); } public void SetPos1() { clicked_position = 1; } public void SetPos2() { clicked_position = 2; } public void SetPos3() { clicked_position = 3; } public void SetPos4() { clicked_position = 4; } public void BanUser() { bool tempbool01 = people_inRoom[clicked_position - 1] != 0; bool tempbool02 = amIguard == 1; bool tempbool03 = clicked_position != pos_guard; if (tempbool01 && tempbool02 && tempbool03) { //벤 패킷 전송 NetTest.instance.SendBanPacket(clicked_position); } } public void Out_By_Server() { //Debug.Log("Disconnect"); SceneChange.instance.DisConnect(); } //방 상태 체크 함수 void SetRoomState() { my_room_num = VariableManager.instance.m_roomid; byte[] temparray = VariableManager.instance.people_inRoom; pos_inRoom = VariableManager.instance.pos_inRoom; pos_guard = VariableManager.instance.pos_guardian; for (int t = 0; t < 4; ++t) people_inRoom[t] = VariableManager.instance.people_inRoom[t]; //Buffer.BlockCopy(temparray, 0, people_inRoom, 0, 4); ////Debug.Log(people_inRoom); amIguard = VariableManager.instance.is_guardian; mode = VariableManager.instance.game_mode; map_mode = VariableManager.instance.map_type; map_num = VariableManager.instance.map_num; //for (int t = 0; t < 4; ++t) //{ // team[t] = VariableManager.instance.team_Turtle[t]; //} team[0] = VariableManager.instance.roominfo[my_room_num-1].team1; team[1] = VariableManager.instance.roominfo[my_room_num - 1].team2; team[2] = VariableManager.instance.roominfo[my_room_num - 1].team3; team[3] = VariableManager.instance.roominfo[my_room_num - 1].team4; if (pos_guard == pos_inRoom) { amIguard = 1; } } //팀변경 함수 public void TeamChange(int a) { VariableManager.instance.SetTeam((byte)a); NetTest.instance.SendTeamChangePacket(); } //맵 변경 우측 화살표 public void SetMap() { if (amIguard == 1) { int temp = (map_mode + 1) % 3; VariableManager.instance.SetMapMode(temp); NetTest.instance.SendRoomStateChangePacket(); } } public void SetMapMinus() { if (amIguard == 1) { if (mode <= 0) { VariableManager.instance.SetMapMode(2); NetTest.instance.SendRoomStateChangePacket(); } else { int temp = map_mode - 1; if (temp < 0) temp = 2; VariableManager.instance.SetMapMode(temp); NetTest.instance.SendRoomStateChangePacket(); } } } //모드 변경 함수 public void SetMode_2(byte m) { mode = m; } public void SetMap_2(byte m) { map_mode = m; } public void SetMapNum2(byte m) { map_num = m; } //모드 변경 우측 화살표 public void SetMode() { if (amIguard == 1) { int temp = (mode + 1) % 5; if (temp < 2) temp = 2; VariableManager.instance.SetGameMode(temp); NetTest.instance.SendRoomStateChangePacket(); mode_changed = true; } if (mode == 1) { } } //모드 변경 좌측 화살표 public void SetModeMinus() { if (amIguard == 1) { if (mode <= 2) { VariableManager.instance.SetGameMode(4); NetTest.instance.SendRoomStateChangePacket(); } else { int temp = (mode - 1); VariableManager.instance.SetGameMode(temp); NetTest.instance.SendRoomStateChangePacket(); } } } public void SetMapNum() { if (amIguard == 1) { int temp = (map_num + 1) % 4; VariableManager.instance.SetMapNum(temp); NetTest.instance.SendRoomStateChangePacket(); } } public void SetMapNumMinus() { if (amIguard == 1) { if (map_num <= 0) { VariableManager.instance.SetMapNum(3); NetTest.instance.SendRoomStateChangePacket(); } else { int temp = map_num - 1; if (temp < 0) temp = 3; VariableManager.instance.SetMapNum(temp); NetTest.instance.SendRoomStateChangePacket(); } } } //게임모드 변경 void CheckMode() { mapImage_now.texture = mapImage[map_mode]; m_count_text.text = mode + "인 플레이"; } // Update is called once per frame void Update() { ////Debug.Log(turtles.Length); ready_num = 0; int people = 0; if (load_on) { } if (pop_loading) { loadingimage.gameObject.SetActive(true); } else { loadingimage.gameObject.SetActive(false); } turtles[0].SetActive(true); for (int i = 1; i < 13; ++i) { turtles[i].SetActive(false); } if (SceneChange.instance.GetSceneState() == 6) { SetRoomState(); if (amIguard == 1) { SRButton[0].gameObject.SetActive(true); SRButton[1].gameObject.SetActive(false); } else { SRButton[1].gameObject.SetActive(true); SRButton[0].gameObject.SetActive(false); } CheckMode(); if (mode == 0) { m_text.text = VariableManager.instance.m_roomid + "번 방"; } else { m_text.text = VariableManager.instance.m_roomid + "번 방"; } if (m_ready == 1) { readyimage[0].SetActive(true); } else { readyimage[0].SetActive(false); } switch (pos_inRoom) { case 1: for (int i = 1; i < 4; ++i) { if (VariableManager.instance.ready_Turtle[i] == 1) { ready_num += 1; readyimage[i].SetActive(true); } else readyimage[i].SetActive(false); } break; case 2: for (int i = 0; i < 4; ++i) { if (i != 1) { if (i == 0) { if (VariableManager.instance.ready_Turtle[i] == 1) { ready_num += 1; readyimage[i + 1].SetActive(true); } else readyimage[i + 1].SetActive(false); } else { if (VariableManager.instance.ready_Turtle[i] == 1) { ready_num += 1; readyimage[i].SetActive(true); } else readyimage[i].SetActive(false); } } } break; case 3: for (int i = 0; i < 4; ++i) { if (i != 2) { if (i < 2) { if (VariableManager.instance.ready_Turtle[i] == 1) { ready_num += 1; readyimage[i + 1].SetActive(true); } else readyimage[i + 1].SetActive(false); } else { if (VariableManager.instance.ready_Turtle[i] == 1) { ready_num += 1; readyimage[i].SetActive(true); } else readyimage[i].SetActive(false); } } } break; case 4: for (int i = 0; i < 3; ++i) { if (VariableManager.instance.ready_Turtle[i] == 1) { ready_num += 1; readyimage[i + 1].SetActive(true); } else readyimage[i + 1].SetActive(false); } break; } if (ready_num == VariableManager.instance.roominfo[VariableManager.instance.m_roomid - 1].people_count - 1) { SRButton[0].interactable = true; } else { SRButton[0].interactable = false; } if (amIguard == 1) { crown[1].gameObject.SetActive(false); crown[2].gameObject.SetActive(false); crown[3].gameObject.SetActive(false); crown[0].gameObject.SetActive(true); } else { crown[0].gameObject.SetActive(false); switch (pos_inRoom) { case 1: crown[pos_guard - 1].gameObject.SetActive(true); break; case 2: if (pos_guard < 2) { crown[1].gameObject.SetActive(true); crown[2].gameObject.SetActive(false); crown[3].gameObject.SetActive(false); } else { for (int i = 0; i < 4; ++i) { crown[i].gameObject.SetActive(false); } crown[pos_guard - 1].gameObject.SetActive(true); } break; case 3: if (pos_guard > 3) { crown[3].gameObject.SetActive(true); crown[1].gameObject.SetActive(false); crown[2].gameObject.SetActive(false); crown[0].gameObject.SetActive(false); } else { for (int i = 0; i < 4; ++i) { crown[i].gameObject.SetActive(false); } crown[pos_guard].gameObject.SetActive(true); } break; case 4: for (int i = 0; i < 4; ++i) { crown[i].gameObject.SetActive(false); } crown[pos_guard].gameObject.SetActive(true); break; default: break; } } Map_Num_Text.text = "" + (map_num + 1); for (byte i = 0; i < 4; ++i) { if (pos_inRoom - 1 != i) //내가 아닌 유저 찾기 { people++; } if (VariableManager.instance.people_inRoom[i] != 0 && pos_inRoom - 1 != i) { if (people < 4) { int tempteamcolor = team[i]; //Debug.Log(i+"th Color:"+tempteamcolor); turtles[people + (tempteamcolor * 3)].SetActive(true); } ////Debug.Log(people + "th On!!"); } else if (VariableManager.instance.people_inRoom[i] == 0) { if (people < 4) { turtles[people].SetActive(false); turtles[people+3].SetActive(false); turtles[people+6].SetActive(false); turtles[people+9].SetActive(false); } } } turtles[0].transform.localScale = new Vector3(1.1f, 1.1f, 1.1f); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Terrain_Net : MonoBehaviour { public Terrain m_terrain; public Texture2D[] m_terrainmat; List<TreeInstance> tree_list = new List<TreeInstance>(); public GameObject[] m_objects; GameObject[] mapObject = new GameObject[12]; // Use this for initialization void Start() { SplatPrototype[] tex = new SplatPrototype[1]; //Debug.Log(VariableManager.instance.map_type); tex[0] = new SplatPrototype(); tex[0].texture = m_terrainmat[VariableManager.instance.map_type]; tex[0].tileSize = new Vector2(15, 15); //tex[0].texture = m_terrainmat[1]; m_terrain.terrainData.splatPrototypes = tex; for (int i = 0; i < 6; ++i) { mapObject[i] = Instantiate(m_objects[VariableManager.instance.map_type * 2]); if (i % 3 == 0) mapObject[i].transform.position = new Vector3(39.0f, 0.0f, i * 4); else if (i % 3 == 1) mapObject[i].transform.position = new Vector3(-10.0f + i, 0.0f, i * 3); else mapObject[i].transform.position = new Vector3(i * 3, 0.0f, 32.0f + i); mapObject[i + 6] = Instantiate(m_objects[VariableManager.instance.map_type * 2 + 1]); if (i % 3 == 2) { mapObject[i + 6].transform.position = new Vector3(38.0f, 0.0f, i * 4); mapObject[i + 6].transform.Rotate(0, -90.0f, 0); } else if (i % 3 == 0) { mapObject[i + 6].transform.position = new Vector3(-7.0f, 0.0f, i * 3); mapObject[i + 6].transform.Rotate(0, 90.0f, 0); } else { mapObject[i + 6].transform.position = new Vector3(i * 5, 0.0f, 32.0f); mapObject[i + 6].transform.Rotate(0, 180.0f, 0); } } //VariableManager.instance.map_type if (VariableManager.instance.map_type > 0) { for (int i = 0; i < m_terrain.terrainData.treeInstanceCount; ++i) { TreeInstance treeInstance = m_terrain.terrainData.GetTreeInstance(i); treeInstance.heightScale = 0.0f; treeInstance.widthScale = 0.0f; tree_list.Add(treeInstance); //Destroy(treeInstance); } tree_list.RemoveRange(0, m_terrain.terrainData.treeInstanceCount); float[,] heights = m_terrain.terrainData.GetHeights(0, 0, 0, 0); m_terrain.terrainData.SetHeights(0, 0, heights); } } // Update is called once per frame void Update() { } } <file_sep>using System; public struct ClientID { public byte size; // 패킷 크기 public byte packetType; // 패킷 id public byte id; // 클라 id public byte clientType; // 클라 타입( 0 = PC / 1 = AR ) public char[] playerID; // 입력한 플레이어 id public byte firstClient; // 먼저 접속한 클라이언트인지 아닌지 ( 0 = 먼저 접속 / 1 = 나중에 접속) } public struct CharInfo { public byte size; public byte packet_Type; public byte id; public int ani_state; public byte is_alive; public float x; public float z; public float rotateY; } public struct TB_Room { public byte size; //19 public byte type;//8 public byte roomID; public byte people_count; public byte game_start; public byte people_max; //최대 인원 수 public byte made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) public byte guardian_pos; public byte people1; public byte people2; public byte people3; public byte people4; public byte roomtype; public byte team1; public byte team2; public byte team3; public byte team4; public byte ready1; public byte ready2; public byte ready3; public byte ready4; public string password; }; public enum PacketInfo { CharPos = 1, // 캐릭터 좌표 및 스테이터스 BombPos, BombExplode, MapData,// 맵 데이터 ClientID, ItemData, // 아이템 데이터 DeadNotice, // 적 데이터 RoomData, RoomAccept, RoomCreate, ReadyData, // 오브젝트 데이터 GameStart, OUTRoom, ForceOutRoom, GameOver, EnemyData, ThrowBomb, KickBomb, ThrowComp, KickComp, SetMap2, PushBox, Nothing, GetTime, SetBomb, ConnectSuccess, DBInfo1, GameReady, Disconnect, AirDrop }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class NOTICE_SOUND_NUMBER { public const int RED_ALERT = 0; } public class Notice_Sound : Sound_Effect { public AudioClip[] m_AudioClips; public void Play_RedAlertSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[NOTICE_SOUND_NUMBER.RED_ALERT]); } } <file_sep>#pragma once #define WIN32_LEAN_AND_MEAN #define INITGUID #include <WinSock2.h> #include <windows.h> // include important windows stuff #pragma comment(lib, "ws2_32.lib") #include <thread> #include <vector> #include <array> #include <iostream> #include <unordered_set> #include <mutex> #include <vector> #include <set> #include <thread> #include <mutex> #include <queue> #include <stack> #include <set> #include <map> #include <list> #include <thread> #include <string> #include <chrono> #include <WinSock2.h> #include <Windows.h> #include <random> #include <cmath> #include <windows.h> #include <wininet.h> #include <stdio.h> #include<fstream> #include<iterator> #include <math.h> using namespace std; #define MAX_BUFF_SIZE 4000 // 작으면 성능이 떨어진다. #define MAX_PACKET_SIZE 255 #define BOARD_WIDTH 400 #define BOARD_HEIGHT 400 #define DB_HOST "turtlebombdb.cpcqdyzbke8r.ap-northeast-2.rds.amazonaws.com" #define DB_USER "goal1012" #define DB_PASS "<PASSWORD>" #define DB_NAME "TurtleBombDB" #define DB_PORT 3306 #define SHOW_PLAYER_POS_X 10 #define SHOW_PLAYER_POS_Y 10 #define VIEW_RADIUS 3 #define MAX_USER 500 #define NPC_START 1000 #define NUM_OF_NPC 10000 #define MY_SERVER_PORT 9000 // 포트는 서버/클라 동일해야함. #define MAX_STR_SIZE 100 #define CS_UP 1 #define CS_DOWN 2 #define CS_LEFT 3 #define CS_RIGHT 4 #define CS_CHAT 5 #define SC_POS 1 #define SC_PUT_PLAYER 2 #define SC_CHAT 4 //TBServer #define MAX_USER_INROOM 4 #define MAX_NPC 50 #define CASE_POS 1 #define CASE_BOMB 2 #define CASE_BOMB_EX 3 #define CASE_MAP 4 #define CASE_ID 5 #define CASE_ITEM_GET 6 #define CASE_DEAD 7 #define CASE_ROOM 8 #define CASE_GAMESET 15 #define CASE_JOINROOM 9 #define CASE_CREATEROOM 10 #define CASE_READY 11 #define CASE_STARTGAME 12 #define CASE_OUTROOM 13 #define CASE_FORCEOUTROOM 14 #define CASE_ROOMSETTING 15 #define CASE_TEAMSETTING 16 #define CASE_THROWBOMB 17 #define CASE_KICKBOMB 18 #define CASE_THROWCOMPLETE 19 #define CASE_KICKCOMPLETE 20 #define CASE_MAPSET 21 #define CASE_BOXPUSH 22 #define CASE_BOXPUSHCOMPLETE 23 #define CASE_TIME 24 #define CASE_BOMBSET 25 #define CASE_CONNECTSUCCESS 26 #define CASE_DB1 27 #define CASE_GAMEREADY 28 #define SC_REMOVE_PLAYER 29 #define CASE_AIRDROP 30 #define SIZEOF_TB_CharPos 22 #define SIZEOF_TB_BombPos 17 #define SIZEOF_TB_BombExplode 13 #define SIZEOF_TB_BombExplodeRE 15 #define SIZEOF_TB_MAP 227 #define SIZEOF_TB_ID 3 #define SIZEOF_TB_TeamSet_Re 6 #define SIZEOF_TB_ItemGet 13 #define SIZEOF_TB_GetItem 4 #define SIZEOF_TB_DEAD 3 #define SIZEOF_TB_GAMEEND 4 #define SIZEOF_TB_Room 31 #define SIZEOF_TB_join 12 #define SIZEOF_TB_joinRE 14 #define SIZEOF_TB_create 12 #define SIZEOF_TB_createRE 4 #define SIZEOF_TB_GameStart 4 #define SIZEOF_TB_GameStartRE 3 #define SIZEOF_CASE_READY 5 #define SIZEOF_TB_ReadyRE 5 #define SIZEOF_TB_RoomOut 5 #define SIZEOF_TB_RoomOutRE 3 #define SIZEOF_TB_GetOut 4 #define SIZEOF_TB_GetOutRE 2 #define SIZEOF_TB_RoomSetting 6 #define SIZEOF_TB_TeamSetting 5 #define SIZEOF_TB_ThrowBomb 13 #define SIZEOF_TB_ThrowBombRE 20 #define SIZEOF_TB_KickBombRE 21 #define SIZEOF_TB_ThrowComplete 11 #define SIZEOF_TB_MapSetRE 11 #define SIZEOF_TB_BoxPush 13 #define SIZEOF_TB_BoxPushComplete 11 #define SIZEOF_TB_BoxPushRE 21 #define SIZEOF_TB_Time 6 #define MAX_EVENT_SIZE 64 #define SIZEOF_TB_Connect_Success 2 #define SIZEOF_TB_IDPW 44 #define SIZEOF_TB_DBInfo_1 43 #define SIZEOF_TB_GAMEReady 5 #define SIZEOF_TB_AirDrop 2 #define MAP_NOTHING 0 #define MAP_BOX 1 #define MAP_ROCK 2 #define MAP_BUSH 3 #define MAP_ITEM 11 #define MAP_BOMB 5 #define MAP_ITEM_F 13 #define MAP_ITEM_S 12 #define MAP_FIREBUSH 10 #define MAP_KICKITEM 14 #define MAP_THROWITEM 15 #define MAP_CHAR 7 #define MAP_ENEMY 8 #define MAP_BOSS 9 #define MAP_GLIDERITEM 22 #define MAP_AIRDROPITEM 23 #define MAP_ICEBOX1 28 #define MAP_ICEBOX2 29 #define MAP_ICEBOX3 30 #define BASIC_POSX_CHAR1 0 #define BASIC_POSZ_CHAR1 0 #define BASIC_POSX_CHAR2 0 #define BASIC_POSZ_CHAR2 0 #define BASIC_POSX_CHAR3 0 #define BASIC_POSZ_CHAR3 0 #define BASIC_POSX_CHAR4 0 #define BASIC_POSZ_CHAR4 0 #define TURTLE_ANI_IDLE 0 #define TURTLE_ANI_WALK 1 #define TURTLE_ANI_HIDE 2 #define TURTLE_ANI_DEAD 3 #define TURTLE_ANI_KICK 4 #define TURTLE_ANI_PUSH 5 #pragma pack (push, 1) struct cs_packet_up { unsigned char size; unsigned char type; }; struct cs_packet_down { unsigned char size; unsigned char type; }; struct cs_packet_left { unsigned char size; unsigned char type; }; struct cs_packet_right { unsigned char size; unsigned char type; }; struct cs_packet_chat { unsigned char size; unsigned char type; wchar_t message[MAX_STR_SIZE]; }; struct sc_packet_pos { unsigned char size; unsigned char type; unsigned short id; unsigned short x; unsigned short y; }; struct sc_packet_put_player { unsigned char size; unsigned char type; unsigned short id; unsigned short x; unsigned short y; }; struct sc_packet_remove_player { unsigned char size; unsigned char type; short id; }; struct sc_packet_chat { unsigned char size; unsigned char type; short id; wchar_t message[MAX_STR_SIZE]; }; struct Socket_Info { SOCKET sock; bool m_connected; bool m_getpacket; char buf[MAX_BUFF_SIZE]; int type; int id; int recvbytes; int sendbytes; int remainbytes; unsigned char roomID; //디폴트는 0. 안 들어갔다는 뜻 unsigned char is_guardian; //방장인지 아닌지 unsigned char is_ready; //추가 unsigned char fire; unsigned char bomb; unsigned char speed; unsigned char pos_inRoom; }; struct TB_DisConnect { unsigned char size; unsigned char type;//29 short id; }; struct TB_DBInfo_1 { unsigned char size; //43 unsigned char type; //27 unsigned char connect; //2이면 아이디 생성완료, 1이면 아이디 인증 성공, 0면 아이디 인증 실패 char id_string[20]; int win; int lose; int tier; int exp; int exp_max; }; struct TB_Connect_Success { unsigned char size; //2 unsigned char type; //26 }; struct TB_IDPW { unsigned char size; //44 unsigned char type; //26] unsigned char m_id; //26] unsigned char m_type; //1이면 로그인, 2면 생성 char id[20]; char pw[20]; }; struct GameCharInfo { unsigned char speed; unsigned char fire; unsigned char bomb; }; struct TB_CharPos {//type:1 unsigned char size; //22 unsigned char type; unsigned char ingame_id; unsigned char anistate; unsigned char is_alive; unsigned char room_id; unsigned char fire; unsigned char bomb; unsigned char can_throw; unsigned char can_kick; float posx; float posz; float rotY; }; struct TB_BombPos { //type:2 unsigned char size;//17 unsigned char type; unsigned char ingame_id; unsigned char firepower; //화력 //unsigned char throwing; //던져지고 있는지 //unsigned char kicking; //차여지고 있는지 unsigned char room_num; int posx; int posz; float settime; }; struct TB_BombSetRE { unsigned char size;//11 unsigned char type;//25 unsigned char f_power; int posx; int posz; }; struct TB_MapSetRE { unsigned char size;//11 unsigned char type;//21 unsigned char m_type; int posx; int posz; }; struct TB_BombExplode { //type:3 unsigned char size;//13 unsigned char type; unsigned char firepower; unsigned char room_id; unsigned char game_id; int posx; int posz; }; struct TB_BombExplodeRE { //type:3 unsigned char size;//15 unsigned char type; unsigned char upfire; unsigned char rightfire; unsigned char downfire; unsigned char leftfire; unsigned char gameID; int posx; int posz; }; struct TB_ThrowBomb { unsigned char size;//13 unsigned char type;//17 unsigned char roomid; unsigned char ingame_id; unsigned char direction; int posx; int posz; }; struct TB_ThrowBombRE { unsigned char size;//20 unsigned char type;//17 unsigned char direction; unsigned char ingame_id; int posx; int posz; int posx_re; int posz_re; }; struct TB_ThrowComplete { unsigned char size;//11 unsigned char type;//19 unsigned char roomid; int posx; int posz; }; struct TB_KickBomb { unsigned char size;//13 unsigned char type;//18 unsigned char roomid; unsigned char ingame_id; unsigned char direction; int posx; int posz; }; struct TB_KickComplete { unsigned char size;//11 unsigned char type;//20 unsigned char roomid; int posx; int posz; }; struct TB_KickBombRE { unsigned char size;//21 unsigned char type;//18 unsigned char kick; unsigned char ingame_id; unsigned char direction; int posx; int posz; int posx_re; int posz_re; }; struct TB_BoxPush { unsigned char size;//13 unsigned char type;//22 unsigned char roomid; unsigned char ingame_id; unsigned char direction; int posx; int posz; }; struct TB_BoxPushRE { unsigned char size;//21 unsigned char type;//22 unsigned char push; //0이면 안밀어, 1이면 밀어~! unsigned char ingame_id; unsigned char direction; int posx; int posz; int posx_d; int posz_d; }; struct TB_BoxPushComplete { unsigned char size;//11 unsigned char type;//19 unsigned char roomid; int posx; int posz; }; struct TB_ReGame { }; struct TB_Map { //type:4 unsigned char size;//227 unsigned char type; unsigned char mapInfo[15][15]; }; struct TB_ID {//type:5 unsigned char size; //3 unsigned char type; unsigned char id; //0330 수정 int에서- BYTE로 수정 }; struct TB_ItemGet { //type:6 unsigned char size; //13 unsigned char type;//6 unsigned char room_id; unsigned char ingame_id; unsigned char item_type; int posx; int posz; }; struct TB_GetItem { //send : type 6 서버 전송-> 클라 수신 unsigned char size; //4 unsigned char type;//6 unsigned char ingame_id; unsigned char itemType; //타입에 따라 다른 문구가 출력된다 + 능력이 오른다. }; struct TB_DEAD { //죽었을 때 알려주는 패킷 unsigned char size; //3 unsigned char type;//7 unsigned char game_id; //누가 죽었나! }; struct TB_GAMEEND { unsigned char size; //3 unsigned char type;//15 unsigned char winner_id; //누가 이겼나! unsigned char loser_id; }; struct TB_UserInfo { //유저정보 - type: 7 unsigned char size; //9 unsigned char type; unsigned char id; //인게임 id와는 다르다. unsigned char roomID; //디폴트는 0. 안 들어갔다는 뜻 unsigned char is_guardian;//방장인지 아닌지 unsigned char is_ready; //추가 unsigned char fire; unsigned char bomb; unsigned char speed; }; //프로토콜이 아닌 구조체에 맵데이터를 넣은 방 구조체 작성 struct TB_Room { //방장 추가(완) unsigned char size; //31 unsigned char type;//8 unsigned char roomID; unsigned char people_count; unsigned char game_start; //게임 시작 1 unsigned char people_max; //최대 인원 수 unsigned char made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) unsigned char guardian_pos; //배열에 넣을 때 -1할 것 unsigned char people_inroom[4]; unsigned char roomstate; //팀전인가 개인전인가? 0-개인전 1-팀전 unsigned char map_thema; unsigned char map_mode; unsigned char team_inroom[4]; unsigned char ready[4]; char password[8]; }; struct TB_RoomInfo { unsigned char room_num; unsigned char people_count; unsigned char people_max; unsigned char game_start; }; //없는 방입니다. //게임중입니다. struct TB_Ready { unsigned char size; //5 unsigned char type;//11 unsigned char room_num; unsigned char pos_in_room; unsigned char will_ready; // 0이면 레디하겠다고 보내온 것, 1이면 레디를 해제하겠다고 보내온 것. }; struct TB_ReadyRE { unsigned char size; //5 unsigned char type;//11 unsigned char pos_in_room; unsigned char ready;//0이면 레디해제, 1이면 레디 unsigned char roomid; }; struct TB_GAMEReady { unsigned char size; //5 unsigned char type; //28 unsigned char imready; //1이면 레디,0이면 noready unsigned char roomid; unsigned char myid; }; struct TB_GameStart { unsigned char size;//4 unsigned char type;//12 unsigned char roomID; unsigned char my_pos; }; struct TB_GameStartRE { unsigned char size; unsigned char type; unsigned char startTB;//1이면 시작,0이면 땡 }; struct TB_Refresh { //type:? unsigned char size; unsigned char type; unsigned char id; unsigned char roomID; }; struct TB_join { //들어갈 때 보내는 패킷 9 unsigned char size; unsigned char type;//9 unsigned char id; unsigned char roomID; char password[8]; }; struct TB_joinRE { //방장 추가 unsigned char size;//14 unsigned char type; unsigned char respond; //0이면 no, 1이면 yes unsigned char my_room_num; unsigned char yourpos; //1,2,3,4 중 하나 unsigned char guard_pos; //방장 위치 unsigned char people_inroom[4]; unsigned char team_inroom[4]; }; struct TB_create { //type:10 unsigned char size; unsigned char type; unsigned char id; unsigned char roomid; char password[8]; }; struct TB_createRE { unsigned char size; unsigned char type; unsigned char can; //가능하면 1, 불가능하면 0 unsigned char roomid; }; struct TB_GetOut {//클라 전송->서버 수신, 서버 전송할 경우 받은 클라는 강퇴 결과 출력 unsigned char size; unsigned char type;//14 unsigned char roomID; unsigned char position; }; //받았을 경우 turtle_room.people_count-=1; turtle_waitroom.roodID = 0; struct TB_RoomOut {//방에서 나갈 때 unsigned char size;//4 unsigned char type;//13 unsigned char roomID; unsigned char my_pos; unsigned char imwinner; //2일경우 lose }; struct TB_AirDrop { unsigned char size;// unsigned char type;// }; struct TB_GetOUTRE { unsigned char size; unsigned char type;//14 }; struct TB_RoomOutRE { unsigned char size; unsigned char type; unsigned char can; //가능하면 1, 불가능하면 0 }; struct TB_RoomSetting { unsigned char size;//6 unsigned char type;//15 unsigned char roomid; unsigned char peoplemax; //인원수 unsigned char mapthema; unsigned char mapnum; }; struct TB_TeamSetting { unsigned char size;//5 unsigned char type;//16 unsigned char roomid; unsigned char pos_in_room; unsigned char team; }; struct TB_TeamSet_Re { unsigned char size;//6 unsigned char type;//16 unsigned char team[4]; }; struct TB_Time { unsigned char size;//6 unsigned char type;//24 float time; }; struct TB_Room_Data { //방장 추가(완) unsigned char roomID; unsigned char people_count; unsigned char game_start; unsigned char people_max; //최대 인원 수 unsigned char made; //만들어진 방인가? 0-안 만들어짐, 1- 만들어짐(공개), 2-만들어짐(비공개) unsigned char guardian_pos; //배열에 넣을 때 -1할 것 unsigned char people_inroom[4]; TB_Map map; char password[8]; }; struct Map_TB { unsigned char mapTile[15][15]; }; #pragma pack(pop) class Bomb_TB { public: pair<int, int> xz; float time; bool is_throw; bool is_kicked; unsigned char firepower; float explode_time; unsigned char room_num; unsigned char game_id; bool operator ==(const Bomb_TB& other) { return xz == other.xz; } Bomb_TB() { time = (float)GetTickCount() / 1000; explode_time = 3.0f; xz = make_pair(0, 0); is_throw = false; is_kicked = false; } Bomb_TB(int a, int b) { time = (float)GetTickCount() / 1000; explode_time = 3.0f; xz = make_pair(a, b); is_throw = false; is_kicked = false; } Bomb_TB(int a, int b, unsigned char r, unsigned char f, unsigned char g) { time = (float)GetTickCount() / 1000; explode_time = 3.0f; room_num = r; firepower = f; game_id = g; xz = make_pair(a, b); is_throw = false; is_kicked = false; } bool GetTime() { float temptime = (float)GetTickCount() / 1000; return (temptime - time >= explode_time) && !is_throw && !is_kicked; } void ResetExplodeTime() { float temptime = (float)GetTickCount() / 1000; temptime = temptime - time; explode_time = explode_time - temptime; } void ResetTime() { time = (float)GetTickCount() / 1000; } pair<int, int> GetXZ() { return xz; } }; class InGameCalculator { bool id[4]; float time; float airdrop_cooltime; bool gameover; int time_check = 0; public: int people_count; map<pair<int, int>, Bomb_TB> bomb_Map; vector<TB_BombExplodeRE> explode_List; unsigned char idList[4]; TB_Map map; bool is_start; TB_CharPos ingame_Char_Info[4]; int airx[4]; int airy[4]; unsigned char fireMap[15][15]; bool ready_player[4]; int deathcount; InGameCalculator() { people_count = 0; explode_List.clear(); bomb_Map.clear(); deathcount = 0; is_start = false; ready_player[0] = false; ready_player[1] = false; ready_player[2] = false; ready_player[3] = false; airdrop_cooltime = 30.0f; id[0] = true; id[1] = true; id[2] = true; id[3] = true; time_check = 180; time = 180.0f; gameover = false; map.size = SIZEOF_TB_MAP; map.type = CASE_MAP; for (int i = 0; i < 4; ++i) { ingame_Char_Info[i].size = SIZEOF_TB_CharPos; ingame_Char_Info[i].type = CASE_POS; idList[i] = 0; } for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { fireMap[i][j] = 0; } } ingame_Char_Info[0].ingame_id = 0; ingame_Char_Info[1].ingame_id = 1; ingame_Char_Info[2].ingame_id = 2; ingame_Char_Info[3].ingame_id = 3; ingame_Char_Info[0].posx = 0.0f; ingame_Char_Info[0].posz = 0.0f; ingame_Char_Info[0].is_alive = true; ingame_Char_Info[0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[1].posx = 28.0f; ingame_Char_Info[1].posz = 0.0f; ingame_Char_Info[1].is_alive = true; ingame_Char_Info[1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[2].posx = 0.0f; ingame_Char_Info[2].posz = 28.0f; ingame_Char_Info[2].is_alive = true; ingame_Char_Info[2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[3].posx = 28.0f; ingame_Char_Info[3].posz = 28.0f; ingame_Char_Info[3].is_alive = true; ingame_Char_Info[3].rotY = 180.0f; } ~InGameCalculator() {} void InitClass() { is_start = false; map.size = SIZEOF_TB_MAP; map.type = CASE_MAP; ready_player[0] = false; ready_player[1] = false; ready_player[2] = false; ready_player[3] = false; bomb_Map.clear(); deathcount = 0; gameover = false; explode_List.clear(); id[0] = true; id[1] = true; id[2] = true; id[3] = true; time = 180.0f; time_check = 180; for (int i = 0; i < 4; ++i) { ingame_Char_Info[i].size = SIZEOF_TB_CharPos; ingame_Char_Info[i].type = CASE_POS; idList[i] = 0; } for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { fireMap[i][j] = 0; } } airdrop_cooltime = 30.0f; ingame_Char_Info[0].ingame_id = 0; ingame_Char_Info[1].ingame_id = 1; ingame_Char_Info[2].ingame_id = 2; ingame_Char_Info[3].ingame_id = 3; ingame_Char_Info[0].posx = 0.0f; ingame_Char_Info[0].posz = 0.0f; ingame_Char_Info[0].is_alive = true; ingame_Char_Info[0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[1].posx = 28.0f; ingame_Char_Info[1].posz = 0.0f; ingame_Char_Info[1].is_alive = true; ingame_Char_Info[1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[2].posx = 0.0f; ingame_Char_Info[2].posz = 28.0f; ingame_Char_Info[2].is_alive = true; ingame_Char_Info[2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[3].posx = 28.0f; ingame_Char_Info[3].posz = 28.0f; ingame_Char_Info[3].is_alive = true; ingame_Char_Info[3].rotY = 180.0f; } void PlayerDead(unsigned char idd) { if (id[idd]) { id[idd] = false; deathcount++; } } void ChangeID(int place, unsigned char id_p) { idList[place] = id_p; } void PlayerBlank(int id_p) { id[id_p] = false; } void SetGameOver() { gameover = true; } void SetAirMap() { for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { if (map.mapInfo[i][j] == MAP_NOTHING) { } } } } bool IsGameOver() { return gameover; } float GetTime() { return time; } void SetTime(DWORD a) { float temp = ((float)a) / 1000.0f; time = time - temp; airdrop_cooltime = airdrop_cooltime - temp; } bool OneSec() { if (((int)(time * 10) % 10)<1 &&time_check!=(int)(time)){ time_check = (int)((int)time/1); return true; } else return false; } bool AirDropTime() { if (airdrop_cooltime <= 0.0f) { airdrop_cooltime = 30.0f; return true; } else return false; } void AirDrop() { unsigned char tempMap[15][15]; memcpy(tempMap, map.mapInfo, sizeof(tempMap)); for (int i = 0; i < 4; ++i) { int x = rand() % 15; int z = rand() % 15; if (tempMap[z][x] != MAP_NOTHING) { --i; continue; } else { airx[i] = x; airy[i] = z; tempMap[z][x] = MAP_AIRDROPITEM; } } memcpy(map.mapInfo, tempMap, sizeof(tempMap)); } unsigned char GetWinnerID() { for (unsigned char i = 0; i < 4; ++i) { if (id[i]) return i; } return 4; //DRAW를 뜻한다. } void CalculateMap(int x, int z, unsigned char f,unsigned char id_player) { bool l_UpBlock = false; bool l_DownBlock = false; bool l_LeftBlock = false; bool l_RightBlock = false; unsigned char uf = f; unsigned char df = f; unsigned char lf = f; unsigned char rf = f; unsigned char tempMap[15][15]; memcpy(tempMap, map.mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; for (unsigned char b = 1; b <= f; ++b) { if (!l_DownBlock) { if (z - b < 0) { l_DownBlock = true; df = b - 1; } else { if (tempMap[z - b][x] == MAP_BOMB) { tempMap[z - b][x] = MAP_NOTHING; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); if (bomb_Map[make_pair(x, z - b)].firepower != 0) { CalculateMap(x, z- b, fireMap[z - b][x], bomb_Map[make_pair(x, z - b)].game_id); auto a = bomb_Map.find(pair<int, int>(x, z - b)); bomb_Map.erase(a); } memcpy(tempMap, map.mapInfo, sizeof(tempMap)); l_DownBlock = true; df = b; } else if (tempMap[z - b][x] == MAP_BOX || tempMap[z - b][x] == MAP_ICEBOX1) { //cout << "Box!!!" << endl; int temp_rand = (rand() % 16); if (temp_rand < 4) tempMap[z - b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z - b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z - b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z - b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z - b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z - b][x] = MAP_THROWITEM; else if (temp_rand >= 14 && temp_rand <= 15) tempMap[z - b][x] = MAP_GLIDERITEM; l_DownBlock = true; df = b - 1; } else if (tempMap[z - b][x] == MAP_ICEBOX2) { tempMap[z - b][x] = MAP_ICEBOX1; l_DownBlock = true; df = b - 1; } else if (tempMap[z - b][x] == MAP_ICEBOX3) { tempMap[z - b][x] = MAP_ICEBOX2; l_DownBlock = true; df = b - 1; } else if (tempMap[z - b][x] == MAP_ITEM || tempMap[z - b][x] == MAP_GLIDERITEM || tempMap[z - b][x] == MAP_AIRDROPITEM|| tempMap[z - b][x] == MAP_ITEM_F || tempMap[z - b][x] == MAP_ITEM_S || tempMap[z - b][x] == MAP_KICKITEM || tempMap[z - b][x] == MAP_THROWITEM) { tempMap[z - b][x] = MAP_NOTHING; } else if (tempMap[z - b][x] == MAP_BUSH || tempMap[z - b][x] == MAP_FIREBUSH) { } else if (tempMap[z - b][x] == MAP_ROCK) { l_DownBlock = true; df = b - 1; } } } if (!l_UpBlock) { if (z + b > 14) { l_UpBlock = true; uf = b - 1; } else { if (tempMap[z + b][x] == MAP_BOMB) { tempMap[z + b][x] = MAP_NOTHING; l_UpBlock = true; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); if (bomb_Map[make_pair(x, z + b)].firepower != 0) { CalculateMap(x, z + b, fireMap[z + b][x], bomb_Map[make_pair(x, z + b)].game_id); auto a = bomb_Map.find(pair<int, int>(x, z+b)); bomb_Map.erase(a); } //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); memcpy(tempMap, map.mapInfo, sizeof(tempMap)); uf = b; } else if (tempMap[z + b][x] == MAP_BOX || tempMap[z+b][x] == MAP_ICEBOX1) { cout << "Box!!!" << endl; int temp_rand = (rand() % 16); if (temp_rand<4) tempMap[z + b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z + b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z + b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z + b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z + b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z + b][x] = MAP_THROWITEM; else if (temp_rand >= 14 && temp_rand <= 15) tempMap[z + b][x] = MAP_GLIDERITEM; l_UpBlock = true; uf = b - 1; } else if (tempMap[z + b][x] == MAP_ICEBOX2) { tempMap[z + b][x] = MAP_ICEBOX1; l_UpBlock = true; uf = b - 1; } else if (tempMap[z + b][x] == MAP_ICEBOX3) { tempMap[z + b][x] = MAP_ICEBOX2; l_UpBlock = true; uf = b - 1; } else if (tempMap[z + b][x] == MAP_ITEM || tempMap[z + b][x] == MAP_GLIDERITEM || tempMap[z +b][x] == MAP_AIRDROPITEM || tempMap[z + b][x] == MAP_ITEM_F || tempMap[z + b][x] == MAP_ITEM_S || tempMap[z + b][x] == MAP_KICKITEM || tempMap[z + b][x] == MAP_THROWITEM) { tempMap[z + b][x] = MAP_NOTHING; } else if (tempMap[z + b][x] == MAP_ROCK) { l_UpBlock = true; uf = b - 1; } } } if (!l_LeftBlock) { if (x - b < 0) { l_LeftBlock = true; lf = b - 1; } else { if (tempMap[z][x - b] == MAP_BOMB) { tempMap[z][x - b] = MAP_NOTHING; l_LeftBlock = true; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); if (bomb_Map[make_pair(x-b, z)].firepower != 0) { CalculateMap(x-b, z, fireMap[z][x-b], bomb_Map[make_pair(x-b, z)].game_id); auto a = bomb_Map.find(pair<int,int>(x - b, z)); bomb_Map.erase(a); } memcpy(tempMap, map.mapInfo, sizeof(tempMap)); lf = b; } else if (tempMap[z][x - b] == MAP_BOX || tempMap[z][x - b] == MAP_ICEBOX1) { cout << "Box!!!" << endl; int temp_rand = (rand() % 16); if (temp_rand<4) tempMap[z][x - b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x - b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x - b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x - b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x - b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x - b] = MAP_THROWITEM; else if (temp_rand >= 14 && temp_rand <= 15) tempMap[z][x - b] = MAP_GLIDERITEM; l_LeftBlock = true; lf = b - 1; } else if (tempMap[z][x - b] == MAP_ICEBOX2) { tempMap[z][x - b] = MAP_ICEBOX1; l_LeftBlock = true; lf = b - 1; } else if (tempMap[z][x - b] == MAP_ICEBOX3) { tempMap[z][x - b] = MAP_ICEBOX2; l_LeftBlock = true; lf = b - 1; } else if (tempMap[z][x - b] == MAP_ITEM || tempMap[z ][x-b] == MAP_GLIDERITEM || tempMap[z ][x- b] == MAP_AIRDROPITEM || tempMap[z][x - b] == MAP_KICKITEM || tempMap[z][x - b] == MAP_THROWITEM || tempMap[z][x - b] == MAP_ITEM_F || tempMap[z][x - b] == MAP_ITEM_S) { tempMap[z][x - b] = MAP_NOTHING; } else if (tempMap[z][x - b] == MAP_ROCK) { l_LeftBlock = true; lf = b - 1; } } } if (!l_RightBlock) { if (x + b > 14) { l_RightBlock = true; rf = b - 1; } else { if (tempMap[z][x + b] == MAP_BOMB) { tempMap[z][x + b] = MAP_NOTHING; l_RightBlock = true; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); //*tempB = true; //CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); if (bomb_Map[make_pair(x + b, z)].firepower != 0) { CalculateMap(x + b, z, fireMap[z][x + b], bomb_Map[make_pair(x + b, z)].game_id); auto a = bomb_Map.find(pair<int, int>(x+b, z )); bomb_Map.erase(a); } memcpy(tempMap, map.mapInfo, sizeof(tempMap)); rf = b; } else if (tempMap[z][x + b] == MAP_BOX || tempMap[z][x + b] == MAP_ICEBOX1) { cout << "Box!!!" << endl; int temp_rand = (rand() % 16); if (temp_rand<4) tempMap[z][x + b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x + b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x + b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x + b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x + b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x + b] = MAP_THROWITEM; else if (temp_rand >= 14 && temp_rand <= 15) tempMap[z][x + b] = MAP_GLIDERITEM; l_RightBlock = true; rf = b - 1; } else if (tempMap[z][x + b] == MAP_ICEBOX2) { tempMap[z][x + b] = MAP_ICEBOX1; l_RightBlock = true; rf = b - 1; } else if (tempMap[z][x + b] == MAP_ICEBOX3) { tempMap[z][x + b] = MAP_ICEBOX2; l_RightBlock = true; rf = b - 1; } else if (tempMap[z][x + b] == MAP_ITEM || tempMap[z][x+b] == MAP_GLIDERITEM || tempMap[z][x+b] == MAP_AIRDROPITEM || tempMap[z][x + b] == MAP_KICKITEM || tempMap[z][x + b] == MAP_THROWITEM || tempMap[z][x + b] == MAP_ITEM_F || tempMap[z][x + b] == MAP_ITEM_S) { tempMap[z][x + b] = MAP_NOTHING; } else if (tempMap[z][x + b] == MAP_ROCK) { l_RightBlock = true; rf = b - 1; } } } } TB_BombExplodeRE bomb = { SIZEOF_TB_BombExplodeRE,CASE_BOMB_EX,uf,rf,df,lf,id_player,x,z }; explode_List.emplace_back(bomb); //explode_List fireMap[z][x] = 0; tempMap[z][x] = MAP_NOTHING; memcpy(map.mapInfo, tempMap, sizeof(tempMap)); } }; template <class Iter, class Value> Iter myFind(Iter a, Iter b, Value val) { Iter p = a; while (a != b) { if (*a == val) return a; else ++a; } return b; } struct EXOVER { WSAOVERLAPPED m_over; /* WSAOVERLAPPED는 typedef struct _OVERLAPPED { ULONG_PTR Internal; ULONG_PTR InternalHigh; union { struct { DWORD Offset; DWORD OffsetHigh; } DUMMYSTRUCTNAME; PVOID Pointer; } DUMMYUNIONNAME; HANDLE hEvent; } OVERLAPPED, *LPOVERLAPPED; */ char m_iobuf[MAX_BUFF_SIZE]; WSABUF m_wsabuf; bool is_recv; }; class Client { public: SOCKET m_s; bool m_isconnected; unsigned char is_guardian; int m_x; int m_y; int m_scene; // 0 - 로비, 1- 방, 2- 게임중 EXOVER m_rxover; int m_packet_size; // 지금 조립하고 있는 패킷의 크기 int m_prev_packet_size; // 지난번 recv에서 완성되지 않아서 저장해 놓은 패킷의 앞부분의 크기 char m_packet[MAX_PACKET_SIZE]; int id; int roomNum; char stringID[20]; int win_vs; int lose_vs; int tier; int exp; int exp_max; float communicate_time; //최근 교류한 시간 // set<int> view_list; // 삽입/삭제가 자유로워야 한다. + 시간복잡도 상 가장 효율적인것이 set이다. (list는 삽입/삭제가 빠르지만 검색 성능이 느리다.) // multiset 은 중복가능 이기때문에 사용하지 않아야한다. unordered_set<int> m_view_list; // 정렬이 딱히 필요하지 않기 때문에 비정렬셋으로 성능 향상. mutex m_mVl; // 뷰리스트를 보호하기위해 Client() { m_isconnected = false; m_x = 4; m_y = 4; communicate_time = GetTickCount(); ZeroMemory(&m_rxover.m_over, sizeof(WSAOVERLAPPED)); m_rxover.m_wsabuf.buf = m_rxover.m_iobuf; m_rxover.m_wsabuf.len = sizeof(m_rxover.m_wsabuf.buf); m_rxover.is_recv = true; m_prev_packet_size = 0; } void CleanClient() { win_vs = 0; lose_vs = 0; tier = 0; exp = 0; exp_max = 0; m_isconnected = false; is_guardian = 0; m_scene = 0; roomNum = 0; is_guardian = 0; } void ChangeRecieveTime() { communicate_time = GetTickCount(); } bool IsUnConnected(DWORD t_time) { return ((float)t_time-communicate_time)/ 1000.0f >=20.0f; } bool IsUnConnected_inRoom(DWORD t_time) { return ((float)t_time - communicate_time) / 1000.0f >= 80.0f; } bool IsUnConnected_inGame(DWORD t_time) { return ((float)t_time - communicate_time) / 1000.0f >= 100.0f; } }; <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Jump_Checker : MonoBehaviour { Bomb_Remaster m_Parent; void Awake() { m_Parent = transform.parent.GetComponent<Bomb_Remaster>(); } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Box") || other.gameObject.CompareTag("Rock") || (other.gameObject.CompareTag("Bomb") && other.gameObject != m_Parent.gameObject) || other.gameObject.CompareTag("icicle_Body") ) { if (m_Parent.transform.position.y >= other.transform.position.y + 0.3f) m_Parent.Set_Rising(THROWN_BOMB_VALUES.RERISING_MAX_Y); else m_Parent.Set_Bomb(); } if (other.gameObject.CompareTag("Land")) m_Parent.Set_Bomb(); if (other.gameObject.CompareTag("Wall")) { if (m_Parent.transform.position.y >= other.transform.position.y + 0.3f) m_Parent.Return_To_Pool(); else m_Parent.Set_Bomb(); } } /* void OnCollisionEnter(Collision collision) { if (collision.gameObject.CompareTag("Box") || collision.gameObject.CompareTag("Rock") || collision.gameObject.CompareTag("Bomb") ) { if (m_Parent.transform.position.y >= collision.transform.position.y + 0.5f) m_Parent.Set_Rising(); } if (collision.gameObject.CompareTag("Land")) m_Parent.Set_Bomb(); if (collision.gameObject.CompareTag("Wall")) m_Parent.Return_To_Pool(); } */ } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Normal_Fade : MonoBehaviour { Animation m_Animation; IEnumerator m_Fade_Out_Checker; bool m_is_Fade_Out_Over = false; public bool Get_is_Fade_Out_Over () { return m_is_Fade_Out_Over; } void Awake() { m_Animation = GetComponent<Animation>(); m_Fade_Out_Checker = Fade_Out_Check(); FadeIn(); } public void FadeIn() { m_Animation.Play(m_Animation.GetClip("Normal_Fade_In").name); } public void FadeOut() { m_Animation.Play(m_Animation.GetClip("Normal_Fade_Out").name); StartCoroutine(m_Fade_Out_Checker); } IEnumerator Fade_Out_Check() { while(true) { if (m_Animation["Normal_Fade_Out"].normalizedTime >= 0.95f) { StopCoroutine(m_Fade_Out_Checker); m_is_Fade_Out_Over = true; } yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class BGM_NUMBER { public const int NORMAL = 0; public const int BOSS = 1; } public class Audio_Manager : MonoBehaviour { static Audio_Manager m_Instance; public static Audio_Manager GetInstance() { return m_Instance; } static bool m_is_Vib_Mute; public bool Get_is_Vibration_Mute() { return m_is_Vib_Mute; } AudioSource m_BGM_Audio_Source; public AudioClip[] m_BGM_List; IEnumerator m_Fadeout; IEnumerator m_Fadein; float m_FadeSpeed = 0.4f; float m_Volume = 1.0f; void Awake () { m_Instance = this; m_BGM_Audio_Source = GetComponent<AudioSource>(); if (PlayerPrefs.GetInt("System_Option_Vib_ON") == 0) m_is_Vib_Mute = true; else m_is_Vib_Mute = false; if (Sound_Effect.GetInstance() != null) { if (PlayerPrefs.GetInt("System_Option_SE_ON") == 0) Sound_Effect.GetInstance().Set_SE_Mute(true); else Sound_Effect.GetInstance().Set_SE_Mute(false); } m_Fadeout = Sound_Fadeout(); m_Fadein = Sound_Fadein(); } public void Sound_Fadeout_Start() { StartCoroutine(m_Fadeout); } public void Sound_Fadein_Start() { StartCoroutine(m_Fadein); } IEnumerator Sound_Fadeout() { while (true) { m_Volume = Mathf.Lerp(m_Volume, 0.0f, m_FadeSpeed * Time.deltaTime); m_BGM_Audio_Source.volume = m_Volume; Sound_Effect.GetInstance().SetVolume(m_Volume); if (m_Volume <= 0.01f) StopCoroutine(m_Fadeout); yield return null; } } IEnumerator Sound_Fadein() { while (true) { m_Volume = Mathf.Lerp(m_Volume, 1.0f, m_FadeSpeed * Time.deltaTime); m_BGM_Audio_Source.volume = m_Volume; Sound_Effect.GetInstance().SetVolume(m_Volume); if (m_Volume >= 0.99f) StopCoroutine(m_Fadein); yield return null; } } public void BGM_Play(int bgm_number) { m_BGM_Audio_Source.Stop(); m_BGM_Audio_Source.clip = m_BGM_List[bgm_number]; if (PlayerPrefs.GetInt("System_Option_BGM_ON") != 0) m_BGM_Audio_Source.Play(); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Ice_Box : Box { int m_Crash_Count; public void Set_Crash_Count(int count) { m_Crash_Count = count; } public Material[] m_Materials; void Start() { GetComponentInChildren<MeshRenderer>().material = m_Materials[m_Crash_Count - 1]; m_MCL_index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); } void OnTriggerEnter(Collider other) { if (!m_is_Destroyed && other.gameObject.CompareTag("Flame_Remains")) { if (m_Crash_Count > 1) { --m_Crash_Count; GetComponentInChildren<MeshRenderer>().material = m_Materials[m_Crash_Count - 1]; } else { m_is_Destroyed = true; // MCL 갱신 StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_index, false); SetItem(); // 아이템 생성 Instantiate(m_Particle).transform.position = transform.position; // 파티클 발생 Destroy(gameObject); // 박스 파괴 } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using UnityEngine.SceneManagement; //씬 전환 함수 public class SceneChange : MonoBehaviour { public Canvas cv; public RawImage FadeSlider; public RawImage option_image; static public SceneChange instance; int scene=8; int last_scene; bool swap_scene = false; public bool is_discon_byServer; //서버에게 강퇴당했나 // Use this for initialization void Awake() { instance = this; DontDestroyOnLoad(this); } void Start() { if (cv != null) { cv.enabled = true; } is_discon_byServer = false; StartCoroutine("SceneSwap"); if (SceneManager.GetActiveScene().buildIndex == 8) { GoTo_Connect_Scene(); } last_scene = 8; if (SceneManager.GetActiveScene().buildIndex == 1) option_image = GameObject.Find("Notice").GetComponent<RawImage>(); // } public int GetSceneState() { return scene; } public void GoTo_Connect_Scene() { last_scene = scene; //SceneManager.LoadScene(0); scene = 4; swap_scene = true; } public void GoTo_Connect_Scene_Coop() { last_scene = scene; //SceneManager.LoadScene(0); scene = 10; swap_scene = true; } public void GoTo_Matching_Scene() { last_scene = scene; //SceneManager.LoadScene(0); scene = 11; swap_scene = true; } public void GoTo_Ice_VS_Scene() { last_scene = scene; scene = 13; swap_scene = true; } public void GoTo_CoopBoss_Scene() { last_scene = scene; //SceneManager.LoadScene(0); scene = 12; swap_scene = true; } // "타이틀 화면"으로 이동 public void GoTo_Wait_Scene() { last_scene = scene; //SceneManager.LoadScene(0); scene = 5; swap_scene = true; } // "모드 선택 화면"으로 이동 public void GoTo_ModeSelect_Scene() { last_scene = scene; ////Debug.Log("Clicked"); scene = 6; swap_scene = true; //SceneManager.LoadScene(1); } // "모험모드 스테이지 선택 화면"으로 이동 public void GoTo_Game_Scene() { last_scene = scene; scene = 7; swap_scene = true; //SceneManager.LoadScene(2); } public void GoTo_Select_Scene() { last_scene = scene; scene = 1; swap_scene = true; } public void GoTo_Select_Scene_ByServer() { is_discon_byServer = true; last_scene = scene; scene = 1; swap_scene = true; } // "선택한 해당 스테이지"로 이동 public void GoTo_Mode_Adventure_Selected_Stage(int stage_ID) { //if (LobbySound.instanceLS != null) // LobbySound.instanceLS.SoundStop(); // 선택한 스테이지가 몇번인지 PlayerPrefs에 기록! PlayerPrefs.SetInt("Mode_Adventure_Selected_Stage_ID", stage_ID); FadeSlider.gameObject.SetActive(true); // 모험모드 씬을 연다 //Invoke("WaitForFadeSlider", 2.0f); } void WaitForFadeSlider() { SceneManager.LoadScene(7); } IEnumerator SceneSwap() { WaitForSeconds delay = new WaitForSeconds(0.1f); for (; ; ) { if (SceneManager.GetActiveScene().buildIndex == 1) { if (last_scene >= 5 && is_discon_byServer) { // Network_Alarm.instance.m_awake = true; //option_image.gameObject.SetActive(true); } Destroy(this.gameObject); } if (swap_scene) { SceneManager.LoadScene(scene); swap_scene = false; ////Debug.Log("Go!!"); } yield return delay; } } public void DisConnect() { SceneManager.LoadScene(1); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class PLAYER_SOUND_NUMBER { public const int ITEM_GET = 0; public const int BOMB_SET = 1; public const int MOVE = 2; } public class Player_Sound : Sound_Effect { public AudioClip[] m_AudioClips; public void Play_Item_Get_Sound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[PLAYER_SOUND_NUMBER.ITEM_GET]); } public void Play_Bomb_Set_Sound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[PLAYER_SOUND_NUMBER.BOMB_SET]); } public void Play_Move_Sound() { if (!m_is_SE_Mute && !m_AudioSource.isPlaying) m_AudioSource.PlayOneShot(m_AudioClips[PLAYER_SOUND_NUMBER.MOVE]); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Fade_Slider : MonoBehaviour { public static Fade_Slider c_Fade_Slider; bool m_is_Fade_Over = false; public bool m_is_Stage_Select_Scene = false; int m_Fade_Number = 0; bool m_is_Fade_Started = false; void Awake() { c_Fade_Slider = this; } void Update() { if (m_is_Fade_Started) // 페이드가 시작됐다면 { if (Check_Fade_Over()) // 페이드가 끝났는지 확인해서 { if (m_is_Stage_Select_Scene) // 스테이지 선택 창이면, m_is_Fade_Over = true; // 페이드 끝 알림. else gameObject.SetActive(false); // 아니면 그냥 꺼버림. } } } public void Start_Fade_Slider(int num) { m_Fade_Number = num; switch (m_Fade_Number) { case 1: gameObject.GetComponent<Animation>().Play("Fade_Slider_Animation_1"); m_is_Fade_Started = true; break; case 2: gameObject.GetComponent<Animation>().Play("Fade_Slider_Animation_2"); m_is_Fade_Started = true; break; } } bool Check_Fade_Over() { switch (m_Fade_Number) { case 1: return !gameObject.GetComponent<Animation>().IsPlaying("Fade_Slider_Animation_1"); case 2: return !gameObject.GetComponent<Animation>().IsPlaying("Fade_Slider_Animation_2"); } return false; } public bool Get_is_Fade_Over() { return m_is_Fade_Over; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Airdrop_Sound : Sound_Effect { public AudioClip m_AudioClips; public void Play_AirplaneSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; using UnityEngine.SceneManagement; //씬 전환 함수 public class SceneSwaps : MonoBehaviour { public Canvas cv; public GameObject m_Fade_UI; Normal_Fade m_Normal_Fade; IEnumerator m_WaitForFade; int m_Scene_Number; void Start() { if (m_Fade_UI != null) m_Normal_Fade = m_Fade_UI.GetComponent<Normal_Fade>(); } //쓰지 않는 함수(카메라 스위칭 함수) public void switchCamera() { cv.enabled = !cv.enabled; } // "타이틀 화면"으로 이동 public void GoTo_Title_Scene() { SceneManager.LoadScene(0); } // "모드 선택 화면"으로 이동 public void GoTo_ModeSelect_AfterFewSec() { Invoke("GoTo_ModeSelect_Scene", 1.0f); } public void GoTo_ModeSelect_Scene() { SceneManager.LoadScene(1); } public void Return_to_Mode_Select_Scene() { m_Scene_Number = 1; m_Fade_UI.SetActive(true); m_Normal_Fade.FadeOut(); m_WaitForFade = WaitForFade(); StartCoroutine(m_WaitForFade); } // "모험모드 스테이지 선택 화면"으로 이동 public void GoTo_Mode_Adventure_StageSelect_Scene() { m_Scene_Number = 2; m_Fade_UI.SetActive(true); m_Normal_Fade.FadeOut(); m_WaitForFade = WaitForFade(); StartCoroutine(m_WaitForFade); } public void GoTo_Mode_VS_Wait_Scene() { SceneManager.LoadScene(8); } public void GoTo_Mode_CoOp_Wait_Scene() { SceneManager.LoadScene(9); } // "선택한 해당 스테이지"로 이동 public void GoTo_Mode_Adventure_Selected_Stage(int stage_ID) { if (LobbySound.instanceLS != null) LobbySound.instanceLS.SoundStop(); // "맵 로드를 위한" 현재 스테이지 번호를 기록. PlayerPrefs.SetInt("Mode_Adventure_Stage_ID_For_MapLoad", stage_ID); PlayerPrefs.Save(); m_Scene_Number = 3; m_Fade_UI.SetActive(true); m_Normal_Fade.FadeOut(); m_WaitForFade = WaitForFade(); StartCoroutine(m_WaitForFade); } public void GoTo_Mode_Adventure_Selected_Stage_Forest(int stage_ID) { if (LobbySound.instanceLS != null) LobbySound.instanceLS.SoundStop(); // "맵 로드를 위한" 현재 스테이지 번호를 기록. PlayerPrefs.SetInt("Mode_Adventure_Stage_ID_For_MapLoad", stage_ID); PlayerPrefs.Save(); m_Scene_Number = 14; m_Fade_UI.SetActive(true); m_Normal_Fade.FadeOut(); m_WaitForFade = WaitForFade(); StartCoroutine(m_WaitForFade); } public void GoTo_Mode_Adventure_Selected_Stage_Ice(int stage_ID) { if (LobbySound.instanceLS != null) LobbySound.instanceLS.SoundStop(); // "맵 로드를 위한" 현재 스테이지 번호를 기록. PlayerPrefs.SetInt("Mode_Adventure_Stage_ID_For_MapLoad", stage_ID); PlayerPrefs.Save(); m_Scene_Number = 15; m_Fade_UI.SetActive(true); m_Normal_Fade.FadeOut(); m_WaitForFade = WaitForFade(); StartCoroutine(m_WaitForFade); } public void Save_Selected_Stage(int stage_ID) { // 선택한 스테이지가 몇번인지 PlayerPrefs에 기록! PlayerPrefs.SetInt("Mode_Adventure_Current_Stage_ID", stage_ID); PlayerPrefs.Save(); } IEnumerator WaitForFade() { while (true) { if (m_Normal_Fade.Get_is_Fade_Out_Over()) { StopCoroutine(m_WaitForFade); SceneManager.LoadScene(m_Scene_Number); } yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI; public class Matching_Room : MonoBehaviour { public static Matching_Room instance; public byte difficulty; public byte boss; public byte map; public byte how_many; public Text myinfo_text; public Text tier_text; public Text difficult_text; public Text nop_text; public GameObject matching_image; public GameObject matching_image_success; public GameObject matching_image_fail; public GameObject matching_image_vs_status; public GameObject matching_particles; public GameObject[] match_button; public RawImage[] player_Tier; string id_no1; string id_no2; string id_no3; string id_no4; public Text[] partnerIDtext; public RawImage tierimage_cur; public RawImage map_text; public GameObject MyInfo; public GameObject MatchingInfo; public Texture[] tierImage; public Texture[] mapimage; byte[] tier_num = new byte[4]; byte[] copy_info = new byte[87]; public byte success_Match; void Awake() { instance = this; } // Use this for initialization void Start () { tier_num[0] = 0; tier_num[1] = 0; tier_num[2] = 0; tier_num[3] = 0; boss = 0; map = 0; how_many = 2; difficulty = 0; success_Match = 0; difficult_text.text = "Easy"; difficult_text.color = new Color(1.0f, 1.0f, 1.0f); nop_text.text = "2"; nop_text.color = new Color(1.0f, 0.0f, 0.0f); map_text.texture = mapimage[0]; MyInfo.SetActive(false); MatchingInfo.SetActive(true); match_button[0].SetActive(true); match_button[1].SetActive(false); } public string GetID(int i) { switch (i) { case 1: return id_no1; case 2: return id_no2; case 3: return id_no3; case 4: return id_no4; default: return null; } } public void OutMatchingRoom() { NetManager_Coop.instance.Disconnect(); SceneChange.instance.GoTo_Select_Scene(); } public void MyPage(bool open) { if (open) { MyInfo.SetActive(true); MatchingInfo.SetActive(false); } else { MyInfo.SetActive(false); MatchingInfo.SetActive(true); } } public void SetMatchingInfo(byte[] a) { Buffer.BlockCopy(a, 2, copy_info, 0, 87); success_Match = copy_info[0]; //Debug.Log("Data Load"+success_Match); } public void MathcingCorrect(byte a) { success_Match = a; } public void SendMatching() { match_button[0].SetActive(false); match_button[1].SetActive(true); MatchingInfo.SetActive(false); NetManager_Coop.instance.SendMatchPacket(difficulty, boss, map, how_many); matching_image.SetActive(true); } public void CancelMatching() { match_button[0].SetActive(true); match_button[1].SetActive(false); MatchingInfo.SetActive(true); NetManager_Coop.instance.SendMatchPacket(difficulty, boss, map, 0); matching_image.SetActive(false); } void GoToPlay() { SceneChange.instance.GoTo_CoopBoss_Scene(); } public void ChangeNOP(bool downup) { if (downup) { if (how_many != 4) how_many++; } else { if (how_many != 2) how_many--; } switch (how_many) { case 4: nop_text.text = "4"; nop_text.color = new Color(1.0f, 1.0f, 0.0f); break; case 3: nop_text.text = "3"; nop_text.color = new Color(1.0f, 0.5f, 0.0f); break; case 2: nop_text.text = "2"; nop_text.color = new Color(1.0f, 0.0f, 0.0f); break; } } public void ChangeMap(bool downup) { if (downup) { if (map != 2) map++; } else { if (map != 0) map--; } switch (map) { case 0: map_text.texture = mapimage[0]; break; case 1: map_text.texture = mapimage[1]; break; case 2: map_text.texture = mapimage[2]; break; } } public void ChangeDifficulty(bool downup) { if (downup) { if (difficulty != 2) difficulty++; } else { if (difficulty != 0) difficulty--; } switch (difficulty) { case 0: difficult_text.text = "Easy"; difficult_text.color = new Color(1.0f, 1.0f, 1.0f); break; case 1: difficult_text.text = "Normal"; difficult_text.color = new Color(1.0f, 1.0f, 1.0f); break; case 2: difficult_text.text = "Hard"; difficult_text.color = new Color(1.0f, 0.0f, 0.0f); break; } } void VsImageOn() { VariableManager_Coop.instance.howmany = copy_info[1]; VariableManager_Coop.instance.m_roomid = copy_info[2]; for(int i = 0; i < 4; ++i) { tier_num[i] = copy_info[3+i]; } id_no1 = BitConverter.ToString(copy_info, 7, 20); id_no2 = BitConverter.ToString(copy_info, 27, 20); id_no3 = BitConverter.ToString(copy_info, 47, 20); id_no4 = BitConverter.ToString(copy_info, 67, 20); id_no1 = System.Text.Encoding.UTF8.GetString(copy_info, 7, 20); id_no2 = System.Text.Encoding.UTF8.GetString(copy_info, 27, 20); id_no3 = System.Text.Encoding.UTF8.GetString(copy_info, 47, 20); id_no4 = System.Text.Encoding.UTF8.GetString(copy_info, 67, 20); VariableManager_Coop.instance.id_list[0] = id_no1; VariableManager_Coop.instance.id_list[1] = id_no2; VariableManager_Coop.instance.id_list[2] = id_no3; VariableManager_Coop.instance.id_list[3] = id_no4; if (String.Compare(id_no1, VariableManager_Coop.instance.mystringID) == 0) { // Debug.Log("1"); VariableManager_Coop.instance.SetMyPos(1); } if (String.Compare(id_no2, VariableManager_Coop.instance.mystringID) == 0) { // Debug.Log("2"); VariableManager_Coop.instance.SetMyPos(2); } if (String.Compare(id_no3, VariableManager_Coop.instance.mystringID) == 0) { // Debug.Log("3"); VariableManager_Coop.instance.SetMyPos(3); } if (String.Compare(id_no4, VariableManager_Coop.instance.mystringID) == 0) { // Debug.Log("4"); VariableManager_Coop.instance.SetMyPos(4); } partnerIDtext[0].text = id_no1; partnerIDtext[1].text = id_no2; partnerIDtext[2].text = id_no3; partnerIDtext[3].text = id_no4; matching_image_success.SetActive(false); matching_image_vs_status.SetActive(true); matching_particles.SetActive(true); Invoke("GoToPlay", 3.0f); } // Update is called once per frame void Update () { myinfo_text.text = VariableManager_Coop.instance.GetStringID(); switch (VariableManager_Coop.instance.tier) { case 0: tier_text.text = "Bronze"; break; case 1: tier_text.text = "Silver"; break; case 2: tier_text.text = "Gold"; break; case 3: tier_text.text = "Platinum"; break; case 4: tier_text.text = "Master"; break; } for (int i = 0; i < 4; ++i) { if (tier_num[i] <= 4) { player_Tier[i].gameObject.SetActive(true); player_Tier[i].texture = tierImage[tier_num[i]]; } else player_Tier[i].gameObject.SetActive(false); } tierimage_cur.texture = tierImage[VariableManager_Coop.instance.tier]; if (success_Match==1) { Debug.Log("Match Success!!"); matching_image.SetActive(false); matching_image_success.SetActive(true); success_Match = 0; Invoke("VsImageOn", 2.0f); } else if (success_Match == 2) { matching_image.SetActive(false); matching_image_fail.SetActive(true); } } } <file_sep>using System.Collections; using System.Collections.Generic; using System; using UnityEngine; using UnityEngine.UI; public class MapManager_COop : MonoBehaviour { public static MapManager_COop instance; public GameObject m_bomb; public GameObject m_Tbomb; public GameObject[] m_box; public GameObject m_rock; public GameObject m_flame_effect; public GameObject m_bush; public GameObject m_item_speed; public GameObject m_item_bomb; public GameObject m_item_fire; public GameObject m_item_kick; public GameObject m_item_throw; public GameObject m_explode_warn_range; //public AudioSource m_audiosource; //public AudioClip[] MapSound; public GameObject[] m_tile; // public Text g_text; byte[] bombexplode_list = new byte[225]; byte[] up_bombexplode_list = new byte[225]; byte[] right_bombexplode_list = new byte[225]; byte[] down_bombexplode_list = new byte[225]; byte[] left_bombexplode_list = new byte[225]; GameObject[] bomb_list = new GameObject[225]; GameObject[] box_list = new GameObject[225]; GameObject[] rock_list = new GameObject[50]; GameObject[] bombT_list = new GameObject[32]; GameObject[] bombK_list = new GameObject[32]; GameObject[] range_List = new GameObject[225]; List<GameObject> LiveList = new List<GameObject>(); GameObject[] push_box_list = new GameObject[8]; bool[] is_alive_kick = new bool[32]; bool[] set_pos_kick = new bool[32]; int[] dx_kick = new int[32]; int[] dz_kick = new int[32]; byte[] dirc_kick = new byte[32]; int[] sx_kick = new int[32]; int[] sz_kick = new int[32]; bool[] is_alive_box = new bool[8]; bool[] set_pos_box = new bool[8]; bool[] rock_set = new bool[225]; bool[] item_set = new bool[225]; bool[] bush_set = new bool[225]; int[] dx_box = new int[8]; int[] dz_box = new int[8]; byte[] dirc_box = new byte[8]; int[] sx_box = new int[8]; int[] sz_box = new int[8]; bool[] m_is_rising_start = new bool[32]; bool[] m_is_donerising = new bool[32]; bool[] is_alive = new bool[32]; bool[] set_pos = new bool[32]; int[] dx = new int[32]; int[] dz = new int[32]; byte[] dirc = new byte[32]; int[] sx = new int[32]; int[] sz = new int[32]; GameObject[] land1 = new GameObject[225]; public GameObject parent; GameObject[] bush_list = new GameObject[50]; GameObject[] item_s_list = new GameObject[50]; GameObject[] item_f_list = new GameObject[50]; GameObject[] item_b_list = new GameObject[50]; GameObject[] item_t_list = new GameObject[50]; GameObject[] item_k_list = new GameObject[50]; byte[] copy_map_info = new byte[225]; private void Awake() { instance = this; } // Use this for initialization void Start() { //NetTest.instance.Receive(); LobbySound.instanceLS.SoundStop(); // m_audiosource.clip = MapSound[VariableManager.instance.map_type]; // m_audiosource.Play(); for (int i = 0; i < 50; ++i) { rock_list[i] = Instantiate(m_rock); rock_list[i].SetActive(false); rock_list[i].transform.parent = parent.transform; item_s_list[i] = Instantiate(m_item_speed); item_s_list[i].transform.parent = parent.transform; item_s_list[i].SetActive(false); item_f_list[i] = Instantiate(m_item_fire); item_f_list[i].transform.parent = parent.transform; item_f_list[i].SetActive(false); item_b_list[i] = Instantiate(m_item_bomb); item_b_list[i].transform.parent = parent.transform; item_b_list[i].SetActive(false); item_t_list[i] = Instantiate(m_item_throw); item_k_list[i] = Instantiate(m_item_kick); item_k_list[i].transform.parent = parent.transform; item_k_list[i].SetActive(false); item_t_list[i].SetActive(false); item_t_list[i].transform.parent = parent.transform; bush_list[i] = Instantiate(m_bush); bush_list[i].transform.parent = parent.transform; bush_list[i].SetActive(false); if (i < 32) { if (i < 8) { is_alive_box[i] = false; set_pos_box[i] = false; push_box_list[i] = Instantiate(m_box[VariableManager_Coop.instance.map_type]); push_box_list[i].transform.position = new Vector3(100, 0, 100); push_box_list[i].SetActive(false); push_box_list[i].transform.parent = parent.transform; dirc_box[i] = 0; } bombT_list[i] = Instantiate(m_Tbomb); bombT_list[i].transform.position = new Vector3(100, 0, 100); bombT_list[i].SetActive(false); bombT_list[i].transform.parent = parent.transform; bombK_list[i] = Instantiate(m_Tbomb); bombK_list[i].transform.position = new Vector3(100, 0, 100); bombK_list[i].transform.parent = parent.transform; //bombK_list[i].transform.rotation = new Quaternion(0, 0, 90.0f,0); bombK_list[i].SetActive(false); is_alive[i] = false; set_pos[i] = false; is_alive_kick[i] = false; set_pos_kick[i] = false; m_is_donerising[i] = false; m_is_rising_start[i] = true; dirc[i] = 0; dirc_kick[i] = 0; } } for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { range_List[(z * 15) + x] = Instantiate(m_explode_warn_range); range_List[(z * 15) + x].transform.position = new Vector3(x * 2, -0.7f, z * 2); range_List[(z * 15) + x].transform.parent = parent.transform; range_List[(z * 15) + x].SetActive(false); item_set[(z * 15) + x] = false; rock_set[(z * 15) + x] = false; if (((z * 15) + x) % 2 == 0) { land1[(z * 15) + x] = Instantiate(m_tile[VariableManager_Coop.instance.map_type * 2]); land1[(z * 15) + x].transform.position = new Vector3(x * 2, -0.75f, z * 2); land1[(z * 15) + x].SetActive(true); land1[(z * 15) + x].transform.parent = parent.transform; } else { land1[(z * 15) + x] = Instantiate(m_tile[(VariableManager_Coop.instance.map_type * 2) + 1]); land1[(z * 15) + x].transform.position = new Vector3(x * 2, -0.75f, z * 2); land1[(z * 15) + x].SetActive(true); land1[(z * 15) + x].transform.parent = parent.transform; } bomb_list[(z * 15) + x] = Instantiate(m_bomb); bomb_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); bomb_list[(z * 15) + x].SetActive(false); bomb_list[(z * 15) + x].transform.parent = parent.transform; box_list[(z * 15) + x] = Instantiate(m_box[VariableManager_Coop.instance.map_type]); box_list[(z * 15) + x].transform.position = new Vector3(x * 2, 0, z * 2); box_list[(z * 15) + x].SetActive(false); box_list[(z * 15) + x].transform.parent = parent.transform; bombexplode_list[(z * 15) + x] = 0; up_bombexplode_list[(z * 15) + x] = 0; down_bombexplode_list[(z * 15) + x] = 0; right_bombexplode_list[(z * 15) + x] = 0; left_bombexplode_list[(z * 15) + x] = 0; } } StartCoroutine("CheckMap_v2"); StartCoroutine("CheckFire"); } public void Push_Box_Move(int g, int x, int z, int x_dest, int z_dest, byte direction) { if (g >= 0) { float m_PushBox_Speed = 4.0f; if (x_dest == (int)push_box_list[g].gameObject.transform.position.x && z_dest == (int)push_box_list[g].gameObject.transform.position.z) { //Debug.Log(g + "번째 투척완료!!!"); push_box_list[g].gameObject.SetActive(false); is_alive_box[g] = false; NetManager_Coop.instance.SendBox_Packet(x_dest / 2, z_dest / 2); } switch (direction) { case (byte)1: ////Debug.Log("bombBombDown1"); if (push_box_list[g].gameObject.transform.position.x <= x_dest) push_box_list[g].gameObject.transform.Translate(new Vector3((m_PushBox_Speed * Time.deltaTime), 0.0f, 0.0f)); else push_box_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; case (byte)2: ////Debug.Log("bombBombDown2"); if (push_box_list[g].gameObject.transform.position.x >= x_dest) push_box_list[g].gameObject.transform.Translate(new Vector3(-(m_PushBox_Speed * Time.deltaTime), 0.0f, 0.0f)); else push_box_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; case (byte)3: ////Debug.Log("bombBombDown3"); if (push_box_list[g].gameObject.transform.position.z <= z_dest) push_box_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, (m_PushBox_Speed * Time.deltaTime))); else push_box_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; case (byte)4: ////Debug.Log("bombBombDown4"); if (push_box_list[g].gameObject.transform.position.z >= z_dest) push_box_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, -(m_PushBox_Speed * Time.deltaTime))); else push_box_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; default: //Debug.Log("bombBombDownDefault"); break; } } } public void Thrown_Bomb_Move(int g, int x, int z, int x_dest, int z_dest, byte direction) { //gBomb.gameObject.transform.position = new Vector3(x, 0, z); if (g >= 0) { float m_Rising_Limit = 4.0f; float m_Down_Limit = 0.0f; bool tempBool = false; float m_Thrown_Bomb_Speed = 15.0f; float m_Rising_Speed = 8.0f; if (bombT_list[g].gameObject.activeInHierarchy) { if (x_dest == (int)bombT_list[g].gameObject.transform.position.x && z_dest == (int)bombT_list[g].gameObject.transform.position.z && bombT_list[g].gameObject.transform.position.y == 0) { //Debug.Log(g + "번째 투척완료!!!"); bombT_list[g].gameObject.SetActive(false); m_is_rising_start[g] = true; m_is_donerising[g] = false; is_alive[g] = false; NetTest.instance.SendBomb_TCPacket(x_dest / 2, z_dest / 2); } if (m_is_rising_start[g]) { // 폭탄 일정량 상승 bombT_list[g].gameObject.transform.position = new Vector3(bombT_list[g].gameObject.transform.position.x, (bombT_list[g].gameObject.transform.position.y + (m_Rising_Speed * Time.deltaTime)), bombT_list[g].gameObject.transform.position.z); //Debug.Log("bombBombUp"); if (bombT_list[g].gameObject.transform.position.y > 2.0f) { m_is_rising_start[g] = false; //GetComponentInChildren<MeshRenderer>().enabled = true; } } else { // 폭탄 전방 이동 switch (direction) { case (byte)1: //Debug.Log("bombBombDown1"); tempBool = bombT_list[g].gameObject.transform.position.x >= x_dest - 3; if (bombT_list[g].gameObject.transform.position.x <= x_dest) bombT_list[g].gameObject.transform.Translate(new Vector3((m_Thrown_Bomb_Speed * Time.deltaTime), 0.0f, 0.0f)); else bombT_list[g].gameObject.transform.position = (new Vector3(x_dest, bombT_list[g].gameObject.transform.position.y, bombT_list[g].gameObject.transform.position.z)); break; case (byte)2: //Debug.Log("bombBombDown2"); tempBool = bombT_list[g].gameObject.transform.position.x <= x_dest + 3; if (bombT_list[g].gameObject.transform.position.x >= x_dest) bombT_list[g].gameObject.transform.Translate(new Vector3(-(m_Thrown_Bomb_Speed * Time.deltaTime), 0.0f, 0.0f)); else bombT_list[g].gameObject.transform.position = (new Vector3(x_dest, bombT_list[g].gameObject.transform.position.y, bombT_list[g].gameObject.transform.position.z)); break; case (byte)3: //Debug.Log("bombBombDown3"); tempBool = bombT_list[g].gameObject.transform.position.z >= z_dest - 3; if (bombT_list[g].gameObject.transform.position.z <= z_dest) bombT_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, (m_Thrown_Bomb_Speed * Time.deltaTime))); //else // bomb_list[g].gameObject.transform.position = (new Vector3(bomb_list[g].gameObject.transform.position.x, bomb_list[g].gameObject.transform.position.y, z_dest)); break; case (byte)4: //Debug.Log("bombBombDown4"); tempBool = bombT_list[g].gameObject.transform.position.z <= z_dest + 3; if (bombT_list[g].gameObject.transform.position.z >= z_dest) bombT_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, -(m_Thrown_Bomb_Speed * Time.deltaTime))); else bombT_list[g].gameObject.transform.position = (new Vector3(bombT_list[g].gameObject.transform.position.x, bombT_list[g].gameObject.transform.position.y, z_dest)); break; default: //Debug.Log("bombBombDownDefault"); break; } } if (!m_is_donerising[g] && bombT_list[g].gameObject.transform.position.y < m_Rising_Limit) { // 폭탄 상승 ////Debug.Log("올라간다"); bombT_list[g].gameObject.transform.Translate(new Vector3(0.0f, (m_Rising_Speed * Time.deltaTime), 0.0f)); } if (bombT_list[g].gameObject.transform.position.y >= m_Rising_Limit) { // 폭탄 상승 끝 m_is_donerising[g] = true; } //if (m_is_Done_Rising && transform.position.y > m_Down_Limit) if (m_is_donerising[g] && bombT_list[g].gameObject.transform.position.y > m_Down_Limit && tempBool) { // 폭탄 하강 // //Debug.Log("떨어진다"); bombT_list[g].gameObject.transform.Translate(new Vector3(0.0f, -(m_Rising_Speed * Time.deltaTime), 0.0f)); } if (bombT_list[g].gameObject.transform.position.y < m_Down_Limit) { bombT_list[g].gameObject.transform.position = new Vector3(bombT_list[g].gameObject.transform.position.x, 0.0f, bombT_list[g].gameObject.transform.position.z); } if (transform.position.x < -0.5f || transform.position.x > 28.5f || transform.position.z < 49.5f || transform.position.z > 78.5f) { // 맵 범위 밖으로 나가면 제거 // StageManager.Update_MCL_isBlocked(m_My_MCL_Index, false); //Destroy(gBomb); } } } } public void Kick_Bomb_Move(int g, int x, int z, int x_dest, int z_dest, byte direction) { if (g >= 0) { float m_PushBox_Speed = 15.0f; if (x_dest == (int)bombK_list[g].gameObject.transform.position.x && z_dest == (int)bombK_list[g].gameObject.transform.position.z) { //Debug.Log(g + "번째 투척완료!!!"); bombK_list[g].gameObject.SetActive(false); is_alive_kick[g] = false; NetManager_Coop.instance.SendKickCom_Packet(x_dest / 2, z_dest / 2); } switch (direction) { case (byte)1: ////Debug.Log("bombBombDown1"); if (bombK_list[g].gameObject.transform.position.x <= x_dest) { bombK_list[g].gameObject.transform.Translate(new Vector3((m_PushBox_Speed * Time.deltaTime), 0.0f, 0.0f)); } else bombK_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; case (byte)2: ////Debug.Log("bombBombDown2"); if (bombK_list[g].gameObject.transform.position.x >= x_dest) { bombK_list[g].gameObject.transform.Translate(new Vector3(-(m_PushBox_Speed * Time.deltaTime), 0.0f, 0.0f)); } else bombK_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; case (byte)3: ////Debug.Log("bombBombDown3"); if (bombK_list[g].gameObject.transform.position.z <= z_dest) { bombK_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, (m_PushBox_Speed * Time.deltaTime))); } else bombK_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; case (byte)4: ////Debug.Log("bombBombDown4"); if (bombK_list[g].gameObject.transform.position.z >= z_dest) { bombK_list[g].gameObject.transform.Translate(new Vector3(0.0f, 0.0f, -(m_PushBox_Speed * Time.deltaTime))); } else bombK_list[g].gameObject.transform.position = (new Vector3(x_dest, 0, z_dest)); break; default: //Debug.Log("bombBombDownDefault"); break; } } } public void Set_Bomb(int x, int z) { bomb_list[((z * 15) + x)].SetActive(true); } public void Check_Map(byte[] mapinfo) { Buffer.BlockCopy(mapinfo, 2, copy_map_info, 0, 225); } int GetGameObject() { for (int i = 0; i < 32; ++i) { if (!is_alive[i]) { is_alive[i] = true; ////Debug.Log("I get Bomb~To~Throw"); return i; } } return -1; } int GetKickBomb() { for (int i = 0; i < 32; ++i) { if (!is_alive_kick[i]) { is_alive_kick[i] = true; ////Debug.Log("I get Bomb~To~Throw"); return i; } } return -1; } int GetPushBox() { for (int i = 0; i < 8; ++i) { if (!is_alive_box[i]) { is_alive_box[i] = true; ////Debug.Log("I get Bomb~To~Throw"); return i; } } return -1; } public void Initialize_Map(byte[] mapinfo) { for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { byte Tile_Info2 = mapinfo[(z * 15) + (x)]; switch (Tile_Info2) { case 5: //Bomb if (!bomb_list[(z * 15) + (x)].activeInHierarchy) bomb_list[(z * 15) + (x)].SetActive(true); break; case 0: //Nothing ////Debug.Log("Nothing:" + x+","+y); break; case 1: //Cube(Box)로 if (!box_list[(z * 15) + (x)].activeInHierarchy) box_list[(z * 15) + (x)].SetActive(true); break; case 2: //Rock if (!rock_list[(z * 15) + (x)].activeInHierarchy) rock_list[(z * 15) + (x)].SetActive(true); break; case 11: //Item_Bomb if (!item_b_list[(z * 15) + (x)].activeInHierarchy) item_b_list[(z * 15) + (x)].SetActive(true); break; default: break; } } } } public void Explode_Bomb(int x, int z, byte f) { //Explode(f, bomb_list[((z * 15) + x)]); bombexplode_list[((z * 15) + x)] = f; } public void Explode_Bomb_v2(int x, int z, byte[] f) { up_bombexplode_list[((z * 15) + x)] = f[0]; right_bombexplode_list[((z * 15) + x)] = f[1]; down_bombexplode_list[((z * 15) + x)] = f[2]; left_bombexplode_list[((z * 15) + x)] = f[3]; } public bool Check_BombSet(int x, int z) { if (bomb_list[((z * 15) + x)].activeInHierarchy) return true; else return false; } public void Push_BoxSet(int x, int z, int dxx, int dzz, byte dircc) { int tempx = GetPushBox(); if (tempx >= 0) { sx_box[tempx] = x * 2; sz_box[tempx] = z * 2; dx_box[tempx] = dxx * 2; dz_box[tempx] = dzz * 2; dirc_box[tempx] = dircc; set_pos_box[tempx] = true; ////Debug.Log("SetBombThrow" +dirc[tempx]); } else { //Debug.Log("Don't have bomb"); } } public void Kick_BombSet(int x, int z, int dxx, int dzz, byte dircc) { int tempx = GetKickBomb(); if (tempx >= 0) { sx_kick[tempx] = x * 2; sz_kick[tempx] = z * 2; dx_kick[tempx] = dxx * 2; dz_kick[tempx] = dzz * 2; dirc_kick[tempx] = dircc; set_pos_kick[tempx] = true; ////Debug.Log("SetBombThrow" +dirc[tempx]); } else { //Debug.Log("Don't have bomb"); } } public void Throw_BombSet(int x, int z, int dxx, int dzz, byte dircc) { int tempx = GetGameObject(); ////Debug.Log("GetGameObjComplete"); if (tempx >= 0) { sx[tempx] = x * 2; sz[tempx] = z * 2; dx[tempx] = dxx * 2; dz[tempx] = dzz * 2; dirc[tempx] = dircc; set_pos[tempx] = true; ////Debug.Log("SetBombThrow" +dirc[tempx]); } else { //Debug.Log("Don't have bomb"); } //bombT_list[tempx].SetActive(true); } void Explode(byte fire_power, int x, int z) { range_List[(z * 15) + (x)].SetActive(false); for (byte y = 1; y <= fire_power; ++y) { if (x + y < 15) range_List[(z * 15) + (x + y)].SetActive(false); if (x - y >= 0) range_List[(z * 15) + (x - y)].SetActive(false); if (z + y < 15) range_List[((z + y) * 15) + x].SetActive(false); if (z - y >= 0) range_List[((z - y) * 15) + x].SetActive(false); } } void Explode_V2(GameObject bomb, byte up, byte right, byte down, byte left) { GameObject Instance_FlameDir_N; GameObject Instance_FlameDir_S; GameObject Instance_FlameDir_W; GameObject Instance_FlameDir_E; GameObject Instance_FlameDir_M; Instance_FlameDir_M = Instantiate(m_flame_effect); Instance_FlameDir_M.transform.position = new Vector3(bomb.transform.position.x, 0.0f, bomb.transform.position.z); for (byte i = 0; i < up; ++i) { Instance_FlameDir_N = Instantiate(m_flame_effect); Instance_FlameDir_N.transform.position = new Vector3(bomb.transform.position.x, 0.0f, bomb.transform.position.z + (2.0f * (i + 1))); } for (byte i = 0; i < down; ++i) { Instance_FlameDir_S = Instantiate(m_flame_effect); Instance_FlameDir_S.transform.position = new Vector3(bomb.transform.position.x, 0.0f, bomb.transform.position.z - (2.0f * (i + 1))); } for (byte i = 0; i < left; ++i) { Instance_FlameDir_W = Instantiate(m_flame_effect); Instance_FlameDir_W.transform.position = new Vector3(bomb.transform.position.x - (2.0f * (i + 1)), 0.0f, bomb.transform.position.z); } for (byte i = 0; i < right; ++i) { Instance_FlameDir_E = Instantiate(m_flame_effect); Instance_FlameDir_E.transform.position = new Vector3(bomb.transform.position.x + (2.0f * (i + 1)), 0.0f, bomb.transform.position.z); } MusicManager.manage_ESound.soundE2(); bomb.SetActive(false); } // Update is called once per frame void Update() { //g_text.text = "Player1 x :" + NetTest.instance.GetNetPosx(0) + ", z :" + NetTest.instance.GetNetPosz(0) + "\nPlayer2 x :" + NetTest.instance.GetNetPosx(1) + ", z:" + NetTest.instance.GetNetPosz(1) + "\nPlayer3 x :" + NetTest.instance.GetNetPosx(2) + ", z:" + NetTest.instance.GetNetPosz(2) + "\nPlayer4 x :" + NetTest.instance.GetNetPosx(3) + ", z:" + NetTest.instance.GetNetPosz(3); for (int i = 0; i < 32; ++i) { if (i < 8) { if (set_pos_box[i]) { is_alive_box[i] = true; push_box_list[i].SetActive(true); push_box_list[i].transform.position = new Vector3(sx_box[i], 0, sz_box[i]); set_pos_box[i] = false; } if (push_box_list[i].gameObject.activeInHierarchy) { Push_Box_Move(i, sx_box[i], sz_box[i], dx_box[i], dz_box[i], dirc_box[i]); } } if (set_pos_kick[i]) { is_alive_kick[i] = true; bombK_list[i].SetActive(true); bombK_list[i].transform.position = new Vector3(sx_kick[i], 0, sz_kick[i]); set_pos_kick[i] = false; } if (set_pos[i]) { ////Debug.Log("get Throw!!!!"); is_alive[i] = true; bombT_list[i].SetActive(true); bombT_list[i].transform.position = new Vector3(sx[i], 0, sz[i]); set_pos[i] = false; ////Debug.Log("Destination x: " + dx[i] + "z:" + dz[i] + "direction:" + dirc[i]); } if (bombT_list[i].gameObject.activeInHierarchy) { ////Debug.Log(dirc[i]); Thrown_Bomb_Move(i, sx[i], sz[i], dx[i], dz[i], dirc[i]); } if (bombK_list[i].gameObject.activeInHierarchy) { ////Debug.Log(dirc[i]); Kick_Bomb_Move(i, sx_kick[i], sz_kick[i], dx_kick[i], dz_kick[i], dirc_kick[i]); } } } public void GotoRoom() { //Time.timeScale = 1; //Debug.Log("Go to Room"); NetTest.instance.SendOUTPacket2(); LobbySound.instanceLS.SoundStart(); SceneChange.instance.GoTo_ModeSelect_Scene(); } public void GotoRoomWinner() { //Time.timeScale = 1; //Debug.Log("Go to Room"); NetTest.instance.SendOUTPacket2_Winner(); LobbySound.instanceLS.SoundStart(); SceneChange.instance.GoTo_ModeSelect_Scene(); } public void GotoLobby() { //Time.timeScale = 1; //Debug.Log("Go to GotoLobby"); NetTest.instance.SendOUTPacket_lose(); //난 살아있다를 증명하자 LobbySound.instanceLS.SoundStart(); SceneChange.instance.GoTo_Wait_Scene(); } public void GotoLobbyWinner() { //Time.timeScale = 1; //Debug.Log("Go to GotoLobby"); NetTest.instance.SendOUT_WinnerPacket(); //난 살아있다를 증명하자 LobbySound.instanceLS.SoundStart(); SceneChange.instance.GoTo_Wait_Scene(); } GameObject GetRock() { for (int i = 0; i < 50; ++i) { if (!rock_list[i].activeInHierarchy) return rock_list[i]; } return null; } GameObject GetBush() { for (int i = 0; i < 50; ++i) { if (!bush_list[i].activeInHierarchy) return bush_list[i]; } return null; } GameObject GetItem(int type) { switch (type) { case 1: for (int i = 0; i < 50; ++i) { if (!item_b_list[i].activeInHierarchy) return item_b_list[i]; } break; case 2: for (int i = 0; i < 50; ++i) { if (!item_f_list[i].activeInHierarchy) return item_f_list[i]; } break; case 3: for (int i = 0; i < 50; ++i) { if (!item_s_list[i].activeInHierarchy) return item_s_list[i]; } break; case 4: for (int i = 0; i < 50; ++i) { if (!item_k_list[i].activeInHierarchy) return item_k_list[i]; } break; case 5: for (int i = 0; i < 50; ++i) { if (!item_t_list[i].activeInHierarchy) return item_t_list[i]; } break; default: return null; } return null; } void DeleteItem(int x, int z) { if (LiveList.Count > 0) { for (int i = 0; i < LiveList.Count; ++i) { if (LiveList[i].activeInHierarchy && LiveList[i].transform.position.x == x * 2 && LiveList[i].transform.position.z == z * 2) { LiveList[i].SetActive(false); LiveList.Remove(LiveList[i]); } } } } IEnumerator CheckFire() { WaitForSeconds delay = new WaitForSeconds(0.1f); for (; ; ) { for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { byte fireinfo2 = VariableManager_Coop.instance.firepower_list[(z * 15) + (x)]; if (fireinfo2 != 0 && !bush_set[(z * 15) + (x)]) { range_List[(z * 15) + (x)].SetActive(true); bool upBlocked = false; bool downBlocked = false; bool rightBlocked = false; bool leftBlocked = false; for (byte y = 1; y <= fireinfo2; ++y) { if (x + y < 15 && !rightBlocked) { if (rock_set[(z * 15) + (x + y)] || box_list[(z * 15) + (x + y)].activeInHierarchy) rightBlocked = true; if (!rightBlocked) range_List[(z * 15) + (x + y)].SetActive(true); } if (x - y >= 0 && !leftBlocked) { if (rock_set[(z * 15) + (x - y)] || box_list[(z * 15) + (x - y)].activeInHierarchy) leftBlocked = true; if (!leftBlocked) range_List[(z * 15) + (x - y)].SetActive(true); } if (z + y < 15 && !upBlocked) { if (rock_set[((z + y) * 15) + x] || box_list[((z + y) * 15) + x].activeInHierarchy) upBlocked = true; if (!upBlocked) range_List[((z + y) * 15) + x].SetActive(true); } if (z - y >= 0 && !downBlocked) { if (rock_set[((z - y) * 15) + x] || box_list[((z - y) * 15) + x].activeInHierarchy) downBlocked = true; if (!downBlocked) range_List[((z - y) * 15) + x].SetActive(true); } } } //range_List } } yield return delay; } } IEnumerator CheckMap_v2() { WaitForSeconds delay = new WaitForSeconds(0.1f); for (; ; ) { for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { byte Tile_Info2 = VariableManager_Coop.instance.copy_map_info[(z * 15) + (x)]; bool tempbooleen = (down_bombexplode_list[(z * 15) + (x)] != 0) || (up_bombexplode_list[(z * 15) + (x)] != 0) || (left_bombexplode_list[(z * 15) + (x)] != 0) || (right_bombexplode_list[(z * 15) + (x)] != 0); switch (Tile_Info2) { case 5: //Bomb if (!bomb_list[(z * 15) + (x)].activeInHierarchy) { bomb_list[(z * 15) + (x)].SetActive(true); MusicManager.manage_ESound.BombSetSound2(); ////Debug.Log("Made Bomb"); }/* else if (bombexplode_list[(z * 15) + (x)] != 0) { Explode(bombexplode_list[(z * 15) + (x)], bomb_list[((z * 15) + x)]); bombexplode_list[(z * 15) + (x)] = 0; }*/ if (tempbooleen) { Explode_V2(bomb_list[((z * 15) + x)], up_bombexplode_list[((z * 15) + x)], right_bombexplode_list[((z * 15) + x)], down_bombexplode_list[((z * 15) + x)], left_bombexplode_list[((z * 15) + x)]); down_bombexplode_list[((z * 15) + x)] = 0; up_bombexplode_list[((z * 15) + x)] = 0; left_bombexplode_list[((z * 15) + x)] = 0; right_bombexplode_list[((z * 15) + x)] = 0; } break; case 0: //Nothing ////Debug.Log("Nothing:" + x+","+y); if (VariableManager_Coop.instance.firepower_list[(z * 15) + (x)] != 0) { Explode(VariableManager_Coop.instance.firepower_list[(z * 15) + (x)], x, z); VariableManager_Coop.instance.firepower_list[(z * 15) + (x)] = 0; } if (tempbooleen) { Explode_V2(bomb_list[((z * 15) + x)], up_bombexplode_list[((z * 15) + x)], right_bombexplode_list[((z * 15) + x)], down_bombexplode_list[((z * 15) + x)], left_bombexplode_list[((z * 15) + x)]); down_bombexplode_list[((z * 15) + x)] = 0; up_bombexplode_list[((z * 15) + x)] = 0; left_bombexplode_list[((z * 15) + x)] = 0; right_bombexplode_list[((z * 15) + x)] = 0; } bomb_list[((z * 15) + x)].SetActive(false); box_list[(z * 15) + (x)].SetActive(false); item_set[(z * 15) + x] = false; DeleteItem(x, z); break; case 1: //Cube(Box)로 if (!box_list[(z * 15) + (x)].activeInHierarchy) box_list[(z * 15) + (x)].SetActive(true); break; case 2: //Rock if (!rock_set[(z * 15) + (x)]) { GameObject tempb = GetRock(); tempb.SetActive(true); tempb.transform.position = new Vector3(x * 2, 0, z * 2); rock_set[(z * 15) + (x)] = true; } break; case 11: //Item_Bomb box_list[(z * 15) + (x)].SetActive(false); if (!item_set[(z * 15) + (x)]) { GameObject tempib = GetItem(1); tempib.SetActive(true); tempib.transform.position = new Vector3(x * 2, 0, z * 2); LiveList.Add(tempib); item_set[(z * 15) + (x)] = true; } break; case 3: if (!bush_set[(z * 15) + (x)]) { GameObject tempib = GetBush(); tempib.SetActive(true); tempib.transform.position = new Vector3(x * 2, -0.7f, z * 2); bush_set[(z * 15) + (x)] = true; } break; case 13: box_list[(z * 15) + (x)].SetActive(false); if (!item_set[(z * 15) + (x)]) { GameObject tempib = GetItem(2); tempib.SetActive(true); tempib.transform.position = new Vector3(x * 2, 0, z * 2); LiveList.Add(tempib); item_set[(z * 15) + (x)] = true; } break; case 12: box_list[(z * 15) + (x)].SetActive(false); if (!item_set[(z * 15) + (x)]) { GameObject tempib = GetItem(3); tempib.SetActive(true); tempib.transform.position = new Vector3(x * 2, 0, z * 2); LiveList.Add(tempib); item_set[(z * 15) + (x)] = true; } break; case 14: box_list[(z * 15) + (x)].SetActive(false); if (!item_set[(z * 15) + (x)]) { GameObject tempib = GetItem(4); tempib.SetActive(true); tempib.transform.position = new Vector3(x * 2, 0, z * 2); LiveList.Add(tempib); item_set[(z * 15) + (x)] = true; } break; case 15: box_list[(z * 15) + (x)].SetActive(false); if (!item_set[(z * 15) + (x)]) { GameObject tempib = GetItem(5); tempib.SetActive(true); tempib.transform.position = new Vector3(x * 2, 0, z * 2); LiveList.Add(tempib); item_set[(z * 15) + (x)] = true; } break; default: //rock_list[(z * 15) + (x)].SetActive(true); break; } } } yield return delay; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class BOMB_TIMER { public const float EXPLODE_TIME = 3.0f; } static class BOMB_COLLIDER_SIZE { public const float NORMAL_X = 1.8f; public const float NORMAL_Y = 1.5f; public const float NORMAL_Z = 1.8f; public const float SMALL_X = 1.2f; public const float SMALL_Y = 1.3f; public const float SMALL_Z = 1.2f; } static class THROWN_BOMB_STATE { public const int RISING = 0; public const int FALLING = 1; } static class THROWN_BOMB_VALUES { public const float IN_AIR_SPEED = 10.0f; // 체공 (상승/하강) 속도 public const float THROUGH_SPEED = 8.0f; // 체공 (진행) 속도 public const float OFFSET_Z = 0.7f; // 초기 OFFSET Z public const float OFFSET_Y = 0.4f; // 초기 OFFSET Y public const float RISING_MAX_Y = 4.0f; // 최대 높이 Y public const float RERISING_MAX_Y = 2.5f; // 최대 높이 Y public const float DEST_Z = 4.0f; // 최대 y에 도달까지 거리, 이후 낙하 완료 까지 거리 } static class KICKED_BOMB_VALUES { public const float THROUGH_SPEED = 10.0f; // 이동속도 } public class Bomb_Remaster : MonoBehaviour { public GameObject m_Bomb_Model; Shake_Checker m_Shake_Checker; Jump_Checker m_Jump_Checker; Bomb_Sound m_Bomb_Sound; GameObject m_Range_Box; public GameObject m_Center_Range; List<GameObject> m_N_Ranges; List<GameObject> m_S_Ranges; List<GameObject> m_W_Ranges; List<GameObject> m_E_Ranges; GameObject m_Fire_Box; public GameObject m_Center_Fire; public GameObject m_Fire_Object; List<GameObject> m_N_Fires; List<GameObject> m_S_Fires; List<GameObject> m_W_Fires; List<GameObject> m_E_Fires; BoxCollider m_Center_Fire_Collider; List<BoxCollider> m_N_Fire_Colliders; List<BoxCollider> m_S_Fire_Colliders; List<BoxCollider> m_W_Fire_Colliders; List<BoxCollider> m_E_Fire_Colliders; public Flame_Remains[] m_Fire_Remains; IEnumerator m_Idle_State; IEnumerator m_Thrown_State; IEnumerator m_Kicked_State; IEnumerator m_Fire_Checker; Animation m_Animations; ParticleSystem m_Center_Particle; BoxCollider m_Bomb_Collider; public void Change_Bomb_Colliders_isTrigger(bool b) { m_Bomb_Collider.isTrigger = b; } bool m_is_Set_Complete; // 설치가 완료 되었는가? Bomb_Setter m_Whose_Bomb; // 누구의 폭탄인가? GameObject m_Who_Throw; // 누가 던졌는가? GameObject m_Who_Kick; // 누가 찼는가? float m_Curr_Bomb_Timer; // 폭탄의 현재 타이머 값 float m_FireCount; int m_Curr_Thrown_State; // 현재의 던지기 상태 Vector3 m_Throw_Middle_Point; // 던지기 이후 중간지점. Vector3 m_Throw_End_Point; // 던지기 이후 종료지점. bool m_is_Thrown; // 던지기 당했는가? public bool Get_is_Thrown() { return m_is_Thrown; } bool m_is_Rising; // 상승 중인가? bool m_is_Kicked; // 발차기 당했는가? bool m_is_Hardend; // 굳혀졌는가? bool m_is_Explode; // 폭발했는가? bool m_is_Fire_Life_Over; // 불꽃의 수명이 다했는가? (불꽃 충돌체 끄기) public bool Get_is_Hardend() { return m_is_Hardend; } public void Set_is_Hardend(bool b) { m_is_Hardend = b; Change_Bomb_Colliders_isTrigger(!b); } int m_MCL_Index; // MCL 인덱스 void Awake() { m_Idle_State = Idle_State(); m_Thrown_State = Thrown_State(); m_Kicked_State = Kicked_State(); m_Fire_Checker = Fire_Check(); m_Center_Particle = m_Center_Fire.GetComponent<ParticleSystem>(); m_Animations = GetComponent<Animation>(); m_Bomb_Collider = GetComponent<BoxCollider>(); m_Bomb_Sound = GetComponentInChildren<Bomb_Sound>(); m_Shake_Checker = GetComponentInChildren<Shake_Checker>(); m_Shake_Checker.gameObject.SetActive(false); m_Jump_Checker = GetComponentInChildren<Jump_Checker>(); m_Jump_Checker.gameObject.SetActive(false); m_Curr_Bomb_Timer = 0.0f; m_is_Thrown = false; m_is_Rising = false; m_is_Kicked = false; m_is_Set_Complete = false; m_is_Explode = false; m_is_Hardend = false; m_is_Fire_Life_Over = true; Range_Object_Init(); Fire_Object_Init(); m_Bomb_Model.SetActive(false); } void OnTriggerEnter(Collider other) { if (other.CompareTag("Flame") || other.CompareTag("Flame_Remains") || other.CompareTag("Flame_Bush") || other.CompareTag("Flame_Crash") || other.CompareTag("icicle_Body")) { if (m_is_Kicked || m_is_Thrown) Set_Bomb(); Explode(); } } void OnCollisionEnter(Collision collision) { if (m_is_Kicked) { if (!m_is_Set_Complete && ( collision.gameObject.CompareTag("Box") || collision.gameObject.CompareTag("Wall") || collision.gameObject.CompareTag("Rock") || collision.gameObject.CompareTag("Bomb") || collision.gameObject.CompareTag("Monster") || collision.gameObject.CompareTag("Boss_Monster") || collision.gameObject.CompareTag("icicle_Body")) ) Set_Bomb(); } if (m_is_Thrown) { if (!m_is_Set_Complete && !m_is_Rising && ( collision.gameObject.CompareTag("Monster") || collision.gameObject.CompareTag("Boss_Monster") || collision.gameObject.CompareTag("icicle_Body")) ) Set_Bomb(); } } IEnumerator Idle_State() { while(true) { if (!StageManager.GetInstance().Get_is_Pause()) { if (m_Curr_Bomb_Timer >= BOMB_TIMER.EXPLODE_TIME) Explode(); else { m_Curr_Bomb_Timer += Time.deltaTime; m_Animations.Play("Bomb_Pumpin"); Range_Reset(); } } yield return null; } } IEnumerator Thrown_State() { while(true) { if (!StageManager.GetInstance().Get_is_Pause()) { switch (m_Curr_Thrown_State) { case THROWN_BOMB_STATE.RISING: m_Animations.Play(m_Animations.GetClip("Bomb_Rollin").name); transform.Translate(new Vector3(0.0f, THROWN_BOMB_VALUES.IN_AIR_SPEED * Time.deltaTime, THROWN_BOMB_VALUES.THROUGH_SPEED * Time.deltaTime)); if (transform.position.y >= m_Throw_Middle_Point.y - 0.05f) Set_Falling(); break; case THROWN_BOMB_STATE.FALLING: m_Animations.Play(m_Animations.GetClip("Bomb_Rollin").name); transform.Translate(new Vector3(0.0f, -THROWN_BOMB_VALUES.IN_AIR_SPEED * Time.deltaTime, THROWN_BOMB_VALUES.THROUGH_SPEED * Time.deltaTime)); if (transform.position.y <= m_Throw_End_Point.y + 0.05f) Set_Bomb(); break; } } yield return null; } } IEnumerator Kicked_State() { while (true) { if (!StageManager.GetInstance().Get_is_Pause()) { transform.Translate(new Vector3(0.0f, 0.0f, KICKED_BOMB_VALUES.THROUGH_SPEED * Time.deltaTime)); m_Animations.Play(m_Animations.GetClip("Bomb_Rollin").name); } yield return null; } } public void Throw_Bomb(GameObject who) // 폭탄 던지기 { if (!m_is_Thrown && !m_is_Kicked) { m_Who_Throw = who; m_Curr_Thrown_State = THROWN_BOMB_STATE.RISING; Set_Bomb_Off(); transform.position = m_Who_Throw.transform.position; // 포지션 전환 transform.localEulerAngles = new Vector3 (0.0f, m_Who_Throw.transform.localEulerAngles.y, 0.0f); // 방향 전환 transform.Translate(new Vector3(0.0f, THROWN_BOMB_VALUES.OFFSET_Y, THROWN_BOMB_VALUES.OFFSET_Z)); // 오프셋 적용 Set_Collider_Size_Small(); Set_Rising(THROWN_BOMB_VALUES.RISING_MAX_Y); m_is_Thrown = true; m_is_Set_Complete = false; StopCoroutine(m_Idle_State); StartCoroutine(m_Thrown_State); } } public void Drop_Bomb(GameObject who) // 폭탄 떨구기 { if (!m_is_Thrown && !m_is_Kicked) { m_Who_Throw = who; Set_Falling(); Set_Bomb_Off(); transform.position = m_Who_Throw.transform.position; // 포지션 전환 transform.localEulerAngles = new Vector3(0.0f, m_Who_Throw.transform.localEulerAngles.y, 0.0f); // 방향 전환 Set_Collider_Size_Small(); m_is_Thrown = true; m_is_Set_Complete = false; StopCoroutine(m_Idle_State); StartCoroutine(m_Thrown_State); } } public void Kick_Bomb(GameObject who) // 폭탄 발차기 { if (!m_is_Kicked && !m_is_Thrown) { m_Who_Kick = who; float rotY = m_Who_Kick.transform.localEulerAngles.y; if (rotY <= 45.0f && rotY > -45.0f) rotY = 0.0f; else if (rotY <= 135.0f && rotY > 45.0f) rotY = 90.0f; else if (rotY <= 225.0f && rotY > 135.0f) rotY = 180.0f; else rotY = 270.0f; transform.localEulerAngles = new Vector3(0.0f, rotY, 0.0f); transform.Translate(new Vector3(0.0f, 0.1f, 0.0f)); Set_Bomb_Off(); m_is_Kicked = true; m_is_Set_Complete = false; StopCoroutine(m_Idle_State); StartCoroutine(m_Kicked_State); } } public void Set_Rising(float height) { m_Throw_Middle_Point = transform.position; // 던져진 시점의 포인트 저장. m_Throw_Middle_Point.y = height; m_Throw_Middle_Point.z += THROWN_BOMB_VALUES.DEST_Z; m_is_Rising = true; m_Jump_Checker.gameObject.SetActive(false); m_Curr_Thrown_State = THROWN_BOMB_STATE.RISING; // 다음으로 간다. } public void Set_Falling() { m_Throw_End_Point = transform.position; // 던져진 시점의 포인트 저장. m_Throw_End_Point.y = 0.0f; m_Throw_End_Point.z += THROWN_BOMB_VALUES.DEST_Z; m_is_Rising = false; m_Jump_Checker.gameObject.SetActive(true); m_Curr_Thrown_State = THROWN_BOMB_STATE.FALLING; // 다음으로 간다. } void Set_Collider_Size_Small() { m_Bomb_Collider.size = new Vector3(BOMB_COLLIDER_SIZE.SMALL_X, BOMB_COLLIDER_SIZE.SMALL_Y, BOMB_COLLIDER_SIZE.SMALL_Z); } void Set_Collider_Size_Normal() { m_Bomb_Collider.size = new Vector3(BOMB_COLLIDER_SIZE.NORMAL_X, BOMB_COLLIDER_SIZE.NORMAL_Y, BOMB_COLLIDER_SIZE.NORMAL_Z); } public void Set_Bomb() // 폭탄 설치 (재조정) { m_Bomb_Model.SetActive(true); m_Bomb_Model.transform.localEulerAngles = Vector3.zero; m_Shake_Checker.gameObject.SetActive(true); m_MCL_Index = StageManager.GetInstance().Find_Own_MCL_Index(transform.position.x, transform.position.z); Vector3 pos = transform.position; pos.y = 0.0f; StageManager.GetInstance().Get_MCL_Coordinate(m_MCL_Index, ref pos.x, ref pos.z); transform.position = pos; Set_Collider_Size_Normal(); StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_Index, true); Range_Reset(); m_is_Thrown = false; m_Who_Throw = null; StopCoroutine(m_Thrown_State); m_is_Kicked = false; m_Who_Kick = null; StopCoroutine(m_Kicked_State); m_is_Set_Complete = true; StartCoroutine(m_Idle_State); } void Set_Bomb_Off() // 폭탄 해제 (기능은 살아있는 채로..) { StageManager.GetInstance().Update_MCL_isBlocked(m_MCL_Index, false); Range_OFF(); } public void Get_Out_Of_Pool(GameObject who, int state) // 풀에서 나온다! { transform.position = who.transform.position; Set_Whose_Bomb(who.GetComponent<Bomb_Setter>()); m_FireCount = m_Whose_Bomb.Get_Fire_Count(); switch (state) { case CALL_BOMB_STATE.NORMAL: Set_Bomb(); break; case CALL_BOMB_STATE.DROP: Drop_Bomb(who); break; } } public void Return_To_Pool() // 풀로 복귀시키기 전의 작업들 { Fire_OFF(); m_Whose_Bomb.GetComponent<Bomb_Setter>().Bomb_Reload(); // 주인의 폭탄 개수를 다시 채워준다. if (m_Whose_Bomb.GetComponent<Player>() != null) m_Whose_Bomb.GetComponent<Player>().UI_Status_Update(); m_Whose_Bomb = null; // 주인 마킹을 지운다. m_is_Hardend = false; // 굳히기 초기화. Change_Bomb_Colliders_isTrigger(true); // 트리거로 변경시킨다. m_Curr_Bomb_Timer = 0.0f; // 폭발 타이머 초기화. m_is_Explode = false; Set_Collider_Size_Normal(); m_Jump_Checker.gameObject.SetActive(false); StopAllCoroutines(); // 모든 행동을 멈춘다. m_Center_Particle.Stop(); // 파티클 정지 gameObject.transform.position = Vector3.zero; // 폭탄위치 초기화. Bomb_Pooling_Manager.GetInstance().Enqueue_Bomb(gameObject);// 풀에 채워넣는다. } public void Set_Whose_Bomb(Bomb_Setter who) { m_Whose_Bomb = who; } // 폭탄 주인 설정 void Range_Object_Init() // 폭발 범위 오브젝트 초기화 { m_Range_Box = new GameObject(); m_Range_Box.transform.parent = transform; m_N_Ranges = new List<GameObject>(); m_S_Ranges = new List<GameObject>(); m_W_Ranges = new List<GameObject>(); m_E_Ranges = new List<GameObject>(); Vector3 pos; float unit; for (int i = 1; i <= MAX_STATUS.FIRE; ++i) { m_N_Ranges.Add(Instantiate(m_Center_Range)); m_S_Ranges.Add(Instantiate(m_Center_Range)); m_W_Ranges.Add(Instantiate(m_Center_Range)); m_E_Ranges.Add(Instantiate(m_Center_Range)); unit = MAP_SIZE.UNIT * i; pos = transform.position; pos.y = m_Center_Range.transform.position.y; pos.z = transform.position.z + unit; m_N_Ranges[i - 1].transform.position = pos; m_N_Ranges[i - 1].transform.parent = m_Range_Box.transform; pos = transform.position; pos.y = m_Center_Range.transform.position.y; pos.z = transform.position.z - unit; m_S_Ranges[i - 1].transform.position = pos; m_S_Ranges[i - 1].transform.parent = m_Range_Box.transform; pos = transform.position; pos.y = m_Center_Range.transform.position.y; pos.x = transform.position.x - unit; m_W_Ranges[i - 1].transform.position = pos; m_W_Ranges[i - 1].transform.parent = m_Range_Box.transform; pos = transform.position; pos.y = m_Center_Range.transform.position.y; pos.x = transform.position.x + unit; m_E_Ranges[i - 1].transform.position = pos; m_E_Ranges[i - 1].transform.parent = m_Range_Box.transform; } Range_OFF(); } void Range_OFF() // 범위 끄기 { m_Center_Range.SetActive(false); for (int i = 1; i <= MAX_STATUS.FIRE; ++i) { m_N_Ranges[i - 1].SetActive(false); m_S_Ranges[i - 1].SetActive(false); m_W_Ranges[i - 1].SetActive(false); m_E_Ranges[i - 1].SetActive(false); } } void Range_Reset() // 범위 재설정 { Range_OFF(); m_Center_Range.SetActive(true); bool is_N_Blocked = false; bool is_S_Blocked = false; bool is_W_Blocked = false; bool is_E_Blocked = false; // 한번이라도 막히는 순간 더이상 진행되지 않는다! for (int i = 0; i < m_FireCount; ++i) { if (!is_N_Blocked && !StageManager.GetInstance().Get_MCL_is_Blocked_With_Coord(m_N_Ranges[i].transform.position.x, m_N_Ranges[i].transform.position.z)) m_N_Ranges[i].SetActive(true); else is_N_Blocked = true; if (!is_S_Blocked && !StageManager.GetInstance().Get_MCL_is_Blocked_With_Coord(m_S_Ranges[i].transform.position.x, m_S_Ranges[i].transform.position.z)) m_S_Ranges[i].SetActive(true); else is_S_Blocked = true; if (!is_W_Blocked && !StageManager.GetInstance().Get_MCL_is_Blocked_With_Coord(m_W_Ranges[i].transform.position.x, m_W_Ranges[i].transform.position.z)) m_W_Ranges[i].SetActive(true); else is_W_Blocked = true; if (!is_E_Blocked && !StageManager.GetInstance().Get_MCL_is_Blocked_With_Coord(m_E_Ranges[i].transform.position.x, m_E_Ranges[i].transform.position.z)) m_E_Ranges[i].SetActive(true); else is_E_Blocked = true; } } void Fire_Remains_Reset() { m_Fire_Remains[0].transform.position = Vector3.zero; m_Fire_Remains[0].gameObject.SetActive(false); m_Fire_Remains[1].transform.position = Vector3.zero; m_Fire_Remains[1].gameObject.SetActive(false); m_Fire_Remains[2].transform.position = Vector3.zero; m_Fire_Remains[2].gameObject.SetActive(false); m_Fire_Remains[3].transform.position = Vector3.zero; m_Fire_Remains[3].gameObject.SetActive(false); } void Fire_Object_Init() // 불꽃 오브젝트 초기화 { m_Fire_Box = new GameObject(); m_Fire_Box.transform.parent = transform; m_Center_Fire.SetActive(false); m_Center_Fire_Collider = m_Center_Fire.GetComponent<BoxCollider>(); m_N_Fires = new List<GameObject>(); m_S_Fires = new List<GameObject>(); m_W_Fires = new List<GameObject>(); m_E_Fires = new List<GameObject>(); m_N_Fire_Colliders = new List<BoxCollider>(); m_S_Fire_Colliders = new List<BoxCollider>(); m_W_Fire_Colliders = new List<BoxCollider>(); m_E_Fire_Colliders = new List<BoxCollider>(); Vector3 pos; float unit; for (int i = 1; i <= MAX_STATUS.FIRE; ++i) { m_N_Fires.Add(Instantiate(m_Fire_Object)); m_S_Fires.Add(Instantiate(m_Fire_Object)); m_W_Fires.Add(Instantiate(m_Fire_Object)); m_E_Fires.Add(Instantiate(m_Fire_Object)); unit = MAP_SIZE.UNIT * i; pos = transform.position; pos.y = m_Fire_Object.transform.position.y; pos.z = transform.position.z + unit; m_N_Fires[i - 1].transform.position = pos; m_N_Fires[i - 1].transform.parent = m_Fire_Box.transform; m_N_Fire_Colliders.Add(m_N_Fires[i - 1].GetComponent<BoxCollider>()); m_N_Fires[i - 1].SetActive(false); pos = transform.position; pos.y = m_Fire_Object.transform.position.y; pos.z = transform.position.z - unit; m_S_Fires[i - 1].transform.position = pos; m_S_Fires[i - 1].transform.parent = m_Fire_Box.transform; m_S_Fire_Colliders.Add(m_S_Fires[i - 1].GetComponent<BoxCollider>()); m_S_Fires[i - 1].SetActive(false); pos = transform.position; pos.y = m_Fire_Object.transform.position.y; pos.x = transform.position.x - unit; m_W_Fires[i - 1].transform.position = pos; m_W_Fires[i - 1].transform.parent = m_Fire_Box.transform; m_W_Fire_Colliders.Add(m_W_Fires[i - 1].GetComponent<BoxCollider>()); m_W_Fires[i - 1].SetActive(false); pos = transform.position; pos.y = m_Fire_Object.transform.position.y; pos.x = transform.position.x + unit; m_E_Fires[i - 1].transform.position = pos; m_E_Fires[i - 1].transform.parent = m_Fire_Box.transform; m_E_Fire_Colliders.Add(m_E_Fires[i - 1].GetComponent<BoxCollider>()); m_E_Fires[i - 1].SetActive(false); } } void Fire_OFF() // 불꽃 오브젝트 끄기 { m_Center_Fire.SetActive(false); for (int i = 0; i < m_FireCount; ++i) { m_N_Fires[i].SetActive(false); m_S_Fires[i].SetActive(false); m_W_Fires[i].SetActive(false); m_E_Fires[i].SetActive(false); } } void Fire_Collider_OFF() { m_Center_Fire_Collider.enabled = false; for (int i = 0; i < m_FireCount; ++i) { m_N_Fire_Colliders[i].enabled = false; m_S_Fire_Colliders[i].enabled = false; m_W_Fire_Colliders[i].enabled = false; m_E_Fire_Colliders[i].enabled = false; } } void Fire_ON() // 불꽃 오브젝트 켜기 { m_Center_Fire.SetActive(true); for (int i = 0; i < m_FireCount; ++i) { if (m_N_Ranges[i].activeSelf) { m_N_Fires[i].SetActive(true); m_N_Fires[i].GetComponentInChildren<ParticleSystem>().Play(); } else { m_Fire_Remains[0].gameObject.SetActive(true); m_Fire_Remains[0].GetComponent<Flame_Remains>().Cycle_Start(); m_Fire_Remains[0].transform.position = m_N_Fires[i].transform.position; break; } } for (int i = 0; i < m_FireCount; ++i) { if (m_S_Ranges[i].activeSelf) { m_S_Fires[i].SetActive(true); m_S_Fires[i].GetComponentInChildren<ParticleSystem>().Play(); } else { m_Fire_Remains[1].gameObject.SetActive(true); m_Fire_Remains[1].GetComponent<Flame_Remains>().Cycle_Start(); m_Fire_Remains[1].transform.position = m_S_Fires[i].transform.position; break; } } for (int i = 0; i < m_FireCount; ++i) { if (m_W_Ranges[i].activeSelf) { m_W_Fires[i].SetActive(true); m_W_Fires[i].GetComponentInChildren<ParticleSystem>().Play(); } else { m_Fire_Remains[2].gameObject.SetActive(true); m_Fire_Remains[2].GetComponent<Flame_Remains>().Cycle_Start(); m_Fire_Remains[2].transform.position = m_W_Fires[i].transform.position; break; } } for (int i = 0; i < m_FireCount; ++i) { if (m_E_Ranges[i].activeSelf) { m_E_Fires[i].SetActive(true); m_E_Fires[i].GetComponentInChildren<ParticleSystem>().Play(); } else { m_Fire_Remains[3].gameObject.SetActive(true); m_Fire_Remains[3].GetComponent<Flame_Remains>().Cycle_Start(); m_Fire_Remains[3].transform.position = m_E_Fires[i].transform.position; break; } } Fire_Collider_ON(); } void Fire_Collider_ON() { m_Center_Fire_Collider.enabled = true; for (int i = 0; i < m_FireCount; ++i) { m_N_Fire_Colliders[i].enabled = true; m_S_Fire_Colliders[i].enabled = true; m_W_Fire_Colliders[i].enabled = true; m_E_Fire_Colliders[i].enabled = true; } } void Explode() // 폭탄 폭발! { if (!m_is_Explode) { m_is_Explode = true; m_Bomb_Sound.Play_ExplodeSound(); m_Bomb_Model.SetActive(false); if (m_Shake_Checker.Get_Target() != null) m_Shake_Checker.Get_Target().GetComponent<Player>().Camera_Wave(); m_Shake_Checker.Set_Out_of_Range(); m_Shake_Checker.gameObject.SetActive(false); Fire_ON(); m_is_Fire_Life_Over = false; Set_Bomb_Off(); m_Center_Particle.Play(); StopCoroutine(m_Idle_State); StartCoroutine(m_Fire_Checker); } } IEnumerator Fire_Check() { while (true) { if (m_Center_Particle.time >= m_Center_Particle.main.duration) // 불꽃 연출이 끝났다면 { Return_To_Pool(); // 폭탄을 풀로 돌려보낸다. } else if (!m_is_Fire_Life_Over && m_Center_Particle.time >= m_Center_Particle.main.duration * 0.6f) { Fire_Collider_OFF(); m_is_Fire_Life_Over = true; } yield return null; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; // MCL에 들어갈 좌표 구조체 public class StageManager : MonoBehaviour { // ================================ // =========== 프리팹들 =========== // 오브젝트 프리팹들 public GameObject m_Prefab_Box; public GameObject m_Prefab_Rock; public GameObject m_Prefab_Grass; public GameObject m_Prefab_Goblin; public GameObject m_Prefab_Goblin_Boss; public GameObject m_Prefab_Start_Point; public GameObject m_Prefab_Next_Portal; public GameObject m_Prefab_End_Portal; //public GameObject m_Prefab_Chractrer_Spawn; public GameObject m_Prefab_Ork_Boss; public GameObject m_Prefab_Airplane; public GameObject m_Prefab_Item_Bomb; public GameObject m_Prefab_Item_Speed; public GameObject m_Prefab_Item_Fire; public GameObject m_Prefab_Item_Kick; public GameObject m_Prefab_Item_Throw; public GameObject m_Prefab_Info_Trigger_Bomb; public GameObject m_Prefab_Info_Trigger_Speed; public GameObject m_Prefab_Info_Trigger_Fire; public GameObject m_Prefab_Info_Trigger_Kick; public GameObject m_Prefab_Info_Trigger_Throw; public GameObject m_Prefab_Box_None_Item; public GameObject m_Prefab_Icicle; public GameObject m_Prefab_Ice_Box_1; public GameObject m_Prefab_Ice_Box_2; public GameObject m_Prefab_Ice_Box_3; public GameObject m_Prefab_Ice_Rock; // ================================ // ===== 생성한 오브젝트 관리 ===== List<GameObject> m_Current_Map_Objects = new List<GameObject>(); // 테이블을 통해 현재 맵에 생성된 오브젝트들 + 비행기 int m_Current_Map_Objects_Count; // 생성된 오브젝트 개수 int m_Current_Stage_index_Count = 0; // 현재 스테이지의 맵 인덱스 카운트 Vector3 m_Object_Position; // 오브젝트 생성시 위치 변경에 이용할 벡터 // ================================ // =========== UI 관련 ============ int m_Star_Count = 0; // 획득한 별 개수 int m_Total_Monster_Count = 0; // 총 스폰된 일반 몹 수 int m_Left_Monster_Count = 0; // 남은 일반 몹 수 // ================================== // =========== 보스관련 ============= bool m_is_Boss_Stage; // 현재 스테이지가 보스전인가? public int m_Boss_ID; // 보스 테이블 번호 (*** 디버깅용 public ***) // -1로 설정시 테이블에 따른다. public GameObject m_SuddenDeath_JetGoblin; // 서든데스 고블맨 객체 bool m_is_Boss_Dead; // 보스 스테이지의 보스 몬스터가 죽었는가? bool m_is_SuddenDeath_Summoned = false; public GameObject m_Boss_HP_Bar; // ================================== // ========== 시스템관련 ============ static StageManager m_Instance; public static StageManager GetInstance() { return m_Instance; } [HideInInspector] public List<Map_Coordinate> m_Map_Coordinate_List; // MCL [HideInInspector] public List<bool> m_MCL_is_Blocked_List; // MCL의 is_Blocked를 따로 분리했다.. [HideInInspector] public bool m_is_init_MCL = false; // MCL이 초기화 되었는가? public int m_Stage_ID; // 현재 스테이지 번호 (*** 디버깅용 public ***) public float m_Stage_Time_Limit; // 현재 스테이지의 제한시간 // 디버깅용 변수이며, -1로 설정할 경우 기획 설정(테이블)에 따른다 bool m_is_Intro_Over = false; // 인트로가 끝났는가? bool m_is_Pause = false; // 게임이 일시정지 되었는가? bool m_is_Goal_In = false; // 목표 지점에 들어갔는가? bool m_is_Stage_Clear = false; // 스테이지를 클리어했는가? bool m_is_Game_Over = false; // 게임이 끝났는가? bool m_is_Player_Alive = true; // 맵 사이즈 int m_Map_Size_X = 17; int m_Map_Size_Z = 17; public GameObject m_Direction_Camera; // 연출용 카메라 // ================================ // =========== CSV 관련 =========== // 현재 스테이지의 퀘스트 목록 List<Adventure_Quest_Data> m_QuestList = new List<Adventure_Quest_Data>(); // 오브젝트 테이블 List<Object_Table_Data> m_Object_Table_List; // 현재 스테이지의 오브젝트 배치 목록 List<Object_Spawn_Position_Data> m_Object_Spawn_Position_List = new List<Object_Spawn_Position_Data>(); // 보스 스테이터스 데이터 Adventure_Boss_Data m_Adventure_Boss_Data = new Adventure_Boss_Data(); // 스테이지 데이터 Adventure_Stage_Data m_Adventure_Stage_Data = new Adventure_Stage_Data(); IEnumerator m_StageManager; bool m_is_Block_Object = false; // ================================ // =========== Methods ============ void Awake() // 생성자 { Screen.SetResolution(1280, 720, true); m_Instance = this; // 스테이지 매니저 인스턴스 지정 m_StageManager = StageManagement(); // 스테이지 관리 코루틴 StartCoroutine(m_StageManager); // 스테이지 관리 코루틴 시작. m_Map_Coordinate_List = new List<Map_Coordinate>(); m_MCL_is_Blocked_List = new List<bool>(); MCL_init(); // MCL 초기화 m_Object_Table_List = new List<Object_Table_Data>(CSV_Manager.GetInstance().Get_Object_Table_List()); // 오브젝트 테이블 목록 로드 if (m_Stage_ID == -1) m_Stage_ID = PlayerPrefs.GetInt("Mode_Adventure_Current_Stage_ID"); // 스테이지 ID를 받아온다. m_Adventure_Stage_Data.Adventure_Quest_ID_List = new int[3]; m_Adventure_Stage_Data.Stage_Pattern_ID_List = new int[3]; CSV_Manager.GetInstance().Get_Adventure_Stage_Data(ref m_Adventure_Stage_Data, m_Stage_ID); // 스테이지 테이블 데이터 로드 CSV_Manager.GetInstance().Get_Adventure_Quest_List(ref m_QuestList, ref m_Adventure_Stage_Data.Adventure_Quest_ID_List); // 퀘스트 데이터 로딩 Boss_Stage_Setting(); // 보스 스테이지인지 검사 후 설정. (브금 까지) Create_Map(m_Adventure_Stage_Data.Stage_Pattern_ID_List[m_Current_Stage_index_Count]); // 설정된 번호를 받아서 맵 생성! if (m_Stage_Time_Limit == -1) m_Stage_Time_Limit = m_Adventure_Stage_Data.Stage_Time; // 시간 설정 Intro_Direction_Play(); // 인트로 연출 시작 } void Start() { // 페이드 인 if (Fade_Slider.c_Fade_Slider != null) Fade_Slider.c_Fade_Slider.Start_Fade_Slider(2); } IEnumerator StageManagement() { while (true) { Check_GameOver(); yield return null; } } void Intro_Direction_Play() { if (!m_is_Boss_Stage) m_Direction_Camera.GetComponentInChildren<Camera_Directing>().Direction_Play(DIRECTION_NUMBER.INTRO_NORMAL_1); else m_Direction_Camera.GetComponentInChildren<Camera_Directing>().Direction_Play(DIRECTION_NUMBER.INTRO_BOSS_1); } void Boss_Stage_Setting() { m_Boss_HP_Bar.SetActive(false); Audio_Manager.GetInstance().BGM_Play(BGM_NUMBER.NORMAL); // 일반 스테이지 BGM 재생. if (m_Boss_ID == -1) // 설정이 안돼있다면 { foreach (Adventure_Quest_Data questdata in m_QuestList) // 현재 스테이지의 퀘스트를 뒤져본다 { if (questdata.Quest_ID == 4) // 퀘스트 목록에 "보스 몬스터 처치"가 있다면 { m_is_Boss_Stage = true; // 해당 스테이지는 보스 스테이지라는 뜻! m_Boss_HP_Bar.SetActive(true); Audio_Manager.GetInstance().BGM_Play(BGM_NUMBER.BOSS); // 보스 스테이지 BGM 재생. // 보스 테이블의 번호를 설정 if (m_Stage_ID == 5) m_Boss_ID = 1; else if (m_Stage_ID == 9) m_Boss_ID = 2; else if (m_Stage_ID == 14) m_Boss_ID = 3; else if (m_Stage_ID == 19) m_Boss_ID = 4; } } } } // ===================================================== // ==================== 맵 관련 ======================== void Create_Map(int stage_id) // 맵 생성 및 설정 { // 오브젝트 스폰 위치 목록을 받아온다. CSV_Manager.GetInstance().Get_Object_Spawn_Position_List(ref m_Object_Spawn_Position_List, stage_id); m_Current_Map_Objects_Count = 0; int index = 0; // 위치에 맞게 오브젝트를 생성한다. for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { if (m_Object_Spawn_Position_List[z].Spawn_Node[x] != 0) { // x, z 좌표 설정 m_Object_Position.x = x * 2.0f; m_Object_Position.z = 78.0f - (z * 2.0f); switch (m_Object_Spawn_Position_List[z].Spawn_Node[x]) { case OBJECT_TABLE_NUMBER.BOX: // 박스 m_Current_Map_Objects.Add(Instantiate(m_Prefab_Box)); m_Object_Position.y = m_Prefab_Box.transform.position.y; m_is_Block_Object = true; break; case OBJECT_TABLE_NUMBER.ROCK: // 바위 m_Current_Map_Objects.Add(Instantiate(m_Prefab_Rock)); m_Object_Position.y = m_Prefab_Rock.transform.position.y; m_is_Block_Object = true; break; case OBJECT_TABLE_NUMBER.GRASS: // 부쉬 m_Current_Map_Objects.Add(Instantiate(m_Prefab_Grass)); m_Object_Position.y = m_Prefab_Grass.transform.position.y; break; case OBJECT_TABLE_NUMBER.GOBLIN: // 일반 고블린 m_Current_Map_Objects.Add(Instantiate(m_Prefab_Goblin)); m_Object_Position.y = m_Prefab_Goblin.transform.position.y; break; case OBJECT_TABLE_NUMBER.BOSS_GOBLIN: // 보스 고블린 break; case OBJECT_TABLE_NUMBER.START_POINT: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Start_Point)); m_Object_Position.y = m_Prefab_Start_Point.transform.position.y; break; case OBJECT_TABLE_NUMBER.NEXT_POINT: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Next_Portal)); m_Object_Position.y = m_Prefab_Next_Portal.transform.position.y; break; case OBJECT_TABLE_NUMBER.END_POINT: m_Current_Map_Objects.Add(Instantiate(m_Prefab_End_Portal)); m_Object_Position.y = m_Prefab_End_Portal.transform.position.y; break; case OBJECT_TABLE_NUMBER.CHARACTER_SPAWN: //m_Current_Map_Objects.Add(Instantiate(m_Prefab_Character_Spawn)); //m_Object_Position.y = m_Prefab_Character_Spawn.transform.position.y; break; case OBJECT_TABLE_NUMBER.BOSS_GIANT_1: // 보스 데이터 읽어오기 CSV_Manager.GetInstance().Get_Adventure_Boss_Data(ref m_Adventure_Boss_Data, m_Boss_ID); // 생성 m_Current_Map_Objects.Add(Instantiate(m_Prefab_Ork_Boss)); m_Object_Position.y = m_Prefab_Ork_Boss.transform.position.y; break; case OBJECT_TABLE_NUMBER.ITEM_BOMB: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Item_Bomb)); m_Object_Position.y = m_Prefab_Item_Bomb.transform.position.y; break; case OBJECT_TABLE_NUMBER.ITEM_SPEED: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Item_Speed)); m_Object_Position.y = m_Prefab_Item_Speed.transform.position.y; break; case OBJECT_TABLE_NUMBER.ITEM_FIRE: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Item_Fire)); m_Object_Position.y = m_Prefab_Item_Fire.transform.position.y; break; case OBJECT_TABLE_NUMBER.ITEM_KICK: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Item_Kick)); m_Object_Position.y = m_Prefab_Item_Kick.transform.position.y; break; case OBJECT_TABLE_NUMBER.ITEM_THROW: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Item_Throw)); m_Object_Position.y = m_Prefab_Item_Throw.transform.position.y; break; case OBJECT_TABLE_NUMBER.INFO_TRIGGER_BOMB: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Info_Trigger_Bomb)); m_Object_Position.y = m_Prefab_Info_Trigger_Bomb.transform.position.y; break; case OBJECT_TABLE_NUMBER.INFO_TRIGGER_SPEED: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Info_Trigger_Speed)); m_Object_Position.y = m_Prefab_Info_Trigger_Speed.transform.position.y; break; case OBJECT_TABLE_NUMBER.INFO_TRIGGER_FIRE: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Info_Trigger_Fire)); m_Object_Position.y = m_Prefab_Info_Trigger_Fire.transform.position.y; break; case OBJECT_TABLE_NUMBER.INFO_TRIGGER_KICK: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Info_Trigger_Kick)); m_Object_Position.y = m_Prefab_Info_Trigger_Kick.transform.position.y; break; case OBJECT_TABLE_NUMBER.INFO_TRIGGER_THROW: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Info_Trigger_Throw)); m_Object_Position.y = m_Prefab_Info_Trigger_Throw.transform.position.y; break; case OBJECT_TABLE_NUMBER.BOX_NONE_ITEM: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Box_None_Item)); m_Object_Position.y = m_Prefab_Box_None_Item.transform.position.y; m_is_Block_Object = true; break; case OBJECT_TABLE_NUMBER.ICICLE_1: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Icicle)); m_Current_Map_Objects[m_Current_Map_Objects_Count].GetComponent<Icicle>().Start_With_Offset_Time(ICICLE_OFFSET_TIME.ICICLE_1); m_Object_Position.y = m_Prefab_Icicle.transform.position.y; break; case OBJECT_TABLE_NUMBER.ICICLE_2: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Icicle)); m_Current_Map_Objects[m_Current_Map_Objects_Count].GetComponent<Icicle>().Start_With_Offset_Time(ICICLE_OFFSET_TIME.ICICLE_2); m_Object_Position.y = m_Prefab_Icicle.transform.position.y; break; case OBJECT_TABLE_NUMBER.ICE_BOX_1: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Ice_Box_1)); m_Current_Map_Objects[m_Current_Map_Objects_Count].GetComponent<Ice_Box>().Set_Crash_Count(1); m_Object_Position.y = m_Prefab_Icicle.transform.position.y; m_is_Block_Object = true; break; case OBJECT_TABLE_NUMBER.ICE_BOX_2: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Ice_Box_2)); m_Current_Map_Objects[m_Current_Map_Objects_Count].GetComponent<Ice_Box>().Set_Crash_Count(2); m_Object_Position.y = m_Prefab_Icicle.transform.position.y; m_is_Block_Object = true; break; case OBJECT_TABLE_NUMBER.ICE_BOX_3: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Ice_Box_3)); m_Current_Map_Objects[m_Current_Map_Objects_Count].GetComponent<Ice_Box>().Set_Crash_Count(3); m_Object_Position.y = m_Prefab_Icicle.transform.position.y; m_is_Block_Object = true; break; case OBJECT_TABLE_NUMBER.ICE_ROCK: m_Current_Map_Objects.Add(Instantiate(m_Prefab_Ice_Rock)); m_Object_Position.y = m_Prefab_Icicle.transform.position.y; m_is_Block_Object = true; break; } // 생성한 객체 좌표 이동 m_Current_Map_Objects[m_Current_Map_Objects_Count].transform.position = m_Object_Position; if (m_is_Block_Object) { index = Find_Own_MCL_Index(m_Current_Map_Objects[m_Current_Map_Objects_Count].transform.position.x, m_Current_Map_Objects[m_Current_Map_Objects_Count].transform.position.z); Update_MCL_isBlocked(index, true); m_is_Block_Object = false; } ++m_Current_Map_Objects_Count; // 카운트 증가 } } } Airplane_Object_Spawn(); // 에어드랍 비행기 객체 소환 } public void Next_Map_Load() // 다음 맵 불러오기 { ++m_Current_Stage_index_Count; // 다음 맵 번호를 지정하고 if (m_Adventure_Stage_Data.Stage_Pattern_ID_List[m_Current_Stage_index_Count] != 0) // 리스트에 맵 번호가 있으면 시작 { Destroy_Objects(); // 남아있는 오브젝트들을 제거한다. MCL_init(); // MCL을 재설정한다. Create_Map(m_Adventure_Stage_Data.Stage_Pattern_ID_List[m_Current_Stage_index_Count]); // 새 맵을 생성! } } void Airplane_Object_Spawn() { GameObject airplane = Instantiate(m_Prefab_Airplane); // 인스턴스 생성 airplane.GetComponent<Airplane>().Set_Airdrop_Count(m_Adventure_Stage_Data.Number_Of_DropItem); // 드랍 개수 설정 } // ===================================================== // ==================== MCL 관련 ======================= void MCL_init() // MCL 좌표 및 is_Blocked 초기화 { m_Map_Coordinate_List.Clear(); m_MCL_is_Blocked_List.Clear(); Map_Coordinate m_tmpCoordinate; for (int i = -1; i < m_Map_Size_X - 1; ++i) { for (int j = -1; j < m_Map_Size_Z - 1; ++j) { m_tmpCoordinate.x = i * 2; m_tmpCoordinate.z = j * 2 + 50; m_Map_Coordinate_List.Add(m_tmpCoordinate); m_MCL_is_Blocked_List.Add(false); } } for (int i = 0; i < 17; ++i) { // z라인 울타리 Update_MCL_isBlocked(i, true); Update_MCL_isBlocked(i + 272, true); // x라인 울타리 Update_MCL_isBlocked(i * 17, true); Update_MCL_isBlocked(i * 17 + 16, true); } m_is_init_MCL = true; } public bool Get_is_init_MCL() // MCL이 초기화 되었는가를 반환 { return m_is_init_MCL; } public void Update_MCL_isBlocked(int index, bool isBlocked) // isBlocked 갱신 메소드 { if (index != -1) { m_MCL_is_Blocked_List[index] = isBlocked; } } public bool Get_MCL_index_is_Blocked(int index) // MCL 안의 해당 index가 막혀있는지를 반환해준다. { return m_MCL_is_Blocked_List[index]; } public void Get_MCL_Coordinate(int index, ref float x, ref float z) // 인덱스에 따른 위치로 설정해준다. { x = m_Map_Coordinate_List[index].x; z = m_Map_Coordinate_List[index].z; } public int Find_Own_MCL_Index(float x, float z) // 받아온 좌표로 MCL 인덱스를 반환해준다. { Map_Coordinate m_tmpCoordinate; // 받아온 좌표에서 가장 가까운 좌표로 설정한다. int index_X = (int)x; int index_Z = (int)z; if (index_X % 2 == 1) { m_tmpCoordinate.x = index_X + 1; } else if (index_X % 2 == -1) { m_tmpCoordinate.x = index_X - 1; } else m_tmpCoordinate.x = index_X; if (index_Z % 2 == 1) { m_tmpCoordinate.z = index_Z + 1; } else if (index_Z % 2 == -1) { m_tmpCoordinate.z = index_Z - 1; } else m_tmpCoordinate.z = index_Z; // 속한 좌표의 인덱스를 뽑아서 반환한다. return m_Map_Coordinate_List.IndexOf(m_tmpCoordinate); } public bool Get_MCL_is_Blocked_With_Coord(float x, float z) { if (Find_Own_MCL_Index(x, z) == -1) return true; // 없는 범위는 막힌것으로 간주한다. return Get_MCL_index_is_Blocked(Find_Own_MCL_Index(x, z)); // 있는 범위는 정상적으로 판단한다. } // ===================================================== // =================== 시스템 관련 ===================== public void Stage_Clear() // 스테이지 클리어시 호출 { m_is_Stage_Clear = true; // 스테이지 클리어라고 알림! m_is_Pause = true; // 일시정지 시킨다. Condition_For_Getting_Stars(ref m_Adventure_Stage_Data.Adventure_Quest_ID_List); // 별 획득 조건 체크 및 저장 // 현재 스테이지가 플레이 가능 최대 스테이지라면 int tempMaxStage = PlayerPrefs.GetInt("Mode_Adventure_Playable_Max_Stage"); if (PlayerPrefs.GetInt("Mode_Adventure_Current_Stage_ID") == tempMaxStage) { tempMaxStage += 1; // 최대 스테이지 범위 내에서 플레이가능 최대 스테이지 증가! if (tempMaxStage <= PlayerPrefs_Manager_Constants.MAX_STAGE_NUM) { PlayerPrefs.SetInt("Mode_Adventure_Playable_Max_Stage", tempMaxStage); } } PlayerPrefs.Save(); } void Condition_For_Getting_Stars(ref int[] list) // 별 획득 조건 관리 { foreach (Adventure_Quest_Data QuestData in m_QuestList) { string tempString; for (int i = 0; i < 3; ++i) { if (QuestData.ID == list[i]) { if (QuestData.Quest_ID == 1) // 시간 { if (UI.GetInstance().Get_Left_Time() >= QuestData.Quest_Goal) { m_Star_Count += 1; tempString = "Adventure_Stars_ID_" + list[i]; PlayerPrefs.SetInt(tempString, 1); } } else if (QuestData.Quest_ID == 2) // 일반몹처치 { if (m_Total_Monster_Count - m_Left_Monster_Count >= QuestData.Quest_Goal) { m_Star_Count += 1; tempString = "Adventure_Stars_ID_" + list[i]; PlayerPrefs.SetInt(tempString, 1); } } else if (QuestData.Quest_ID == 3) // 목표지점 { if (m_is_Goal_In) { m_Star_Count += 1; tempString = "Adventure_Stars_ID_" + list[i]; PlayerPrefs.SetInt(tempString, 1); } } else if (QuestData.Quest_ID == 4) // 보스처치 { if (m_is_Boss_Dead) { m_Star_Count += 1; tempString = "Adventure_Stars_ID_" + list[i]; PlayerPrefs.SetInt(tempString, 1); } } } } } PlayerPrefs.Save(); } public bool Get_is_Stage_Clear() // 스테이지가 클리어 되었는가를 반환 { return m_is_Stage_Clear; } public void Set_is_Pause(bool b) // 일시정지 여부를 설정 { m_is_Pause = b; } public bool Get_is_Pause() // 일시정지인가를 반환 { return m_is_Pause; } public void Set_is_Intro_Over(bool b) // 인트로 모션 수행 여부를 설정 { m_is_Intro_Over = b; } public bool Get_is_Intro_Over() // 인트로 모션 수행 여부를 반환 { return m_is_Intro_Over; } public void Set_is_Player_Alive(bool b) { m_is_Player_Alive = b; } void Check_GameOver() // 게임오버인지 체크하여 설정 { if (!m_is_Player_Alive) // 죽어서 끝났거나, { UI.GetInstance().GameOver_Directing(); Set_Game_Over(); } else if (m_is_Stage_Clear) // 클리어해서 끝났거나! { UI.GetInstance().Stage_Clear_Directing(); Set_Game_Over(); } } public void Set_Game_Over() { m_is_Game_Over = true; m_is_Pause = true; Audio_Manager.GetInstance().Sound_Fadeout_Start(); StopCoroutine(m_StageManager); } public bool Get_Game_Over() // 게임오버인가를 반환 { return m_is_Game_Over; } public bool Get_is_Boss_Stage() // 현재 스테이지가 보스 스테이지인지를 반환 { return m_is_Boss_Stage; } public void SetBossDead(bool b) // 보스가 죽었는지를 설정 { m_is_Boss_Dead = b; } public bool GetBossDead() // 보스가 죽었는지를 반환 { return m_is_Boss_Dead; } public void SetGoalIn(bool b) // 목표지점에 도달했는지를 설정 { m_is_Goal_In = b; } public void Summon_SuddenDeath_Glider() // 서든데스 고블린 소환 { if (!m_is_SuddenDeath_Summoned && UI.GetInstance().Get_Left_Time() <= m_Stage_Time_Limit - m_Adventure_Stage_Data.SuddenDeath_Time) { Notice_UI.GetInstance().Notice_Play(NOTICE_NUMBER.DANGER); for (int i = 0; i < m_Adventure_Stage_Data.Number_Of_GliderGoblin; ++i) Instantiate(m_SuddenDeath_JetGoblin).GetComponent<Jet_Goblin>().Set_Bomb_info(m_Adventure_Stage_Data.GliderGoblin_Bomb, m_Adventure_Stage_Data.GliderGoblin_Fire, 12.0f); m_is_SuddenDeath_Summoned = true; } } public float Get_AirDrop_Time() { return m_Adventure_Stage_Data.AirDrop_Time; } public void Increase_Normal_Monster_Count() // 일반몹 개수 증가시키기 { ++m_Total_Monster_Count; ++m_Left_Monster_Count; } public void Decrease_Normal_Monster_Count() { --m_Left_Monster_Count; } public int Get_Left_Normal_Monster_Count() // 남은 일반몹 수 반환 { return m_Total_Monster_Count - m_Left_Monster_Count; } public void Init_Left_Time() // UI에 제한시간 설정 { UI.GetInstance().Set_Left_Time(m_Stage_Time_Limit); } public int Get_Star_Count() // 획득한 별 개수 반환 { return m_Star_Count; } public void Destroy_Objects() // 씬전환 이전에 객체들을 제거한다. { // 테이블로 생성했던 오브젝트들을 제거 foreach (GameObject g in m_Current_Map_Objects) { if (g != null) Destroy(g); } m_Current_Map_Objects.Clear(); // 폭탄들 풀로 복귀 GameObject[] bombs = GameObject.FindGameObjectsWithTag("Bomb"); foreach (GameObject b in bombs) b.GetComponent<Bomb_Remaster>().Return_To_Pool(); // 불 붙은 부쉬의 파티클도 제거 //GameObject[] fBushs = GameObject.FindGameObjectsWithTag("Flame_Bush_Particle"); //foreach (GameObject fb in fBushs) // Destroy(fb); // 동적생성 아이템들도 제거 GameObject[] items = GameObject.FindGameObjectsWithTag("Bomb_Item"); foreach (GameObject i in items) Destroy(i); items = GameObject.FindGameObjectsWithTag("Fire_Item"); foreach (GameObject i in items) Destroy(i); items = GameObject.FindGameObjectsWithTag("Speed_Item"); foreach (GameObject i in items) Destroy(i); items = GameObject.FindGameObjectsWithTag("Kick_Item"); foreach (GameObject i in items) Destroy(i); items = GameObject.FindGameObjectsWithTag("Throw_Item"); foreach (GameObject i in items) Destroy(i); items = GameObject.FindGameObjectsWithTag("Airdrop_Item"); foreach (GameObject i in items) Destroy(i); } public int Get_Boss_ID() { return m_Boss_ID; } // ===================================================== // ================ 테이블 데이터 관련 ================= public void GetQuestList(ref List<Adventure_Quest_Data> list) // 퀘스트 내용 리스트를 리턴해준다. (UI에 띄우기 위해) { list = m_QuestList; } public Adventure_Boss_Data Get_Adventure_Boss_Data() // 보스 데이터를 리턴해준다. { return m_Adventure_Boss_Data; } public float Get_Boss_HP() { return m_Adventure_Boss_Data.Boss_HP; } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class TeamChange : MonoBehaviour { public Material[] team_material; //public GameObject[] team_turtle; Renderer rend; // Use this for initialization void Start () { rend = GetComponent<Renderer>(); rend.sharedMaterial = team_material[0]; } // Update is called once per frame void Update () { rend.sharedMaterial = team_material[VariableManager.instance.myteam]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class ORK_BOSS_SOUND_NUMBER { public const int IDLE = 0; public const int ATTACK = 1; public const int HURT = 2; public const int DEAD = 3; } public class Ork_Boss_Sound : Sound_Effect { public AudioClip[] m_AudioClips; public void Play_IdleSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[ORK_BOSS_SOUND_NUMBER.IDLE]); } public void Play_AttackSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[ORK_BOSS_SOUND_NUMBER.ATTACK]); } public void Play_HurtSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[ORK_BOSS_SOUND_NUMBER.HURT]); } public void Play_DeadSound() { if (!m_is_SE_Mute) m_AudioSource.PlayOneShot(m_AudioClips[ORK_BOSS_SOUND_NUMBER.DEAD]); } } <file_sep> #include "protocol.h" #include <mysql.h> HANDLE gh_iocp; DWORD g_prevTime2; //GetTickCount()를 활용한 시간을 체크할 때 사용할 함수 TB_Room room; array <Client, MAX_USER> g_clients; map<BYTE, TB_Room> room_Map; map<BYTE, InGameCalculator> gameRoom_Manager; Map_TB g_TB_Map[3][4]; MYSQL* conn_ptr=NULL; MYSQL_RES* result_sql=NULL; MYSQL_ROW row=NULL; list<TB_Room> room_page; void SetMap(BYTE, BYTE, BYTE, TB_Map*); void SetMapToValue(int, int); void Throw_Calculate_Map(int x, int z, BYTE room_num, TB_ThrowBombRE* temppacket, BYTE direction, TB_MapSetRE* tempp); void BoxPush_Calculate_Map(int x, int z, BYTE room_num, TB_BoxPushRE* temppacket, BYTE direction, TB_MapSetRE* tempp); void Kick_CalculateMap(int x, int z, BYTE room_num, TB_KickBombRE* temppacket, BYTE direction, TB_MapSetRE* tempp); void CopyRoomAtoB(TB_Room* a, TB_RoomInfo*b); void Timer_thread(); void error_display(const char *msg, int err_no) { WCHAR *lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, err_no, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); std::cout << msg; std::wcout << L" 에러" << lpMsgBuf << std::endl; LocalFree(lpMsgBuf); while (true); } void ErrorDisplay(const char *location) { error_display(location, WSAGetLastError()); } void initialize() { for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) SetMapToValue(i, j); } //맵 데이터를 txt파일에서 불러와서 배열값에 지정. gh_iocp = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); /* 의미없는 파라메터, 마지막은 알아서 쓰레드를 만들어준다. 지정된 파일에 대해서 input/output completion port를 만든다. // 파라미터 1. 핸들 변수,INVALID_HANDLE_VALUE 열린 파일이라면 중첩 입출력을 지원하는 객체여야 한다. 파라미터 2. 이미 만들어진 입출력 완료 포트 혹은 NULL, 이미 만들어진 입출력 완료포트 지정 시 -> 이 함수는 파라미터 1을 입출력 완료 포트에 등록 NULL일 경우, 새로운 입출력 완료 포트를 만들고 여기에 Filehandle을 등록 파라미터 3. 입출력 완료 포트 핸들을 가리키는 키로, 유저가 정의한 값. 부가적인 정보를 함께 넘길 수 있지만, 0으로 뒀다. 파라미터 4. 입출력 완료 포트의 처리를 위해 몇개의 스레드를 할당할 것인지에 대한 변수. 0일 경우, 시스템에서 프로세스에 있는 스레드를 가능한만큼 사용한다는 뜻 반환값 - NULL일 경우 실패(GetLastError(:4200)으로 에러값을 가져올 수 있다) */ std::wcout.imbue(std::locale("korean"));// wcout 유니코드 출력! WSADATA wsadata; WSAStartup(MAKEWORD(2, 2), &wsadata); //WSAStartup printf("Initialize Complete!!"); } void StartRecv(int id) { unsigned long r_flag = 0; ZeroMemory(&g_clients[id].m_rxover.m_over, sizeof(WSAOVERLAPPED)); int ret = WSARecv(g_clients[id].m_s, &g_clients[id].m_rxover.m_wsabuf, 1, NULL, &r_flag, &g_clients[id].m_rxover.m_over, NULL); //해당 클라이언트의 연결 소켓으로부터 데이터를 읽는다. if (0 != ret) { int err_no = WSAGetLastError(); if (WSA_IO_PENDING != err_no) error_display("Recv Error", err_no); } } void SendPacket(int id, void *ptr) { //cout <<"ID : "<< id << endl; unsigned char *packet = reinterpret_cast<unsigned char *>(ptr); EXOVER *s_over = new EXOVER; s_over->is_recv = false; memcpy(s_over->m_iobuf, packet, packet[0]); s_over->m_wsabuf.buf = s_over->m_iobuf; if (s_over->m_iobuf[0] < 0) { if (s_over->m_iobuf[1] == CASE_MAP) s_over->m_wsabuf.len = 227; else s_over->m_wsabuf.len = 227; } else s_over->m_wsabuf.len = s_over->m_iobuf[0]; ZeroMemory(&s_over->m_over, sizeof(WSAOVERLAPPED)); int res = WSASend(g_clients[id].m_s, &s_over->m_wsabuf, 1, NULL, 0, &s_over->m_over, NULL); if (0 != res) { int err_no = WSAGetLastError(); if (WSA_IO_PENDING != err_no) error_display("Send Error! ", err_no); } } void SendPutObjectPacket(int client, int object) { sc_packet_put_player p; p.id = object; p.size = sizeof(p); p.type = SC_PUT_PLAYER; p.x = g_clients[object].m_x; p.y = g_clients[object].m_y; SendPacket(client, &p); } void SendRemovePacket(int client, int object) { sc_packet_remove_player p; p.id = object; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; SendPacket(client, &p); } void ProcessPacket(int id, char *packet) { TB_join * joininfo; unsigned char temproomid; unsigned char tempid; switch (packet[1]) { case CASE_GAMEREADY: { TB_GAMEReady* tempt = reinterpret_cast<TB_GAMEReady*>(packet); temproomid = tempt->roomid; unsigned char tempid = tempt->myid; gameRoom_Manager[temproomid].ready_player[tempid] = true; } break; case CASE_POS: { g_clients[id].ChangeRecieveTime(); TB_CharPos* pos = reinterpret_cast<TB_CharPos*>(packet); bool tempbool = false; unsigned char tempid = pos->ingame_id; temproomid = pos->room_id; BYTE lastdeadID = 4; gameRoom_Manager[temproomid].ingame_Char_Info[tempid].posx = pos->posx; gameRoom_Manager[temproomid].ingame_Char_Info[tempid].posz = pos->posz; gameRoom_Manager[temproomid].ingame_Char_Info[tempid].rotY = pos->rotY; gameRoom_Manager[temproomid].ingame_Char_Info[tempid].is_alive = pos->is_alive; gameRoom_Manager[temproomid].ingame_Char_Info[tempid].anistate = pos->anistate; if (!gameRoom_Manager[temproomid].ingame_Char_Info[tempid].is_alive && !gameRoom_Manager[temproomid].IsGameOver()) { gameRoom_Manager[temproomid].PlayerDead(tempid); lastdeadID = tempid; tempbool = true; } if (gameRoom_Manager[temproomid].deathcount == (room_Map[temproomid].people_count - 1)) { gameRoom_Manager[temproomid].SetGameOver(); } if (tempbool) { TB_DEAD tempDead = { SIZEOF_TB_DEAD,CASE_DEAD,tempid }; auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { cout << "Send You are Dead" << endl; SendPacket(a->id - 1, &tempDead); } } //retval = send(SocketInfoArray[j].sock, (char*)&tempd, sizeof(TB_DEAD), 0); } auto a = g_clients.begin(); if (gameRoom_Manager[temproomid].IsGameOver() && gameRoom_Manager[temproomid].deathcount == (room_Map[temproomid].people_count - 1)) { unsigned char winnerid = gameRoom_Manager[temproomid].GetWinnerID(); TB_GAMEEND gameover = { SIZEOF_TB_GAMEEND,CASE_GAMESET,winnerid,lastdeadID }; //retval = send(SocketInfoArray[j].sock, (char*)&gameover, sizeof(TB_GAMEEND), 0); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { cout << "Send GameOver" << endl; //if(gameRoom_Manager[temproomid].ingame_Char_Info[tempid].is_alive) a->m_scene = 1; SendPacket(a->id - 1, &gameover); } } } for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { SendPacket(a->id - 1, &gameRoom_Manager[temproomid].ingame_Char_Info[tempid]); } } if (gameRoom_Manager[temproomid].IsGameOver()) gameRoom_Manager[temproomid].deathcount = 0; } break; case CASE_BOMB: { g_clients[id].ChangeRecieveTime(); TB_BombExplode* b_pos = reinterpret_cast<TB_BombExplode*>(packet); int tempx = b_pos->posx; int tempz = b_pos->posz; unsigned char roomid = b_pos->room_id; gameRoom_Manager[roomid].map.mapInfo[tempz][tempx] = MAP_BOMB; unsigned char tempfire = b_pos->firepower; unsigned char tempgameid = b_pos->game_id; //fireMap[roomid - 1][tempz][tempx] = tempfire; TB_BombPos tempbomb = { SIZEOF_TB_BombPos,CASE_BOMB,tempgameid,tempfire,b_pos->room_id,tempx,tempz,0.0f }; gameRoom_Manager[roomid].bomb_Map.insert(pair<pair<int, int>, Bomb_TB>(make_pair(tempx, tempz), Bomb_TB(tempx, tempz, roomid, tempfire, tempgameid))); gameRoom_Manager[roomid].fireMap[tempz][tempx] = tempfire; TB_BombSetRE tBomb = { SIZEOF_TB_MapSetRE,CASE_BOMBSET,tempfire,tempx,tempz }; auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == roomid) { SendPacket(a->id - 1, &tBomb); } } //retval = send(SocketInfoArray[j].sock, (char*)&tB, sizeof(TB_MapSetRE), 0); } break; case CASE_ITEM_GET: { g_clients[id].ChangeRecieveTime(); TB_ItemGet* tempitem = reinterpret_cast<TB_ItemGet*>(packet); temproomid = tempitem->room_id; unsigned char tempid = tempitem->ingame_id; unsigned char tempi = tempitem->item_type; printf("%d의 item type 획득\n", tempi); int tempx = tempitem->posx; int tempz = tempitem->posz; bool tempbool = gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] != MAP_NOTHING; printf("bool 초기화\n"); if (tempbool) { gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] = MAP_NOTHING; TB_GetItem tempIRE = { SIZEOF_TB_GetItem,CASE_ITEM_GET,tempid,tempi }; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; //retval = send(ptr->sock, (char*)&tempIRE, sizeof(TB_GetItem), 0); auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { SendPacket(a->id - 1, &tempIRE); SendPacket(a->id - 1, &tMap); } } } } break; case CASE_KICKBOMB: { g_clients[id].ChangeRecieveTime(); cout << "Kick Bomb" << endl; TB_KickBomb* tK = reinterpret_cast<TB_KickBomb*>(packet); unsigned char tempdirc = tK->direction; unsigned char temproomid = tK->roomid; unsigned char tempid = tK->ingame_id; int tempx = tK->posx; int tempz = tK->posz; int ax = tempx; int az = tempz; switch (tempdirc) { case 1: ax = tempx + 1; break; case 2: ax = tempx - 1; break; case 3: az = tempz + 1; break; case 4: az = tempz - 1; break; } printf("발로까는캐릭터위치 %d,%d!!!\n", tempx, tempz); if (gameRoom_Manager[temproomid].bomb_Map.size() > 0) { auto bomb_b = gameRoom_Manager[temproomid].bomb_Map.find(pair<int, int>(ax, az)); if (bomb_b != gameRoom_Manager[temproomid].bomb_Map.end()) { TB_KickBombRE tempKick = { SIZEOF_TB_KickBombRE,CASE_KICKBOMB,1,tempid,tempdirc,tempx,tempz }; gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] = MAP_NOTHING; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; Kick_CalculateMap(tempx, tempz, temproomid, &tempKick, tempdirc, &tMap); Bomb_TB tempBomb = Bomb_TB(tempKick.posx_re, tempKick.posz_re, temproomid, bomb_b->second.firepower, bomb_b->second.game_id); tempBomb.time = bomb_b->second.time; tempBomb.ResetExplodeTime(); tempBomb.is_kicked = true; gameRoom_Manager[temproomid].bomb_Map.insert(pair<pair<int, int>, Bomb_TB>(make_pair(tempKick.posx_re, tempKick.posz_re), tempBomb)); gameRoom_Manager[temproomid].fireMap[tempz][tempx] = 0; gameRoom_Manager[temproomid].bomb_Map.erase(bomb_b); gameRoom_Manager[temproomid].ingame_Char_Info[tempid].anistate = TURTLE_ANI_KICK;//throw ani auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { if (tempKick.kick == 1) { SendPacket(a->id - 1, &tMap); } SendPacket(a->id - 1, &tempKick); } } } } } break; case CASE_KICKCOMPLETE: { g_clients[id].ChangeRecieveTime(); TB_KickComplete* tK = reinterpret_cast<TB_KickComplete*>(packet); unsigned char temproomid = tK->roomid; int tempx = tK->posx; int tempz = tK->posz; TB_BombSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_BOMBSET,MAP_BOMB,tempx,tempz }; gameRoom_Manager[temproomid].bomb_Map[pair<int, int>(tempx, tempz)].is_kicked = false; gameRoom_Manager[temproomid].bomb_Map[pair<int, int>(tempx, tempz)].ResetTime(); gameRoom_Manager[temproomid].fireMap[tempz][tempx] = gameRoom_Manager[temproomid].bomb_Map[pair<int, int>(tempx, tempz)].firepower; gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] = MAP_BOMB; auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { SendPacket(a->id - 1, &tMap); } } } break; case CASE_THROWBOMB: { g_clients[id].ChangeRecieveTime(); TB_ThrowBomb* tempt = reinterpret_cast<TB_ThrowBomb*>(packet); temproomid = tempt->roomid; unsigned char tempid = tempt->ingame_id; int tempx = tempt->posx; int tempz = tempt->posz; unsigned char tempdirect = tempt->direction; if (gameRoom_Manager[temproomid].bomb_Map.size() > 0) { auto bomb_b = gameRoom_Manager[temproomid].bomb_Map.find(make_pair(tempx, tempz)); if (bomb_b != gameRoom_Manager[temproomid].bomb_Map.end()) { TB_ThrowBombRE tempThrow = { SIZEOF_TB_ThrowBombRE,CASE_THROWBOMB,tempdirect,tempid,tempx,tempz }; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; Throw_Calculate_Map(tempx, tempz, temproomid, &tempThrow, tempdirect,&tMap); gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] = MAP_NOTHING; gameRoom_Manager[temproomid].fireMap[tempz][tempx] = 0; Bomb_TB tempBomb = Bomb_TB(tempThrow.posx_re, tempThrow.posz_re, temproomid, bomb_b->second.firepower, bomb_b->second.game_id); tempBomb.time = bomb_b->second.time; tempBomb.ResetExplodeTime(); tempBomb.is_throw = true; gameRoom_Manager[temproomid].bomb_Map.insert(pair<pair<int, int>, Bomb_TB>(make_pair(tempThrow.posx_re, tempThrow.posz_re), tempBomb)); gameRoom_Manager[temproomid].bomb_Map.erase(bomb_b); auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { SendPacket(a->id - 1, &tMap); SendPacket(a->id - 1, &tempThrow); } } } } } break; case CASE_THROWCOMPLETE: { g_clients[id].ChangeRecieveTime(); TB_ThrowComplete* tempt = reinterpret_cast<TB_ThrowComplete*>(packet); temproomid = tempt->roomid; int tempx = tempt->posx; int tempz = tempt->posz; gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] = MAP_BOMB; TB_BombSetRE tB = { SIZEOF_TB_MapSetRE,CASE_BOMBSET,MAP_BOMB,tempx,tempz }; gameRoom_Manager[temproomid].fireMap[tempz][tempx] = gameRoom_Manager[temproomid].bomb_Map[pair<int, int>(tempx, tempz)].firepower; gameRoom_Manager[temproomid].bomb_Map[pair<int, int>(tempx, tempz)].is_throw = false; gameRoom_Manager[temproomid].bomb_Map[pair<int, int>(tempx, tempz)].ResetTime(); //fireMap[temproomid - 1][tempz][tempx] = bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].firepower; auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { SendPacket(a->id - 1, &tB); } } } break; case CASE_BOXPUSH: { g_clients[id].ChangeRecieveTime(); TB_BoxPush* tB = reinterpret_cast<TB_BoxPush*>(packet); unsigned char tempdirc = tB->direction; unsigned char temproomid = tB->roomid; unsigned char tempid = tB->ingame_id; int tempx = tB->posx; int tempz = tB->posz; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; TB_BoxPushRE tBox = { SIZEOF_TB_BoxPushRE, CASE_BOXPUSH,0,tempid }; BoxPush_Calculate_Map(tempx, tempz, temproomid, &tBox, tempdirc, &tMap); printf("box받았다!!!\n"); auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { if (tBox.push == 1) SendPacket(a->id - 1, &tMap); SendPacket(a->id - 1, &tBox); } } //printf("보냈다 패킷!!!\n"); } break; case CASE_BOXPUSHCOMPLETE: { g_clients[id].ChangeRecieveTime(); TB_BoxPushComplete* tB = reinterpret_cast<TB_BoxPushComplete*>(packet); printf("boxcom받았다!!!\n"); temproomid = tB->roomid; int tempx = tB->posx; int tempz = tB->posz; gameRoom_Manager[temproomid].map.mapInfo[tempz][tempx] = MAP_BOX; TB_MapSetRE tBd = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_BOX,tempx,tempz }; auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 2 && a->m_isconnected&&a->roomNum == temproomid) { SendPacket(a->id - 1, &tBd); } } } break; case CASE_JOINROOM: { g_clients[id].ChangeRecieveTime(); joininfo = reinterpret_cast<TB_join*>(packet); temproomid = joininfo->roomID; tempid = joininfo->id; if (temproomid != 0) { bool tempBool1 = room_Map[temproomid].people_count < room_Map[temproomid].people_max; bool tempBool2 = room_Map[temproomid].game_start != 1; bool tempBool3 = room_Map[temproomid].people_count >= 1; if (tempBool1&&tempBool2&&tempBool3) { g_clients[id].m_scene = 1; unsigned char tempcount = room_Map[temproomid].people_count; unsigned char tempguard = room_Map[temproomid].guardian_pos; for (unsigned char j = 0; j < 4; ++j) { if (room_Map[temproomid].people_inroom[j] == 0) { room_Map[temproomid].people_inroom[j] = joininfo->id; room_Map[temproomid].people_count = room_Map[temproomid].people_count + 1; g_clients[id].roomNum = temproomid; //tempcount = j + 1; tempcount = room_Map[temproomid].people_count; printf("%d가 %d번방에 들어감, %d+1번째 위치\n", joininfo->id, joininfo->roomID, j); break; } } g_clients[id].m_mVl.lock(); auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { cout << "Send Roominfo-Join" << endl; room_Map[temproomid].size = SIZEOF_TB_Room; room_Map[temproomid].type = CASE_ROOM; SendPacket(a->id - 1, &room_Map[temproomid]); } if (a->m_scene == 1 && a->m_isconnected &&a->roomNum == temproomid) { cout << "Send Roominfo2-Join" << endl; room_Map[temproomid].size = SIZEOF_TB_Room; room_Map[temproomid].type = CASE_ROOM; SendPacket(a->id - 1, &room_Map[temproomid]); } } TB_joinRE tempjoin = { SIZEOF_TB_joinRE,CASE_JOINROOM,1,temproomid,tempcount,tempguard }; for (int i = 0; i < 4; ++i) { tempjoin.people_inroom[i] = room_Map[temproomid].people_inroom[i]; tempjoin.team_inroom[i] = room_Map[temproomid].team_inroom[i]; } SendPacket(id, &tempjoin); g_clients[id].m_mVl.unlock(); } else { TB_joinRE tempjoin = { SIZEOF_TB_joinRE,CASE_JOINROOM,0 }; SendPacket(id, &tempjoin); } } } break; case CASE_CREATEROOM: { g_clients[id].ChangeRecieveTime(); TB_create* createinfo = reinterpret_cast<TB_create*>(packet); temproomid = createinfo->roomid; TB_createRE re_createPacket = { SIZEOF_TB_createRE,CASE_CREATEROOM,0 }; auto roomcreateinfo = room_Map.find(temproomid); if (room_Map[temproomid].made == 0) { //room_Map[temproomid] cout << "Create Room!!!" << endl; room_Map[temproomid].size = SIZEOF_TB_Room; room_Map[temproomid].type = CASE_ROOM; room_Map[temproomid].guardian_pos = 1; room_Map[temproomid].made = 1; room_Map[temproomid].people_count = 1; room_Map[temproomid].people_inroom[0] = createinfo->id; room_Map[temproomid].roomID = temproomid; room_Map[temproomid].people_max = 2; for(int i=0;i<4;++i) room_Map[temproomid].team_inroom[i] = 0; //ptr->roomID = room_Map[temproomid - 1].roomID; re_createPacket.can = 1; re_createPacket.roomid = room_Map[temproomid].roomID; g_clients[id].m_scene = 1; g_clients[id].is_guardian = 1; g_clients[id].roomNum = temproomid; SendPacket(id, &room_Map[temproomid]); SendPacket(id, &re_createPacket); g_clients[id].m_mVl.lock(); auto a = g_clients.begin(); TB_RoomInfo new_room; //CopyRoomAtoB(&room_Map[temproomid], &new_room); room_page.emplace_back(room_Map[temproomid]); for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { cout << "Send Roominfo-Create" << endl; SendPacket(a->id - 1, &room_Map[temproomid]); } } g_clients[id].m_mVl.unlock(); cout << (int)(createinfo->id) << "Create " << (int)temproomid << "Room" << endl; } else { cout << "Cannot Create Room!!!" << endl; re_createPacket.can = 0; SendPacket(id, &re_createPacket); } } break; case CASE_READY: { g_clients[id].ChangeRecieveTime(); TB_Ready* tempready = reinterpret_cast<TB_Ready*>(packet); unsigned char temproompos = tempready->pos_in_room; temproomid = tempready->room_num; bool b_isready = room_Map[temproomid].ready[temproompos - 1] == 1; if (!b_isready) { room_Map[temproomid].ready[temproompos - 1] = 1; //ptr->is_ready = 1; } else { room_Map[temproomid].ready[temproompos - 1] = 0; //ptr->is_ready = 0; } unsigned char tempReady = room_Map[temproomid].ready[temproompos - 1]; TB_ReadyRE tempRE = { SIZEOF_TB_ReadyRE,CASE_READY,temproompos,tempReady,temproomid }; SendPacket(id, &tempRE); for (int i = 0; i < 4; ++i) { if (room_Map[temproomid].people_inroom[i] != 0) { cout << (int)room_Map[temproomid].people_inroom[i] << "에게 보낸다." << endl; SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &tempRE); } } } break; case CASE_OUTROOM: { g_clients[id].ChangeRecieveTime(); TB_RoomOut* tempRO = reinterpret_cast<TB_RoomOut*>(packet); temproomid = tempRO->roomID; unsigned char temproompos = tempRO->my_pos; if (temproompos != 0) { TB_RoomOutRE outRE = { SIZEOF_TB_RoomOutRE,CASE_OUTROOM,1 }; room_Map[temproomid].people_count -= 1; room_Map[temproomid].people_inroom[temproompos - 1] = 0; if (tempRO->imwinner == 1) { g_clients[id].win_vs += 1; printf("%s win:%d %dXexp get\n", g_clients[id].stringID, g_clients[id].win_vs, room_Map[temproomid].people_max); int max = room_Map[temproomid].people_max; g_clients[id].exp = g_clients[id].exp + 100; cout << "Winner!!!!DB Update" << endl; } if (tempRO->imwinner == 2) { g_clients[id].lose_vs += 1; printf("%s lose:%d\n", g_clients[id].stringID, g_clients[id].lose_vs); g_clients[id].exp = g_clients[id].exp + 50; } if (room_Map[temproomid].people_count <= 0) { room_Map[temproomid].made = 0; room_Map[temproomid].game_start = 0; auto myroomState = room_Map.find(temproomid); room_Map.erase(myroomState); auto a = room_page.begin(); for (; a != room_page.end();) { if (a->roomID == temproomid) { room_page.erase(a++); break; } else { a++; } } } if (g_clients[id].is_guardian == 1) { g_clients[id].is_guardian = 0; //이제 자유의 몸이야! for (int a = 0; a < 4; ++a) { if (room_Map[temproomid].people_inroom[a] != 0 && room_Map[temproomid].people_inroom[a] != g_clients[id].id) { room_Map[temproomid].guardian_pos = a + 1; g_clients[room_Map[temproomid].people_inroom[a] - 1].is_guardian = 1; break; } } } SendPacket(id, &outRE); g_clients[id].m_mVl.lock(); auto a = g_clients.begin(); g_clients[id].m_scene = 0; auto myroomState2 = room_Map.find(temproomid); bool tempbool = myroomState2 != room_Map.end(); for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { if (tempbool) { cout << "Send Roominfo-Out" << endl; room_Map[temproomid].size = SIZEOF_TB_Room; room_Map[temproomid].type = CASE_ROOM; room_Map[temproomid].roomID = temproomid; SendPacket(a->id - 1, &room_Map[temproomid]); } else { cout << "Send Roominfo-Out2" << endl; TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,temproomid,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } if (a->m_scene == 1 && a->m_isconnected &&a->roomNum == temproomid) { cout << "Send Roominfo2=Out" << endl; if (tempbool) SendPacket(a->id - 1, &room_Map[temproomid]); else { TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,temproomid,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } } g_clients[id].m_mVl.unlock(); } else { g_clients[id].m_scene = 1; } } break; case CASE_FORCEOUTROOM: { g_clients[id].ChangeRecieveTime(); TB_GetOut* tempFO = reinterpret_cast<TB_GetOut*>(packet); temproomid = tempFO->roomID; unsigned char temproompos = tempFO->position; room_Map[temproomid].people_count -= 1; unsigned char tempid = room_Map[temproomid].people_inroom[temproompos - 1]; room_Map[temproomid].people_inroom[temproompos - 1] = 0; TB_GetOUTRE tempForceOut = { SIZEOF_TB_GetOutRE,CASE_FORCEOUTROOM }; auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 1 && a->m_isconnected&&a->roomNum == temproomid) { if (a->id == tempid) { int tempcount = 0; list<TB_Room>::iterator room_t = room_page.begin(); for (; room_t != room_page.end();) { if (tempcount >= 8) { break; } if (room_t->roomID != 0) { cout << "Send RRRoominfo\n" << endl; TB_Room roomList = { SIZEOF_TB_Room,CASE_ROOM,room_t->roomID,room_t->people_count,room_t->game_start,room_t->people_max,room_t->made, room_t->guardian_pos,room_t->people_inroom[0],room_t->people_inroom[1],room_t->people_inroom[2],room_t->people_inroom[3],room_t->roomstate ,room_t->map_thema ,room_t->map_mode, room_t->team_inroom[0],room_t->team_inroom[1],room_t->team_inroom[2],room_t->team_inroom[3],room_t->ready[0],room_t->ready[1],room_t->ready[2],room_t->ready[3] }; SendPacket(id, &roomList); tempcount++; room_t++; } else { break; } } SendPacket(a->id - 1, &tempForceOut); } else { SendPacket(a->id - 1, &room_Map[temproomid]); } } } } break; case CASE_ROOMSETTING: { g_clients[id].ChangeRecieveTime(); TB_RoomSetting* tempSetting = reinterpret_cast<TB_RoomSetting*>(packet); temproomid = tempSetting->roomid; unsigned char temproomstate = tempSetting->peoplemax; unsigned char tempmapthema = tempSetting->mapthema; unsigned char tempmaptype = tempSetting->mapnum; room_Map[temproomid].people_max = temproomstate; room_Map[temproomid].map_mode = tempmaptype; room_Map[temproomid].map_thema = tempmapthema; g_clients[id].m_mVl.lock(); auto a = g_clients.begin(); for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { cout << "Send Roominfo-Setting" << endl; SendPacket(a->id - 1, &room_Map[temproomid]); } if (a->m_scene == 1 && a->m_isconnected &&a->roomNum == temproomid) { cout << "Send Roominfo2-Setting" << endl; SendPacket(a->id - 1, &room_Map[temproomid]); } } g_clients[id].m_mVl.unlock(); } break; case CASE_TEAMSETTING: { g_clients[id].ChangeRecieveTime(); TB_TeamSetting* tempTeamSet = reinterpret_cast<TB_TeamSetting*>(packet); temproomid = tempTeamSet->roomid; unsigned char temppos = tempTeamSet->pos_in_room; unsigned char tempteam = tempTeamSet->team; room_Map[temproomid].team_inroom[temppos] = tempteam; g_clients[id].m_mVl.lock(); auto a = g_clients.begin(); TB_TeamSet_Re temp_team = { SIZEOF_TB_TeamSet_Re ,CASE_TEAMSETTING }; for (int i = 0; i < 4; ++i) temp_team.team[i] = room_Map[temproomid].team_inroom[i]; for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { cout << "Send Roominfo-Team" << endl; SendPacket(a->id - 1, &room_Map[temproomid]); } if (a->m_scene == 1 && a->m_isconnected &&a->roomNum == temproomid) { cout << "Send Roominfo2-Team" << endl; SendPacket(a->id - 1, &temp_team); } } g_clients[id].m_mVl.unlock(); } break; case CASE_STARTGAME: { g_clients[id].ChangeRecieveTime(); TB_GameStart* startinfo = reinterpret_cast<TB_GameStart*>(packet); temproomid = startinfo->roomID; bool check_guard = (room_Map[temproomid].guardian_pos == startinfo->my_pos); int readycount = 0; TB_GameStartRE p_startGame = { SIZEOF_TB_GameStartRE,CASE_STARTGAME,0 }; for (int i = 0; i < 4; ++i) { if (room_Map[temproomid].ready[i] == 1) readycount = readycount + 1; } bool check_ready = readycount + 1 == room_Map[temproomid].people_count; if (check_guard &&check_ready) { auto myroomState = gameRoom_Manager.find(temproomid); if (myroomState != gameRoom_Manager.end()) { gameRoom_Manager[temproomid].InitClass(); } else { gameRoom_Manager.insert(make_pair(temproomid, InGameCalculator())); } gameRoom_Manager[temproomid].people_count = room_Map[temproomid].people_count; p_startGame.startTB = 1; SetMap(room_Map[temproomid].map_mode, room_Map[temproomid].map_thema, temproomid, &gameRoom_Manager[temproomid].map); TB_Map tempmap = { SIZEOF_TB_MAP,CASE_MAP }; memcpy(&tempmap, &gameRoom_Manager[temproomid].map, sizeof(Map_TB)); room_Map[temproomid].game_start = 1; for (int i = 0; i < 4; ++i) { if (room_Map[temproomid].people_inroom[i] == 0) { cout << "Player Blank!!!" << endl; gameRoom_Manager[temproomid].PlayerBlank(i); } else { cout << "Player Change ID!!!" << endl; gameRoom_Manager[temproomid].ChangeID(i, room_Map[temproomid].people_inroom[i]); } } g_clients[id].m_mVl.lock(); for (int i = 0; i < 4; ++i) { if (room_Map[temproomid].people_inroom[i] != 0) { cout << "Send Start\n" << endl; SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &gameRoom_Manager[temproomid].map); SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &gameRoom_Manager[temproomid].ingame_Char_Info[0]); SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &gameRoom_Manager[temproomid].ingame_Char_Info[1]); SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &gameRoom_Manager[temproomid].ingame_Char_Info[2]); SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &gameRoom_Manager[temproomid].ingame_Char_Info[3]); } } for (int i = 0; i < 4; ++i) { if (room_Map[temproomid].people_inroom[i] != 0) { g_clients[room_Map[temproomid].people_inroom[i] - 1].m_scene = 2; cout << "Send Map" << endl; room_Map[temproomid].ready[i] = 0; SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &p_startGame); } } g_clients[id].m_mVl.unlock(); } else { for (int i = 0; i < 4; ++i) { if (room_Map[temproomid].people_inroom[i] != 0) { //SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &gameRoom_Manager[temproomid].map); SendPacket((int)(room_Map[temproomid].people_inroom[i]) - 1, &p_startGame); } } } } break; case CASE_CONNECTSUCCESS: { g_clients[id].ChangeRecieveTime(); TB_IDPW* idpwinfo = reinterpret_cast<TB_IDPW*>(packet); temproomid = idpwinfo->m_id; unsigned char login_type = idpwinfo->m_type; char tempID[20]; char tempPW[20]; memcpy(tempID, idpwinfo->id, sizeof(tempID)); memcpy(tempPW, idpwinfo->pw, sizeof(tempPW)); cout <<"ID: "<< tempID << endl; g_clients[id].m_mVl.lock(); char query[255]; int query_stat; conn_ptr = mysql_init(NULL); conn_ptr = mysql_real_connect(conn_ptr, DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT, (char*)NULL, 0); if (conn_ptr) { printf("DB Access Success_To update\n"); } else { printf("Fail To connect DB\n"); } if (login_type == 1) { sprintf(query, "select * from UserTable where id='%s' and password='%s'", idpwinfo->id, idpwinfo->pw); printf("%s\n", query); if (mysql_query(conn_ptr, query)) { printf("Fail To Login DB\n"); TB_DBInfo_1 dbresult = { SIZEOF_TB_DBInfo_1,CASE_DB1,0 }; SendPacket(id, &dbresult); } else { printf("Success Login\n"); result_sql = mysql_store_result(conn_ptr); if (!result_sql) { printf("Fail To Login DB222\n"); TB_DBInfo_1 dbresult = { SIZEOF_TB_DBInfo_1,CASE_DB1,0 }; } else { TB_DBInfo_1 dbresult = { SIZEOF_TB_DBInfo_1,CASE_DB1,0 }; unsigned int fields = mysql_num_fields(result_sql); unsigned long* lengths = mysql_fetch_lengths(result_sql); MYSQL_ROW row2; printf("%d counts\n", fields); printf("%d lengths\n", lengths); while (row2 = mysql_fetch_row(result_sql)) { memcpy(dbresult.id_string, row2[0], 20); printf("%s and %s\n", dbresult.id_string, tempID); if (!strncmp(dbresult.id_string, tempID, sizeof(row2[0]))) { sscanf(row2[2], "%d", &dbresult.win); sscanf(row2[3], "%d", &dbresult.lose); sscanf(row2[4], "%d", &dbresult.tier); sscanf(row2[5], "%d", &dbresult.exp); sscanf(row2[6], "%d", &dbresult.exp_max); g_clients[id].win_vs = dbresult.win; g_clients[id].lose_vs = dbresult.lose; g_clients[id].tier = dbresult.tier; g_clients[id].exp = dbresult.exp; g_clients[id].exp_max = dbresult.exp_max; memcpy(g_clients[id].stringID, idpwinfo->id, sizeof(idpwinfo->id)); printf("ID :%s, win :%d, lose : %d!!\n", row2[0], dbresult.win, dbresult.lose); dbresult.connect = 1; break; } else { dbresult.connect = 0; break; } printf("Success Login1\n"); } SendPacket(id, &dbresult); memcpy(g_clients[id].stringID, dbresult.id_string, 20); } printf("Success Login3333\n"); mysql_free_result(result_sql); } } else if (login_type == 2) { printf("ID_Create\n"); sprintf(query, "select EXISTS (select * from UserTable where id='%s' and password='%s') as success", tempID, tempPW); query_stat = mysql_query(conn_ptr, query); if (query_stat == 0) { printf("There is no ID-Create ID: %s\n", tempID); MYSQL_RES *result = mysql_store_result(conn_ptr); sprintf(query, "insert into UserTable values" "('%s', '%s', '0','0','0','0','50','0','0','1-1:0 1-2:0 1-3:0','1')", tempID, tempPW); query_stat = mysql_query(conn_ptr, query); if (query_stat == 0) { TB_DBInfo_1 dbresult = { SIZEOF_TB_DBInfo_1,CASE_DB1,2,*tempID,0,0,0,0,0 }; memcpy(&dbresult.id_string, tempID, 20); SendPacket(id, &dbresult); g_clients[id].win_vs = 0; g_clients[id].lose_vs = 0; g_clients[id].tier = 0; g_clients[id].exp = 0; g_clients[id].exp_max = 50; memcpy(&g_clients[id].stringID, &dbresult.id_string, 20); } else { printf("Create Error%d\n", query_stat); TB_DBInfo_1 dbresult = { SIZEOF_TB_DBInfo_1,CASE_DB1,3 }; SendPacket(id, &dbresult); } mysql_free_result(result); } else { printf("Fail%d\n", query_stat); TB_DBInfo_1 dbresult = { SIZEOF_TB_DBInfo_1,CASE_DB1,3 }; SendPacket(id, &dbresult); } } mysql_close(conn_ptr); g_clients[id].m_mVl.unlock(); //memcpy( } break; } sc_packet_pos pos_packet; pos_packet.id = id; pos_packet.size = sizeof(sc_packet_pos); pos_packet.type = SC_POS; } void DisconnectPlayer(int id) { sc_packet_remove_player p; p.id = id; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; g_clients[id].m_isconnected = false; g_clients[id].m_mVl.lock(); int query_stat; conn_ptr = mysql_init(NULL); conn_ptr = mysql_real_connect(conn_ptr, DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT, (char*)NULL, 0); if (conn_ptr) { printf("Success\n"); } else { printf("Fail To connect DB\n"); return; } char query[255]; cout << g_clients[id].stringID << endl; sprintf(query, "update UserTable set win_vs = %d,lose_vs=%d,tier=%d,exp=%d,expmax=%d where id='%s'", g_clients[id].win_vs, g_clients[id].lose_vs, g_clients[id].tier, g_clients[id].exp, g_clients[id].exp_max, g_clients[id].stringID); //임시테스트로 승을 1추가 cout << query << endl; if (mysql_query(conn_ptr, query))//업데이트는 false가 성공 { printf("Disconnect&Update DB FAIL\n"); } else { printf("Disconnect&Update DB SUCCESS\n"); g_clients[id].win_vs = 0; g_clients[id].lose_vs = 0; g_clients[id].tier = 0; g_clients[id].exp = 0; g_clients[id].exp_max = 0; g_clients[id].m_isconnected = false; g_clients[id].is_guardian = 0; g_clients[id].m_scene = 0; g_clients[id].roomNum = 0; ZeroMemory(&g_clients[id].stringID, sizeof(g_clients[id].stringID)); cout << "Send Disconnect Socket" << endl; } g_clients[id].m_mVl.unlock(); g_clients[id].m_isconnected = false; g_clients[id].is_guardian = 0; g_clients[id].m_scene = 0; g_clients[id].roomNum = 0; printf("Close_Socket\n"); closesocket(g_clients[id].m_s); } void DisconnectPlayer_inroom(int id) { sc_packet_remove_player p; p.id = id; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; g_clients[id].m_isconnected = false; g_clients[id].m_mVl.lock(); int query_stat; conn_ptr = mysql_init(NULL); cout << "Disconnect_inroom" << endl; room_Map[g_clients[id].roomNum].people_count =room_Map[g_clients[id].roomNum].people_count-1; for (int i = 0; i < 4; ++i) { if (room_Map[g_clients[id].roomNum].people_inroom[i]==g_clients[id].id) { room_Map[g_clients[id].roomNum].people_inroom[i] = 0; } } cout << "Disconnect_inroom2" << endl; if (room_Map[g_clients[id].roomNum].people_count <= 0) { room_Map[g_clients[id].roomNum].made = 0; room_Map[g_clients[id].roomNum].game_start = 0; auto myroomState = room_Map.find(g_clients[id].roomNum); //room_Map.erase(myroomState); } cout << "Disconnect_inroom3" << endl; auto a = g_clients.begin(); g_clients[id].m_scene = 0; auto myroomState2 = room_Map.find(g_clients[id].roomNum); bool tempbool = myroomState2 != room_Map.end(); cout << "Disconnect_inroom4" << endl; for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { if (tempbool) { cout << "Send Roominfo-Out" << endl; room_Map[g_clients[id].roomNum].size = SIZEOF_TB_Room; room_Map[g_clients[id].roomNum].type = CASE_ROOM; room_Map[g_clients[id].roomNum].roomID = g_clients[id].roomNum; SendPacket(a->id - 1, &room_Map[g_clients[id].roomNum]); } else { cout << "Send Roominfo-Out2" << endl; TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,g_clients[id].roomNum,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } if (a->m_scene == 1 && a->m_isconnected &&a->roomNum == g_clients[id].roomNum) { cout << "Send Roominfo2=Out" << endl; if (tempbool) SendPacket(a->id - 1, &room_Map[g_clients[id].roomNum]); else { TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,g_clients[id].roomNum,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } } conn_ptr = mysql_real_connect(conn_ptr, DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT, (char*)NULL, 0); if (conn_ptr) { printf("Success\n"); } else { printf("Fail To connect DB\n"); return; } char query[255]; cout << g_clients[id].stringID << endl; sprintf(query, "update UserTable set win_vs = %d,lose_vs=%d,tier=%d,exp=%d,expmax=%d where id='%s'", g_clients[id].win_vs, g_clients[id].lose_vs, g_clients[id].tier, g_clients[id].exp, g_clients[id].exp_max, g_clients[id].stringID); //임시테스트로 승을 1추가 cout << query << endl; if (mysql_query(conn_ptr, query))//업데이트는 false가 성공 { printf("Disconnect&Update DB FAIL\n"); } else { printf("Disconnect&Update DB SUCCESS\n"); g_clients[id].win_vs = 0; g_clients[id].lose_vs = 0; g_clients[id].tier = 0; g_clients[id].exp = 0; g_clients[id].exp_max = 0; g_clients[id].m_isconnected = false; g_clients[id].is_guardian = 0; g_clients[id].m_scene = 0; g_clients[id].roomNum = 0; ZeroMemory(&g_clients[id].stringID, sizeof(g_clients[id].stringID)); cout << "Send Disconnect Socket" << endl; } g_clients[id].m_mVl.unlock(); g_clients[id].m_isconnected = false; g_clients[id].is_guardian = 0; g_clients[id].m_scene = 0; g_clients[id].roomNum = 0; printf("Close_Socket\n"); closesocket(g_clients[id].m_s); } void DisconnectPlayer_ingame(int id) { cout << "Disconnect InGame "<<id << endl; sc_packet_remove_player p; p.id = id; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; g_clients[id].m_isconnected = false; g_clients[id].m_mVl.lock(); int query_stat; conn_ptr = mysql_init(NULL); int tempingameid = 4; room_Map[g_clients[id].roomNum].people_count = room_Map[g_clients[id].roomNum].people_count - 1; for (int i = 0; i < 4; ++i) { if (room_Map[g_clients[id].roomNum].people_inroom[i] == g_clients[id].id) { room_Map[g_clients[id].roomNum].people_inroom[i] = 0; tempingameid = i; } } gameRoom_Manager[g_clients[id].roomNum].PlayerDead(tempingameid); TB_DEAD tempDead = { SIZEOF_TB_DEAD,CASE_DEAD,tempingameid }; auto b = g_clients.begin(); for (; b != g_clients.end(); b++) { if (b->m_scene == 2 && b->m_isconnected&&b->roomNum == g_clients[id].roomNum) { cout << "Send You are Dead_Disconnect" << endl; if(tempingameid!=4) SendPacket(b->id - 1, &tempDead); } if (gameRoom_Manager[g_clients[id].roomNum].deathcount == (room_Map[g_clients[id].roomNum].people_count - 1)) { gameRoom_Manager[g_clients[id].roomNum].SetGameOver(); } if (gameRoom_Manager[g_clients[id].roomNum].IsGameOver() && gameRoom_Manager[g_clients[id].roomNum].deathcount == (room_Map[g_clients[id].roomNum].people_count - 1)) { cout << "Send Winner!!!\n" << endl; unsigned char winnerid = gameRoom_Manager[g_clients[id].roomNum].GetWinnerID(); TB_GAMEEND gameover = { SIZEOF_TB_GAMEEND,CASE_GAMESET,winnerid,tempingameid }; if (b->m_scene == 2 && b->m_isconnected&&b->roomNum == g_clients[id].roomNum) { //if(gameRoom_Manager[temproomid].ingame_Char_Info[tempid].is_alive) b->m_scene = 1; SendPacket(b->id - 1, &gameover); } } } gameRoom_Manager[g_clients[id].roomNum].idList[tempingameid]=0; //gameRoom_Manager[g_clients[id].roomNum] if (room_Map[g_clients[id].roomNum].people_count <= 0) { room_Map[g_clients[id].roomNum].made = 0; room_Map[g_clients[id].roomNum].game_start = 0; gameRoom_Manager[g_clients[id].roomNum].SetGameOver(); auto myroomState = room_Map.find(g_clients[id].roomNum); //room_Map.erase(myroomState); } else if (room_Map[g_clients[id].roomNum].people_count <= 1) { gameRoom_Manager[g_clients[id].roomNum].SetGameOver(); auto myroomState = room_Map.find(g_clients[id].roomNum); //room_Map.erase(myroomState); } auto a = g_clients.begin(); g_clients[id].m_scene = 0; auto myroomState2 = room_Map.find(g_clients[id].roomNum); bool tempbool = myroomState2 != room_Map.end(); for (; a != g_clients.end(); a++) { if (a->m_scene == 0 && a->m_isconnected) { if (tempbool) { cout << "Send Roominfo-Out" << endl; room_Map[g_clients[id].roomNum].size = SIZEOF_TB_Room; room_Map[g_clients[id].roomNum].type = CASE_ROOM; room_Map[g_clients[id].roomNum].roomID = g_clients[id].roomNum; SendPacket(a->id - 1, &room_Map[g_clients[id].roomNum]); } else { cout << "Send Roominfo-Out2" << endl; TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,g_clients[id].roomNum,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } if (a->m_scene == 1 && a->m_isconnected &&a->roomNum == g_clients[id].roomNum) { cout << "Send Roominfo2=Out" << endl; if (tempbool) SendPacket(a->id - 1, &room_Map[g_clients[id].roomNum]); else { TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,g_clients[id].roomNum,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } if (a->m_scene == 2 && a->m_isconnected &&a->roomNum == g_clients[id].roomNum) { cout << "Send Roominfo2=Out" << endl; if (tempbool) SendPacket(a->id - 1, &room_Map[g_clients[id].roomNum]); else { TB_Room empty_room = { SIZEOF_TB_Room,CASE_ROOM,g_clients[id].roomNum,0,0,0,0 }; SendPacket(a->id - 1, &empty_room); } } } conn_ptr = mysql_real_connect(conn_ptr, DB_HOST, DB_USER, DB_PASS, DB_NAME, DB_PORT, (char*)NULL, 0); if (conn_ptr) { printf("Success\n"); } else { printf("Fail To connect DB\n"); return; } char query[255]; cout << g_clients[id].stringID << endl; sprintf(query, "update UserTable set win_vs = %d,lose_vs=%d,tier=%d,exp=%d,expmax=%d where id='%s'", g_clients[id].win_vs, g_clients[id].lose_vs, g_clients[id].tier, g_clients[id].exp, g_clients[id].exp_max, g_clients[id].stringID); //임시테스트로 승을 1추가 cout << query << endl; if (mysql_query(conn_ptr, query))//업데이트는 false가 성공 { printf("Disconnect&Update DB FAIL\n"); } else { printf("Disconnect&Update DB SUCCESS\n"); g_clients[id].win_vs = 0; g_clients[id].lose_vs = 0; g_clients[id].tier = 0; g_clients[id].exp = 0; g_clients[id].exp_max = 0; g_clients[id].m_isconnected = false; g_clients[id].is_guardian = 0; g_clients[id].m_scene = 0; g_clients[id].roomNum = 0; ZeroMemory(&g_clients[id].stringID, sizeof(g_clients[id].stringID)); cout << "Send Disconnect Socket" << endl; } g_clients[id].m_mVl.unlock(); g_clients[id].m_isconnected = false; g_clients[id].is_guardian = 0; g_clients[id].m_scene = 0; g_clients[id].roomNum = 0; printf("Close_Socket\n"); closesocket(g_clients[id].m_s); } void worker_thread() { while (true) { unsigned long io_size; unsigned long long iocp_key; // 64 비트 integer , 우리가 64비트로 컴파일해서 64비트 WSAOVERLAPPED *over;// overlapped(중첩) 입출력 연산의 초기화와 이후 작업 완료 루틴 사이에서의 통신수단을 제공한다. WSAOVERLAPPED 구조체는 OVERLAPPED 구조체와 호환된다. BOOL ret = GetQueuedCompletionStatus(gh_iocp, &io_size, &iocp_key, &over, INFINITE); /*GQCS -> 입출력 완료 대기열로부터 입출력 완료를 기다린다. 만약 대기열에 완료가 없다면 이 함수는 대기열에 입출력 완료가 있을 때가지 대기한다. 파라미터1. HANDLE 변수 - CreateIoCompletionPort(:12) 파라미터2. 입출력으로 인해 전송된 데이터 크기 - 함수가 반환되면 파라미터에 입력이 된다. 파라미터3,4 중첩 연산의 정보를 가지고 있는 overlapped 구조체를 가리키는 포인터 파라미터 5 - 시간을 얼마나 기다릴건지 입력하는 변수 */ int key = static_cast<int>(iocp_key); if (FALSE == ret) { cout << "Error in GQCS\n"; if (g_clients[key].m_scene == 0) DisconnectPlayer(key); else if (g_clients[key].m_scene == 1) DisconnectPlayer_inroom(key); else if (g_clients[key].m_scene == 2) DisconnectPlayer_ingame(key); continue; } //GQCS 에서 실패를 반환 했을 시, scene 별로 다른 종료함수 if (0 == io_size) { if (g_clients[key].m_scene == 0) DisconnectPlayer(key); else if (g_clients[key].m_scene == 1) DisconnectPlayer_inroom(key); else if (g_clients[key].m_scene == 2) DisconnectPlayer_ingame(key); continue; } //입출력이 일어났지만 결과로 전송된 데이터의 크기가 0일 때 에러로 여겨 종료 처리 EXOVER *p_over = reinterpret_cast<EXOVER *>(over); /* protocol.h 에서 선언했던 EXOVER 구조체로 변환 한다. WSAOVERLAPPED 구조체 변수 -> 입출력 연산의 초기화/ 작업/ 완료/ 루틴 사이에서의 통신수단 제공해주는 구조체 -> 첫번째 멤버변수 internal->예비필드로 중첩 입출력이 실행되는 곳에서 내부적으로 사용 -> 두번째 internalHigh-> 첫번째 멤버변수와 기능이 같다 -> 세번째,네번째,다섯번째 offset,offsetHigh,Pointer 서비스 프로바이더를 위해 예약되어있는 변수 ->여섯번째 HANDLE hEvent 중첩 입출력 연산이 완료 루틴이 없는 상태에서 발생했다면 (lpCompletionRoutine이 NULL일 경우), 이 필드는 WSAEVENT 객체나 혹은 NULL을 가져야 한다. 만약 lpCompletionRoutine이 NULL이 아니라면 이 필드는 자유로이 사용할 수 있다. */ if (true == p_over->is_recv) { int work_size = io_size; //work_size라는 int형 변수에 GQCS함수를 통해 얻은 입출력 사이즈 값을 복사 char *wptr = p_over->m_iobuf; while (0 < work_size) { //work_size가 0이 될때까지 process packet 처리 int p_size; if (0 != g_clients[key].m_packet_size) //패킷사이즈가 0이 아닐경우 p_size = g_clients[key].m_packet_size; else { //0일경우 p_size = wptr[0]; g_clients[key].m_packet_size = p_size; } // int need_size = p_size - g_clients[key].m_prev_packet_size; if (need_size <= work_size) { // 지정된 패킷의 사이즈의 이상이면 processpacket을 진행 memcpy(g_clients[key].m_packet + g_clients[key].m_prev_packet_size, wptr, need_size); ProcessPacket(key, g_clients[key].m_packet); g_clients[key].m_prev_packet_size = 0; g_clients[key].m_packet_size = 0; work_size -= need_size; wptr += need_size; } else { //사이즈가 지정된 패킷의 사이즈보다 작다면 memcpy(g_clients[key].m_packet + g_clients[key].m_prev_packet_size, wptr, work_size); g_clients[key].m_prev_packet_size += work_size; work_size = -work_size; wptr += work_size; } } StartRecv(key); } else { // is_recv가 false인 경우, 아무것도 받지 않았으므로, 수행하지 않는다. delete p_over; } } } void accept_thread() //새로 접속해 오는 클라이언트를 IOCP로 넘기는 역할 { SOCKET s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); SOCKADDR_IN bind_addr; ZeroMemory(&bind_addr, sizeof(SOCKADDR_IN)); bind_addr.sin_family = AF_INET; bind_addr.sin_port = htons(MY_SERVER_PORT); bind_addr.sin_addr.s_addr = INADDR_ANY; // 0.0.0.0 아무대서나 오는 것을 다 받겠다. ::bind(s, reinterpret_cast<sockaddr *>(&bind_addr), sizeof(bind_addr)); listen(s, 1000); while (true) { SOCKADDR_IN c_addr; ZeroMemory(&c_addr, sizeof(SOCKADDR_IN)); c_addr.sin_family = AF_INET; c_addr.sin_port = htons(MY_SERVER_PORT); c_addr.sin_addr.s_addr = INADDR_ANY; // 0.0.0.0 아무대서나 오는 것을 다 받겠다. int addr_size = sizeof(sockaddr); SOCKET cs = WSAAccept(s, reinterpret_cast<sockaddr *>(&c_addr), &addr_size, NULL, NULL); if (INVALID_SOCKET == cs) { ErrorDisplay("In Accept Thread:WSAAccept()"); continue; } cout << "New Client Connected!\n"; int id = -1; for (int i = 0; i < MAX_USER; ++i) { if (false == g_clients[i].m_isconnected) { id = i; break; } } if (-1 == id) { cout << "MAX USER Exceeded\n"; continue; } cout << "ID of new Client is [" << id << "]"; g_clients[id].m_s = cs; g_clients[id].m_scene = 0; //로비로 들어갔다~ g_clients[id].m_packet_size = 0; g_clients[id].m_prev_packet_size = 0; g_clients[id].m_view_list.clear(); g_clients[id].ChangeRecieveTime(); g_clients[id].m_x = SHOW_PLAYER_POS_X; g_clients[id].m_y = SHOW_PLAYER_POS_Y; g_clients[id].id = id + 1; CreateIoCompletionPort(reinterpret_cast<HANDLE>(cs), gh_iocp, id, 0); g_clients[id].m_isconnected = true; StartRecv(id); TB_Connect_Success s_success; s_success.size = SIZEOF_TB_Connect_Success; s_success.type = CASE_CONNECTSUCCESS; /* EXOVER *s_over = new EXOVER; unsigned char *packet = reinterpret_cast<unsigned char *>(&s_success); memcpy(s_over->m_iobuf, packet, packet[0]); s_over->m_wsabuf.len = s_over->m_iobuf[0]; ZeroMemory(&s_over->m_over, sizeof(WSAOVERLAPPED)); */ //int res = WSASend(cs, &s_over->m_wsabuf, 1, NULL, 0,&s_over->m_over, NULL); //SendPacket(id, &s_success); TB_ID s_id; s_id.id = id + 1; s_id.size = SIZEOF_TB_ID; s_id.type = CASE_ID; sc_packet_put_player p; p.id = id; p.size = sizeof(p); p.type = SC_PUT_PLAYER; p.x = g_clients[id].m_x; p.y = g_clients[id].m_y; SendPacket(id, &s_id); SendPacket(id, &s_success); // 나의 접속을 기존 플레이어들에게 알려준다. for (int i = 0; i < MAX_USER; ++i) { if (g_clients[i].m_scene == 0 && g_clients[i].m_isconnected) { if (i == id) continue; //내가 접속했다는 것을 알림 - 친구한테만 허용할 것인가? 아니면?? } } // 나에게 이미 접속된 플레이어들의 정보를 알려준다. for (int i = 0; i < MAX_USER; ++i) { if (!g_clients[i].m_isconnected) continue; if (i == id) continue; //g_clients[id].m_mVl.lock(); //g_clients[id].m_mVl.unlock(); } //로비에서 방이 어떤게 있는지 페이지로 출력 for (int i = 1; i < 8; ++i) { } int tempcount = 0; map<BYTE, TB_Room>::iterator room_t = room_Map.begin(); //list<TB_Room>::iterator room_t = room_page.begin(); for (; room_t != room_Map.end();) { if (tempcount >= 8) { break; } if (room_t->second.roomID != 0) { cout << "Send RRRoominfo\n" << endl; TB_Room roomList = { SIZEOF_TB_Room,CASE_ROOM,room_t->second.roomID,room_t->second.people_count,room_t->second.game_start,room_t->second.people_max,room_t->second.made, room_t->second.guardian_pos,room_t->second.people_inroom[0],room_t->second.people_inroom[1],room_t->second.people_inroom[2],room_t->second.people_inroom[3],room_t->second.roomstate ,room_t->second.map_thema ,room_t->second.map_mode, room_t->second.team_inroom[0],room_t->second.team_inroom[1],room_t->second.team_inroom[2],room_t->second.team_inroom[3],room_t->second.ready[0],room_t->second.ready[1],room_t->second.ready[2],room_t->second.ready[3] }; SendPacket(id, &roomList); tempcount++; room_t++; } else { break; } } //SendPacket(id, &room_page); } } int main() { vector <thread> w_threads; conn_ptr = mysql_init(NULL); initialize(); for (int i = 0; i < 4; ++i) w_threads.push_back(thread{ worker_thread }); thread a_thread{ accept_thread }; thread timer_Thread{ Timer_thread }; for (auto& th : w_threads) th.join(); a_thread.join(); timer_Thread.join(); } void SetMap(unsigned char maptype, unsigned char mapnum, unsigned char room_num, TB_Map* map) { map->size = SIZEOF_TB_MAP; map->type = CASE_MAP; memcpy(map->mapInfo, &g_TB_Map[mapnum][maptype], sizeof(Map_TB)); for (int i = 0; i < 15; ++i) { for (int j = 0; j < 15; ++j) { cout << map->mapInfo[i][j] << " "; } cout << endl; } } void SetMapToValue(int maptype, int mapnum) { if (maptype == 0 || maptype == 2) { ifstream in("Map1-1.txt"); vector <string> v({ istream_iterator<string>(in),istream_iterator<string>() }); in.close(); vector<string> string_list; for (int i = 3 + (mapnum * 15); i < 18 + (mapnum * 15); ++i) { string wordlist; for (auto word : v[i]) { if (word == v[i].back()) { } if (word == ',' || word == '\0') { cout << wordlist << " "; string_list.emplace_back(wordlist); wordlist.clear(); } else { //cout << word << " "; wordlist += word; } } cout << endl << endl; int x = 0; int z = 0; for (auto a : string_list) { if (x >= 5) { g_TB_Map[maptype][mapnum].mapTile[z][x - 5] = atoi(a.c_str()); } if (x < 20) ++x; if (x >= 20) { x = 0; z = z + 1; } } } } else if (maptype == 1) { ifstream in("Map2-1.txt"); vector <string> v({ istream_iterator<string>(in),istream_iterator<string>() }); in.close(); vector<string> string_list; for (int i = 3 + (mapnum * 15); i < 18 + (mapnum * 15); ++i) { string wordlist; for (auto word : v[i]) { if (word == v[i].back()) { } if (word == ',' || word == '\0') { cout << wordlist << " "; string_list.emplace_back(wordlist); wordlist.clear(); } else { //cout << word << " "; wordlist += word; } } cout << endl << endl; int x = 0; int z = 0; for (auto a : string_list) { if (x >= 5) { g_TB_Map[maptype][mapnum].mapTile[z][x - 5] = atoi(a.c_str()); } if (x < 20) ++x; if (x >= 20) { x = 0; z = z + 1; } } } } } void CopyRoomAtoB(TB_Room* a, TB_RoomInfo*b) { b->room_num = a->roomID; b->game_start = a->game_start; b->people_max = a->people_max; b->people_count = a->people_count; } void BoxPush_Calculate_Map(int x, int z, BYTE room_num, TB_BoxPushRE* temppacket, BYTE direction, TB_MapSetRE* tempp) { BYTE tempMap[15][15]; memcpy(tempMap, gameRoom_Manager[room_num].map.mapInfo, sizeof(tempMap)); //tempMap[z][x] = MAP_NOTHING; int tempx = x; int tempz = z; int startx = x; int startz = z; temppacket->push = 0; //direction에따라 어디로 차는지 알고 검색 1-우 2-좌 3-하 4-상 switch (direction) { case 1: if (tempx > 14) { temppacket->push = 0; tempx = 14; } else if (tempMap[z][x + 1] == MAP_NOTHING || tempMap[z][x + 1] == MAP_ITEM || tempMap[z][x + 1] == MAP_ITEM_F || tempMap[z][x + 1] == MAP_ITEM_S) { temppacket->push = 0; tempx = x + 1; } else if (tempMap[z][x + 1] == MAP_BOX) { startx = x + 1; if (x + 2 > 14) { temppacket->push = 0; tempx = 14; } else if (tempMap[z][x + 2] == MAP_NOTHING || tempMap[z][x + 2] == MAP_ITEM || tempMap[z][x + 2] == MAP_ITEM_F || tempMap[z][x + 2] == MAP_ITEM_S) { temppacket->push = 1; tempx = x + 2; } } break; case 2: if (tempx < 0) { temppacket->push = 0; tempx = 0; } else if (tempMap[z][x - 1] == MAP_NOTHING || tempMap[z][x - 1] == MAP_ITEM || tempMap[z][x - 1] == MAP_ITEM_F || tempMap[z][x - 1] == MAP_ITEM_S) { temppacket->push = 0; tempx = x - 1; } else if (tempMap[z][x - 1] == MAP_BOX) { startx = x - 1; if (x - 2< 0) { temppacket->push = 0; tempx = 0; } else if (tempMap[z][x - 2] == MAP_NOTHING || tempMap[z][x - 2] == MAP_ITEM || tempMap[z][x - 2] == MAP_ITEM_F || tempMap[z][x - 2] == MAP_ITEM_S) { temppacket->push = 1; tempx = x - 2; } } break; case 3: if (tempz > 14) { temppacket->push = 0; tempz = 14; } else if (tempMap[z + 1][x] == MAP_NOTHING || tempMap[z + 1][x] == MAP_ITEM || tempMap[z + 1][x] == MAP_ITEM_F || tempMap[z + 1][x] == MAP_ITEM_S) { temppacket->push = 0; tempz = z; } else if (tempMap[z + 1][x] == MAP_BOX) { startz = z + 1; if (z + 2 > 14) { temppacket->push = 0; tempz = 14; } else if (tempMap[z + 2][x] == MAP_NOTHING || tempMap[z + 2][x] == MAP_ITEM || tempMap[z + 2][x] == MAP_ITEM_F || tempMap[z + 2][x] == MAP_ITEM_S) { temppacket->push = 1; tempz = z + 2; } } break; case 4: if (tempz < 0) { temppacket->push = 0; tempz = 0; } else if (tempMap[z - 1][x] == MAP_NOTHING || tempMap[z - 1][x] == MAP_ITEM || tempMap[z - 1][x] == MAP_ITEM_F || tempMap[z - 1][x] == MAP_ITEM_S) { temppacket->push = 0; tempz = z; } else if (tempMap[z - 1][x] == MAP_BOX) { startz = z - 1; if (z - 2 <0) { temppacket->push = 0; tempz = 0; } else if (tempMap[z - 2][x] == MAP_NOTHING || tempMap[z - 2][x] == MAP_ITEM || tempMap[z - 2][x] == MAP_ITEM_F || tempMap[z - 2][x] == MAP_ITEM_S) { temppacket->push = 1; tempz = z - 2; } } break; default: printf("Unknown Direction!!!!\n"); break; } //throw관련 송신패킷구조체에 넣어줘야 한다. if (temppacket->push == 1) tempMap[startz][startx] = MAP_NOTHING; temppacket->posx = startx; temppacket->posz = startz; temppacket->posx_d = tempx; temppacket->posz_d = tempz; temppacket->direction = direction; tempp->posx = startx; tempp->posz = startz; memcpy(gameRoom_Manager[room_num].map.mapInfo, tempMap, sizeof(tempMap)); } void Throw_Calculate_Map(int x, int z, BYTE room_num, TB_ThrowBombRE* temppacket, BYTE direction, TB_MapSetRE* tempp) { BYTE tempMap[15][15]; memcpy(tempMap, gameRoom_Manager[room_num].map.mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; int tempx = x; int tempz = z; //direction에따라 어디로 차는지 알고 검색 1-우 2-좌 3-하 4-상 switch (direction) { case 1: tempx = x + 4; if (tempx > 14) tempx = 14; for (int i = tempx; i < 15; ++i) { if (tempMap[z][i] == MAP_NOTHING || tempMap[z][i] == MAP_ITEM || tempMap[z][i] == MAP_BUSH || tempMap[z][i] == MAP_ITEM_F || tempMap[z][i] == MAP_ITEM_S) { tempx = i; tempz = z; break; } if (i == 14) { tempx = i; tempz = z; break; } } break; case 2: tempx = x - 4; if (tempx < 0) tempx = 0; for (int i = tempx; i >= 0; --i) { if (tempMap[z][i] == MAP_NOTHING || tempMap[z][i] == MAP_ITEM || tempMap[z][i] == MAP_BUSH || tempMap[z][i] == MAP_ITEM_F || tempMap[z][i] == MAP_ITEM_S) { tempx = i; tempz = z; break; } if (i == 0) { tempx = i; tempz = z; break; } } break; case 3: tempz = z + 4; if (tempz > 14) tempz = 14; for (int i = tempz; i < 15; ++i) { if (tempMap[i][x] == MAP_NOTHING || tempMap[i][x] == MAP_ITEM || tempMap[i][x] == MAP_BUSH || tempMap[i][x] == MAP_ITEM_F || tempMap[i][x] == MAP_ITEM_S) { tempx = x; tempz = i; break; } if (i == 14) { tempx = x; tempz = i; break; } } break; case 4: tempz = z - 4; if (tempz < 0) tempz = 0; for (int i = tempz; i >= 0; --i) { if (tempMap[i][x] == MAP_NOTHING || tempMap[i][x] == MAP_ITEM || tempMap[i][x] == MAP_BUSH || tempMap[i][x] == MAP_ITEM_F || tempMap[i][x] == MAP_ITEM_S) { tempx = x; tempz = i; break; } if (i == 0) { tempx = x; tempz = i; break; } } break; default: printf("Unknown Direction!!!!\n"); break; } //throw관련 송신패킷구조체에 넣어줘야 한다. temppacket->posx_re = tempx; temppacket->posz_re = tempz; temppacket->posx = x; temppacket->posz = z; temppacket->direction = direction; memcpy(gameRoom_Manager[room_num].map.mapInfo, tempMap, sizeof(tempMap)); } void Kick_CalculateMap(int x, int z, BYTE room_num, TB_KickBombRE* temppacket, BYTE direction, TB_MapSetRE* tempp) { BYTE tempMap[15][15]; memcpy(tempMap, gameRoom_Manager[room_num].map.mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; int tempx = x; int tempz = z; int startx = x; int startz = z; temppacket->kick = 0; //direction에따라 어디로 차는지 알고 검색 1-우 2-좌 3-하 4-상 switch (direction) { case 1: if (tempx > 14) tempx = 14; else if (tempMap[z][x + 1] == MAP_NOTHING || tempMap[z][x + 1] == MAP_ITEM || tempMap[z][x + 1] == MAP_ITEM_F || tempMap[z][x + 1] == MAP_ITEM_S) { temppacket->kick = 0; tempx = x + 1; } else if (tempMap[z][x + 1] == MAP_BOMB) { startx = x + 1; if (x + 2 > 14) { temppacket->kick = 0; tempx = 14; } else if (tempMap[z][x + 2] == MAP_NOTHING || tempMap[z][x + 2] == MAP_ITEM || tempMap[z][x + 2] == MAP_ITEM_F || tempMap[z][x + 2] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z][x + 2 + i] == MAP_ROCK || tempMap[z][x + 2 + i] == MAP_BOMB || tempMap[z][x + 2 + i] == MAP_BOX || x + 2 + i>14) { temppacket->kick = 1; tempx = x + 1 + i; break; } } } } break; case 2: if (tempx < 0) tempx = 0; else if (tempMap[z][x - 1] == MAP_NOTHING || tempMap[z][x - 1] == MAP_ITEM || tempMap[z][x - 1] == MAP_ITEM_F || tempMap[z][x - 1] == MAP_ITEM_S) { temppacket->kick = 0; tempx = x - 1; } else if (tempMap[z][x - 1] == MAP_BOMB) { startx = x - 1; if (x - 2 <0) { temppacket->kick = 0; tempx = 0; } else if (tempMap[z][x - 2] == MAP_NOTHING || tempMap[z][x - 2] == MAP_ITEM || tempMap[z][x - 2] == MAP_ITEM_F || tempMap[z][x - 2] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z][x - 2 - i] == MAP_ROCK || tempMap[z][x - 2 - i] == MAP_BOMB || tempMap[z][x - 2 - i] == MAP_BOX || x - 2 - i<0) { temppacket->kick = 1; tempx = x - 1 - i; break; } } } } break; case 3: if (tempz > 14) tempz = 14; else if (tempMap[z + 1][x] == MAP_NOTHING || tempMap[z + 1][x] == MAP_ITEM || tempMap[z + 1][x] == MAP_ITEM_F || tempMap[z + 1][x] == MAP_ITEM_S) { temppacket->kick = 0; tempz = z + 1; } else if (tempMap[z + 1][x] == MAP_BOMB) { startz = z + 1; if (z + 2 > 14) { temppacket->kick = 0; tempz = 14; } else if (tempMap[z + 2][x] == MAP_NOTHING || tempMap[z + 2][x] == MAP_ITEM || tempMap[z + 2][x] == MAP_ITEM_F || tempMap[z + 2][x] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z + 2 + i][x] == MAP_ROCK || tempMap[z + 2 + i][x] == MAP_BOMB || tempMap[z + 2 + i][x] == MAP_BOX || z + 2 + i>14) { temppacket->kick = 1; tempz = z + 1 + i; break; } } } } break; case 4: if (tempz < 0) tempz = 0; else if (tempMap[z - 1][x] == MAP_NOTHING || tempMap[z - 1][x] == MAP_ITEM || tempMap[z - 1][x] == MAP_ITEM_F || tempMap[z - 1][x] == MAP_ITEM_S) { temppacket->kick = 0; tempz = z - 1; } else if (tempMap[z - 1][x] == MAP_BOMB) { startz = z - 1; if (x - 2 <0) { temppacket->kick = 0; tempz = 0; } else if (tempMap[z - 2][x] == MAP_NOTHING || tempMap[z - 2][x] == MAP_ITEM || tempMap[z - 2][x] == MAP_ITEM_F || tempMap[z - 2][x] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z - 2 - i][x] == MAP_ROCK || tempMap[z - 2 - i][x] == MAP_BOMB || tempMap[z - 2 - i][x] == MAP_BOX || z - 2 - i<0) { temppacket->kick = 1; tempz = z - 1 - i; break; } } } } break; default: printf("Unknown Direction!!!!\n"); break; } //kick관련 송신패킷구조체에 넣어줘야 한다. if (temppacket->kick == 1) tempMap[startz][startx] = MAP_NOTHING; temppacket->posx = startx; temppacket->posz = startz; temppacket->posx_re = tempx; temppacket->posz_re = tempz; temppacket->direction = direction; tempp->posx = startx; tempp->posz = startz; memcpy(gameRoom_Manager[room_num].map.mapInfo, tempMap, sizeof(tempMap)); } void Timer_thread() { while (true) { Sleep(1); DWORD currTime = GetTickCount(); DWORD elapsedTime = currTime - g_prevTime2; g_prevTime2 = currTime; auto t_client = g_clients.begin(); for (; t_client != g_clients.end(); t_client++) { if (t_client->IsUnConnected(currTime)&&t_client->m_isconnected&&t_client->m_scene==0) { cout << "Close Socket" << endl; //closesocket(t_client->m_s); t_client->ChangeRecieveTime(); //t_client->m_isconnected = false; //수정필요 sc_packet_remove_player p; p.id = t_client->id; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; SendPacket(t_client->id-1, &p); DisconnectPlayer(t_client->id-1); //수정필요 } else if (t_client->IsUnConnected_inRoom(currTime) && t_client->m_isconnected&&t_client->m_scene == 1) { cout << "Close Socket_inroom" << endl; //closesocket(t_client->m_s); t_client->ChangeRecieveTime(); //t_client->m_isconnected = false; //수정필요 sc_packet_remove_player p; p.id = t_client->id; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; SendPacket(t_client->id - 1, &p); DisconnectPlayer_inroom(t_client->id - 1); //수정필요 } else if (t_client->IsUnConnected_inGame(currTime) && t_client->m_isconnected&&t_client->m_scene ==2) { cout << "Close Socket_ingame" << endl; //closesocket(t_client->m_s); t_client->ChangeRecieveTime(); //t_client->m_isconnected = false; //수정필요 sc_packet_remove_player p; p.id = t_client->id; p.size = sizeof(p); p.type = SC_REMOVE_PLAYER; SendPacket(t_client->id - 1, &p); DisconnectPlayer_ingame(t_client->id - 1); //수정필요 } } auto a = gameRoom_Manager.begin(); for (; a != gameRoom_Manager.end(); a++) { if (!a->second.is_start) { int tempcount = 0; for (int i = 0; i < a->second.people_count; ++i) { if (a->second.ready_player[i]) tempcount++; } if (tempcount == a->second.people_count) { cout << "ALL READY!!! START!!!" << endl; a->second.is_start = true; } else { cout << "Only " << tempcount << "Player is Ready...Total Player:" << a->second.people_count << endl; } } if (!a->second.IsGameOver()) { if (a->second.is_start) { a->second.SetTime(elapsedTime); if (a->second.OneSec()) { float tempT = a->second.GetTime(); TB_Time temp_t = { SIZEOF_TB_Time,CASE_TIME,tempT }; for (int i = 0; i < 4; ++i) { //cout << "TimeSend" << endl; if (a->second.idList[i] != 0 ) { //cout << i << endl; SendPacket(a->second.idList[i] - 1, &temp_t); } } } if (a->second.AirDropTime()) { cout << "Airdrop_Time!!!" << endl; } if (a->second.bomb_Map.size() > 0) { auto b = a->second.bomb_Map.begin(); for (; b != a->second.bomb_Map.end();) { if (b->second.GetTime()) { int tempx = b->second.GetXZ().first; int tempz = b->second.GetXZ().second; unsigned char tfire = b->second.firepower; unsigned char tempid = b->second.game_id; a->second.CalculateMap(tempx, tempz, tfire, tempid); for (int i = 0; i < 4; ++i) { if (a->second.idList[i] != 0) { auto c = a->second.explode_List.begin(); for (; c != a->second.explode_List.end(); c++) { //cout << (int)c->size<<" "<<(int)c->type << endl; c->size = SIZEOF_TB_BombExplodeRE; c->type = CASE_BOMB_EX; TB_BombExplodeRE bomb = { SIZEOF_TB_BombExplodeRE,CASE_BOMB_EX,c->upfire,c->rightfire,c->downfire,c->leftfire,c->gameID,c->posx,c->posz }; SendPacket(a->second.idList[i] - 1, &bomb); } //cout << "TimeMap" << endl; SendPacket(a->second.idList[i] - 1, &a->second.map); } } a->second.bomb_Map.erase(b++); a->second.explode_List.clear(); //CalculateBomb(); } else { b++; } } } } } } } }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Script_Box : MonoBehaviour { public Text m_Text; public Button m_Next_Button; public static Script_Box c_Script_Box; List<string> m_Script_List; int m_curr_Script_Number = 0; void Awake() { c_Script_Box = this; m_Script_List = new List<string>(); gameObject.SetActive(false); } void Update() { if (gameObject.activeSelf) // 켜져있으면 StageManager.GetInstance().Set_is_Pause(true); // 일시정지 } public void Set_TextList(List<string> s_list) { m_Script_List.Clear(); m_Script_List = s_list; m_curr_Script_Number = 0; if (m_Script_List.Count != 0) Next_Button(); } void Set_Text(int num) { m_Text.text = m_Script_List[num]; } public void Next_Button() { if (m_curr_Script_Number < m_Script_List.Count) { Set_Text(m_curr_Script_Number); ++m_curr_Script_Number; } else { StageManager.GetInstance().Set_is_Pause(false); gameObject.SetActive(false); // 끝이므로 닫기 } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class Turtle_Move : MonoBehaviour { public static Turtle_Move instance; int m_Bombindex_X = 0; int m_Bombindex_Z = 0; // 폭탄 배치를 위한 위치값 float m_BombLocX = 0.0f; float m_BombLocZ = 0.0f; float m_GliderfloatSpeed = 1.0f; public GameObject[] m_DropBomb; bool m_YouCanSetBomb = false; byte id = 0; int touchNum=0; public Text[] state_text; public Button bombButton; public Button throwButton; float m_Touch_PrevPoint_X; public GameObject glider; public float m_PlayerSpeed = 3.0f; float m_RotateSensX = 150.0f; bool dead_ani = false; bool throw_ani = false; bool walk_ani = false; bool push_ani = false; bool kick_ani = false; public bool overpower = false; public GameObject bush_ui; byte direction; byte fire_power = 1; byte bomb_power = 1; byte bomb_set = 1; byte speed_power = 1; public bool can_kick = false; public bool can_throw = false; public bool get_glider = false; public bool glider_on = false; Animator m_TurtleMan_Animator; Animator m_animator; int itemtype=0; bool getItem = false; bool kick_bomb; // 회전 각 public byte alive = 1; float m_RotationX = 0.0f; bool m_is_Touch_Started = false; public Animator animator_camera; void Awake() { instance = this; } // Use this for initialization void Start() { m_animator = GetComponent<Animator>(); //Invoke("SetAnimation", 1.0f); fire_power = 1; bomb_power = 1; speed_power = 1; kick_bomb = false; alive = 1; direction = 0; //Invoke("SetPosition", 2.0f); SetPosition(); } void Throw_Ani_False() { m_animator.SetBool("TurtleMan_isThrow", false); } void Walk_Ani_False() { m_animator.SetBool("TurtleMan_isWalk", false); m_animator.SetBool("TurtleMan_GliderMove", false); } void Push_Ani_False() { m_animator.SetBool("TurtleMan_isPush", false); } void Kick_Ani_False() { m_animator.SetBool("TurtleMan_isKick", false); } void OnCollisionEnter(Collision collision) { if (can_kick && collision.gameObject.CompareTag("Bomb")) { //kick_bomb = true; Bomb_Kick(); } } void OnTriggerEnter(Collider other) { if (other.gameObject.CompareTag("Bomb")) { if (can_throw) { if (!glider_on) { bombButton.gameObject.SetActive(false); throwButton.gameObject.SetActive(true); } } } if (other.gameObject.CompareTag("Bush")) { bush_ui.SetActive(true); } if (other.gameObject.CompareTag("Flame_Bush")) { if (glider_on) { } else { alive = 0; } NetTest.instance.SetmoveTrue(); } } private void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Bomb")) { if (can_throw) { bombButton.gameObject.SetActive(true); throwButton.gameObject.SetActive(false); } other.isTrigger = false; } if (other.gameObject.CompareTag("Bush")) { bush_ui.SetActive(false); } } void SetFalse() { //gameObject.SetActive(false); } public byte GetFirePower() { return fire_power; } public void Throw_Case(byte m_id) { if (id == m_id) { throw_ani = true; } else { switch (m_id) { case 0: NetUser.instance.SetThrowMotion(); break; case 1: NetUser2.instance.SetThrowMotion(); break; case 2: NetUser3.instance.SetThrowMotion(); break; case 3: NetUser4.instance.SetThrowMotion(); break; default: break; } } } public void Kick_Case(byte m_id) { if (id == m_id) { kick_ani = true; kick_bomb = false; } else { switch (m_id) { case 0: NetUser.instance.SetKickMotion(); break; case 1: NetUser2.instance.SetKickMotion(); break; case 2: NetUser3.instance.SetKickMotion(); break; case 3: NetUser4.instance.SetKickMotion(); break; default: break; } } } public void Push_Case(byte m_id) { if (id == m_id) { push_ani = true; } else { switch (m_id) { case 0: NetUser.instance.SetPushMotion(); break; case 1: NetUser2.instance.SetPushMotion(); break; case 2: NetUser3.instance.SetPushMotion(); break; case 3: NetUser4.instance.SetPushMotion(); break; default: break; } } } public void Move_Case(byte m_id) { if (id == m_id) { walk_ani = true; } else { switch (m_id) { case 0: NetUser.instance.SetMoveMotion(); break; case 1: NetUser2.instance.SetMoveMotion(); break; case 2: NetUser3.instance.SetMoveMotion(); break; case 3: NetUser4.instance.SetMoveMotion(); break; default: break; } } } public void Dead_Case(byte m_id) { if (id == m_id) { //죽음 dead_ani = true; } else { switch (m_id) { //상대방이 죽음 case 0: NetUser.instance.SetDeadMotion(); break; case 1: NetUser2.instance.SetDeadMotion(); break; case 2: NetUser3.instance.SetDeadMotion(); break; case 3: NetUser4.instance.SetDeadMotion(); break; default: break; } } } public void SetItem_Ability(byte m_id, byte type) { //getItem = true; /* switch (type) { case 0: bomb_power++; bomb_set++; //Debug.Log("Bomb Up~"); break; case 1: fire_power++; //Debug.Log("Fire Up~"); break; case 2: speed_power++; //Debug.Log("Speed Up~"); break; case 3: can_kick = true; break; case 4: can_throw = true; break; default: break; }*/ if (id == m_id) { getItem = true; switch (type) { case 0: bomb_power++; bomb_set++; if (bomb_power >= 5) bomb_power = 5; if (bomb_set >= 5) bomb_set = 5; itemtype = 0; //Debug.Log("Bomb Up~"); break; case 1: fire_power++; if (fire_power >= 5) fire_power = 5; itemtype = 1; //Debug.Log("Fire Up~"); break; case 2: speed_power++; itemtype = 2; if (speed_power >= 5) speed_power = 5; //Debug.Log("Speed Up~"); break; case 3: can_kick = true; itemtype = 3; break; case 4: can_throw = true; itemtype = 4; break; case 5: get_glider = true; itemtype = 5; break; case 6: bomb_power++; bomb_set++; if (bomb_power >= 5) bomb_power = 5; if (bomb_set >= 5) bomb_set = 5; fire_power++; if (fire_power >= 5) fire_power = 5; speed_power++; if (speed_power >= 5) speed_power = 5; itemtype = 6; break; default: break; } } else { //Debug.Log("Not Mine" + id + "!=" + m_id); switch (m_id) { case 0: NetUser.instance.SetText(type); break; case 1: NetUser2.instance.SetText(type); break; case 2: NetUser3.instance.SetText(type); break; case 3: NetUser4.instance.SetText(type); break; default: break; } } } void SetPosition() { switch (VariableManager.instance.pos_inRoom) { case 1: id = 0; transform.position = new Vector3(0.0f, transform.position.y, 0.0f); break; case 2: id = 1; transform.position = new Vector3(28.0f, transform.position.y, 0.0f); break; case 3: id = 2; transform.position = new Vector3(0.0f, transform.position.y, 28.0f); transform.Rotate(new Vector3(0, 180.0f, 0)); break; case 4: id = 3; transform.position = new Vector3(28.0f, transform.position.y, 28.0f); transform.Rotate(new Vector3(0, 180.0f, 0)); break; default: break; } } void SetOPOff() { overpower = false; } // Update is called once per frame void Update() { GetComponent<Rigidbody>().velocity = new Vector3(0.0f, 0.0f, 0.0f); state_text[0].text = bomb_set + " / " + bomb_power; state_text[1].text = "" + fire_power; state_text[2].text = "" + speed_power; if (get_glider) { MusicManager.manage_ESound.ItemGetSound(); gameObject.transform.position = new Vector3(gameObject.transform.position.x, 2.0f, gameObject.transform.position.z); get_glider = false; glider_on = true; } if (getItem) { VSModeManager.instance.GetItemUI_Activate(itemtype); MusicManager.manage_ESound.ItemGetSound(); getItem = false; } if (glider_on) { alive = 2; m_animator.SetBool("TurtleMan_GetGlider", true); glider.SetActive(true); if (gameObject.transform.position.y >= 3.0f) m_GliderfloatSpeed = -0.01f; else if (gameObject.transform.position.y <= 2.0f) m_GliderfloatSpeed = 0.01f; gameObject.transform.position = new Vector3(gameObject.transform.position.x, gameObject.transform.position.y + (m_GliderfloatSpeed), gameObject.transform.position.z); } else { m_animator.SetBool("TurtleMan_GetGlider", false); glider.SetActive(false); gameObject.transform.position = new Vector3(gameObject.transform.position.x, -0.3f, gameObject.transform.position.z); } if (overpower) { Invoke("SetOPOff", 1.5f); } if (dead_ani) { //Debug.Log("Dead!!!"); m_animator.SetBool("TurtleMan_isDead", true); Invoke("SetFalse", 2.1f); dead_ani = false; } if (push_ani) { m_animator.SetBool("TurtleMan_isPush", true); Invoke("Push_Ani_False", 1.0f); push_ani = false; } if (kick_ani) { m_animator.SetBool("TurtleMan_isKick", true); Invoke("Kick_Ani_False", 1.0f); kick_ani = false; } if (walk_ani) { if(glider_on) m_animator.SetBool("TurtleMan_GliderMove", true); else m_animator.SetBool("TurtleMan_isWalk", true); Invoke("Walk_Ani_False", 1.0f); walk_ani = false; } if (throw_ani) { m_animator.SetBool("TurtleMan_isThrow", true); Invoke("Throw_Ani_False", 1.0f); throw_ani = false; } /* if (Input.GetMouseButton(0)) { m_RotationX += Input.GetAxis("Mouse X") * m_RotateSensX * Time.deltaTime; transform.localEulerAngles = new Vector3(0.0f, m_RotationX, 0.0f); if(!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); }*/ if (!Camera_Directing_Net.GetInstance().ani_is_working) { if (JoyStickMove.instance.Get_NormalizedVector() != Vector3.zero) { Vector3 normal = JoyStickMove.instance.Get_NormalizedVector(); normal.z = normal.y; normal.y = 0.0f; if (!glider_on) { transform.Translate((m_PlayerSpeed + speed_power) * normal * Time.deltaTime); } else transform.Translate((m_PlayerSpeed + 4) * normal * Time.deltaTime); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); } else { // 릴리즈 빌드할 때는 적용할 것! if (glider_on) m_animator.SetBool("TurtleMan_GliderMove", false); else m_animator.SetBool("TurtleMan_isWalk", false); } BodyRotation(); // ================== if (Input.GetKey(KeyCode.W)) { if (glider_on) { transform.Translate(new Vector3(0.0f, 0.0f, (m_PlayerSpeed + 4) * Time.deltaTime)); } else transform.Translate(new Vector3(0.0f, 0.0f, (m_PlayerSpeed + speed_power) * Time.deltaTime)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); } if (Input.GetKey(KeyCode.S)) { if (glider_on) { transform.Translate(new Vector3(0.0f, 0.0f, -(m_PlayerSpeed + 4) * Time.deltaTime)); } else transform.Translate(new Vector3(0.0f, 0.0f, -(m_PlayerSpeed + speed_power) * Time.deltaTime)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); } if (Input.GetKey(KeyCode.A)) { if (glider_on) { transform.Translate(new Vector3(-(m_PlayerSpeed + 4) * Time.deltaTime, 0.0f, 0.0f)); } else transform.Translate(new Vector3(-(m_PlayerSpeed + speed_power) * Time.deltaTime, 0.0f, 0.0f)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); } if (Input.GetKey(KeyCode.D)) { if (glider_on) { transform.Translate(new Vector3((m_PlayerSpeed + 4) * Time.deltaTime, 0.0f, 0.0f)); } else transform.Translate(new Vector3((m_PlayerSpeed + speed_power) * Time.deltaTime, 0.0f, 0.0f)); if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); } if (Input.GetKeyDown(KeyCode.Space)) { if (!VSModeManager.instance.game_set) SetBomb(); } } } public void ReloadBomb(byte tID) { if (id == tID) { bomb_set++; } } public byte GetId() { return id; } public void SetBomb() // 폭탄 설치 { if (!Camera_Directing_Net.GetInstance().ani_is_working) { m_YouCanSetBomb = true; // 폭탄 위치 설정 m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; if (MapManager.instance.Check_BombSet((int)(m_BombLocX / 2), (int)(m_BombLocZ / 2))) { //Debug.Log("You can't set bomb"); m_YouCanSetBomb = false; } // 이미 놓인 폭탄 검사 // 폭탄 생성 if (m_YouCanSetBomb && bomb_set > 0) { bomb_set--; NetTest.instance.SetBombPos((int)m_BombLocX, (int)m_BombLocZ, fire_power); NetTest.instance.SendBombPacket(); //UI.m_bomb_count = UI.m_bomb_count - 1; } } } public void Box_Push() { float yRotation = gameObject.transform.eulerAngles.y; ////Debug.Log(yRotation); if (yRotation >= 315.0f || yRotation < 45.0f) direction = 3; else if (yRotation >= 45.0f && yRotation < 135.0f) direction = 1; else if (yRotation >= 135.0f && yRotation < 225.0f) direction = 4; else if (yRotation >= 225.0f && yRotation < 315.0f) direction = 2; m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; m_BombLocX = m_BombLocX / 2; m_BombLocZ = m_BombLocZ / 2; NetTest.instance.PushBox_Packet(direction, (int)m_BombLocX, (int)m_BombLocZ); } public void Bomb_Throw() // 폭탄 던지기 { float yRotation = gameObject.transform.eulerAngles.y; ////Debug.Log(yRotation); if (yRotation >= 315.0f || yRotation < 45.0f) direction = 3; else if (yRotation >= 45.0f && yRotation < 135.0f) direction = 1; else if (yRotation >= 135.0f && yRotation < 225.0f) direction = 4; else if (yRotation >= 225.0f && yRotation < 315.0f) direction = 2; m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; m_BombLocX = m_BombLocX / 2; m_BombLocZ = m_BombLocZ / 2; NetTest.instance.SendBomb_TPacket(direction, (int)m_BombLocX, (int)m_BombLocZ); bombButton.gameObject.SetActive(true); throwButton.gameObject.SetActive(false); } public void Bomb_Kick() { float yRotation = gameObject.transform.eulerAngles.y; ////Debug.Log(yRotation); if (yRotation >= 315.0f || yRotation < 45.0f) direction = 3; else if (yRotation >= 45.0f && yRotation < 135.0f) direction = 1; else if (yRotation >= 135.0f && yRotation < 225.0f) direction = 4; else if (yRotation >= 225.0f && yRotation < 315.0f) direction = 2; m_Bombindex_X = (int)transform.position.x; m_Bombindex_Z = (int)transform.position.z; if (m_Bombindex_X % 2 == 1) { m_BombLocX = m_Bombindex_X + 1.0f; } else if (m_Bombindex_X % 2 == -1) { m_BombLocX = m_Bombindex_X - 1.0f; } else m_BombLocX = m_Bombindex_X; if (m_Bombindex_Z % 2 == 1) { m_BombLocZ = m_Bombindex_Z + 1.0f; } else if (m_Bombindex_Z % 2 == -1) { m_BombLocZ = m_Bombindex_Z - 1.0f; } else m_BombLocZ = m_Bombindex_Z; m_BombLocX = m_BombLocX / 2; m_BombLocZ = m_BombLocZ / 2; NetTest.instance.SendBomb_KPacket(direction, (int)m_BombLocX, (int)m_BombLocZ); } void BodyRotation() { if (VSModeManager.instance.Get_isClicked()) // 조이스틱 + 회전 + ... { if (!m_is_Touch_Started) { if (JoyStickMove.instance.Get_is_Joystick_First_Touched_Net()) // 조이스틱이 먼저면 touchNum = 1; else touchNum = 0; // 회전이 먼저면 m_is_Touch_Started = true; } switch (Input.GetTouch(touchNum).phase) // 회전 처리 { case TouchPhase.Began: m_Touch_PrevPoint_X = Input.GetTouch(touchNum).position.x; break; case TouchPhase.Moved: transform.Rotate(0, (Input.GetTouch(touchNum).position.x - m_Touch_PrevPoint_X) * 0.5f, 0); m_Touch_PrevPoint_X = Input.GetTouch(touchNum).position.x; if (!VSModeManager.instance.game_set) NetTest.instance.SetMyPos(transform.position.x, transform.localEulerAngles.y, transform.position.z); break; } } else m_is_Touch_Started = false; } public void MakeGameOverAni() { animator_camera.SetTrigger("Dead"); } public void AniBomb_Start() { animator_camera.SetTrigger("Ring"); } public void KeyBoard_Move() // 플레이어 이동 및 회전 { } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using System; public class Boss_AI_Coop : MonoBehaviour { public static Boss_AI_Coop instance; public RawImage m_Boss_HP_Bar; // 보스 HP바 이미지 public RawImage m_Boss_HP_Character; // 보스 HP바 캐릭터 public int hp; float m_Attack_Speed = 1.5f; int target; byte[] copy_info = new byte[16]; public byte bossani; public byte boss_damaged; public byte boss_alive; public byte boss_target = 1; public float bossX = 14.0f; public float bossZ = 14.0f; public float boss_rotY = 1.0f; public GameObject m_Attack_Collider; public GameObject m_Attack_Collider_UI; public GameObject[] m_Flame_Crash; void Awake() { instance =this; } // Use this for initialization void Start () { for(int i = 0; i < 5; ++i) { m_Flame_Crash[i].SetActive(false); } m_Attack_Collider.SetActive(false); hp = 30; Boss_HP_Gauge.GetInstance().Set_Max_HP(hp); boss_damaged = 0; transform.position = new Vector3(14.0f, transform.position.y, 14.0f); transform.rotation = new Quaternion(transform.rotation.x, boss_rotY, transform.rotation.z, transform.rotation.w); } public void SetBossState(byte[] a) { bossani = a[2]; hp = a[3]; boss_damaged = a[4]; } public void SetBossPoss(byte[] a) { Buffer.BlockCopy(a, 2, copy_info, 0, 16); // Debug.Log("Copy PosSet_Boss"); // Debug.Log("End PosSet_Boss"); bossani = copy_info[0]; boss_alive = copy_info[1]; if (boss_alive == 2) { boss_target = copy_info[2]; } else { boss_target = copy_info[2]; bossX = BitConverter.ToSingle(copy_info, 4); bossZ = BitConverter.ToSingle(copy_info, 8); boss_rotY = BitConverter.ToSingle(copy_info, 12); } //boss_rotY = (boss_rotY * 2.0f) - 1.0f; } void SetAniState(byte anistate) { switch (anistate) { case (byte)0: break; case (byte)1: GetComponent<Animator>().SetBool("OrkBoss_isHurt", false); GetComponent<Animator>().SetBool("OrkBoss_isAttack", false); GetComponent<Animator>().SetBool("OrkBoss_isSummon", false); GetComponent<Animator>().SetBool("OrkBoss_isWalk", true); break; case (byte)2: if (!GetComponent<Animator>().GetBool("OrkBoss_isSummon")) { GetComponent<Animator>().SetBool("OrkBoss_isHurt", false); GetComponent<Animator>().SetBool("OrkBoss_isWalk", false); GetComponent<Animator>().SetBool("OrkBoss_isSummon", false); GetComponent<Animator>().SetBool("OrkBoss_isAttack", true); } bossani = 0; break; case (byte)3: GetComponent<Animator>().SetBool("OrkBoss_isWalk", false); GetComponent<Animator>().SetBool("OrkBoss_isAttack", false); GetComponent<Animator>().SetBool("OrkBoss_isSummon", true); Skill_Fire_Crash(); bossani = 0; break; case (byte)4: GetComponent<Animator>().SetBool("OrkBoss_isWalk", false); GetComponent<Animator>().SetBool("OrkBoss_isAttack", false); GetComponent<Animator>().SetBool("OrkBoss_isHurt", true); bossani = 0; break; case (byte)5: GetComponent<Animator>().SetBool("OrkBoss_isDead", true); break; } } void Skill_Fire_Crash() { for (int i = 0; i < 5; ++i) { m_Flame_Crash[i].SetActive(true); } } // Update is called once per frame void Update () { int hp_current = hp; Vector3 newPos; newPos.x = 0 - (hp_current * 10); newPos.y = 0.0f; newPos.z = 0.0f; if (GetComponent<Animator>().GetCurrentAnimatorStateInfo(0).normalizedTime >= 0.2f && GetComponent<Animator>().GetBool("OrkBoss_isAttack")) // 초기 부분 { GetComponent<Animator>().SetFloat("Attack_Speed", m_Attack_Speed); // 슬로우모션 후 뒷부분은 빠르게하기 위해.. m_Attack_Collider.SetActive(true); // 공격용 충돌체를 꺼낸다. m_Attack_Collider_UI.SetActive(true); // 공격용 충돌체를 꺼낸다. } else { GetComponent<Animator>().SetFloat("Attack_Speed", 0.2f); m_Attack_Collider.SetActive(false); m_Attack_Collider_UI.SetActive(false); // 공격용 충돌체를 꺼낸다. } SetAniState(bossani); if (boss_damaged == 1) { Boss_HP_Gauge.GetInstance().Set_Curr_HP(hp_current); //m_Boss_HP_Character.GetComponent<Animator>().SetTrigger("Damaged"); boss_damaged = 0; } Vector3 newPos2; newPos2.x = 260.0f - (hp_current * 17); newPos2.y = 60.0f; newPos2.z = 0.0f; //m_Boss_HP_Bar.rectTransform.sizeDelta = new Vector2(585.0f - (hp_current * 19), 30); //m_Boss_HP_Bar.rectTransform.localPosition = newPos; //m_Boss_HP_Character.rectTransform.localPosition = newPos2; target = boss_target; //Debug.Log(bossX+","+bossZ); if (!GetComponent<Animator>().GetBool("OrkBoss_isSummon")) { Vector3 targetPos = new Vector3(bossX, -0.76f, bossZ); transform.position = Vector3.Lerp(transform.position, targetPos, Time.deltaTime * 1.5f); if (target > 0) { if (target == VariableManager_Coop.instance.pos_id) { // Debug.Log("Look at Me!!"); transform.LookAt(CoOpManager.instance.myturtle.transform); } else { //Debug.Log(target); if (CoOpManager.instance.m_net_user[target - 1].activeInHierarchy) transform.LookAt(CoOpManager.instance.m_net_user[target - 1].transform); } boss_rotY = transform.eulerAngles.y; } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class BoxCollider_z : MonoBehaviour { //public static BoxCollider_z instance; BoxCollider m_box_col; // Use this for initialization void Start() { m_box_col = GetComponent<BoxCollider>(); } public void ChangeBoxColZ(int down, int up) { m_box_col = GetComponent<BoxCollider>(); float centerz = ((float)((up - down) / 2.0f)) * 2; int sizez = (down + up + 1) * 2; m_box_col.center = new Vector3(0, centerz, -2); m_box_col.size = new Vector3(2, sizez, 4); } // Update is called once per frame void Update() { } void OnTriggerEnter(Collider other) { if (gameObject.activeInHierarchy) { if (!Camera_Directing_Net.GetInstance().ani_is_working) { if (other.gameObject.CompareTag("Player")) { if (SceneManager.GetActiveScene().buildIndex == 7 || SceneChange.instance.GetSceneState() == 13) { if (Turtle_Move.instance.alive != 0) { //Debug.Log("TTaGawa"); if (Turtle_Move.instance.glider_on) { Turtle_Move.instance.alive = 1; Turtle_Move.instance.glider_on = false; Turtle_Move.instance.overpower = true; } else { if (!Turtle_Move.instance.overpower) Turtle_Move.instance.alive = 0; } NetTest.instance.SetmoveTrue(); } } else { Turtle_Move_Coop.instance.alive = 0; NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; // 게임 씬 UI 함수 public class UI_Beta : MonoBehaviour { static UI_Beta m_Instance; public static UI_Beta GetInstance() { return m_Instance; } // ========= Notice UI ========= public GameObject m_Intro_Fade; public GameObject m_Direction_Skip_Button; public GameObject m_Option_UI; // 옵션 버튼 public Text m_FireCountText; // 플레이어 화력 텍스트 public Text m_BombCountText; // 플레이어 폭탄 텍스트 public Text m_SpeedCountText; // 플레이어 스피드 텍스트 public Text m_GetItemText; // 아이템 획득 UI 텍스트 public Text m_TimeLimitText; // 시간 텍스트 public RawImage m_GetItemBackground; // 아이템 획득시 출력 이미지 public RawImage m_GetItemImage; // 아이템 획득시 출력 이미지 public Texture m_Bomb_Icon; public Texture m_Fire_Icon; public Texture m_Speed_Icon; public Texture m_Kick_Icon; public Texture m_Throw_Icon; public Texture m_AirDrop_Icon; public Animator m_KickIcon_Animator; // 발차기 아이콘 애니메이터 public Animator m_ThrowIcon_Animator; // 던지기 아이콘 애니메이터 public Animator m_GetItem_Animator; // 아이템 획득 UI 애니메이터 public Image m_InBushImage; // 부쉬 입장 효과 public Button m_PushButton; // 밀기 버튼 public Button m_Set_Bomb_Button; // 폭탄 설치 버튼 public Button m_Throw_Bomb_Button; // 폭탄 던지기 버튼 public Animator ani; // 애니메이터 float deltaTime = 0.0f; // 시간 변수 // ============================= // ==== 스테이지 클리어 UI ===== public GameObject m_Stage_Clear_UI; public Texture m_Activated_Star_Texture; // 활성화된 별 텍스쳐 public Texture m_Deactivated_Star_Texture; // 비활성화된 별 텍스쳐 // ============================= // ===========미션 UI=========== public Text[] m_MissionText; public RawImage[] m_Mission_Star_Images; int m_timeLimit = 0; int m_monsterKill = 0; bool m_is_Goal = false; bool m_is_Boss_Kill = false; List<Adventure_Quest_Data> m_QuestList; // 퀘스트 목록 // ============================= // ======== 게임오버 UI ======== GameObject m_GameOver_UI; // ============================= // UI에 표시될 변수 float time_Second; // 경과시간 float m_Elapsed_Time = 0.0f; // 클릭 bool m_isClicked = false; void Awake() { m_Instance = this; StageManager_Copy.GetInstance().Init_Left_Time(); Application.targetFrameRate = 30; } void Start() { m_GameOver_UI = GetComponentInChildren<GameOver_UI>().gameObject; m_Option_UI = GameObject.FindGameObjectWithTag("Option_UI"); m_Option_UI.SetActive(false); m_InBushImage.gameObject.SetActive(false); Push_Button_Management(false); // 밀기버튼 비활성 // 폭탄 설치/던지기 활성/비활성 m_Set_Bomb_Button.gameObject.SetActive(true); m_Throw_Bomb_Button.gameObject.SetActive(false); GetItemUI_Deactivate(); m_QuestList = new List<Adventure_Quest_Data>(); StageManager_Copy.GetInstance().GetQuestList(ref m_QuestList); for (int i = 0; i < 3; ++i) { // 퀘스트 id가 1번 (잔여시간) 이면 시간을 받아온다. if (m_QuestList[i].Quest_ID == 1) m_timeLimit = m_QuestList[i].Quest_Goal; // 퀘스트 id가 2번 (일반 몬스터 킬) 이면 몬스터 수를 받아온다. else if (m_QuestList[i].Quest_ID == 2) m_monsterKill = m_QuestList[i].Quest_Goal; } m_Direction_Skip_Button.SetActive(false); StartCoroutine(Wait_For_Intro()); } IEnumerator Wait_For_Intro() { while (true) { if (StageManager_Copy.GetInstance().Get_is_Intro_Over()) { StopAllCoroutines(); StartCoroutine(UI_Update()); } yield return null; } } // FPS 출력 void OnGUI() { int w = Screen.width, h = Screen.height; GUIStyle style = new GUIStyle(); Rect rect = new Rect(0, 0, w, h * 2 / 100); style.alignment = TextAnchor.UpperLeft; style.fontSize = h * 2 / 100; style.normal.textColor = new Color(0.0f, 0.0f, 0.5f, 1.0f); float msec = deltaTime * 1000.0f; float fps = 1.0f / deltaTime; string text = string.Format("{0:0.0} ms ({1:0.} fps)", msec, fps); GUI.Label(rect, text, style); } // 나가기 버튼 public void StageClear_ExitButton() { StageManager_Copy.GetInstance().Set_is_Pause(true); if (LobbySound.instanceLS != null && PlayerPrefs.GetInt("System_Option_BGM_ON") != 0) LobbySound.instanceLS.SoundStart(); SceneManager.LoadScene(2); } // 재시작 버튼 public void StageClear_RestartButton() { StageManager_Copy.GetInstance().Set_is_Pause(true); SceneManager.LoadScene(3); } // 아이템 스탯 UI 관리 public void Stat_UI_Management(int cbc, int mbc, int fc, int sc) { // 화력, 폭탄 설치 갯수, 스피드 정보 출력 m_FireCountText.text = fc.ToString(); if (cbc >= MAX_STATUS.BOMB) m_BombCountText.text = cbc.ToString() + " / max"; else m_BombCountText.text = cbc.ToString() + " / " + mbc.ToString(); m_SpeedCountText.text = sc.ToString(); } // 박스밀기 버튼 관리 public void Push_Button_Management(bool is_On) { if (!StageManager_Copy.GetInstance().Get_is_Pause()) { ColorBlock cb = m_PushButton.colors; Color c; if (!is_On) { c = Color.gray; m_PushButton.interactable = false; } else { c = Color.white; m_PushButton.interactable = true; } cb.normalColor = c; m_PushButton.colors = cb; } } // 부쉬 입장시 색 변화 효과 public void HideInBush_Management(bool is_On) {m_InBushImage.gameObject.SetActive(is_On);} // 던지기 버튼 관리 public void Throw_Button_Management(bool is_On) { // 던지기 버튼 활성화 if (is_On) { m_Set_Bomb_Button.gameObject.SetActive(false); m_Throw_Bomb_Button.gameObject.SetActive(true); } else { m_Set_Bomb_Button.gameObject.SetActive(true); m_Throw_Bomb_Button.gameObject.SetActive(false); } } // 미션 UI 관리 void Mission_UI_Management() { for (int i = 0; i < 3; ++i) { if (m_QuestList[i].Quest_ID == 1) // 시간제한 { m_MissionText[i].text = m_QuestList[i].Quest_Script + " " + ((int)time_Second).ToString() + " / " + m_timeLimit.ToString(); if (time_Second > m_timeLimit) m_Mission_Star_Images[i].texture = m_Activated_Star_Texture; else m_Mission_Star_Images[i].texture = m_Deactivated_Star_Texture; } else if (m_QuestList[i].Quest_ID == 2) // 일반 몬스터 처치 { m_MissionText[i].text = m_QuestList[i].Quest_Script + " " + StageManager_Copy.GetInstance().Get_Left_Normal_Monster_Count().ToString() + " / " + m_monsterKill.ToString(); if (StageManager_Copy.GetInstance().Get_Left_Normal_Monster_Count() >= m_monsterKill) m_Mission_Star_Images[i].texture = m_Activated_Star_Texture; } else // 목표도달, 보스 처치, 튜토리얼 { m_MissionText[i].text = m_QuestList[i].Quest_Script; if (m_is_Goal || m_is_Boss_Kill) { m_Mission_Star_Images[i].texture = m_Activated_Star_Texture; } } } } public void Set_is_Goal(bool b) { m_is_Goal = b; Mission_UI_Management(); } public void Set_is_Boss_Kill(bool b) { m_is_Boss_Kill = b; Mission_UI_Management(); } public void Kick_Icon_Activate() { m_KickIcon_Animator.SetBool("is_Icon_Activated", true); } public void Throw_Icon_Activate() { m_ThrowIcon_Animator.SetBool("is_Icon_Activated", true); } public void GetItemUI_Activate(int Item_Num) { switch(Item_Num) { case 0: m_GetItemText.text = "Bomb Up !"; m_GetItemImage.texture = m_Bomb_Icon; break; case 1: m_GetItemText.text = "Fire Up !"; m_GetItemImage.texture = m_Fire_Icon; break; case 2: m_GetItemText.text = "Speed Up !"; m_GetItemImage.texture = m_Speed_Icon; break; case 3: m_GetItemText.text = "Kick Activated !"; m_GetItemImage.texture = m_Kick_Icon; break; case 4: m_GetItemText.text = "Throw Activated !"; m_GetItemImage.texture = m_Throw_Icon; break; case 5: m_GetItemText.text = "You've Got AirDrop !!"; m_GetItemImage.texture = m_AirDrop_Icon; break; } m_GetItemBackground.gameObject.SetActive(true); m_GetItemText.gameObject.SetActive(true); m_GetItemImage.gameObject.SetActive(true); m_GetItem_Animator.SetBool("is_Got_Item", true); Invoke("GetItemUI_Deactivate", 1.4f); } void GetItemUI_Deactivate() { m_GetItem_Animator.SetBool("is_Got_Item", false); m_GetItemBackground.gameObject.SetActive(false); m_GetItemText.gameObject.SetActive(false); m_GetItemImage.gameObject.SetActive(false); } IEnumerator UI_Update() { while(true) { if (!StageManager_Copy.GetInstance().Get_is_Pause()) { // 시간 경과 if (time_Second > 0) { deltaTime += (Time.unscaledDeltaTime - deltaTime) * 0.1f; time_Second = time_Second - deltaTime; m_Elapsed_Time += deltaTime; } // 시간 텍스트 출력 if (time_Second % 60 < 10) m_TimeLimitText.text = "0" + (int)time_Second / 60 + ":0" + (int)time_Second % 60; else m_TimeLimitText.text = "0" + (int)time_Second / 60 + ":" + (int)time_Second % 60; Mission_UI_Management(); // 미션 UI 출력 StageManager_Copy.GetInstance().Summon_SuddenDeath_Glider(); // 시간촉박 애니매이션 출력, 초기에는 애니매이션을 꺼놨다가 발동 -R if (time_Second < 15.0f) ani.enabled = true; else ani.enabled = false; if (time_Second <= 0) { time_Second = 0; GameOver_Directing(); StageManager_Copy.GetInstance().Set_Game_Over(); } } yield return null; } } public void Stage_Clear_Directing() { m_Stage_Clear_UI.GetComponent<Stage_Clear>().Stage_Clear_Direction_Play(); // 스테이지 클리어 연출 발동 } public void GameOver_Directing() { m_GameOver_UI.SetActive(true); m_GameOver_UI.GetComponent<GameOver_UI>().GameOver_Direction_Play(); // 게임 오버 연출 발동 } // 옵션 UI 비활성화 public void Option_UI_Deactivate() { m_Option_UI.SetActive(false); } // 옵션 버튼 UI 활성화 public void Option_Button() { m_Option_UI.SetActive(true); StageManager_Copy.GetInstance().Set_is_Pause(true); } // 옵션의 Return 버튼 (게임으로 돌아가기) public void Option_Return_Button() { StageManager_Copy.GetInstance().Set_is_Pause(false); m_Option_UI.SetActive(false); } public float Get_Left_Time() { return time_Second; } public void Set_Left_Time(float t) { time_Second = t; } public float Get_Elapsed_Time() { return m_Elapsed_Time; } public void Set_Elapsed_Time(float t) { m_Elapsed_Time = t; } public void isClicked() { m_isClicked = true; } public void isClickedOff() { m_isClicked = false; } public bool Get_isClicked() { return m_isClicked; } } <file_sep>using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class GameRoom : MonoBehaviour { public static GameRoom instance; byte my_room_num = 0; public byte pos_inRoom=0; byte pos_guard=0; byte amIguard = 0; byte[] people_inRoom = new byte[4]; public GameObject popup; public Text m_text; public GameObject[] turtles; public TextMesh[] turtle_text; byte m_ready; //0일 경우 ready x, 1일 경우 ready o byte m_guardian; //0일경우는 유저, 1일 경우 방장 byte clicked_position; // Use this for initialization void Awake() { instance = this; //Application.LoadLevel(Application.loadedLevel); //DontDestroyOnLoad(this); } void Start () { SetRoomState(); } public byte GetRoomID() { return my_room_num; } public void StartGame() { NetTest.instance.SendStartPacket(); //SceneChange.instance.GoTo_Game_Scene(); } public void ExitRoom() { //나간다고 패킷 보냄 NetTest.instance.SendOUTPacket(); } public void Popup() { popup.transform.position = new Vector2(Input.mousePosition.x, Input.mousePosition.y); popup.SetActive(true); } public void PopupCancel() { popup.SetActive(false); } public void SetPos1() { clicked_position = 1; } public void SetPos2() { clicked_position = 2; } public void SetPos3() { clicked_position = 3; } public void SetPos4() { clicked_position = 4; } public void BanUser() { bool tempbool01 = people_inRoom[clicked_position - 1] != 0; bool tempbool02 = amIguard == 1; bool tempbool03 = clicked_position != pos_guard; if (tempbool01&&tempbool02&&tempbool03) { //벤 패킷 전송 NetTest.instance.SendBanPacket(clicked_position); } } void SetRoomState() { byte[] temparray = VariableManager.instance.people_inRoom; pos_inRoom = VariableManager.instance.pos_inRoom; //Debug.Log(pos_inRoom); pos_guard = VariableManager.instance.pos_guardian; Buffer.BlockCopy(temparray, 0, people_inRoom, 0, 4); amIguard = VariableManager.instance.is_guardian; my_room_num = VariableManager.instance.m_roomid; } // Update is called once per frame void Update () { //Debug.Log(turtles.Length); if (SceneChange.instance.GetSceneState() == 2) { SetRoomState(); m_text.text = "My position : " + VariableManager.instance.pos_inRoom; for (byte i = 0; i < turtles.Length; ++i) { if (people_inRoom[i] != 0) { turtles[i].SetActive(true); if (people_inRoom[i] == 1) { turtle_text[i].text = "ID : " + people_inRoom[i]; } else if (people_inRoom[i] == 2) { // turtle_text[i].text = "ID : " + people_inRoom[i]+"\n M A S T E R"; } turtle_text[i].text = "ID : " + people_inRoom[i]; //Debug.Log("T.ID : "+people_inRoom[i]); } else { turtles[i].SetActive(false); } } turtles[pos_inRoom - 1].transform.localScale = new Vector3(3, 3, 3); if (pos_guard != 0) turtle_text[pos_guard - 1].text = "ID : " + people_inRoom[pos_guard - 1] + "\n M A S T E R"; } } } <file_sep>#include "stdafx.h" int g_TotalSockets = 0; DWORD io_size, key; Socket_Info SocketInfoArray[WSA_MAXIMUM_WAIT_EVENTS];//유저들을 담을 소켓정보 구조체의 배열 WSAEVENT EventArray[WSA_MAXIMUM_WAIT_EVENTS];//WSAEVENT의 배열 CString GetIpAddress(); Map_TB g_TB_Map[3][4]; //맵 정보2 TB_Map g_TurtleMap_room[20]; //맵 정보2 BYTE fireMap[20][15][15]; BYTE dfMap[20][15][15]; BYTE ufMap[20][15][15]; BYTE lfMap[20][15][15]; BYTE rfMap[20][15][15]; //string real_ip(); TB_CharPos char_info[4]; //4명의 캐릭터정보를 담아둘 캐릭터 정보 ->방 정보가 추가될 경우 2차원배열로 활용할 예정 TB_CharPos ingame_Char_Info[20][4]; //4명의 캐릭터정보를 담아둘 캐릭터 정보 ->방 정보가 추가될 경우 2차원배열로 활용할 예정 InGameCalculator ingamestate[20]; TB_Room room[20]; void Refresh_Map(); //맵을 서버에서 갱신하기 위해 만든 함수 -> 계산도 추가할 예정 void SetMapToValue(int, int); BYTE g_total_member = 1;//현재 접속자의 수 void SetGameRoomInit(BYTE); //list<Bomb_TB> bomb_List; vector<TB_BombExplodeRE> explode_List; map<pair<int,int>,Bomb_TB> bomb_Map[20]; void err_quit(char* msg); //에러 종료 및 출력 함수 void err_display(char* msg); //에러 출력 함수 BOOL AddSOCKETInfo(SOCKET sock); //접속자 소켓 정보 입력 함수 void RemoveSocketInfo(int nIndex);//접속자 중 종료 유저 정보 삭제 함수 void err_display(int errcode);//에러코드에 따른 에러 출력 함수 DWORD g_prevTime2; //GetTickCount()를 활용한 시간을 체크할 때 사용할 함수 void ArrayMap(); //맵 초기화 및 정렬 함수 void ReGame(BYTE); void CalculateMap(int, int, byte, byte, TB_BombExplodeRE*); void CalculateMap_Simple(int, int, byte, byte); void Throw_Calculate_Map(int, int, BYTE, TB_ThrowBombRE*, BYTE); void Kick_CalculateMap(int x, int z, BYTE , TB_KickBombRE* , BYTE, TB_MapSetRE*); void BoxPush_Calculate_Map(int, int, BYTE, TB_BoxPushRE*, BYTE, TB_MapSetRE*); void SetMap(BYTE,BYTE,BYTE); int main(int argc, char* argv[]) { printf("-------------------------------------------------------------------------\n\n%d Server Start\n\n-------------------------------------------------------------------------\n\n", sizeof(char)); ArrayMap(); // 맵 초기화 for (int i = 0; i < 3; ++i) { for (int j = 0; j < 4; ++j) SetMapToValue(i, j); } int retval; //recv, 및 send 등 몇바이트를 받았는가 나타내는 지역변수 WSADATA wsa; //윈속데이터 변수 //기본적인 wsastartup부터 ~ if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) return 0; SOCKET listen_sock = socket(AF_INET, SOCK_STREAM, 0); if (listen_sock == INVALID_SOCKET) err_quit("socket()"); SOCKADDR_IN serveraddr; ZeroMemory(&serveraddr, sizeof(serveraddr)); serveraddr.sin_family = AF_INET; serveraddr.sin_addr.s_addr = htonl(INADDR_ANY); serveraddr.sin_port = htons(TB_SERVER_PORT); CString MyIPadress = GetIpAddress(); char * tmpch; char* myipadd = new char[MyIPadress.GetLength()]; //strcpy(myipadd, CT2A(MyIPadress));  int ipLen= WideCharToMultiByte(CP_ACP, 0, MyIPadress, -1, NULL, 0, NULL, NULL); tmpch = new char[ipLen + 1]; WideCharToMultiByte(CP_ACP, 0, MyIPadress, -1, tmpch, ipLen, NULL, NULL); //cout << real_ip() << endl; cout << MyIPadress.GetLength()<<" "<<ipLen<<endl; cout <<"My IP :"<< (inet_addr(tmpch)) << endl; //delete myipadd; retval = ::bind(listen_sock, (SOCKADDR*)&serveraddr, sizeof(serveraddr)); if (retval == SOCKET_ERROR) err_quit("bind()"); retval = listen(listen_sock, SOMAXCONN); if (retval == SOCKET_ERROR) err_quit("listen()"); //~Listen 까지 //소켓 정보 추가(WSAEventSelect를 위한 소켓 정보 추가)&WSAEventSelect AddSOCKETInfo(listen_sock); retval = WSAEventSelect(listen_sock, EventArray[g_TotalSockets - 1], FD_ACCEPT | FD_CLOSE); if (retval == SOCKET_ERROR) err_quit("WSAEventSelect()"); WSANETWORKEVENTS m_NetworkEvents; SOCKET client_sock; SOCKADDR_IN clientaddr; int i, addrlen; while (1) { //Loop문 //이벤트 객체 관찰하기 DWORD currTime = GetTickCount(); DWORD elapsedTime = currTime - g_prevTime2; g_prevTime2 = currTime; //i = WSAWaitForMultipleEvents(g_TotalSockets, EventArray, FALSE, WSA_INFINITE, FALSE); i = WSAWaitForMultipleEvents(g_TotalSockets, EventArray, FALSE, 1, FALSE); //타임아웃에 걸릴 경우 - 폭탄 시간은 계속 체크하고 있어야 하므로, 여기서도 시간체크를 실행시킨다. if (i == WSA_WAIT_FAILED || i == 258 || i == WAIT_TIMEOUT) { for (int a = 0; a < 20; ++a) { if (room[a].game_start == 1 && !ingamestate[a].IsGameOver()) { ingamestate[a].SetTime(elapsedTime); if (ingamestate[a].OneSec()) { float tempT = ingamestate[a].GetTime(); TB_Time temp_t = { SIZEOF_TB_Time,CASE_TIME,tempT }; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == BYTE(a + 1)) { //printf("시간정보 전송 %f\n", ingamestate[a].GetTime()); retval = send(SocketInfoArray[j].sock, (char*)&temp_t, sizeof(TB_Time), 0); } } } } if (bomb_Map[a].size() > 0) { map<pair<int, int>, Bomb_TB>::iterator bomb = bomb_Map[a].begin(); for (; bomb != bomb_Map[a].end(); ++bomb) { if (bomb->second.GetTime()) { BYTE temproom = bomb->second.room_num; int tempx = bomb->second.xz.first; int tempz = bomb->second.xz.second; BYTE tempfire = bomb->second.firepower; g_TurtleMap_room[temproom - 1].mapInfo[tempz][tempx] = MAP_NOTHING; TB_BombExplodeRE temp_Bomb = { SIZEOF_TB_BombExplodeRE,CASE_BOMB_EX,0,0,0,0,bomb->second.game_id }; CalculateMap(tempx, tempz, tempfire, temproom, &temp_Bomb); fireMap[temproom - 1][tempz][tempx] = 0; g_TurtleMap_room[temproom - 1].size = SIZEOF_TB_MAP; for (int j = 0; j < g_TotalSockets; ++j) { //printf("폭발할 폭탄 전송!!!\n"); if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproom) { //printf("Send size : %d\n", temp_bomb.size); retval = send(SocketInfoArray[j].sock, (char*)&temp_Bomb, sizeof(TB_BombExplodeRE), 0); if (explode_List.size() > 0) { for(int i=0;i<explode_List.size();++i) retval = send(SocketInfoArray[j].sock, (char*)&explode_List[i], sizeof(TB_BombExplodeRE), 0); } //printf("Retval size : %d\n", retval); //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&g_TurtleMap_room[temproom - 1], sizeof(TB_Map), 0); //printf("Retval size : %d\n", retval); } } } explode_List.clear(); bomb_Map[a].erase(bomb++); if (bomb_Map[a].size() <= 0) { break; } } } } } } continue; } else { for (int a = 0; a < 20; ++a) { if (room[a].game_start == 1 && !ingamestate[a].IsGameOver()) { ingamestate[a].SetTime(elapsedTime); if (ingamestate[a].OneSec()) { float tempT = ingamestate[a].GetTime(); TB_Time temp_t = { SIZEOF_TB_Time,CASE_TIME,tempT }; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == BYTE(a + 1)) { //printf("시간정보 전송 %f\n", ingamestate[a].GetTime()); retval = send(SocketInfoArray[j].sock, (char*)&temp_t, sizeof(TB_Time), 0); } } } } if (bomb_Map[a].size() > 0) { map<pair<int, int>, Bomb_TB>::iterator bomb = bomb_Map[a].begin(); for (; bomb != bomb_Map[a].end(); ++bomb) { if (bomb->second.GetTime()) { BYTE temproom = bomb->second.room_num; int tempx = bomb->second.xz.first; int tempz = bomb->second.xz.second; BYTE tempfire = bomb->second.firepower; g_TurtleMap_room[temproom - 1].mapInfo[tempz][tempx] = MAP_NOTHING; TB_BombExplodeRE temp_Bomb = { SIZEOF_TB_BombExplodeRE,CASE_BOMB_EX,0,0,0,0,bomb->second.game_id }; CalculateMap(tempx, tempz, tempfire, temproom, &temp_Bomb); fireMap[temproom - 1][tempz][tempx] = 0; g_TurtleMap_room[temproom - 1].size = SIZEOF_TB_MAP; for (int j = 0; j < g_TotalSockets; ++j) { //printf("폭발할 폭탄 전송!!!\n"); if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproom) { //printf("Send size : %d\n", temp_bomb.size); retval = send(SocketInfoArray[j].sock, (char*)&temp_Bomb, sizeof(TB_BombExplodeRE), 0); for (int i = 0; i<explode_List.size(); ++i) retval = send(SocketInfoArray[j].sock, (char*)&explode_List[i], sizeof(TB_BombExplodeRE), 0); //printf("Retval size : %d\n", retval); //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&g_TurtleMap_room[temproom - 1], sizeof(TB_Map), 0); //printf("Retval size : %d\n", retval); } } } explode_List.clear(); bomb_Map[a].erase(bomb++); if (bomb_Map[a].size() <= 0) { break; } } } } } } i -= WSA_WAIT_EVENT_0; //구체적인 네트워크 이벤트 알아내기 retval = WSAEnumNetworkEvents(SocketInfoArray[i].sock, EventArray[i], &m_NetworkEvents); if (retval == SOCKET_ERROR) continue; //FD_ACCEPT 이벤트 처리 if (m_NetworkEvents.lNetworkEvents&FD_ACCEPT) { if (m_NetworkEvents.iErrorCode[FD_ACCEPT_BIT] != 0) { err_display(m_NetworkEvents.iErrorCode[FD_ACCEPT_BIT]); continue; } addrlen = sizeof(clientaddr); client_sock = accept(SocketInfoArray[i].sock, (SOCKADDR*)&clientaddr, &addrlen); if (client_sock == INVALID_SOCKET) { err_display("accept()"); continue; } printf("[TCP 서버] 클라이언트 접속 : IP 주소 =%s, 포트번호=%d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); TB_ID tempid = { SIZEOF_TB_ID,CASE_ID,g_total_member }; retval = send(client_sock, (char*)&tempid, sizeof(TB_ID), 0); //ID 전송. printf("전송-%d번째 -ID : %d\n", i, g_total_member); // 현재 접속자 수 체크 retval = send(client_sock, (char*)&room, sizeof(room), 0); //초기화된 맵정보 클라이언트에게 전송 printf("방정보 전송 :%d바이트\n", retval); //retval = send(client_sock, (char*)&g_TurtleMap, sizeof(TB_Map), 0); //초기화된 맵정보 클라이언트에게 전송 //printf("맵정보 전송 :%d바이트\n", retval); if (g_TotalSockets >= WSA_MAXIMUM_WAIT_EVENTS) //접속자가 서버의 최대일 경우 { printf("[오류] 더 이상 접속을 받아들일 수 없습니다!!!!!\n"); closesocket(client_sock); continue; } if (retval == SOCKET_ERROR) //send 오류 시 { if (WSAGetLastError() != WSAEWOULDBLOCK) { err_display("send()"); RemoveSocketInfo(i); } continue; } //소켓 정보 추가 AddSOCKETInfo(client_sock); g_total_member++; retval = WSAEventSelect(client_sock, EventArray[g_TotalSockets - 1], FD_READ | FD_WRITE | FD_CLOSE); if (retval == SOCKET_ERROR) err_quit("WSAEventSelect()-client"); } //클라이언트 요청이 읽기나 쓰기일 경우 if (m_NetworkEvents.lNetworkEvents&FD_READ || m_NetworkEvents.lNetworkEvents&FD_WRITE) { if (m_NetworkEvents.lNetworkEvents&FD_READ &&m_NetworkEvents.iErrorCode[FD_READ_BIT] != 0) { err_display(m_NetworkEvents.iErrorCode[FD_READ_BIT]); continue; } if (m_NetworkEvents.lNetworkEvents&FD_WRITE &&m_NetworkEvents.iErrorCode[FD_WRITE_BIT] != 0) { err_display(m_NetworkEvents.iErrorCode[FD_WRITE_BIT]); continue; } Socket_Info* ptr = &SocketInfoArray[i]; int m_temp_id = 0; if (ptr->recvbytes == 0) { //데이터 받기 char recv_buf[MAX_BUFF_SIZE]; retval = recv(ptr->sock, (char*)recv_buf, sizeof(recv_buf), 0); char* c_buf = recv_buf; if (retval == SOCKET_ERROR) { err_display("recv()"); printf("수신 오류 !!\n"); continue; } else { memcpy(ptr->buf + ptr->remainbytes, c_buf, retval); //printf("%d바이트 수신 !!\n", retval); //c_buf[retval] = '\0'; //ptr->buf[retval + ptr->remainbytes] = '\0'; //ptr->recvbytes = ptr->recvbytes+retval; ptr->remainbytes = ptr->remainbytes + retval; //c_buf[ptr->remainbytes] = '\0'; } if (ptr->remainbytes >= 4) { switch (c_buf[1]) { case CASE_POS: //CharPos if (ptr->remainbytes >= SIZEOF_TB_CharPos) { TB_CharPos* pos = reinterpret_cast<TB_CharPos*>(c_buf); //필수 - bool tempbool = false; BYTE tempid = pos->ingame_id; BYTE temproom = pos->room_id; /* char_info[tempid].anistate = pos->anistate; char_info[tempid].is_alive = pos->is_alive; char_info[tempid].posx = pos->posx; char_info[tempid].rotY = pos->rotY; char_info[tempid].posz = pos->posz; */ ingame_Char_Info[temproom - 1][tempid].anistate = pos->anistate; ingame_Char_Info[temproom - 1][tempid].is_alive = pos->is_alive; ingame_Char_Info[temproom - 1][tempid].posx = pos->posx; ingame_Char_Info[temproom - 1][tempid].rotY = pos->rotY; ingame_Char_Info[temproom - 1][tempid].posz = pos->posz; if (!ingame_Char_Info[temproom - 1][tempid].is_alive && !ingamestate[temproom - 1].IsGameOver()) { ingamestate[temproom - 1].PlayerDead(tempid); tempbool = true; printf("%d\n", ingamestate[temproom - 1].deathcount); } //몇명이 죽었는가 테스트 if (ingamestate[temproom - 1].deathcount == (room[temproom - 1].people_count - 1)) { ingamestate[temproom - 1].SetGameOver(); printf("GameOver!!!!%d\n", ingamestate[temproom - 1].deathcount); } //printf("1p포지션값 :x :%f, z:%f , roty:%f \n", char_info[0].posx, char_info[0].posz, char_info[0].rotY); //printf("2p포지션값 :x :%f, z:%f , roty:%f \n", char_info[1].posx, char_info[1].posz, char_info[1].rotY); //printf("3p포지션값 :x :%f, z:%f , roty:%f \n", char_info[2].posx, char_info[2].posz, char_info[2].rotY); //printf("4p포지션값 :x :%f, z:%f , roty:%f \n", char_info[3].posx, char_info[3].posz, char_info[3].rotY); ptr->remainbytes -= SIZEOF_TB_CharPos; memcpy(c_buf, ptr->buf + SIZEOF_TB_CharPos, ptr->remainbytes); memcpy(ptr->buf, c_buf, ptr->remainbytes); for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { //printf("Send size : %d\n", char_info[tempid].size); if (SocketInfoArray[j].roomID == temproom) { ingame_Char_Info[temproom - 1][tempid].size = SIZEOF_TB_CharPos; ingame_Char_Info[temproom - 1][tempid].type = CASE_POS; ingame_Char_Info[temproom - 1][tempid].anistate = 1; retval = send(SocketInfoArray[j].sock, (char*)&ingame_Char_Info[temproom - 1][tempid], sizeof(TB_CharPos), 0); if (ingamestate[temproom - 1].IsGameOver()&& ingamestate[temproom - 1].deathcount == (room[temproom - 1].people_count - 1)) { BYTE winnerid = ingamestate[temproom - 1].GetWinnerID(); TB_GAMEEND gameover = { SIZEOF_TB_GAMEEND,CASE_GAMESET,winnerid }; retval = send(SocketInfoArray[j].sock, (char*)&gameover, sizeof(TB_GAMEEND), 0); } if (tempbool) { TB_DEAD tempd = { SIZEOF_TB_DEAD,CASE_DEAD,tempid }; //retval = send(SocketInfoArray[j].sock, (char*)&tempd, sizeof(TB_DEAD), 0); retval = send(SocketInfoArray[j].sock, (char*)&tempd, sizeof(TB_DEAD), 0); } } //printf("Retval size : %d\n", retval); } } if (ingamestate[temproom - 1].IsGameOver()) ingamestate[temproom - 1].deathcount = 0; break; } break; case CASE_BOMB: if (ptr->remainbytes >= SIZEOF_TB_BombExplode) { TB_BombExplode* b_pos = reinterpret_cast<TB_BombExplode*>(c_buf); int tempx = b_pos->posx; int tempz = b_pos->posz; BYTE roomid = b_pos->room_id; g_TurtleMap_room[roomid - 1].mapInfo[tempz][tempx] = MAP_BOMB; printf("폭탄포지션값 :x :%d, z:%d , \n", b_pos->posx, b_pos->posz); BYTE tempfire = b_pos->firepower; BYTE tempgameid = b_pos->game_id; fireMap[roomid - 1][tempz][tempx] = tempfire; TB_BombPos tempbomb = { SIZEOF_TB_BombPos,CASE_BOMB,tempgameid,tempfire,b_pos->room_id,tempx,tempz,0.0f }; bomb_Map[roomid - 1].insert(pair<pair<int,int>,Bomb_TB>(make_pair(tempx, tempz), Bomb_TB(tempx, tempz, roomid, tempfire, tempgameid))); ptr->remainbytes -= SIZEOF_TB_BombExplode; memcpy(ptr->buf, c_buf + SIZEOF_TB_BombExplode, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); //Refresh_Map(); TB_BombSetRE tB = { SIZEOF_TB_MapSetRE,CASE_BOMBSET,tempfire,tempx,tempz }; for (int j = 0; j < g_TotalSockets; ++j) { //폭탄을 받았으므로 갱신된 맵정보를 접속해있는 유저에게 전송 if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == roomid) { printf("Send size : %d\n", g_TurtleMap_room[roomid - 1].size); retval = send(SocketInfoArray[j].sock, (char*)&tB, sizeof(TB_MapSetRE), 0); printf("Retval size : %d\n", retval); printf("Bomb가 추가된 맵정보값 전송!\n"); } } } break; } break; case CASE_JOINROOM: if (ptr->remainbytes >= SIZEOF_TB_join) { TB_join* joininfo = reinterpret_cast<TB_join*>(c_buf); byte temproomid = joininfo->roomID;//방id 변수 printf("ID:%d\n", temproomid); if (temproomid != 0) { bool bool_a = room[temproomid - 1].people_count < room[temproomid - 1].people_max; bool bool_b = room[temproomid - 1].game_start != 1; bool bool_c = room[temproomid - 1].made == 1; if (bool_a&&bool_b&&bool_c) { BYTE tempcount = room[temproomid - 1].people_count + 1; BYTE tempguard = room[temproomid - 1].guardian_pos; room[temproomid - 1].people_count += 1; for (BYTE j = 0; j < 4; ++j) { if (room[temproomid - 1].people_inroom[j] == 0) { room[temproomid - 1].people_inroom[j] = joininfo->id; ptr->pos_inRoom = j + 1; tempcount = j + 1; printf("%d가 %d번방에 들어감, %d+1번째 위치\n", joininfo->id, joininfo->roomID, j); break; } } ptr->roomID = temproomid; ptr->is_guardian = 0; TB_joinRE tempjoin = { SIZEOF_TB_joinRE,CASE_JOINROOM,1,temproomid,tempcount,tempguard }; for (int j = 0; j < 4; ++j) tempjoin.people_inroom[j] = room[temproomid - 1].people_inroom[j]; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == 0) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room, sizeof(room), 0); //방정보 전송 } if (SocketInfoArray[j].roomID == temproomid) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room[temproomid - 1], sizeof(TB_Room), 0); //방에 들어있는 친구들에게도 전송 } //retval = send(SocketInfoArray[j].sock, (char*)&tempjoin, sizeof(tempjoin), 0); } } retval = send(ptr->sock, (char*)&tempjoin, sizeof(tempjoin), 0); printf("send yes!! %d\n", retval); } else { TB_joinRE tempjoin = { SIZEOF_TB_joinRE,CASE_JOINROOM,0 }; retval = send(ptr->sock, (char*)&tempjoin, sizeof(tempjoin), 0); printf("send no! %d\n", retval); } ptr->remainbytes -= SIZEOF_TB_join; memcpy(ptr->buf, c_buf + SIZEOF_TB_join, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } } break; case CASE_CREATEROOM: if (ptr->remainbytes >= SIZEOF_TB_create) { TB_create* createinfo = reinterpret_cast<TB_create*>(c_buf); TB_createRE tempa = { SIZEOF_TB_createRE,CASE_CREATEROOM,0 }; /*for (int a = 0; a < 20; ++a) { if (room[a].made == 0) { tempa.can = 1; tempa.roomid = room[a].roomID; room[a].guardian_pos = 1; room[a].made = 1; room[a].people_count = 1; room[a].people_inroom[0] = createinfo->id; ptr->is_guardian = 1; ptr->roomID = room[a].roomID; //printf("%d Created No.%d Room!!\n", room[a].people_inroom[0],ptr->roomID); break; } }*/ for (auto roominfo : room) { if (roominfo.made == 1) printf("%d(Made) ", roominfo.roomID); } BYTE temproomid = createinfo->roomid; if (room[temproomid - 1].made == 0) { room[temproomid - 1].guardian_pos = 1; room[temproomid - 1].made = 1; room[temproomid - 1].people_count = 1; room[temproomid - 1].people_inroom[0] = createinfo->id; ptr->is_guardian = 1; ptr->roomID = room[temproomid - 1].roomID; tempa.can = 1; tempa.roomid = room[temproomid - 1].roomID; } retval = send(ptr->sock, (char*)&tempa, sizeof(TB_createRE), 0); for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == 0) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room, sizeof(room), 0); //초기화된 맵정보 클라이언트에게 전송 } } } ptr->remainbytes -= SIZEOF_TB_create; memcpy(ptr->buf, c_buf + SIZEOF_TB_create, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_READY: if (ptr->remainbytes >=SIZEOF_CASE_READY) { TB_Ready* tempready = reinterpret_cast<TB_Ready*>(c_buf); byte temproompos = tempready->pos_in_room; byte temproomid = tempready->room_num; bool b_isready = room[temproomid - 1].ready[temproompos - 1] == 1; if (!b_isready) { room[temproomid - 1].ready[temproompos - 1] = 1; ptr->is_ready = 1; } else { room[temproomid - 1].ready[temproompos - 1] = 0; ptr->is_ready = 0; } BYTE tempReady = room[temproomid - 1].ready[temproompos - 1]; TB_ReadyRE tempRE = { SIZEOF_TB_ReadyRE,CASE_READY,temproompos,tempReady,temproomid }; for (int j = 0; j < g_TotalSockets; ++j) { //폭탄을 받았으므로 갱신된 맵정보를 접속해있는 유저에게 전송 if (SocketInfoArray[j].m_connected) { printf("Connected\n"); if (SocketInfoArray[j].roomID == temproomid) { retval = send(SocketInfoArray[j].sock, (char*)&tempRE, sizeof(TB_ReadyRE), 0); printf("Retval size : %d\n", retval); } } } ptr->remainbytes -= SIZEOF_CASE_READY; memcpy(ptr->buf, c_buf + SIZEOF_CASE_READY, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_STARTGAME: if (ptr->remainbytes >= SIZEOF_TB_GameStart) { TB_GameStart* startinfo = reinterpret_cast<TB_GameStart*>(c_buf); byte temproomid = startinfo->roomID; printf("Get Start Data from No.%d Room\n", startinfo->roomID); bool check_guard = (room[temproomid - 1].guardian_pos == startinfo->my_pos); bool survivalgame = room[temproomid - 1].roomstate == 0; int teamaCount = 0; for (int t = 0; t < 4; ++t) { if (room[temproomid - 1].team_inroom[t] == 0) teamaCount++; } bool teamGame; //room[temproomid-1].people_max<4 if (room[temproomid - 1].people_count <= 2) teamGame = (1 == teamaCount) && room[temproomid - 1].roomstate == 1; else if (room[temproomid - 1].people_count == 3) teamGame = (1 == teamaCount || 2 == teamaCount) && room[temproomid - 1].roomstate == 1; else teamGame = 2 == teamaCount&& room[temproomid - 1].roomstate == 1; printf("Start Check guardian_pos : %d == %d?\n", room[temproomid - 1].guardian_pos, startinfo->my_pos); //bool check_all_ready= 전원 준비상태인가 int readycount = 0; for (int i = 0; i < 4; ++i) { if (room[temproomid - 1].ready[i] == 1) readycount = readycount + 1; } teamGame = readycount + 1 == room[temproomid - 1].people_count; if (check_guard && (teamGame)) { if (ingamestate[temproomid - 1].IsGameOver()) { ingamestate[temproomid - 1].InitClass(); SetGameRoomInit(temproomid); } ReGame(temproomid); SetMap(room[temproomid - 1].map_mode, room[temproomid - 1].map_thema, temproomid); room[temproomid - 1].game_start = 1; for (int i = 0; i < 4; ++i) { printf("%d는 없는 유저\n",i); if (room[temproomid - 1].people_inroom[i] == 0) ingamestate[temproomid - 1].PlayerBlank(i); } //ingamestate[temproomid - 1] printf("True\n"); for (int j = 0; j < g_TotalSockets; ++j) { //폭탄을 받았으므로 갱신된 맵정보를 접속해있는 유저에게 전송 if (SocketInfoArray[j].m_connected) { printf("Connected\n"); if (SocketInfoArray[j].roomID == temproomid) { printf("Connected\n"); g_TurtleMap_room[temproomid - 1].size = SIZEOF_TB_MAP; retval = send(SocketInfoArray[j].sock, (char*)&g_TurtleMap_room[temproomid - 1], sizeof(TB_Map), 0); //초기화된 맵정보 클라이언트에게 전송 printf("Retval size : %d\n", retval); printf("맵정보 전송 :%d바이트\n", retval); } } } for (int j = 0; j < g_TotalSockets; ++j) { //폭탄을 받았으므로 갱신된 맵정보를 접속해있는 유저에게 전송 if (SocketInfoArray[j].m_connected) { printf("Connected\n"); if (SocketInfoArray[j].roomID == temproomid) { printf("Connected\n"); TB_GameStartRE tempRE = { SIZEOF_TB_GameStartRE,CASE_STARTGAME,1 }; retval = send(SocketInfoArray[j].sock, (char*)&tempRE, sizeof(TB_GameStartRE), 0); } } } } else { TB_GameStartRE tempRE = { SIZEOF_TB_GameStartRE,CASE_STARTGAME,0 }; retval = send(ptr->sock, (char*)&tempRE, sizeof(TB_GameStartRE), 0); printf("Rejected size : %d\n", retval); } ptr->remainbytes -= SIZEOF_TB_GameStart; memcpy(ptr->buf, c_buf + SIZEOF_TB_GameStart, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_OUTROOM: if (ptr->remainbytes >= SIZEOF_TB_RoomOut) { TB_RoomOut* tempRO = reinterpret_cast<TB_RoomOut*>(c_buf); byte temproomid = tempRO->roomID; byte temproompos = tempRO->my_pos; TB_RoomOutRE tempRE = { SIZEOF_TB_RoomOutRE,CASE_OUTROOM,1 }; room[temproomid - 1].people_count -= 1; room[temproomid - 1].people_inroom[temproompos - 1] = 0; if (room[temproomid - 1].people_count <= 0) { room[temproomid - 1].made = 0; room[temproomid - 1].game_start = 0; } if (ptr->is_guardian == 1) { ptr->is_guardian = 0; //이제 자유의 몸이야! for (int a = 0; a < 4; ++a) { if (room[temproomid - 1].people_inroom[a] != 0 && room[temproomid - 1].people_inroom[a] != ptr->id) { room[temproomid - 1].guardian_pos = a + 1; break; } } } for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { //printf("Send size : %d\n", g_TurtleMap.size); //for (int t = 0; t < 4; ++t) { BYTE tempt = room[temproomid - 1].guardian_pos; if (SocketInfoArray[j].id == room[temproomid - 1].people_inroom[tempt - 1]) { printf("Guardian Change\n"); SocketInfoArray[j].is_guardian = 1; } // //자기한테 보내는 것을 방지해야 할 것 retval = send(SocketInfoArray[j].sock, (char*)&room[temproomid - 1], sizeof(TB_Room), 0); //초기화된 맵정보 클라이언트에게 전송 } if (SocketInfoArray[j].roomID == 0) { retval = send(SocketInfoArray[j].sock, (char*)&room, sizeof(room), 0); //초기화된 맵정보 클라이언트에게 전송 } } } ptr->roomID = 0; retval = send(ptr->sock, (char*)&tempRE, sizeof(TB_RoomOutRE), 0); retval = send(ptr->sock, (char*)&room, sizeof(room), 0); ptr->remainbytes -= SIZEOF_TB_RoomOut; memcpy(ptr->buf, c_buf + SIZEOF_TB_RoomOut, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_FORCEOUTROOM: if (ptr->remainbytes >= SIZEOF_TB_GetOut) { TB_GetOut* tempFO = reinterpret_cast<TB_GetOut*>(c_buf); byte temproomid = tempFO->roomID; byte temproompos = tempFO->position; printf("강퇴 요청자 :ID:%d\n", ptr->id); room[temproomid - 1].people_count -= 1; byte tempid = room[temproomid - 1].people_inroom[temproompos - 1]; room[temproomid - 1].people_inroom[temproompos - 1] = 0; TB_GetOUTRE tempRE = { SIZEOF_TB_GetOutRE,CASE_FORCEOUTROOM }; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].id == tempid) { //강퇴당했다! printf("%d가 강퇴당함!!\n", SocketInfoArray[j].id); retval = send(SocketInfoArray[j].sock, (char*)&tempRE, sizeof(TB_GetOUTRE), 0); retval = send(SocketInfoArray[j].sock, (char*)&room, sizeof(room), 0); } if (SocketInfoArray[j].roomID == temproomid) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room[temproomid - 1], sizeof(TB_Room), 0); //초기화된 맵정보 클라이언트에게 전송 } } } ptr->remainbytes -= SIZEOF_TB_GetOut; memcpy(ptr->buf, c_buf + SIZEOF_TB_GetOut, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_ROOMSETTING: if (ptr->remainbytes >= SIZEOF_TB_RoomSetting) { TB_RoomSetting* temproom = reinterpret_cast<TB_RoomSetting*>(c_buf); BYTE temproomid = temproom->roomid; BYTE temproomstate = temproom->peoplemax; BYTE tempmapthema = temproom->mapthema; BYTE tempmaptype = temproom->mapnum; room[temproomid - 1].people_max = temproomstate; room[temproomid - 1].map_mode = tempmaptype; room[temproomid - 1].map_thema = tempmapthema; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room[temproomid - 1], sizeof(TB_Room), 0); //초기화된 맵정보 클라이언트에게 전송 } if (SocketInfoArray[j].roomID == 0) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room, sizeof(room), 0); //초기화된 맵정보 클라이언트에게 전송 } } } ptr->remainbytes -= SIZEOF_TB_RoomSetting; memcpy(ptr->buf, c_buf + SIZEOF_TB_RoomSetting, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_TEAMSETTING: if (ptr->remainbytes >= SIZEOF_TB_TeamSetting) { TB_TeamSetting* tempt = reinterpret_cast<TB_TeamSetting*>(c_buf); BYTE temproomid = tempt->roomid; BYTE temppos = tempt->pos_in_room; BYTE tempteam = tempt->team; room[temproomid - 1].team_inroom[temppos] = tempteam; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { //printf("Send size : %d\n", g_TurtleMap.size); retval = send(SocketInfoArray[j].sock, (char*)&room[temproomid - 1], sizeof(TB_Room), 0); //초기화된 맵정보 클라이언트에게 전송 } } } ptr->remainbytes -= SIZEOF_TB_TeamSetting; memcpy(ptr->buf, c_buf + SIZEOF_TB_TeamSetting, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_ITEM_GET: if (ptr->remainbytes >= SIZEOF_TB_ItemGet) { TB_ItemGet* tempitem = reinterpret_cast<TB_ItemGet*>(c_buf); BYTE temproomid = tempitem->room_id; BYTE tempid = tempitem->ingame_id; BYTE tempi = tempitem->item_type; printf("%d의 item type 획득\n", tempi); int tempx = tempitem->posx; int tempz = tempitem->posz; bool tempbool = g_TurtleMap_room[temproomid - 1].mapInfo[tempz][tempx] != MAP_NOTHING; printf("bool 초기화\n"); if (tempbool) { g_TurtleMap_room[temproomid - 1].mapInfo[tempz][tempx] = MAP_NOTHING; TB_GetItem tempIRE = { SIZEOF_TB_GetItem,CASE_ITEM_GET,tempid,tempi }; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; //retval = send(ptr->sock, (char*)&tempIRE, sizeof(TB_GetItem), 0); printf("임시 구조체 생성\n"); for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { retval = send(SocketInfoArray[j].sock, (char*)&tempIRE, sizeof(TB_GetItem), 0); printf("연결된 친구들 검색 - 아이템 정보 올림\n"); retval = send(SocketInfoArray[j].sock, (char*)&tMap, sizeof(TB_MapSetRE), 0); printf("연결된 친구들 검색 - 맵 정보 올림\n"); } } } } ptr->remainbytes -= SIZEOF_TB_ItemGet; memcpy(ptr->buf, c_buf + SIZEOF_TB_ItemGet, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_THROWBOMB: if (ptr->remainbytes >= SIZEOF_TB_ThrowBomb) { TB_ThrowBomb* tempt = reinterpret_cast<TB_ThrowBomb*>(c_buf); BYTE temproomid = tempt->roomid; BYTE tempid = tempt->ingame_id; int tempx = tempt->posx; int tempz = tempt->posz; BYTE tempdirect = tempt->direction; //printf("던진다 폭탄!!! x:%d , z:%d \n",tempx,tempz); if (bomb_Map[temproomid-1].size() > 0) { auto bomb_b = bomb_Map[temproomid - 1].find(make_pair(tempx, tempz)); if (bomb_b != bomb_Map[temproomid - 1].end()) { TB_ThrowBombRE tempThrow = { SIZEOF_TB_ThrowBombRE,CASE_THROWBOMB,tempdirect,tempid,tempx,tempz }; Throw_Calculate_Map(tempx, tempz, temproomid, &tempThrow, tempdirect); g_TurtleMap_room[temproomid - 1].mapInfo[tempz][tempx] = MAP_NOTHING; Bomb_TB tempBomb = Bomb_TB(tempThrow.posx_re, tempThrow.posz_re, temproomid, bomb_b->second.firepower, tempid); tempBomb.time = bomb_b->second.time; tempBomb.ResetExplodeTime(); tempBomb.is_throw = true; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; bomb_Map[temproomid - 1].insert(pair<pair<int, int>, Bomb_TB>(make_pair(tempThrow.posx_re, tempThrow.posz_re), tempBomb)); bomb_Map[temproomid - 1].erase(bomb_b); for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { printf("보냈다 패킷!!!\n"); retval = send(SocketInfoArray[j].sock, (char*)&tMap, sizeof(TB_MapSetRE), 0); retval = send(SocketInfoArray[j].sock, (char*)&ingame_Char_Info[temproomid - 1][tempid], sizeof(TB_CharPos), 0); retval = send(SocketInfoArray[j].sock, (char*)&tempThrow, sizeof(TB_ThrowBombRE), 0); } } } //bomb_b->second.xz } //bomb_b->second.xz } ptr->remainbytes -= SIZEOF_TB_ThrowBomb; memcpy(ptr->buf, c_buf + SIZEOF_TB_ThrowBomb, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_THROWCOMPLETE: if (ptr->remainbytes >= SIZEOF_TB_ThrowComplete) { TB_ThrowComplete* tempt = reinterpret_cast<TB_ThrowComplete*>(c_buf); BYTE temproomid = tempt->roomid; int tempx = tempt->posx; int tempz = tempt->posz; g_TurtleMap_room[temproomid - 1].mapInfo[tempx][tempz] = MAP_BOMB; TB_BombSetRE tB = { SIZEOF_TB_MapSetRE,CASE_BOMBSET,MAP_BOMB,tempx,tempz }; bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].is_throw = false; bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].ResetTime(); fireMap[temproomid - 1][tempz][tempx] = bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].firepower; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { retval = send(SocketInfoArray[j].sock, (char*)&tB, sizeof(TB_BombSetRE), 0); } } } ptr->remainbytes -= SIZEOF_TB_ThrowComplete; memcpy(ptr->buf, c_buf + SIZEOF_TB_ThrowComplete, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_BOXPUSH: if (ptr->remainbytes >= SIZEOF_TB_BoxPush) { TB_BoxPush* tB = reinterpret_cast<TB_BoxPush*>(c_buf); BYTE tempdirc = tB->direction; BYTE temproomid = tB->roomid; BYTE tempid = tB->ingame_id; int tempx = tB->posx; int tempz = tB->posz; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; TB_BoxPushRE tBox = { SIZEOF_TB_BoxPushRE, CASE_BOXPUSH,0,tempid }; BoxPush_Calculate_Map(tempx, tempz, temproomid, &tBox, tempdirc, &tMap); printf("box받았다!!!\n"); for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { //printf("보냈다 패킷!!!\n"); if (tBox.push == 1) retval = send(SocketInfoArray[j].sock, (char*)&tMap, sizeof(TB_MapSetRE), 0); retval = send(SocketInfoArray[j].sock, (char*)&ingame_Char_Info[temproomid - 1][tempid], sizeof(TB_CharPos), 0); retval = send(SocketInfoArray[j].sock, (char*)&tBox, sizeof(TB_BoxPushRE), 0); } } } ptr->remainbytes -= SIZEOF_TB_BoxPush; memcpy(ptr->buf, c_buf + SIZEOF_TB_BoxPush, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_BOXPUSHCOMPLETE: if (ptr->remainbytes >= SIZEOF_TB_BoxPushComplete) { TB_BoxPushComplete* tB = reinterpret_cast<TB_BoxPushComplete*>(c_buf); printf("boxcom받았다!!!\n"); BYTE temproomid = tB->roomid; int tempx = tB->posx; int tempz = tB->posz; g_TurtleMap_room[temproomid - 1].mapInfo[tempz][tempx] = MAP_BOX; TB_MapSetRE tBd = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_BOX,tempx,tempz }; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { retval = send(SocketInfoArray[j].sock, (char*)&tBd, sizeof(TB_MapSetRE), 0); } } } ptr->remainbytes -= SIZEOF_TB_BoxPushComplete; memcpy(ptr->buf, c_buf + SIZEOF_TB_BoxPushComplete, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_KICKBOMB: if (ptr->remainbytes >= SIZEOF_TB_BoxPush) { TB_KickBomb* tK = reinterpret_cast<TB_KickBomb*>(c_buf); BYTE tempdirc = tK->direction; BYTE temproomid = tK->roomid; BYTE tempid = tK->ingame_id; int tempx = tK->posx; int tempz = tK->posz; int ax=tempx; int az=tempz; switch (tempdirc) { case 1: ax = tempx + 1; break; case 2: ax = tempx - 1; break; case 3: az = tempz + 1; break; case 4: az = tempz - 1; break; } printf("발로까는캐릭터위치 %d,%d!!!\n",tempx,tempz); if (bomb_Map[temproomid - 1].size() > 0) { auto bomb_b = bomb_Map[temproomid - 1].find(pair<int, int>(ax, az)); if (bomb_b != bomb_Map[temproomid - 1].end()) { TB_KickBombRE tempKick = { SIZEOF_TB_ThrowBombRE,CASE_THROWBOMB,tempdirc,tempid,tempx,tempz }; g_TurtleMap_room[temproomid - 1].mapInfo[tempz][tempx] = MAP_NOTHING; TB_MapSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_MAPSET,MAP_NOTHING,tempx,tempz }; Kick_CalculateMap(tempx, tempz, temproomid, &tempKick, tempdirc, &tMap); Bomb_TB tempBomb = Bomb_TB(tempKick.posx_re, tempKick.posz_re, temproomid, bomb_b->second.firepower, tempid); tempBomb.time = bomb_b->second.time; tempBomb.ResetExplodeTime(); tempBomb.is_kicked = true; bomb_Map[temproomid - 1].insert(pair<pair<int, int>, Bomb_TB>(make_pair(tempKick.posx_re, tempKick.posz_re), tempBomb)); bomb_Map[temproomid - 1].erase(bomb_b); ingame_Char_Info[temproomid - 1][tempid].anistate = TURTLE_ANI_KICK;//throw ani for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { printf("보냈다 발패킷!!!\n"); if (tempKick.kick == 1) { printf("보냈다 참발패킷!!!\n"); retval = send(SocketInfoArray[j].sock, (char*)&tMap, sizeof(TB_MapSetRE), 0); } retval = send(SocketInfoArray[j].sock, (char*)&ingame_Char_Info[temproomid - 1][tempid], sizeof(TB_CharPos), 0); retval = send(SocketInfoArray[j].sock, (char*)&tempKick, sizeof(TB_KickBombRE), 0); } } } //bomb_b->second.xz } } //bomb_Map[temproomid-1][pair<int,int>(ax,az)] ptr->remainbytes -= SIZEOF_TB_BoxPush; memcpy(ptr->buf, c_buf + SIZEOF_TB_BoxPush, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; case CASE_KICKCOMPLETE: if (ptr->remainbytes >= SIZEOF_TB_ThrowComplete) { TB_KickComplete* tK = reinterpret_cast<TB_KickComplete*>(c_buf); BYTE temproomid = tK->roomid; int tempx = tK->posx; int tempz = tK->posz; TB_BombSetRE tMap = { SIZEOF_TB_MapSetRE,CASE_BOMBSET,MAP_BOMB,tempx,tempz }; bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].is_kicked = false; bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].ResetTime(); g_TurtleMap_room[temproomid - 1].mapInfo[tempz][tempx] = MAP_BOMB; fireMap[temproomid - 1][tempz][tempx] = bomb_Map[temproomid - 1][pair<int, int>(tempx, tempz)].firepower; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == temproomid) { //printf("보냈다 패킷!!!\n"); retval = send(SocketInfoArray[j].sock, (char*)&tMap, sizeof(TB_MapSetRE), 0); } } } ptr->remainbytes -= SIZEOF_TB_ThrowComplete; memcpy(ptr->buf, c_buf + SIZEOF_TB_ThrowComplete, ptr->remainbytes); memset(c_buf, 0, sizeof(c_buf)); memcpy(c_buf, ptr->buf, sizeof(ptr->buf)); } break; default: printf("현재 버퍼 첫 바이트값 : %d\n", c_buf[0]); break; } } addrlen = sizeof(clientaddr); getpeername(ptr->sock, (SOCKADDR*)&clientaddr, &addrlen); } } //FD_CLOSE 이벤트 처리 if (m_NetworkEvents.lNetworkEvents&FD_CLOSE) { if (m_NetworkEvents.iErrorCode[FD_CLOSE_BIT] != 0) { err_display(m_NetworkEvents.iErrorCode[FD_CLOSE_BIT]); } RemoveSocketInfo(i); } } } WSACleanup(); return 0; } void err_display(char *msg) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); printf("[%s] %s", msg, (char *)lpMsgBuf); LocalFree(lpMsgBuf); } void err_quit(char* msg) { LPVOID lpMsgBuf; FormatMessage( FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); MessageBox(NULL, (LPCTSTR)lpMsgBuf, (LPCWSTR)msg, MB_ICONERROR); LocalFree(lpMsgBuf); exit(1); } void err_display(int errcode) { LPVOID lpMsgBuf; FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM, NULL, WSAGetLastError(), MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT), (LPTSTR)&lpMsgBuf, 0, NULL); printf("[오류]%s", (char*)lpMsgBuf); LocalFree(lpMsgBuf); } BOOL AddSOCKETInfo(SOCKET sock) { Socket_Info* ptr = &SocketInfoArray[g_TotalSockets]; if (ptr == NULL) { printf("Not enough Memory!!!\n"); return FALSE; } WSAEVENT hEvent = WSACreateEvent(); if (hEvent == WSA_INVALID_EVENT) { err_display("WSACreateEvent()"); return FALSE; } ZeroMemory(ptr->buf, sizeof(ptr->buf)); //ZeroMemory(ptr->c_buf, sizeof(ptr->c_buf)); ptr->id = g_total_member; ptr->m_getpacket = false; ptr->sock = sock; ptr->recvbytes = 0; ptr->remainbytes = 0; ptr->sendbytes = 0; if (g_TotalSockets == 0) ptr->m_connected = false; else ptr->m_connected = true; ptr->roomID = 0; ptr->bomb = 2; ptr->fire = 2; ptr->speed = 2; ptr->is_guardian = 0; ptr->is_ready = 0; EventArray[g_TotalSockets] = hEvent; ++g_TotalSockets; printf("등록완료\n"); return TRUE; } void RemoveSocketInfo(int nIndex) { Socket_Info* ptr = &SocketInfoArray[nIndex]; if (ptr->roomID != 0) { room[ptr->roomID - 1].people_count--; room[ptr->roomID - 1].people_inroom[ptr->pos_inRoom - 1] = 0; room[ptr->roomID - 1].ready[ptr->pos_inRoom - 1] = 0; room[ptr->roomID - 1].team_inroom[ptr->pos_inRoom - 1] = 0; if (ptr->is_guardian == 1&&room[ptr->roomID - 1].people_count > 0) { for (int a = 0; a < 4; ++a) { if (room[ptr->roomID - 1].people_inroom[a] != 0 && room[ptr->roomID - 1].people_inroom[a] != ptr->id) { room[ptr->roomID - 1].guardian_pos = a + 1; for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == ptr->roomID) { send(SocketInfoArray[j].sock, (char*)&room[ptr->roomID - 1], sizeof(TB_Room), 0); } } } break; } } } else if (room[ptr->roomID - 1].people_count > 0) { for (int j = 0; j < g_TotalSockets; ++j) { if (SocketInfoArray[j].m_connected) { if (SocketInfoArray[j].roomID == ptr->roomID) { send(SocketInfoArray[j].sock, (char*)&room[ptr->roomID - 1], sizeof(TB_Room), 0); } } } } if (room[ptr->roomID - 1].people_count <= 0) { room[ptr->roomID - 1].made = 0; room[ptr->roomID - 1].people_count = 0; room[ptr->roomID - 1].game_start = 0; room[ptr->roomID - 1].guardian_pos = 0; room[ptr->roomID - 1].map_thema = 0; room[ptr->roomID - 1].map_mode = 0; room[ptr->roomID - 1].people_max = 4; for (int i = 0; i < 4; ++i) { room[ptr->roomID - 1].team_inroom[i] = 0; room[ptr->roomID - 1].people_inroom[i] = 0; room[ptr->roomID - 1].ready[i] = 0; } } } ptr->roomID = 0; ptr->recvbytes = 0; ptr->remainbytes = 0; ptr->sendbytes = 0; ptr->pos_inRoom = 0; ptr->is_guardian = 0; ptr->m_connected = false; SOCKADDR_IN clientaddr; int addrlen = sizeof(clientaddr); getpeername(ptr->sock, (SOCKADDR*)&clientaddr, &addrlen); printf("TCP서버 클라이언트 종료:IP 주소=%s,포트번호 = %d\n", inet_ntoa(clientaddr.sin_addr), ntohs(clientaddr.sin_port)); closesocket(ptr->sock); WSACloseEvent(EventArray[nIndex]); if (nIndex != (g_TotalSockets - 1)) { SocketInfoArray[nIndex] = SocketInfoArray[g_TotalSockets - 1]; EventArray[nIndex] = EventArray[g_TotalSockets - 1]; } --g_TotalSockets; } void SetGameRoomInit(BYTE j) { ingame_Char_Info[j][0].ingame_id = 0; ingame_Char_Info[j][1].ingame_id = 1; ingame_Char_Info[j][2].ingame_id = 2; ingame_Char_Info[j][3].ingame_id = 3; //char_info[0].hp = 10.0f; ingame_Char_Info[j][0].posx = 0.0f; ingame_Char_Info[j][0].posz = 0.0f; ingame_Char_Info[j][0].is_alive = true; ingame_Char_Info[j][0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[j][1].posx = 28.0f; ingame_Char_Info[j][1].posz = 0.0f; ingame_Char_Info[j][1].is_alive = true; ingame_Char_Info[j][1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[j][2].posx = 0.0f; ingame_Char_Info[j][2].posz = 28.0f; ingame_Char_Info[j][2].is_alive = true; ingame_Char_Info[j][2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[j][3].posx = 28.0f; ingame_Char_Info[j][3].posz = 28.0f; ingame_Char_Info[j][3].is_alive = true; ingame_Char_Info[j][3].rotY = 180.0f; } void CalculateMap_Simple(int x, int z, byte f, byte room_num) { bool l_UpBlock = false; bool l_DownBlock = false; bool l_LeftBlock = false; bool l_RightBlock = false; BYTE uf = f; BYTE df = f; BYTE lf = f; BYTE rf = f; BYTE tempMap[15][15]; memcpy(tempMap, g_TurtleMap_room[room_num - 1].mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; for (byte b = 1; b <= f; ++b) { if (!l_DownBlock) { if (z - b < 0) { l_DownBlock = true; dfMap[room_num - 1][z - b][x] = b; } else { if (tempMap[z - b][x] == MAP_BOMB) { tempMap[z - b][x] = MAP_NOTHING; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); l_DownBlock = true; dfMap[room_num - 1][z][x] = b-1; } else if (tempMap[z - b][x] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand < 4) tempMap[z - b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z - b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z - b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z - b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z - b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z - b][x] = MAP_THROWITEM; l_DownBlock = true; dfMap[room_num - 1][z][x] = b-1; } else if (tempMap[z - b][x] == MAP_ITEM || tempMap[z - b][x] == MAP_ITEM_F || tempMap[z - b][x] == MAP_ITEM_S) { tempMap[z - b][x] = MAP_NOTHING; } else if (tempMap[z - b][x] == MAP_BUSH || tempMap[z - b][x] == MAP_FIREBUSH) { } else if (tempMap[z - b][x] == MAP_ROCK) { l_DownBlock = true; dfMap[room_num - 1][z][x] = b-1; } } } if (!l_UpBlock) { if (z + b > 14) { l_UpBlock = true; ufMap[room_num - 1][z][x] = b-1; } else { if (tempMap[z + b][x] == MAP_BOMB) { tempMap[z + b][x] = MAP_NOTHING; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x, z + b, fireMap[room_num - 1][z + b][x], room_num); l_UpBlock = true; ufMap[room_num - 1][z][x] = b-1; } else if (tempMap[z + b][x] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z + b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z + b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z + b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z + b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z + b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z + b][x] = MAP_THROWITEM; l_UpBlock = true; ufMap[room_num - 1][z][x] = b-1; } else if (tempMap[z + b][x] == MAP_ITEM || tempMap[z + b][x] == MAP_ITEM_F || tempMap[z + b][x] == MAP_ITEM_S) { tempMap[z + b][x] = MAP_NOTHING; } else if (tempMap[z + b][x] == MAP_ROCK) { l_UpBlock = true; ufMap[room_num - 1][z][x] = b-1; } } } if (!l_LeftBlock) { if (x - b < 0) { l_LeftBlock = true; lfMap[room_num - 1][z][x] = b-1; } else { if (tempMap[z][x - b] == MAP_BOMB) { tempMap[z][x - b] = MAP_NOTHING; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x-b, z, fireMap[room_num - 1][z ][x-b], room_num); l_LeftBlock = true; lfMap[room_num - 1][z][x] = b-1; } else if (tempMap[z][x - b] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z][x - b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x - b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x - b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x - b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x - b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x - b] = MAP_THROWITEM; l_LeftBlock = true; lfMap[room_num - 1][z][x] = b-1; } else if (tempMap[z][x - b] == MAP_ITEM || tempMap[z][x - b] == MAP_ITEM_F || tempMap[z][x - b] == MAP_ITEM_S) { tempMap[z][x - b] = MAP_NOTHING; } else if (tempMap[z][x - b] == MAP_ROCK) { l_LeftBlock = true; lfMap[room_num - 1][z][x] = b-1; } } } if (!l_RightBlock) { if (x + b > 14) { l_RightBlock = true; rfMap[room_num - 1][z][x] = b-1; } else { if (tempMap[z][x + b] == MAP_BOMB) { tempMap[z][x + b] = MAP_NOTHING; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x + b, z, fireMap[room_num - 1][z][x + b], room_num); l_RightBlock = true; rfMap[room_num - 1][z][x] = b-1; } else if (tempMap[z][x + b] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z][x + b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x + b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x + b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x + b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x + b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x + b] = MAP_THROWITEM; l_RightBlock = true; rfMap[room_num - 1][z][x] = b-1; } else if (tempMap[z][x + b] == MAP_ITEM || tempMap[z][x + b] == MAP_ITEM_F || tempMap[z][x + b] == MAP_ITEM_S) { tempMap[z][x + b] = MAP_NOTHING; } else if (tempMap[z][x + b] == MAP_ROCK) { l_RightBlock = true; rfMap[room_num - 1][z][x ] = b-1; } } } } g_TurtleMap_room[room_num - 1].type = CASE_MAP; BYTE gID = bomb_Map[room_num - 1][pair<int, int>(x, z)].game_id; TB_BombExplodeRE tempBomb = { SIZEOF_TB_BombExplodeRE,CASE_BOMB_EX,ufMap[room_num - 1][z][x],rfMap[room_num - 1][z][x],dfMap[room_num - 1][z][x],lfMap[room_num - 1][z][x],gID,x,z }; explode_List.emplace_back(tempBomb); auto bomb = bomb_Map[room_num - 1].find(pair<int, int>(x, z)); bomb_Map[room_num - 1].erase(bomb); fireMap[room_num - 1][z][x] = 0; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); } void CalculateMap(int x, int z, byte f, byte room_num, TB_BombExplodeRE* temppacket) { bool l_UpBlock = false; bool l_DownBlock = false; bool l_LeftBlock = false; bool l_RightBlock = false; BYTE uf = f; BYTE df = f; BYTE lf = f; BYTE rf = f; BYTE tempMap[15][15]; memcpy(tempMap, g_TurtleMap_room[room_num - 1].mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; for (byte b = 1; b <= f; ++b) { if (!l_DownBlock) { if (z - b < 0) { l_DownBlock = true; df = b-1; } else { if (tempMap[z - b][x] == MAP_BOMB) { tempMap[z - b][x] = MAP_NOTHING; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); l_DownBlock = true; df = b-1; } else if (tempMap[z - b][x] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand < 4) tempMap[z - b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z - b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z - b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z - b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z - b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z - b][x] = MAP_THROWITEM; l_DownBlock = true; df = b-1; } else if (tempMap[z - b][x] == MAP_ITEM || tempMap[z - b][x] == MAP_ITEM_F || tempMap[z - b][x] == MAP_ITEM_S || tempMap[z - b][x] == MAP_KICKITEM || tempMap[z - b][x] == MAP_THROWITEM) { tempMap[z - b][x] = MAP_NOTHING; } else if (tempMap[z - b][x] == MAP_BUSH || tempMap[z - b][x] == MAP_FIREBUSH) { } else if (tempMap[z - b][x] == MAP_ROCK) { l_DownBlock = true; df = b-1; } } } if (!l_UpBlock) { if (z + b > 14) { l_UpBlock = true; uf = b-1; } else { if (tempMap[z + b][x] == MAP_BOMB) { tempMap[z + b][x] = MAP_NOTHING; l_UpBlock = true; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); uf = b-1; } else if (tempMap[z + b][x] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z + b][x] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z + b][x] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z + b][x] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z + b][x] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z + b][x] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z + b][x] = MAP_THROWITEM; l_UpBlock = true; uf = b-1; } else if (tempMap[z + b][x] == MAP_ITEM || tempMap[z + b][x] == MAP_ITEM_F || tempMap[z + b][x] == MAP_ITEM_S || tempMap[z + b][x] == MAP_KICKITEM || tempMap[z + b][x] == MAP_THROWITEM) { tempMap[z + b][x] = MAP_NOTHING; } else if (tempMap[z + b][x] == MAP_ROCK) { l_UpBlock = true; uf = b-1; } } } if (!l_LeftBlock) { if (x - b < 0) { l_LeftBlock = true; lf = b-1; } else { if (tempMap[z][x - b] == MAP_BOMB) { tempMap[z][x - b] = MAP_NOTHING; l_LeftBlock = true; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); lf = b-1; } else if (tempMap[z][x - b] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z][x - b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x - b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x - b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x - b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x-b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x-b] = MAP_THROWITEM; l_LeftBlock = true; lf = b-1; } else if (tempMap[z][x - b] == MAP_ITEM || tempMap[z][x - b] == MAP_KICKITEM || tempMap[z][x - b] == MAP_THROWITEM || tempMap[z][x - b] == MAP_ITEM_F || tempMap[z][x - b] == MAP_ITEM_S) { tempMap[z][x - b] = MAP_NOTHING; } else if (tempMap[z][x - b] == MAP_ROCK) { l_LeftBlock = true; lf = b-1; } } } if (!l_RightBlock) { if (x + b > 14) { l_RightBlock = true; rf = b-1; } else { if (tempMap[z][x + b] == MAP_BOMB) { tempMap[z][x + b] = MAP_NOTHING; l_RightBlock = true; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); CalculateMap_Simple(x, z - b, fireMap[room_num - 1][z - b][x], room_num); rf = b-1; } else if (tempMap[z][x + b] == MAP_BOX) { int temp_rand = (rand() % 14); if (temp_rand<4) tempMap[z][x + b] = MAP_NOTHING; else if (temp_rand >= 4 && temp_rand <= 5) tempMap[z][x + b] = MAP_ITEM; else if (temp_rand >= 6 && temp_rand <= 7) tempMap[z][x + b] = MAP_ITEM_F; else if (temp_rand >= 8 && temp_rand <= 9) tempMap[z][x + b] = MAP_ITEM_S; else if (temp_rand >= 10 && temp_rand <= 11) tempMap[z][x+b] = MAP_KICKITEM; else if (temp_rand >= 12 && temp_rand <= 13) tempMap[z][x+b] = MAP_THROWITEM; l_RightBlock = true; rf = b-1; } else if (tempMap[z][x + b] == MAP_ITEM || tempMap[z][x + b] == MAP_KICKITEM || tempMap[z][x + b] == MAP_THROWITEM || tempMap[z][x + b] == MAP_ITEM_F || tempMap[z][x + b] == MAP_ITEM_S) { tempMap[z][x + b] = MAP_NOTHING; } else if (tempMap[z][x + b] == MAP_ROCK) { l_RightBlock = true; rf = b-1; } } } } g_TurtleMap_room[room_num - 1].type = CASE_MAP; fireMap[room_num - 1][z][x] = 0; temppacket->size = SIZEOF_TB_BombExplodeRE; temppacket->type = CASE_BOMB_EX; temppacket->upfire = uf; temppacket->downfire = df; temppacket->rightfire = rf; temppacket->leftfire = lf; temppacket->posx = x; temppacket->posz = z; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); } void Kick_CalculateMap(int x, int z, BYTE room_num, TB_KickBombRE* temppacket, BYTE direction, TB_MapSetRE* tempp) { BYTE tempMap[15][15]; memcpy(tempMap, g_TurtleMap_room[room_num - 1].mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; int tempx = x; int tempz = z; int startx = x; int startz = z; temppacket->kick = 0; //direction에따라 어디로 차는지 알고 검색 1-우 2-좌 3-하 4-상 switch (direction) { case 1: if (tempx > 14) tempx = 14; else if (tempMap[z][x + 1] == MAP_NOTHING || tempMap[z][x + 1] == MAP_ITEM || tempMap[z][x + 1] == MAP_ITEM_F || tempMap[z][x + 1] == MAP_ITEM_S) { temppacket->kick = 0; tempx = x + 1; } else if (tempMap[z][x + 1] == MAP_BOMB) { startx = x + 1; if (x + 2 > 14) { temppacket->kick = 0; tempx = 14; } else if (tempMap[z][x + 2] == MAP_NOTHING || tempMap[z][x + 2] == MAP_ITEM || tempMap[z][x + 2] == MAP_ITEM_F || tempMap[z][x + 2] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z][x + 2 + i] == MAP_ROCK || tempMap[z][x + 2 + i] == MAP_BOMB || tempMap[z][x + 2 + i] == MAP_BOX || x+2+i>14) { temppacket->kick = 1; tempx = x + 1 + i; break; } } } } break; case 2: if (tempx < 0 ) tempx = 0; else if (tempMap[z][x - 1] == MAP_NOTHING || tempMap[z][x - 1] == MAP_ITEM || tempMap[z][x - 1] == MAP_ITEM_F || tempMap[z][x - 1] == MAP_ITEM_S) { temppacket->kick = 0; tempx = x - 1; } else if (tempMap[z][x - 1] == MAP_BOMB) { startx = x - 1; if (x - 2 <0) { temppacket->kick = 0; tempx = 0; } else if (tempMap[z][x - 2] == MAP_NOTHING || tempMap[z][x - 2] == MAP_ITEM || tempMap[z][x - 2] == MAP_ITEM_F || tempMap[z][x - 2] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z][x - 2 - i] == MAP_ROCK || tempMap[z][x - 2 - i] == MAP_BOMB || tempMap[z][x - 2 - i] == MAP_BOX || x - 2 - i<0) { temppacket->kick = 1; tempx = x - 1 - i; break; } } } } break; case 3: if (tempz > 14) tempz = 14; else if (tempMap[z+1][x] == MAP_NOTHING || tempMap[z+1][x] == MAP_ITEM || tempMap[z+1][x] == MAP_ITEM_F || tempMap[z+1][x] == MAP_ITEM_S) { temppacket->kick = 0; tempz = z + 1; } else if (tempMap[z+1][x] == MAP_BOMB) { startz = z + 1; if (z + 2 > 14) { temppacket->kick = 0; tempz= 14; } else if (tempMap[z+2][x] == MAP_NOTHING || tempMap[z+2][x] == MAP_ITEM || tempMap[z+2][x] == MAP_ITEM_F || tempMap[z+2][x] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z + 2 + i][x] == MAP_ROCK || tempMap[z+2+i][x] == MAP_BOMB || tempMap[z+2+i][x] == MAP_BOX || z+ 2 + i>14) { temppacket->kick = 1; tempz = z + 1 + i; break; } } } } break; case 4: if (tempz < 0) tempz = 0; else if (tempMap[z-1][x] == MAP_NOTHING || tempMap[z-1][x] == MAP_ITEM || tempMap[z-1][x] == MAP_ITEM_F || tempMap[z-1][x] == MAP_ITEM_S) { temppacket->kick = 0; tempz = z - 1; } else if (tempMap[z-1][x] == MAP_BOMB) { startz = z - 1; if (x - 2 <0) { temppacket->kick = 0; tempz = 0; } else if (tempMap[z-2][x] == MAP_NOTHING || tempMap[z-2][x] == MAP_ITEM || tempMap[z-2][x] == MAP_ITEM_F || tempMap[z-2][x] == MAP_ITEM_S) { for (int i = 1; i < 14; ++i) { if (tempMap[z - 2 - i][x] == MAP_ROCK || tempMap[z-2-i][x] == MAP_BOMB || tempMap[z-2-i][x] == MAP_BOX || z - 2 - i<0) { temppacket->kick = 1; tempz = z - 1 - i; break; } } } } break; default: printf("Unknown Direction!!!!\n"); break; } //kick관련 송신패킷구조체에 넣어줘야 한다. if (temppacket->kick == 1) tempMap[startz][startx] = MAP_NOTHING; temppacket->posx = startx; temppacket->posz = startz; temppacket->posx_re = tempx; temppacket->posz_re = tempz; temppacket->direction = direction; tempp->posx = startx; tempp->posz = startz; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); } void Throw_Calculate_Map(int x, int z, BYTE room_num, TB_ThrowBombRE* temppacket, BYTE direction) { BYTE tempMap[15][15]; memcpy(tempMap, g_TurtleMap_room[room_num - 1].mapInfo, sizeof(tempMap)); tempMap[z][x] = MAP_NOTHING; int tempx = x; int tempz = z; //direction에따라 어디로 차는지 알고 검색 1-우 2-좌 3-하 4-상 switch (direction) { case 1: tempx = x + 4; if (tempx > 14) tempx = 14; for (int i = tempx; i < 15; ++i) { if (tempMap[z][i] == MAP_NOTHING || tempMap[z][i] == MAP_ITEM || tempMap[z][i] == MAP_BUSH || tempMap[z][i] == MAP_ITEM_F || tempMap[z][i] == MAP_ITEM_S) { tempx = i; tempz = z; break; } if (i == 14) { tempx = i; tempz = z; break; } } break; case 2: tempx = x - 4; if (tempx < 0) tempx = 0; for (int i = tempx; i >= 0; --i) { if (tempMap[z][i] == MAP_NOTHING || tempMap[z][i] == MAP_ITEM || tempMap[z][i] == MAP_BUSH || tempMap[z][i] == MAP_ITEM_F || tempMap[z][i] == MAP_ITEM_S) { tempx = i; tempz = z; break; } if (i == 0) { tempx = i; tempz = z; break; } } break; case 3: tempz = z + 4; if (tempz > 14) tempz = 14; for (int i = tempz; i < 15; ++i) { if (tempMap[i][x] == MAP_NOTHING || tempMap[i][x] == MAP_ITEM || tempMap[i][x] == MAP_BUSH || tempMap[i][x] == MAP_ITEM_F || tempMap[i][x] == MAP_ITEM_S) { tempx = x; tempz = i; break; } if (i == 14) { tempx = x; tempz = i; break; } } break; case 4: tempz = z - 4; if (tempz < 0) tempz = 0; for (int i = z; i >= 0; --i) { if (tempMap[i][x] == MAP_NOTHING || tempMap[i][x] == MAP_ITEM || tempMap[i][x] == MAP_BUSH || tempMap[i][x] == MAP_ITEM_F || tempMap[i][x] == MAP_ITEM_S) { tempx = x; tempz = i; break; } if (i == 0) { tempx = x; tempz = i; break; } } break; default: printf("Unknown Direction!!!!\n"); break; } //throw관련 송신패킷구조체에 넣어줘야 한다. temppacket->posx_re = tempx; temppacket->posz_re = tempz; temppacket->posx = x; temppacket->posz = z; temppacket->direction = direction; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); } void BoxPush_Calculate_Map(int x, int z, BYTE room_num, TB_BoxPushRE* temppacket, BYTE direction, TB_MapSetRE* tempp) { BYTE tempMap[15][15]; memcpy(tempMap, g_TurtleMap_room[room_num - 1].mapInfo, sizeof(tempMap)); //tempMap[z][x] = MAP_NOTHING; int tempx = x; int tempz = z; int startx = x; int startz = z; temppacket->push = 0; //direction에따라 어디로 차는지 알고 검색 1-우 2-좌 3-하 4-상 switch (direction) { case 1: if (tempx > 14) { temppacket->push = 0; tempx = 14; } else if (tempMap[z][x + 1] == MAP_NOTHING || tempMap[z][x + 1] == MAP_ITEM || tempMap[z][x + 1] == MAP_ITEM_F || tempMap[z][x + 1] == MAP_ITEM_S) { temppacket->push = 0; tempx = x + 1; } else if (tempMap[z][x + 1] == MAP_BOX) { startx = x + 1; if (x + 2 > 14) { temppacket->push = 0; tempx = 14; } else if (tempMap[z][x + 2] == MAP_NOTHING || tempMap[z][x + 2] == MAP_ITEM || tempMap[z][x + 2] == MAP_ITEM_F || tempMap[z][x + 2] == MAP_ITEM_S) { temppacket->push = 1; tempx = x + 2; } } break; case 2: if (tempx < 0) { temppacket->push = 0; tempx = 0; } else if (tempMap[z][x - 1] == MAP_NOTHING || tempMap[z][x - 1] == MAP_ITEM || tempMap[z][x - 1] == MAP_ITEM_F || tempMap[z][x - 1] == MAP_ITEM_S) { temppacket->push = 0; tempx = x - 1; } else if (tempMap[z][x - 1] == MAP_BOX) { startx = x - 1; if (x - 2< 0) { temppacket->push = 0; tempx = 0; } else if (tempMap[z][x - 2] == MAP_NOTHING || tempMap[z][x - 2] == MAP_ITEM || tempMap[z][x - 2] == MAP_ITEM_F || tempMap[z][x - 2] == MAP_ITEM_S) { temppacket->push = 1; tempx = x - 2; } } break; case 3: if (tempz > 14) { temppacket->push = 0; tempz = 14; } else if (tempMap[z + 1][x] == MAP_NOTHING || tempMap[z + 1][x] == MAP_ITEM || tempMap[z + 1][x] == MAP_ITEM_F || tempMap[z + 1][x] == MAP_ITEM_S) { temppacket->push = 0; tempz = z; } else if (tempMap[z + 1][x] == MAP_BOX) { startz = z + 1; if (z + 2 > 14) { temppacket->push = 0; tempz = 14; } else if (tempMap[z + 2][x] == MAP_NOTHING || tempMap[z + 2][x] == MAP_ITEM || tempMap[z + 2][x] == MAP_ITEM_F || tempMap[z + 2][x] == MAP_ITEM_S) { temppacket->push = 1; tempz = z + 2; } } break; case 4: if (tempz < 0) { temppacket->push = 0; tempz = 0; } else if (tempMap[z - 1][x] == MAP_NOTHING || tempMap[z - 1][x] == MAP_ITEM || tempMap[z - 1][x] == MAP_ITEM_F || tempMap[z - 1][x] == MAP_ITEM_S) { temppacket->push = 0; tempz = z; } else if (tempMap[z - 1][x] == MAP_BOX) { startz = z - 1; if (z - 2 <0) { temppacket->push = 0; tempz = 0; } else if (tempMap[z - 2][x] == MAP_NOTHING || tempMap[z - 2][x] == MAP_ITEM || tempMap[z - 2][x] == MAP_ITEM_F || tempMap[z - 2][x] == MAP_ITEM_S) { temppacket->push = 1; tempz = z - 2; } } break; default: printf("Unknown Direction!!!!\n"); break; } //throw관련 송신패킷구조체에 넣어줘야 한다. if (temppacket->push == 1) tempMap[startz][startx] = MAP_NOTHING; temppacket->posx = startx; temppacket->posz = startz; temppacket->posx_d = tempx; temppacket->posz_d = tempz; temppacket->direction = direction; tempp->posx = startx; tempp->posz = startz; memcpy(g_TurtleMap_room[room_num - 1].mapInfo, tempMap, sizeof(tempMap)); } void SetMapToValue(int maptype,int mapnum) { if (maptype == 0 || maptype == 2) { ifstream in("Map1-1.csv"); vector <string> v({ istream_iterator<string>(in),istream_iterator<string>() }); in.close(); vector<string> string_list; for (int i = 3 + (mapnum * 15); i < 18 + (mapnum * 15); ++i) { string wordlist; for (auto word : v[i]) { if (word == v[i].back()) { } if (word == ',' || word == '\0') { cout << wordlist << " "; string_list.emplace_back(wordlist); wordlist.clear(); } else { //cout << word << " "; wordlist += word; } } cout << endl << endl; int x = 0; int z = 0; for (auto a : string_list) { if (x >= 5) { g_TB_Map[maptype][mapnum].mapTile[z][x - 5] = atoi(a.c_str()); } if (x < 20) ++x; if (x >= 20) { x = 0; z = z + 1; } } } } else if (maptype == 1) { ifstream in("Map2-1.csv"); vector <string> v({ istream_iterator<string>(in),istream_iterator<string>() }); in.close(); vector<string> string_list; for (int i = 3 + (mapnum * 15); i < 18 + (mapnum * 15); ++i) { string wordlist; for (auto word : v[i]) { if (word == v[i].back()) { } if (word == ',' || word == '\0') { cout << wordlist << " "; string_list.emplace_back(wordlist); wordlist.clear(); } else { //cout << word << " "; wordlist += word; } } cout << endl << endl; int x = 0; int z = 0; for (auto a : string_list) { if (x >= 5) { g_TB_Map[maptype][mapnum].mapTile[z][x - 5] = atoi(a.c_str()); } if (x < 20) ++x; if (x >= 20) { x = 0; z = z + 1; } } } } } void SetMap(BYTE maptype, BYTE mapnum,BYTE room_num) { memcpy(&g_TurtleMap_room[room_num - 1].mapInfo, &g_TB_Map[mapnum][maptype], sizeof(g_TB_Map[mapnum][maptype])); } void ReGame(BYTE roomnum) { for(int i=0;i<4;++i) room[roomnum - 1].ready[i] = 0; ingame_Char_Info[roomnum - 1][0].posx = 0.0f; ingame_Char_Info[roomnum - 1][0].posz = 0.0f; ingame_Char_Info[roomnum - 1][0].is_alive = true; ingame_Char_Info[roomnum - 1][0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[roomnum - 1][1].posx = 28.0f; ingame_Char_Info[roomnum - 1][1].posz = 0.0f; ingame_Char_Info[roomnum - 1][1].is_alive = true; ingame_Char_Info[roomnum - 1][1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[roomnum - 1][2].posx = 0.0f; ingame_Char_Info[roomnum - 1][2].posz = 28.0f; ingame_Char_Info[roomnum - 1][2].is_alive = true; ingame_Char_Info[roomnum - 1][2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[roomnum - 1][3].posx = 28.0f; ingame_Char_Info[roomnum - 1][3].posz = 28.0f; ingame_Char_Info[roomnum - 1][3].is_alive = true; ingame_Char_Info[roomnum - 1][3].rotY = 180.0f; for (int i = 0; i < 4; ++i) { ingame_Char_Info[roomnum - 1][i].is_alive = true; ingame_Char_Info[roomnum - 1][i].can_kick = false; ingame_Char_Info[roomnum - 1][i].can_throw = false; ingame_Char_Info[roomnum - 1][i].ingame_id = i; ingame_Char_Info[roomnum - 1][i].anistate = 0; ingame_Char_Info[roomnum - 1][i].is_alive = 0; ingame_Char_Info[roomnum - 1][i].can_kick = 0; ingame_Char_Info[roomnum - 1][i].can_throw = 0; ingame_Char_Info[roomnum - 1][i].bomb = 2; ingame_Char_Info[roomnum - 1][i].fire = 2; } } void ArrayMap() { for (int j = 0; j < 20; ++j) { g_TurtleMap_room[j].size = SIZEOF_TB_MAP; g_TurtleMap_room[j].type = CASE_MAP; room[j].game_start = 0; room[j].size = SIZEOF_TB_Room; room[j].type = CASE_ROOM; room[j].made = 0; room[j].people_count = 0; room[j].people_max = 4; room[j].roomID = j + 1; room[j].roomstate = 0; room[j].guardian_pos = 0; room[j].map_mode = 0; room[j].map_thema = 0; for (int z = 0; z < 15; ++z) { for (int x = 0; x < 15; ++x) { fireMap[j][z][x] = 0; dfMap[j][z][x]=0; ufMap[j][z][x]=0; lfMap[j][z][x]=0; rfMap[j][z][x]=0; } } for (int i = 0; i < 4; ++i) { room[j].ready[i] = 0; room[j].people_inroom[i] = 0; ingame_Char_Info[j][i].size = SIZEOF_TB_CharPos; ingame_Char_Info[j][i].type = CASE_POS; ingame_Char_Info[j][i].anistate = 0; ingame_Char_Info[j][i].is_alive = 0; ingame_Char_Info[j][i].can_kick = 0; ingame_Char_Info[j][i].can_throw = 0; ingame_Char_Info[j][i].bomb = 2; ingame_Char_Info[j][i].fire = 2; //ingame_Char_Info[j][i].speed = 2; //char_info[i].speed = 2; } ingame_Char_Info[j][0].ingame_id = 0; ingame_Char_Info[j][1].ingame_id = 1; ingame_Char_Info[j][2].ingame_id = 2; ingame_Char_Info[j][3].ingame_id = 3; //char_info[0].hp = 10.0f; ingame_Char_Info[j][0].posx = 0.0f; ingame_Char_Info[j][0].posz = 0.0f; ingame_Char_Info[j][0].is_alive = true; ingame_Char_Info[j][0].rotY = 0.0f; //char_info[1].hp = 10.0f; ingame_Char_Info[j][1].posx = 28.0f; ingame_Char_Info[j][1].posz = 0.0f; ingame_Char_Info[j][1].is_alive = true; ingame_Char_Info[j][1].rotY = 0.0f; //char_info[2].hp = 10.0f; ingame_Char_Info[j][2].posx = 0.0f; ingame_Char_Info[j][2].posz = 28.0f; ingame_Char_Info[j][2].is_alive = true; ingame_Char_Info[j][2].rotY = 180.0f; //char_info[3].hp = 10.0f; ingame_Char_Info[j][3].posx = 28.0f; ingame_Char_Info[j][3].posz = 28.0f; ingame_Char_Info[j][3].is_alive = true; ingame_Char_Info[j][3].rotY = 180.0f; } /* room[0].made = 1; room[2].made = 1; room[10].made = 1; room[0].people_inroom[2] = 25; room[0].guardian_pos = 3; */ } CString GetIpAddress() { WORD wVersionRequested; WSADATA wsaData; char name[255]; PHOSTENT hostinfo; CString strIpAddress = _T(""); wVersionRequested = MAKEWORD(2, 2); if (WSAStartup(wVersionRequested, &wsaData) == 0) { cout << "Get IP"; if (gethostname(name, sizeof(name)) == 0) { cout << "Get IP2"; if ((hostinfo = gethostbyname(name)) != NULL) { strIpAddress = inet_ntoa(*(struct in_addr *)*hostinfo->h_addr_list); cout << "Get IP3"; } } WSACleanup(); } return strIpAddress; } void Refresh_Map() { system("cls"); } /* string real_ip() { HINTERNET net = InternetOpenA("IP retriever", INTERNET_OPEN_TYPE_PRECONFIG, NULL, NULL, 0); HINTERNET conn = InternetOpenUrlA(net, "http://myexternalip.com/raw", NULL, 0, INTERNET_FLAG_RELOAD, 0); char buffer[4096]; DWORD read; InternetReadFile(conn, buffer, sizeof(buffer) / sizeof(buffer[0]), &read); InternetCloseHandle(net); return std::string(buffer, read); }*/<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; static class NOTICE_NUMBER { public const int AIR_DROP = 0; public const int DANGER = 1; public const int BOSS_INTRO_1_DANGER = 2; } public class Notice_UI : MonoBehaviour { static Notice_UI m_Instance; Animation m_Animations; Notice_Sound m_Notice_Sound; public RawImage m_Child_Image; public Texture m_AirDrop_Image_Font; public Texture m_Danger_Image_Font; void Awake() { m_Instance = this; m_Animations = GetComponent<Animation>(); m_Notice_Sound = GetComponentInChildren<Notice_Sound>(); } public static Notice_UI GetInstance() { return m_Instance; } public void Notice_Play(int num) { switch(num) { case NOTICE_NUMBER.AIR_DROP: m_Child_Image.texture = m_AirDrop_Image_Font; m_Animations.Play(m_Animations.GetClip("Air_Drop").name); break; case NOTICE_NUMBER.DANGER: m_Child_Image.texture = m_Danger_Image_Font; m_Animations.Play(m_Animations.GetClip("Danger").name); break; case NOTICE_NUMBER.BOSS_INTRO_1_DANGER: m_Child_Image.texture = m_Danger_Image_Font; m_Animations.Play(m_Animations.GetClip("Boss_Intro_1_Danger").name); Invoke("RedAlert_Sound", 0.9f); break; } } void RedAlert_Sound() { m_Notice_Sound.Play_RedAlertSound(); } } <file_sep>#define WIN32_LEAN_AND_MEAN #define INITGUID #include <winsock2.h> #include <Windows.h> #include <thread> #include <vector> #include <array> #include "protocol.h" #include <iostream> #pragma comment(lib, "ws2_32.lib") using namespace std; HANDLE g_hIOCP; struct EXOVERLAPPED { WSAOVERLAPPED m_over; char m_iobuf[MAX_BUFF_SIZE]; WSABUF m_WSABUF; bool is_recv; }; class Client { public: SOCKET m_Socket; bool m_isConnected; int m_X; int m_Y; EXOVERLAPPED m_Recv_exover; int m_prev_packet_size; // 이전 recv에서 완성되지 않고 쌓인 패킷 크기 int m_curr_packet_size; // 지금 조립하는 패킷 크기 char m_packet[MAX_PACKET_SIZE]; Client() { m_isConnected = false; m_X = 4; m_Y = 4; ZeroMemory(&m_Recv_exover.m_over, sizeof(WSAOVERLAPPED)); m_Recv_exover.m_WSABUF.buf = m_Recv_exover.m_iobuf; m_Recv_exover.m_WSABUF.len = sizeof(m_Recv_exover.m_WSABUF.buf); m_Recv_exover.is_recv = true; }; ~Client() {}; }; array<Client, MAX_USER> g_Clients; void Initialize() { g_hIOCP = CreateIoCompletionPort(INVALID_HANDLE_VALUE, 0, 0, 0); } void StartRecv(int id) { unsigned long r_flag = 0; ZeroMemory(&g_Clients[id].m_Recv_exover.m_over, sizeof(WSAOVERLAPPED)); WSARecv(g_Clients[id].m_Socket, &g_Clients[id].m_Recv_exover.m_WSABUF, 1, NULL, &r_flag, &g_Clients[id].m_Recv_exover.m_over, NULL); } void ProcessPacket(int id, char* packet) { int x = g_Clients[id].m_X; int y = g_Clients[id].m_Y; switch (packet[1]) { case CS_UP: if (y > 0) --y; break; case CS_DOWN: if (y < BOARD_HEIGHT - 1) ++y; break; case CS_LEFT: if (x > 0) --x; break; case CS_RIGHT: if (x < BOARD_WIDTH - 1) ++x; break; default: cout << "Unknown Packet Type from Client [" << id << "]\n"; return; } g_Clients[id].m_X = x; g_Clients[id].m_Y = y; sc_packet_pos pos_packet; pos_packet.id = id; pos_packet.size = sizeof(sc_packet_pos); pos_packet.type = SC_POS; pos_packet.x = x; pos_packet.y = y; EXOVERLAPPED* send_over = new EXOVERLAPPED; send_over->is_recv = false; memcpy(send_over->m_iobuf, &pos_packet, pos_packet.size); send_over->m_over, 0; send_over->m_WSABUF.buf = send_over->m_iobuf; send_over->m_WSABUF.len = send_over->m_iobuf[0]; WSASend(g_Clients[id].m_Socket, &send_over->m_WSABUF, 1, NULL, 0, &send_over->m_over, NULL); } void Worker_Thread() { while (true) { unsigned long io_size; unsigned long long iocp_key; // x64 = long long, x86 = long WSAOVERLAPPED* over; // WSAOVERLAPPED 구조체는 winsock2.h 에 있다. BOOL ret = GetQueuedCompletionStatus(g_hIOCP, &io_size, &iocp_key, &over, INFINITE); int key = static_cast<int> (iocp_key); // Send / Recv 처리를 한다. if (ret == FALSE) // 오류처리 { cout << "ERROR in GQCS\n"; continue; } if (io_size == 0) // 접속 종료 처리 { closesocket(g_Clients[key].m_Socket); g_Clients[key].m_isConnected = false; continue; } EXOVERLAPPED* p_Overlapped = reinterpret_cast<EXOVERLAPPED*>(&over); if (p_Overlapped->is_recv == true) // recv 처리 { int work_size = io_size; char* wptr = p_Overlapped->m_iobuf; while (work_size > 0) { int p_size; if (g_Clients[key].m_curr_packet_size != 0) p_size = g_Clients[key].m_curr_packet_size; else { p_size = wptr[0]; g_Clients[key].m_prev_packet_size = p_size; } int need_size = p_size - g_Clients[key].m_prev_packet_size; // 패킷 처리 if (need_size <= work_size) { memcpy(g_Clients[key].m_packet + g_Clients[key].m_prev_packet_size, wptr, need_size); ProcessPacket(key, g_Clients[key].m_packet); g_Clients[key].m_prev_packet_size = 0; g_Clients[key].m_curr_packet_size = 0; work_size -= need_size; } // 패킷을 처리할 수 없어서 저장 else { memcpy(g_Clients[key].m_packet + g_Clients[key].m_prev_packet_size, wptr, work_size); g_Clients[key].m_prev_packet_size += work_size; work_size = -work_size; wptr += work_size; } } StartRecv(key); } else // send 후처리 { delete p_Overlapped; } } } void Accept_Thread() { SOCKET s = WSASocket(AF_INET, SOCK_STREAM, IPPROTO_TCP, NULL, 0, WSA_FLAG_OVERLAPPED); // 마지막 인자에 주의! SOCKADDR_IN bind_Addr; ZeroMemory(&bind_Addr, sizeof(SOCKADDR_IN)); bind_Addr.sin_family = AF_INET; bind_Addr.sin_port = htons(MY_SERVER_PORT); bind_Addr.sin_addr.s_addr = INADDR_ANY; ::bind(s, reinterpret_cast<sockaddr*>(&bind_Addr), sizeof(bind_Addr)); listen(s, 1000); while (true) { SOCKADDR_IN recv_Addr; ZeroMemory(&recv_Addr, sizeof(SOCKADDR_IN)); recv_Addr.sin_family = AF_INET; recv_Addr.sin_port = htons(MY_SERVER_PORT); recv_Addr.sin_addr.s_addr = INADDR_ANY; int addr_size = sizeof(sockaddr); // WSAAccept()를 호출하여 클라이언트 소켓을 받는다. SOCKET client_socket = WSAAccept(s, reinterpret_cast<sockaddr*>(&recv_Addr), &addr_size, NULL, NULL); int id = -1; for (int i = 0; i < MAX_USER; ++i) { if (g_Clients[i].m_isConnected == false) { id = i; break; } } if (id == -1) { cout << "MAX_USER Exceeded\n"; continue; } // 받아온 소켓을 IOCP에 등록한다. CreateIoCompletionPort(reinterpret_cast<HANDLE>(client_socket), g_hIOCP, id, 0); g_Clients[id].m_isConnected = true; StartRecv(id); } } void main() { vector<thread> w_threads; Initialize(); for (int i = 0; i < 4; ++i) w_threads.push_back(thread{ Worker_Thread, i }); thread a_thread{ Accept_Thread }; for (auto& th : w_threads) th.join(); a_thread.join(); }<file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Stage_Clear : MonoBehaviour { Animation m_Animations; void Start () { m_Animations = GetComponent<Animation>(); } public void Stage_Clear_Direction_Play() { m_Animations.Play(m_Animations.GetClip("Stage_Clear").name); } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO; public struct Adventure_Quest_Data { public int ID; public int Quest_ID; public int isCountable; public string Quest_Script; public int Quest_Goal; } public struct Object_Table_Data { public int ID; } public struct Object_Spawn_Position_Data { public int[] Spawn_Node; } public struct Adventure_Stage_Data { public int ID; public int Use_Terrain_Number; public int Use_Tile_Number; public int Stage_Time; public int AirDrop_Time; public int Number_Of_DropItem; public int SuddenDeath_Time; public int Number_Of_GliderGoblin; public int GliderGoblin_Bomb; public int GliderGoblin_Fire; public int[] Adventure_Quest_ID_List; public int[] Stage_Pattern_ID_List; } public struct Adventure_Boss_Data { public int Boss_HP; public int Bomb_Damage; public int Angry_Condition_Start_HP; public int Groggy_Condition_Start_HP; public int Spawn_MonsterGroup_Id; public int Spawn_MonsterGroup_Number; } public struct Adventure_Big_Boss_Normal_Mode_AI_Data { public double Boss_Speed_Value; public int[] Skill_Time; public int[] Spawn_Monster_Value_Min; public int[] Spawn_Monster_Value_Max; public int[] Spawn_Monster_Speed_Value; public int Glider_Goblin_Bomb_Value; public int Glider_Goblin_Fire_Value; public int Skill_Fire_Range_Min; public int Skill_Fire_Range_Max; public int Fire_In_Range_Min; public int Fire_In_Range_Max; public List<int[]> Skill_Percentage; public List<int> Skill_Duration; public List<int> Link_Skill; } public struct Adventure_Big_Boss_Angry_Mode_AI_Data { public double Boss_Speed_Value; public int[] Skill_Time; public int[] Spawn_Monster_Value_Min; public int[] Spawn_Monster_Value_Max; public int[] Spawn_Monster_Speed_Value; public int Glider_Goblin_Bomb_Value; public int Glider_Goblin_Fire_Value; public int Skill_Fire_Range_Min; public int Skill_Fire_Range_Max; public int Fire_In_Range_Min; public int Fire_In_Range_Max; public List<int[]> Skill_Percentage; public List<int> Skill_Duration; public List<int> Link_Skill; } public struct Adventure_Big_Boss_Groggy_Mode_AI_Data { public double Boss_Speed_Value; } public class CSV_Manager : MonoBehaviour { private static CSV_Manager instance = null; public static CSV_Manager GetInstance() { if (instance == null) instance = new CSV_Manager(); return instance; } public TextAsset m_Adventure_Quest_csvFile; public TextAsset m_Object_Table_csvFile; public TextAsset m_Object_Spawn_Table_csvFile; public TextAsset m_Stage_Table_csvFile; public TextAsset m_Script_Table_csvFile; public TextAsset m_Adventure_Boss_Table_csvFile; public TextAsset m_Adventure_Boss_AI_csvFile; protected string[] m_data; protected string[] m_stringList; protected string m_Read_Text; private void Awake() { instance = this; } // ========= 이하는 CSV 파일을 읽어 List로 반환해주는 함수들이다. ========= // 어드벤쳐모드 퀘스트 목록 public void Get_Adventure_Quest_List(ref List<Adventure_Quest_Data> list, ref int[] mission_list) { Adventure_Quest_Data data = new Adventure_Quest_Data(); m_stringList = m_Adventure_Quest_csvFile.text.Split('\n'); list.Clear(); // 3 부터 시작 for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); // 스테이지 번호를 확인한다. for (int j = 0; j < 3; ++j) { if (System.Convert.ToInt32(m_data[0]) == mission_list[j]) { // 입력한 값과 일치한다면 필요한 데이터를 리스트에 삽입. data.ID = System.Convert.ToInt32(m_data[0]); data.Quest_ID = System.Convert.ToInt32(m_data[1]); data.isCountable = System.Convert.ToInt32(m_data[2]); data.Quest_Script = m_data[3]; data.Quest_Goal = System.Convert.ToInt32(m_data[4]); list.Add(data); } } } } // 인게임 오브젝트 목록 public List<Object_Table_Data> Get_Object_Table_List() { Object_Table_Data data = new Object_Table_Data(); List<Object_Table_Data> List = new List<Object_Table_Data>(); m_stringList = m_Object_Table_csvFile.text.Split('\n'); for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); data.ID = System.Convert.ToInt32(m_data[0]); List.Add(data); } return List; } // 오브젝트 스폰 좌표 목록 public void Get_Object_Spawn_Position_List(ref List<Object_Spawn_Position_Data> list, int stage_id) { Object_Spawn_Position_Data data; m_stringList = m_Object_Spawn_Table_csvFile.text.Split('\n'); list.Clear(); for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); if (stage_id == System.Convert.ToInt32(m_data[2])) { data = new Object_Spawn_Position_Data(); data.Spawn_Node = new int[15]; for (int j = 0; j < 15; ++j) { data.Spawn_Node[j] = System.Convert.ToInt32(m_data[j + 5]); } list.Add(data); } } } // 스크립트 하나 가져오기 public List<string> Get_Script(int scriptID) { List<string> script_List = new List<string>(); string temp = ""; string temp2 = ""; m_stringList = m_Script_Table_csvFile.text.Split('\n'); for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); if (scriptID == System.Convert.ToInt32(m_data[0])) temp = m_data[2]; } for (int i = 0; i < temp.Length; ++i) { if (temp[i] == '-' && temp[i + 1] == 'n' && temp[i + 2] == '-') // "-n-" 를 만나면 리스트에 삽입 { script_List.Add(temp2); temp2 = ""; i += 2; } else temp2 += temp[i]; // 임시변수에 한글자씩 담는다. } if (temp2.Length != 0) // 마지막 라인이 빈 글이 아니면 또 추가 script_List.Add(temp2); return script_List; } // 보스 테이블 public void Get_Adventure_Boss_Data(ref Adventure_Boss_Data Boss_Data_Structure, int objectNum) { m_stringList = m_Adventure_Boss_Table_csvFile.text.Split('\n'); for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); // 한 줄씩 읽기 if (objectNum == System.Convert.ToInt32(m_data[0])) // id는 오브젝트 테이블의 번호가 아닌 보스 테이블의 번호임! { Boss_Data_Structure.Boss_HP = System.Convert.ToInt32(m_data[2]); Boss_Data_Structure.Bomb_Damage = System.Convert.ToInt32(m_data[3]); Boss_Data_Structure.Angry_Condition_Start_HP = System.Convert.ToInt32(m_data[6]); Boss_Data_Structure.Groggy_Condition_Start_HP = System.Convert.ToInt32(m_data[7]); Boss_Data_Structure.Spawn_MonsterGroup_Id = System.Convert.ToInt32(m_data[8]); Boss_Data_Structure.Spawn_MonsterGroup_Number = System.Convert.ToInt32(m_data[9]); break; } } } // 스테이지 테이블 public void Get_Adventure_Stage_Data(ref Adventure_Stage_Data Stage_Data_Structure, int stage_ID) { m_stringList = m_Stage_Table_csvFile.text.Split('\n'); m_data = m_stringList[3 + stage_ID].Split(','); Stage_Data_Structure.ID = System.Convert.ToInt32(m_data[0]); Stage_Data_Structure.Use_Terrain_Number = System.Convert.ToInt32(m_data[2]); Stage_Data_Structure.Use_Tile_Number = System.Convert.ToInt32(m_data[3]); Stage_Data_Structure.Stage_Time = System.Convert.ToInt32(m_data[4]); Stage_Data_Structure.AirDrop_Time = System.Convert.ToInt32(m_data[5]); Stage_Data_Structure.Number_Of_DropItem = System.Convert.ToInt32(m_data[6]); Stage_Data_Structure.SuddenDeath_Time = System.Convert.ToInt32(m_data[7]); Stage_Data_Structure.Number_Of_GliderGoblin = System.Convert.ToInt32(m_data[8]); Stage_Data_Structure.GliderGoblin_Bomb = System.Convert.ToInt32(m_data[9]); Stage_Data_Structure.GliderGoblin_Fire = System.Convert.ToInt32(m_data[10]); for (int i = 0; i < 3; ++i) { if (m_data[11 + i] != "0") // 빈칸이 아니면 Stage_Data_Structure.Adventure_Quest_ID_List[i] = System.Convert.ToInt32(m_data[11 + i]); if (m_data[14 + i] != "0") // 빈칸이 아니면 Stage_Data_Structure.Stage_Pattern_ID_List[i] = System.Convert.ToInt32(m_data[14 + i]); } } // 스테이지별 퀘스트 번호만 받아오기 (PlayerPref용) public void Get_Adv_Mission_Num_List(ref int[] list, int stage_ID) { m_stringList = m_Stage_Table_csvFile.text.Split('\n'); m_data = m_stringList[3 + stage_ID].Split(','); for (int i = 0; i < 3; ++i) { if (m_data[11 + i] != "0") // 빈칸이 아니면 list[i] = System.Convert.ToInt32(m_data[11 + i]); } } // 구현된 퀘스트의 마지막 번호를 받아오기 (PlayerPref용) public void Get_Adv_Max_Mission_Num(ref int max_num) { m_stringList = m_Adventure_Quest_csvFile.text.Split('\n'); int num = 0; for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); if (System.Convert.ToInt32(m_data[0]) > num) num = System.Convert.ToInt32(m_data[0]); } max_num = num; } // 구현된 스테이지의 마지막 번호를 받아오기 (PlayerPref용) public void Get_Adv_Max_Stage_Num(ref int max_num, ref int max_num_for_Load) { m_stringList = m_Stage_Table_csvFile.text.Split('\n'); int max = 0; int max_for_Load = 0; for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); if (System.Convert.ToInt32(m_data[0]) > max) { max = System.Convert.ToInt32(m_data[0]); } if (System.Convert.ToInt32(m_data[14]) > max_for_Load) { max_for_Load = System.Convert.ToInt32(m_data[14]); if (System.Convert.ToInt32(m_data[15]) > max_for_Load) { max_for_Load = System.Convert.ToInt32(m_data[15]); if (System.Convert.ToInt32(m_data[16]) > max_for_Load) { max_for_Load = System.Convert.ToInt32(m_data[16]); } } } } max_num = max; max_num_for_Load = max_for_Load; } // 보스 AI 데이터 public void Get_Adventure_Big_Boss_AI_Data(ref Adventure_Big_Boss_Normal_Mode_AI_Data normal, ref Adventure_Big_Boss_Angry_Mode_AI_Data angry, ref Adventure_Big_Boss_Groggy_Mode_AI_Data groggy) { string tmpStr = ""; m_stringList = m_Adventure_Boss_AI_csvFile.text.Split('\n'); for (int i = 3; i < m_stringList.Length; ++i) { m_data = m_stringList[i].Split(','); // 한 줄 읽어서 ','로 분해 //======================================================================= // normal if (i == 3) normal.Boss_Speed_Value = System.Convert.ToDouble(m_data[2]); else if (i == 4) { for (int j = 0; j < 4; ++j) { normal.Skill_Time[j] = System.Convert.ToInt32(m_data[j + 2]); } } else if (i == 5) { for (int j = 0; j < 2; ++j) { normal.Spawn_Monster_Value_Min[j] = System.Convert.ToInt32(m_data[j + 3]); } } else if (i == 6) { for (int j = 0; j < 2; ++j) { normal.Spawn_Monster_Value_Max[j] = System.Convert.ToInt32(m_data[j + 3]); } } else if (i == 7) { for (int j = 0; j < 2; ++j) { normal.Spawn_Monster_Speed_Value[j] = System.Convert.ToInt32(m_data[j + 3]); } } else if (i == 8) { normal.Glider_Goblin_Bomb_Value = System.Convert.ToInt32(m_data[4]); } else if (i == 9) { normal.Glider_Goblin_Fire_Value = System.Convert.ToInt32(m_data[4]); } else if (i == 10) { normal.Skill_Fire_Range_Min = System.Convert.ToInt32(m_data[5]); } else if (i == 11) { normal.Skill_Fire_Range_Max = System.Convert.ToInt32(m_data[5]); } else if (i == 12) { normal.Fire_In_Range_Min = System.Convert.ToInt32(m_data[5]); } else if (i == 13) { normal.Fire_In_Range_Max = System.Convert.ToInt32(m_data[5]); } else if (i == 14) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } normal.Skill_Percentage.Add(tmpArray); } else if (i == 15) normal.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 16) normal.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); else if (i == 17) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } normal.Skill_Percentage.Add(tmpArray); } else if (i == 18) normal.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 19) normal.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); else if (i == 20) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } normal.Skill_Percentage.Add(tmpArray); } else if (i == 21) normal.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 22) normal.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); else if (i == 23) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } normal.Skill_Percentage.Add(tmpArray); } else if (i == 24) normal.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 25) normal.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); else if (i == 26) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } normal.Skill_Percentage.Add(tmpArray); } else if (i == 27) normal.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 28) normal.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); //======================================================================= // angry else if (i == 29) angry.Boss_Speed_Value = System.Convert.ToDouble(m_data[2]); else if (i == 30) { for (int j = 0; j < 4; ++j) angry.Skill_Time[j] = System.Convert.ToInt32(m_data[j + 2]); } else if (i == 31) { for (int j = 0; j < 2; ++j) angry.Spawn_Monster_Value_Min[j] = System.Convert.ToInt32(m_data[j + 3]); } else if (i == 32) { for (int j = 0; j < 2; ++j) angry.Spawn_Monster_Value_Max[j] = System.Convert.ToInt32(m_data[j + 3]); } else if (i == 33) { for (int j = 0; j < 2; ++j) angry.Spawn_Monster_Speed_Value[j] = System.Convert.ToInt32(m_data[j + 3]); } else if (i == 34) { angry.Glider_Goblin_Bomb_Value = System.Convert.ToInt32(m_data[4]); } else if (i == 35) { angry.Glider_Goblin_Fire_Value = System.Convert.ToInt32(m_data[4]); } else if (i == 36) { angry.Skill_Fire_Range_Min = System.Convert.ToInt32(m_data[5]); } else if (i == 37) { angry.Skill_Fire_Range_Max = System.Convert.ToInt32(m_data[5]); } else if (i == 38) { angry.Fire_In_Range_Min = System.Convert.ToInt32(m_data[5]); } else if (i == 39) { angry.Fire_In_Range_Max = System.Convert.ToInt32(m_data[5]); } else if (i == 40) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } angry.Skill_Percentage.Add(tmpArray); } else if (i == 41) angry.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 42) angry.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); else if (i == 43) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } angry.Skill_Percentage.Add(tmpArray); } else if (i == 44) angry.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 45) angry.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); else if (i == 46) { int[] tmpArray = new int[4]; for (int j = 0; j < 4; ++j) { foreach (char c in m_data[j + 2]) { if (c != '%') tmpStr += c; } tmpArray[j] = System.Convert.ToInt32(tmpStr); tmpStr = ""; } angry.Skill_Percentage.Add(tmpArray); } else if (i == 47) angry.Skill_Duration.Add(System.Convert.ToInt32(m_data[2])); else if (i == 48) angry.Link_Skill.Add(System.Convert.ToInt32(m_data[2])); //======================================================================= // groggy else if (i == 49) groggy.Boss_Speed_Value = System.Convert.ToDouble(m_data[2]); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Net_Boss_1 : MonoBehaviour { bool sensored = false; bool cooltime = false; // Use this for initialization void Start () { sensored = false; StartCoroutine("SendTester"); } void OnTriggerEnter(Collider other) { if (gameObject.activeInHierarchy && !Performance_Network.instance.ani_is_working) { if (other.gameObject.CompareTag("Player")) { if (Turtle_Move_Coop.instance.alive != 0) { if(!cooltime) sensored = true; //Debug.Log("Sensored"); } } } } void OnTriggerStay(Collider other) { if (other.gameObject.CompareTag("Player")) { if (Turtle_Move_Coop.instance.alive != 0) { if (!cooltime) sensored = true; } } // =================== } void OnTriggerExit(Collider other) { if (other.gameObject.CompareTag("Player")) { sensored = false; } } void CoolTimeOff() { cooltime = false; } // Update is called once per frame IEnumerator SendTester() { WaitForSeconds delay = new WaitForSeconds(0.1f); for (; ; ) { if (sensored) { NetManager_Coop.instance.SendBossPacket(VariableManager_Coop.instance.pos_id); sensored = false; cooltime = true; //Debug.Log("Send BossPacket"); Invoke("CoolTimeOff", 2.0f); } yield return delay; } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class NetTeam4 : MonoBehaviour { public Material[] team_material; //public GameObject[] team_turtle; Renderer rend; // Use this for initialization void Start() { rend = GetComponent<Renderer>(); rend.sharedMaterial = team_material[VariableManager.instance.roominfo[VariableManager.instance.m_roomid - 1].team4]; } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class BoxCollider_x : MonoBehaviour { //public static BoxCollider_x instance; BoxCollider m_box_col; // Use this for initialization void Start () { m_box_col = GetComponent<BoxCollider>(); } public void ChangeBoxColX(int left,int right) { m_box_col = GetComponent<BoxCollider>(); float centerx = ((float)((right - left) / 2.0f))*2; int sizex = (left + right+1)*2; m_box_col.center = new Vector3(centerx, 0, -2); m_box_col.size = new Vector3(sizex,2,4); } // Update is called once per frame void OnTriggerEnter(Collider other) { if (gameObject.activeInHierarchy) { if (!Camera_Directing_Net.GetInstance().ani_is_working) { if (other.gameObject.CompareTag("Player")) { if (SceneManager.GetActiveScene().buildIndex == 7 || SceneChange.instance.GetSceneState() == 13) { if (Turtle_Move.instance.alive != 0) { //Debug.Log("TTaGawa"); if (Turtle_Move.instance.glider_on) { Turtle_Move.instance.alive = 1; Turtle_Move.instance.glider_on = false; Turtle_Move.instance.overpower = true; } else { if (!Turtle_Move.instance.overpower) Turtle_Move.instance.alive = 0; } NetTest.instance.SetmoveTrue(); } } else { Turtle_Move_Coop.instance.alive = 0; NetManager_Coop.instance.SetMyPos(transform.position.x, transform.rotation.y, transform.position.z); } } } } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Info_Trigger : MonoBehaviour { public int m_Script_Num; void OnTriggerEnter(Collider other) { if (other.gameObject.tag == "Player") { Script_Box.c_Script_Box.Set_TextList(CSV_Manager.GetInstance().Get_Script(m_Script_Num)); // 대사 받아오기 Script_Box.c_Script_Box.gameObject.SetActive(true); // 박스 활성화 // 트리거 제거 GameObject[] triggers = GameObject.FindGameObjectsWithTag(gameObject.tag); foreach (GameObject t in triggers) Destroy(t); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; static class CALL_BOMB_STATE { public const int NORMAL = 0; public const int DROP = 1; } static class BOMB_POOL_VALUES { public const int BOMB_MAX_COUNT = 40; } public class Bomb_Pooling_Manager : MonoBehaviour { static Bomb_Pooling_Manager m_Instance; public static Bomb_Pooling_Manager GetInstance() { return m_Instance; } Queue<GameObject> m_Bomb_Pool; public GameObject m_Bomb_Object; GameObject m_Temp_Bomb; void Awake() { m_Instance = this; m_Bomb_Pool = new Queue<GameObject>(); GameObject temp; for (int i = 0; i < BOMB_POOL_VALUES.BOMB_MAX_COUNT; ++i) { temp = Instantiate(m_Bomb_Object); temp.transform.parent = transform; temp.tag = "Untagged"; m_Bomb_Pool.Enqueue(temp); } } public GameObject Dequeue_Bomb(GameObject who, int state) // 꺼내기 { m_Temp_Bomb = null; if (who.GetComponent<Bomb_Setter>().Get_Curr_Bomb_Count() > 0) { m_Temp_Bomb = m_Bomb_Pool.Dequeue(); m_Temp_Bomb.tag = "Bomb"; m_Temp_Bomb.GetComponent<Bomb_Remaster>().Get_Out_Of_Pool(who, state); who.GetComponent<Bomb_Setter>().Decrease_Bomb_Count(); } return m_Temp_Bomb; } public void Enqueue_Bomb(GameObject bomb) { bomb.tag = "Untagged"; m_Bomb_Pool.Enqueue(bomb); } // 넣기 } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; public class Airplane : MonoBehaviour { static Airplane m_Instance; public static Airplane GetInstance() { return m_Instance; } public GameObject Airdrop_Item; Animation m_Animations; float m_Airdrop_Time; // 테이블로 관리됨. StageManager에서 받아온다. int m_Airdrop_Count = 0; [HideInInspector] public bool m_is_able_to_Drop = false; IEnumerator m_Airdrop; IEnumerator m_Time_Checker; void Start() { m_Instance = this; m_Animations = GetComponent<Animation>(); m_Airdrop = AirDrop(); m_Time_Checker = AirDrop_Time_Check(); StartCoroutine(Wait_For_Intro()); m_Airdrop_Time = StageManager.GetInstance().Get_AirDrop_Time(); } IEnumerator AirDrop() { while (true) { if (m_Animations["Air_Drop"].normalizedTime >= 0.8f) { for (int i = 0; i < m_Airdrop_Count; ++i) { int index; while (true) // 루프를 돌면서 지형 탐색 { index = Random.Range(17, 271); // 맵 범위 if (!StageManager.GetInstance().Get_MCL_index_is_Blocked(index)) // 막혀있지 않으면 break; // 탈출 } Vector3 pos; pos.x = 0.0f; pos.y = 15.0f; pos.z = 0.0f; StageManager.GetInstance().Get_MCL_Coordinate(index, ref pos.x, ref pos.z); Instantiate(Airdrop_Item).transform.position = pos; // 설정한 위치에 아이템 투하 } StopCoroutine(m_Airdrop); // 에어드랍 종료 StartCoroutine(m_Time_Checker); // 시간 체크 시작 } yield return null; } } IEnumerator AirDrop_Time_Check() { while(true) { if (UI.GetInstance().Get_Elapsed_Time() >= m_Airdrop_Time) { Dispatch_Airplane(); UI.GetInstance().Set_Elapsed_Time(0.0f); } yield return null; } } IEnumerator Wait_For_Intro() { while(true) { if (StageManager.GetInstance().Get_is_Intro_Over()) { StopAllCoroutines(); StartCoroutine(m_Time_Checker); } yield return null; } } void Dispatch_Airplane() { Notice_UI.GetInstance().Notice_Play(NOTICE_NUMBER.AIR_DROP); StopCoroutine(m_Time_Checker); GetComponentInChildren<Airdrop_Sound>().Play_AirplaneSound(); m_Animations.Play(m_Animations.GetClip("Air_Drop").name); StartCoroutine(m_Airdrop); } public void Set_Airdrop_Count(int c) { m_Airdrop_Count = c; } }
dbd26fe9facebf25c2b173dbfc9bf1682bd9bae8
[ "C#", "Text", "C++" ]
113
C#
RRE1012/Turtle_Bomb
d7996b761e5fc4a20706cc5aee1b9f0226fa6157
0cb2c8c7c00793ad17599544fbdd9878b79c133b
refs/heads/master
<file_sep># RFID based Attendance Managment System Attendance needs to be taken at various places including colleges, school for students and in the industries for the login/logout time. Radio Frequency Identification (RFID) based attendance management system can be used in any college or university or company.Main objective of RFID based Attendance System project is to take the attendance of students or employees. Microcontroller does the task of storing the attendance of the respective person in the Microcontroller memory. Problem with existing attendance system is that wrong attendance can be entered. For example, in colleges one student can give proxy attendance of another student. Probability of this is very less but it does happen.Also in an industry, employee can enter invalid/incorrect login logout time. They can come at 10am and can enter time as 8 am. We have implemented automated attendance system which utilizes RFID cards. Thus it is a RFID based attendance system. In this system each user, student or employee will have a RFID card. And RFID reader will be placed on the door or the entry gate of the company or on the door of the classroom or school. Whenever employee wants to enter in the office; he/she has to show the RFID card to the reader. He/she has to take the RFID card near to the RFID reader. Then the RFID reader will note down the RFID card number and the time at which the employees / student has logged in. And in the same manner while leaving employee/student has to show the card. So the exit time will be noted. ## Software Requirements: - Arduino IDE: You will be needing Arduino IDE software to write and upload the programming logic onto the NodeMCU board - Programming language: Embedded C ## Hardware Requirements: - Arduino UNO - Potentiometer - RFID Reader - LCD - RFID tags - Rtc module(DS1307) - Bread Board - Connecting wires(male to female wires) ## Implementation - **Step 1:** RFID First thing we do is start wiring up the power to the RFID and the breadboard. - **Step 2:** LCD and Potentiometer Next we wire up the power to the LCD and the potentiometer. - **Step 3:** Wiring the LCD Then we wire the LCD screen to the Arduino - **Step 4:** LCD to Potentiometer and RTC module A small but important step is wiring the potentiometer to the LCD to adjust brightness. - **Step 5:** RFID Finally we wire up the RFID to the Arduino. Source included. <file_sep>//All Credit Technic 1510 // // // // #include <SPI.h> #include <MFRC522.h> #include <LiquidCrystal.h> #include <RTClib.h> // for the RTC #define SS_PIN 10 #define RST_PIN 9 // Instance of the class for RTC RTC_DS1307 rtc; MFRC522 mfrc522(SS_PIN, RST_PIN); LiquidCrystal lcd(6 , 7, 5, 4, 3, 2); // Define check in time const int checkInHour =22; const int checkInMinute = 5; int userCheckInHour; int userCheckInMinute; const int redLED = 6; const int greenLED = 7; const int buzzer = 5; void setup() { SPI.begin(); mfrc522.PCD_Init(); DateTime now = rtc.now(); userCheckInHour = now.hour(); userCheckInMinute = now.minute(); lcd.begin(16, 2); lcd.print("Scan RFID Card"); // Setup for the RTC if(!rtc.begin()) { lcd.print("Couldn't find RTC"); Serial.println("Couldn't find RTC"); while(1); } else { // following line sets the RTC to the date & time this sketch was compiled rtc.adjust(DateTime(F(__DATE__), F(__TIME__))); } if(!rtc.isrunning()) { Serial.println("RTC is NOT running!"); } } void loop() { if ( ! mfrc522.PICC_IsNewCardPresent()) { return; } if ( ! mfrc522.PICC_ReadCardSerial()) { return; } lcd.clear(); lcd.begin(16, 2); lcd.print("Place your id card:"); String content= ""; byte letter; for (byte i = 0; i < mfrc522.uid.size; i++) { lcd.setCursor(0, 1); lcd.print(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " "); lcd.print(mfrc522.uid.uidByte[i], HEX); content.concat(String(mfrc522.uid.uidByte[i] < 0x10 ? " 0" : " ")); content.concat(String(mfrc522.uid.uidByte[i], HEX)); } lcd.clear(); lcd.begin(16, 2); lcd.print(" "); content.toUpperCase(); if (content.substring(1) == "0E D4 4C 75") //Plz change to your cards UID { DateTime now = rtc.now(); userCheckInHour = now.hour(); userCheckInMinute = now.minute(); lcd.print("time:"); lcd.print(userCheckInHour); lcd.print(":"); lcd.print(userCheckInMinute); if((userCheckInHour < checkInHour)||((userCheckInHour==checkInHour) && (userCheckInMinute <= checkInMinute))) { lcd.setCursor(0,1); lcd.print("Welcome Abhigna"); digitalWrite(greenLED, HIGH); delay(2000); digitalWrite(greenLED,LOW); } else{ digitalWrite(redLED, HIGH); delay(2000); digitalWrite(redLED,LOW); //Serial.println("You are late..."); lcd.setCursor(0,1); lcd.print("You are Late"); } delay(3000); lcd.clear(); setup(); } else { lcd.setCursor(0, 1); lcd.print(" Access denied"); delay(3000); lcd.clear(); setup(); }}
1afb57b5f57aa426a7680d20400f2fbd80902aad
[ "Markdown", "C++" ]
2
Markdown
abhignas/rfid
7591488f8526fb15497904c32ef3d39af75f3b59
ba0d10bb021333a3dddb8279059142087f330213
refs/heads/master
<repo_name>Carnival-Corpse/ProgramacionAvanzada2019-2<file_sep>/src/programacionavanzada2019/pkg2/ProgramacionAvanzada20192.java /* * 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. */ package programacionavanzada2019.pkg2; /** * * @author <NAME> */ public class ProgramacionAvanzada20192 { /** * @param args the command line arguments */ public static void main(String[] args) { Fecha fecha1 = new Fecha(); Fecha fecha2 = new Fecha(23,10,1999); Fecha fecha3 = new Fecha(fecha2); System.out.println(); // System.out.println(f2.dia+"/"+f2.mes+"/"+f2.anyo); } } <file_sep>/src/programacionavanzada2019/pkg2/Fecha.java /* * 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. */ package programacionavanzada2019.pkg2; /** * * @author <NAME> */ public class Fecha { int dia; int mes; int anyo; Fecha(){ dia = 0; mes = 0; anyo= 0; } // metodo constructor Fecha(int d,int m, int a){ dia = d; mes = m; anyo=a; } Fecha(Fecha f){ dia = f.dia; mes = f.mes; anyo = f.anyo; } }
4495e2af60e0835fe108037273e6cca3bb9fbe2a
[ "Java" ]
2
Java
Carnival-Corpse/ProgramacionAvanzada2019-2
1ae2a57cbb3abe8c9e5e57aa6b272e42c31f8f1d
9ed9b2b3681a6eb990a4ad53f174246b448c5773
refs/heads/master
<repo_name>sa616473/ML_Bootcamp<file_sep>/excersices/excersice_Panda.py import numpy as np import pandas as pd df = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/04-Pandas-Exercises/Salaries.csv') # print df.head() df.to_csv('test.csv', index = False) print df.info() # in order to get the average of one column grab the column and run mean print df['BasePay'].mean() print df['OvertimePay'].max() print df[df['EmployeeName'] == '<NAME>']['JobTitle'] print df[df['EmployeeName'] == '<NAME>']['TotalPay'] print df[df['TotalPay'] == df['TotalPay'].max()]['EmployeeName'] print df[df['TotalPay'] == df['TotalPay'].min()]['EmployeeName'] byyear = df.groupby('Year')['BasePay'] print byyear.mean() print df['JobTitle'].nunique() print df['JobTitle'].value_counts()[0:5] print sum(df[df['Year'] == 2013]['JobTitle'].value_counts()== 1) print len (df [df['JobTitle'].str.find("chief") >= 0]) def cheif_string(title): if 'chief' in title.lower().split(): return True else: return False print sum(df['JobTitle'].apply(lambda x: cheif_string(x))) df['title_len'] = df['JobTitle'].apply(len) print df[['TotalPayBenefits','title_len']].corr()<file_sep>/README.md # ML_Bootcamp This repositary contains all the work I have done in the Machine Learning Bootcamp. # What did I learn through this course? - Programming with Python - NumPy with Python - Using pandas Data Frames to solve complex tasks - Use pandas to handle Excel Files - Web scraping with python - Connect Python to SQL - Use matplotlib and seaborn for data visualizations - Use plotly for interactive visualizations - Machine Learning with SciKit Learn, including: - Linear Regression - K Nearest Neighbors - K Means Clustering - Decision Trees - Random Forests - Natural Language Processing - Neural Nets and Deep Learning - Support Vector Machines <file_sep>/data_analytics/Intro_NUM.py import numpy as np # lesson 1 #-------------------------------------------------------------------------------- ''' my_list = [1,2,3] print np.array(my_list) my_mat = [[1,2,3], [4,5,6], [7,8,9]] print my_mat print np.array(my_mat) #np.array() converts the list into a matrix print np.arange(0,10) # arange function which similar to range function in for loops # gives all the numbers in the given range print np.arange(0,10,2) # gives all the even numbers gives the every 2 number print np.zeros(5) # zeros function generates number of zeros print np.zeros((5,4)) # the tuple acts as the dimension of the zero matrices print np.ones((7,8)) # gives all ones print np.linspace(0,25,27) # gives EVENLY PLAced number of integers in the given range print np.eye(4) # gives and identity matrix this is crazy python is out of the world print np.random.rand(3,2) print np.random.randn(2,4) # given the matrix generates random numbers form 0 to 1 print np.random.randint(1,100, 20) # generates low inclusive and high exculsive # and the third parameter number of items arr = np.arange(25) # an array from 0 to 24 ranarr = np.random.randint(0,50,10) # generates 10 rand integers form 0 to 49 myarr = arr.reshape(5,5) # change the 1d array into an 5 X 5 array ranarr = ranarr.reshape(2,5) print myarr print ranarr # reshapes the array into specfic dimensions print ranarr.max() print myarr.min() print ranarr.argmax() # return the max value indices # finding min and max on a matrix print myarr.shape print arr.dtype # cheching the shape and date type """ #--------------------------------------------------------------------------------- #lesson 2 # Numpy indexing and selection """ arr = np.arange(0,11) print arr print arr[8] print arr[1:5] print arr[:6] print arr[5:] arr[0:5] = 100 # changes those indices to 100 print arr slice_of_arr = arr[0:6] print slice_of_arr slice_of_arr[:] = 99 print slice_of_arr print arr # here we can see that when we do slice_of_arr # we do not make copy of the orginal # we actually transfer the address of the orginal # so the orginals get manipulated # how to make a copy of an array? arr_copy = arr[0:6].copy() arr_copy[:] = 87 print arr_copy print arr # wuth this method the orginal is not effected arr_2d = np.array([[5,20,14], [6,4,8], [5,2,1]]) print arr_2d print arr_2d[2,1] #2d array print arr_2d[:2, 1:] # getting a sub matrix from a orginal matrix """ """ -- -- | 3 4 5 | arr[:2] | 7 2 1 | grab elemnts from rows 0 all the way to 1 | 8 2 4 | result : -- -- -- -- |3 4 5 | |7 2 1 | -- -- arr [:, 1:] result : -- -- | 4 5 | | 2 1 | | 2 4 | -- -- arr [:2, 1:] result : -- -- | 4 5 | | 2 1 | -- -- """ """ arr = np.arange(1,11) print arr > 5 # prints boolean values true for all the values greater than 5 otherwise false bool_arr = arr > 5 print arr[bool_arr] print arr [arr < 7] # prints all the numbers to be true arr_2d = np.arange(50).reshape(10,5) print arr_2d print arr_2d[5:7, 2:4] # practice sub matrices """ #-------------------------------------------------------------------------------------- # lesson 3 # NumPy Operations """ arr = np.arange(0,11) print arr + arr print arr*2 print arr[1:] / arr[1:] print arr % 4 print arr**3 print arr + 288 print arr / arr print 1 / arr # numpy just gives a warning when we try to to 1/0 # Basic arthematic operations on arrays arr = arr**2 print np.sqrt(arr) print np.tan(arr) # trignometric functions print np.log(arr) # universal array functions """ #------------------------------------------------------------------------------------- # Practice problems """ print np.zeros(10) # create an arrays of 10 zeros print np.ones(10) # create an array of 10 ones print np.ones(10) * 5 # create an array of ten fives print np.arange(10,51) # create an array of integers from 10 to 50 print np.arange(10, 51, 2) # same array with only even integers print np.arange(0,9).reshape(3,3) # create a 3 X 3 matrix from values 0 to 8 print np.eye(3) # create an 3 X 3 identity matrix print np.random.rand(1) # genarate a random number in between 0 to 1 print np.random.randn(25) # random samples of 25 numbers print np.arange(1,101).reshape(10,10)/100 # create an 10 X 10 matrinx numbers from 0.01 to 1 print np.linspace(0.01,1,100).reshape(10,10) #another way print np.linspace(0,1,20) # creat an 20 equally spaced array mat = np.arange(1,26).reshape(5,5) print mat[2:3, 1:5] # NumPy indexing and selection print np.sum(mat) # getiing the sum of all elements in the matrix print np.std(mat) # getting standard deviation for mat print mat.sum(axis = 0) # to sum all the columns """ #------------------------------------------------------------------------------------------------ '''<file_sep>/data_visulization/Pands_B_T.py import matplotlib matplotlib.use('Agg') import numpy as np import pandas as pd import seaborn as sns import matplotlib.pyplot as plt """ df1 = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/07-Pandas-Built-in-Data-Viz/df1', index_col = 0) # If I set the index column to 0 i get the 0 column as my index df2 = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/07-Pandas-Built-in-Data-Viz/df2') df3 = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/07-Pandas-Built-in-Data-Viz/df3') """ """ --> Data we are working with A B C D 2000-01-01 1.339091 -0.163643 -0.646443 1.041233 2000-01-02 -0.774984 0.137034 -0.882716 -2.253382 2000-01-03 -0.921037 -0.482943 -0.417100 0.478638 2000-01-04 -1.738808 -0.072973 0.056517 0.015085 2000-01-05 -0.905980 1.778576 0.381918 0.291436 a b c d 0 0.039762 0.218517 0.103423 0.957904 1 0.937288 0.041567 0.899125 0.977680 2 0.780504 0.008948 0.557808 0.797510 3 0.672717 0.247870 0.264071 0.444358 4 0.053829 0.520124 0.552264 0.190008 a b c d 0 0.336272 0.325011 0.001020 0.401402 1 0.980265 0.831835 0.772288 0.076485 2 0.480387 0.686839 0.000575 0.746758 3 0.502106 0.305142 0.768608 0.654685 4 0.856602 0.171448 0.157971 0.321231 """ # sna_plot = df1['A'].hist() # Gets me the histogram diretly from pandas # sna_plot = df1['A'].plot.hist() # sna_plot = df2.plot.area(alpha = 0.4) # sna_plot = df2.plot.bar(stacked = True) # print df1.index # df1.plot.line(x = df1.index(), y ='B') # sna_plot = df1.plot.scatter(x = 'A', y = 'B', c= 'C', cmap = 'coolwarm') # sna_plot = df1.plot.hexbin(x = 'A', y = 'B', cmap = 'coolwarm', gridsize = 25) """ sna_plot = df1.plot.density() fig = sna_plot.get_figure() fig.savefig('blank.pdf') """ #____________________________________________________________________________________ #Pandas built in exersice """ df3 = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/07-Pandas-Built-in-Data-Viz/df3') # sna_plot = df3.plot.scatter(x = 'a', y = 'b', color= 'red', figsize = (12,3)) # sna_plot = df3[['a','b']].plot.box() # sna_plot = df3['a'].plot.hist(bins = 30) temp = df3.iloc[0:30] f = plt.figure() sna_plot = temp.plot.area(alpha = 0.4) plt.legend(loc = 'center left', bbox_to_anchor = (1.0,0.5)) # sna_plot = df3['a'].plot.kde(lw = 5, linestyle = '--') fig = sna_plot.get_figure() fig.savefig('blank.pdf') """<file_sep>/data_visulization/Mat_Plot_excersice.py import matplotlib as plt print plt.use('Agg') import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages pp_1 = PdfPages('blank.pdf') x = np.arange(0,100) y = x*2 z = x ** 2 fig = plt.figure() axes= fig.add_axes([0,0,1,1]) axes.plot(x,y) axes.set_xlabel('X axis') axes.set_ylabel('y axis') axes.set_title('Grrsph') fig = plt.figure() ax1 = fig.add_axes([0.1,0.1,1,1]) ax2 = fig.add_axes([0.2,0.5,.2,.2]) ax1.plot(x,z) ax2.plot(x,y) fig,axes = plt.subplots(nrows = 1, ncols=2) plt.savefig(pp_1, format='pdf') pp_1.close()<file_sep>/intro/Hello.py import sys # First python program def main(): print(sys.argv) print('hello world') # command line arguments for python main() <file_sep>/data_analytics/Intro_PAn.py import numpy as np import pandas as pd #___________________________________________________________________________________ #lesson 1 # Series in panda ''' labels = ['a', 'b', 'c'] my_data = [10, 20, 30] arr = np.array(my_data) d = {'a':10, 'b':20, 'c':30} print pd.Series(data = my_data) """ """ --> returns this 0 10 1 20 2 30 """ """ print pd.Series(data=my_data, index= labels) """ """ -->returns this a 10 b 20 c 30 """ """ print pd.Series(d) """ """ --> returns this Key Value a 10 b 20 c 30 """ # a series cna hold anything objects to datatypes and functions """ # pd.series([sum,print,len]) 0 fucntion built in 1 function built in 2 function built in """ """ ser1 = pd.Series([1,2,3,4], ['USA', 'Germany', 'USSR', 'Japan']) ser2 = pd.Series([1,2,5,4], ['USA', 'Germany', 'Italy', 'Japan']) print ser1 print ser2['Italy'] print ser1 + ser2 # we can perform arthematic operations on series just like arrays """ """ """ #____________________________________________________________________________ #lesson 2 # Data frames in panda """ np.random.seed(101) df = pd.DataFrame(np.random.randn(5,4), ['a','b','c','d','e'], ['w','x','y','z']) l = [[1,2],[2,3]] l = np.array(l) l = pd.DataFrame(l,['age','height'],['life', 'health']) print l print df """ """ resut -> life health age 1 2 height 2 3 w x y z a 2.706850 0.628133 0.907969 0.503826 b 0.651118 -0.319318 -0.848077 0.605965 c -2.018168 0.740122 0.528813 -0.589001 d 0.188695 -0.758872 -0.933237 0.955057 e 0.190794 1.978757 2.605967 0.683509 # Gives us a perfect data frame """ """ print df['x']['c'] print df.x.c # alrenative way and confusings print df[['x','z']] # gives a part of the data frame # to grab the items first get the column and then the row df['new'] = df['w'] + df['x'] print df df['new'] = [1,2,3,4,5] print df # adding a new cloumn to dataframe print df.drop('x', axis = 1) # to remove columns we use the drop method this will not change the orginal # data in order to change the orginal data we need to set the inplace = True # axis= 0 for rows # axis= 1 for columns print df.shape # for the shape dimensions of the data frame print df.loc['c'] print df.iloc[2] #prints a series of the row c print df.loc['c':'d', 'x':'y'] print df.iloc[2:4, 1:3] # Grabing the subsets of the data frames """ #__________________________________________________________________________________________ # lesson 3 # DAta frames part 2 """ w x y z a 2.706850 0.628133 0.907969 0.503826 b 0.651118 -0.319318 -0.848077 0.605965 c -2.018168 0.740122 0.528813 -0.589001 d 0.188695 -0.758872 -0.933237 0.955057 e 0.190794 1.978757 2.605967 0.683509 # inital data frame """ """ np.random.seed(101) df = pd.DataFrame(np.random.randn(5,4), ['a','b','c','d','e'], ['w','x','y','z']) print df print df > 0 # this will return a data fram true for all values greater the 0 """ """ ---> Result w x y z a True True True True b True False False True c False True True False d True False False True e True True True True """ """ booldf = df > 0 print df[booldf] # Equvilent df[df > 0] """ """ --> Result w x y z a 2.706850 0.628133 0.907969 0.503826 b 0.651118 NaN NaN 0.605965 c NaN 0.740122 0.528813 NaN d 0.188695 NaN NaN 0.955057 e 0.190794 1.978757 2.605967 0.683509 # retruns a data frame with NaNs and values # NaNs are false """ """ print df['w'] > 0 """ """ --> Result a True b True c False d True e True Name: w, dtype: bool """ """ print df.loc['c'] > 0 """ """ --> Result w False x True y True z False Name: c, dtype: bool """ """ print df.loc['c' : 'd', 'w' : 'y'] > 1 """ """ --> Result w x y c False False False d False False False """ """ print df[df['w'] > 0] """ """ --> Result w x y z a 2.706850 0.628133 0.907969 0.503826 b 0.651118 -0.319318 -0.848077 0.605965 d 0.188695 -0.758872 -0.933237 0.955057 e 0.190794 1.978757 2.605967 0.683509 # gets rid of the false row in the w column """ """ print df[df['z'] < 0] """ """ --> result w x y z c -2.018168 0.740122 0.528813 -0.589001 """ """ print df[df['z'] < 0][['x','y']] """ """ --> Result x y c 0.740122 0.528813SS """ """ print df[df['w'] > 0][df[df['w'] > 0]['y'] < 0] print df[(df['w'] > 0) & (df['y'] < 0)] """ """ --> Result w x y z b 0.651118 -0.319318 -0.848077 0.605965 d 0.188695 -0.758872 -0.933237 0.955057 # python and works only for one for multiple conditions # we need to use & """ """ print df.reset_index() """ """ --> Result index w x y z 0 a 2.706850 0.628133 0.907969 0.503826 1 b 0.651118 -0.319318 -0.848077 0.605965 2 c -2.018168 0.740122 0.528813 -0.589001 3 d 0.188695 -0.758872 -0.933237 0.955057 4 e 0.190794 1.978757 2.605967 0.683509 """ """ newindex = ['hello','world','happy','horray','hell'] df['fun'] = newindex print df.set_index('fun', inplace = True) print df """ """ --> result w x y z fun hello 2.706850 0.628133 0.907969 0.503826 world 0.651118 -0.319318 -0.848077 0.605965 happy -2.018168 0.740122 0.528813 -0.589001 horray 0.188695 -0.758872 -0.933237 0.955057 hell 0.190794 1.978757 2.605967 0.683509 """ #_______________________________________________________________________________________ #lesson 4 # Multi Index and Index hirerachy """ outside = ['G1', 'G1', 'G1','G2','G2','G2'] inside = [1,2,3,1,2,3] hier_index = list(zip(outside,inside)) """ """ --> Result [('G1', 1), ('G1', 2), ('G1', 3), ('G2', 1), ('G2', 2), ('G2', 3)] """ """ hier_index = pd.MultiIndex.from_tuples(hier_index) print hier_index """ """ --> Result MultiIndex(levels=[[u'G1', u'G2'], [1, 2, 3]], codes=[[0, 0, 0, 1, 1, 1], [0, 1, 2, 0, 1, 2]]) """ """ df = pd.DataFrame(np.random.randn(6,2), hier_index,['A','B']) print df """ """ --> result A B G1 1 -0.807648 0.598966 2 0.569462 -0.347479 3 -0.343528 0.926892 G2 1 -1.026740 0.450313 2 -0.845371 -0.464961 3 -0.681891 -0.914345 """ """ print df.loc['G1','A'][1] """ """ -> result -1.134097264252374 """ """ df.index.names = ['groups', 'NUm'] print df """ """ --> Result A B groups NUm G1 1 -0.853974 0.116750 2 0.794272 -0.972888 3 0.370144 2.558539 G2 1 0.619690 -0.883645 2 0.530668 -0.607246 3 -0.102381 0.713712 """ """ print df.loc['G2','B'][2] print df.xs print df.xs(1, level = 'NUm') """ """ Returns a cross section of the rows and columns of a data frame A B groups G1 0.219976 -0.770112 G2 -1.431489 1.005300 """ #_______________________________________________________________________________ #lesson 5 #Missing Data """ d = {'A':[1,2,np.nan], 'B' : [5,np.nan, np.nan], 'C' : [1,2,3]} df = pd.DataFrame(d) print df """ """ --> result A B C 0 1.0 5.0 1 1 2.0 NaN 2 2 NaN NaN 3 """ """ print df.dropna() """ """ --> result A B C 0 1.0 5.0 1 """ """ print df.dropna(axis=1) """ """ --> Result C 0 1 1 2 2 3 """ """ print df.dropna(thresh = 2) """ """ --> Result A B C 0 1.0 5.0 1 1 2.0 NaN 2 # Row two has 2 NaN values """ """ print df.fillna(value = df .mean()) """ """ --> Reuslt Fills the empty spaces with mean of the column's value A B C 0 1.0 5.0 1 1 2.0 5.0 2 2 1.5 5.0 3 """ #___________________________________________________________________________________ # lesson 7 # Group By """ data = {'Company' : ['GOOG','GOOG', 'MSFT', 'MSFT', 'FB', 'FB'], 'Person' : ['Sam', 'Charlie', 'Amy', 'Vanessa', 'Carl', 'Sarah'], 'Sales' : [200, 100, 340, 124, 243, 350] } df = pd.DataFrame(data) print df """ """ --> Result Company Person Sales 0 GOOG Sam 200 1 GOOG Charlie 100 2 MSFT Amy 340 3 MSFT Vanessa 124 4 FB Carl 243 5 FB Sarah 350 """ """ byComp = df.groupby('Company') print 1 print byComp.mean() #1 print 2 print byComp.sum() #2 print 3 print byComp.std() #3 """ """ --> Result 1 Sales Company FB 296.5 GOOG 150.0 MSFT 232.0 2 Sales Company FB 593 GOOG 300 MSFT 464 3 Sales Company FB 75.660426 GOOG 70.710678 MSFT 152.735065 """ """ print byComp.sum().loc['FB'] """ """ --> result Sales 593 Name: FB, dtype: int64 """ """ print df.groupby('Company').count() ''' ''' --> RESULT Person Sales Company FB 2 2 GOOG 2 2 MSFT 2 2 ''' ''' print df.groupby('Company').describe() """ """ --> Reuslt Sales count mean std min 25% 50% 75% max Company FB 2.0 296.5 75.660426 243.0 269.75 296.5 323.25 350.0 GOOG 2.0 150.0 70.710678 100.0 125.00 150.0 175.00 200.0 MSFT 2.0 232.0 152.735065 124.0 178.00 232.0 286.00 340.0 """ """ print df.groupby('Company').describe().transpose() """ """ --> Result Company FB GOOG MSFT Sales count 2.000000 2.000000 2.000000 mean 296.500000 150.000000 232.000000 std 75.660426 70.710678 152.735065 min 243.000000 100.000000 124.000000 25% 269.750000 125.000000 178.000000 50% 296.500000 150.000000 232.000000 75% 323.250000 175.000000 286.000000 max 350.000000 200.000000 340.000000 """ #__________________________________________________________________________________ # lesson 8 # Merging concatenation and joining """ pd.concat([df1, df2, df3]) this method will concatnat all three data frames into one this will concatenate top and bottom pd.concat([df1, df2, df3], axis = 1) this will concat sidewards Glues the data frame """ """ left = pd.DataFrame({'key' : ['k1', 'k2', 'k3'], 'hello' : ['H4','H5','H6'], 'world' : ['W7','W8','W9']}) right = pd.DataFrame({'key' : ['k1', 'k2', 'k3'], 'hell' : ['h4','h5','h6'], 'war' : ['w7','w8','w9']}) print left print right print pd.merge(left, right, how = 'inner', on = 'key') """ """ --> Result hello key world 0 H4 k1 W7 1 H5 k2 W8 2 H6 k3 W9 hell key war 0 h4 k1 w7 1 h5 k2 w8 2 h6 k3 w9 hello key world hell war 0 H4 k1 W7 h4 w7 1 H5 k2 W8 h5 w8 2 H6 k3 W9 h6 w9 """ """ left = pd.DataFrame({'hello' : ['H4','H5','H6'], 'world' : ['W7','W8','W9']}, index = ['k1', 'k2', 'k3'] ) right = pd.DataFrame({'hell' : ['h4','h5','h6'], 'war' : ['w7','w8','w9']}, index = ['k1', 'k2', 'k3'] ) print left.join(right) print left.join(right, how = 'outer') print left.join(right, how = 'right') print left.join(right, how = 'left') """ """ --> Result 1. Inner hello world hell war k1 H4 W7 h4 w7 k2 H5 W8 h5 w8 k3 H6 W9 h6 w9 2.Outer hello world hell war k1 H4 W7 h4 w7 k2 H5 W8 h5 w8 k3 H6 W9 h6 w9 3. Right hello world hell war k1 H4 W7 h4 w7 k2 H5 W8 h5 w8 k3 H6 W9 h6 w9 4. left hello world hell war k1 H4 W7 h4 w7 k2 H5 W8 h5 w8 k3 H6 W9 h6 w9 """ #______________________________________________________________________________ # lesson 9 # Operations """ df = pd.DataFrame({'col1' : [1,2,3,4], 'col2' : [444, 555, 666, 444], 'col3' : ['abc', 'def', 'ghi', 'xyz']}) print df.head() """ """ --> Result col1 col2 col3 0 1 444 abc 1 2 555 def 2 3 666 ghi 3 4 444 xyz """ """ print df['col2'].unique() print df['col2'].nunique() print df['col2'].value_counts() """ """ --> result [444 555 666] 3 --> Unquie values # 444 2 555 1 666 1 Name: col2, dtype: int64 This method gives us all the unique values in a given column """ """ print df[df['col1'] > 2] """ """ --> Result col1 col2 col3 2 3 666 ghi 3 4 444 xyz you can put paranthesses and use conditonal operators such as & and | """ """ def times2(x): return x*2 print df['col2'].apply(times2) print df['col3'].apply(len) print df['col2'].apply(lambda x : x + x) """ """ --> result 1. 0 888 1 1110 2 1332 3 888 Name: col2, dtype: int64 2. 0 3 1 3 2 3 3 3 Name: col3, dtype: int64 3. 0 888 1 1110 2 1332 3 888 Name: col2, dtype: int64 """ """ print df.drop(0) # to drop row print df.drop('col1', axis = 1) # drop column """ """ ---> result col1 col2 col3 1 2 555 def 2 3 666 ghi 3 4 444 xyz col2 col3 0 444 abc 1 555 def 2 666 ghi 3 444 xyz """ """ print df.columns print df.index """ """ --> Result Index([u'col1', u'col2', u'col3'], dtype='object') RangeIndex(start=0, stop=4, step=1) """ """ print df.sort_values('col2') print df.sort_values(by = 'col2') """ """ --> result 1. col1 col2 col3 0 1 444 abc 3 4 444 xyz 1 2 555 def 2 3 666 ghi 2. col1 col2 col3 0 1 444 abc 3 4 444 xyz 1 2 555 def 2 3 666 ghi """ """ print df.isnull() """ """ --> result col1 col2 col3 0 False False False 1 False False False 2 False False False 3 False False False """ """ data = {'A' : ['foo', 'foo', 'foo', 'bar', 'bar', 'bar'], 'B' : ['one','one', 'two', 'two', 'one','one'], 'c' : ['x', 'y', 'x', 'y', 'x', 'y'], 'd' : [1,3,2,5,4,1]} df = pd.DataFrame(data) print df """ """ --> Data frame we are working with A B c d 0 foo one x 1 1 foo one y 3 2 foo two x 2 3 bar two y 5 4 bar one x 4 5 bar one y 1 """ """ print df.pivot_table(values = 'd', index = ['A', 'B'], columns = ['c']) """ """ --> Result A B bar one 4.0 1.0 two NaN 5.0 foo one 1.0 3.0 two 2.0 NaN """ #_________________________________________________________________________________________ #lesson 10 #Data imput and output """ print pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/03-Python-for-Data-Analysis-Pandas/example') """ """ --> Data fram we are woring with a b c d 0 0 1 2 3 1 4 5 6 7 2 8 9 10 11 3 12 13 14 15 """ """ df = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/03-Python-for-Data-Analysis-Pandas/example') df.to_csv('test.csv', index = False) df = pd.read_excel('Refactored_Py_DS_ML_Bootcamp-master/03-Python-for-Data-Analysis-Pandas/Excel_Sample.xlsx') df.to_excel('test.xlsx', sheet_name = 'New') """ """ --> Result We read the example file wrote that file to test.csv and we read the example one more time and wrote it to test.xlsv # pip install openpyxl """ """ data_html = pd.read_html('https://www.fdic.gov/bank/individual/failed/banklist.html') print data_html print data[0].head() """ """ Webscrapping the html file using pandas """ """ from sqlalchemy import create_engine # import create_engine from sqlalchemy """ """ engine = create_engine('sqlite:///:memo:') df.to_sql('my_table', engine) sqldf = pd.read_sql('my_table', con = engine) # reading and writing into pandas simple sql engine """ #______________________________ END OF PANDAS _________________________________________________________________________________________________________________ '''<file_sep>/data_visulization/ploty_cuff.py import matplotlib matplotlib.use('Agg') import pandas as pd import numpy as np from plotly import __version__ import cufflinks as cf from plotly.offline import plot import plotly.graph_objs as go import plotly.express as px cf.go_offline() #Data df = pd.DataFrame(np.random.randn(100,4), columns = 'A B C D'.split()) """ --> Data we are working with A B C D 0 0.040720 0.088769 0.947860 -0.223775 1 -0.070617 -1.293854 0.317639 -0.761501 2 0.408111 -0.089325 -0.404231 -0.044232 3 -0.666402 -0.131516 -1.404194 -1.853543 4 -0.110669 0.127784 -0.303840 -0.000030 """ df2 = pd.DataFrame({'Category' : ['A', 'B', 'C'], 'Values' : [32,43,50]}) """ --> Data we are working with Category Values 0 A 32 1 B 43 2 C 50 """ sna_plot = df.plot() fig = sna_plot.get_figure() fig.savefig('blank.pdf') <file_sep>/excersices/E-commerce.py import pandas as pd import numpy as np df = pd.read_csv('Refactored_Py_DS_ML_Bootcamp-master/04-Pandas-Exercises/Ecommerce Purchases') # print df.to_csv('temo.csv') print df.shape[1] ''' other ways len(ecom.colums) ecom.info() ''' print df['Purchase Price'].mean() print df['Purchase Price'].max() print df['Purchase Price'].min() print len(df[df['Language'] == 'en']) print len(df[df['Job'] == 'Lawyer']) print len(df[df['AM or PM'] == 'PM']) print len(df[df['AM or PM'] == 'AM']) # 5 most popular titles print df['Job'].value_counts()[0:5] print df[df['Lot'] == "90 WT"]['Purchase Price'] print df[df['Credit Card'] == 4926535242672853]['Email'] print len(df[(df['CC Provider'] == 'American Express') & (df ['Purchase Price'] > 95)]) print len (df [df['CC Exp Date'].apply(lambda exp : exp[3:] == '25')]) print df['Email'].apply(lambda exp : exp.split('@')[1]).value_counts()[0:5]<file_sep>/data_visulization/tes_Sea.py import matplotlib matplotlib.use('Agg') import seaborn as sns import numpy as np import matplotlib.pyplot as plt # Lesson 1 # Distribution Plots #_________________________________________________________________________________ """ tips = sns.load_dataset('tips') """ """ --> Result --> Data frame we are working with total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 """ # to get rid of the line we can do kde = False # bins gives you more detailed distrbution of the histogram """ #Different type of plots sns_plot = sns.distplot(tips['total_bill'], bins=30, kde=False) sns_plot = sns.jointplot(x ='total_bill', y = 'tip', data=tips, kind= 'kde', color= 'purple') sns_plot = sns.pairplot(tips, hue= 'sex', palette= 'coolwarm') sns_plot = sns.rugplot(tips['total_bill']) """ """ #Saving graphs to pdf fig = sns_plot.get_figure() fig.savefig('blank.pdf') # sns_plot.savefig("blank.pdf") """ #_________________________________________________________________________________ #lesson 2 # categorical plots """ tips = sns.load_dataset('tips') print tips.head() """ """ --> result total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 """ """ sns_plot = sns.barplot(x= 'sex', y='total_bill', data= tips, estimator = np.std) sns_plot = sns.countplot(x = 'sex', data = tips) sns_plot = sns.boxplot(x = 'day', y = 'total_bill', data=tips, hue= 'smoker') sns_plot = sns.violinplot(x = 'day', y = 'total_bill', data=tips, hue = 'sex', split=True) sns_plot = sns.stripplot(x='day', y = 'total_bill', data=tips, jitter=True, hue = 'se', split = True) sns_plot = sns.swarmplot(x ='day', y = 'total_bill', data=tips, color= 'black' ) sns_plot = sns.catplot(x = 'day', y = 'total_bill', data=tips, kind='violin') """ """ # fig = sns_plot.get_figure() # fig.savefig('blank.pdf') sns_plot.savefig('blank.pdf') """ #__________________________________________________________________________________ #lesson 3 #Matrix Plots """ tips = sns.load_dataset('tips') flights = sns.load_dataset('flights') print tips.head() print print flights.head() """ """ --> tips total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 --> Flights year month passengers 0 1949 January 112 1 1949 February 118 2 1949 March 132 3 1949 April 129 4 1949 May 121 """ """ tc = tips.corr() fg = flights.pivot_table(index = 'month', columns= 'year', values='passengers') """ """ --> Data we are working with total_bill tip size total_bill 1.000000 0.675734 0.598315 tip 0.675734 1.000000 0.489299 size 0.598315 0.489299 1.000000 """ """ print fg """ """ --> Flights dataframe after pivot table year 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 month January 112 115 145 171 196 204 242 284 315 340 360 417 February 118 126 150 180 196 188 233 277 301 318 342 391 March 132 141 178 193 236 235 267 317 356 362 406 419 April 129 135 163 181 235 227 269 313 348 348 396 461 May 121 125 172 183 229 234 270 318 355 363 420 472 June 135 149 178 218 243 264 315 374 422 435 472 535 July 148 170 199 230 264 302 364 413 465 491 548 622 August 148 170 199 242 272 293 347 405 467 505 559 606 September 136 158 184 209 237 259 312 355 404 404 463 508 October 119 133 162 191 211 229 274 306 347 359 407 461 November 104 114 146 172 180 203 237 271 305 310 362 390 December 118 140 166 194 201 229 278 306 336 337 405 432 """ """ ==> plots sns_plot = sns.heatmap(tc, color = 'red', annot=True, cmap='coolwarm') sns_plot = sns.heatmap(fg, cmap = 'magma', linecolor ='black' , linewidths=1) sns_plot = sns.clustermap(fg, cmap='coolwarm', standard_scale= 1) """ """ Saving to pdf # sns_plot.savefig('blank.pdf') # fig = sns_plot.get_figure() # fig.savefig('blank.pdf') """ #____________________________________________________________________________________ # lesson 4 # Grid models """ iris = sns.load_dataset('iris') print iris.head() """ """ --> Data we are working with sepal_length sepal_width petal_length petal_width species 0 5.1 3.5 1.4 0.2 setosa 1 4.9 3.0 1.4 0.2 setosa 2 4.7 3.2 1.3 0.2 setosa 3 4.6 3.1 1.5 0.2 setosa 4 5.0 3.6 1.4 0.2 setosa """ """ print iris['species'].unique() """ """ ['setosa' 'versicolor' 'virginica'] """ """ g = sns.PairGrid(iris) g.map_diag(sns.distplot) g.map_upper(plt.scatter) sns_plot = g.map_lower(sns.kdeplot) tips = sns.load_dataset('tips') g = sns.FacetGrid(data = tips, col = 'time', row = 'smoker') g.map(plt.scatter, 'total_bill', 'tip') sns_plot = g sns_plot.savefig('blank.pdf') """ #___________________________________________________________________________________ #lesson 5 # Regression plots """ tips = sns.load_dataset('tips') print tips.head() """ """ --> Date we are working with total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 """ """ sns_plot = sns.lmplot(x ='total_bill', y= 'tip', data=tips, hue='sex', markers= ['o', 'v'], scatter_kws={'s':100}, legend=True,col = 'sex', row = 'time', aspect= 0.6, height=8) sns_plot.savefig('blank.pdf') """ #___________________________________________________________________________________________________________________________________________________________________________________________ #lesson 6 # Style and color """ tips = sns.load_dataset('tips') """ """ --> Data we are working with total_bill tip sex smoker day time size 0 16.99 1.01 Female No Sun Dinner 2 1 10.34 1.66 Male No Sun Dinner 3 2 21.01 3.50 Male No Sun Dinner 3 3 23.68 3.31 Male No Sun Dinner 2 4 24.59 3.61 Female No Sun Dinner 4 """ """ sns.set_style('darkgrid') # plt.figure(figsize = (12,3)) sns.set_context('talk', font_scale= 2.5) sna_plot = sns.countplot(x='sex', data= tips) sns.despine(left=True) fig = sna_plot.get_figure() fig.savefig('blank.pdf') """ #________________________________________________________________________________ #Seaborn Excersice """ sns.set_style('whitegrid') titanic = sns.load_dataset('titanic') titanic.head() titanic_corr = titanic.corr() # sna_plot = sns.jointplot(x = 'fare', y = 'age', data = titanic) # sna_plot = sns.distplot(titanic['fare'], norm_hist=False, kde=False, color = 'red', bins = 30) # sna_plot = sns.swarmplot(x = 'class', y = 'age', data=titanic) g = sns.FacetGrid(data = titanic, col = 'sex') g.map(sns.distplot, 'age') sna_plot = g # sna_plot = sns.boxplot(x = 'class', y = 'age', data=titanic) # sna_plot = sns.violinplot(x = 'class', y = 'age', data=titanic, split=True, jitter = True) # sna_plot = sns.stripplot(x = 'class', y = 'age', data=titanic, dodge=True, jitter=True) # sna_plot = sns.countplot(x = 'sex', data=titanic) # sna_plot = sns.heatmap(titanic_corr, annot=False, cmap= 'coolwarm') # sna_plot= sns.FacetGrid(col= 'class' , row = 'age', data = titanic ) # fig = sna_plot.get_figure() # fig.savefig('blank.pdf') sna_plot.savefig('blank.pdf') """ #__________________________________________________________________________________________ <file_sep>/machineLearning/NLP/NLP.py import nltk # nltk.download_shell() messages = [line.rstrip() for line in open('smsspamcollection/SMSSpamCollection')] print(len(messages)) for mes_no, message in enumerate(messages[:10]): print(mes_no, message) print('\n') # Detecing which one is spam which one is ham import pandas as pd messages = pd.read_csv('smsspamcollection/SMSSpamCollection', sep='\t', names=['label', 'message']) print(messages.head()) <file_sep>/Refactored_Py_DS_ML_Bootcamp-master/test.py { "cells": [ { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "import matplotlib.pyplot as plt" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "%matplotlib inline" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import numpy as np\n", "x = np.linspace(0,5,11)\n", "y = x ** 2" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "image/png": "<KEY>", "text/plain": [ "<Figure size 432x288 with 1 Axes>" ] }, "metadata": { "needs_background": "light" }, "output_type": "display_data" } ], "source": [ "plt.plot(x,y)\n", "plt.show()" ] }, { "cell_type": "code", "execution_count": null, "metadata": {}, "outputs": [], "source": [] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.4" } }, "nbformat": 4, "nbformat_minor": 2 } <file_sep>/data_visulization/Mat_Plot.py import matplotlib as plt print plt.use('Agg') import matplotlib.pyplot as plt import numpy as np from matplotlib.backends.backend_pdf import PdfPages #lesson 1 # MAtplot lib #_____________________________________________________________________________________ pp_1 = PdfPages('blank.pdf') x = np.linspace(0,5,11) y = x ** 2 """ --> DATA xaxis = [0. 0.5 1. 1.5 2. 2.5 3. 3.5 4. 4.5 5. ] yaxis = [ 0. 0.25 1. 2.25 4. 6.25 9. 12.25 16. 20.25 25. ] """ plt.plot(x,y, 'r-') plt.xlabel('x axis') plt.ylabel('Y axis') plt.title('title') #Multiplots plt.subplot(1,2,1) plt.plot(x,y,'r') plt.subplot(1,2,2) plt.plot(y, x, 'b') #plots two different graphs # Object oriented method fig = plt.figure() axes = fig.add_axes([0.1,0.1,0.8,0.8]) axes.plot(x,y) axes.set_xlabel('X axis') axes.set_ylabel('y axis') axes.set_title('Grrsph') fig = plt.figure() #figure is an empty canvas and we can add graphs to it axes1 = fig.add_axes([0.1,0.1,0.8,0.8]) axes2 = fig.add_axes([0.2,0.5,0.4,0.3]) # axes3 = fig.add_axes([0.5,0.1,0.4,0.8]) axes1.plot(x,y, 'y') axes2.plot(y,x, 'g') fig,axes = plt.subplots(nrows=2, ncols=2) plt.tight_layout() axes[0][0].plot(x,y) fig , axes = plt.subplots(figsize = (8,2), nrows = 2, ncols = 1) fig = plt.figure() ax = fig.add_axes([0,0,1,1]) ax.plot(x,x**2,'#FF0093', label='x Square',linewidth=1,linestyle = 'steps') ax.plot(y,x**3, 'b', label = 'x cubes', marker = 'o', markersize = 30) ax.set_xlim([0,1]) ax.set_ylim([0,2]) ax.legend(loc = (0.5,0.3)) # ax.plot(x,y, color = '#FF0093', linewidth= 20) fig.tight_layout() plt.savefig(pp_1, format='pdf') pp_1.close() """ plotting the data and consverting it to a pdf file """ <file_sep>/intro/intro_python.py # raisin 7^4 can be done two ways x = 7*7*7*7 print x # simple way x = 7**4 print x # truning a string into a character array s = "Hi there Sam!" l = list(s) print l # spliting a string according to spaces and new lines l = s.split() print l planet = "Earth" diameter = 12742 # without using .format() print 'The diameter of', planet, 'is', diameter, 'kilometers' # Using .format() print 'The diameter of {} is {} kilometers'.format(planet, diameter) #Given the nested dictonary grab the word hello d = {'k1': [1,2,3,{'tricky':['oh','man','inception',{'target':[1,2,3,'hello']}]}]} print d.keys() print d['k1'][3]['tricky'][3]['target'][3] # the main difference between a tuple and a list is that # a list is mutable and tuple is immutable #simple function that returns the email.com def domainget(email): x = email.split('@') return x[1] #Fancy def domaingetfancy(email): return email.split('@')[1] print domainget('<EMAIL>') print domaingetfancy('<EMAIL>') # a function returns true if the word dog is presented in the string def finddog(s): x = s.lower() y = x.split() for i in range(len(y)): if y[i] == 'dog': return True return False print finddog('Is there a dog here?') # A function that counts the occurences of the word dog def countdog(s): counter = 0 x = s.lower().split() for i in range(len(x)): if x[i] == 'dog': counter = counter + 1 return counter print countdog('This dog is faster than 10 dog with 5 dog') seq = ['soup', 'dog', 'salad', 'cat', 'great'] # without using lamda and filter expression x = [] for i in range(len(seq)): if seq[i][0] == 's': x.append(seq[i]) print x; # using lambda expression and the filter function print list(filter(lambda word : word[0] == 's', seq)) # You are driving a little too fast, and a # police officer stops you. Write a function # to return one of 3 possible results: # No ticket, Small ticket, or Big Ticket. # If your speed is 60 or less, the result is # No Ticket. If speed is between 61 nd 80 # inclusive, the result is Small Ticket. # If speed is 81 or more, the result is # Big Ticket unless it is your birthday # (encoded as a boolean value in the parameters of the function) # on your birthday, your speed can be 5 higher in all cases. def caught_speeding(speed, is_birthday): if is_birthday == False: if speed <= 60: return 'NO TICKET' elif speed > 60 and speed <= 80: return 'SMALL TICKET' elif speed > 80: return 'BIG TICKET' elif is_birthday == True: if speed <= 65: return 'NO TICKET' elif speed > 65 and speed <= 85: return 'SMALL TICKET' elif speed > 85: return 'BIG TICKET' print caught_speeding(75, True)
96f61aab1b992a1643abe8e5440bcd04aa0d920f
[ "Markdown", "Python" ]
14
Python
sa616473/ML_Bootcamp
c52e3c18dc971e448e3634ec54f95593ad197ea8
c4d689784843a6308863861e9dca882374bd303b
refs/heads/master
<file_sep>import React from 'react'; import './Title.css'; const Title = props => ( <h1 className="title"> <img id="title-image" className="title__image" src="../../images/curious-george-logo.png" alt="curious-george" /> {" "}{props.children} </h1> ); export default Title;
343b4ade3f6dc847dddc28fee0958a7875e44e2f
[ "JavaScript" ]
1
JavaScript
Anri1214/clicky-game
6b7505c8b020adf0f3a259236629f98da9527073
9b20f8a9b2d86ff19f56704e5c81d494350913d8
refs/heads/master
<file_sep><?php namespace LunarPHP; /** * * 自动载入函数 * User: ljy * Date: 17-08-18 */ class Autoloader { const NAMESPACE_PREFIX = 'LunarPHP\\'; public static function register() { spl_autoload_register(array(new self, 'autoload')); } /** * 根据类名载入所在文件 */ public static function autoload($className) { $namespacePrefixStrlen = strlen(self::NAMESPACE_PREFIX); if ( strncmp(self::NAMESPACE_PREFIX, $className, $namespacePrefixStrlen) === 0 ){ $className = strtolower($className); $filePath = str_replace('\\', DIRECTORY_SEPARATOR, substr($className, $namespacePrefixStrlen)); $filePath = realpath(__DIR__ . ( empty($filePath) ? '' : DIRECTORY_SEPARATOR) . $filePath . '.lrp.php' ); if ( file_exists($filePath) ) { require_once $filePath; } else { echo $filePath; } } } }<file_sep><?php /** * Created by ljy * User: ljy <<EMAIL>> * Date: 2017/8/29 * Time: 11:30 */ namespace LunarPHP\Core; class Constellation { private $log; private $db; public function __construct() { $this->log = new Logger(); $this->db = new Model('constellation'); } /** * 获取运势 */ public function getFortune($name, $keyWorld, $date) { if (empty($name)) $this->log->log('获取运势失败:参数[星座]error'); $keyWorld = '爱情'; $date = '8月29日'; // $where = "name like '%{$name}%$keyWorld1%$keyWorld2%'"; $where = "name like '%{$name}%$keyWorld%'"; $data = $this->db->query('*', $where); return $data[0]; } }<file_sep><?php namespace LunarPHP; /** * 系统语言文件. * @Author: ljy * @Date: 17-08-18 */ $lang['home_contactHint'] = "<div style='text-align:justify'>感谢您对本网站的支持,若在使用上有任何问题或建议,请您不吝指教。我们会诚恳地接受并作为未来改善的重要参考。<br><br>现在,请稍加说明您的意见或您遇到的问题:</div>"; $lang['home_contactComplete'] = "感谢您的联系!<br><br>我们会尽速处理,使服务至臻完善。"; $lang['home_date'] = '国历(西元)'; $lang['home_originDate'] = '国历'; $lang['home_convertDate'] = '农历'; $lang['home_destiny'] = '本命卦'; $lang['home_divine'] = '卜卦'; $lang['home_hour1'] = '子时'; $lang['home_hour2'] = '丑时'; $lang['home_hour3'] = '寅时'; $lang['home_hour4'] = '卯时'; $lang['home_hour5'] = '辰时'; $lang['home_hour6'] = '巳时'; $lang['home_hour7'] = '午时'; $lang['home_hour8'] = '未时'; $lang['home_hour9'] = '申时'; $lang['home_hour10'] = '酉时'; $lang['home_hour11'] = '戌时'; $lang['home_hour12'] = '亥时'; $lang['home_animal1'] = '青龙'; $lang['home_animal2'] = '朱雀'; $lang['home_animal3'] = '勾陈'; $lang['home_animal4'] = '腾蛇'; $lang['home_animal5'] = '白虎'; $lang['home_animal6'] = '玄武'; $lang['home_sky1'] = '甲'; $lang['home_sky2'] = '乙'; $lang['home_sky3'] = '丙'; $lang['home_sky4'] = '丁'; $lang['home_sky5'] = '戊'; $lang['home_sky6'] = '己'; $lang['home_sky7'] = '庚'; $lang['home_sky8'] = '辛'; $lang['home_sky9'] = '壬'; $lang['home_sky10'] = '癸'; $lang['home_ground1'] = '子'; $lang['home_ground2'] = '丑'; $lang['home_ground3'] = '寅'; $lang['home_ground4'] = '卯'; $lang['home_ground5'] = '辰'; $lang['home_ground6'] = '巳'; $lang['home_ground7'] = '午'; $lang['home_ground8'] = '未'; $lang['home_ground9'] = '申'; $lang['home_ground10'] = '酉'; $lang['home_ground11'] = '戌'; $lang['home_ground12'] = '亥'; $lang['home_broken'] = '⚠破'; $lang['home_empty'] = '&curren;空亡'; $lang['home_treat'] = '<世>'; $lang['home_response'] = '<应>'; $lang['home_property1'] = '金'; $lang['home_property2'] = '木'; $lang['home_property3'] = '水'; $lang['home_property4'] = '火'; $lang['home_property5'] = '土'; $lang['home_groundAndProperty1'] = "子<span class='property'>(水)</span>"; $lang['home_groundAndProperty2'] = "丑<span class='property'>(土)</span>"; $lang['home_groundAndProperty3'] = "寅<span class='property'>(木)</span>"; $lang['home_groundAndProperty4'] = "卯<span class='property'>(木)</span>"; $lang['home_groundAndProperty5'] = "辰<span class='property'>(土)</span>"; $lang['home_groundAndProperty6'] = "巳<span class='property'>(火)</span>"; $lang['home_groundAndProperty7'] = "午<span class='property'>(火)</span>"; $lang['home_groundAndProperty8'] = "未<span class='property'>(土)</span>"; $lang['home_groundAndProperty9'] = "申<span class='property'>(金)</span>"; $lang['home_groundAndProperty10'] = "酉<span class='property'>(金)</span>"; $lang['home_groundAndProperty11'] = "戌<span class='property'>(土)</span>"; $lang['home_groundAndProperty12'] = "亥<span class='property'>(水)</span>"; $lang['home_family1'] = '父母'; $lang['home_family2'] = '兄弟'; $lang['home_family3'] = '子孙'; $lang['home_family4'] = '妻财'; $lang['home_family5'] = '官鬼'; $lang['home_symbol1'] = '干为天'; $lang['home_symbol2'] = '天山遁'; $lang['home_symbol3'] = '风地观'; $lang['home_symbol4'] = '火地晋'; $lang['home_symbol5'] = '天风姤'; $lang['home_symbol6'] = '天地否'; $lang['home_symbol7'] = '山地剥'; $lang['home_symbol8'] = '火天大有'; $lang['home_symbol9'] = '兑为泽'; $lang['home_symbol10'] = '泽地萃'; $lang['home_symbol11'] = '水山蹇'; $lang['home_symbol12'] = '雷山小过'; $lang['home_symbol13'] = '泽水困'; $lang['home_symbol14'] = '泽山咸'; $lang['home_symbol15'] = '地山谦'; $lang['home_symbol16'] = '雷泽归妹'; $lang['home_symbol17'] = '离为火'; $lang['home_symbol18'] = '火风鼎'; $lang['home_symbol19'] = '山水蒙'; $lang['home_symbol20'] = '天水讼'; $lang['home_symbol21'] = '火山旅'; $lang['home_symbol22'] = '火水未济'; $lang['home_symbol23'] = '风水涣'; $lang['home_symbol24'] = '天火同人'; $lang['home_symbol25'] = '震为雷'; $lang['home_symbol26'] = '雷水解'; $lang['home_symbol27'] = '地风升'; $lang['home_symbol28'] = '泽风大过'; $lang['home_symbol29'] = '雷地豫'; $lang['home_symbol30'] = '雷风恒'; $lang['home_symbol31'] = '水风井'; $lang['home_symbol32'] = '泽雷随'; $lang['home_symbol33'] = '巽为风'; $lang['home_symbol34'] = '风天小畜'; $lang['home_symbol35'] = '风火家人'; $lang['home_symbol36'] = '天雷旡妄'; $lang['home_symbol37'] = '风雷益'; $lang['home_symbol38'] = '山雷颐'; $lang['home_symbol39'] = '山风蛊'; $lang['home_symbol40'] = '火雷噬嗑'; $lang['home_symbol41'] = '坎为水'; $lang['home_symbol42'] = '水泽节'; $lang['home_symbol43'] = '水雷屯'; $lang['home_symbol44'] = '水火既济'; $lang['home_symbol45'] = '泽火革'; $lang['home_symbol46'] = '雷火丰'; $lang['home_symbol47'] = '地火明夷'; $lang['home_symbol48'] = '地水师'; $lang['home_symbol49'] = '艮为山'; $lang['home_symbol50'] = '山火贲'; $lang['home_symbol51'] = '山天大畜'; $lang['home_symbol52'] = '山泽损'; $lang['home_symbol53'] = '火泽睽'; $lang['home_symbol54'] = '天泽履'; $lang['home_symbol55'] = '风泽中孚'; $lang['home_symbol56'] = '风山渐'; $lang['home_symbol57'] = '坤为地'; $lang['home_symbol58'] = '地雷复'; $lang['home_symbol59'] = '地泽临'; $lang['home_symbol60'] = '地天泰'; $lang['home_symbol61'] = '雷天大壮'; $lang['home_symbol62'] = '泽天夬'; $lang['home_symbol63'] = '水天需'; $lang['home_symbol64'] = '水地比'; $lang['home_yearError'] = '"年" 栏位请输入数字'; $lang['home_yearRangeError'] = '"年" 栏位请输入1201 ~ 2050 之间'; $lang['home_monthError'] = '"月" 栏位请输入数字'; $lang['home_monthRangeError'] = '"月" 栏位请输入1 ~ 12 之间'; $lang['home_dayError'] = '"日" 栏位请输入数字'; $lang['home_dayRangeError'] = '"日" 栏位请输入1 ~ 31 之间'; define('LANG',json_encode($lang)); $tianGan = array("甲","乙","丙","丁","戊","己","庚","辛","壬","癸"); $diZhi = array("子","丑","寅","卯","辰","巳","午","未","申","酉","戌","亥"); $yearGan = array( '1' => array('甲','己'), '2' => array('乙','庚'), '3' => array('丙','辛'), '4' => array('丁','壬'), '5' => array('戊','癸'), ); $monthGan = array( '1' => array( '1' => '丙寅', '2' => '丁卯', '3' => '戊辰', '4' => '己巳', '5' => '庚午', '6' => '辛未', '7' => '壬申', '8' => '癸酉', '9' => '甲戌', '10' => '乙亥', '11' => '丙子', '12' => '丁丑', ), '2' => array( '1' => '戊寅', '2' => '己卯', '3' => '庚辰', '4' => '辛巳', '5' => '壬午', '6' => '癸未', '7' => '甲申', '8' => '乙酉', '9' => '丙戌', '10' => '丁亥', '11' => '戊子', '12' => '己丑', ), '3' => array( '1' => '庚寅', '2' => '辛卯', '3' => '壬辰', '4' => '癸巳', '5' => '甲午', '6' => '乙未', '7' => '丙申', '8' => '丁酉', '9' => '戊戌', '10' => '己亥', '11' => '庚子', '12' => '辛丑', ), '4' => array( '1' => '壬寅', '2' => '癸卯', '3' => '甲辰', '4' => '乙巳', '5' => '丙午', '6' => '丁未', '7' => '戊申', '8' => '己酉', '9' => '庚戌', '10' => '辛亥', '11' => '壬子', '12' => '癸丑', ), '5' => array( '1' => '甲寅', '2' => '乙卯', '3' => '丙辰', '4' => '丁巳', '5' => '戊午', '6' => '己未', '7' => '庚申', '8' => '辛酉', '9' => '壬戌', '10' => '癸亥', '11' => '甲子', '12' => '乙丑', ), ); /** 天干地支 **/ $dataInfo = array( 0x04bd8,0x04ae0,0x0a570,0x054d5,0x0d260,0x0d950,0x16554,0x056a0,0x09ad0,0x055d2,//1900-1909 0x04ae0,0x0a5b6,0x0a4d0,0x0d250,0x1d255,0x0b540,0x0d6a0,0x0ada2,0x095b0,0x14977,//1910-1919 0x04970,0x0a4b0,0x0b4b5,0x06a50,0x06d40,0x1ab54,0x02b60,0x09570,0x052f2,0x04970,//1920-1929 0x06566,0x0d4a0,0x0ea50,0x06e95,0x05ad0,0x02b60,0x186e3,0x092e0,0x1c8d7,0x0c950,//1930-1939 0x0d4a0,0x1d8a6,0x0b550,0x056a0,0x1a5b4,0x025d0,0x092d0,0x0d2b2,0x0a950,0x0b557,//1940-1949 0x06ca0,0x0b550,0x15355,0x04da0,0x0a5b0,0x14573,0x052b0,0x0a9a8,0x0e950,0x06aa0,//1950-1959 0x0aea6,0x0ab50,0x04b60,0x0aae4,0x0a570,0x05260,0x0f263,0x0d950,0x05b57,0x056a0,//1960-1969 0x096d0,0x04dd5,0x04ad0,0x0a4d0,0x0d4d4,0x0d250,0x0d558,0x0b540,0x0b6a0,0x195a6,//1970-1979 0x095b0,0x049b0,0x0a974,0x0a4b0,0x0b27a,0x06a50,0x06d40,0x0af46,0x0ab60,0x09570,//1980-1989 0x04af5,0x04970,0x064b0,0x074a3,0x0ea50,0x06b58,0x055c0,0x0ab60,0x096d5,0x092e0,//1990-1999 0x0c960,0x0d954,0x0d4a0,0x0da50,0x07552,0x056a0,0x0abb7,0x025d0,0x092d0,0x0cab5,//2000-2009 0x0a950,0x0b4a0,0x0baa4,0x0ad50,0x055d9,0x04ba0,0x0a5b0,0x15176,0x052b0,0x0a930,//2010-2019 0x07954,0x06aa0,0x0ad50,0x05b52,0x04b60,0x0a6e6,0x0a4e0,0x0d260,0x0ea65,0x0d530,//2020-2029 0x05aa0,0x076a3,0x096d0,0x04bd7,0x04ad0,0x0a4d0,0x1d0b6,0x0d250,0x0d520,0x0dd45,//2030-2039 0x0b5a0,0x056d0,0x055b2,0x049b0,0x0a577,0x0a4b0,0x0aa50,0x1b255,0x06d20,0x0ada0,//2040-2049 0x14b63,0x09370,0x049f8,0x04970,0x064b0,0x168a6,0x0ea50, 0x06b20,0x1a6c4,0x0aae0,//2050-2059 0x0a2e0,0x0d2e3,0x0c960,0x0d557,0x0d4a0,0x0da50,0x05d55,0x056a0,0x0a6d0,0x055d4,//2060-2069 0x052d0,0x0a9b8,0x0a950,0x0b4a0,0x0b6a6,0x0ad50,0x055a0,0x0aba4,0x0a5b0,0x052b0,//2070-2079 0x0b273,0x06930,0x07337,0x06aa0,0x0ad50,0x14b55,0x04b60,0x0a570,0x054e4,0x0d160,//2080-2089 0x0e968,0x0d520,0x0daa0,0x16aa6,0x056d0,0x04ae0,0x0a9d4,0x0a2d0,0x0d150,0x0f252,//2090-2099 0x0d520 ); $animals = array("鼠","牛","虎","兔","龙","蛇","马","羊","猴","鸡","狗","猪"); $lunarInfo = array( array(0,2,9,21936),array(6,1,30,9656),array(0,2,17,9584),array(0,2,6,21168),array(5,1,26,43344),array(0,2,13,59728), array(0,2,2,27296),array(3,1,22,44368),array(0,2,10,43856),array(8,1,30,19304),array(0,2,19,19168),array(0,2,8,42352), array(5,1,29,21096),array(0,2,16,53856),array(0,2,4,55632),array(4,1,25,27304),array(0,2,13,22176),array(0,2,2,39632), array(2,1,22,19176),array(0,2,10,19168),array(6,1,30,42200),array(0,2,18,42192),array(0,2,6,53840),array(5,1,26,54568), array(0,2,14,46400),array(0,2,3,54944),array(2,1,23,38608),array(0,2,11,38320),array(7,2,1,18872),array(0,2,20,18800), array(0,2,8,42160),array(5,1,28,45656),array(0,2,16,27216),array(0,2,5,27968),array(4,1,24,44456),array(0,2,13,11104), array(0,2,2,38256),array(2,1,23,18808),array(0,2,10,18800),array(6,1,30,25776),array(0,2,17,54432),array(0,2,6,59984), array(5,1,26,27976),array(0,2,14,23248),array(0,2,4,11104),array(3,1,24,37744),array(0,2,11,37600),array(7,1,31,51560), array(0,2,19,51536),array(0,2,8,54432),array(6,1,27,55888),array(0,2,15,46416),array(0,2,5,22176),array(4,1,25,43736), array(0,2,13,9680),array(0,2,2,37584),array(2,1,22,51544),array(0,2,10,43344),array(7,1,29,46248),array(0,2,17,27808), array(0,2,6,46416),array(5,1,27,21928),array(0,2,14,19872),array(0,2,3,42416),array(3,1,24,21176),array(0,2,12,21168), array(8,1,31,43344),array(0,2,18,59728),array(0,2,8,27296),array(6,1,28,44368),array(0,2,15,43856),array(0,2,5,19296), array(4,1,25,42352),array(0,2,13,42352),array(0,2,2,21088),array(3,1,21,59696),array(0,2,9,55632),array(7,1,30,23208), array(0,2,17,22176),array(0,2,6,38608),array(5,1,27,19176),array(0,2,15,19152),array(0,2,3,42192),array(4,1,23,53864), array(0,2,11,53840),array(8,1,31,54568),array(0,2,18,46400),array(0,2,7,46752),array(6,1,28,38608),array(0,2,16,38320), array(0,2,5,18864),array(4,1,25,42168),array(0,2,13,42160),array(10,2,2,45656),array(0,2,20,27216),array(0,2,9,27968), array(6,1,29,44448),array(0,2,17,43872),array(0,2,6,38256),array(5,1,27,18808),array(0,2,15,18800),array(0,2,4,25776), array(3,1,23,27216),array(0,2,10,59984),array(8,1,31,27432),array(0,2,19,23232),array(0,2,7,43872),array(5,1,28,37736), array(0,2,16,37600),array(0,2,5,51552),array(4,1,24,54440),array(0,2,12,54432),array(0,2,1,55888),array(2,1,22,23208), array(0,2,9,22176),array(7,1,29,43736),array(0,2,18,9680),array(0,2,7,37584),array(5,1,26,51544),array(0,2,14,43344), array(0,2,3,46240),array(4,1,23,46416),array(0,2,10,44368),array(9,1,31,21928),array(0,2,19,19360),array(0,2,8,42416), array(6,1,28,21176),array(0,2,16,21168),array(0,2,5,43312),array(4,1,25,29864),array(0,2,12,27296),array(0,2,1,44368), array(2,1,22,19880),array(0,2,10,19296),array(6,1,29,42352),array(0,2,17,42208),array(0,2,6,53856),array(5,1,26,59696), array(0,2,13,54576),array(0,2,3,23200),array(3,1,23,27472),array(0,2,11,38608),array(11,1,31,19176),array(0,2,19,19152), array(0,2,8,42192),array(6,1,28,53848),array(0,2,15,53840),array(0,2,4,54560),array(5,1,24,55968),array(0,2,12,46496), array(0,2,1,22224),array(2,1,22,19160),array(0,2,10,18864),array(7,1,30,42168),array(0,2,17,42160),array(0,2,6,43600), array(5,1,26,46376),array(0,2,14,27936),array(0,2,2,44448),array(3,1,23,21936),array(0,2,11,37744),array(8,2,1,18808), array(0,2,19,18800),array(0,2,8,25776),array(6,1,28,27216),array(0,2,15,59984),array(0,2,4,27424),array(4,1,24,43872), array(0,2,12,43744),array(0,2,2,37600),array(3,1,21,51568),array(0,2,9,51552),array(7,1,29,54440),array(0,2,17,54432), array(0,2,5,55888),array(5,1,26,23208),array(0,2,14,22176),array(0,2,3,42704),array(4,1,23,21224),array(0,2,11,21200), array(8,1,31,43352),array(0,2,19,43344),array(0,2,7,46240),array(6,1,27,46416),array(0,2,15,44368),array(0,2,5,21920), array(4,1,24,42448),array(0,2,12,42416),array(0,2,2,21168),array(3,1,22,43320),array(0,2,9,26928),array(7,1,29,29336), array(0,2,17,27296),array(0,2,6,44368),array(5,1,26,19880),array(0,2,14,19296),array(0,2,3,42352),array(4,1,24,21104), array(0,2,10,53856),array(8,1,30,59696),array(0,2,18,54560),array(0,2,7,55968),array(6,1,27,27472),array(0,2,15,22224), array(0,2,5,19168),array(4,1,25,42216),array(0,2,12,42192),array(0,2,1,53584),array(2,1,21,55592),array(0,2,9,54560) ); $hour = array( '子时' => 1, // (23 ~ 1) '丑时' => 2, // (1 ~ 3) '寅时' => 3, // (3 ~ 5) '卯时' => 4, // (5 ~ 7) '辰时' => 5, // (7 ~ 9) '巳时' => 6, // (9 ~ 11) '午时' => 7, // (11 ~ 13) '未时' => 8, // (13 ~ 15) '申时' => 9, // (15 ~ 17) '酉时' => 10, // (17 ~ 19) '戌时' => 11, // (19 ~ 21) '亥时' => 12, // (21 ~ 23) ); define('YEARGAN',json_encode($yearGan)); // 六十甲子年 define('MONTHGAN',json_encode($monthGan)); // 六十甲子月 define('TIANGAN',json_encode($tianGan)); // 十天干 define('DIZHI',json_encode($diZhi)); // 十二地支 define('DATAINFO',json_encode($dataInfo)); // 农历十六进制数据 define('ANIMALS',json_encode($animals)); // 十二生肖 define('LUNARINFO',json_encode($lunarInfo)); define('HOUR',json_encode($hour)); // 时辰 <file_sep><?php require_once 'LunarPHP.php'; use LunarPHP\Core\Lunar; use LunarPHP\Core\Calendar; use LunarPHP\Core\Hexagrams; use LunarPHP\Core\Logger; use LunarPHP\Core\Constellation; use LunarPHP\Core\Common; class example { private $calendar; private $lunar; private $hexagrams; private $log; private $date; private $year; private $month; private $day; private $DZ = array('Y','M','D'); public $error; public $hour; private $hourList; private $common; public function __construct( $date, $hour = '子时', Common $common ) { $this->date = $date; // 阳历日期 $this->year = date("Y",strtotime($date)); // 年 $this->month = date("m",strtotime($date)); // 月 $this->day = date("d",strtotime($date)); // 日 $this->calendar = new Calendar($this->date); $this->lunar = new Lunar(); $this->hexagrams = new Hexagrams(); $this->log = new Logger(); $this->common = $common; $this->hourList = json_decode(HOUR,true); // 时辰数组 $this->guaData = json_decode(GUA_DATA,true); // 卦象数据 $this->hour = $this->hourList[$hour]; } /** * 获取天干地支 * @param string $type Y:地支纪年 M:地支纪月 D:地支纪日 * @param boolean $suffix 是否显示后缀 * return string */ public function getGanZhi( $type, $suffix = true ) { $type = is_string($type) ? strtoupper($type) : false; if ( !in_array($type, $this->DZ) ) { $this->log->log('获取天干地支传递参数类型错误'); return false; } $suffixTitle = ''; if ($suffix) { $suffixTitle = array( 'Y' => '年', 'M' => '月', 'D' => '日', )[$type]; } switch ($type) { case 'Y': return $this->calendar->getYGanZhi().$suffixTitle; break; case 'M': return $this->calendar->getMGanZhi().$suffixTitle; break; case 'D': return $this->calendar->getDGanZhi().$suffixTitle; break; } } /** * 阳->阴 * @return array */ public function convertSolarToLunar() { $data = $this->lunar->convertSolarToLunar($this->year, $this->month, $this->day); $res['convertCYear'] = $data[0]; $res['convertCMonth'] = $data[1]; $res['convertCDay'] = $data[2]; $res['yearText'] = $this->getGanZhi('y',0); $res['monthText'] = $this->calendar->getMGanZhi(mb_substr($res['yearText'], 0, 1, 'utf-8'), $data[4]); $res['dayText'] = $this->getGanZhi('d',0); $res['convertNYear'] = $data[7]; $res['convertNMonth'] = $data[4]; $res['convertNDay'] = $data[5]; $res['animal'] = $data[6]; return $res; } /** * 获取卦象 */ public function getDisplay() { $data = $this->convertSolarToLunar(); $res['originYear'] = $this->year; $res['originMonth'] = $this->month; $res['originDay'] = $this->day; $res['hour'] = $this->hour; $res['convertYear'] = $data['convertCYear']; $res['convertMonth'] = $data['convertNMonth']; $res['convertDay'] = $data['convertNDay']; $res['yearText'] = $data['yearText']; $res['monthText'] = $data['monthText']; $res['dayText'] = $data['dayText']; $res['animal'] = $data['animal']; $res['type'] = 'destiny'; return $this->disposalArray($this->getRow($this->hexagrams->getDisplay($res))); } /** * 获取卦象结果 * @param array $data 卦象数组 * @return array */ private function getRow($data) { $keyWorld = '婚姻'; /** 判断有没有变卦 **/ if ( array_key_exists('convert',$data) && !empty($data['convert']) ) { $tmp = $this->common->arr_blurry_query([$data['convert'], $keyWorld], $this->guaData); if (!$tmp) $tmp = $this->common->arr_blurry_query($data['convert'], $this->guaData); $res['name'] = $data['convert']; $res['content'] = $tmp['content']; } else { $tmp = $this->common->arr_blurry_query([$data['origin'], $keyWorld], $this->guaData); if (!$tmp) $tmp = $this->common->arr_blurry_query($data['origin'], $this->guaData); $res['name'] = $data['origin']; } $sfHexagrams = ''; $res['content'] = $tmp['content']; return $res; } /** * 数组处理 * @param array $arr * @return array */ private function disposalArray($arr) { var_dump($arr);exit; $arr['content'] = preg_replace('/&#13;/','',$arr['content']); $arr['content'] = preg_replace('#<div([\s\S])(.*)<\/div>#is', '',$arr['content']); $arr['content'] = preg_replace("#\s| #","",$arr['content']); $arr['content'] = strip_tags($arr['content']); $content = preg_split( "#【(.*?)】+#",$arr['content'] ); preg_match_all( "#【(.*?)】+#",$arr['content'],$title ); unset($content[0]); $tmp = array_combine($title[0],$content); foreach ($tmp as $title => $content) { $data[] = array( 'title' => $title, 'content' => $content, ); } return array( 'name' => $arr['name'], 'dataList' => $data, ); } } echo '<pre>'; $optArr = getopt('d:h:'); /** 阳历日期 **/ // $date = '1992-01-15'; $date = $optArr['d'] ?? '1992-01-15'; /** 时辰 **/ // $hour = '子时'; // 子时 丑时 寅时 卯时 辰时 巳时 午时 未时 申时 酉时 戌时 亥时 $hour = $optArr['h'] ?? '子时'; /** 实例化 **/ $example = new example($date, $hour, new Common()); // 不传时辰默认子时 /** 获取卦象结果 **/ $gua = $example->getDisplay(); /** 打印结果 **/ var_dump($gua); exit; <file_sep><?php namespace LunarPHP; /** * 系统主配置文件. * @Author: ljy * @Date: 17-08-18 */ /** * 数据库配置 */ $db_conf = array( 'dbms' => 'mysql', // 数据库类型 'serverName' => '127.0.0.1', // 地址 'dbName' => 'demo', // 数据库 'user' => 'root', // 账号 'pass' => '<PASSWORD>', // 密码 ); define('DB_CONFIG',json_encode($db_conf)); /** * 日志配置 */ $log_conf = array( 'log_file' => 'logs', 'separator' => '^_^', ); define('LOG_CONF',json_encode($log_conf)); // 当前路径 define('SITE_PATH', dirname(dirname(__FILE__)) . "/"); /** * json数据 */ $gua_json = file_get_contents(SITE_PATH.'/database/gua.json'); $constellation_json = file_get_contents(SITE_PATH.'/database/constellation.json'); define('GUA_DATA', $gua_json); define('CONSTELLATION_DATA', $constellation_json); //版本号 define('LUNARPHP_VERSION', '1.6'); define('LUNARPHP_VERSION_DATE', '2018-05-16');<file_sep><?php namespace LunarPHP\Core; /** *author:dequan *date:2016-06-20 *原文地址:http://blog.csdn.net/hsd2012/article/details/51701640 */ class Calendar { private $animals; private $curData = null;//当前阳历时间 private $ylYeal = 0; private $ylMonth = 0; private $yldate = 0; private $ylDays = 0; //当前日期是农历年的第多少天 private $leap = 0;//代表润哪一个月 private $leapDays = 0;//代表闰月的天数 private $difmonth = 0;//当前时间距离参考时间相差多少月 private $difDay = 0;//当前时间距离参考时间相差多少天 private $tianGan; private $diZhi; private $yearGan; private $monthGan; private $dataInfo; public function __construct($curData=null) { $this->animals = json_decode(ANIMALS,true); $this->tianGan = json_decode(TIANGAN,true); $this->diZhi = json_decode(DIZHI,true); $this->yearGan = json_decode(YEARGAN,true); $this->monthGan = json_decode(MONTHGAN,true); $this->dataInfo = json_decode(DATAINFO,true); if ( !empty($curData) ) { $this->curData = $curData; } else { $this->curData = date('Y-n-j'); } $this->init(); } public function init() { $basedate = '1900-1-31';//参照日期 $timezone = 'PRC'; $datetime = new \DateTime($basedate, new \DateTimeZone($timezone)); $curTime = new \DateTime($this->curData, new \DateTimeZone($timezone)); $offset = ($curTime->format('U') - $datetime->format('U'))/86400; //相差的天数 $offset = ceil($offset); $this->difDay = $offset; $offset += 1;//只能使用ceil,不能使用intval或者是floor,因为1900-1-31为正月初一,故需要加1 for ($i=1900; $i<2050 && $offset>0; $i++) { $temp = $this->getYearDays($i); //计算i年有多少天 $offset -= $temp ; $this->difmonth+=12; //判断该年否存在闰月 if ($this->leapMonth($i)>0) { $this->difmonth+=1; } } if ($offset<0) { $offset += $temp; $i--; $this->difmonth-=12; } if ($this->leapMonth($i)>0) { $this->difmonth-=1; } $this->ylDays = $offset; //此时$offset代表是农历该年的第多少天 $this->ylYeal = $i;//农历哪一年 //计算月份,依次减去1~12月份的天数,直到offset小于下个月的天数 $curMonthDays = $this->monthDays($this->ylYeal,1); //判断是否该年是否存在闰月以及闰月的天数 $this->leap = $this->leapMonth($this->ylYeal); if ($this->leap !=0) { $this->leapDays = $this->leapDays($this->ylYeal); } for ($i=1; $i<13 && $curMonthDays < $offset; $curMonthDays = $this->monthDays($this->ylYeal,++$i)) { if ($this->leap == $i) { //闰月 if ($offset>$this->leapDays) { --$i; $offset -= $this->leapDays; $this->difmonth+=1; } else { break; } } else { $offset -= $curMonthDays; $this->difmonth += 1; } } $this->ylMonth = $i; $this->yldate = $offset; } /** *计算农历y年有多少天 **/ public function getYearDays($y) { $sum = 348;//12*29=348,不考虑小月的情况下 for ($i=0x8000; $i>=0x10; $i>>=1) { $sum += ($this->dataInfo[$y-1900] & $i)? 1: 0; } return ( $sum + $this->leapDays($y) ); } /** * 获取某一年闰月的天数 */ public function leapDays($y) { if ( $this->leapMonth($y) ) { return ( ($this->dataInfo[$y-1900] & 0x10000) ? 30 : 29 ); } else { return(0); } } /** * 计算哪一月为闰月 */ public function leapMonth($y) { return ($this->dataInfo[$y-1900] & 0xf); } /** * 计算农历y年m月有多少天 */ public function monthDays($y,$m) { return (($this->dataInfo[$y-1900] & (0x10000>>$m))? 30: 29 ); } /** * getLyTime */ public function getLyTime() { $tmp = array('初','一','二','三','四','五','六','七','八','九','十','廿'); $dateStr=''; if ($this->ylMonth > 10) { $m2 = intval($this->ylMonth -10); //十位 $dateStr = '十'.$tmp[$m2].'月'; } elseif ($this->ylMonth == 1) { $dateStr = '正月'; } else { $dateStr = $tmp[$this->ylMonth].'月'; } if ($this->yldate <11) { $dateStr .= '初'.$tmp[$this->yldate]; } else { $m1 = intval($this->yldate / 10); if ( $m1 !=3) { $dateStr .= ($m1==1) ? '十' : '廿'; $m2 = $this->yldate % 10; if ($m2==0) { $dateStr.='十'; } else { $dateStr.=$tmp[$m2]; } } else { $dateStr.='三十'; } } return $dateStr; } /** * 获取该年对于的天干地支年 */ public function getYGanZhi() { $gan = $this->tianGan[($this->ylYeal-4) % 10]; $zhi = $this->diZhi[($this->ylYeal-4) % 12]; return $gan.$zhi; } /** * 获取该年对于的天干地支月 * */ public function getMGanZhi($yGan,$convertMonth) { /*$gan=$this->tianGan[($this->difmonth+4) % 10]; $zhi=$this->diZhi[($this->difmonth+10) % 12]; return $gan.$zhi;*/ $GanNum = ''; foreach ($this->yearGan as $k => $Gan) { if ( in_array($yGan,$Gan) ) { $GanNum = $k; } } return $this->monthGan[$GanNum][$convertMonth]; } /** * 获取该年对于的天干地支日 */ public function getDGanZhi() { $gan = $this->tianGan[$this->difDay % 10]; $zhi = $this->diZhi[($this->difDay+4) % 12]; return $gan.$zhi; } }<file_sep><?php namespace LunarPHP\Core; /** * 数据库模型 * User: ljy * Date: 17-08-17 */ class Model { private $db; private $_table = ''; private $log; public function __construct($table) { $this->_table = $table; $db_config = json_decode(DB_CONFIG,true); $this->log = new Logger(); $dsn = $db_config['dbms'].":host=".$db_config['serverName'].";dbname=".$db_config['dbName']; try { $this->db = new \PDO($dsn, $db_config['user'], $db_config['pass'], array(\PDO::ATTR_PERSISTENT => true)); } catch (\PDOException $e) { $this->log->log('数据库连接失败:'.$e->getMessage()); die ("Error!: " . $e->getMessage() . "<br/>"); } } /** * 查询 */ public function query($filed = array(),$where = '') { if (!empty($where) && !empty($filed)) { if (is_array($where)) { $where = $this->where($where); } $sql = sprintf("SELECT %s FROM `%s` WHERE %s", $this->fields($filed), $this->_table, $where); } else { $sql = sprintf("SELECT %s FROM `%s`", $this->fields($filed), $this->_table); } $stmt = $this->db->prepare($sql); $stmt->execute(); while ($row = $stmt->fetch(\PDO::FETCH_ASSOC)) { $data[] = $row; } if (!empty($data)) { return $data; } else { return false; } } /** * 处理字段 */ private function fields($data) { if ($data == '*') { return $data; } else { foreach ($data as $key => $value) { $fileds[] = '`'.$value.'`'; } $str = implode(',', $fileds); return $str; } } /** * 设置条件语句 */ private function where($where) { $str = ''; $i = 1; foreach ($where as $key => $value) { if( $i == 1) { $str .= '`'.$key.'` = '."'".$value."'"; } else { $str .= ' AND `'.$key.'` = '."'".$value."'"; } $i++; } return $str; } } <file_sep><?php namespace LunarPHP\Core; class Common { /** * 模糊查询 * * @param mixed $keywords 关键词 * @param array $data 数据 * * @return array */ public function arr_blurry_query($keywords, $data) { $arr = []; if (is_array($keywords)) { foreach ( $data as $key => $values ) { foreach ($keywords as $item) { if ( (strstr( $values['name'] , $item ) !== false) && (strstr( $values['name'] , $item ) !== false) ) $arr = $values; } } } else { foreach ( $data as $key => $values ) { if ( strstr( $values['name'] , $keywords ) !== false ) $arr = $values; } } return $arr; } }<file_sep><?php namespace LunarPHP\Core; /** * Lunar */ class Lunar { var $MIN_YEAR = 1891; var $MAX_YEAR = 2100; var $lunarInfo; /** * 析构 */ public function __construct() { $this->lunarInfo = json_decode(LUNARINFO,true); } /** * 将阳历转换为阴历 * @param year 公历-年 * @param month 公历-月 * @param date 公历-日 */ public function convertSolarToLunar($year,$month,$date) {//debugger; $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; if ( $year == $this->MIN_YEAR && $month <= 2 && $date<=9 ) { return array(1891,'正月','初一','辛卯',1,1,'兔'); } return $this->getLunarByBetween($year,$this->getDaysBetweenSolar($year,$month,$date,$yearData[1],$yearData[2])); } public function convertSolarMonthToLunar($year,$month,$date) { $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; if ( $year == $this->MIN_YEAR && $month <= 2 && $date<=9 ) { return array(1891,'正月','初一','辛卯',1,1,'兔'); } $month_days_ary = array(31,28,31,30,31,30,31,31,30,31,30,31); $dd = $month_days_ary[$month]; if ($this->isLeapYear($year) && $month == 2) $dd++; $lunar_ary=array(); for ($i=1;$i<$dd;$i++) { $array = $this->getLunarByBetween($year,$this->getDaysBetweenSolar($year,$month,$i,$yearData[1],$yearData[2])); $array[] = $year.'-'.$month.'-'.$i; $lunar_ary[$i] = $array; } return $lunar_ary; } /** * 将阴历转换为阳历 * @param year 阴历-年 * @param month 阴历-月,闰月处理:例如如果当年闰五月,那么第二个五月就传六月,相当于阴历有13个月,只是有的时候第13个月的天数为0 * @param date 阴历-日 */ public function convertLunarToSolar($year,$month,$date) { $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; $between = $this->getDaysBetweenLunar($year,$month,$date); $res = mktime(0,0,0,$yearData[1],$yearData[2],$year); $res = date('Y-m-d',$res + $between*24*60*60); $day = explode('-',$res); $year = $day[0]; $month = $day[1]; $day = $day[2]; return array($year,$month,$day); } /** * 判断是否是闰年 * @param year */ public function isLeapYear($year) { return ( ($year%4 == 0 && $year%100 != 0) || ($year%400 == 0) ); } /** * 获取干支纪年 * @param year */ public function getLunarYearName($year) { $sky = array('庚','辛','壬','癸','甲','乙','丙','丁','戊','己'); $earth = array('申','酉','戌','亥','子','丑','寅','卯','辰','巳','午','未'); $year = $year.''; return $sky[$year{3}].$earth[$year%12]; } /** * 根据阴历年获取生肖 * @param year 阴历年 */ public function getYearZodiac($year) { $zodiac = array('猴','鸡','狗','猪','鼠','牛','虎','兔','龙','蛇','马','羊'); return $zodiac[$year%12]; } /** * 获取阳历月份的天数 * @param year 阳历-年 * @param month 阳历-月 */ public function getSolarMonthDays($year,$month) { $monthHash = array( '1' => 31, '2' => $this->isLeapYear($year) ? 29 : 28, '3' => 31, '4' => 30, '5' => 31, '6' => 30, '7' => 31, '8' => 31, '9' => 30, '10' => 31, '11' => 30, '12' => 31 ); return $monthHash["$month"]; } /** * 获取阴历月份的天数 * @param year 阴历-年 * @param month 阴历-月,从一月开始 */ public function getLunarMonthDays($year,$month) { $monthData = $this->getLunarMonths($year); return $monthData[$month-1]; } /** * 获取阴历每月的天数的数组 * @param year */ public function getLunarMonths($year) { $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; $leapMonth = $yearData[0]; $bit = decbin($yearData[3]); for ($i=0; $i<strlen($bit); $i ++) { $bitArray[$i] = substr($bit,$i,1); } for ($k=0, $klen = 16-count($bitArray); $k<$klen; $k++){ array_unshift($bitArray,'0'); } $bitArray = array_slice($bitArray,0,($leapMonth==0?12:13)); for ($i=0; $i<count($bitArray); $i++) { $bitArray[$i]=$bitArray[$i] + 29; } return $bitArray; } /** * 获取农历每年的天数 * @param year 农历年份 */ public function getLunarYearDays($year) { $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; $monthArray = $this->getLunarYearMonths($year); $len = count($monthArray); return ($monthArray[$len-1]==0?$monthArray[$len-2]:$monthArray[$len-1]); } /** * 获取农历每年的月份 * @param string $year 农历年份 */ public function getLunarYearMonths($year) {//debugger; $monthData = $this->getLunarMonths($year); $res = array(); $temp = 0; $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; $len = ($yearData[0]==0?12:13); for ($i=0;$i<$len;$i++) { $temp=0; for ($j=0;$j<=$i;$j++) { $temp+=$monthData[$j]; } array_push($res,$temp); } return $res; } /** * 获取闰月 * @param year 阴历年份 */ public function getLeapMonth($year) { $yearData = $this->lunarInfo[$year-$this->MIN_YEAR]; return $yearData[0]; } /** * 计算阴历日期与正月初一相隔的天数 * @param year * @param month * @param date */ public function getDaysBetweenLunar($year,$month,$date) { $yearMonth = $this->getLunarMonths($year); $res = 0; for ($i=1; $i<$month; $i++) { $res += $yearMonth[$i-1]; } $res += $date-1; return $res; } /** * 计算2个阳历日期之间的天数 * @param year 阳历年 * @param cmonth * @param cdate * @param dmonth 阴历正月对应的阳历月份 * @param ddate 阴历初一对应的阳历天数 */ public function getDaysBetweenSolar($year,$cmonth,$cdate,$dmonth,$ddate) { $a = mktime(0,0,0,$cmonth,$cdate,$year); $b = mktime(0,0,0,$dmonth,$ddate,$year); return ceil(($a-$b)/24/3600); } /** * 根据距离正月初一的天数计算阴历日期 * @param year 阳历年 * @param between 天数 */ public function getLunarByBetween($year,$between) {//debugger; $lunarArray = array(); $yearMonth = array(); $t = 0; $e = 0; $leapMonth = 0; $m = ''; if ($between == 0) { array_push($lunarArray,$year,'正月','初一'); $t = 1; $e = 1; } else { $year = $between>0? $year : ($year-1); $yearMonth = $this->getLunarYearMonths($year); $leapMonth = $this->getLeapMonth($year); $between = $between>0?$between : ($this->getLunarYearDays($year)+$between); for ($i=0; $i<13; $i++) { if ($between == $yearMonth[$i]) { $t = $i+2; $e = 1; break; } else if ($between < $yearMonth[$i]){ $t = $i+1; $e = $between-(empty($yearMonth[$i-1])?0:$yearMonth[$i-1])+1; break; } } $m = ($leapMonth!=0&&$t==$leapMonth+1)?('闰'.$this->getCapitalNum($t- 1,true)):$this->getCapitalNum(($leapMonth!=0&&$leapMonth+1<$t?($t-1):$t),true); array_push($lunarArray,$year,$m,$this->getCapitalNum($e,false)); } array_push($lunarArray,$this->getLunarYearName($year));// 天干地支 array_push($lunarArray,$t,$e); array_push($lunarArray,$this->getYearZodiac($year));// 12生肖 array_push($lunarArray,$leapMonth);// 闰几月 return $lunarArray; } /** * 获取数字的阴历叫法 * @param num 数字 * @param isMonth 是否是月份的数字 */ public function getCapitalNum($num,$isMonth) { $isMonth = $isMonth||false; $dateHash = array('0'=>'','1'=>'一','2'=>'二','3'=>'三','4'=>'四','5'=>'五','6'=>'六','7'=>'七','8'=>'八','9'=>'九','10'=>'十 '); $monthHash = array('0'=>'','1'=>'正月','2'=>'二月','3'=>'三月','4'=>'四月','5'=>'五月','6'=>'六月','7'=>'七月','8'=>'八月','9'=>'九月','10'=>'十月','11'=>'冬月','12'=>'腊月'); $res = ''; if ($isMonth) { $res = $monthHash[$num]; } else { if ($num <= 10) { $res = '初'.$dateHash[$num]; } else if ($num>10&&$num<20){ $res = '十'.$dateHash[$num-10]; } else if ($num==20){ $res = "二十"; } else if ($num>20&&$num<30){ $res = "廿".$dateHash[$num-20]; } else if ($num==30){ $res = "三十"; } } return $res; } }<file_sep>lunarPHP =============== [![Latest Stable Version](https://poser.pugx.org/jyil/lunar-php/v/stable)](https://packagist.org/packages/jyil/lunar-php) [![Total Downloads](https://poser.pugx.org/jyil/lunar-php/downloads)](https://packagist.org/packages/jyil/lunar-php) [![License](https://poser.pugx.org/jyil/lunar-php/license)](https://packagist.org/packages/jyil/lunar-php) ## About lunarPHP 根据以下开源项目修改整合封装的一个php易经六十四卦排盘类库,只需要引入路口文件就可以简单的调用方法求出卦象结果 - [64divine](https://github.com/tc31/64divine). > 运行环境要求PHP7以上。 ## 目录结构 初始的目录结构如下: ~~~ ├─core 类库核心文件 │ ├─Calendar.lrp.php │ ├─GanZhi.php │ ├─Hexagrams.lrp.php │ ├─Logger.lrp.php │ ├─Lunar.lrp.php │ └─Model.lrp.php │ └─Common.lrp.php │ ├─config 系统配置文件 │ └─config.php │ ├─database 数据文件 │ └─gua.json │ ├─language 语言包 │ └─language.php │ ├─logs 日志信息 │ └─xxx.log │ ├─autoloader.php 自动加载文件 ├─example.php 示例文件 ├─composer.json composer 定义文件 ├─lunarPHP.php 入口文件 ├─README.md README 文件 ~~~ ## EXAMPLE ~~~ php example.php -d yyyy-mm-dd -h 时辰 ~~~ ## QUICK START ~~~ require_once 'LunarPHP.php'; ~~~ ## License lunarPHP is open-sourced software licensed under the [WTFPL license](http://www.wtfpl.net/about/).<file_sep><?php namespace LunarPHP\Core; /** * Hexagrams */ class Hexagrams { public $error; private $lang; public function __construct() { $this->lang = json_decode(LANG,true); } /** * @param array $params * @return mixed */ public function getDisplay($params) { if ( !array_key_exists('originYear', $params) || !array_key_exists('originMonth', $params) || !array_key_exists('originDay', $params) || !array_key_exists('hour', $params) || !array_key_exists('type', $params) || !array_key_exists('convertYear', $params) || !array_key_exists('convertMonth', $params) || !array_key_exists('convertDay', $params) || !array_key_exists('yearText', $params) || !array_key_exists('monthText', $params) || !array_key_exists('dayText', $params) || !array_key_exists('animal', $params) ) { $this->error = '参数错误'; return false; } $event = $this->getEvent($params); $symbol = ( $params['type'] == 'destiny' ) ? $this->getDestiny($params, $event) : $this->getDivine($params, $event); return $symbol; } /** * getEvent */ private function getEvent($urlParam) { $result = array(); $emptyType = array(); $skyIndex = 1; $skyText = mb_substr($urlParam['dayText'], 0, 1); $groundIndex = 1; $groundText = mb_substr($urlParam['dayText'], 1); switch ( $skyText ) { case $this->lang['home_sky2']: $skyIndex = 2; break; case $this->lang['home_sky3']: $skyIndex = 3; break; case $this->lang['home_sky4']: $skyIndex = 4; break; case $this->lang['home_sky5']: $skyIndex = 5; break; case $this->lang['home_sky6']: $skyIndex = 6; break; case $this->lang['home_sky7']: $skyIndex = 7; break; case $this->lang['home_sky8']: $skyIndex = 8; break; case $this->lang['home_sky9']: $skyIndex = 9; break; case $this->lang['home_sky10']: $skyIndex = 10; break; case $this->lang['home_sky1']: default: $skyIndex = 1; break; } switch ($groundText) { case $this->lang['home_ground2']: $groundIndex = 2; break; case $this->lang['home_ground3']: $groundIndex = 3; break; case $this->lang['home_ground4']: $groundIndex = 4; break; case $this->lang['home_ground5']: $groundIndex = 5; break; case $this->lang['home_ground6']: $groundIndex = 6; break; case $this->lang['home_ground7']: $groundIndex = 7; break; case $this->lang['home_ground8']: $groundIndex = 8; break; case $this->lang['home_ground9']: $groundIndex = 9; break; case $this->lang['home_ground10']: $groundIndex = 10; break; case $this->lang['home_ground11']: $groundIndex = 11; break; case $this->lang['home_ground12']: $groundIndex = 12; break; case $this->lang['home_sky1']: default: $groundIndex = 1; break; } $groundResult = $groundIndex - $skyIndex; if ( $groundResult == 1 ) { $emptyType[1] = $this->lang["home_ground1"]; $emptyType[12] = $this->lang["home_ground12"]; } else if ( $groundResult <= 0 ) { $groundResult = 12 + $groundResult; $emptyType[$groundResult-1] = $this->lang["home_ground" . ($groundResult-1)]; $emptyType[$groundResult] = $this->lang["home_ground" . $groundResult]; } else { $emptyType[$groundResult-1] = $this->lang["home_ground" . ($groundResult-1)]; $emptyType[$groundResult] = $this->lang["home_ground" . $groundResult]; } $result['emptyType'] = $emptyType; $emptyType = join(', ', $emptyType); $brokenType = array(); $existType = array(mb_substr($urlParam['yearText'], 1), mb_substr($urlParam['monthText'], 1), mb_substr($urlParam['dayText'], 1), mb_substr($this->lang["home_hour{$urlParam['hour']}"], 0, 1)); if ( in_array($this->lang['home_ground1'], $existType) ) { $brokenType[7] = $this->lang['home_ground7']; } if ( in_array($this->lang['home_ground2'], $existType) ) { $brokenType[8] = $this->lang['home_ground8']; } if ( in_array($this->lang['home_ground3'], $existType) ) { $brokenType[9] = $this->lang['home_ground9']; } if ( in_array($this->lang['home_ground4'], $existType) ) { $brokenType[10] = $this->lang['home_ground10']; } if ( in_array($this->lang['home_ground5'], $existType) ) { $brokenType[11] = $this->lang['home_ground11']; } if ( in_array($this->lang['home_ground6'], $existType) ) { $brokenType[12] = $this->lang['home_ground12']; } if ( in_array($this->lang['home_ground7'], $existType) ) { $brokenType[1] = $this->lang['home_ground1']; } if ( in_array($this->lang['home_ground8'], $existType) ) { $brokenType[2] = $this->lang['home_ground2']; } if ( in_array($this->lang['home_ground9'], $existType) ) { $brokenType[3] = $this->lang['home_ground3']; } if ( in_array($this->lang['home_ground10'], $existType) ) { $brokenType[4] = $this->lang['home_ground4']; } if ( in_array($this->lang['home_ground11'], $existType) ) { $brokenType[5] = $this->lang['home_ground5']; } if ( in_array($this->lang['home_ground12'], $existType) ) { $brokenType[6] = $this->lang['home_ground6']; } $result['brokenType'] = $brokenType; $brokenType = join(', ', $brokenType); $result['html'] = "<div class='event'> <span>" . $this->lang['home_empty'] . ": {$emptyType}</span> <span>" . $this->lang['home_broken'] . ": {$brokenType}</span> </div>"; return $result; } /** * 時辰起卦 */ private function getDestiny($urlParam, $event) { $monthType = $urlParam['convertMonth'] % 8; $monthType = ( $monthType == 0 ) ? 8 : $monthType; $dayType = $urlParam['convertDay'] % 8; $dayType = ( $dayType == 0 ) ? 8 : $dayType; $hourType = $urlParam['hour'] % 6; $hourType = ( $hourType == 0 ) ? 6 : $hourType; $animal = $this->getAnimal(mb_substr($urlParam['dayText'], 0, 1)); $originUpSymbol = $this->getSymbol($dayType); $originDownSymbol = $this->getSymbol($monthType); $originFamily = $this->getFamily($dayType, $monthType, $event['emptyType'], $event['brokenType']); $soul = $this->getSoul($hourType); $convertSymbol = $this->getConvertSymbol($dayType, $monthType, $hourType, $event); $convertInfo = ( !$convertSymbol ) ? '' : $convertSymbol['symbolName']; $result['origin'] = $originFamily['symbolName']; $result['convert'] = $convertInfo; return $result; } /** * 獲取生肖 */ private function getAnimal($dayText) { $currIndex = 1; switch ( $dayText ) { case $this->lang['home_sky3']: case $this->lang['home_sky4']: $currIndex = 2; break; case $this->lang['home_sky5']: $currIndex = 3; break; case $this->lang['home_sky6']: $currIndex = 4; break; case $this->lang['home_sky7']: case $this->lang['home_sky8']: $currIndex = 5; break; case $this->lang['home_sky9']: case $this->lang['home_sky10']: $currIndex = 6; break; case $this->lang['home_sky1']: case $this->lang['home_sky2']: default: $currIndex = 1; break; } $temp = array(); for ( $i=0; $i<6; $i++ ) { if ( $currIndex > 6 ) { $currIndex = 1; } $temp[] = "<div>" . $this->lang["home_animal{$currIndex}"] . "</div>"; $currIndex++; } krsort($temp); $result = "<div class='animal'>" . join('', $temp) . "</div>"; return $result; } private function getSymbol($type) { $temp = ''; switch ( $type ) { case 1: $temp = "<div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div>"; break; case 2: $temp = "<div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div>"; break; case 3: $temp = "<div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div>"; break; case 4: $temp = "<div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div>"; break; case 5: $temp = "<div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div>"; break; case 6: $temp = "<div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div>"; break; case 7: $temp = "<div>&ndash;&mdash;&mdash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div>"; break; case 8: default: $temp = "<div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div> <div>&ndash;&ndash; &nbsp; &nbsp;&ndash;&ndash;</div>"; break; } $result = "<div class='symbol'>{$temp}</div>"; return $result; } private function getFamily($upSymbolType, $downSymbolType, $emptyType, $brokenType) { $result = array(); $emptys = array(); foreach ( $emptyType as $k=>$et ) { $emptys[$k] = "&curren;"; } $brokens = array(); foreach ( $brokenType as $k=>$bt ) { $brokens[$k] = "&#9888;"; } if ( $upSymbolType == 1 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol1']; } else if ( $upSymbolType == 1 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol2']; } else if ( $upSymbolType == 5 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol3']; } else if ( $upSymbolType == 3 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol4']; } else if ( $upSymbolType == 1 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol5']; } else if ( $upSymbolType == 1 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol6']; } else if ( $upSymbolType == 7 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol7']; } else if ( $upSymbolType == 3 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol8']; } else if ( $upSymbolType == 2 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol9']; } else if ( $upSymbolType == 2 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol10']; } else if ( $upSymbolType == 6 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol11']; } else if ( $upSymbolType == 4 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol12']; } else if ( $upSymbolType == 2 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol13']; } else if ( $upSymbolType == 2 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol14']; } else if ( $upSymbolType == 8 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol15']; } else if ( $upSymbolType == 4 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property1']; $result['symbolName'] = $this->lang['home_symbol16']; } else if ( $upSymbolType == 3 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol17']; } else if ( $upSymbolType == 3 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol18']; } else if ( $upSymbolType == 7 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol19']; } else if ( $upSymbolType == 1 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol20']; } else if ( $upSymbolType == 3 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol21']; } else if ( $upSymbolType == 3 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol22']; } else if ( $upSymbolType == 5 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol23']; } else if ( $upSymbolType == 1 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property4']; $result['symbolName'] = $this->lang['home_symbol24']; } else if ( $upSymbolType == 4 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol25']; } else if ( $upSymbolType == 4 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol26']; } else if ( $upSymbolType == 8 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol27']; } else if ( $upSymbolType == 2 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol28']; } else if ( $upSymbolType == 4 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol29']; } else if ( $upSymbolType == 4 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol30']; } else if ( $upSymbolType == 6 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol31']; } else if ( $upSymbolType == 2 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol32']; } else if ( $upSymbolType == 5 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol33']; } else if ( $upSymbolType == 5 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol34']; } else if ( $upSymbolType == 5 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol35']; } else if ( $upSymbolType == 1 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol36']; } else if ( $upSymbolType == 5 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol37']; } else if ( $upSymbolType == 7 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol38']; } else if ( $upSymbolType == 7 && $downSymbolType == 5 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol39']; } else if ( $upSymbolType == 3 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property2']; $result['symbolName'] = $this->lang['home_symbol40']; } else if ( $upSymbolType == 6 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol41']; } else if ( $upSymbolType == 6 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol42']; } else if ( $upSymbolType == 6 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol43']; } else if ( $upSymbolType == 6 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol44']; } else if ( $upSymbolType == 2 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol45']; } else if ( $upSymbolType == 4 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol46']; } else if ( $upSymbolType == 8 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol47']; } else if ( $upSymbolType == 8 && $downSymbolType == 6 ) { $result['symbolProperty'] = $this->lang['home_property3']; $result['symbolName'] = $this->lang['home_symbol48']; } else if ( $upSymbolType == 7 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol49']; } else if ( $upSymbolType == 7 && $downSymbolType == 3 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol50']; } else if ( $upSymbolType == 7 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol51']; } else if ( $upSymbolType == 7 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol52']; } else if ( $upSymbolType == 3 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol53']; } else if ( $upSymbolType == 1 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol54']; } else if ( $upSymbolType == 5 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol55']; } else if ( $upSymbolType == 5 && $downSymbolType == 7 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol56']; } else if ( $upSymbolType == 8 && $downSymbolType == 8 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol57']; } else if ( $upSymbolType == 8 && $downSymbolType == 4 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol58']; } else if ( $upSymbolType == 8 && $downSymbolType == 2 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol59']; } else if ( $upSymbolType == 8 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol60']; } else if ( $upSymbolType == 4 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol61']; } else if ( $upSymbolType == 2 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol62']; } else if ( $upSymbolType == 6 && $downSymbolType == 1 ) { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol63']; } else { $result['symbolProperty'] = $this->lang['home_property5']; $result['symbolName'] = $this->lang['home_symbol64']; } // ( $upSymbolType == 6 && $downSymbolType == 8 ) return $result; } /** * getSoul */ private function getSoul($hour) { $hour = ( $hour != 0 ) ? $hour : 6; return "<div class='soul soul{$hour}'>O</div>"; } /** * getConvertSymbol */ private function getConvertSymbol($dayType, $monthType, $hourType, $event) { if ( !$hourType ) { return array(); } $hourType = ( is_array($hourType) ) ? $hourType : array($hourType); $result = array(); $dayHour = array(); if ( in_array(4, $hourType) ) { $dayHour[] = 1; } if ( in_array(5, $hourType) ) { $dayHour[] = 2; } if ( in_array(6, $hourType) ) { $dayHour[] = 3; } $dayType = $this->convertType($dayType, $dayHour); $upSymbol = $this->getSymbol($dayType); $monthHour = array(); if ( in_array(1, $hourType) ) { $monthHour[] = 1; } if ( in_array(2, $hourType) ) { $monthHour[] = 2; } if ( in_array(3, $hourType) ) { $monthHour[] = 3; } $monthType = $this->convertType($monthType, $monthHour); $downSymbol = $this->getSymbol($monthType); $result['symbol'] = $upSymbol . $downSymbol; $family = $this->getFamily($dayType, $monthType, $event['emptyType'], $event['brokenType']); $result['symbolName'] = $family['symbolName']; $result['symbolProperty'] = $family['symbolProperty']; return $result; } /** * convertType */ private function convertType($type, $hour) { if ( !$hour ) { return $type; } $resultType = $type; switch ( $type ) { case 1: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 8; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 7; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 6; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 4; } else if ( in_array(1, $hour) ) { $resultType = 5; } else if ( in_array(2, $hour) ) { $resultType = 3; } else if ( in_array(3, $hour) ) { $resultType = 2; } else { return false; } break; case 2: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 7; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 8; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 5; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 3; } else if ( in_array(1, $hour) ) { $resultType = 6; } else if ( in_array(2, $hour) ) { $resultType = 4; } else if ( in_array(3, $hour) ) { $resultType = 1; } else { return false; } break; case 3: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 6; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 5; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 8; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 2; } else if ( in_array(1, $hour) ) { $resultType = 7; } else if ( in_array(2, $hour) ) { $resultType = 1; } else if ( in_array(3, $hour) ) { $resultType = 4; } else { return false; } break; case 4: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 5; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 6; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 7; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 1; } else if ( in_array(1, $hour) ) { $resultType = 8; } else if ( in_array(2, $hour) ) { $resultType = 2; } else if ( in_array(3, $hour) ) { $resultType = 3; } else { return false; } break; case 5: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 4; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 3; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 2; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 8; } else if ( in_array(1, $hour) ) { $resultType = 1; } else if ( in_array(2, $hour) ) { $resultType = 7; } else if ( in_array(3, $hour) ) { $resultType = 6; } else { return false; } break; case 6: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 3; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 4; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 1; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 7; } else if ( in_array(1, $hour) ) { $resultType = 2; } else if ( in_array(2, $hour) ) { $resultType = 8; } else if ( in_array(3, $hour) ) { $resultType = 5; } else { return false; } break; case 7: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 2; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 1; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 4; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 6; } else if ( in_array(1, $hour) ) { $resultType = 3; } else if ( in_array(2, $hour) ) { $resultType = 5; } else if ( in_array(3, $hour) ) { $resultType = 8; } else { return false; } break; case 8: default: if ( in_array(1, $hour) && in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 1; } else if ( in_array(1, $hour) && in_array(2, $hour) ) { $resultType = 2; } else if ( in_array(1, $hour) && in_array(3, $hour) ) { $resultType = 3; } else if ( in_array(2, $hour) && in_array(3, $hour) ) { $resultType = 5; } else if ( in_array(1, $hour) ) { $resultType = 4; } else if ( in_array(2, $hour) ) { $resultType = 6; } else if ( in_array(3, $hour) ) { $resultType = 7; } else { return false; } break; } return $resultType; } }
2893c572edb7c020e6617ab883d73a3fba03161f
[ "Markdown", "PHP" ]
11
PHP
zunyinet/lunarPHP
32f1ba295cdd2eb1d5d7f7ba0a68e5c0b2805d29
d0da707d1dcd988246eb9c4e0f2961a2739c72d1
refs/heads/master
<repo_name>IcQsang/test<file_sep>/report_me.php <?php include("conend/mysqlconend.php"); $sql = "SELECT * FROM poly"; $result = mysqli_query($conn, $sql); if (mysqli_num_rows($result) > 0) { // output data of each row while($row = mysqli_fetch_assoc($result)) { echo "userid: " . $row["userid"]. " - Name: " . $row["firstname"]. " " . $row["lastname"]. " " . $row["id"]." " . $row["email"]." " . $row["size"]." " . $row["age"]." " . $row["gender"]. "<br>"; } } else { echo "0 results"; } ?>
7b893f288772fdf55a4ea00cf90d89de8be545f7
[ "PHP" ]
1
PHP
IcQsang/test
728cd01e6de98a4eff66298faa908a4c27eec357
ff5f6d0dc25a7ef799eee7402dc493e462e75ff7
refs/heads/master
<file_sep>// // ModuleB.swift // ModuleB // // Created by <NAME> on 11.06.15. // Copyright (c) 2015 <NAME>. All rights reserved. // import Foundation import Alamofire import SwiftyJSON private let message = "Hello, here's module B!" public func computeMessageB(completion: (String) -> Void) { Alamofire.request(.GET, "http://httpbin.org/get", parameters: ["message": message]) .responseJSON { (request, response, data, error) in if let result: AnyObject = data { let json = JSON(result) if let msg = json["args"]["message"].string { completion("from response: " + msg) } else { completion("no message") } } else { completion("no result") } } } <file_sep>// // ModuleA.swift // ModuleA // // Created by <NAME> on 11.06.15. // Copyright (c) 2015 <NAME>. All rights reserved. // import Foundation import ModuleB // private let message = "Hello, here's Module A!" public func computeMessageA(completion: (String) -> Void) { ModuleB.computeMessageB(completion) }<file_sep>// // ViewController.swift // TestApp // // Created by <NAME> on 10.06.15. // Copyright (c) 2015 <NAME>. All rights reserved. // import UIKit import ModuleA class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() ModuleA.computeMessageA(){msg in self.message.text = msg} } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBOutlet weak var message: UILabel! }
7737013ac23e69467b38360731aae0a980f0070d
[ "Swift" ]
3
Swift
ulid000/frmwrks
59ba293049845470c3e6a73adb7221b1ec96c318
b9bdedb347ab6fc61c83257d32d410ba1b5d44b1
refs/heads/master
<repo_name>saltefishcong/springTest<file_sep>/src/com/springTest/junit/Test.java package com.springTest.junit; import org.aopalliance.intercept.MethodInterceptor; import org.junit.BeforeClass; import org.junit.Ignore; import org.junit.runner.RunWith; import org.springframework.aop.AfterAdvice; import org.springframework.aop.BeforeAdvice; import org.springframework.aop.ThrowsAdvice; import org.springframework.aop.framework.ProxyFactory; import org.springframework.aop.support.DelegatingIntroductionInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.DependsOn; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.stereotype.Component; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.springTest.Aop.teacherAfter; import com.springTest.Aop.teacherAround; import com.springTest.Aop.teacherBofore; import com.springTest.Aop.teacherIntroduction; import com.springTest.Aop.teacherThrows; import com.springTest.eity.User; import com.springTest.eity.student; import com.springTest.eity.teacher; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:com/springTest/junit/Test-context.xml"}) public class Test extends AbstractJUnit4SpringContextTests{ @Autowired private User user; private static ApplicationContext ctx; @BeforeClass public static void Init(){ ctx=new ClassPathXmlApplicationContext("classpath*:spring.xml"); } @Ignore @org.junit.Test public void test(){ System.out.println(user.getName()+" "+user.getPassword()); } @Ignore @org.junit.Test public void aop(){ teacher th=new teacher(); BeforeAdvice bofore=new teacherBofore(); AfterAdvice after=new teacherAfter(); MethodInterceptor around=new teacherAround(); ProxyFactory pf=new ProxyFactory(); pf.setTarget(th); pf.addAdvice(bofore); pf.addAdvice(after); pf.addAdvice(around); teacher th2=(teacher)pf.getProxy(); th2.say("黄老师好!"); } @Ignore @org.junit.Test public void aop2(){ teacher th=(teacher)ctx.getBean("th"); th.say("黄老师好!"); } @Ignore @org.junit.Test public void thros(){ teacher th=(teacher)ctx.getBean("thros"); th.thros("小明"); } @Ignore @org.junit.Test public void thros2(){ teacher th=new teacher(); ProxyFactory pf=new ProxyFactory(); ThrowsAdvice thors=new teacherThrows(); pf.setTarget(th); pf.addAdvice(thors); teacher th2=(teacher)pf.getProxy(); th2.thros("小红"); } @Ignore @org.junit.Test public void inter(){ teacher th=(teacher)ctx.getBean("intro"); th.say("157"); } @org.junit.Test public void inter2(){ teacher th=new teacher(); ProxyFactory pf=new ProxyFactory(); DelegatingIntroductionInterceptor intor=new teacherIntroduction(); BeforeAdvice bofore=new teacherBofore(); pf.setInterfaces(student.class); pf.setOptimize(true); pf.setTarget(th); pf.addAdvice(intor); pf.addAdvice(bofore); teacher th2=(teacher)pf.getProxy(); th2.say("157"); } } <file_sep>/src/com/springTest/Aop/teacherThrows.java package com.springTest.Aop; import java.lang.reflect.Method; import org.springframework.aop.ThrowsAdvice; public class teacherThrows implements ThrowsAdvice { public void afterThrowing(Method method, Object[] args, Object target, Exception ex){ System.out.println(ex.getMessage()); } } <file_sep>/src/com/springTest/Aop/teacherAround.java package com.springTest.Aop; import org.aopalliance.intercept.MethodInterceptor; import org.aopalliance.intercept.MethodInvocation; public class teacherAround implements MethodInterceptor{ @Override public Object invoke(MethodInvocation arg0) throws Throwable { // TODO Auto-generated method stub Object[] args=arg0.getArguments(); System.out.println("how are you !" +args[0]); Object object=arg0.proceed(); System.out.println("об©нак."); return object; } }
8b61d1d0448165d4b00b2d71a635be833b6530e2
[ "Java" ]
3
Java
saltefishcong/springTest
07c92b560269205f438a7eb99179d7b4717c9832
7f15292d7028e919f9e0f6d32b54fa714bf68bef
refs/heads/master
<repo_name>mendaxfz/masters-thesis<file_sep>/mastersRun_chunking10e4_white_i.py # Master's Thesis iPython Notebook scripts to run import numpy as np from pylab import * from scipy import * from matplotlib import * import datetime import pickle from mastersFunctions import * from emailing import * try: stim_type = 'white' version = 0 M = int(10e4) nBins = 250 adapt = np.linspace(0,25,100) if version == 0: adapt = adapt[0:30] elif version == 1: adapt = adapt[30:60] elif version == 2: adapt = adapt[60:100] steady_state_mem = [] steady_state_mem2 = [] steady_state_pred = [] steady_state_pred2 = [] steady_state_max = [] steady_state_max2 = [] sum_mem = [] sum_mem2 = [] sum_pred = [] sum_pred2 = [] sum_max = [] sum_max2 = [] i_mem_fnA = np.zeros((3,999)) i_mem_fnA2 = np.zeros((3,999)) i_pred_fnA = np.zeros((3,999)) i_pred_fnA2 = np.zeros((3,999)) i_max_fnA = np.zeros((3,999)) i_max_fnA2 = np.zeros((3,999)) for a in adapt: print str(a) # run simulation V,w,spikes,sptimes,T,stimulus = ensemble(a,int(M),stim_type,1000) V = np.asarray(V) stimulus = np.asarray(stimulus) # compute i_mem, i_pred, i_max i_mem = [] i_mem2 = [] i_pred = [] i_pred2 = [] i_max = [] i_max2 = [] # I used to flatten V, stimulus but this not only takes a long time # but gives unfair advantage to nonspiking Vs when the range is smaller # and discrimination is effectively much higher minV = -73.0 maxV = 20.0 minC = 0.0 maxC = 880.0 for i in xrange(shape(V)[1]-1): H, I = mutiN(V[:,i],stimulus[:,i],nBins,minV,maxV,minC,maxC) I2 = binaryWordsInformation(spikes[:,i],stimulus[:,i]) i_mem.append(I) i_mem2.append(I2) H, I = mutiN(V[:,i],stimulus[:,i+1],nBins,minV,maxV,minC,maxC) I2 = binaryWordsInformation(spikes[:,i],stimulus[:,i+1]) i_pred.append(I) i_pred2.append(I2) H, I = mutiN(stimulus[:,i],stimulus[:,i+1],nBins,minC,maxC,minC,maxC) I2 = binaryWordsInformation(stimulus[:,i],stimulus[:,i+1]) i_max.append(I) i_max2.append(I2) steady_state_mem.append(i_mem[-1]) steady_state_pred.append(i_pred[-1]) steady_state_max.append(i_max[-1]) steady_state_mem2.append(i_mem2[-1]) steady_state_pred2.append(i_pred2[-1]) steady_state_max2.append(i_max2[-1]) sum_mem.append(sum(i_mem)) sum_pred.append(sum(i_pred)) sum_max.append(sum(i_max)) sum_mem2.append(sum(i_mem2)) sum_pred2.append(sum(i_pred2)) sum_max2.append(sum(i_max2)) if a < 0.1: i_mem_fnA[0,:] = asarray(i_mem) i_pred_fnA[0,:] = asarray(i_pred) i_max_fnA[0,:] = asarray(i_max) i_mem_fnA2[0,:] = asarray(i_mem2) i_pred_fnA2[0,:] = asarray(i_pred2) i_max_fnA2[0,:] = asarray(i_max2) elif abs(a - 6) < 0.1: i_mem_fnA[1,:] = asarray(i_mem) i_pred_fnA[1,:] = asarray(i_pred) i_max_fnA[1,:] = asarray(i_max) i_mem_fnA2[1,:] = asarray(i_mem2) i_pred_fnA2[1,:] = asarray(i_pred2) i_max_fnA2[1,:] = asarray(i_max2) elif abs(a - 25) < 0.1: i_mem_fnA[2,:] = asarray(i_mem) i_pred_fnA[2,:] = asarray(i_pred) i_max_fnA[2,:] = asarray(i_max) i_mem_fnA2[2,:] = asarray(i_mem2) i_pred_fnA2[2,:] = asarray(i_pred2) i_max_fnA2[2,:] = asarray(i_max2) with open('masters_data_steadyState_' + str(stim_type) + '_a' + str(a) + '_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([steady_state_mem, steady_state_pred, steady_state_max], f, -1) with open('masters_data_sum_' + str(stim_type) + '_a' + str(a) + '_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([sum_mem, sum_pred, sum_max], f, -1) with open('masters_data_examples_' + str(stim_type) + '_a' + str(a) + '_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([i_mem_fnA, i_pred_fnA, i_max_fnA], f, -1) with open('masters_data_steadyState2_' + str(stim_type) + '_a' + str(a) + '_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([steady_state_mem2, steady_state_pred2, steady_state_max2], f, -1) with open('masters_data_sum2_' + str(stim_type) + '_a' + str(a) + '_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([sum_mem2, sum_pred2, sum_max2], f, -1) with open('masters_data_examples2_' + str(stim_type) + '_a' + str(a) + '_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([i_mem_fnA2, i_pred_fnA2, i_max_fnA2], f, -1) emailWhenDone() except: import traceback import smtplib sysexecinfo = sys.exc_info() emailWhenError(sysexecinfo) <file_sep>/README.md masters-thesis ============== Code for simulating an adaptive, exponential integrate-and-fire neuron and analyzing its predictive power and memory. Currently masterscript(10e5,2000) is running on corn07 with screenname lmcintosh. <file_sep>/mastersFunctions.py # Master's Thesis functions import numpy as np from pylab import * from scipy import * from matplotlib import * #import pyentropy # Adaptive exponential integrate-and-fire neuron def aEIF(adaptationIndex, inputCurrent, v0): """ Adaptive exponential integrate-and-fire neuron from Gerstner 2005 Parameters ---------- adaptationIndex : degree to which neuron adapts inputCurrent : np array of the stimulus with size (M,N) v0 : specify the membrane potential at time 0 Returns ------- V : membrane voltage for the simulation w : adaptation variable for the simulation spikes : 0 or 1 for each time bin sptimes : list of spike times """ # keep in mind that inputCurrent needs to start at 0 for sys to be in equilibrium # Physiologic neuron parameters from Gerstner et al. C = 281 # capacitance in pF ... this is 281*10^(-12) F g_L = 30 # leak conductance in nS E_L = -70.6 # leak reversal potential in mV ... this is -0.0706 V delta_T = 2 # slope factor in mV V_T = -50.4 # spike threshold in mV tau_w = 144 # adaptation time constant in ms V_peak = 20 # when to call action potential in mV b = 0.0805 # spike-triggered adaptation a = adaptationIndex noiseT = 0.3 # Simulation parameters delta = 0.5 # dt M = inputCurrent.shape[0] # number of neurons N = inputCurrent.shape[1] # number of simulation points is determined by size of inputCurrent T = np.linspace(0,N*delta,N) # time points corresponding to inputCurrent (same size as V, w, I) # Thermodynamic parameters kB = 1.3806503*10**(-23) # Boltzmann's constant beta = 1/(kB*310.65) # kB times T where T is in Kelvin # Initialize variables V = np.zeros((N,M)) w = np.zeros((N,M)) spikes = np.zeros((N,M)) sptimes = [[] for _ in xrange(M)] V[0] = v0 # this gives us a chance to say what the membrane voltage starts at # so we can draw initial conditions from the Boltzmann dist. later # Run model for i in xrange(N-1): V[i+1,:] = V[i,:] + (delta/C)*( -g_L*(V[i,:] - E_L) + g_L*delta_T*np.exp((V[i,:] - V_T)/delta_T) - w[i,:] + inputCurrent[:,i+1]) + np.sqrt(noiseT)*randn(1,M) w[i+1,:] = w[i,:] + (delta/tau_w)*(a*(V[i,:] - E_L) - w[i,:]) # spiking mechanism ind = where(V[i+1,:] >= V_peak) if size(ind[0]) > 0: V[i+1,ind] = E_L w[i+1,ind] = w[i,ind] + b spikes[i+1,ind] = 1 [sptimes[j].append(T[i+1]) for j in ind[0]] return [V.transpose(),w.transpose(),spikes.transpose(),sptimes] # Define raster plot def raster(event_times_list, color='k'): """ Creates a raster plot Parameters ---------- event_times_list : iterable a list of event time iterables color : string color of vlines Returns ------- ax : an axis containing the raster plot """ ax = gca() for ith, trial in enumerate(event_times_list): vlines(trial, ith + .5, ith + 1.5, color=color,linewidth=1.3) ylim(.5, len(event_times_list) + .5) return ax # Define input current types def stepFn(meanCurrent,variance,N, M): ''' stepFn(meanCurrent, variance, N,M) ''' x = meanCurrent*np.ones((N,M)) + np.sqrt(variance)*np.random.randn(N,M) x[0] = 0 return x.transpose() def whiteNoise(meanCurrent,variance,N,M): ''' whiteNoise(meanCurrent, variance, N,M) ''' x = meanCurrent + np.sqrt(variance)*np.random.randn(N,M) x[0] = 0 return x.transpose() def shotNoise(meanCurrent,variance,N,M,tau=3): ''' shotNoise(meanCurrent, variance, N,M) ''' dt = 0.5 #tau = 3 # ms F = 30 t = linspace(0,F*dt,F) x = meanCurrent + np.sqrt(variance)*np.random.randn(N+F-1,M) y = t*np.exp(-t/tau) z = np.zeros((N,M)) for i in xrange(M): z_i = np.convolve(x[:,i], y, mode = 'valid') z[:,i] = z_i z = z - np.mean(z) + meanCurrent z[0] = 0 return z.transpose() def ouProcess(meanCurrent,variance,N,M): ''' shotNoise(meanCurrent, variance, N,M) ''' dt = 0.5 tau = 3 # ms tau2 = N/20 F = 30 t = linspace(0,F*dt,F) t2 = linspace(0,N*dt,N) x = meanCurrent + np.sqrt(variance)*np.random.randn(N+F-1,M) y = np.exp(-t/tau) y2 = np.exp(-t2/tau2) z0 = 0 drift = (z0 - meanCurrent)*y2 z = np.zeros((N,M)) for i in xrange(M): z_i = np.convolve(x[:,i], y, mode = 'valid') z[:,i] = z_i - np.mean(z_i) + meanCurrent + drift return z.transpose() """ brownian() implements one dimensional Brownian motion (i.e. the Wiener process). """ #from math import sqrt from scipy.stats import norm #import numpy as np def brownian(x0, n, dt, delta, out=None): """\ Generate an instance of Brownian motion (i.e. the Wiener process): X(t) = X(0) + N(0, delta**2 * t; 0, t) where N(a,b; t0, t1) is a normally distributed random variable with mean a and variance b. The parameters t0 and t1 make explicit the statistical independence of N on different time intervals; that is, if [t0, t1) and [t2, t3) are disjoint intervals, then N(a, b; t0, t1) and N(a, b; t2, t3) are independent. Written as an iteration scheme, X(t + dt) = X(t) + N(0, delta**2 * dt; t, t+dt) If `x0` is an array (or array-like), each value in `x0` is treated as an initial condition, and the value returned is a numpy array with one more dimension than `x0`. Arguments --------- x0 : float or numpy array (or something that can be converted to a numpy array using numpy.asarray(x0)). The initial condition(s) (i.e. position(s)) of the Brownian motion. n : int The number of steps to take. dt : float The time step. delta : float delta determines the "speed" of the Brownian motion. The random variable of the position at time t, X(t), has a normal distribution whose mean is the position at time t=0 and whose variance is delta**2*t. out : numpy array or None If `out` is not None, it specifies the array in which to put the result. If `out` is None, a new numpy array is created and returned. Returns ------- A numpy array of floats with shape `x0.shape + (n,)`. Note that the initial value `x0` is not included in the returned array. """ x0 = np.asarray(x0) # For each element of x0, generate a sample of n numbers from a # normal distribution. r = norm.rvs(size=x0.shape + (n,), scale=delta*sqrt(dt)) # If `out` was not given, create an output array. if out is None: out = np.empty(r.shape) # This computes the Brownian motion by forming the cumulative sum of # the random samples. np.cumsum(r, axis=-1, out=out) # Add the initial condition. out += np.expand_dims(x0, axis=-1) return out def ensemble(adaptiveIndex, numNeurons, inputType, duration, tau=3): ''' Simulates an ensemble of neurons inputs: adaptiveIndex, numNeurons, and inputType possible inputType includes: 'step' 'white' 'ou' 'shotnoise' 'brownian' returns: V (neurons x time), w, spikes, stimulus ''' # constants N = duration a = adaptiveIndex M = numNeurons v0 = -70.6 # mV meanCurrent = 555.0 # pA ? variance = 100.0 delta = 0.5 x0 = 0.0 # initialize variables T = np.linspace(0,N*delta,N) # time points corresponding to inputCurrent (same size as V, w, I) if inputType == 'step': current = stepFn(meanCurrent,variance,N,M) elif inputType == 'white': current = whiteNoise(meanCurrent,variance,N,M) elif inputType == 'ou': current = ouProcess(meanCurrent,variance,N,M) elif inputType == 'shotnoise': current = shotNoise(meanCurrent,variance,N,M,tau) elif inputType == 'brownian': current = brownian(np.ones((M,)) * meanCurrent, N, delta, variance/25.0, out=None) current[:,0] = x0 V,w,spikes,sptimes = aEIF(a, current, v0) return V, w, spikes, sptimes, T, current def mutiN(voltage, current, nBins, minV, maxV, minC, maxC): '''Function to compute the mutual information between neuron voltage and the input current - with just two bins! Note that you need to use asarray(V) and asarray(current) to get time slices instead of per-neuron slices''' # could potentially ask for min, max, and then use linspace to specify bin edges binsA = linspace(minV, maxV, nBins+1) binsB = linspace(minC, maxC, nBins+1) # note that in this function's MATLAB counterpart, I explicitly made one bin spiking. # here I avoid doing that because I don't force a spike to have a particular voltage, # I just call it when it passes threshold on the next iteration # Counting CountsAB, xedges, yedges = histogram2d(squeeze(voltage),squeeze(current), bins=[binsA, binsB]) CountsA = sum(CountsAB,0) # this sums all the rows, leaving the marginal distribution of voltage CountsB = sum(CountsAB,1) # this sums all the cols, leaving the marginal distribution of current pA = CountsA.astype(float)/float(sum(CountsA)) pB = CountsB.astype(float)/float(sum(CountsB)) pAB = CountsAB.astype(float)/float(sum(CountsAB)) if abs(1 - sum(pA)) > 0.01: print 'Probabilities pA do not sum to one ' + str(sum(pA)) if abs(1 - sum(pB)) > 0.01: print 'Probabilities pB do not sum to one ' + str(sum(pB)) if abs(1 - sum(pAB)) > 0.01: print 'Probabilities pAB do not sum to one ' + str(sum(pAB)) # Entropies HA = 0.0 HB = 0.0 HAB = 0.0 for prob in pB: if prob != 0: HB = HB - prob*log2(prob) for j in xrange(len(pA)): if pA[j] != 0: HA = HA - pA[j] * log2(pA[j]) for i in xrange(len(pB)): if pAB[i,j] != 0: HAB = HAB - pAB[i,j] * log2(pAB[i,j]) H = [HA, HB, HAB] I = HA + HB - HAB return H, I def binaryWordsInformation(spikes,stimulus): '''Compute entropy of spike trains with binary words approach. Spikes and stimulus are both 1-d vertical numpy arrays with as many elements as neurons. ''' nBins = 2 H, I = mutiN(spikes,stimulus,nBins,0,1,0,880) return I <file_sep>/bash_master.sh #!/bin/bash # bash_master.sh: ssh'ing into corn servers and executing MA code echo "Please enter password for <EMAIL>" read PASSWORD LIST="$(ls ~/Git/masters-thesis/run_these)" for i in "$LIST"; do sshpass -p $PASSWORD ssh <EMAIL> "python ~/masters/python/"$i" &" & sleep 0.5 done # prepare corn for running a long program in a screen session #pagsh #kinit;aklog #$PASSWORD #screen -S masters #keeptoken #source /tmp/.krbhold_lanemc.csh #python mastersRun_chunking10e4_brownian_i.py # to detach screen execute keyboard shortcut #xdotool key "ctrl+a+d" <file_sep>/mastersRun.py # Master's Thesis iPython Notebook scripts to run import numpy as np from pylab import * from scipy import * from matplotlib import * import datetime import pickle from mastersFunctions import * from emailing import * try: M = int(60) nBins = 250 adapt = linspace(0,25,100) steady_state_mem = [] steady_state_pred = [] steady_state_max = [] sum_mem = [] sum_pred = [] sum_max = [] i_mem_fnA = np.zeros((3,999)) i_pred_fnA = np.zeros((3,999)) i_max_fnA = np.zeros((3,999)) for a in adapt: # run simulation V,w,spikes,sptimes,T,stimulus = ensemble(a,int(M),'brownian',1000) V = np.asarray(V) stimulus = np.asarray(stimulus) # compute i_mem, i_pred, i_max i_mem = [] i_pred = [] i_max = [] minV = min(flatten(V)) maxV = max(flatten(V)) minC = min(flatten(stimulus)) maxC = max(flatten(stimulus)) for i in xrange(shape(V)[1]-1): H, I = mutiN(V[:,i],stimulus[:,i],nBins,minV,maxV,minC,maxC) i_mem.append(I) H, I = mutiN(V[:,i],stimulus[:,i+1],nBins,minV,maxV,minC,maxC) i_pred.append(I) H, I = mutiN(stimulus[:,i],stimulus[:,i+1],nBins,minC,maxC,minC,maxC) i_max.append(I) steady_state_mem.append(i_mem[-1]) steady_state_pred.append(i_pred[-1]) steady_state_max.append(i_max[-1]) sum_mem.append(sum(i_mem)) sum_pred.append(sum(i_pred)) sum_max.append(sum(i_max)) if a < 0.1: i_mem_fnA[0,:] = asarray(i_mem) i_pred_fnA[0,:] = asarray(i_pred) i_max_fnA[0,:] = asarray(i_max) elif abs(a - 6) < 0.1: i_mem_fnA[1,:] = asarray(i_mem) i_pred_fnA[1,:] = asarray(i_pred) i_max_fnA[1,:] = asarray(i_max) elif abs(a - 25) < 0.1: i_mem_fnA[2,:] = asarray(i_mem) i_pred_fnA[2,:] = asarray(i_pred) i_max_fnA[2,:] = asarray(i_max) with open('masters_data_steadyState_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([steady_state_mem, steady_state_pred, steady_state_max], f, -1) with open('masters_data_sum_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([sum_mem, sum_pred, sum_max], f, -1) with open('masters_data_examples_' + str(datetime.date.today()) + '.pik', 'wb') as f: pickle.dump([i_mem_fnA, i_pred_fnA, i_max_fnA], f, -1) emailWhenDone() except: import traceback import smtplib sysexecinfo = sys.exc_info() emailWhenError(sysexecinfo) <file_sep>/makeHostFile.py #makeHostFile.py import numpy as np numCornServers = 30 cornServers = range(1,numCornServers+1) taus = np.linspace(0.01,40,numCornServers) versions = [1,2,3] hostFile = open('host_file.txt','a') for f in xrange(numCornServers): if cornServers[f] < 10: hostFile.write('lanemc@corn0' + str(cornServers[f]) + '.stanford.edu python ~/masters/python/mastersRun_chunking10e4_shotnoise.py ' + str(versions[0]) + ' ' + str(taus[f]) + ' ' + '</dev/null >nohup.out 2>&1 &' + '\n') else: hostFile.write('lanemc@corn' + str(cornServers[f]) + '.stanford.edu python ~/masters/python/mastersRun_chunking10e4_shotnoise.py ' + str(versions[0]) + ' ' + str(taus[f]) + ' ' + '</dev/null >nohup.out 2>&1 &' + '\n') hostFile.close()
817f834e1ca21d3aea90ed4927a6e2bf6c5f167a
[ "Markdown", "Python", "Shell" ]
6
Python
mendaxfz/masters-thesis
91e131dc103d26d3caef82909f407b87e578735c
8a88702e7fe3037421944839c760f7a67a8e5a61
refs/heads/master
<repo_name>shsun/AndroidServiceDemo<file_sep>/ServiceDemo/src/com/example/bind/PlayBindMusicActivity.java package com.example.bind; import android.app.Activity; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.R; public class PlayBindMusicActivity extends Activity implements OnClickListener { public static final String TAG = "PlayBindMusicActivity"; private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private BindMusicService musicService; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.bind_music_service); playBtn = (Button) findViewById(R.id.play); stopBtn = (Button) findViewById(R.id.stop); pauseBtn = (Button) findViewById(R.id.pause); exitBtn = (Button) findViewById(R.id.exit); playBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); pauseBtn.setOnClickListener(this); exitBtn.setOnClickListener(this); connection(); } private void connection() { Intent intent = new Intent("com.example.bind.bindService"); bindService(intent, serviceConnectionListener, Context.BIND_AUTO_CREATE); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.play: musicService.play(); break; case R.id.stop: if (musicService != null) { musicService.stop(); } break; case R.id.pause: if (musicService != null) { musicService.pause(); } break; case R.id.exit: this.finish(); break; } } /** * */ private ServiceConnection serviceConnectionListener = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { musicService = ((BindMusicService.MusicBinder) (service)).getService(); if (musicService != null) { musicService.play(); } } @Override public void onServiceDisconnected(ComponentName name) { // disconnect Service musicService = null; } }; @Override public void onDestroy() { Log.i(TAG, "onDestroy"); super.onDestroy(); if (serviceConnectionListener != null) { unbindService(serviceConnectionListener); } } }<file_sep>/ServiceDemo/src/com/example/receiver/MusicReceiver.java package com.example.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class MusicReceiver extends BroadcastReceiver { public static final String TAG = "MusicReceiver"; public MusicReceiver() { super(); } @Override public void onReceive(Context pContext, Intent pIntent) { Log.i(TAG, "onReceive"); if (pIntent != null) { Bundle bundle = pIntent.getExtras(); Intent itent = new Intent(pContext, MusicReceiverService.class); // call service for MusicReceiverService.class itent.putExtras(bundle); if (bundle != null) { int operationType = bundle.getInt("op"); if (operationType == 4) { pContext.stopService(itent); } else { pContext.startService(itent); } } } } } <file_sep>/ServiceDemo/src/com/example/service/PlayMusicServiceActivity.java package com.example.service; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import com.example.R; import com.example.Utils; public class PlayMusicServiceActivity extends Activity implements OnClickListener { public static final String TAG = "PlayMusicServiceActivity"; private Button playBtn; private Button stopBtn; private Button pauseBtn; private Button exitBtn; private Button closeBtn; private Intent intent; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.music_service); String p = Utils.getCurProcessName(this); Thread thread = Thread.currentThread(); playBtn = (Button) findViewById(R.id.play); stopBtn = (Button) findViewById(R.id.stop); pauseBtn = (Button) findViewById(R.id.pause); exitBtn = (Button) findViewById(R.id.exit); closeBtn = (Button) findViewById(R.id.close); playBtn.setOnClickListener(this); stopBtn.setOnClickListener(this); pauseBtn.setOnClickListener(this); exitBtn.setOnClickListener(this); closeBtn.setOnClickListener(this); } @Override public void onClick(View v) { int operation = -1; intent = new Intent("com.example.service.musicService"); switch (v.getId()) { case R.id.play: operation = 1; break; case R.id.stop: operation = 2; break; case R.id.pause: operation = 3; break; case R.id.close: this.finish(); break; case R.id.exit: operation = 4; stopService(intent); this.finish(); break; } Bundle bundle = new Bundle(); bundle.putInt("op", operation); intent.putExtras(bundle); startService(intent); } @Override public void onDestroy() { Log.i(TAG, "onDestroy"); super.onDestroy(); if (intent != null) { stopService(intent); } } }<file_sep>/README.md # AndroidServiceDemo service demo
1ebfc53d032644caf848e42013faa4607c7bc196
[ "Markdown", "Java" ]
4
Java
shsun/AndroidServiceDemo
ab4c8f66deddadcab3d21d56a36c75eaefbcff5f
fdd447b51517a269e77e6d75b394a1d88df2aa6b
refs/heads/master
<file_sep>![Library Banner](https://res.cloudinary.com/alvarosaburido/image/upload/v1589993773/portfolio/web/vue-dynamic-forms/open-graph-preview_kv4glm.png) # Vue Dynamic Forms <p align="center"> <a href="https://www.npmjs.com/package/@asigloo/vue-dynamic-forms"> <img src="https://badgen.net/npm/v/@asigloo/vue-dynamic-forms" alt="Current npm version"> </a> <a href="https://bundlephobia.com/result?p=@asigloo/vue-dynamic-forms@latest"> <img src="https://flat.badgen.net/bundlephobia/min/@asigloo/vue-dynamic-forms" alt="Minified size"> </a> <a href="https://vuejs.org"> <img src="https://flat.badgen.net/badge/vue.js/2.6.x/4fc08d?icon=github" alt="Vue.js version"> </a> </p> Implementing handcrafted forms can be: 1. Costly 2. Time-consuming Especially if you need to create a very large form, in which the inputs are similar to each other, and they change frequently to meet rapidly changing business and regulatory requirements. So, wouldn't it be more economical to create the forms dynamically? Based on metadata that describes the business object model? That's Vue Dynamic Forms. ## Vue support This is the Vue `2.x.x` compatible version. For the Vue `3.x.x` and Typescript support, please use the version available in the branch [next](https://github.com/alvarosaburido/vue-dynamic-forms/tree/next). ## Documentation Complete documentation and examples available at - **[Documentation](https://vue-dynamic-forms.netlify.app)** - **[Sandbox Demo](https://codesandbox.io/s/vue-dynamic-forms-ftzes)** ## Installation ```bash $ npm install @asigloo/vue-dynamic-forms ``` or if you prefer yarn ```bash $ yarn add @asigloo/vue-dynamic-forms ``` ## Usage ### Global Register the component globally in your `main.js`: ```js import Vue from 'vue'; import VueDynamicForms from '@asigloo/vue-dynamic-forms'; Vue.use(VueDynamicForms); ``` ### Local You can include the dynamic form directly to your component. ```js import Vue from 'vue'; import { DynamicForm } from '@asigloo/vue-dynamic-forms'; const components = { DynamicForm }; export { ... components, ... } ``` ## Development ### Project setup ``` yarn install ``` ### Compiles and hot-reloads ``` yarn run serve ``` ### Compiles and minifies for production ``` yarn run build ``` ### Run your tests ``` yarn run test ``` ### Lints and fixes files ``` yarn run lint ``` ### Run your unit tests ``` yarn run test:unit ``` ## Contributing If you find this library useful and you want to help improve it, maintain it or just want a new feature, feel free to contact me, or feel free to do a PR 😁. ## Todolist This are the features I have planned for next versions of this library - [x] Material theme - [ ] Form Mixins for fields manipulation (for example, change values of a field depending of other) - [ ] More complex input types. - [x] Nuxt plugin istall - [x] Better docs & online examples ## License This project is licensed under the MIT License - see the [LICENSE.md](LICENSE.md) file for details. <file_sep>import { FormControl } from '@/core/utils'; import InputText from '@/components/input-text/InputText.vue'; import InputTextarea from '@/components/input-textarea/InputTextarea.vue'; import InputSelect from '@/components/input-select/InputSelect.vue'; import InputCheckbox from '@/components/input-checkbox/InputCheckbox.vue'; import InputRadio from '@/components/input-radio/InputRadio.vue'; const components = { InputText, InputTextarea, InputSelect, InputCheckbox, InputRadio, }; const props = { formControl: { default: () => new FormControl({}), type: Object, }, }; const methods = { valueChange(val) { this.$emit('change', val); }, onBlur() { this.$emit('blur'); }, onFocus() { this.$emit('focus'); }, validate() { const control = this.formControl; if (control.validations && control.validations.length > 0) { const validation = control.validations.reduce((prev, curr) => { const val = typeof curr.validator === 'function' ? curr.validator(control) : null; if (val !== null) { const [key, value] = Object.entries(val)[0]; const obj = {}; obj[key] = { value, text: curr.text, }; return { ...prev, ...obj, }; } return { ...prev, }; }, {}); control.errors = validation; control.valid = Object.keys(validation).length === 0; } }, }; const watch = { 'formControl.value': { handler(_after) { this.formControl.dirty = true; this.validate(); this.$emit('change', _after); }, deep: true, }, }; const computed = { getClasses() { return [ 'dynamic-input', 'form-group', { 'form-group--error': this.showErrors, }, `${this.formControl.customClass || ''}`, ]; }, hasValue() { const { value } = this.formControl; return value !== null && value !== undefined; }, showErrors() { return ( this.formControl.errors && Object.keys(this.formControl.errors).length > 0 && (this.submited || this.autoValidate) ); }, getStyles() { return this.formControl.customStyles; }, errorMessages() { const errors = Object.entries(this.formControl.errors); if (errors.length > 0) { return errors.map(([_key, value]) => value.text); } return []; }, submited() { return this.$parent.submited; }, autoValidate() { return ( this.$parent.options.autoValidate && this.formControl.touched === true ); }, }; const DynamicInput = { name: 'asDynamicInput', components, watch, props, computed, methods, }; export default DynamicInput; <file_sep>export function FormControl({ id, type = null, value = null, validations = [], label = null, form, name = null, customClass = null, customStyles = null, options = [], placeholder = null, rows = null, cols = null, errors = {}, disabled = false, valid = true, touched = false, dirty = false, helper, }) { this.id = id || `${form}-${name}`; this.type = type; this.form = form; this.value = value; this.validations = validations; this.label = label; this.name = name; this.customClass = customClass; this.customStyles = customStyles; this.options = options; this.placeholder = placeholder; this.disabled = disabled; this.errors = errors; this.valid = valid; this.touched = touched; this.dirty = dirty; this.rows = rows; this.cols = cols; this.helper = helper; } export function FormField({ id, type = 'text', value = null, validations = [], label = null, name = null, customClass = null, customStyles = null, disabled = false, options = [], placeholder = null, inline = false, rows = null, cols = null, helper, }) { this.id = id; this.type = type; this.value = value; this.validations = validations; this.label = label; this.name = name; this.customClass = customClass; this.customStyles = customStyles; this.disabled = disabled; this.options = options; this.placeholder = placeholder; this.inline = inline; this.rows = rows; this.cols = cols; this.helper = helper; } export function FormValidation( validator = null, text = 'There is something wrong with this field', ) { this.validator = validator; this.text = text; } export function FormOptions({ customClass = '', customStyles = '', method = 'POST', autoValidate = false, netlify = false, netlifyHoneypot = null, }) { this.customClass = customClass; this.customStyles = customStyles; this.method = method; this.autoValidate = autoValidate; this.netlify = netlify; this.netlifyHoneypot = netlifyHoneypot; } export default { FormControl, FormField, FormValidation, FormOptions };
7c926b8e218821b2ae00c2e9f84bd037003d20fb
[ "Markdown", "JavaScript" ]
3
Markdown
alvarosaburido/vue-dynamic-forms
4ffd8c01e8e6da0e1459b59e9493d564720768c3
112b0de288f0174b37dba64b1bb61b357b8aa8f1
refs/heads/master
<repo_name>xiaoyaolong/Book-Manage-System<file_sep>/src/com0619/Book_Add_Dialog.java package com0619; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Book_Add_Dialog extends JDialog implements ActionListener { // Define the window container. JLabel jl1,jl2,jl3,jl4,jl5,jl6,jl7; JButton jb1,jb2; JTextField jtf1,jtf2,jtf3,jtf4,jtf5; JPanel jp1,jp2,jp3; Toolkit tk; JComboBox jcb,jcb2; public Book_Add_Dialog(Frame owner,String title,boolean modal) // Construct function for window. d { super(owner,title,modal); jcb = new JComboBox(); jcb.addItem("文学"); jcb.addItem("数学"); jcb.addItem("计算机"); jcb.addItem("通信电子"); jcb.addItem("金融经济"); jcb.addItem("其他"); jcb.addActionListener(this); jcb2 = new JComboBox(); jcb2.addItem("望府"); jcb2.addItem("鲍家汇"); jcb2.addItem("长丰"); jcb2.addActionListener(this); jl1 = new JLabel(" ISBN : "); jl2 = new JLabel(" 书 名: "); jl3 = new JLabel(" 作 者: "); jl4 = new JLabel(" 出版时间: "); jl5 = new JLabel(" 出 版 社: "); jl6 = new JLabel(" 所在位置: "); jl7 = new JLabel(" 图书类别: "); jtf1 = new JTextField(); jtf2 = new JTextField(); jtf3 = new JTextField(); jtf4 = new JTextField(); jtf5 = new JTextField(); jb1 = new JButton("确定"); jb2 = new JButton("取消"); jp1 = new JPanel(); jp2 = new JPanel(); jp3 = new JPanel(); jp1.setLayout(new GridLayout(7,1)); jp2.setLayout(new GridLayout(7,1)); jp1.add(jl1); jp1.add(jl2); jp1.add(jl3); jp1.add(jl4); jp1.add(jl5); jp1.add(jl6);jp1.add(jl7); jp2.add(jtf1); jp2.add(jtf2); jp2.add(jtf3); jp2.add(jtf4); jp2.add(jtf5); jp2.add(jcb2);jp2.add(jcb); jp3.add(jb1); jp3.add(jb2); this.add(jp1,BorderLayout.WEST); this.add(jp2,BorderLayout.CENTER); this.add(jp3,BorderLayout.SOUTH); jb1.addActionListener(this); jb2.addActionListener(this); this.setSize(400, 300); tk = getToolkit(); Dimension dim = tk.getScreenSize(); this.setLocation((dim.width - getWidth())/2, (dim.height -getHeight())/2); this.setResizable(false); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource() == jcb || e.getSource() == jcb2); else if(e.getSource() == jb1) // Confirm button to add a record. { int item = this.jcb.getSelectedIndex(); String book_cal = null; switch (item) { case 0: book_cal = "文学"; break; case 1: book_cal = "数学"; break; case 2: book_cal = "计算机"; break; case 3: book_cal = "通信电子"; break; case 4: book_cal = "金融经济"; break; case 5: book_cal = "其他"; break; } int item2 = this.jcb2.getSelectedIndex(); String book_loc = null; switch (item2) { case 0: book_loc = "望府"; break; case 1: book_loc = "鲍家汇"; break; case 2: book_loc = "长丰"; break; } String sql_insert = "insert into dbo.books values(?,?,?,?,?,?,?)"; String []paras = {jtf1.getText(),jtf2.getText(),jtf3.getText(), jtf4.getText(),jtf5.getText(),book_loc,book_cal}; Book_Model temp = new Book_Model(); // Temp model for updating database. if(temp.Book_update(sql_insert,paras)) { JOptionPane.showMessageDialog(this, "添加成功","恭喜",JOptionPane.INFORMATION_MESSAGE); }else { JOptionPane.showMessageDialog(this, "添加失败","遗憾",JOptionPane.ERROR_MESSAGE); } this.dispose(); } else if(e.getSource() == jb2) // Cancel the operation. { this.dispose(); } } }<file_sep>/src/com0619/Book_Delete_Confirm.java package com0619; import javax.swing.*; import java.awt.*; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; public class Book_Delete_Confirm extends JDialog implements ActionListener { JLabel jl1; JButton jb1,jb2; JPanel jp1,jp2; String row_num; public Book_Delete_Confirm(Frame owner, String title, boolean modal, Book_Model stu_model, int row_num) { super(owner,title,modal); this.row_num = stu_model.getValueAt(row_num,0).toString(); jl1 = new JLabel("是否删除本条记录?"); jb1 = new JButton("是"); jb2 = new JButton("否"); jb1.addActionListener(this); jb2.addActionListener(this); jp1 = new JPanel(); jp2 = new JPanel(); jp1.add(jl1); jp2.add(jb1); jp2.add(jb2); this.add(jp1,BorderLayout.NORTH); this.add(jp2,BorderLayout.CENTER); this.setSize(300,90); this.setResizable(false); this.setLocation(400,300); this.setVisible(true); } public void actionPerformed(ActionEvent e) { if(e.getSource() == jb1) { String sql_delete = "delete from dbo.books where book_id=?"; String []paras = {row_num}; Book_Model temp = new Book_Model(); // Temp model for updating the database. if(temp.Book_update(sql_delete,paras)) { JOptionPane.showMessageDialog(this, "删除成功", "恭喜",JOptionPane.INFORMATION_MESSAGE); }else { JOptionPane.showMessageDialog(this, "删除失败","遗憾",JOptionPane.ERROR_MESSAGE); } this.dispose(); } else if(e.getSource() == jb2) // Cancel the Operation. { this.dispose(); } } }<file_sep>/src/com0619/Book_Model.java package com0619; import javax.swing.*; import javax.swing.table.AbstractTableModel; import java.sql.*; import java.util.Vector; public class Book_Model extends AbstractTableModel { Vector rowData,columnNames; // Vectors for containing the results. // for SQL Server Link and Process. PreparedStatement ps = null; Connection ct = null; ResultSet rs = null; public boolean Book_update(String sql_update,String []paras) { SQLHelper sql_helper = new SQLHelper(); return sql_helper.SQL_Update(sql_update,paras); } public void Book_Model_Init(String sql_command, String []name) { columnNames = new Vector(); // Define the name of columns. columnNames.add(" ISBN "); columnNames.add("书 名"); columnNames.add("作 者"); columnNames.add("出版时间"); columnNames.add("出 版 社"); columnNames.add("所在位置"); columnNames.add("图书类别"); rowData = new Vector(); // Define the data in each row. try { SQLHelper sql_helper = new SQLHelper(); rs = sql_helper.SQL_Search(sql_command,name); while(rs.next()) // Receive and output the Results. { Vector row_temp = new Vector(); // Temp data for each row in table. row_temp.add(rs.getString(1)); row_temp.add(rs.getString(2)); row_temp.add(rs.getString(3)); row_temp.add(rs.getString(4)); row_temp.add(rs.getString(5)); row_temp.add(rs.getString(6)); row_temp.add(rs.getString(7)); rowData.add(row_temp); } }catch (Exception e) { e.printStackTrace(); // print the exception. }finally // Close the resource of SQL Server!!! { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (ct != null) ct.close(); }catch (Exception e) { e.printStackTrace(); } } } public Book_Model(String sql_search, String []name) { this.Book_Model_Init(sql_search, name); } public Book_Model() // Construction function for initial model. { String [] name = {}; this.Book_Model_Init("",name); } public int getRowCount() // Get the number of rows. { return this.rowData.size(); } public int getColumnCount() // Get the number of columns. { return this.columnNames.size(); } public Object getValueAt(int rowIndex, int columnIndex) // Get the entry at (rowIndex,columnIndex). { return ((Vector)this.rowData.get(rowIndex)).get(columnIndex); } public String getColumnName(int column) { return (String)this.columnNames.get(column); } }<file_sep>/SQLQuery1.sql use Book_Manage; /*drop table dbo.books; create table books ( book_id char(13) primary key, book_name nvarchar(50) not null, book_author nvarchar(20), book_date date, book_from nvarchar(20) not null, book_loc nvarchar(5) check (book_loc in ('鲍家汇', '望府', '长丰')) default '望府' not null, book_cal nvarchar(5) check (book_cal in ('文学','数学','计算机','通信电子','金融经济','其他')) default '其他' ) insert into books values (9787115418081,'Oracle 数据库管理与开发','尚展垒','20160401','人民邮电出版社','鲍家汇','计算机') insert into books values (9787309120042,'银行业法律法规与综合能力','银行业专业人员职业资格考试研究中心','20160101','复旦大学出版社','望府','金融经济') insert into books values (1,'a','aa','20160401','人民邮电出版社','鲍家汇','数学') insert into books values (2,'b','bb','20160101','复旦大学出版社','望府','金融经济') insert into books values (3,'c','cc','20160401','人民邮电出版社','鲍家汇','数学') insert into books values (4,'d','dd','20160101','复旦大学出版社','望府','金融经济') insert into books values (5,'e','ee','20160401','人民邮电出版社','鲍家汇','数学') insert into books values (6,'f','ff','20160101','复旦大学出版社','望府','金融经济')*/ select book_id ISBN, book_name 图书名称, book_author 作者, book_loc 所在位置, book_cal 图书类别 from books; select top 1 * from books where (book_id > (select max(book_id) from (select top 3 book_id from books order by book_id) as T)) order by book_id; select top 10 * from books where (book_cal='数学' and book_id > (select max(book_id) from (select top 2 book_id from books where book_cal='数学' order by book_id) as T));
2a54df9a3bd89c730f41d28a0544a87ebb918949
[ "Java", "SQL" ]
4
Java
xiaoyaolong/Book-Manage-System
e8514a15dc46b6c7c5b6b80d8a93910618b0f3c3
44ae90dcfeb870be6fca2d49e497dd0fff30ca2c
refs/heads/master
<file_sep>class User < ActiveRecord::Base has_and_belongs_to_many :stores has_many :comments has_many :posts has_many :upvotes has_secure_password def self.search(search) @split_search = search.split(' ') @search_fname = @split_search.first @search_lname = @split_search.last where("first_name ILIKE ?", "%#{@search_fname}%") where("last_name ILIKE ?", "%#{@search_lname}%") end end <file_sep>class StatusesController < ApplicationController before_action :authorize def create @status = Status.new(user_id: current_user.id, article: params[:article]) if @status.save render json: {status: 'success'} else render json: {status: 'server error in statuses_controller'} end end end <file_sep>class AddAdminAndPendingToStores < ActiveRecord::Migration def change add_reference :stores, :user, index: true, foreign_key: true add_column :stores, :pending_approval, :boolean end end <file_sep>class PostsController < ApplicationController before_action :authorize def show @post = Post.find(params[:id]) @author = User.find(@post.user_id) @first_name = @author.first_name.capitalize @last_name = @author.last_name.capitalize @comments = Comment.where(:post_id => @post.id).map{|e| {content: e.content, post_id: e.post_id, user_id: e.user_id, author_fname: User.find(e.user_id).first_name.capitalize, author_lname: User.find(e.user_id).last_name.capitalize}} render component: 'PostContainer', props: { post: @post, first_name: @first_name, last_name: @last_name, comments: @comments } end def create @post = Post.new(title: params[:title], post_type: 'standard', content: params[:content], user_id: current_user.id) if @post.save render json: {status: 'success'} else render json: {status: 'error'} end end end <file_sep>class CommentsController < ApplicationController def new @comment = Comment.new(content: params[:content], user_id: current_user.id, post_id: params[:post_id]) if @comment.save render json: {status: 'success'} else render json: {status: 'error in comments_controller'} end end end <file_sep>class Post < ActiveRecord::Base belongs_to :user belongs_to :store has_many :upvotes has_many :comments end <file_sep>class Store < ActiveRecord::Base has_and_belongs_to_many :users has_many :comments has_many :posts end <file_sep>class UsersController < ApplicationController before_action :authorize def home @user = User.find(current_user.id) @friend_post = Post.where(:user_id => current_user.following).order(created_at: :desc).first(5).map{|e| {id: e.id, user_id: e.user_id, title: e.title, post_type: e.post_type, author_fname: User.find(e.user_id).first_name.capitalize, author_lname: User.find(e.user_id).last_name.capitalize}} @friend_status = Status.where(:user_id => current_user.following).order(created_at: :desc).first(8).map{|e| {title: e.article, user_id: e.user_id, author_fname: User.find(e.user_id).first_name.capitalize, author_lname: User.find(e.user_id).last_name.capitalize}} @first_name = @user.first_name.capitalize render component: 'UserHomeContainer', props: { user: @user, first_name: @first_name, friend_post: @friend_post, friend_status: @friend_status } end def index @users = User.where(:id=>current_user.following) @proper_users = @users.map{|e| {id: e.id, first_name: e.first_name.capitalize, last_name: e.last_name.capitalize}} render component: 'UserIndexContainer', props: { users: @proper_users } end def search @users = User.all if params[:search] @users = User.search(params[:search]) end @proper_users = @users.map{|e| {id: e.id, first_name: e.first_name.capitalize, last_name: e.last_name.capitalize}} render component: 'UserSearchContainer', props: {search_users: @proper_users} end def show @user = User.find(params[:id]) @posts = @user.posts @statuses = Status.where(:user_id => @user.id).order(created_at: :desc).first(10) @user_follow = false current_user.following.map do |e| if e.to_i == @user.id @user_follow = true end end render component: 'UserShow', props: { first_name: @user.first_name.capitalize, last_name: @user.last_name.capitalize, user: @user, posts: @posts, statuses: @statuses, user_follow: @user_follow} end def following @user=User.find(current_user.id) @user.following << params[:follow_id] if @user.save render json: {status: 'success'} else render json: {status: 'server error from users_controller'} end end end <file_sep>class NewusersController < ApplicationController def new render component: 'UserSignup' end def create if params[:password1] == params[:password2] @user = User.new(first_name: params[:firstName], last_name: params[:lastName], email: params[:email], password: params[:<PASSWORD>1]) @user.save session[:user_id] = @user.id redirect_to '/' end end end
9eb12ce6302203d564b19137521ad87988b96edb
[ "Ruby" ]
9
Ruby
smithopher/vape_app
90f815f25b0036e6bd995477fe12c5a02b8c492d
195c0e374e9b5ac5b8222a3f6bb8cf5dd6355053
refs/heads/master
<repo_name>vbashur/accounting<file_sep>/settings.gradle rootProject.name = 'accounting' include 'acceptanceTest' <file_sep>/acceptanceTest/gradle.properties logbackVersion=1.2.3 jUnitVersion=5.4.2 cucumberVersion=4.8.0 <file_sep>/docker-compose.yml version: '3.7' services: accounting: build: context: . target: app dockerfile: ./devops/docker/Dockerfile image: vbashur/accounting restart: always ports: - 8080:8080 <file_sep>/src/main/java/com/vbashur/accounting/controller/StatusController.java package com.vbashur.accounting.controller; import com.vbashur.accounting.domain.*; import org.json.JSONObject; import org.springframework.beans.factory.annotation.Value; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import static org.springframework.http.MediaType.APPLICATION_JSON_VALUE; @RestController public class StatusController { private final String version; public StatusController(@Value("${spring.application.version}") String version) { this.version = version; } @GetMapping(value = {"/status"}, produces = APPLICATION_JSON_VALUE) public ResponseEntity<String> status() { String resultBody = new JSONObject() .put("status", "success") .put("version", this.version) .toString(); String employeeRepresentation = new JSONObject() .put("personalData", new JSONObject().put("name", "employeeName")) .put("financialData", new JSONObject().put("monthIncome", "salary")) .toString(); FinancialData fd = ImmutableFinancialData.builder().monthIncome(1.2).build(); PersonalData pd = ImmutablePersonalData.builder().name("name").build(); Employee e = ImmutableEmployee.builder() .id("id") .financialData(fd).personalData(pd).build(); return ResponseEntity .status(HttpStatus.OK) .body(resultBody + "\njson\n" + employeeRepresentation + "\n\n\nobject\n" + e.toString()); } } <file_sep>/devops/docker/Dockerfile FROM openjdk:11-jdk AS buildenv # prepare Gradle WORKDIR /app ADD gradlew /app ADD gradle /app/gradle RUN ./gradlew --version >/dev/null FROM buildenv AS build ADD .git /app/.git ADD src /app/src ADD build.gradle /app ADD settings.gradle /app WORKDIR /app RUN ./gradlew --no-daemon bootJar FROM openjdk:11-slim AS app EXPOSE 8080 RUN mkdir /app COPY --from=build /app/build/libs/*.jar /app ADD ./devops/docker/entrypoint.sh / ENTRYPOINT [ "/entrypoint.sh" ] <file_sep>/acceptanceTest/src/test/java/com/vbashur/accounting/CommonStepDefenitions.java package com.vbashur.accounting; import org.apache.http.HttpStatus; import static io.restassured.RestAssured.given; public class CommonStepDefenitions { private final TestContext context; /* .ctor must be public to make pico container happy */ public CommonStepDefenitions(TestContext context) { this.context = context; } @io.cucumber.java.en.Given("^service is running$") public void serviceIsRunning() { given() .baseUri(TestContext.ACCOUNTING_BASE_URI) .when() .get("/status") .then() .statusCode(HttpStatus.SC_OK); } } <file_sep>/acceptanceTest/build.gradle plugins { id 'java' id "com.github.spacialcircumstances.gradle-cucumber-reporting" version "0.1.14" } group 'com.vbashur' version '0.0.1-SNAPSHOT' sourceCompatibility = JavaVersion.VERSION_11 repositories { mavenCentral() } dependencies { testCompile group: 'junit', name: 'junit', version: '4.12' // testCompile group: 'org.junit.jupiter', name: 'junit-jupiter-api', version: "${jUnitVersion}" testCompile group: 'org.hamcrest', name: 'hamcrest', version: '2.2' testCompile group: 'com.jayway.jsonpath', name: 'json-path-assert', version: '2.4.0' testCompile group: 'io.cucumber', name: 'cucumber-java8', version: '4.8.0' testCompile group: 'io.cucumber', name: 'cucumber-junit', version: '4.8.0' testCompile group: 'io.cucumber', name: 'cucumber-picocontainer', version: '4.8.0' // DI support testCompile group: 'io.rest-assured', name: 'rest-assured', version: '4.1.2' testImplementation group: 'org.json', name: 'json', version: '20190722' testCompile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.26' testCompile group: 'org.slf4j', name: 'slf4j-simple', version: '1.7.26' } <file_sep>/build.gradle plugins { id 'org.springframework.boot' version '2.2.1.RELEASE' id 'io.spring.dependency-management' version '1.0.8.RELEASE' id 'java' } group = 'com.vbashur' version = '0.0.1-SNAPSHOT' sourceCompatibility = JavaVersion.VERSION_11 repositories { mavenCentral() } processResources { filesMatching('application.yml') { expand(version: version) } } dependencies { implementation 'org.springframework.boot:spring-boot-starter-data-rest' implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.json:json:20190722' implementation 'org.immutables:value:2.8.2' implementation 'org.immutables:criteria-inmemory:2.8.2' annotationProcessor 'org.immutables:value:2.8.1' runtimeOnly 'com.h2database:h2' testImplementation('org.springframework.boot:spring-boot-starter-test') { exclude group: 'org.junit.jupiter', module: 'junit-jupiter-engine' } } configurations { annotationProcessor } compileJava { options.annotationProcessorPath = configurations.annotationProcessor } test { useJUnitPlatform() } <file_sep>/acceptanceTest/src/test/java/com/vbashur/accounting/TestContext.java package com.vbashur.accounting; import io.restassured.response.ValidatableResponse; public class TestContext { private ValidatableResponse requestResponse; public static final String ACCOUNTING_BASE_URI = "http://localhost:8080"; public ValidatableResponse getRequestResponse() { return requestResponse; } public void setRequestResponse(ValidatableResponse requestResponse) { this.requestResponse = requestResponse; } } <file_sep>/devops/docker/entrypoint.sh #!/usr/bin/env bash # shell script required to make use of variable expansion exec java -jar /app/accounting-*.jar "$@" <file_sep>/src/main/java/com/vbashur/accounting/configuration/RepositoryConfiguration.java package com.vbashur.accounting.configuration; import com.vbashur.accounting.domain.EmployeeRepository; import org.immutables.criteria.backend.Backend; import org.immutables.criteria.inmemory.InMemoryBackend; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class RepositoryConfiguration { private final Backend backend = new InMemoryBackend(); @Bean EmployeeRepository employeeRepository() { return new EmployeeRepository(backend); } } <file_sep>/src/main/java/com/vbashur/accounting/domain/AccountingResponse.java package com.vbashur.accounting.domain; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import com.fasterxml.jackson.databind.annotation.JsonSerialize; import io.reactivex.annotations.Nullable; import org.immutables.value.Value; import java.util.List; @Value.Immutable @JsonInclude(JsonInclude.Include.NON_NULL) @JsonSerialize(as = ImmutableAccountingResponse.class) @JsonDeserialize(as = ImmutableAccountingResponse.class) public interface AccountingResponse { @Value.Parameter List<Employee> employees(); @Value.Parameter String message(); }
6be1ae789d7762e469675356cd267d441c7d14ee
[ "YAML", "INI", "Gradle", "Java", "Dockerfile", "Shell" ]
12
Gradle
vbashur/accounting
0de559ee63adc01728997e6e1c571a06704faec1
9c84c66d8c435a2f46e3679afdc523f5433e5b22
refs/heads/master
<file_sep>#encoding=latin-1 #empiezo el approach por LSH #DATASETS=== http://jmcauley.ucsd.edu/data/amazon/links.html #https://nickgrattan.wordpress.com/2014/03/03/lsh-for-finding-similar-documents-from-a-large-number-of-documents-in-c/ #https://github.com/chrisjmccormick/MinHash/blob/master/runMinHashExample.py import numpy as np from random import randint, seed, choice, random from pyspark import SparkContext, SparkConf import string import sys import itertools import json import gzip import shutil primo = 1007 minClusterSize = 5 maxint = sys.maxint bandas = 17 hashesPorBanda = 2 cantHashes = bandas * hashesPorBanda #hashDisplaces = [str(random() % primo) for x in range(cantHashes)] #OFFSET PARA GENERAR DISTINTOS VALORES DE FUNCIONES DE HASH hashDisplaces = [] for x in range(cantHashes): hashDisplaces.append(int(random())) shingleaWords = True valoresPorBanda = dict() def dame_shingles_chars(texto, cantidadChars): '''Devuelve una lista con los shingles de texto, procesado caracter por caracter, donde los mismos tienen un tamaño de cantidadChars.''' return [texto[i:i + cantidadChars] for i in range(len(texto) - cantidadChars + 1)] def dame_shingles_words(texto, cantidadPalabras, maxLargoPalabra): '''Devuelve una lista con los shingles de texto, procesado palabra por palabra, donde los mismos tienen un tamaño de cantidadChars y un máximo de largo de palabra igual a maxLargoPalabra.''' texto = texto.split() return [texto[i:i+cantidadPalabras] for i in range(len(texto) - cantidadPalabras + 1) if len(texto[i]) < maxLargoPalabra] def dame_minhashes_shingles(shingles): '''Devuelve una lista de minhashes para la lista de shingles pasada por parámetro, utiliza hash and displace.''' minhashes = [] for i in range(cantHashes): minhash = maxint if shingleaWords: for conjunto in shingles: for shingle in conjunto: shingle += hashDisplaces[i] esteHash = abs(hash(shingle)) if esteHash < minhash: minhash = esteHash else: for shingle in shingles: shingle += hashDisplaces[i] esteHash = abs(hash(shingle)) if esteHash < minhash: minhash = esteHash minhashes.append(minhash) return minhashes def dame_minhashes_shingles2(shingles): '''Devuelve una lista de minhashes para la lista de shingles pasada por parámetro, utiliza hash and displace.''' minhashes = [] for i in range(cantHashes): minhash = maxint esteHash = 0 if shingleaWords: for conjunto in shingles: for shingle in conjunto: esteHash += abs(hash(shingle) + hashDisplaces[i]) if esteHash < minhash: minhash = esteHash else: for shingle in shingles: esteHash = abs(hash(shingle + hashDisplaces[i])) if esteHash < minhash: minhash = esteHash minhashes.append(minhash) return minhashes def dame_hash_bandasNumpy(minhashes): '''Devuelve una lista de hashes de banda a partir de una lista de minhashes en la cual hay un número de bandas y un número de hashesPorBanda para la misma.''' a = np.zeros(bandas) codigosBandas = [] hashBanda = 0 intervalo = 0 indiceArreglo = 0 for i in range(cantHashes): intervalo = intervalo + 1 if (intervalo == hashesPorBanda): a[indiceArreglo] = hashBanda indiceArreglo = indiceArreglo + 1 hashBanda = 0 intervalo = 0 hashBanda += hash(minhashes[i]) return a def dame_hash_bandas(minhashes): '''Devuelve una lista de hashes de banda a partir de una lista de minhashes en la cual hay un número de bandas y un número de hashesPorBanda para la misma.''' codigosBandas = [] hashBanda = 0 intervalo = 0 for i in range(cantHashes): #hashBanda += hash(minhashes[i]) hashBanda += minhashes[i] intervalo = intervalo + 1 if (intervalo == bandas): codigosBandas.append(hashBanda) hashBanda = 0 intervalo = 0 return codigosBandas def proc_texto_rating(texto, rating): '''Genera los shingles de texto, los minhashes y luego los hashes de cada banda. Por cada hash de banda, lo agrega al diccionario valoresPorBanda y le asigna a cada uno una lista donde el valor en la misma es rating.''' if shingleaWords: codigosBandas = dame_hash_bandas(dame_minhashes_shingles(dame_shingles_words(texto, 2, 15))) else: codigosBandas = dame_hash_bandas(dame_minhashes_shingles(dame_shingles_chars(texto, 5))) for codigo in codigosBandas: valoresPorBanda.setdefault(codigo, []) valoresPorBanda[codigo].append(rating) def flatmapeo(idReview, puntaje, array): '''Devuelve una lista donde cada posición es una tupla donde la primera posición es idReview, la segunda puntaje y la tercera, domde el valor de la misma posición en array.''' lista = [] for x in array: lista.append((idReview,puntaje,x)) return lista def damePromedioBucket(indiceDict): '''Devuelve el promedio del bucket dado por la clave indiceDict en dicto (un diccionario), donde el valor de la misma es una lista de enteros. En caso de error, devuelve 0.''' count = 0 acum = 0 try: for i in valoresPorBanda[indiceDict]: count += 1 acum += float(i) if (count != 0): return acum / count else: return 0 except: return 0 def calcScore(bandas): '''Devuelve el promedio del promedio de cada banda en bandas (lista de bandas), donde el primer promedio se calcula mediante damePromedioBucket de la banda (en el diccionario dicto), y el segundo es un promedio de todos esos promedios. En caso de error, devuelve -1.''' acum = 0 count = 0 for unaBanda in bandas: promedioBucket = damePromedioBucket(unaBanda) if (promedioBucket != 0): count += 1 acum += promedioBucket if (acum == 0): return -1 else: return acum / count sc = SparkContext(conf = SparkConf()) learn = sc.textFile('parsedTrainSmall.csv',8) learn = learn.map(lambda x: x.split('|')).map(lambda x: (x[0],x[2], dame_minhashes_shingles2(dame_shingles_words(x[1],3,15)))) from pyspark.mllib.tree import DecisionTree, DecisionTreeModel from pyspark.mllib.regression import LabeledPoint from pyspark.mllib.linalg import DenseVector data_for_decision_tree = learn.map(lambda x: LabeledPoint(label = x [1], features = DenseVector(x[2]))) (dataTrain, dataTest) = data_for_decision_tree.randomSplit([0.7, 0.3]) model = DecisionTree.trainRegressor(dataTrain, categoricalFeaturesInfo={}, impurity='variance', maxDepth=5, maxBins=32) predictions = model.predict(dataTest.map(lambda x: x.features)) labelsAndPredictions = dataTest.map(lambda x: x.label).zip(predictions) testMSE = labelsAndPredictions.map(lambda (v, p): (v - p) * (v - p)).sum() / float(dataTest.count()) print "MSE = %f"%(testMSE) learn = learn.map(lambda x: (x[0],x[1], dame_hash_bandas(x[2]))) learn = learn.flatMap(lambda x: flatmapeo(x[0], x[1], x[2])) #(u'a9wx8dk93sn5', u'1.0', 813759583895638922) learn = learn.map(lambda x: (x[2], x[1])) data = learn.collect() for a in data: valoresPorBanda.setdefault(a[0], []) valoresPorBanda[a[0]].append(a[1]) #flatmapeado = learn.count() #learn = learn.groupByKey() #agrupado = learn.count() #learn = learn.filter(lambda x: len(x[1].data) >= minClusterSize) #filtrado = learn.count() #dicto = learn.collectAsMap() try: shutil.rmtree('finalout.csv') except: print "Folder does not exist." #learn.saveAsTextFile('/media/tino/Tera/bigdata/finalout.csv') # # Comienza la prediccion # test = sc.textFile('parsedTestSmall.csv',8) test = test.map(lambda x: x.split('|')).map(lambda x: (x[0],x[2], dame_hash_bandas(dame_minhashes_shingles2(dame_shingles_words(x[1],3,15))))) test = test.map(lambda x: (x[0],x[1],calcScore(x[2]))) cantReviewsToPredict = test.count() test = test.filter(lambda x: x[2] != -1) cantReviewsPredicted = test.count() try: shutil.rmtree('scores.csv') except: print "Folder does not exist." test.saveAsTextFile('scores.csv') print "REVIEWS A PREDECIR: " + str(cantReviewsToPredict) print "REVIEWS CON SCORE: " + str(cantReviewsPredicted) print "RELACION: " + str(cantReviewsPredicted / cantReviewsToPredict) <file_sep> #encoding: utf-8 import csv TEST_SALIDA_VW = "test_predicciones.txt" TEST = "test.csv" TEST_ENTREGA = "predicciones.csv" #"Id","ProductId","UserId","ProfileName","HelpfulnessNumerator","HelpfulnessDenominator","Prediction","Time","Summary","Text" def parser(test_salida_vw, test): try: #archivo_entrada = open(nombre_archivo_entrada) salida_vw = open(test_salida_vw, 'rb') salida_vw_csv = csv.reader(salida_vw) except IOError as exc: print "Error al arir el archivo de entrada, más información: ", exc return try: test_aux = open(test, 'rb') test_csv = csv.DictReader(test_aux) except IOError as exc: print "Error al abrir el archivo de entrada, más información: ", exc salida_vw.close() return try: predic = open(TEST_ENTREGA, 'w') except IOError as exc: print "Error al abrir el archivo de entrada, más información: ", exc salida_vw.close() test_aux.close() return # cabecera = "\"Id\",\"ProductId\",\"UserId\",\"ProfileName\",\"HelpfulnessNumerator\",\"HelpfulnessDenominator\",\"Prediction\",\"Time\",\"Summary\",\"Text\" \n" cabecera = "\"Prediction\",\"Id\"\n" predic.write(cabecera); for linea in salida_vw_csv: linea_salida = linea[0].replace(" ", ",") linea_aux = linea_salida.split(",") if ( float(linea_aux[0]) < 1.0 ): num = 1.0 elif( float(linea_aux[0]) > 5.0 ): num = 5.0 else: num = float(linea_aux[0]) linea_salida = str(num) + "," + str(linea_aux[1]) + "\n" # for linea in test_csv: # linea_vw = salida_vw_csv.next(); # ProductId = "\"" + linea["ProductId"] + "\"" # UserId = "\"" + linea["UserId"] + "\"" # ProfileName = "\"" + linea["ProfileName"] + "\"" # Summary = "\"" + linea["Summary"] + "\"" # Text = "\"" + linea["Text"] + "\"" # linea_salida = linea["Id"] +"," + ProductId + "," + UserId + "," + ProfileName + "," +\ # linea["HelpfulnessNumerator"] + "," + linea["HelpfulnessDenominator"] + "," +\ # str(linea_vw[0][0]) + "," + linea["Time"] + "," + Summary + "," + Text + "\n" predic.write(linea_salida) salida_vw.close() test_aux.close() predic.close() def main(): parser(TEST_SALIDA_VW, TEST) main()<file_sep>#encoding=latin-1 ARCHIVO_MATERIAS = "materias_informatica.csv" ARCHIVO_APROBADAS = "aprobadas.csv" import csv #Opción 1: Marcar materia como aprobada. def agregar_aprobada(codigo): '''Agrega un código al final de un archivo ARCHIVO_APROBADAS con un caracter de salto de línea. De no existir lo crea, y al final lo cierra.''' aprobadas = open(ARCHIVO_APROBADAS, "a") aprobadas.write(codigo + '\n') aprobadas.close() def diccionario_cat1_cats(lista_dic, cat1, cats): '''Devuelve un diccionario cuyas claves son los valores de cada diccionario en lista_dic correspondientes a la clave cat1. Y sus valores son listas de los valores correspondientes a lista_dic según las claves en cats. Estos valores se convierten a entero si su correspondiente valor en cats es "créditos", y si este es "correlativas", entonces se convierten a lista.''' dic_cat1_cats = {} for dic in lista_dic: dic_cat1_cats [dic [cat1]] = [] for cat in cats: if cat == "créditos": dic_cat1_cats [dic [cat1]].append(int(dic [cat])) elif cat == "correlativas": if "-" in dic [cat]: dic_cat1_cats [dic [cat1]].append(dic [cat].split("-")) else: dic_cat1_cats [dic [cat1]].append([dic [cat]]) else: dic_cat1_cats [dic [cat1]].append(dic [cat]) return dic_cat1_cats def pedir_codigo_aprobada(set_aprobadas, dic_materias): '''Pide el código de una materia, si esta no está en el diccionario de todas las materias disponibles (dic_materias), o si está en el set de aprobadas (set_aprobadas), entonces lo sigue pidiendo hasta obtener un dato válido. Cuando lo obtiene, devuelve el código y la materia correspondiente según el primer diccionario. Si se ingresa "*", se devuleve dos valores None.''' codigo = raw_input("Ingrese el código de la materia, * para salir: ") while codigo not in dic_materias or codigo in set_aprobadas: if codigo == "*": return None, None codigo = raw_input("Código inválido: ") return codigo, dic_materias [codigo] [0] def marcar_materia_aprobada(set_aprobadas, dic_materias): '''Pide un código de materia hasta que esta esté en el dic_materias y no está en set_aprobadas, cuando lo tiene, lo imprime junto con la materia correspondiente, y pide que se confirme si se quiere agregar la materia como aprobada a ARCHIVO_APROBADAS. Si se acepta, la agrega, sino, se sigue pidiendo un código de materia. Si el código es None, se devuelve None. Además, agrega el código a set_aprobadas.''' while True: codigo, materia = pedir_codigo_aprobada(set_aprobadas, dic_materias) if codigo == None: return print codigo, " - ", materia confirmar = raw_input("¿Marcar materia como aprobada? [s/n]: ").lower() while confirmar != "s" and confirmar != "n": confirmar = raw_input("¿Marcar materia como aprobada? [s/n]: ").lower() if confirmar == "s": break if confirmar == "n": continue agregar_aprobada(codigo) set_aprobadas.add(codigo) #Opción 2: Ver la cantidad de materias y créditos. def mostrar_aprobadas_y_creditos(set_aprobadas, dic_materias): '''A partir de los códigos en set_aprobadas, imprime cada código, la materia correspondiente y los códigos correspondientes (dados por dic_materias), y al final imprime la suma de todos los créditos.''' creditos_totales = 0 for codigo in set_aprobadas: print codigo + " - " + dic_materias [codigo] [0] + " " * (60 - len(dic_materias [codigo] [0])) + str(dic_materias [codigo] [1]) + "c" creditos_totales += dic_materias [codigo] [1] print "Total:" + " " * 60 + str(creditos_totales) + "c" #Opción 3: Ver materias habilitadas para cursar. def mostrar_materias_habilitadas(set_aprobadas, dic_materias): '''Imprime los códigos, nombres y créditos de todas las materias habilitadas a cursar (obtenidas de dic_materias), a partir de verificar que los codigos de las materias correlativas (obtenidos de dic_materias también) se encuentren en el set_aprobadas, y además si estos códigos de aprobadas están en esa lista de materias habilitadas, no los agrega.''' lista_habilitadas = [] for codigo in dic_materias: if codigo in set_aprobadas: continue correlativas = dic_materias [codigo] [2] if len(correlativas) < 1 or correlativas [0] == "": lista_habilitadas.append(codigo) else: for correlativa in correlativas: if correlativa not in set_aprobadas: break else: lista_habilitadas.append(codigo) for codigo in lista_habilitadas: print codigo, " - ", dic_materias [codigo] [0], " " * (60 - len(dic_materias [codigo] [0])), str(dic_materias [codigo] [1]) + "c" #Opción 4: Ver información detallada de una materia. def mostrar_informacion_materia(set_aprobadas, dic_materias): '''Pide un codigo de materia, el cual debe estar en dic_materias, e imprime un mensaje con todos los detalles del mismo según la lista correspondiente a la clave código ingresado en dic_materias: nombre, cantidad de créditos si está aprobada o no, y sus correlativas, diciendo si estas están aprobadas o no (según set_aprobadas).''' codigo = raw_input("Ingrese el código de una materia, : ") while codigo not in dic_materias: codigo = raw_input("Código no válido: ") print codigo, " - ", dic_materias [codigo] [0] print dic_materias [codigo] [1], " créditos" if codigo in set_aprobadas: aprobada = "si" else: aprobada = "no" print "Aprobada: ", aprobada, "\n" print "Correlativas:" correlativas = dic_materias [codigo] [2] if len(correlativas) < 1 or correlativas [0] == "": print "No tiene" else: for correlativa in correlativas: if correlativa in set_aprobadas: print correlativa, " - ", dic_materias [correlativa] [0], " " * (60 - len(dic_materias [correlativa] [0])), str(dic_materias [correlativa] [1]) + "c (aprobada)" else: print correlativa, " - ", dic_materias [correlativa] [0], " " * (60 - len(dic_materias [correlativa] [0])), str(dic_materias [correlativa] [1]) + "c" #Opción 5: Salir. def salir(a, b): '''Termina la ejecución del programa, se le pasan dos parámetros, los cuales pueden ser cualquier cosa.''' exit() #Main: Ejecución del programa. def main(): '''Se intenta abrir ARCHIVO_MATERIAS, en caso de haber algún error, se imprime un mensaje y se sale del programa. Una vez abierto, se intenta leer el archivo en formato csv, en caso de haber algún problema, se imprime un mensaje y se sale del programa, antes cerrando el archivo. El archivo csv debe tener encabezados "código", "nombre", "créditos", "correlativas", donde los valores de "créditos" son enteros y "correlativas" son códigos. Se intenta abrir ARCHIVO_APROBADAS, en caso de haber algún error o no poseer encabezado "código", lo borra y crea uno nuevo con ese encabezado, lo mismo sucede si hay algún error durante la apertura del mismo. Luego se intenta leer el archivo en formato csv, en caso de haber algún problema se imprime un mensaje de error y se sale del programa, antes cerrando el archivo. Se imprime una serie de 5 opciones que representan distintas acciones, y se pide al usuario que ingrese una válida, en caso contrario sigue pidiendo el ingreso. Si se elige "1" se ejecuta marcar_materia_aprobada, "2" se ejecuta mostrar_aprobadas_y_creditos, "3" se ejecuta mostrar_materias_habilitadas, "4" mostrar_informacion_materia, "5" salir.''' try: archivo = open(ARCHIVO_MATERIAS, "r") except IOError as e: print "Error al abrir el archivo de materias, más información: ", e return try: arch_csv = csv.DictReader(archivo) materias = list(arch_csv) except IOError as e: print "Error al leer el archivo de materias, más información: ", e return finally: archivo.close() dic_materias = diccionario_cat1_cats(materias, "código", ("nombre", "créditos", "correlativas")) try: aprobadas = open(ARCHIVO_APROBADAS, "r") if aprobadas.readline() != "código\n": aprobadas.close() aprobadas = open(ARCHIVO_APROBADAS, "w") aprobadas.write("código\n") aprobadas.close() except IOError as exc: print "Sucedió un error al intentar abrir el archivo de aprobadas, se creará uno; más información: ", exc aprobadas = open(ARCHIVO_APROBADAS, "w") aprobadas.write("código\n") aprobadas.close() try: aprobadas = open(ARCHIVO_APROBADAS, "r") except IOError as e: print "Error al intentar abrir el archivo de aprobadas, más información: ", e return try: aprobadas.readline() set_aprobadas = set() for codigo in csv.reader(aprobadas): set_aprobadas.add("".join(codigo)) except IOError as exc: print "Error al leer el archivo de aprobadas, más información: ", exc return finally: aprobadas.close() diccionario_opciones = {"1" : marcar_materia_aprobada, "2" : mostrar_aprobadas_y_creditos, "3" : mostrar_materias_habilitadas, "4" : mostrar_informacion_materia, "5" : salir} while True: print "1 - Marcar una materia como aprobada." print "2 - Ver las materias aprobadas y la cantidad de créditos." print "3 - Ver las materias habilitadas para cursar." print "4 - Ver información detallada de una materia." print "5 - Salir." opcion = raw_input("Elija una acción a realizar: ") while opcion not in diccionario_opciones: opcion = raw_input("Acción no válida: ") try: diccionario_opciones [opcion](set_aprobadas, dic_materias) except IOError as ex: print "Hubo algún error en la ejecución de los archivos, más información: ", ex return None except MemoryError: print "Error de memoria." return None main()<file_sep>#empiezo el approach por LSH #DATASETS=== http://jmcauley.ucsd.edu/data/amazon/links.html #https://nickgrattan.wordpress.com/2014/03/03/lsh-for-finding-similar-documents-from-a-large-number-of-documents-in-c/ #https://github.com/chrisjmccormick/MinHash/blob/master/runMinHashExample.py from random import randint, seed, choice, random from pyspark import SparkContext, SparkConf import string import sys import itertools import json import gzip primo = 1007 maxint = sys.maxint bandas = 5 hashesPorBanda = 5 cantHashes = bandas * hashesPorBanda hashDisplaces = [str(random() % primo) for x in range(cantHashes)] #OFFSET PARA GENERAR DISTINTOS VALORES DE FUNCIONES DE HASH shingleaWords = True valoresPorBanda = dict() def dame_shingles_chars(texto, cantidadChars): return [texto[i:i + cantidadChars] for i in range(len(texto) - cantidadChars + 1)] def dame_shingles_words(texto, cantidadPalabras, maxLargoPalabra): texto = texto.split() return [texto[i:i+cantidadPalabras] for i in range(len(texto) - cantidadPalabras + 1) if len(texto[i]) < maxLargoPalabra] def dame_minhashes_shingles(shingles): minhashes = [] for i in range(cantHashes): #Para cada función de hash minhash = maxint if shingleaWords: #Si usé shingles de palabras for conjunto in shingles: for shingle in conjunto: shingle += hashDisplaces[i] #Obtengo un nuevo shingle a partir de un hashDisplace, para cambiar el valor de hash esteHash = abs(hash(shingle)) #Obtengo el hash del shingle if esteHash < minhash: minhash = esteHash #Si este hash es menor al minimo, se guarda else: #Si usé shingles de chars for shingle in shingles: shingle += hashDisplaces[i] esteHash = abs(hash(shingle)) if esteHash < minhash: minhash = esteHash minhashes.append(minhash) #Guardo el minhash para la actual función de hash return minhashes def dame_hash_bandas(minhashes): codigosBandas = [] hashBanda = 0 for i in range(cantHashes): #Para cada función de hash if (i % hashesPorBanda == 0 and i > 0): #Para diferenciar las bandas codigosBandas.append(hashBanda) #Guaro el nuevo hash de la banda hashBanda = 0 hashBanda += hash(minhashes[i]) #Obtengo un nuevo hash para la banda como la suma de todos los hashes de la misma (Para comparar) codigosBandas.append(hashBanda) #Guardo los hashes de banda en una lista, para luego asociarlos a un valor de predicción return codigosBandas def proc_texto_rating(texto, rating): if shingleaWords: codigosBandas = dame_hash_bandas(dame_minhashes_shingles(dame_shingles_words(texto, 2, 15))) else: codigosBandas = dame_hash_bandas(dame_minhashes_shingles(dame_shingles_chars(texto, 5))) for codigo in codigosBandas: valoresPorBanda.setdefault(codigo, []) valoresPorBanda[codigo].append(rating) sc = SparkContext(conf = SparkConf()) rdd = sc.textFile('/media/tino/Tera/bigdata/elcsvTEST.csv',10) #rdd = rdd.map(lambda x: x.split('|')).map(lambda x: (x[2], dame_shingles_words(x[1],2,15))) rdd = rdd.map(lambda x: x.split('|')).map(lambda x: (x[2], dame_hash_bandas(dame_minhashes_shingles(dame_shingles_words(x[1],2,15))))) #rdd.saveAsTextFile('/media/tino/Tera/bigdata/outtest.csv') rdd = rdd.flatMap(lambda x: (x[0], x[1])) rdd = rdd.map(lambda x: (x[1], x[0], 1)) rdd.saveAsTextFile('/media/tino/Tera/bigdata/outtest.csv') <file_sep>import csv import string header = "\"ID\",\"Texto\"\n" try: f = open('test_procesado.csv', 'w') except IOError: print "Error al arir el archivo de salida.", exc try: csvfile = open('test.csv', 'rb') archivo_csv = csv.DictReader(csvfile) except IOError as exc: print "Error al abrir el archivo de entrada.", exc f.close() replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation)) for linea in archivo_csv: iduser = str(linea['Id']) texto = str(linea['Text']).translate(replace_punctuation).lower() linea = iduser + "|" + texto + "\n" f.write(linea) csvfile.close() f.close() <file_sep> #encoding: utf-8 import csv ARCHIVO_ENTRADA_ENTRENAMIENTO = "data_train.csv" ARCHIVO_SALIDA_ENTRENAMIENTO = "data_train_vw.txt" ARCHIVO_ENTRADA_TEST = "data_test.csv" ARCHIVO_SALIDA_TEST = "data_test_vw.txt" #"Id","ProductId","UserId","ProfileName","HelpfulnessNumerator","HelpfulnessDenominator","Prediction","Time","Summary","Text" def parser(nombre_archivo_entrada, nombre_archivo_salida, pesoTexto, pesoResumen, conPrediccion): try: #archivo_entrada = open(nombre_archivo_entrada) archivo_salida = open(nombre_archivo_salida, 'w') except IOError: print "Error al arir el archivo de entrada, más información: ", exc return try: csvfile = open(nombre_archivo_entrada, 'rb') archivo_csv = csv.DictReader(csvfile) except IOError as exc: print "Error al abrir el archivo de entrada, más información: ", exc archivo_salida.close() return promedioHelpDenom = obtenerPromedio(nombre_archivo_entrada) for linea in archivo_csv: tag = linea["Id"] resumen = linea["Summary"] texto = linea["Text"] HelpNumerator = float(linea ["HelpfulnessNumerator"]) HelpDenominator = float(linea ["HelpfulnessDenominator"]) if HelpDenominator != 0: importancia = 1 + ((HelpNumerator / HelpDenominator) * (HelpDenominator / promedioHelpDenom)) else: importancia = 1 base = 0 campoResumen = resumen campoTexto = texto if (conPrediccion): prediction = float(linea["Prediction"]) linea_salida = str(prediction) + " " else: linea_salida = "" linea_salida += str(importancia) + " " + str(base) + " '" + str(tag) \ + " |Resumen:" + str(pesoResumen) + " " + str(str(campoResumen).replace(':',"")) \ + " |Texto:" + str(pesoTexto) + " " + str(str(campoTexto).replace(':',"")) + "\n" archivo_salida.write(linea_salida) csvfile.close() archivo_salida.close() def obtenerPromedio(setPath): with open(setPath, 'rb') as csvfile: reader = csv.DictReader(csvfile) contador = 0 acumulador = 0 for linea in reader: if contador != 0: acumulador += int(linea["HelpfulnessDenominator"]) contador += 1 return acumulador / float(contador) def main(): parser(ARCHIVO_ENTRADA_ENTRENAMIENTO, ARCHIVO_SALIDA_ENTRENAMIENTO, 1.0, 0.5, True) parser(ARCHIVO_ENTRADA_TEST, ARCHIVO_SALIDA_TEST, 1.0, 0.5, False) main()<file_sep>import json import gzip import string header = "\"ID\",\"Texto\",\"Score\"\n" totalreviews = 83680000 vistas = 0 porc = -1 porcAnt = -2 f = open('/media/tino/Tera/bigdata/elcsvTEST.csv', 'w') replace_punctuation = string.maketrans(string.punctuation, ' '*len(string.punctuation)) with gzip.open("/home/tino/Downloads/item_dedup.json.gz", "rb") as file: for line in file: linea = json.loads(line) iduser = str(linea['reviewerID'].replace('|','')).translate(replace_punctuation).lower() texto = str(linea['reviewText'].replace('|','')).translate(replace_punctuation).lower() puntaje = str(linea['overall']) linea = iduser + "|" + texto + "|" + puntaje + "\n" f.write(linea) if (vistas % 100000 == 0): print vistas #/ totalreviews * 100 if (vistas == 1000000): f = open('/media/tino/Tera/bigdata/elcsvTRAIN.csv', 'w') if (vistas == 1300000): break vistas = vistas + 1 <file_sep># # # TP ORGANIZACION DE DATOS - GRUPO 3 - <NAME>, <NAME> Y <NAME> # 28/11/16 # FACULTAD DE INGENIERIA DE LA UNIVERSIDAD DE BUENOS AIRES # # #DATASETS=== http://jmcauley.ucsd.edu/data/amazon/links.html #https://nickgrattan.wordpress.com/2014/03/03/lsh-for-finding-similar-documents-from-a-large-number-of-documents-in-c/ #https://github.com/chrisjmccormick/MinHash/blob/master/runMinHashExample.py from random import randint, random import math from pyspark import SparkContext, SparkConf import string import sys, os import itertools import json import gzip import shutil import datetime maxint = sys.maxint bandas = 15 hashesPorBanda = 1 cantHashes = bandas * hashesPorBanda nGram = 15 xorHash = True shingleaWords = False escribeScoresKaggle = False estimaFaltantes = True #lineasEnLearn = 300000 #Big Dataset Learn File lineasEnLearn = 227380 #TrainKaggle00 #cantReviewsToPredict = 82680000 #cantReviewsToPredict = 600001 cantReviewsToPredict = 227380 #cantReviewsToPredict = 113691 #kaggleTestFile hashDisplaces = [] valoresPorBanda = dict() rutaLearnFile = "/home/tino/Documents/trainKaggle00.csv" rutaTestFile = "/home/tino/Documents/trainKaggle01.csv" rutaScores = "/home/tino/Documents/kagglePredictions.csv" # # # Funciones # # def esPrimo(n): for i in range(3, n): if n % i == 0: return False return True def damePrimoSiguiente(numero): numero = numero + 1 while (not esPrimo(numero)): numero = numero + 1 return numero primoC = damePrimoSiguiente(bandas * lineasEnLearn) def log(text): with open("/media/tino/Tera/bigdata/log.txt", "a") as myfile: myfile.write(text + "\n") def logInit(): log("\n\n" + str(datetime.datetime.now())) log("-------------LOG---------------") log("Learn file: " + rutaLearnFile) log("Reviews to learn: " + str(lineasEnLearn)) log("Test file: " + rutaTestFile) log("Reviews to predict: " + str(cantReviewsToPredict)) log("Bandas: " + str(bandas)) log("Hashes por banda: " + str(hashesPorBanda)) log("Bandas calculadas: " + str(bandas * lineasEnLearn)) log("Cantidad de hashes: " + str(hashesPorBanda * bandas)) log("XOR: " + str(xorHash)) log("Escribe scores Kaggle: " + str(escribeScoresKaggle)) if (escribeScoresKaggle): log("En : " + rutaScores) if (shingleaWords): log("Shinglea por palabras con K-Grams: " + str(nGram)) else: log("Shinglea por caracteres con K-Grams: " + str(nGram)) log(" ") # # generateRandoms() # Genera una lista de numeros semi-aleatorios, con estos se XORea la funcion de Hash de python para obtener variantes de la funcion de hash. # def generateRandoms(): randoms = [] for x in range(cantHashes): randoms.append(int(randint(0,maxint))) return randoms # # dameShingles() # Si shingleaWords = True, devuelve una lista de listas. Cada subLista contiene nGram cantidad de palabras (< maxLargoPalabra) por shingle. # si shingleaWords = False, devuelve una lista de shingles de nGram caracteres. # def dameShingles(texto, nGram, maxLargoPalabra): if (shingleaWords): texto = texto.split() return [texto[i:i+nGram] for i in range(len(texto) - nGram + 1) if len(texto[i]) < maxLargoPalabra] else: return [texto[i:i + nGram] for i in range(len(texto) - nGram + 1)] # # dameMinhashShingles() # Devuelve la lista de minhashes para la lista de shingles por caracteres o palabra. # Si xorHash = True, el displace random para la funcion hash() se XOrea, de lo contrario se suma. # def dameMinhashShingles(shingles): minhashes = [] for i in range(cantHashes): minhash = maxint esteHash = 0 if shingleaWords: for conjunto in shingles: if xorHash: esteHash = abs(hash(" ".join(conjunto)) ^ hashDisplaces[i]) else : esteHash = abs(hash(" ".join(conjunto)) + hashDisplaces[i]) if esteHash < minhash: minhash = esteHash esteHash = 0 else: for shingle in shingles: if xorHash: esteHash = abs(hash(shingle) ^ hashDisplaces[i]) else: esteHash = abs(hash(shingle) + hashDisplaces[i]) if esteHash < minhash: minhash = esteHash minhashes.append(minhash) return minhashes # # dameHashBandas() # Acumula los hashes de los minhashes de acuerdo a la cantidad de Bandas y hashesPorBandas. # Si xorHash = True, el displace random para la funcion hash() se XOrea, de lo contrario se suma. # def dameHashBandas(minhashes): codigosBandas = [] hashBanda = 0 intervalo = 0 for i in range(cantHashes): hashBanda += hash(minhashes[i]) intervalo = intervalo + 1 if (intervalo == hashesPorBanda): codigosBandas.append(hashBanda) hashBanda = 0 intervalo = 0 return codigosBandas # # myFlatMap() # Para un review, un puntaje y un array de claves de bandas: # Genera tuplas del estilo: (idReview, Puntaje, claveBanda) # def myFlatMap(idReview, puntaje, array): lista = [] for x in array: lista.append((idReview,puntaje,x)) return lista # # damePromedioBucket() # Para una clave de Bandas, busca en el diccionario y # devuelve el promedio de los scores que se encuentran en ese bucket. # def damePromedioBucket(indiceDict): count = 0 acum = 0 try: for i in valoresPorBanda[indiceDict]: count += 1 acum += float(i) if (count != 0): return float(acum / float(count)) else: return 0 except: return 0 # # calcScore() # Para una lista de claves de Bandas, consulta los promedios para cada una # y devuelve el promedio de los promedios de los buckets. # def calcScore(bandas): acum = 0 count = 0 for unaBanda in bandas: promedioBucket = damePromedioBucket(unaBanda) if (promedioBucket != 0): count += 1 acum += promedioBucket if (acum == 0): if estimaFaltantes: return 3 return -1 else: promedioBuckets = acum / count if (promedioBuckets < 1): promedioBuckets = 1 return promedioBuckets # # myReduce() # Se utiliza en el reduce del calculo del error cuadratico. # En una parte de la tupla almacena la sumatoria de los errores al cuadrado, # y en la otra la cantidad de reviews con predictedScore != -1 # def myReduce(tup0,tup1): return (tup0[0]+tup1[0], tup0[1]+tup1[1]) # # # Plain Locality Sensitive Hashing # # logInit() hashDisplaces = generateRandoms() sc = SparkContext(conf = SparkConf()) learn = sc.textFile(rutaLearnFile,8) learn = learn.map(lambda x: x.split('|')) #(ID, ReviewText, Score) learn = learn.map(lambda x: (x[0],x[2], dameShingles(x[1],nGram,500))) #(ID, Score, [Shingles]) learn = learn.map(lambda x: (x[0],x[1], dameMinhashShingles(x[2]))) #(ID, Score, [minHashShingles]) learn = learn.map(lambda x: (x[0],x[1], dameHashBandas(x[2]))) #(ID, Score, [clavesBandas]) learn = learn.flatMap(lambda x: myFlatMap(x[0], x[1], x[2])) #(ID, Score, claveBanda) learn = learn.map(lambda x: (x[2], x[1])) #(claveBanda, Score) data = learn.collect() #Non Lazy Operation print("\nDICCIONARIO\n") for learnedReview in data: valoresPorBanda.setdefault(learnedReview[0], []) #Establece el formato del diccionario valoresPorBanda[learnedReview[0]].append(float(learnedReview[1])) #Agrega el valor del score de learnedReview al diccionario log("Claves en el diccionario: " + str(len(valoresPorBanda))) print("\nFIN DICCIONARIO\n") # # Comienza la prediccion # print("\nCOMIENZA PREDICCION\n") test = sc.textFile(rutaTestFile,8) test = test.map(lambda x: x.split('|')) #(ID, ReviewText, Score) test = test.map(lambda x: (x[0],x[2], dameShingles(x[1],nGram,500))) #(ID, Score, [Shingles]) test = test.map(lambda x: (x[0],x[1], dameMinhashShingles(x[2]))) #(ID, Score, [MinHashes]) test = test.map(lambda x: (x[0],x[1], dameHashBandas(x[2]))) #(ID, Score, [ClavesBandas]) test = test.map(lambda x: (x[0],x[1],calcScore(x[2]))) #(ID, Score, predictedScore) test = test.filter(lambda x: x[2] != -1) if escribeScoresKaggle: data = test.collect() f = open(rutaScores, 'w') for pred in data: linea = str(pred[2]) + "," + str(pred[0]) + "\n" f.write(linea) sys.exit(0) # # Obtenemos el Error en las predicciones # #(ID, Score, predictedScore) test = test.map(lambda x: abs(float(x[2])-float(x[1]))) #(abs(predictedScore - Score) test = test.map(lambda x: (x*x)) #(diff^2) test = test.map(lambda x: (x,1)) #((diff^2,1)) tupla = test.reduce(lambda x,y: myReduce(x,y)) #tupla = (Sum(diff^2), cantReviewsPredicted) sumaCuadradosDiferencia = tupla[0] cantReviewsPredicted = tupla[1] error = sumaCuadradosDiferencia / cantReviewsPredicted log("Predicted / To Predict: " + str(float(float(cantReviewsPredicted) / float(cantReviewsToPredict)))) log("Reviews con score: " + str(cantReviewsPredicted)) log("Error cuadratico medio: " + str(error))
cd36d542a09d89c4f2ef37eba61e6d19e887adea
[ "Python" ]
8
Python
estanislaoledesma/orga-datos
4dae9dbc35c7120310098776181fff83165a2d7d
00ed0ce81ac04becf152047b94859ee46cdb674b
refs/heads/master
<repo_name>kotouch/WPFMouseGameboi<file_sep>/WPFMouseGame/MainWindow.xaml.cs  using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; using System.Windows.Threading; using System.Windows.Forms; using MessageBox = System.Windows.Forms.MessageBox; using System.Threading; using System.IO; namespace WPFMouseGame { /// <summary> /// Interaction logic for MainWindow.xaml /// </summary> public partial class MainWindow : Window { public static Random _random = new Random(); int playerScore = 0; public static int xMouseLocation = 20; public static int yMouseLocation = 20; public MainWindow() { InitializeComponent(); Thread crazyMouseThread = new Thread(new ThreadStart(CrazyMouseThread)); crazyMouseThread.Start(); StreamReader sr = new StreamReader("Test_File.txt"); var line = sr.ReadLine(); MessageBox.Show(line); } public void CrazyMouseThread() { int moveX = 0; int moveY = 0; while (true) { moveX = _random.Next(xMouseLocation) - (xMouseLocation / 2); moveY = _random.Next(yMouseLocation) - (yMouseLocation / 2); System.Windows.Forms.Cursor.Position = new System.Drawing.Point(System.Windows.Forms.Cursor.Position.X + moveX, System.Windows.Forms.Cursor.Position.Y + moveY); Thread.Sleep(50); } } public void xTheButton_Click(object sender, RoutedEventArgs e) { if (xTheButton.Height <= 100) { MessageBox.Show("K get outta here tryhard."); xMouseLocation = 1; yMouseLocation = 1; } else { //Increment Score playerScore++; xMyScore.Text = playerScore.ToString(); //Increment Randomness xMouseLocation = xMouseLocation + 2; yMouseLocation = yMouseLocation + 2; //Shrink the Target xTheButton.Height = xTheButton.Height - 10; xTheButton.Width = xTheButton.Width - 14; } } private void Time_TextChanged(object sender, TextChangedEventArgs e) { } private void Window_Loaded(object sender, RoutedEventArgs e) { DispatcherTimer dt = new DispatcherTimer(); dt.Interval = TimeSpan.FromSeconds(1); dt.Tick += dtTicker; dt.Start(); } private int increment = 0; private void dtTicker(object sender, EventArgs e) { increment++; Time.Content = increment.ToString(); if (increment == 10) { MessageBox.Show("YOU LOST TRY AGAIN, sPress Enter to continue."); xMouseLocation = 1; yMouseLocation = 1; } } private void SaveScore_Click(object sender, RoutedEventArgs e) { StreamWriter File = new StreamWriter("Test_File.txt"); File.Write($"{playerScore}"); File.Close(); Environment.Exit(0); } } }
4be59f6473712b01d2fa94dc2133f095a9c4a2a1
[ "C#" ]
1
C#
kotouch/WPFMouseGameboi
7c5e2036ba75855c3b4b0d73c2ad1ac62cc96a74
708b732144dcd73b70028d89ea8545e613ebed6a
refs/heads/master
<file_sep>.. _examples-page: Examples ******** Reading and plotting ASCAT H25 data from netCDF format ====================================================== This Example script reads and plots ASCAT H25 SSM data with different masking options and also converts the data to absolute values using the included porosity data. It can be found in the /examples folder of the pytesmo package under the name read_ASCAT_H25.py If the standard file names assumed by the script have changed this can be specified during initialization of the AscatH25_SSM object. Please see the documentation of :class:`pytesmo.io.sat.ascat.AscatH25_SSM` .. include:: read_ASCAT_H25.rst Reading and plotting H-SAF images ================================= `H-SAF <http://hsaf.meteoam.it/soil-moisture.php>`_ provides three different image products: * SM OBS 1 - H07 - Large scale surface soil moisture by radar scatterometer in BUFR format over Europe * SM OBS 2 - H08 - Small scale surface soil moisture by radar scatterometer in BUFR format over Europe * SM DAS 2 - H14 - Profile index in the roots region by scatterometer data assimilation in GRIB format, global The following example will show how to read and plot each of them. It can be found in the /examples folder of the pytesmo package under the name Read_H_SAF_images.py .. include:: Read_H_SAF_images.rst Reading and plotting data from the ISMN ======================================= This example program chooses a random Network and Station and plots the first variable,depth,sensor combination. To see how to get data for a variable from all stations see the next example. It can be found in the /examples folder of the pytesmo package under the name plot_ISMN_data.py. .. include:: plot_ISMN.rst Calculating anomalies and climatologies ======================================= This Example script reads and plots ASCAT H25 SSM data. The :mod:`pytesmo.time_series.anomaly` module is then used to calculate anomalies and climatologies of the time series. It can be found in the /examples folder of the pytesmo package under the name anomalies.py .. include:: anomalies.rst Calculation of the Soil Water Index =================================== The Soil Water Index(SWI) which is a method to estimate root zone soil moisture can be calculated from Surface Soil Moisture(SSM) using an exponential Filter. For more details see this publication of `C.Abergel et.al <http://www.hydrol-earth-syst-sci.net/12/1323/2008/>`_. The following example shows how to calculate the SWI for two T values from ASCAT H25 SSM. .. include:: swi_calculation/swi_calc.rst .. include:: validation_framework.rst Triple collocation and triple collocation based scaling ======================================================= This example shows how to use the triple collocation routines in the :mod:`pytesmo.metrics` module. It also is a crash course to the theory behind triple collocation and links to relevant publications. .. include:: Triple collocation.rst Comparing ASCAT and insitu data from the ISMN without the validation framework ============================================================================== This example program loops through all insitu stations that measure soil moisture with a depth between 0 and 0.1m it then finds the nearest ASCAT grid point and reads the ASCAT data. After temporal matching and scaling using linear CDF matching it computes several metrics, like the correlation coefficients(Pearson's, Spearman's and Kendall's), Bias, RMSD as well as the Nash–Sutcliffe model efficiency coefficient. It also shows the usage of the :mod:`pytesmo.df_metrics` module. It is stopped after 2 stations to not take to long to run and produce a lot of plots It can be found in the /examples folder of the pytesmo package under the name compare_ISMN_ASCAT.py. .. include:: compare_ASCAT_ISMN.rst Reading and plotting ASCAT data from binary format ================================================== This example program reads and plots ASCAT SSM and SWI data with different masking options. It can be found in the /examples folder of the pytesmo package under the name plot_ASCAT_data.py. .. include:: plot_ascat_data.rst <file_sep>''' Created on May 21, 2014 @author: <NAME> ''' import unittest import datetime import numpy as np import numpy.testing as nptest import os import sys import pytest import pytesmo.io.sat.h_saf as H_SAF @pytest.mark.skipif(sys.platform == 'win32', reason="Does not work on Windows") class Test_H08(unittest.TestCase): def setUp(self): data_path = os.path.join( os.path.dirname(__file__), '..', 'test-data', 'sat', 'h_saf', 'h08') self.reader = H_SAF.H08img(data_path) def tearDown(self): self.reader = None def test_offset_getting(self): """ test getting the image offsets for a known day 2010-05-01 """ timestamps = self.reader.tstamps_for_daterange( datetime.datetime(2010, 5, 1), datetime.datetime(2010, 5, 1)) timestamps_should = [datetime.datetime(2010, 5, 1, 8, 33, 1)] assert sorted(timestamps) == sorted(timestamps_should) @pytest.mark.skipif("TRAVIS_PYTHON_VERSION" in os.environ, reason="Needs to much memory on CI server") def test_image_reading(self): data, meta, timestamp, lons, lats, time_var = self.reader.read( datetime.datetime(2010, 5, 1, 8, 33, 1)) # do not check data content at the moment just shapes and structure assert sorted(data.keys()) == sorted( ['ssm', 'corr_flag', 'ssm_noise', 'proc_flag']) assert lons.shape == (3120, 7680) assert lats.shape == (3120, 7680) for var in data: assert data[var].shape == (3120, 7680) @pytest.mark.skipif("TRAVIS_PYTHON_VERSION" in os.environ, reason="Needs to much memory on CI server") def test_image_reading_bbox_empty(self): data, meta, timestamp, lons, lats, time_var = self.reader.read(datetime.datetime(2010, 5, 1, 8, 33, 1), lat_lon_bbox=[45, 48, 15, 18]) # do not check data content at the moment just shapes and structure assert data is None assert lons is None assert lats is None @pytest.mark.skipif("TRAVIS_PYTHON_VERSION" in os.environ, reason="Needs to much memory on CI server") def test_image_reading_bbox(self): data, meta, timestamp, lons, lats, time_var = self.reader.read(datetime.datetime(2010, 5, 1, 8, 33, 1), lat_lon_bbox=[60, 70, 15, 25]) # do not check data content at the moment just shapes and structure assert sorted(data.keys()) == sorted( ['ssm', 'corr_flag', 'ssm_noise', 'proc_flag']) assert lons.shape == (2400, 2400) assert lats.shape == (2400, 2400) for var in data: assert data[var].shape == (2400, 2400) @pytest.mark.skipif(sys.platform == 'win32', reason="Does not work on Windows") class Test_H07(unittest.TestCase): def setUp(self): data_path = os.path.join( os.path.dirname(__file__), '..', 'test-data', 'sat', 'h_saf', 'h07') self.reader = H_SAF.H07img(data_path) def tearDown(self): self.reader = None def test_offset_getting(self): """ test getting the image offsets for a known day 2010-05-01 """ timestamps = self.reader.tstamps_for_daterange( datetime.datetime(2010, 5, 1), datetime.datetime(2010, 5, 1)) timestamps_should = [datetime.datetime(2010, 5, 1, 8, 33, 1)] assert sorted(timestamps) == sorted(timestamps_should) def test_image_reading(self): data, meta, timestamp, lons, lats, time_var = self.reader.read( datetime.datetime(2010, 5, 1, 8, 33, 1)) ssm_should = np.array([51.2, 65.6, 46.2, 56.9, 61.4, 61.5, 58.1, 47.1, 72.7, 13.8, 60.9, 52.1, 78.5, 57.8, 56.2, 79.8, 67.7, 53.8, 86.5, 29.4, 50.6, 88.8, 56.9, 68.9, 52.4, 64.4, 81.5, 50.5, 84., 79.6, 47.4, 79.5, 46.9, 60.7, 81.3, 52.9, 84.5, 25.5, 79.2, 93.3, 52.6, 93.9, 74.4, 91.4, 76.2, 92.5, 80., 88.3, 79.1, 97.2, 56.8]) lats_should = np.array([70.21162, 69.32506, 69.77325, 68.98149, 69.12295, 65.20364, 67.89625, 67.79844, 67.69112, 67.57446, 67.44865, 67.23221, 66.97207, 66.7103, 66.34695, 65.90996, 62.72462, 61.95761, 61.52935, 61.09884, 60.54359, 65.60223, 65.33588, 65.03098, 64.58972, 61.46131, 60.62553, 59.52057, 64.27395, 63.80293, 60.6569, 59.72684, 58.74838, 63.42774]) nptest.assert_allclose(lats[25:-1:30], lats_should, atol=1e-5) nptest.assert_allclose(data['ssm'][15:-1:20], ssm_should, atol=0.01) pass @pytest.mark.skipif(sys.platform == 'win32', reason="Does not work on Windows") class Test_H14(unittest.TestCase): def setUp(self): data_path = os.path.join( os.path.dirname(__file__), '..', 'test-data', 'sat', 'h_saf', 'h14') self.reader = H_SAF.H14img(data_path, expand_grid=False) self.expand_reader = H_SAF.H14img(data_path, expand_grid=True) def tearDown(self): self.reader = None self.expand_reader = None def test_image_reading(self): data, meta, timestamp, lons, lats, time_var = self.reader.read( datetime.datetime(2014, 5, 15)) assert sorted(data.keys()) == sorted(['SM_layer1_0-7cm', 'SM_layer2_7-28cm', 'SM_layer3_28-100cm', 'SM_layer4_100-289cm']) assert lons.shape == (843490,) assert lats.shape == (843490,) for var in data: assert data[var].shape == (843490,) def test_expanded_image_reading(self): data, meta, timestamp, lons, lats, time_var = self.expand_reader.read( datetime.datetime(2014, 5, 15)) assert sorted(data.keys()) == sorted(['SM_layer1_0-7cm', 'SM_layer2_7-28cm', 'SM_layer3_28-100cm', 'SM_layer4_100-289cm']) assert lons.shape == (800, 1600) assert lats.shape == (800, 1600) for var in data: assert data[var].shape == (800, 1600) if __name__ == "__main__": # import sys;sys.argv = ['', 'Test.testName'] unittest.main() <file_sep>.. pytesmo documentation master file, created by sphinx-quickstart on Tue Aug 6 18:18:08 2013. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. Welcome to the documentation of pytesmo - a Python Toolbox for the Evaluation of Soil Moisture Observations =========================================================================================================== Contents: .. toctree:: :maxdepth: 4 introduction.rst examples.rst moduleindex.rst <file_sep> .. code:: python import pytesmo.io.ismn.interface as ismn import pytesmo.io.sat.ascat as ascat import pytesmo.temporal_matching as temp_match import pytesmo.scaling as scaling import pytesmo.df_metrics as df_metrics import pytesmo.metrics as metrics import os import matplotlib.pyplot as plt .. code:: python ascat_folder = os.path.join('R:\\','Datapool_processed','WARP','WARP5.5', 'ASCAT_WARP5.5_R1.2','080_ssm','netcdf') ascat_grid_folder = os.path.join('R:\\','Datapool_processed','WARP','ancillary','warp5_grid') #init the ASCAT_SSM reader with the paths #let's not include the orbit direction since it is saved as 'A' #or 'D' it can not be plotted ascat_SSM_reader = ascat.AscatH25_SSM(ascat_folder,ascat_grid_folder, include_in_df=['sm', 'sm_noise', 'ssf', 'proc_flag']) .. code:: python #set path to ISMN data path_to_ismn_data =os.path.join('D:\\','small_projects','cpa_2013_07_ISMN_userformat_reader','header_values_parser_test') #Initialize reader ISMN_reader = ismn.ISMN_Interface(path_to_ismn_data) .. code:: python .. code:: python i = 0 label_ascat='sm' label_insitu='insitu_sm' .. code:: python #this loops through all stations that measure soil moisture for station in ISMN_reader.stations_that_measure('soil moisture'): #this loops through all time series of this station that measure soil moisture #between 0 and 0.1 meters for ISMN_time_series in station.data_for_variable('soil moisture',min_depth=0,max_depth=0.1): ascat_time_series = ascat_SSM_reader.read_ssm(ISMN_time_series.longitude, ISMN_time_series.latitude, mask_ssf=True, mask_frozen_prob = 5, mask_snow_prob = 5) #drop nan values before doing any matching ascat_time_series.data = ascat_time_series.data.dropna() ISMN_time_series.data = ISMN_time_series.data.dropna() #rename the soil moisture column in ISMN_time_series.data to insitu_sm #to clearly differentiate the time series when they are plotted together ISMN_time_series.data.rename(columns={'soil moisture':label_insitu},inplace=True) #get ISMN data that was observerd within +- 1 hour(1/24. day) of the ASCAT observation #do not include those indexes where no observation was found matched_data = temp_match.matching(ascat_time_series.data,ISMN_time_series.data, window=1/24.) #matched ISMN data is now a dataframe with the same datetime index #as ascat_time_series.data and the nearest insitu observation #continue only with relevant columns matched_data = matched_data[[label_ascat,label_insitu]] #the plot shows that ISMN and ASCAT are observed in different units matched_data.plot(figsize=(15,5),secondary_y=[label_ascat], title='temporally merged data') plt.show() #this takes the matched_data DataFrame and scales all columns to the #column with the given reference_index, in this case in situ scaled_data = scaling.scale(matched_data, method='lin_cdf_match', reference_index=1) #now the scaled ascat data and insitu_sm are in the same space scaled_data.plot(figsize=(15,5), title='scaled data') plt.show() plt.scatter(scaled_data[label_ascat].values,scaled_data[label_insitu].values) plt.xlabel(label_ascat) plt.ylabel(label_insitu) plt.show() #calculate correlation coefficients, RMSD, bias, <NAME> x, y = scaled_data[label_ascat].values, scaled_data[label_insitu].values print "ISMN time series:",ISMN_time_series print "compared to" print ascat_time_series print "Results:" #df_metrics takes a DataFrame as input and automatically #calculates the metric on all combinations of columns #returns a named tuple for easy printing print df_metrics.pearsonr(scaled_data) print "Spearman's (rho,p_value)", metrics.spearmanr(x, y) print "Kendalls's (tau,p_value)", metrics.kendalltau(x, y) print df_metrics.kendalltau(scaled_data) print df_metrics.rmsd(scaled_data) print "Bias", metrics.bias(x, y) print "<NAME>", metrics.nash_sutcliffe(x, y) i += 1 #only show the first 2 stations, otherwise this program would run a long time #and produce a lot of plots if i >= 2: break .. image:: compare_ASCAT_ISMN_files/compare_ASCAT_ISMN_5_0.png .. image:: compare_ASCAT_ISMN_files/compare_ASCAT_ISMN_5_1.png .. image:: compare_ASCAT_ISMN_files/compare_ASCAT_ISMN_5_2.png .. parsed-literal:: ISMN time series: OZNET Alabama 0.00 m - 0.05 m soil moisture measured with Stevens-Hydra-Probe compared to ASCAT time series gpi:1884359 lat:-35.342 lon:147.541 Results: (Pearsons_r(sm_and_insitu_sm=0.61607679781575175), p_value(sm_and_insitu_sm=3.1170801211098453e-65)) Spearman's (rho,p_value) (0.64651747115098912, 1.0057610194056589e-73) Kendalls's (tau,p_value) (0.4685441550995097, 2.4676437876515864e-67) (Kendall_tau(sm_and_insitu_sm=0.4685441550995097), p_value(sm_and_insitu_sm=2.4676437876515864e-67)) rmsd(sm_and_insitu_sm=0.078018684719599857) Bias 0.00168114697282 Nash Sutcliffe 0.246416864767 .. image:: compare_ASCAT_ISMN_files/compare_ASCAT_ISMN_5_4.png .. image:: compare_ASCAT_ISMN_files/compare_ASCAT_ISMN_5_5.png .. image:: compare_ASCAT_ISMN_files/compare_ASCAT_ISMN_5_6.png .. parsed-literal:: ISMN time series: OZNET Balranald-Bolton_Park 0.00 m - 0.08 m soil moisture measured with CS615 compared to ASCAT time series gpi:1821003 lat:-33.990 lon:146.381 Results: (Pearsons_r(sm_and_insitu_sm=0.66000287576696759), p_value(sm_and_insitu_sm=1.3332742454781072e-126)) Spearman's (rho,p_value) (0.65889275747696652, 4.890533231776912e-126) Kendalls's (tau,p_value) (0.48653686844813893, 6.6517671082477896e-118) (Kendall_tau(sm_and_insitu_sm=0.48653686844813893), p_value(sm_and_insitu_sm=6.6517671082477896e-118)) rmsd(sm_and_insitu_sm=0.028314835540753237) Bias 4.56170862568e-05 Nash Sutcliffe 0.316925662899 .. code:: python <file_sep> .. code:: python import os import matplotlib.pyplot as plt from pytesmo.time_series.filters import exp_filter import pytesmo.io.sat.ascat as ascat ascat_folder = os.path.join('/media', 'sf_R', 'Datapool_processed', 'WARP', 'WARP5.5', 'IRMA0_WARP5.5_P2', 'R1', '080_ssm', 'netcdf') ascat_grid_folder = os.path.join('/media', 'sf_R', 'Datapool_processed', 'WARP', 'ancillary', 'warp5_grid') # init the ASCAT_SSM reader with the paths # ascat_folder is the path in which the cell files are # located e.g. TUW_METOP_ASCAT_WARP55R12_0600.nc # ascat_grid_folder is the path in which the file # TUW_WARP5_grid_info_2_1.nc is located # let's not include the orbit direction since it is saved as 'A' # or 'D' it can not be plotted # the AscatH25_SSM class automatically detects the version of data # that you have in your ascat_folder. Please do not mix files of # different versions in one folder ascat_SSM_reader = ascat.AscatH25_SSM(ascat_folder, ascat_grid_folder, include_in_df=['sm', 'sm_noise', 'ssf', 'proc_flag']) .. code:: python ascat_ts = ascat_SSM_reader.read_ssm(gpi, mask_ssf=True, mask_frozen_prob=10, mask_snow_prob=10) ascat_ts.plot() .. image:: swi_calculation/output_2_1.png .. code:: python # Drop NA measurements ascat_sm_ts = ascat_ts.data[['sm', 'sm_noise']].dropna() # Get julian dates of time series jd = ascat_sm_ts.index.to_julian_date().get_values() # Calculate SWI T=10 ascat_sm_ts['swi_t10'] = exp_filter(ascat_sm_ts['sm'].values, jd, ctime=10) ascat_sm_ts['swi_t50'] = exp_filter(ascat_sm_ts['sm'].values, jd, ctime=50) fig, ax = plt.subplots(1, 1, figsize=(15, 5)) ascat_sm_ts['sm'].plot(ax=ax, alpha=0.4, marker='o',color='#00bfff', label='SSM') ascat_sm_ts['swi_t10'].plot(ax=ax, lw=2,label='SWI T=10') ascat_sm_ts['swi_t50'].plot(ax=ax, lw=2,label='SWI T=50') plt.legend() .. image:: swi_calculation/output_3_1.png <file_sep># Copyright (c) 2014,Vienna University of Technology, # Department of Geodesy and Geoinformation # 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. # * Neither the name of the Vienna University of Technology, # Department of Geodesy and Geoinformation nor the # names of its contributors may be used to endorse or promote products # derived from this software without specific prior written permission. # 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 VIENNA UNIVERSITY OF TECHNOLOGY, # DEPARTMENT OF GEODESY AND GEOINFORMATION 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. ''' Created on Mar 7, 2014 Plot anomalies around climatology using colors @author: <NAME> <EMAIL> ''' import matplotlib.pyplot as plt import matplotlib.gridspec as gridspec import pandas as pd import pytesmo.time_series.anomaly as anom def plot_clim_anom(df, clim=None, axes=None, markersize=0.75, mfc='0.3', mec='0.3', clim_color='0.0', clim_linewidth=0.5, clim_linestyle='-', pos_anom_color='#799ADA', neg_anom_color='#FD8086', anom_linewidth=0.2, add_titles=True): """ Takes a pandas DataFrame and calculates the climatology and anomaly and plots them in a nice way for each column Parameters ---------- df : pandas.DataFrame clim : pandas.DataFrame, optional if given these climatologies will be used if not given then climatologies will be calculated this DataFrame must have the same number of columns as df and also the column names. each climatology must have doy as index. axes : list of matplotlib.Axes, optional list of axes on which each column should be plotted if not given a standard layout is generated markersize : float, optional size of the markers for the datapoints mfc : matplotlib color, optional markerfacecolor, color of the marker face mec : matplotlib color, optional markeredgecolor clim_color : matplotlib color, optional color of the climatology clim_linewidth : float, optional linewidth of the climatology clim_linestyle : string, optional linestyle of the climatology pos_anom_color : matplotlib color, optional color of the positive anomaly neg_anom_color : matplotlib color, optional color of the negative anomaly anom_linewidth : float, optional linewidth of the anomaly lines add_titles : boolean, optional if set each subplot will have it's column name as title Default : True Returns ------- Figure : matplotlib.Figure if no axes were given axes : list of matploblib.Axes if no axes were given """ if type(df) == pd.Series: df = pd.DataFrame(df) nr_columns = len(df.columns) # make own axis if necessary if axes is None: own_axis = True gs = gridspec.GridSpec(nr_columns, 1, right=0.8) fig = plt.figure(num=None, figsize=(6, 2 * nr_columns), dpi=150, facecolor='w', edgecolor='k') last_axis = fig.add_subplot(gs[nr_columns - 1]) axes = [] for i, grid in enumerate(gs): if i < nr_columns - 1: ax = fig.add_subplot(grid, sharex=last_axis) axes.append(ax) ax.xaxis.set_visible(False) axes.append(last_axis) else: own_axis = False for i, column in enumerate(df): Ser = df[column] ax = axes[i] if clim is None: clima = anom.calc_climatology(Ser) else: clima = clim[column] anomaly = anom.calc_anomaly(Ser, climatology=clima, return_clim=True) anomaly[Ser.name] = Ser anomaly = anomaly.dropna() pos_anom = anomaly[Ser.name].values > anomaly['climatology'].values neg_anom = anomaly[Ser.name].values < anomaly['climatology'].values ax.plot(anomaly.index, anomaly[Ser.name].values, 'o', markersize=markersize, mfc=mfc, mec=mec) ax.plot(anomaly.index, anomaly['climatology'].values, linestyle=clim_linestyle, color=clim_color, linewidth=clim_linewidth) ax.fill_between(anomaly.index, anomaly[Ser.name].values, anomaly['climatology'].values, interpolate=True, where=pos_anom, color=pos_anom_color, linewidth=anom_linewidth) ax.fill_between(anomaly.index, anomaly[Ser.name].values, anomaly['climatology'].values, interpolate=True, where=neg_anom, color=neg_anom_color, linewidth=anom_linewidth) if add_titles: ax.set_title(column) if own_axis: return fig, axes else: return None, None
6e119883dddccbdc143638aed6aec36cddd5627a
[ "Python", "reStructuredText" ]
6
reStructuredText
fFasccetti/pytesmo
393a432d09d5c89a0a6bce5abd6c623f2a3456c3
20ce615ee5ee2abb2a0b25dcfff8015e06e4b7ea
refs/heads/master
<repo_name>evantzhao/nlp-ner-analysis<file_sep>/src/emission.py from collections import Counter from typing import Dict from typing import List from constants import Constants class EmissionMatrix: def __init__( self, token_stream: List[str], tag_stream: List[str] ) -> None: self.emissions_matrix = self.construct_emissions( token_stream, tag_stream, ) self.tag_count = self.construct_emissions_tag_count() def construct_emissions( self, token_stream: List[str], tag_stream: List[str] ) -> Dict[str, Dict[str, int]]: assert(len(token_stream) == len(tag_stream)) emissions_matrix = {} for token, tag in zip(token_stream, tag_stream): if token == Constants.START or token == Constants.END: continue if tag not in emissions_matrix: emissions_matrix[tag] = Counter() emissions_matrix[tag][token] += 1 return emissions_matrix def get_state_with_token_count( self, state: str, token: str, ) -> int: return self.emissions_matrix[state][token] def construct_emissions_tag_count(self) -> Dict[str, int]: tag_count = {} for tag in self.emissions_matrix: count = sum(self.emissions_matrix[tag].values()) tag_count[tag] = count return tag_count def get_state_occurences( self, state: str, ) -> int: if state not in self.tag_count: return 1 return self.tag_count[state] def e( self, word: str, state: str, ) -> float: state_token_count = self.get_state_with_token_count(state, word) state_occurs = self.get_state_occurences(state) return float(state_token_count) / state_occurs <file_sep>/src/hmm.py import time from typing import List from typing import Set from typing import Tuple from transition import TransitionMatrix from emission import EmissionMatrix from constants import Constants from unknown import Unknown class HiddenMarkovModel: def __init__( self, token_stream: List[str], tag_stream: List[str], ): self.emission = EmissionMatrix(token_stream, tag_stream) self.transition = TransitionMatrix(tag_stream) def classify_test_stream( self, test_stream: Tuple[List[str], List[str], List[str]], ) -> List[str]: predictions = [] for token_stream, _, _ in test_stream: memo, backtracking = self.viterbi(token_stream) predicted_tags = self.backtrack(memo, backtracking) predictions.extend(predicted_tags) return predictions def viterbi( self, tokens: List[str], ) -> List[str]: memo = [ [0] * len(Constants.ALL_TAGS) for i in range(len(tokens) - 1) ] backtracking = [ [-1] * len(Constants.ALL_TAGS) for i in range(len(tokens) - 1) ] memo[0] = [1] for token_index in range(1, len(memo)): for tag_index in range(len(memo[token_index])): maximum_probability, backtrack_tag = 0, -1 # deal with base case if token_index == 1: past_prob = memo[token_index - 1][0] transition_prob = self.transition.get_bigram_interpolated_probability( Constants.START, Constants.TAG_TO_STRING[tag_index] ) emission_prob = self.emission.e( word=tokens[token_index], state=Constants.TAG_TO_STRING[tag_index] ) # TODO evanzhao Use log probabilities sequence_prob = past_prob * transition_prob * emission_prob memo[token_index][tag_index] = sequence_prob backtracking[token_index][tag_index] = Constants.START continue for tag in Constants.ALL_TAGS: past_prob = memo[token_index - 1][tag] transition_prob = self.transition.get_bigram_interpolated_probability( Constants.TAG_TO_STRING[tag], Constants.TAG_TO_STRING[tag_index] ) emission_prob = self.emission.e( word=tokens[token_index], state=Constants.TAG_TO_STRING[tag_index] ) sequence_prob = float(past_prob) * transition_prob * emission_prob if sequence_prob > maximum_probability: maximum_probability = sequence_prob backtrack_tag = tag memo[token_index][tag_index] = maximum_probability backtracking[token_index][tag_index] = backtrack_tag return memo, backtracking def backtrack( self, memo: List[List[float]], backtracking: List[List[int]] ) -> List[str]: seed_level = memo[-1] seed_index = seed_level.index(max(seed_level)) result = [] i = len(backtracking) - 1 while i >= 1: result.append(seed_index) seed_index = backtracking[i][seed_index] i -= 1 return [Constants.TAG_TO_STRING[tag] for tag in reversed(result)] <file_sep>/src/unknown.py import re from collections import Counter from typing import List, Dict, Set, Tuple from constants import Constants class Regex: twoDigitNum = re.compile('^[0-9]{2}$'), ".twoDigitNum." fourDigitNum = re.compile('^[0-9]{4}$'), ".fourDigitNum." containsDigitAndDash = re.compile('^[0-9]+(\-)[0-9]+$'), ".containsDigitAndDash." containsDigitAndSlash = re.compile('^([0-9]+(\/))+[0-9]+$'), ".containsDigitAndSlash." containsDigitAndComma = re.compile('^[0-9]+,[0-9.]+$'), ".containsDigitAndComma." containsDigitAndPeriod = re.compile('^[0-9]*\.[0-9]+$'), ".containsDigitAndPeriod." otherNum = re.compile('^[0-9]+$'), ".otherNum." allCaps = re.compile('^[A-Z]+$'), ".allCaps." capPeriod = re.compile('^[A-Z]\.$'), ".capPeriod." firstWord = re.compile('^$'), ".firstWord." initCap = re.compile('^[A-Z][a-z]+$'), ".initCap." lowercase = re.compile('^[a-z]+$'), ".lowercase." OTHER = ".other." ITERABLE_REGEX = [ twoDigitNum, fourDigitNum, containsDigitAndDash, containsDigitAndSlash, containsDigitAndComma, containsDigitAndPeriod, otherNum, allCaps, capPeriod, initCap, lowercase ] class Unknown: LOW_FREQUENCY_THRESHOLD = 3 def get_token_counts( token_stream: List[str] ) -> Dict[str, int]: token_counts = Counter() for token in token_stream: token_counts[token] += 1 return token_counts def replace_low_frequency_tokens( token_stream: List[str], ) -> Tuple[List[str], Set[str]]: """ For all words that appear less than [frequency_threshold] times, we remove them from the corpus and replace them with a psuedo word. The same thing is done to the test set at classification time -- if an unknown word appears, we will simply convert it to this psuedo word and continue classifying as normal. """ token_counts = Unknown.get_token_counts(token_stream) low_frequency_tokens = set() for token in token_counts: if token_counts[token] < Unknown.LOW_FREQUENCY_THRESHOLD: low_frequency_tokens.add(token) closed_vocab_corpus = Unknown.convert_word_to_psuedo_word( token_stream, low_frequency_tokens ) for token in low_frequency_tokens: del token_counts[token] return closed_vocab_corpus, set(token_counts) def replace_unknown_tokens( test_stream: Tuple[List[str], List[str], List[str]], closed_vocabulary: Set[str], ) -> List[Tuple[List[str], List[str], List[str]]]: replaced_test_stream = [] for token_stream, pos_stream, index_stream in test_stream: tokens = Unknown.convert_word_to_psuedo_word( token_stream, Unknown.compute_test_word_replacement_set( closed_vocabulary, token_stream, ), ) replaced_test_stream.append((tokens, pos_stream, index_stream)) return replaced_test_stream def convert_word_to_psuedo_word( og_stream: List[str], low_freq_words: Set[str] ) -> List[str]: stream = list(og_stream) # Convert stream into a closed vocabulary for index in range(0, len(stream)): if stream[index] == Constants.START or stream[index] == Constants.END: continue word = stream[index] if word in low_freq_words: has_match = False for i in range(9): if Regex.ITERABLE_REGEX[i][0].match(word): stream[index] = Regex.ITERABLE_REGEX[i][1] has_match = True break if has_match: continue if stream[index - 1] == Constants.START: stream[index] = Regex.firstWord[1] continue for i in range(9, len(Regex.ITERABLE_REGEX)): if Regex.ITERABLE_REGEX[i][0].match(word): stream[index] = Regex.ITERABLE_REGEX[i][1] has_match = True break if not has_match: stream[index] = Regex.OTHER return stream def compute_test_word_replacement_set( recognized_words: Set[str], sentence: List[str] ): replace_set = set() for i in range(len(sentence)): word = sentence[i] if word == Constants.START or word == Constants.END: continue if word not in recognized_words: replace_set.add(word) return replace_set <file_sep>/src/utilities.py from constants import Constants from typing import Dict from typing import List from typing import Tuple class Utils: def read_training_file( filepath: str, insert_start_and_end: bool = True, ) -> List[str]: streams = [[], [], []] index = 0 with open(filepath, 'r') as f: for line in f: line_arr = line.strip().split() if insert_start_and_end: line_arr.insert(0, Constants.START) line_arr.append(Constants.END) streams[index].extend(line_arr) index = (index + 1) % len(streams) return streams def create_training_validation_split( training_file_path: str, ): training_streams = [] validation_streams = [] with open(training_file_path, 'r') as f: lines = f.readlines() offset = 0 entry_num = 0 while offset < len(lines): tokens = lines[offset] pos = lines[offset + 1] tags = lines[offset + 2] entry = (tokens, pos, tags) if entry_num % 10 != 9: training_streams.append(entry) else: validation_streams.append(entry) offset += 3 entry_num += 1 return training_streams, validation_streams def write_streams_to_file( streams: Tuple[List[str], List[str], List[str]], output_file_path: str, ) -> None: with open(output_file_path, 'w') as f: for token_stream, pos_stream, index_stream in streams: f.write(token_stream) f.write(pos_stream) f.write(index_stream) f.close() def add_start_end_tokens( line: str, ) -> List[str]: line_arr = line.strip().split() line_arr.insert(0, Constants.START) line_arr.append(Constants.END) return line_arr def read_test_file( filepath: str, ): sentences = [] index = 0 with open(filepath, 'r') as f: streams = [[], [], []] for line in f: line_arr = line.strip().split() if index == 2: line_arr.insert(0, -1) line_arr.append(-1) else: line_arr.insert(0, Constants.START) line_arr.append(Constants.END) streams[index].extend(line_arr) if index == 2: sentences.append((streams[0], streams[1], streams[2])) streams = [[], [], []] index = (index + 1) % len(streams) return sentences # TODO ryan can u refactor this :( def compile_output_data( tags: List[str] ) -> Dict[str, List[str]]: results = { "PER": [], "LOC": [], "ORG": [], "MISC": [], } mode = Constants.OTHER start = -1 for idx, predicted_tag in enumerate(tags): if "I-" in predicted_tag: continue # Either something has terminated, or nothing is happening if predicted_tag == "O": # Something has terminated if mode == Constants.BMISC: results["MISC"].append(f"{start}-{idx-1}") elif mode == Constants.BPER: results["PER"].append(f"{start}-{idx-1}") elif mode == Constants.BLOC: results["LOC"].append(f"{start}-{idx-1}") elif mode == Constants.BORG: results["ORG"].append(f"{start}-{idx-1}") mode = Constants.OTHER # Transition here from another B or from O or from I elif predicted_tag == "B-MISC": if mode == Constants.BMISC: results["MISC"].append(f"{start}-{idx-1}") elif mode == Constants.BPER: results["PER"].append(f"{start}-{idx-1}") elif mode == Constants.BLOC: results["LOC"].append(f"{start}-{idx-1}") elif mode == Constants.BORG: results["ORG"].append(f"{start}-{idx-1}") mode = Constants.BMISC start = idx elif predicted_tag == "B-PER": if mode == Constants.BMISC: results["MISC"].append(f"{start}-{idx-1}") elif mode == Constants.BPER: results["PER"].append(f"{start}-{idx-1}") elif mode == Constants.BLOC: results["LOC"].append(f"{start}-{idx-1}") elif mode == Constants.BORG: results["ORG"].append(f"{start}-{idx-1}") mode = Constants.BPER start = idx elif predicted_tag == "B-LOC": if mode == Constants.BMISC: results["MISC"].append(f"{start}-{idx-1}") elif mode == Constants.BPER: results["PER"].append(f"{start}-{idx-1}") elif mode == Constants.BLOC: results["LOC"].append(f"{start}-{idx-1}") elif mode == Constants.BORG: results["ORG"].append(f"{start}-{idx-1}") mode = Constants.BLOC start = idx elif predicted_tag == "B-ORG": if mode == Constants.BMISC: results["MISC"].append(f"{start}-{idx-1}") elif mode == Constants.BPER: results["PER"].append(f"{start}-{idx-1}") elif mode == Constants.BLOC: results["LOC"].append(f"{start}-{idx-1}") elif mode == Constants.BORG: results["ORG"].append(f"{start}-{idx-1}") mode = Constants.BORG start = idx return results def write_results_to_file( predictions: List[str], output_file: str = "../output/output.txt" ) -> None: results = Utils.compile_output_data(predictions) with open(output_file, 'w') as f: f.write("Type,Prediction\n") f.write("PER,") f.write(" ".join(results["PER"])) f.write("\n") f.write("LOC,") f.write(" ".join(results["LOC"])) f.write("\n") f.write("ORG,") f.write(" ".join(results["ORG"])) f.write("\n") f.write("MISC,") f.write(" ".join(results["MISC"])) f.write("\n") <file_sep>/src/constants.py class Constants: START = "<START(*)>" END = "</END(STOP)>" BPER = 0 BLOC = 1 BORG = 2 BMISC = 3 IPER = 4 ILOC = 5 IORG = 6 IMISC = 7 OTHER = 8 ALL_TAGS = {BPER, BLOC, BORG, BMISC, IPER, ILOC, IORG, IMISC, OTHER} TAG_TO_STRING = { BPER: "B-PER", BLOC: "B-LOC", BORG: "B-ORG", BMISC: "B-MISC", IPER: "I-PER", ILOC: "I-LOC", IORG: "I-ORG", IMISC: "I-MISC", OTHER: "O", } <file_sep>/src/baseline.py from collections import Counter from typing import Dict from typing import List from typing import Tuple from constants import Constants class MostFrequentClassBaseline: def __init__( self, training_token_stream: List[str], training_tag_stream: List[str], ): self.training_token_stream = training_token_stream self.training_tag_stream = training_tag_stream self.most_frequent_tag_per_token = self.compute_most_frequent_tag_per_token() def compute_tag_counts_per_token(self) -> Dict[str, Dict[str, int]]: tag_counts_per_token = {} for token, tag in zip(self.training_token_stream, self.training_tag_stream): if token == Constants.START or token == Constants.END: continue if token not in tag_counts_per_token: tag_counts_per_token[token] = Counter() tag_counts_per_token[token][tag] += 1 return tag_counts_per_token def compute_most_frequent_tag_per_token(self) -> Dict[str, str]: most_frequent_tag_per_token = {} tag_counts_per_token = self.compute_tag_counts_per_token() for token in tag_counts_per_token: most_frequent_tag = "" most_frequent_tag_count = 0 for tag in tag_counts_per_token[token]: if tag_counts_per_token[token][tag] > most_frequent_tag_count: most_frequent_tag_count = tag_counts_per_token[token][tag] most_frequent_tag = tag most_frequent_tag_per_token[token] = most_frequent_tag return most_frequent_tag_per_token def classify_test_stream( self, test_stream: Tuple[List[str], List[str], List[str]], ) -> List[str]: predictions = [] for token_stream, _, _ in test_stream: for token in token_stream: if token == Constants.START or token == Constants.END: continue predictions.append(self.most_frequent_tag_per_token[token]) return predictions <file_sep>/src/memm.py class MaxEntMarkovModel: def __init__(self): pass def main(): print("memm run") if __name__ == '__main__': main() <file_sep>/README.md # Natural Language Processing Named entity recognition -- a hidden markov model that efficiently and accurately tags "entities" within text streams with their appropriate categories. # To run NER task using baseline, HMM, and MEMM: $ python3 main.py # Requirements: - nltk - numpy - python3.6 <file_sep>/src/transition.py from collections import Counter from typing import List, Dict from constants import Constants class TransitionMatrix: def __init__( self, tag_stream: List[str], ): self.total_tag_count = self.compute_total_tag_count(tag_stream) self.unigram_counts = self.compute_unigram_counts(tag_stream) self.bigram_counts = self.compute_bigram_counts(tag_stream) self.trigram_counts = self.compute_trigram_counts(tag_stream) def compute_total_tag_count( self, tag_stream: List[str], ) -> int: total_tag_count = 0 for tag in tag_stream: if tag != Constants.START and tag != Constants.END: total_tag_count += 1 return total_tag_count def compute_unigram_counts( self, tag_stream: List[str], ) -> Dict[str, int]: unigram_counts = Counter() for token in tag_stream: unigram_counts[token] += 1 return unigram_counts def compute_bigram_counts( self, tag_stream: List[str], ) -> Dict[str, Dict[str, int]]: bigram_counts = {} prior_i_1 = tag_stream[0] for tag in tag_stream[1:]: if tag != Constants.START: if prior_i_1 not in bigram_counts: bigram_counts[prior_i_1] = Counter() bigram_counts[prior_i_1][tag] += 1 prior_i_1 = tag return bigram_counts def compute_trigram_counts( self, tag_stream: List[str], ) -> Dict[str, Dict[str, Dict[str, int]]]: trigram_counts = {} prior_i_2 = tag_stream[0] prior_i_1 = tag_stream[1] for tag in tag_stream[2:]: if tag != Constants.START and prior_i_1 != Constants.START: if prior_i_2 not in trigram_counts: trigram_counts[prior_i_2] = {} if prior_i_1 not in trigram_counts[prior_i_2]: trigram_counts[prior_i_2][prior_i_1] = Counter() trigram_counts[prior_i_2][prior_i_1][tag] += 1 prior_i_2 = prior_i_1 prior_i_1 = tag return trigram_counts def get_unigram_probability( self, tag: str, ) -> float: return self.unigram_counts[tag] / float(self.total_tag_count) def get_bigram_probability( self, prior_i_1: str, tag: str, ) -> float: if prior_i_1 not in self.bigram_counts: return 0.0 return self.bigram_counts[prior_i_1][tag] / float(self.unigram_counts[prior_i_1]) def get_trigram_probability( self, prior_i_2: str, prior_i_1: str, tag: str, ) -> float: if prior_i_2 not in self.trigram_counts or prior_i_1 not in self.trigram_counts[prior_i_2]: return 0.0 return self.self.trigram_counts[prior_i_2][prior_i_1][tag] / float(self.bigram_counts[prior_i_2][prior_i_1]) def get_bigram_interpolated_probability( self, prior_i_1: str, tag: str, ) -> float: UNIGRAM_LAMBDA = 0.05 BIGRAM_LAMBDA = 0.95 weighted_unigram_probability = UNIGRAM_LAMBDA * self.get_unigram_probability(tag) weighted_bigram_probability = BIGRAM_LAMBDA * self.get_bigram_probability(prior_i_1, tag) return weighted_unigram_probability + weighted_bigram_probability def get_trigram_interpolated_probability( self, prior_i_2: str, prior_i_1: str, tag: str, ) -> float: UNIGRAM_LAMBDA = 0.01 BIGRAM_LAMBDA = 0.09 TRIGRAM_LAMBDA = 0.90 weighted_unigram_probability = UNIGRAM_LAMBDA * self.get_unigram_probability(tag) weighted_bigram_probability = BIGRAM_LAMBDA * self.get_bigram_probability(prior_i_1, tag) weighted_trigram_probability = TRIGRAM_LAMBDA * self.get_trigram_probability(prior_i_2, prior_i_1, tag) return weighted_trigram_probability + weighted_unigram_probability + weighted_bigram_probability <file_sep>/src/main.py import time from baseline import MostFrequentClassBaseline from constants import Constants from emission import EmissionMatrix from hmm import HiddenMarkovModel from transition import TransitionMatrix from unknown import Unknown from utilities import Utils TRAINING_FILE_PATH = "../train.txt" TEST_FILE_PATH = "../test.txt" def log(msg): def fill_spaces(msg): return " " * (60 - len(msg)) elapsed = time.time() - start minutes = int(elapsed / 60) seconds = int(elapsed) % 60 print(f"{msg}{fill_spaces(msg)}Elapsed time: {minutes} min {seconds} sec") def main(): log("Starting named entity recognition task") log("Splitting training set into training and validation sets") training, validation = Utils.create_training_validation_split(TRAINING_FILE_PATH) log("Writing training and validation sets to file") Utils.write_streams_to_file(training, "./input/training.txt") Utils.write_streams_to_file(validation, "./input/validation.txt") log("Reading training file") token_stream, pos_stream, tag_stream = Utils.read_training_file(TRAINING_FILE_PATH) log("Replacing low frequency tokens from training set") token_stream, closed_vocabulary = Unknown.replace_low_frequency_tokens(token_stream) log("Reading test file") test_stream = Utils.read_test_file(TEST_FILE_PATH) log("Replacing unknown tokens from test set") test_stream = Unknown.replace_unknown_tokens(test_stream, closed_vocabulary) log("Training most frequent class baseline") baseline = MostFrequentClassBaseline(token_stream, tag_stream) log("Predicting tags using baseline") baseline_predictions = baseline.classify_test_stream(test_stream) log("Writing predictions with baseline to file") Utils.write_results_to_file(baseline_predictions, "../output/baseline_output.txt") log("Training Hidden Markov Model") hmm = HiddenMarkovModel(token_stream, tag_stream) log("Predicting tags using HMM") hmm_predictions = hmm.classify_test_stream(test_stream) log("Writing predictions with HMM to file") Utils.write_results_to_file(hmm_predictions, "../output/hmm_output.txt") if __name__ == '__main__': global start start = time.time() main()
8603011bd7ab65b8f55aabdb17eff636fc1bdff7
[ "Markdown", "Python" ]
10
Python
evantzhao/nlp-ner-analysis
ddc032c88990ea0f28cb500c5fc487c5e8765569
0a4f3d4747ac2c1cc50d22ea03c88c1bf1c96ece
refs/heads/master
<repo_name>ErnaOudman/ProgrammingAssignment2<file_sep>/cachematrix.R ## Matrix inversions might be computational differnt, especially with ## large matrices. These functions will cache the inverse when it has been ## computed. Every time it will check beforehand if the matrix ## has been inverted before. If so, the inverse will be caught from cachhe. ## makeCacheMatrix creates a special object that stores a matrix and caches ## its inverse ## The value of the matrix is set and can be gotten ## The value of the inversie is set and can bet gotten makeCacheMatrix <- function(x = matrix()) { m <- NULL set <- function(y){ x <<- y m <<- NULL } get <- function()x setInverse <- function(solve) m <<- solve getInverse <- function() m list(set = set, get = get, setInverse = setInvervse getInverse = getInverse) } ## cacheSolve computes the inverse of special "matrix" from makeCacheMatrix. When it was ## calculated before, it will get the inverse from the cache and skips the computation. cacheSolve <- function(x, ...) { ## Return a matrix that is the inverse of 'x' m <- x$getInverse() if(!is.null(m)){ ## Matrix was inverted before and result will be gotten from cache message("getting cached data") return(m) } data <- x$get() ## Matrix was not inverted before, computation will be done now m <- solve(data, ...) x$setInverse(m) m }
93d603ac027386aa2a8c1d2b9a53e3d792e542a9
[ "R" ]
1
R
ErnaOudman/ProgrammingAssignment2
8527c7ab3491183f8398ee3c8014eb1b9f3d7c57
1f6795de12be9abc40782adea1f507f4cf4c18f1
refs/heads/master
<file_sep># daily-code Daily code exercises <file_sep># frozen_string_literal: true # Given an array of integers, return a new array such that each element at # index i of the new array is the product of all the numbers in the original # array except the one at i. # For example, if our input was [1, 2, 3, 4, 5], the expected output would # be [120, 60, 40, 30, 24]. # This answer assumes that none of the values in the array are 0. def products_of_array(array) product = array.reduce(:*) array.map { |i| product / i } end array = [1, 2, 3, 4, 5] products_of_array(array) <file_sep># frozen_string_literal: true # This problem was recently asked by Google. # Given a list of numbers and a number k, return # whether any two numbers from the list add up to k. # For example, given [10, 15, 3, 7] and k of 17, return true since 10 + 7 is 17. require 'set' def array_includes_sum_of_number?(array, number) set = Set.new(array) array.any? { |n| set.include?(number - n) } end array = [10, 15, 3, 7] number = 17 array_includes_sum_of_number?(array, number) <file_sep>class Node attr_accessor :value, :left, :right def initialize(value:, left: nil, right: nil) self.value = value self.left = left self.right = right end def to_s value.to_s end end def serialize(node) queue = [node] string = '' loop do break if queue.size <= 0 current = queue.shift string += "#{current&.value}," next if current.nil? queue += [current.left, current.right] end string end def deserialize(string) string_queue = string.split(',', -1) tree = Node.new(value: string_queue.shift) queue = [] queue << tree loop do break if queue.size <= 0 current = queue.shift left = string_queue.shift right = string_queue.shift current.left = create_node(left, queue) current.right = create_node(right, queue) end tree end def create_node(node_value, queue) new_node = node_value.empty? ? nil : Node.new(value: node_value) queue << new_node unless new_node.nil? new_node end # CASE 1 d_node = Node.new(value: 'left.left') c_node = Node.new(value: 'right') b_node = Node.new(value: 'left', left: d_node) a_node = Node.new(value: 'root', left: b_node, right: c_node) new_tree = deserialize(serialize(a_node)) puts new_tree.left.left.value == 'left.left' # CASE 2 g_node = Node.new(value: 'G') f_node = Node.new(value: 'F') e_node = Node.new(value: 'E', left: g_node) d_node = Node.new(value: 'D', left: f_node) c_node = Node.new(value: 'C', left: e_node) b_node = Node.new(value: 'B', left: d_node) a_node = Node.new(value: 'A', left: b_node, right: c_node) new_tree = deserialize(serialize(a_node)) puts new_tree.right.left.value == 'E' puts new_tree.right.left.left.value == 'G'
4af459cecf0a3773d70c44147340b05e706f9866
[ "Markdown", "Ruby" ]
4
Markdown
acsalcedo/daily-code
8a4b276b8d0f4ef3ed5600c880ddf719802420ae
4ff4a5bf02c70e38f0c436a26f413c52e7384e19
refs/heads/master
<repo_name>agilesdesign/exceptum<file_sep>/src/Exceptum/Foundation/Exceptions/Handler.php <?php namespace Exceptum\Foundation\Exceptions; use Exception; use Exceptum\Facades\Exceptum; use App\Exceptions\Handler as LaravelHandler; class Handler extends LaravelHandler { /** * Render an exception into an HTTP response. * * @param \Illuminate\Http\Request $request * @param \Exception $exception * * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { return Exceptum::render($request, $exception) ?? parent::render($request, $exception); } }<file_sep>/src/Exceptum/Facades/Exceptum.php <?php namespace Exceptum\Facades; use Exceptum\Contracts\Repository; use Illuminate\Support\Facades\Facade; class Exceptum extends Facade { public static function getFacadeAccessor() { return Repository::class; } }<file_sep>/src/Exceptum/Contracts/Abettor.php <?php namespace Exceptum\Contracts; use Exception; interface Abettor { public function render($request, Exception $exception); }<file_sep>/src/Exceptum/Providers/ExceptumServiceProvider.php <?php namespace Exceptum\Providers; use Exceptum\Support\Repository; use Exceptum\Foundation\Exceptions\Handler; use Illuminate\Support\Facades\App; use Illuminate\Support\ServiceProvider; use Illuminate\Contracts\Debug\ExceptionHandler as LaravelExceptionHandler; use Exceptum\Contracts\Repository as RepositoryContract; class ExceptumServiceProvider extends ServiceProvider { /** * Bootstrap the application services. * * @return void */ public function boot() { // } /** * Register the application services. * * @return void */ public function register() { App::bind(LaravelExceptionHandler::class, Handler::class); App::singleton(RepositoryContract::class, Repository::class); } } <file_sep>/README.md # exceptum Custom Exception Handling for Laravel ### Installation ##### Include through composer `composer require agilesdesign/exceptum` ##### Add to provider list ```php 'providers' => [ Exceptum\Providers\ExceptumServiceProvider::class, ]; ``` ### Usage ##### Create an Abettor `Abettor` is synonymous with `App\Exceptions\Handler` in it's intent, but is not an extension of it. Currently it only supports implementing the response provided to the `render` method on `App\Exception\Handler` ```?php class AuthorizatonExceptionAbettor implements Abettor { public function render($request, Exception $exception) { // handle exception } } ``` ##### Register Mapping Exceptum falls back to Laravel's App\Exception\Handler class unless it knows about an Abettor responsible for Exception thrown. To tell Exceptum about an Abettor register a mapping in your `ServiceProviders` `register` method ```php public function register() { Exceptum::map(AuthorizationException::class, AuthorizationExceptionAbettor::class); } ``` <file_sep>/src/Exceptum/Contracts/Repository.php <?php namespace Exceptum\Contracts; interface Repository { public function map(string $exception, string $handler); } <file_sep>/src/Exceptum/Support/Repository.php <?php namespace Exceptum\Support; use Exception; use App\Exceptions\Handler; use Exceptum\Contracts\Repository as RepositoryContract; class Repository implements RepositoryContract { protected $map; protected $handler; /** * Repository constructor. * * @param \App\Exceptions\Handler $laravelHandler */ public function __construct(Handler $handler) { $this->handler = $handler; } /** * Add Excetion -> Abettor mapping * * @param string $exception * @param string $abettor */ public function map(string $exception, string $abettor) { $this->map[$exception] = $abettor; } /** * Resolve the appropriate Exception Handler * * @param \Exception $exception * * @return \App\Exceptions\Handler */ public function resolve(Exception $exception) { if($abettor = $this->getAbettor($exception)) { return new $abettor; } return $this->handler; } /** * Retrieve Abettor from Exception Map * * @param \Exception $exception * * @return mixed */ protected function getAbettor(Exception $exception) { return collect($this->map)->pull(get_class($exception)); } /** * Render Exception * * @param $request * @param \Exception $exception * * @return \Illuminate\Http\Response */ public function render($request, Exception $exception) { return $this->resolve($exception)->render($request, $exception) ?? parent::render($request, $exception); } }
e9dfadfd4238f67871d0039540820edaf74ceb2e
[ "Markdown", "PHP" ]
7
PHP
agilesdesign/exceptum
b986e9be971145cc4cc2b69c1e40e5ed9a5848d5
163c681fc21cb4036765dc1a26a51232d4ebf49a
refs/heads/master
<file_sep>require 'rails_helper' RSpec.describe User, type: :model do it { should validate_presence_of(:username) } it { should validate_presence_of(:password_digest) } it { should validate_length_of(:password).is_at_least(6) } it { should have_many(:goals) } it "creates a password digest" do User.create!(username: "test_user", password: "<PASSWORD>") user = User.find_by_username("test_user") expect(user.password_digest).to_not be_nil end it "ensures a session token before validation" do User.create!(username: "test_user", password: "<PASSWORD>") user = User.find_by_username("test_user") user.valid? expect(user.session_token).to_not be_nil end describe "#reset_token!" do it "sets a new session token" do User.create!(username: "test_user", password: "<PASSWORD>") user = User.find_by_username("test_user") user.valid? old_token = user.session_token user.reset_token! expect(user.session_token).to_not eq(old_token) end it "returns the new session token" do User.create!(username: "test_user", password: "<PASSWORD>") user = User.find_by_username("test_user") expect(user.reset_token!).to eq(user.session_token) end end describe "#is_password" do it "returns true if the password is correct" do User.create!(username: "test_user", password: "<PASSWORD>") user = User.find_by_username("test_user") expect(user.is_password?("password")).to be true end end describe ".find_by_credentials" do it "returns user if valid credentials" do User.create!(username: "test_user", password: "<PASSWORD>") user = User.find_by_username("test_user") found_user = User.find_by_credentials("test_user", "password") expect(found_user).to eq(user) end it "returns nil if invalid credentials" do User.create!(username: "test_user", password: "<PASSWORD>") found_user = User.find_by_credentials("test_user", "<PASSWORD>kdjf") expect(found_user).to be_nil end end end <file_sep>module TracksHelper def ugly_lyrics(lyrics) uglified = [""] lyrics.lines.each { |line| uglified << h(line) } "<pre>#{uglified.join('&#9835; ')}</pre>".html_safe end end <file_sep>require 'hand.rb' require 'rspec' describe Hand do # let(:card1) { double("card1") } # let(:card2) { double("card2") } # let(:card3) { double("card3") } # let(:card4) { double("card4") } # let(:card5) { double("card5") } # subject(:hand) { Hand.new([card1, card2, card3, card4, card5]) } describe '#initialize' do let(:card) { double("card") } subject(:hand) { Hand.new([card, card, card, card, card]) } it "should have an array of 5 cards" do allow(card).to receive(:is_a?).with(Card).and_return(true) expect(hand.cards.length).to eq(5) expect(hand.cards.all? { |card| card.is_a? Card }).to be true end end describe '#kind_of_hand' do context 'when there is a good hand' do let(:card1) { double("card1", :value => 7, :suit => :hearts) } let(:card2) { double("card2", :value => 8, :suit => :spades) } let(:card3) { double("card3", :value => 9, :suit => :hearts) } let(:card4) { double("card4", :value => 10, :suit => :diamonds) } let(:card5) { double("card5", :value => 11, :suit => :clubs) } subject(:hand) { Hand.new([card1, card2, card3, card4, card5]) } it "returns the kind of hand" do expect(hand.kind_of_hand).to eq(:straight) end end context 'where there is No Pair' do let(:card1) { double("card1", :value => 7, :suit => :hearts) } let(:card2) { double("card2", :value => 2, :suit => :spades) } let(:card3) { double("card3", :value => 9, :suit => :hearts) } let(:card4) { double("card4", :value => 10, :suit => :diamonds) } let(:card5) { double("card5", :value => 11, :suit => :clubs) } subject(:hand) { Hand.new([card1, card2, card3, card4, card5]) } it "returns the highest card" do expect(hand.kind_of_hand).to eq(11) end end end end <file_sep>require_relative 'piece.rb' class Knight < Piece include SteppingPiece def initialize(color, position, board) super(color, :N, position, board) end def to_s "N".colorize(color) end end <file_sep>json.extract! @pokemon, :id, :name, :attack, :defense, :image_url, :moves, :poke_type json.items do json.array! @pokemon.items do |item| json.id item.id json.name item.name json.pokemon_id item.pokemon_id json.price item.price json.happiness item.happiness json.image_url item.image_url end end <file_sep>require "byebug" class QuestionsBase attr_reader :id def self.find_by_id(id) data = QuestionsDatabase.instance.execute(<<-SQL, id) SELECT * FROM #{table} WHERE id = ? SQL return nil if data.empty? self.new(data.first) end def self.all data = QuestionsDatabase.instance.execute(<<-SQL) SELECT * FROM #{table} SQL return nil if data.empty? data.map { |datum| self.new(datum) } end def attributes atr = {} self.instance_variables.each do |name| fixed_name = name.to_s[1..-1] atr[fixed_name] = instance_variable_get(name) end atr end def save @id ? update : create end def update set_attributes = attributes.keys set_attributes.delete("id") set_attributes = set_attributes.map { |key| "#{key} = ?" }.join(", ") QuestionsDatabase.instance.execute(<<-SQL, *attributes.values ) UPDATE #{self.class.table} SET #{set_attributes} WHERE id = ? SQL end def create set_attributes = attributes set_attributes.delete("id") set_columns = set_attributes.keys.map { |key| "#{key}" }.join(", ") set_values = set_attributes.keys.map { |key| "?" }.join(", ") debugger QuestionsDatabase.instance.execute(<<-SQL, *set_attributes.values) INSERT INTO #{self.class.table} (#{set_columns}) VALUES (#{set_values}) SQL @id = QuestionsDatabase.instance.last_insert_row_id end end <file_sep>class Employee attr_reader :salary def initialize(name, title, salary) @name = name @title = title @salary = salary @boss = nil end def bonus(multiplier) @salary * multiplier end def add_boss(boss) @boss = boss @boss.subordinates << self end end class Manager < Employee attr_reader :subordinates def initialize(name, title, salary) super(name, title, salary) @subordinates = [] end def bonus(multiplier) subordinates_sal * multiplier end def subordinates_sal sum = 0 @subordinates.each do |employee| sum += employee.salary sum += employee.subordinates_sal if employee.is_a?(Manager) end sum end end darren = Manager.new("Darren", "TA Manager", 78000) ned = Manager.new("Ned", "Founder", 1000000) darren.add_boss(ned) shawna = Employee.new("Shawna", "TA", 12000) shawna.add_boss(darren) david = Employee.new("David", "TA", 10000) david.add_boss(darren) p ned.bonus(5) p darren.bonus(4) p david.bonus(3) <file_sep>import { connect } from 'react-redux'; import ItemDetail from './item_detail.jsx'; import { selectPokemonItem } from '../../reducers/selector.js'; const mapStateToProps = (state, ownProps) => ({ item: selectPokemonItem(state, ownProps.params.itemId) }); const mapDispatchToProps = (dispatch) => ({ }); export default connect( mapStateToProps, mapDispatchToProps )(ItemDetail); <file_sep>#SOLUTION (OURS SURELY SUCKED) class ComputerPlayer attr_accessor :previous_guess, :board_size def initialize(size) @board_size = size @matched_cards = {} @known_cards = {} @previous_guess = nil end def receive_revealed_card(pos,value) @known_cards[pos] = value end def receive_match(pos1, pos2) @matched_cards[pos1] = true @matched_cards[pos2] = true end def get_input if previous_guess second_guess else first_guess end end def unmatched_pos (pos, _) = @known_cards.find do |pos, val| @known_cards.any? do |pos2, val2| (pos != pos2 && val == val2) && !(@matched_cards[pos] || @matched_cards[pos2]) end end pos end def match_previous (pos, _) = @known_cards.find do |pos, val| pos != previous_guess && val == @known_cards[previous_guess] && !@matched_cards[pos] end pos end def first_guess unmatched_pos || random_guess end def second_guess match_previous || random_guess end def random_guess guess = nil until guess && !@known_cards[guess] guess = [rand(board_size), rand(board_size)] end guess end end # class ComputerPlayer # # def initialize(positions, name = "Bobby") # @name = name # @known_cards = Hash.new { |h, k| h[k] = [] } # @remaining_positions = positions # @matched_positions = [] # @previous_value = Hash.new { |h, k| h[k] = [] } # end # # def prompt # guess = nil # keys = @known_cards.keys.select { |el| el.size == 2 } # if keys.empty? # return @remaining_positions.sample if guessed_positions.nil? # guess = @remaining_positions.reject { |pos| guessed_positions.include?(pos) }.first # else # keys.each do |key| # next if @known_cards[key].any? { |pos| @matched_positions.include?(pos) } # guess = @known_cards[key].values.first # @known_cards[key].values.rotate! # end # end # guess # end # # def guessed_positions # @known_cards.values.inject(&:+) # end # # def receive_revealed_card(pos, face_value) # @known_cards[face_value] << pos unless @known_cards[face_value].include?(pos) # receive_match([@previous_value.values.first, pos]) if face_value == @previous_value.keys.first # @previous_value[face_value] << pos # @previous_value = Hash.new { |h, k| h[k] = [] } if @previous_value.size == 2 || @previous_value.first.size == 2 # end # # def receive_match(*positions) # @matched_positions += positions # positions.each { |pos| @remaining_positions.delete(pos) } # end # # end <file_sep># json.partial! 'api/guests/guest', guest: @guest # json.gifts do # json.array! @guest.gifts do |gift| # json.title gift.title # json.description gift.description # end # end json.partial! 'api/guests/guestgifts', guest: @guest <file_sep>require_relative 'graph' # Implementing topological sort using both Khan's and Tarian's algorithms def topological_sort_khans(vertices) sorted = [] queue = [] in_degrees = {} vertices.each do |vertex| queue.unshift(vertex) if vertex.in_count == 0 in_degrees[vertex] = vertex.in_count end until queue.empty? current = queue.pop sorted << current current.out_edges.each do |edge| destination = edge.to_vertex in_degrees[destination] -= 1 queue.unshift(destination) if in_degrees[destination] == 0 end end sorted end def visit!(vertex, visited, result) return if visited.include?(vertex) vertex.out_edges.each do |edge| visit!(edge.to_vertex, visited, result) end visited.add(vertex) result.unshift(vertex) end def topological_sort(vertices) sorted = [] visited = Set.new vertices.each { |vertex| visit!(vertex, visited, sorted) } sorted end <file_sep>DROP TABLE IF EXISTS users; DROP TABLE IF EXISTS questions; DROP TABLE IF EXISTS question_follows; DROP TABLE IF EXISTS replies; DROP TABLE IF EXISTS question_likes; CREATE TABLE users ( id INTEGER PRIMARY KEY, fname TEXT NOT NULL, lname TEXT NOT NULL ); CREATE TABLE questions ( id INTEGER PRIMARY KEY, title TEXT NOT NULL, body TEXT, user_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id) ); CREATE TABLE question_follows ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULL, question_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (question_id) REFERENCES questions(id) ); CREATE TABLE replies ( id INTEGER PRIMARY KEY, parent_id INTEGER, user_id INTEGER NOT NULL, body TEXT NOT NULL, question_id INTEGER NOT NULL, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (question_id) REFERENCES questions(id), FOREIGN KEY (parent_id) REFERENCES replies(id) ); CREATE TABLE question_likes ( id INTEGER PRIMARY KEY, user_id INTEGER NOT NULl, question_id INTEGER NOT NULL ); INSERT INTO users (fname,lname) VALUES ('Katarina','Rossi'), ('Ujwala','Aaduru'), ('Jon', 'Snow'), ('Daenerys', 'Targaryen'); INSERT INTO questions (title,body,user_id) VALUES ('What is your favorite?','color',1), ('What is RDBMS?','sql',1), ('What is RSPEC','ruby',1), ('How do you insert into tables','using sql',2), ('Where are my dragons????','seriously dude', 4), ('Is Ghost still alive?', 'Can''t remember', 1); INSERT INTO question_follows (user_id,question_id) VALUES (1, 2), (3, 2), (4, 2), (1, 3), (2, 3), (4, 1); INSERT INTO replies (user_id,body,question_id) VALUES (2,'Black',1), (3, 'Presumably', 4); INSERT INTO replies (user_id,body,question_id, parent_id) VALUES (1, 'Good. Enough are already dead.', 4, 2); INSERT INTO question_likes (user_id,question_id) VALUES (2,1), (2, 3), (2,2), (2,4), (3,2), (1, 3); <file_sep>// // const readline = require('readline'); // // const reader = readline.createInterface({ // input: process.stdin, // output: process.stdout // }); class Game { constructor (numOfDiscs) { this.towers = [[],[],[]]; for (let i = numOfDiscs; i > 0; i--) { this.towers[0].push(i); } } promptMove (reader, callBack) { // console.log(reader); this.print(); reader.question("Where do you want to move a disc from: ", (startTower) => { reader.question("Where do you want to move a disc to: ", (endTower) => { startTower = parseInt(startTower) - 1; endTower = parseInt(endTower) - 1; callBack(startTower, endTower); }); }); } isValidMove(start, end) { let startTower = this.towers[start]; let endTower = this.towers[end]; if (startTower.length === 0) { return false; } else if (startTower[startTower.length - 1] > endTower[endTower.length - 1]) { return false; } else { return true; } } move(start, end) { if (this.isValidMove(start, end)) { this.towers[end].push(this.towers[start].pop()); return true; } return false; } print () { console.log(`First Tower: ${this.towers[0]}`); console.log(`Second Tower: ${this.towers[1]}`); console.log(`Third Tower: ${this.towers[2]}`); } isWon() { return ((this.towers[0].length === 0 && this.towers[1].length === 0 ) || (this.towers[0].length === 0 && this.towers[2].length === 0 )); } run(reader, completionCallback) { if (this.isWon()) { completionCallback(); } else { this.promptMove(reader, (start, end) => { let result = this.move(start, end); if (!result) { console.log("I am an error message."); } this.run(reader, completionCallback); }); } } } module.exports = Game; // let game = new Game(3); // game.run(() => console.log("testing")); <file_sep>def windowed_max_range(array, window_size) max_range = nil array.each_index do |idx| window = array[idx, window_size] break if window.length < window_size range = window.max - window.min max_range = range if max_range.nil? || max_range < range end max_range end <file_sep>require 'card.rb' require 'rspec' describe Card do subject(:card) { Card.new(11, :hearts) } describe "#initialize" do it "initializes with a value" do expect(card.value).to eq(11) end it "initializes with a suit" do expect(card.suit).to eq(:hearts) end end end <file_sep>const APIUtil = require('./api_util.js'); class InfiniteTweets{ constructor(el){ this.$el = $(el); this.maxCreatedAt = null; this.$el.find('a.fetch-more').on("click", (e) => {this.fetchTweets(e);}) ; } fetchTweets(e){ console.log("fetched!"); let data = null; if(this.maxCreatedAt) {data = {'max_created_at': this.maxCreatedAt};} APIUtil.fetchTweets(data).then(result => { this.insertTweets(result); }); } insertTweets(result) { result.forEach((tweet) => { let $li = $('<li>'); $li.text(JSON.stringify(tweet)); this.$el.find('ul').append($li); }); if(result.length<20){ this.$el.find('a.fetch-more').remove(); console.log("no more"); } else { this.maxCreatedAt = result[result.length-1].created_at; } } } module.exports = InfiniteTweets; <file_sep>require 'byebug' class BinaryMinHeap def initialize(&prc) @store = [] @prc = prc end def count @store.length end def extract raise "heap is empty" if @store.empty? min = @store[0] @store[count - 1], @store[0] = @store[0], @store[count - 1] @store.pop self.class.heapify_down(@store, 0, &@prc) min end def peek @store[0] end def push(val) @store << val self.class.heapify_up(@store, count - 1, &@prc) end protected attr_accessor :prc, :store public def self.child_indices(len, parent_index) first_child = (parent_index * 2) + 1 second_child = (parent_index * 2) + 2 [first_child, second_child].select { |idx| idx < len } end def self.parent_index(child_index) raise "root has no parent" if child_index == 0 (child_index - 1) / 2 end def self.heapify_down(array, parent_idx, len = array.length, &prc) prc ||= Proc.new { |el1, el2| el1 <=> el2 } children = child_indices(len, parent_idx) || [] first_child, second_child = children children = children.map { |idx| array[idx] } return array if children.all? { |child| prc.call(array[parent_idx], child) <= 0 } smaller_idx = first_child unless children.length == 1 smaller_idx = prc.call(children[0], children[1]) == -1 ? first_child : second_child end array[parent_idx], array[smaller_idx] = array[smaller_idx], array[parent_idx] heapify_down(array, smaller_idx, len, &prc) end def self.heapify_up(array, child_idx, len = array.length, &prc) return array if child_idx == 0 prc ||= Proc.new { |el1, el2| el1 <=> el2 } parent_idx = parent_index(child_idx) child_val, parent_val = array[child_idx], array[parent_idx] return array unless prc.call(child_val, parent_val) < 0 array[child_idx], array[parent_idx] = parent_val, child_val heapify_up(array, parent_idx, len, &prc) end end <file_sep>require_relative 'board.rb' require 'byebug' class MinesweeperGame def initialize(size = 9) @current_tile = nil @board = Board.new(size) end def run until game_over? system("clear") @board.render operation, @current_tile = get_input @current_tile.flag if operation == "f" check_tile if operation == "r" end display_end_condition end def game_over? return false if @current_tile.nil? (@current_tile.is_bomb && @current_tile.revealed) || @board.won? end def get_input puts "Enter an operation followed by a postion" puts "f = flag/unflag, r = reveal" puts "For example: f,2,5" begin parse_input(gets.chomp) rescue puts "Invalid input, try again!" retry end end def parse_input(input) arr = input.split(',').map { |el| el =~ /\d/ ? el.to_i : el } op = arr.shift raise if @board[arr].flagged && op == "r" [op, @board[arr]] end def display_end_condition system("clear") @board.render puts @board.won? ? "You win!" : "You lose :(" end def check_tile @board.reveal_applicable(@current_tile) end end if __FILE__ == $PROGRAM_NAME game = MinesweeperGame.new game.run end <file_sep>class FixTracksIndex < ActiveRecord::Migration def change remove_index :tracks, :album_id add_index :tracks, :album_id end end <file_sep>require 'set' class WordChainer def initialize(dictionary_file_name) @dictionary = File.readlines(dictionary_file_name).map(&:chomp) @dictionary = Set.new(@dictionary) end # def adjacent_words(word) # @dictionary.select { |entry| entry != word && is_adjacent?(word, entry) } # end # # def is_adjacent?(word, entry) # return false unless entry.length == word.length # different_count = 0 # word.chars.each_with_index do |letter, idx| # different_count += 1 unless entry[idx] == letter # return false if different_count > 1 # end # true # end def adjacent_words(word) # variable name *masks* (hides) method name; references inside # `adjacent_words` to `adjacent_words` will refer to the variable, # not the method. This is common, because side-effect free methods # are often named after what they return. adjacent_words = [] # NB: I gained a big speedup by checking to see if small # modifications to the word were in the dictionary, vs checking # every word in the dictionary to see if it was "one away" from # the word. Can you think about why? word.each_char.with_index do |old_letter, i| ('a'..'z').each do |new_letter| # Otherwise we'll include the original word in the adjacent # word array next if old_letter == new_letter new_word = word.dup new_word[i] = new_letter adjacent_words << new_word if dictionary.include?(new_word) end end adjacent_words end def run(src, target) @current_words, @all_seen_words = [src], { src => nil } until @current_words.empty? || @all_seen_words.include?(target) explore_current_words end build_path(target) end def explore_current_words new_current_words = [] @current_words.each do |current_word| adjacent_words(current_word).each do |adjacent| next if @all_seen_words.include?(adjacent) new_current_words << adjacent @all_seen_words[adjacent] = current_word end end @current_words = new_current_words end def build_path(target) return [] if target.nil? path = [target] new_target = @all_seen_words[target] build_path(new_target) + path end end if __FILE__ == $PROGRAM_NAME game = WordChainer.new("dictionary.txt") game.run("market", "goblet") end <file_sep>require_relative 'piece.rb' class Bishop < Piece include SlidingPiece def initialize(color, position, board) super(color, :B, position, board) end def move_dirs [:X] end def to_s "B".colorize(color) end end <file_sep>require "tdd.rb" require 'rspec' describe Array do subject(:arr) { [1,2,1,3,3] } describe "#my_uniq" do it "removes duplicates" do expect(arr.my_uniq).to eq([1,2,3]) end end describe "#two_sum" do context "when there is a zero sum" do subject(:arr) { [-1, 0, 2, -2, 1] } it "returns pairs in proper order" do expect(arr.two_sum).to eq([[0, 4], [2, 3]]) end end context "when there is no zero sum" do it "returns an empty array" do expect(arr.two_sum).to eq([]) end end end describe "#my_transpose" do let(:rectangular) { [ [1, 2, 3], [4, 5, 6] ]} let(:square) {[ [0, 1, 2], [3, 4, 5], [6, 7, 8] ]} it "transposes a rectangular array" do expect(rectangular.my_transpose).to eq([ [1,4], [2,5], [3,6] ]) end it "transposes a square arary" do expect(square.my_transpose).to eq([ [0, 3, 6], [1, 4, 7], [2, 5, 8] ]) end end describe '#stock_picker' do context "with a profitable stock" do subject(:stocks) { [[0, 14], [1, 20], [2, 22], [3, 15], [4, 17], [5, 25], [6, 12]] } it "chooses the most profitable pair of days" do expect(stocks.stock_picker).to eq([0, 5]) end end context "with a nonprofitable stock" do subject(:stocks) {[ [0, 14], [1, 13], [2, 12], [3, 11], [4, 10], [5, 9], [6, 8]] } it "returns an empty array" do expect(stocks.stock_picker).to be_empty end end end end <file_sep>function removeDuplicates(arr) { let dupFree = []; for (let i = 0; i < arr.length; i++) { if (!dupFree.includes(arr[i])) { dupFree.push(arr[i]); } } return dupFree; } // console.log(removeDuplicates([1, 2, 1, 3, 3])); function twoSum(arr) { let output = []; for (let i = 0; i < arr.length - 1; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] + arr[j] === 0) { output.push([i, j]); } } } return output; } // console.log(twoSum([-1, 0, 2, -2, 1])); function myTranspose(arr) { let transposed = []; for (let col = 0; col < arr.length; col++) { let newRow = []; for (let row = 0; row < arr.length; row++) { newRow.push(arr[row][col]); } transposed.push(newRow); } return transposed; } // console.log(myTranspose(([ // [0, 1, 2], // [3, 4, 5], // [6, 7, 8] // ]))); <file_sep>const Util = require('./utils.js'); const MovingObject = require('./moving_object.js'); const Asteroid = require('./asteroid.js'); function Game() { this.DIM_X = 800; this.DIM_Y = 800; this.NUM_ASTEROIDS = 15; this.asteroids = []; this.addAsteroids(); } Game.prototype.addAsteroids = function() { for(let i = 0; i < this.NUM_ASTEROIDS; i++) { let randPos = this.randomPosition(); this.asteroids.push(new Asteroid(randPos, this)); } }; Game.prototype.randomPosition = function() { let x = parseInt(Math.random() * this.DIM_X); let y = parseInt(Math.random() * this.DIM_Y); return [x, y]; }; Game.prototype.draw = function(ctx) { ctx.clearRect(0,0, this.DIM_X, this.DIM_Y); this.asteroids.forEach( function(asteroid) { asteroid.draw(ctx); }); }; Game.prototype.moveObjects = function() { this.asteroids.forEach( function(asteroid) { asteroid.move(); }); }; Game.prototype.wrap = function(pos) { let [x, y] = pos; if (x < 0) { x += this.DIM_X; } else if (x > this.DIM_X) { x -= this.DIM_X; } if (y < 0) { y += this.DIM_Y; } else if (y > this.DIM_Y) { y -= this.DIM_Y; } return [x, y]; }; Game.prototype.checkCollisions = function() { for(let i = 0; i < this.asteroids.length - 1; i++) { let current = this.asteroids[i]; for(let j = i + 1; j < this.asteroids.length; j++ ) { let comparison = this.asteroids[j]; if (current.isCollidedWith(comparison)) { this.remove(current); this.remove(comparison); } } } }; Game.prototype.step = function() { this.moveObjects(); this.checkCollisions(); }; Game.prototype.remove = function(asteroid) { let idx = this.asteroids.indexOf(asteroid); this.asteroids.splice(idx, 1); }; window.Game = Game; module.exports = Game; <file_sep>class BSTNode attr_accessor :left, :right attr_reader :value def initialize(value) @value = value @left = nil @right = nil end end class BinarySearchTree def initialize @root = nil end def insert(value) if @root self.class.insert!(@root, value) else @root = BSTNode.new(value) end end def find(value) self.class.find!(@root, value) end def inorder self.class.inorder!(@root) end def postorder self.class.postorder!(@root) end def preorder self.class.preorder!(@root) end def height self.class.height!(@root) end def min self.class.min(@root) end def max self.class.max(@root) end def delete(value) self.class.delete!(@root, value) end def self.insert!(node, value) if node.nil? return BSTNode.new(value) elsif value <= node.value node.left = insert!(node.left, value) else node.right = insert!(node.right, value) end node end def self.find!(node, value) return nil unless node if node.value == value node elsif value < node.value find!(node.left, value) else find!(node.right, value) end end def self.preorder!(node) return [] unless node ordered = [node.value] ordered += preorder!(node.left) ordered += preorder!(node.right) ordered end def self.inorder!(node) return [] unless node ordered = inorder!(node.left) ordered << node.value ordered += inorder!(node.right) ordered end def self.postorder!(node) return [] unless node ordered = postorder!(node.left) ordered += postorder!(node.right) ordered << node.value ordered end def self.height!(node) return -1 unless node left = 1 + height!(node.left) right = 1 + height!(node.right) left > right ? left : right end def self.max(node) return nil unless node if node.right return max(node.right) end node end def self.min(node) return nil unless node if node.left return min(node.left) end node end def self.delete_min!(node) return nil unless node return node.right unless node.left node.left = delete_min!(node.left) node end def self.delete!(node, value) return nil unless node if node.value == value return node.right unless node.left return node.left unless node.right replacement = node.right.min replacement.right = delete_min!(node.right) replacement.left = node.left return replacement elsif value < node.value node.left = delete!(node.left, value) else node.right = delete!(node.right, value) end node end end <file_sep>require 'set' # Dynamic Programming practice # NB: you can, if you want, define helper functions to create the necessary caches as instance variables in the constructor. # You may find it helpful to delegate the dynamic programming work itself to a helper method so that you can # then clean out the caches you use. You can also change the inputs to include a cache that you pass from call to call. class DPProblems def initialize @fibs_cache = { 1 => 1, 2 => 1 } @knapsack_cache = {} @str_cache = Hash.new { |h, k| h[k] = {} } @maze_cache = {} @maze_cache[:seen] = Set.new # Use this to create any instance variables you may need end # Takes in a positive integer n and returns the nth Fibonacci number # Should run in O(n) time def fibonacci(n) return nil if n < 1 return @fibs_cache[n] if @fibs_cache[n] ans = fibonacci(n - 1) + fibonacci(n - 2) @fibs_cache[n] = ans end # Make Change: write a function that takes in an amount and a set of coins. Return the minimum number of coins # needed to make change for the given amount. You may assume you have an unlimited supply of each type of coin. # If it's not possible to make change for a given amount, return nil. You may assume that the coin array is sorted # and in ascending order. #pseudo code: # return amt if its in the cache # return infinity if the amount is less than the smallest coin # set the answer to start as infinity # go through each coin # break if the coin is too big # set num coins to 1 for current coin plus change for the remaining amount # set ans to num coins unless num_coins is bigger than current (valid) ans # return and cache the ans if it is an Integer, otherwise set to infinity def make_change(amt, coins, coin_cache = { 0 => 0 }) return coin_cache[amt] if coin_cache[amt] return 0.0 / 0.0 if amt < coins[0] ans = 0.0 / 0.0 coins.each do |coin| break if coin > amt num_coins = 1 + make_change(amt - coin, coins, coin_cache) ans = num_coins unless ans.is_a?(Integer) && num_coins > ans end coin_cache[amt] = ans.is_a?(Integer) ? ans : 0.0 / 0.0 end # Knapsack Problem: write a function that takes in an array of weights, an array of values, and a weight capacity # and returns the maximum value possible given the weight constraint. For example: if weights = [1, 2, 3], # values = [10, 4, 8], and capacity = 3, your function should return 10 + 4 = 14, as the best possible set of items # to include are items 0 and 1, whose values are 10 and 4 respectively. Duplicates are not allowed -- that is, you # can only include a particular item once. def knapsack(weights, values, capacity) situation = [weights.length, capacity] return @knapsack_cache[situation] if @knapsack_cache.key?([situation]) if weights.empty? || capacity == 0 0 elsif weights[0] > capacity knapsack(weights[1..-1], values[1..-1], capacity) else with_item = knapsack(weights[1..-1], values[1..-1], capacity - weights[0]) without_item = knapsack(weights[1..-1], values[1..-1], capacity) result = [with_item + values[0], without_item].max @knapsack_cache[situation] = result end end # Stair Climber: a frog climbs a set of stairs. It can jump 1 step, 2 steps, or 3 steps at a time. # Write a function that returns all the possible ways the frog can get from the bottom step to step n. # For example, with 3 steps, your function should return [[1, 1, 1], [1, 2], [2, 1], [3]]. # NB: this is similar to, but not the same as, make_change. Try implementing this using the opposite # DP technique that you used in make_change -- bottom up if you used top down and vice versa. def stair_climb(n) ways_table = build_ways_table(n) ways_table[n] end def build_ways_table(n) ways = [[[]], [[1]], [[1, 1], [2]]] (3..n).each do |stair_height| ways_for_height = [] (1..3).each do |current_jump| ways[stair_height - current_jump].each do |previous_way| new_way = previous_way + [current_jump] ways_for_height << new_way end end ways << ways_for_height end ways end # String Distance: given two strings, str1 and str2, calculate the minimum number of operations to change str1 into # str2. Allowed operations are deleting a character ("abc" -> "ac", e.g.), inserting a character ("abc" -> "abac", e.g.), # and changing a single character into another ("abc" -> "abz", e.g.). def str_distance(str1, str2) return @str_cache[str1][str2] if @str_cache[str1][str2] return str1.length if str2.nil? return str2.length if str1.nil? if str1 == str2 @str_cache[str1][str2] = 0 return 0 end if str1[0] == str2[0] @str_cache[str1][str2] = str_distance(str1[1..-1], str2[1..-1]) else replace_dist = 1 + str_distance(str1[1..-1], str2[1..-1]) delete_dist = 1 + str_distance(str1[1..-1], str2) insert_dist = 1 + str_distance(str1, str2[1..-1]) @str_cache[str1][str2] = [replace_dist, delete_dist, insert_dist].min end @str_cache[str1][str2] end # Maze Traversal: write a function that takes in a maze (represented as a 2D matrix) and a starting # position (represented as a 2-dimensional array) and returns the minimum number of steps needed to reach the edge of the maze (including the start). # Empty spots in the maze are represented with ' ', walls with 'x'. For example, if the maze input is: # [['x', 'x', 'x', 'x'], # ['x', ' ', ' ', 'x'], # ['x', 'x', ' ', 'x']] # and the start is [1, 1], then the shortest escape route is [[1, 1], [1, 2], [2, 2]] and thus your function should return 3. def maze_escape(maze, start) distance = calculate_escape(maze, start) @maze_cache = {} # reset cache @maze_cache[:seen] = Set.new distance end def calculate_escape(maze, start) return @maze_cache[start] if @maze_cache[start] @maze_cache[:seen] << start if on_edge?(maze, start) @maze_cache[start] = 1 return 1 end x, y = start all_moves = [[x, y + 1], [x, y - 1], [x - 1, y], [x + 1, y]] possible_moves = all_moves.select do |pos| maze[pos[0]][pos[1]] == ' ' && !@maze_cache[:seen].include?(pos) end minimum = nil possible_moves.each do |move| if on_edge?(maze, move) @maze_cache[start] = 2 return 2 end dist = calculate_escape(maze, move) minimum = dist if minimum.nil? || (dist && dist < minimum) end @maze_cache[start] = (minimum.nil? ? nil : 1 + minimum) end def on_edge?(maze, space) (space[0] == 0 || space[1] == 0) || (space[0] == maze.length - 1 || space[1] == maze[0].length - 1) end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) User.create(user_name: "<NAME>") User.create(user_name: "<NAME>") User.create(user_name: "<NAME>") Poll.create(title: "All Your Faves", user_id: 1) Poll.create(title: "FOOD", user_id: 2) Poll.create(title: "Citys", user_id: 2) Question.create(poll_id: 1, text: "What's your favorite animal?") AnswerChoice.create(text: "Cheetah", question_id: 1) AnswerChoice.create(text: "Bobcat", question_id: 1) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 1) Question.create(poll_id: 1, text: "What's your favorite color?") AnswerChoice.create(text: "Turqiouse", question_id: 2) AnswerChoice.create(text: "Burgundy", question_id: 2) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 2) Question.create(poll_id: 1, text: "What's your favorite movie?") AnswerChoice.create(text: "Elf", question_id: 3) AnswerChoice.create(text: "Dune", question_id: 3) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 3) Question.create(poll_id: 1, text: "What's your favorite band?") AnswerChoice.create(text: "Tool", question_id: 4) AnswerChoice.create(text: "The Weeknd", question_id: 4) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 4) Question.create(poll_id: 2, text: "What's your favorite food?") AnswerChoice.create(text: "Pasta", question_id: 5) AnswerChoice.create(text: "The YAM", question_id: 5) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 5) Question.create(poll_id: 2, text: "Tomato or cucumber?") AnswerChoice.create(text: "tomato", question_id: 6) AnswerChoice.create(text: "Cucumber", question_id: 6) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 6) Question.create(poll_id: 3, text: "New York or San Francisco?") AnswerChoice.create(text: "SF", question_id: 7) AnswerChoice.create(text: "New York", question_id: 7) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 7) Question.create(poll_id: 3, text: "Pick your favorite city?") AnswerChoice.create(text: "Rome", question_id: 8) AnswerChoice.create(text: "Milan", question_id: 8) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 8) Question.create(poll_id: 3, text: "Which Coast") AnswerChoice.create(text: "West", question_id: 9) AnswerChoice.create(text: "East", question_id: 9) AnswerChoice.create(text: "Ivory", question_id: 9) AnswerChoice.create(text: "Giraffe!!!!!!!!", question_id: 9) Response.create(user_id: 3, answer_id: 1) Response.create(user_id: 2, answer_id: 2) Response.create(user_id: 2, answer_id: 4) Response.create(user_id: 3, answer_id: 8) Response.create(user_id: 2, answer_id: 9) Response.create(user_id: 1, answer_id: 9) Response.create(user_id: 2, answer_id: 28) Response.create(user_id: 3, answer_id: 13) Response.create(user_id: 2, answer_id: 12) Response.create(user_id: 3, answer_id: 11) Response.create(user_id: 2, answer_id: 6) Response.create(user_id: 1, answer_id: 2) Response.create(user_id: 3, answer_id: 14) Response.create(user_id: 2, answer_id: 22) Response.create(user_id: 1, answer_id: 25) <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) Cat.create( name: 'Finn', color: 'tabby', sex: 'M', birth_date: "2013/01/20") Cat.create( name: 'Storm', color: 'silver', sex: 'M', birth_date: "2006/09/13") Cat.create( name: 'Sasha', color: 'tabby', sex: 'F', birth_date: "1985/10/13") Cat.create( name: 'tuhyfu', color: 'white', sex: 'F', birth_date: "2014/01/22") Cat.create( name: 'Snowball', color: 'white', sex: 'F', birth_date: "2012/01/20") Cat.create( name: 'Kitty Chaos', color: 'tabby', sex: 'F', birth_date: "1990/06/05") Cat.create( name: 'Cheeto', color: 'orange', sex: 'M', birth_date: "2015/03/30") <file_sep>json.partial! 'api/parties/party', party: @party json.guests do json.array! @party.guests, partial: 'api/guests/guestgifts', as: :guest end <file_sep>require 'addressable/uri' require 'rest-client' def index_users url = Addressable::URI.new( scheme: 'http', host: 'localhost', port: 3000, path: '/users/sloth' ).to_s puts RestClient.get(url) end def do_something url = Addressable::URI.new( scheme: 'http', host: 'localhost', port: 3000, path: '/users/5.json', query_values: { 'some_category[a_key]' => 'another value', 'some_category[a_second_key]' => 'yet another value', 'some_category[inner_inner_hash][key]' => 'value', 'something_else' => 'aaahhhhh' } ).to_s puts RestClient.get(url) end def create_user(name, email) url = Addressable::URI.new( scheme: 'http', host: 'localhost', port: 3000, path: '/users.json' ).to_s puts RestClient.post( url, { user: { name: name, email: email } } ) end def create_fail(name) url = Addressable::URI.new( scheme: 'http', host: 'localhost', port: 3000, path: '/users.json' ).to_s puts RestClient.post( url, { user: { name: name } } ) end # create_user("Samantha", "<EMAIL>") create_fail("Maggie") #index_users # do_something <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; class Tabs extends React.Component { constructor(props) { super(props); this.state = {index: 0}; this.updateIndex = this.updateIndex.bind(this); } updateIndex(idx) { return ()=> this.setState({index: idx}); } makeList() { return this.props.tabArray.map((tab,idx)=>{ return <li key={idx} onClick={this.updateIndex(idx)}>{tab.title}</li>; }); } render() { console.log(this.state.index); return( <div className="tab" > <ul> {this.makeList()} </ul> <article><p>{this.props.tabArray[this.state.index].content}</p></article> </div> ); } } export default Tabs; <file_sep>import React from 'react'; import { withRouter } from 'react-router'; class PokemonForm extends React.Component { constructor(props) { super(props); this.state = { name: "", attack: "", defense: "", poke_type: "", moves: [], image_url: "" }; this.update = this.update.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } errors() { if (this.props.errors) { return ( this.props.errors.map((error, i) => ( <li key={i}>{error}</li> )) ); } } handleSubmit(e) { e.preventDefault(); this.props.createNewPokemon({pokemon: this.state}).then((newPokemon) => { this.props.router.push(`pokemon/${newPokemon.id}`); }); this.setState({ name: "", attack: "", defense: "", poke_type: "", moves: [], image_url: "" }); } update(property) { switch(property) { case "moves": return e => { return this.setState({moves: e.target.value.split(", ")}); }; default: return e => this.setState({[property]: e.target.value}); } } render () { const types = [ "fire", "electric", "normal", "ghost", "psychic", "water", "bug", "dragon", "grass", "fighting", "ice", "flying", "poison", "ground", "rock", "steel" ]; return ( <section> <h3>Create New Pokemon</h3> <ul> {this.errors()} </ul> <form onSubmit={this.handleSubmit}> <input onChange={this.update('name')} key="new-name" placeholder="Name" value={this.state.name}></input> <br /> <input onChange={this.update('image_url')} key="new-img" placeholder="Image Url" value={this.state.image_url}></input> <br /> <select onChange={this.update('poke_type')} key="new-type" > <option key="default" selected disabled>{"Choose a Type!"}</option> {types.map((type) => <option key={type} value={type}>{type}</option>)} </select> <br /> <input onChange={this.update('attack')} key="new-attack" placeholder="Attack" value={this.state.attack}></input> <br /> <input onChange={this.update('defense')} key="new-defense" placeholder="Defense" value={this.state.defense}></input> <br /> <input onChange={this.update('moves')} key="new-moves" placeholder="Moves" value={this.state.moves.join(", ")}></input> <br /> <button>Submit</button> </form> </section> ); } } export default withRouter(PokemonForm); <file_sep>/******/ (function(modules) { // webpackBootstrap /******/ // The module cache /******/ var installedModules = {}; /******/ // The require function /******/ function __webpack_require__(moduleId) { /******/ // Check if module is in cache /******/ if(installedModules[moduleId]) /******/ return installedModules[moduleId].exports; /******/ // Create a new module (and put it into the cache) /******/ var module = installedModules[moduleId] = { /******/ exports: {}, /******/ id: moduleId, /******/ loaded: false /******/ }; /******/ // Execute the module function /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__); /******/ // Flag the module as loaded /******/ module.loaded = true; /******/ // Return the exports of the module /******/ return module.exports; /******/ } /******/ // expose the modules object (__webpack_modules__) /******/ __webpack_require__.m = modules; /******/ // expose the module cache /******/ __webpack_require__.c = installedModules; /******/ // __webpack_public_path__ /******/ __webpack_require__.p = ""; /******/ // Load entry module and return exports /******/ return __webpack_require__(0); /******/ }) /************************************************************************/ /******/ ([ /* 0 */ /***/ function(module, exports, __webpack_require__) { const DOMNodeCollection = __webpack_require__(1); function $1(argument) { if (argument instanceof HTMLElement) { return new DOMNodeCollection([argument]); } else { let nodes = document.querySelectorAll(argument); return new DOMNodeCollection(Array.from(nodes)); } } window.$1 = $1; /***/ }, /* 1 */ /***/ function(module, exports) { class DOMNodeCollection { constructor(els) { this.els = els; } html (string) { if (string === undefined) { return this.els[0].innerHTML; } else { for (let i = 0; i < this.els.length; i++) { this.els[i].innerHTML = string; } } } empty () { for (let i = 0; i < this.els.length; i++) { this.els[i].innerHTML = ""; } } append (addition) { if (addition instanceof DOMNodeCollection) { for (let i = 0; i < addition.els.length; i++) { for (let j = 0; j < this.els.length; j++) { this.els[j].innerHTML += addition.els[i].outerHTML; } } } else { for (let k = 0; k < this.els.length; k++) { this.els[k].innerHTML += addition; } } } attr (attributeName, value) { if (value === undefined) { return this.els[0].getAttribute(attributeName); } else { for (let k = 0; k < this.els.length; k++) { this.els[k].setAttribute(attributeName, value); } } } addClass (className) { for (let k = 0; k < this.els.length; k++) { this.els[k].classList.add(className); } } removeClass (classes) { if (classes !== undefined) { classes = classes.split(" "); } for (let k = 0; k < this.els.length; k++) { if (classes === undefined) { this.els[k].className = ""; } else { this.els[k].classList.remove(...classes); } } } children () { let kids = []; for (let k = 0; k < this.els.length; k++) { kids = kids.concat(Array.from(this.els[k].children)); } return new DOMNodeCollection(kids); } parent () { let parents = []; for (let k = 0; k < this.els.length; k++) { let parent = this.els[k].parentNode; if (!(parents.includes(parent))){ parents.push(parent); } } return new DOMNodeCollection(parents); } remove () { for (let k = 0; k < this.els.length; k++) { let parent = this.els[k].parentNode; parent.removeChild(this.els[k]); } this.els = []; } on (type, fn) { for (let k = 0; k < this.els.length; k++) { let el = this.els[k]; el.addEventListener(type, fn); if (el.cbs === undefined) { el.cbs = {}; } el.cbs[type] = fn; } } off (type) { for (let k = 0; k < this.els.length; k++) { let el = this.els[k]; el.removeEventListener(type, el.cbs[type]); } } } module.exports = DOMNodeCollection; /***/ } /******/ ]);<file_sep>require_relative "heap" require_relative "max_heap" class Array def min_heap_sort! (2..self.length).each do |length| BinaryMinHeap.heapify_up(self, length - 1, length) end self.length.downto(2) do |length| self[length - 1], self[0] = self[0], self[length - 1] BinaryMinHeap.heapify_down(self, 0, length - 1) end self.reverse! end def heap_sort! mid = length / 2 mid.downto(0) do |idx| BinaryMaxHeap.sift_down(self, idx, self.length) end self.length.downto(1) do |len| BinaryMaxHeap.extract(self, len) end end end <file_sep>function MovingObject(options) { this.pos = options.pos; this.vel = options.vel; this.radius = options.radius; this.color = options.color; this.game = options.game; } MovingObject.prototype.draw = function(ctx) { }; MovingObject.prototype.draw = function(ctx) { ctx.fillStyle = this.color; ctx.beginPath(); ctx.arc( this.pos[0], this.pos[1], this.radius, 0, 2 * Math.PI, false ); ctx.fill(); }; MovingObject.prototype.move = function() { let newX = this.pos[0] + this.vel[0]; let newY = this.pos[1] + this.vel[1]; this.pos = this.game.wrap([newX, newY]); }; MovingObject.prototype.isCollidedWith = function(otherObject) { let [x1, y1] = this.pos; let [x2, y2] = otherObject.pos; let sum = this.radius + otherObject.radius; let distance = Math.sqrt(Math.pow((x1 - x2), 2) + Math.pow((y1 - y2), 2)); if (distance < sum) { return true; } else { return false; } }; window.MovingObject = MovingObject; module.exports = MovingObject; // Dist([x_1, y_1], [x_2, y_2]) = sqrt((x_1 - x_2) ** 2 + (y_1 - y_2) ** 2) <file_sep>import React from 'react'; import ReactDOM from 'react-dom'; class Weather extends React.Component { constructor() { super(); this.state = { weather: null, location: null }; } componentDidMount() { this.state.location = navigator.geolocation; this.state.location.getCurrentPosition((pos)=>this.getWeather(pos)); } getWeather(pos) { const lat = pos.coords.latitude; const lon = pos.coords.longitude; const xhr = new XMLHttpRequest(); let that = this; xhr.onreadystatechange = function() { if (xhr.status == 200) { that.setState({weather: xhr.responseText}); } }; xhr.open("GET", `http://api.openweathermap.org/data/2.5/weather?lat=${lat}&lon=${lon}&appid=8060e3a8d1e26a20a92dcea9baf95422`, true); xhr.send(); } render() { const main = this.state.weather !== null ? this.state.weather.weather.main : 'atom shut up'; const temp = this.state.weather !== null ? this.state.weather.main.temp : 'atom shut up'; return ( <div> {main} {temp} {"hello?"} </div> ); } } export default Weather; <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rails db:seed command (or created alongside the database with db:setup). # # Examples: # # movies = Movie.create([{ name: 'Star Wars' }, { name: 'Lord of the Rings' }]) # Character.create(name: 'Luke', movie: movies.first) Todo.create([ {title: 'get a dog', body: 'we need to get a dog', done: false}, {title: 'wash a dog', body: 'we need to wash a dog', done: false}, {title: 'get a car', body: 'we needed to get a car', done: true}, {title: 'wash a car', body: 'we washed a car', done: true} ]) <file_sep>class AddColumnsToCatRentalRequest < ActiveRecord::Migration def change add_column :cat_rental_requests, :cat_id, :integer, null: false add_column :cat_rental_requests, :start_date, :date, null: false add_column :cat_rental_requests, :end_date, :date, null: false add_column :cat_rental_requests, :status, :string, null: false, default: "PENDING" add_index(:cat_rental_requests, :cat_id) end end <file_sep>class UpdateVisits < ActiveRecord::Migration def change remove_index :visits, :user_id remove_index :visits, :url_id add_index :visits, :user_id add_index :visits, :url_id end end <file_sep>require 'colorize' require_relative 'cursor.rb' require_relative 'board.rb' class Display def initialize(board) @cursor = Cursor.new([0,0], board) @board = board end def render display = Array.new(8) { Array.new(8) } system "clear" @board.grid.each_with_index do |row, row_idx| row.each_with_index do |el, col_idx| if [row_idx, col_idx] == @cursor.cursor_pos color = ( @cursor.selected ? :yellow : :green ) el = el.to_s.colorize( :background => color) end display[row_idx][col_idx] = el end end display.each do |row| puts row.join(" | ") end end def move_cur move_from = nil move_to = nil loop do render pos = @cursor.get_input if move_from.nil? move_from = pos else move_to = pos end if move_to @board.move_piece(move_from, move_to) move_from, move_to = nil, nil end end end end if __FILE__ == $PROGRAM_NAME board = Board.new a = Display.new(board) a.move_cur end <file_sep>def first_anagram?(string1, string2) # O(n!) string1.chars.permutation.to_a.include?(string2.chars) end def second_anagram?(string1, string2) # O(n^2) letters1 = string1.chars letters2 = string2.chars to_delete = [] letters1.each do |letter1| letters2.each do |letter2| to_delete << letter1 if letter1 == letter2 end end to_delete.each do |letter| letters1.delete(letter) letters2.delete(letter) end letters1.empty? && letters2.empty? end def third_anagram?(string1, string2) # O(nlogn) string1.chars.sort == string2.chars.sort end def fourth_anagram?(string1, string2) # O(n) string1_freq = Hash.new(0) string2_freq = Hash.new(0) string1.chars.each { |letter| string1_freq[letter] += 1 } string2.chars.each { |letter| string2_freq[letter] += 1 } string1_freq == string2_freq end def fifth_anagram?(string1, string2) # O(n) string1_freq = Hash.new(0) string1.chars.each { |letter| string1_freq[letter] += 1 } string2.chars.each { |letter| string1_freq[letter] -= 1 } string1_freq.values.all? { |freq| freq == 0 } end def another_anagram?(string1, string2) # O(n^2) string1_freq = Hash.new(0) string2_chars = string2.chars string1.chars.each { |letter| string1_freq[letter] += 1 } string2_chars.each do |letter| return false unless string2_chars.count(letter) == string1_freq[letter] end true end <file_sep>class Cat < ActiveRecord::Base CAT_COLORS = %w(white black orange tabby silver calico).freeze validates :name, :birth_date, :sex, :color, presence: true validates :sex, inclusion: { in: %w(M F) } validates :color, inclusion: { in: CAT_COLORS } has_many :cat_rental_requests def age Time.now.year - birth_date.year end end <file_sep>require_relative "king.rb" require_relative "queen.rb" require_relative "rook.rb" require_relative "bishop.rb" require_relative "knight.rb" require_relative "nullpiece.rb" require_relative "pawn.rb" class Board attr_reader :grid def initialize @grid = Array.new(8) { Array.new(8) } populate end def populate @grid.each_with_index do |row, row_num| row.each_index do |col| if row_num == 0 || row_num == 7 all_the_kings_men(row_num) elsif row_num == 1 || row_num == 6 minions_assemble(row_num) else @grid[row_num][col] = NullPiece.instance end end end end def minions_assemble(row_num) color = (row_num == 1 ? :magenta : :green) 8.times do |col| pos = [row_num, col] self[pos] = Pawn.new(color, pos, self) end end def all_the_kings_men(row_num) color = (row_num == 0 ? :magenta : :green) 8.times do |col| pos = [row_num, col] case col when 0, 7 self[pos] = Rook.new(color, pos, self) when 1, 6 self[pos] = Knight.new(color, pos, self) when 2, 5 self[pos] = Bishop.new(color, pos, self) when 3 self[pos] = Queen.new(color, pos, self) when 4 self[pos] = King.new(color, pos, self) end end end def [](pos) row, col = pos @grid[row][col] end def []=(pos, val) row, col = pos @grid[row][col] = val end def in_bounds?(pos) row, col = pos row.between?(0, 7) && col.between?(0, 7) end def move_piece(start_pos, end_pos) current_piece = self[start_pos] raise "No piece to move." if current_piece.is_a? NullPiece raise "Piece cannot move there." unless current_piece.moves.include?(end_pos) self[end_pos] = current_piece current_piece.position = end_pos self[start_pos] = NullPiece.instance end end <file_sep># == Schema Information # # Table name: responses # # id :integer not null, primary key # answer_id :integer not null # user_id :integer not null # created_at :datetime # updated_at :datetime # class Response < ActiveRecord::Base validates :answer_id, :user_id, presence: true validate :not_duplicate_response, :not_own_poll belongs_to :respondent, primary_key: :id, foreign_key: :user_id, class_name: :User belongs_to :answer_choice, primary_key: :id, foreign_key: :answer_id, class_name: :AnswerChoice has_one :question, through: :answer_choice, source: :question has_one :poll, through: :question, source: :poll def sibling_responses self.question.responses.where.not("responses.id = ?", self.id) end private def respondent_already_answered? sibling_responses.exists?(user_id: self.user_id) end def not_duplicate_response if respondent_already_answered? errors[:respondent] << "can't respond to a question twice" end end def not_own_poll if self.poll.author.id == user_id errors[:author] << "can't respond to own poll" end end end <file_sep>require 'byebug' def range(min, max) return [] if max < min [min] + range(min + 1, max) end def range_iter(min, max) return [] if max < min n = min final_range = [] until n > max final_range << n n += 1 end final_range end def sum_array_iter(nums) sum = 0 nums.each { |el| sum += el } sum end def sum_array(nums) return 0 if nums.empty? nums.first + sum_array(nums[1..-1]) end def exponent_1(num, exp) return 1 if exp == 0 num * exponent_1(num, exp - 1) end # def exponent_2(num, exp) # return 1 if exp == 0 # return num if exp == 1 # if exp.even? # new_num = exponent_2(num, exp / 2) # new_num * new_num # else # new_num = exponent_2(num, (exp - 1) / 2) # num * new_num * new_num # end # end #SOLUTION: def exp2(base, power) return 1 if power == 0 half = exp2(base, power / 2) if power.even? half * half else # note that (power / 2) == ((power - 1) / 2) if power.odd? base * half * half end end def deep_dup(arr) duplicate = [] arr.each do |el| if el.is_a?(Array) duplicate << deep_dup(el) else duplicate << el end end duplicate end #ONE LINE SOLUTIONS def dd_inject inject([]) { |dup, el| dup << (el.is_a?(Array) ? dd_inject(el) : el) } end # Beware map! The ultimate one-liner. def dd_map map { |el| el.is_a?(Array) ? dd_map(el) : el } end def fibonacci_iter(n) return [] if n == 0 return [0] if n == 1 fibs = [0, 1] until fibs.length > n fibs << (fibs[-2] + fibs[-1]) end fibs end def fibonacci(n) return [0, 1].take(n) if n <= 2 previous = fibonacci(n - 1) previous << (previous[-2] + previous[-1]) end def permutations(arr) return [arr] if arr.length <= 1 perms = permutations(arr[0..-2]) digit = arr[-1] all_perms = [] (0...arr.length).each do |idx| perms.each do |subarray| all_perms << subarray[0...idx] + [digit] + subarray[idx..-1] # all_perms << subarray.dup.insert(idx, digit) end end all_perms end #bsearch solution which is totally cool # def bsearch(nums, target) # # nil if not found; can't find anything in an empty array # return nil if nums.empty? # # probe_index = nums.length / 2 # case target <=> nums[probe_index] # when -1 # # search in left # bsearch(nums.take(probe_index), target) # when 0 # probe_index # found it! # when 1 # # search in the right; don't forget that the right subarray starts # # at `probe_index + 1`, so we need to offset by that amount. # sub_answer = bsearch(nums.drop(probe_index + 1), target) # (sub_answer.nil?) ? nil : (probe_index + 1) + sub_answer # end # # # Note that the array size is always decreasing through each # # recursive call, so we'll either find the item, or eventually end # # up with an empty array. # end def bsearch(array, target) return nil if array.length <= 1 && array[0] != target mid_idx = (array.length - 1) / 2 if array[mid_idx] == target mid_idx elsif array[mid_idx] < target response = bsearch(array[(mid_idx + 1)..-1], target) response.nil? ? nil : response + mid_idx + 1 else bsearch(array[0...mid_idx], target) end end def merge_sort(arr) return arr if arr.length <= 1 mid = (arr.length - 1) / 2 arr1 = merge_sort(arr[0..mid]) arr2 = merge_sort(arr[(mid + 1)..-1]) merge(arr1, arr2) end #SOLUTION def merge(left, right) merged_array = [] until left.empty? || right.empty? merged_array << ((left.first < right.first) ? left.shift : right.shift) end merged_array + left + right end # def merge(arr1, arr2) # merged = [] # (arr1.length + arr2.length).times do # if arr1.empty? # return merged + arr2 # elsif arr2.empty? # return merged + arr1 # elsif arr1[0] > arr2[0] # merged << arr2.shift # else # merged << arr1.shift # end # end # merged # end def subsets(arr) return [[]] if arr.empty? subsets_arr = [] cur_el = arr[0] prior_subs = subsets(arr[1..-1]) prior_subs.each do |subset| subsets_arr << subset.dup.push(cur_el) end subsets_arr + prior_subs end #SOLUTION # def subsets(arr) # return [[]] if arr.empty? # subs = subsets(arr.take(arr.count - 1)) # subs.concat(subs.map { |sub| sub + [arr.last] }) # end def greedy_make_change(amt, coins) return [] if target == 0 return nil if coins.none? { |coin| coin <= target } return [amt] if coins.include?(amt) best_coin = coins.reject { |coin| coin > amt }.max remaining = amt - best_coin [best_coin] + greedy_make_change(remaining, coins) end def make_better_change(amt, coins) return [amt] if coins.include?(amt) return [] if amt == 0 best_answer = nil valid_coins = coins.reject { |coin| coin > amt} valid_coins.each do |coin| other_coins = make_better_change((amt - coin), coins) next if other_coins.nil? potential_answer = [coin] + other_coins best_answer = potential_answer if best_answer.nil? || potential_answer.length < best_answer.length end best_answer end <file_sep>class QuickSort # Quick sort has average case time complexity O(nlogn), but worst # case O(n**2). # Not in-place. Uses O(n) memory. def self.sort1(array) return array if array.length < 2 pivot = array[0] left, right = [], [] (1...array.length).each do |idx| if array[idx] < pivot left << array[idx] else right << array[idx] end end sort1(left) + [pivot] + sort1(right) end # In-place. def self.sort2!(array, start = 0, length = array.length, &prc) return array if length < 2 pivot_idx = partition(array, start, length, &prc) left_len = pivot_idx - start right_len = length - 1 - left_len sort2!(array, 0, left_len, &prc) # sort left sort2!(array, pivot_idx + 1, right_len, &prc) # sort right array end def self.partition(array, start, length, &prc) prc ||= Proc.new { |el1, el2| el1 <=> el2 } # random between start and length + start - 1 # random_pivot = start + rand(length - 1) # move random pivot to starting element # array[start], array[random_pivot] = array[random_pivot], array[start] wall = start + 1 (wall...(start + length)).each do |idx| next unless prc.call(array[start], array[idx]) > 0 array[wall], array[idx] = array[idx], array[wall] wall += 1 end pivot_idx = wall - 1 array[start], array[pivot_idx] = array[pivot_idx], array[start] pivot_idx end end <file_sep>const APIUtil = require('./api_util.js'); class TweetCompose{ constructor(form){ this.$form = $(form); this.content = this.$form.find('textarea'); this.content.on("keydown", (e) => this.counter(e)); this.$form.find("input[type='Submit']").on("click", (e) => {this.submit(e);}); $('a.remove-mentioned-user').on("click", (e) => {this.removeMentionedUser(e);}); this.$form.find("a.add-mentioned-user").on("click", (e) => {this.addMentionedUser(e);}); } submit(e){ e.preventDefault(); this.$form.prop('disabled', true); let data = this.$form.serializeJSON(); APIUtil.createTweet(data).then((res) => this.handleSuccess(res)); } handleSuccess(res) { let ul = this.$form.data('tweets-ul'); window.res = res; let $tweetString = $(`<li>${res.content} -- <a href='users/${res.user_id}'>${res.user.username}</a> -- ${res.updated_at}</li>`); $(ul).prepend($tweetString); this.clearInput(); this.$form.prop('disabled', false); } clearInput () { this.content.val(""); $('.chars-left').text("140"); this.$form.find('div.mentioned-users').empty(); } counter(e) { let counterChar = this.content.val().length; let counterText = String(139 - counterChar); $('.chars-left').text(counterText); } addMentionedUser(e) { let template = this.$form.find('script').html(); this.$form.find('.mentioned-users').append(template); this.$form.find('a.remove-mentioned-user').on("click", (x) => {this.removeMentionedUser(x);}); return false; } removeMentionedUser(e) { e.preventDefault(); let $theDiv = $(e.currentTarget).parent(); $theDiv.remove(); return false; } } module.exports = TweetCompose; <file_sep>class TowersOfHanoi attr_reader :first, :second, :third def initialize(size = 5) @size = size @first = size.downto(1).to_a @second = [] @third = [] end def make_move(start, finish) raise "Invalid move!" if start.empty? raise "Invalid move!" unless finish.empty? || finish.last > start.last finish << start.pop end def won? return false unless @first.empty? @second == @size.downto(1).to_a || @third == @size.downto(1).to_a end def get_input(position) puts "Select #{position} tower. 1, 2, or 3" tower = gets.chomp case tower when "1" @first when "2" @second when "3" @third else raise "Invalid move!" end end def render puts "First tower: #{@first.join(' ')}" puts "Second tower: #{@second.join(' ')}" puts "Third tower: #{@third.join(' ')}" end def play until won? render begin start_pos = get_input("starting") end_pos = get_input("ending") make_move(start_pos, end_pos) rescue puts "Invalid move!!!!!!!!" retry end end puts "Congrats! You won! :)" end end if __FILE__ == $PROGRAM_NAME game = TowersOfHanoi.new game.play end <file_sep>class Tile def initialize(value = 0) @value = value @given = (value == 0 ? false : true) end def to_s @value == 0 ? " " : @value.to_s end end <file_sep>const DOMNodeCollection = require('./dom_node_collection.js'); function $1(argument) { if (argument instanceof HTMLElement) { return new DOMNodeCollection([argument]); } else { let nodes = document.querySelectorAll(argument); return new DOMNodeCollection(Array.from(nodes)); } } window.$1 = $1; <file_sep>class ShortenedUrl < ActiveRecord::Base validates :user_id, presence: true validates :short_url, uniqueness: true validates :long_url, length: { maximum: 1024 } validate :over_submission validate :submission_count belongs_to :submitter, class_name: :User, primary_key: :id, foreign_key: :user_id has_many :visits, class_name: :Visit, primary_key: :id, foreign_key: :url_id has_many :visitors, through: :visits, source: :visitor has_many :uniq_visitors, -> { distinct }, through: :visits, source: :visitor has_many :taggings, class_name: :Tagging, primary_key: :id, foreign_key: :url_id has_many :topics, through: :taggings, source: :topic def self.random_code new_url = SecureRandom.urlsafe_base64 while ShortenedUrl.exists?(short_url: new_url) new_url = SecureRandom.urlsafe_base64 end new_url end def self.create_for_user_and_long_url!(user, long_url) shortened_url = ShortenedUrl.random_code ShortenedUrl.create!(user_id: user.id, long_url: long_url, short_url: shortened_url) end def num_clicks self.visitors.count end def num_uniques self.uniq_visitors.count end def num_recent_uniques self.uniq_visitors.where(["visits.updated_at > ?", 10.minutes.ago]).count end private def over_submission cur_user = User.find(user_id) if cur_user.recent_submission_count > 5 errors[:submission] << "count can't be greater than 5 within 1 minute" end end def submission_count cur_user = User.find(user_id) unless cur_user.premium || cur_user.submission_count < 5 errors[:count] << "of submissions is too high for non-premium users" end end end <file_sep>class User < ActiveRecord::Base <<<<<<< HEAD validates :email, presence: true, uniqueness: true has_many :submitted_urls, class_name: :ShortenedUrl, primary_key: :id, foreign_key: :user_id has_many :visits, class_name: :Visit, primary_key: :id, foreign_key: :user_id has_many :visited_urls, through: :visits, source: :url has_many :uniq_visited_urls, -> { distinct }, through: :visits, source: :url def recent_submission_count self.submitted_urls.where(["shortened_urls.updated_at > ?", 1.minutes.ago]).count end def submission_count self.submitted_urls.count end def create_shortened_url(long_url) ShortenedUrl.create_for_user_and_long_url!(self, long_url) end ======= has_many :enrollments, primary_key: :id, foreign_key: :student_id, class_name: :Enrollment has_many :enrolled_courses, through: :enrollments, source: :course >>>>>>> associations/master end <file_sep>require_relative "module.rb" require 'singleton' class Piece attr_reader :color, :symbol, :board attr_accessor :position def initialize(color, symbol, position, board) @color = color @symbol = symbol @position = position @board = board end end <file_sep>require_relative 'graph' require_relative 'priority_map' # O(|V| + |E|*log(|V|)). def dijkstra2(start_vertex) possible = PriorityMap.new do |data1, data2| data1[:cost] <=> data2[:cost] end possible[start_vertex] = { cost: 0, parent: nil } shortest_paths = {} until possible.empty? closest, closest_data = possible.extract shortest_paths[closest] = closest_data closest.out_edges.each do |edge| neighbor = edge.to_vertex new_cost = closest_data[:cost] + edge.cost if possible[neighbor].nil? || new_cost < possible[neighbor][:cost] possible[neighbor] = { parent: closest, cost: new_cost } end end end shortest_paths end <file_sep> require 'byebug' module SteppingPiece KNIGHT_DELTAS = [ [1, 2], [2, 1], [2, -1], [1, -2], [-1, -2], [-2, -1], [-2, 1], [-1, 2]] KINGS_DELTAS = [ [1, 0], [1, 1], [0, 1], [-1, 1], [-1, 0], [-1, -1], [0, -1], [1, -1]] def moves deltas = self.is_a?(King) ? KINGS_DELTAS : KNIGHT_DELTAS all_moves = deltas.map { |delta| [delta[0] + position[0], delta[1] + position[1]] } all_moves.select { |pos| valid_move?(pos) } end def valid_move?(pos) return false unless pos[0].between?(0,7) && pos[1].between?(0,7) if board[pos].is_a? NullPiece || board[pos].color != color true else false end end end module SlidingPiece DIAG_DELTAS = [ [1,1], [-1,1], [-1,-1], [1,-1]] R_C_DELTAS = [ [1,0], [0,1], [-1,0], [0,-1]] def moves possible_moves = [] permisions = self.move_dirs possible_moves += diag_moves if permisions.include?(:X) possible_moves += row_col_moves if permisions.include?(:H) possible_moves end def diag_moves all_diags = [] DIAG_DELTAS.each do |delta| 7.times do |spacer| new_x = position[0] + (delta[0] * (spacer + 1)) new_y = position[1] + (delta[1] * (spacer + 1)) all_diags << [new_x, new_y] end end sanitize_moves(all_diags) end def row_col_moves all_row_col_moves = [] R_C_DELTAS.each do |delta| 7.times do |spacer| new_x = position[0] + (delta[0] * (spacer + 1)) new_y = position[1] + (delta[1] * (spacer + 1)) all_row_col_moves << [new_x, new_y] end end sanitize_moves(all_row_col_moves) end def sanitize_moves(all_moves) dir1 = all_moves[0...7] dir2 = all_moves[7...14] dir3 = all_moves[14...22] dir4 = all_moves[14..28] sanitized_moves = [] [dir1, dir2, dir3, dir4].each do |direction| sanitized_moves += sanitize_direction(direction) end sanitized_moves end def sanitize_direction(moves) sanitized_moves = [] moves.each_with_index do |pos, idx| break unless pos[0].between?(0, 7) && pos[1].between?(0, 7) if board[pos].color == color break elsif board[pos].is_a? NullPiece sanitized_moves << pos else sanitized_moves << pos break end end sanitized_moves end end <file_sep>import values from 'lodash/values'; export const selectAllPokemon = (state) => { return values(state.pokemon); }; export const selectPokemonItem = (state, id) => { const { pokemonDetail } = state; const foundItem = (pokemonDetail.items === undefined ? {} : pokemonDetail.items.find(item => item.id === +id)); return foundItem; }; <file_sep>require_relative "card" class Deck attr_reader :pile def self.default_pile cards = [] Card::SUITS.each do |suit| Card::VALUES.each do |value| cards << Card.new(value, suit) end end cards end def initialize(pile = Deck::default_pile) @pile = pile shuffle_deck end def shuffle_deck @pile.shuffle! end def deal(number) dealt = [] number.times { dealt << @pile.pop } dealt end end <file_sep>import React from 'react'; import { Link } from 'react-router'; class PokemonDetail extends React.Component { constructor(props) { super(props); } componentDidMount() { this.props.requestSinglePokemon(parseInt(this.props.params.pokemonId)); } componentWillReceiveProps(newProps) { if (newProps.params.pokemonId !== this.props.params.pokemonId) { this.props.requestSinglePokemon(parseInt(newProps.params.pokemonId)); } } render() { const {image_url, id, attack, defense, name, moves, items, poke_type} = this.props.pokemonDetail; let itemLinks = ( items === undefined ? "" : items.map(item => ( <Link to={`/pokemon/${id}/item/${item.id}`} key={item.id}> <img className="small" src={item.image_url}></img> </Link> )) ); return ( <section> <img src={image_url}></img> <h2>{name}</h2> <ul> <li key="type">Type: {poke_type}</li> <li key="attack">Attack: {attack}</li> <li key="defense">Defense: {defense}</li> <li key="moves">Moves: {moves === undefined ? "" : moves.join(", ")}</li> <li key="items">{itemLinks}</li> </ul> {this.props.children} </section> ); } } export default PokemonDetail; <file_sep># Longest Common Substring # Write a function, longest_common_substring(str1, str2) that takes # two strings and returns the longest common substring. A substring is # defined as any consecutive slice of letters from another string. # Bonus: solve it in O(m * n) using O(m * n) extra space. <file_sep>require 'deck.rb' require 'rspec' describe Deck do subject(:deck) { Deck.new } describe "#initialize" do it "initializes deck pile to be an array of 52 slots" do expect(deck.pile.length).to eq(52) end end describe '#default_pile' do it "has 13 cards of each suit" do hearts, clubs, diamonds, spades = 0, 0, 0, 0 deck.pile.each do |card| case card.suit when :hearts hearts += 1 when :clubs clubs += 1 when :spades spades += 1 when :diamonds diamonds += 1 end end counts = [spades, clubs, diamonds, hearts] expect(counts.all? { |el| el == 13 }).to be true end it "has 4 cards for each value" do hearts, clubs, diamonds, spades = [], [], [], [] deck.pile.each do |card| case card.suit when :hearts hearts << card.value when :clubs clubs << card.value when :spades spades << card.value when :diamonds diamonds << card.value end end expect(hearts.sort).to eq((1..13).to_a) expect(clubs.sort).to eq((1..13).to_a) expect(diamonds.sort).to eq((1..13).to_a) expect(spades.sort).to eq((1..13).to_a) end end describe '#shuffle_deck' do it "shuffles the deck" do expect(deck.pile).to receive(:shuffle!) deck.shuffle_deck end end describe '#deal' do it "removes the number of cards from the pile" do deck.deal(3) expect(deck.pile.length).to eq(49) end it "returns an array of the dealt cards" do dealt = deck.deal(2) expect(dealt.length).to eq(2) expect(dealt).to be_an(Array) end end end <file_sep>class Album < ActiveRecord::Base validates :name, presence: true, uniqueness: true validates :band_id, :kind, presence: true belongs_to :band, primary_key: :id, foreign_key: :band_id, class_name: :Band has_many :tracks, primary_key: :id, foreign_key: :album_id, class_name: :Track def sibling_albums self.band.albums end end <file_sep>class Track < ActiveRecord::Base validates :name, presence: true, uniqueness: true validates :album_id, :kind, presence: true belongs_to :album, primary_key: :id, foreign_key: :album_id, class_name: :Album has_one :band, through: :album, source: :band has_many :notes end <file_sep>require_relative 'tile.rb' class Board def initialize(grid_size = 9) @grid = Array.new(grid_size) { Array.new(grid_size) } populate end def won? not_bombs = @grid.flatten.reject(&:is_bomb) not_bombs.all?(&:revealed) end def render puts " #{(0...size).to_a.join(' ')}" @grid.each.with_index do |row, idx| puts "#{idx} #{row.map(&:to_s).join(' ')}" end end def [](pos) row, col = pos @grid[row][col] end def []=(pos, val) row, col = pos @grid[row][col] = val end def populate tiles = [] total_tiles = size**2 num_bombs = total_tiles / 6 num_bombs.times { tiles << Tile.new(true) } (total_tiles - num_bombs).times { tiles << Tile.new(false) } tiles.shuffle! @grid.each_with_index do |row, j| row.each_index do |k| tile = tiles.pop self[[j, k]] = tile tile.pos = [j, k] end end end def reveal_applicable(tile) tile.reveal return if tile.is_bomb neighbors = find_neighbors(tile) tile.fringe_val = neighbors.count(&:is_bomb) if tile.fringe_val == 0 neighbors.each do |el| reveal_applicable(el) unless el.revealed || el.is_bomb end end end def find_neighbors(tile) @grid.flatten.select { |other_tile| tile.is_neighbor?(other_tile) } end def size @grid.length end end <file_sep>json.partial! 'api/guests/guest', guest: guest json.gifts do json.array! guest.gifts do |gift| json.title gift.title json.description gift.description end end <file_sep>class GoalsController < ApplicationController def new @goal = Goal.new end def create @goal = Goal.new(goal_params) @goal.user_id = current_user.id if @goal.save log_in(@goal) redirect_to goal_url(@goal) else flash.now[:errors] = @goal.errors.full_messages render :new end end def show end def edit end def update @goal = Goal.find(params[:id]) if @goal.update_attributes(goal_params) log_in(@goal) redirect_to goal_url(@goal) else flash.now[:errors] = @goal.errors.full_messages render :new end end def destroy end private def goal_params params.require(:goal).permit(:title, :status, :privacy) end end <file_sep>require_relative 'piece.rb' require 'byebug' class Pawn < Piece def initialize(color, position, board) super(color, :P, position, board) end def to_s "P".colorize(color) end def moves # byebug first_move = (position[0] == 6 || position[0] == 1) direction_changer = color == :green ? -1 : 1 possible_moves = [] possible_moves << [position[0] + 1 * direction_changer, position[1] ] possible_moves << [position[0] + 2 * direction_changer, position[1]] if first_move attack_right = [position[0] + 1 * direction_changer, position[1] + 1] attack_left = [position[0] + 1 * direction_changer, position[1] - 1] possible_moves << attack_left if board[attack_left].color != color possible_moves << attack_right if board[attack_right].color != color possible_moves end end <file_sep>require "towers_of_hanoi" require "rspec" describe TowersOfHanoi do subject(:towers) { TowersOfHanoi.new(3) } describe "#initialize" do context "when a size is given" do it "initializes first tower with disks in descending order" do expect(towers.first).to eq([3, 2, 1]) end it "initializes second and third towers as empty arrays" do expect(towers.second).to be_empty expect(towers.third).to be_empty end end context "when no size is given" do subject(:towers) { TowersOfHanoi.new } it "initializes first tower with 5 disks" do expect(towers.first).to eq([5, 4, 3, 2, 1]) end end end describe '#make_move' do context "when valid input" do it "moves a disk from one tower to another tower" do towers.make_move(towers.first, towers.second) expect(towers.first).to eq([3, 2]) expect(towers.second).to eq([1]) towers.make_move(towers.second, towers.third) expect(towers.second).to eq([]) expect(towers.third).to eq([1]) end end context "when invalid input" do it "raises an error if starting tower is empty" do expect { towers.make_move(towers.second, towers.third) }.to raise_error("Invalid move!") end it "raises an error if moving disk is greater than ending tower's top disk" do towers.third << towers.first.pop towers.second << towers.first.pop expect { towers.make_move(towers.second, towers.third) }.to raise_error("Invalid move!") end end end describe "#won?" do it "returns true if second or third tower has all the disks in proper order" do 3.times { towers.second << towers.first.shift } expect(towers.won?).to be true 3.times { towers.third << towers.second.shift } expect(towers.won?).to be true end it "returns false if second or third tower has all the disks in incorrect order" do 3.times { towers.second << towers.first.pop } expect(towers.won?).to be false 3.times { towers.third << towers.second.shift } expect(towers.won?).to be false end it "returns false if game is in process" do towers.second << towers.first.shift towers.third << towers.first.shift expect(towers.won?).to be false end end end <file_sep>require 'byebug' class PolyTreeNode attr_reader :parent, :children, :value def initialize(value, parent = nil, children = []) @parent = parent @children = children @value = value end def parent=(other_node) @parent.children.delete(self) if @parent @parent = other_node @parent.children << self unless other_node.nil? || @parent.children.include?(self) end def add_child(child) child.parent = self end def remove_child(child) raise "not a child" unless @children.include?(child) child.parent = nil end def dfs(target) return self if self.value == target self.children.each do |child| result = child.dfs(target) return result unless result.nil? end nil end def bfs(target) queue = [self] until queue.empty? cur = queue.shift return cur if cur.value == target cur.children.each { |child| queue.push(child) } end nil end end <file_sep>json.array! @gifts, partial: 'api/gifts/gift', as: :gift <file_sep> import React from 'react'; import ReactDOM from 'react-dom'; import configureStore from './store/store.js'; import {login, logout, signup} from './util/session_api_util.js'; document.addEventListener('DOMContentLoaded', () => { const root = document.getElementById('root'); window.signup = signup; window.login = login; window.logout = logout; window.store = configureStore(); ReactDOM.render(<h1>Welcome to BenchBnB</h1>, root); }); <file_sep>class Tile attr_reader :is_bomb, :revealed, :flagged attr_accessor :fringe_val, :pos def initialize(is_bomb = false) @is_bomb = is_bomb @flagged = false @revealed = false @fringe_val = 0 @pos = nil end def reveal @revealed = true end def to_s return "F" if @flagged return "#" unless @revealed return "@" if @is_bomb @fringe_val == 0 ? "_" : @fringe_val.to_s end def flag @flagged = !@flagged end def neighbors x, y = @pos [[x - 1, y - 1], [x - 1, y], [x - 1, y + 1], [x, y + 1], [x + 1, y + 1], [x + 1, y], [x + 1, y - 1], [x, y - 1]] end def is_neighbor?(tile) neighbors.include?(tile.pos) end end <file_sep>json.array! @guests, partial: 'api/guests/guest', as: :guest <file_sep>class View { constructor(game, $figure) { this.game = game; this.figure = $figure; this.setupTowers(); this.setListeners(); this.fromPile = null; this.toPile = null; } setupTowers () { let $first = $("<ul id='first'>").data('value', 0); for (let i = 0; i < 3; i++) { let $li = $("<li>"); let size = this.game.towers[0][i]; $($li).addClass(`disk${size}`); $($li).data('val', size); $($li).css('width', `${(size) * 30}%`); $first.append($li); } this.figure.append($first); let $second = $("<ul id='second'></ul>").data('value', 1); this.figure.append($second); let $third = $("<ul id='third'></ul>").data('value', 2); this.figure.append($third); } render() { if (this.toPile !== null) { if (this.game.move(this.fromPile.data('value'), this.toPile.data('value')) === true) { let $currListItem = $(':last-child', this.fromPile).detach(); this.toPile.append($currListItem); } this.fromPile = null; this.toPile = null; } } setListeners() { $('ul').on('click', (event) => { if (this.fromPile === null) { this.fromPile = $(event.currentTarget); } else { this.toPile = $(event.currentTarget); } this.render(); if (this.game.isWon()) { setTimeout(() => { alert("You Won!!!!"); }, 500 ); } }); } } module.exports = View; <file_sep>require_relative 'graph' # O(|V|**2 + |E|). def dijkstra1(start_vertex) vertices = { start_vertex => { parent: nil, cost: 0 } } possible = [start_vertex] shortest_paths = {} until possible.empty? closest = possible.min_by { |vertex| vertices[vertex][:cost] } possible.delete(closest) shortest_paths[closest] = vertices[closest] vertices.delete(closest) closest.out_edges.each do |edge| neighbor = edge.to_vertex new_cost = shortest_paths[closest][:cost] + edge.cost if vertices[neighbor].nil? || new_cost < vertices[neighbor][:cost] possible << neighbor vertices[neighbor] = { parent: closest, cost: new_cost } end end end shortest_paths end <file_sep>class DOMNodeCollection { constructor(els) { this.els = els; } html (string) { if (string === undefined) { return this.els[0].innerHTML; } else { for (let i = 0; i < this.els.length; i++) { this.els[i].innerHTML = string; } } } empty () { for (let i = 0; i < this.els.length; i++) { this.els[i].innerHTML = ""; } } append (addition) { if (addition instanceof DOMNodeCollection) { for (let i = 0; i < addition.els.length; i++) { for (let j = 0; j < this.els.length; j++) { this.els[j].innerHTML += addition.els[i].outerHTML; } } } else { for (let k = 0; k < this.els.length; k++) { this.els[k].innerHTML += addition; } } } attr (attributeName, value) { if (value === undefined) { return this.els[0].getAttribute(attributeName); } else { for (let k = 0; k < this.els.length; k++) { this.els[k].setAttribute(attributeName, value); } } } addClass (className) { for (let k = 0; k < this.els.length; k++) { this.els[k].classList.add(className); } } removeClass (classes) { if (classes !== undefined) { classes = classes.split(" "); } for (let k = 0; k < this.els.length; k++) { if (classes === undefined) { this.els[k].className = ""; } else { this.els[k].classList.remove(...classes); } } } children () { let kids = []; for (let k = 0; k < this.els.length; k++) { kids = kids.concat(Array.from(this.els[k].children)); } return new DOMNodeCollection(kids); } parent () { let parents = []; for (let k = 0; k < this.els.length; k++) { let parent = this.els[k].parentNode; if (!(parents.includes(parent))){ parents.push(parent); } } return new DOMNodeCollection(parents); } remove () { for (let k = 0; k < this.els.length; k++) { let parent = this.els[k].parentNode; parent.removeChild(this.els[k]); } this.els = []; } on (type, fn) { for (let k = 0; k < this.els.length; k++) { let el = this.els[k]; el.addEventListener(type, fn); if (el.cbs === undefined) { el.cbs = {}; } el.cbs[type] = fn; } } off (type) { for (let k = 0; k < this.els.length; k++) { let el = this.els[k]; el.removeEventListener(type, el.cbs[type]); } } } module.exports = DOMNodeCollection; <file_sep>require 'byebug' class Card attr_reader :revealed, :face_value def self.make_card_pairs(num_pairs) card_pairs = [] pool = ("a".."z").to_a.shuffle pool = pool.take(num_pairs).map(&:to_sym) pool.each do |face_val| card_pairs << Card.new(face_val) card_pairs << Card.new(face_val) end card_pairs.shuffle end def initialize(face_value) @revealed = false @face_value = face_value end def hide @revealed = false end def reveal @revealed = true end def to_s @revealed ? "#{@face_value}" : "#" end def ==(other_card) object.is_a?(self.class) && @face_value == other_card.face_value end end <file_sep>require_relative 'board.rb' require_relative 'card.rb' require_relative 'human_player.rb' require_relative 'computer_player.rb' class MemoryGame def initialize(board = Board.new, player = HumanPlayer.new(4)) @board = board @previous_guess = nil @player = player end def play until over? show_board pos = get_player_input make_guess(pos) sleep(1) end puts "YOU WON!" end #SOLUTION def get_player_input pos = nil until pos && valid_pos?(pos) pos = @player.get_input end pos end def make_guess(pos) revealed_value = board.reveal(pos) player.receive_revealed_card(pos, revealed_value) board.render compare_guess(pos) sleep(1) board.render end # def check_guess(pos) # current_card = @board.reveal(pos) # @player.receive_revealed_card(pos, current_card.face_value) # show_board # if @previous_guess.nil? # @previous_guess = current_card # else # unless @previous_guess == current_card # @previous_guess.hide # current_card.hide # end # @previous_guess = nil # end # end # SOLUTION def check_guess(new_guess) if previous_guess if match?(previous_guess, new_guess) player.receive_match(previous_guess, new_guess) else puts "Try again." [previous_guess, new_guess].each { |pos| board.hide(pos) } end self.previous_guess = nil player.previous_guess = nil else self.previous_guess = new_guess player.previous_guess = new_guess end end #SOLUTION def match?(pos1, pos2) board[pos1] == board[pos2] end # SOLUTION: def valid_pos?(pos) pos.is_a?(Array) && pos.count == 2 && pos.all? { |x| x.between?(0, board.size - 1) } end def show_board system("clear") @board.render end def over? @board.won? end #SOLUTION: private attr_accessor :previous_guess attr_reader :board end if $PROGRAM_NAME == __FILE__ board = Board.new computer_player = ComputerPlayer.new(board.all_positions, "Bob") game = MemoryGame.new(board, computer_player) game.play end <file_sep>Array.prototype.bubbleSort = function(cb) { let sorted = false; while (sorted === false) { sorted = true; for (let i = 0; i < this.length - 1; i++) { if (cb(this[i], this[i + 1]) === true) { let temp = this[i]; this[i] = this[i + 1]; this[i + 1] = temp; sorted = false; } } } return this; }; String.prototype.subString = function(){ let subs = []; for (let i = 0; i <= this.length - 1; i++) { for (let j = i + 1; j <= this.length; j++) { subs.push(this.slice(i, j)); } } return subs; }; console.log("cat".subString()); <file_sep>class BinaryMaxHeap def initialize(&prc) prc ||= self.class.default_prc @store = [] @prc = prc end def count @store.length end def extract raise "heap is empty" if @store.empty? self.class.extract(@store, count, @prc) @store.pop end def peek @store[0] end def push(val) @store << val self.class.sift_up(@store, count - 1, @prc) end def self.extract(arr, length, prc = default_prc) arr[0], arr[length - 1] = arr[length - 1], arr[0] sift_down(arr, 0, length - 1, prc) end def self.sift_up(arr, current, prc = default_prc) return arr if current == 0 parent = parent_index(current) if prc.call(arr[current], arr[parent]) == 1 arr[current], arr[parent] = arr[parent], arr[current] sift_up(arr, parent, prc) end arr end def self.sift_down(arr, current, len, prc = default_prc) children = child_indices(current, len) || [] return arr if children.empty? larger_idx = children[0] if children[1] && prc.call(arr[children[1]], arr[children[0]]) == 1 larger_idx = children[1] end if prc.call(arr[larger_idx], arr[current]) == 1 arr[current], arr[larger_idx] = arr[larger_idx], arr[current] sift_down(arr, larger_idx, len, prc) end arr end def self.child_indices(idx, len) left = (idx * 2) + 1 right = (idx * 2) + 2 [left, right].select { |index| index < len } end def self.parent_index(idx) raise "root has no parent" if idx == 0 (idx - 1) / 2 end def self.default_prc Proc.new { |el1, el2| el1 <=> el2 } end end <file_sep>json.array! @parties do |party| json.partial! 'api/parties/party', party: party json.guests do json.array! party.guests, partial: 'api/guests/guest', as: :guest end end <file_sep>class Board def self.from_file(file_name) rows = File.readlines(file_name).map(&:chomp) numbers = rows.map(&:chars).map(&:to_i) grid = [] numbers.each do |row| grid << row.map(&:to_i) end Board.new(grid) end def initialize(grid) @grid = grid end #Array.new(9) { Array.new(9) } end <file_sep>class Board def initialize(board_size = 4) @grid = Array.new(board_size) { Array.new(board_size) } @size = board_size populate end def num_cards @size * @size end def self.default_board Array.new(4) { Array.new(4) } end def populate pairs = Card.make_card_pairs(num_cards / 2) all_positions.each do |pos| self[pos] = pairs.pop end end def render puts " #{(0...@size).to_a.join(" ")}" @grid.each_with_index do |row, idx| puts "#{idx} #{row.map(&:to_s).join(" | ")}" end end def [](pos) row, col = pos @grid[row][col] end def []=(pos, val) row, col = pos @grid[row][col] = val end def all_positions positions = [] @size.times do |col| @size.times do |row| positions << [row, col] end end positions end def won? all_positions.all? { |pos| self[pos].revealed } end def reveal(pos) self[pos].reveal self[pos] end end <file_sep>require_relative '02_searchable' require 'active_support/inflector' require 'byebug' # Phase IIIa class AssocOptions attr_accessor( :foreign_key, :class_name, :primary_key ) def model_class class_name.constantize end def table_name model_class.table_name end end class BelongsToOptions < AssocOptions def initialize(name, options = {}) @primary_key = (options[:primary_key] ? options[:primary_key] : :id) @foreign_key = (options[:foreign_key] ? options[:foreign_key] : "#{name.to_s.singularize}_id".to_sym) @class_name = (options[:class_name] ? options[:class_name] : name.to_s.singularize.camelcase) end end class HasManyOptions < AssocOptions def initialize(name, self_class_name, options = {}) @primary_key = (options[:primary_key] ? options[:primary_key] : :id) @foreign_key = (options[:foreign_key] ? options[:foreign_key] : "#{self_class_name.to_s.underscore}_id".to_sym) @class_name = (options[:class_name] ? options[:class_name] : name.to_s.singularize.camelcase) end end module Associatable # Phase IIIb def belongs_to(name, options = {}) options = BelongsToOptions.new(name, options) assoc_options[name] = options define_method(name) do foreign_key_value = self.send(options.foreign_key) results = DBConnection.execute(<<-SQL, foreign_key_value) SELECT #{options.table_name}.* FROM #{options.table_name} JOIN #{self.class.table_name} ON #{options.table_name}.#{options.primary_key} = #{self.class.table_name}.#{options.foreign_key} WHERE #{self.class.table_name}.#{options.primary_key} = ? SQL results.empty? ? nil : options.model_class.new(results.first) end end def has_many(name, options = {}) options = HasManyOptions.new(name, self, options) define_method(name) do primary_key_value = self.send(options.primary_key) results = DBConnection.execute(<<-SQL, primary_key_value) SELECT #{options.table_name}.* FROM #{options.table_name} JOIN #{self.class.table_name} ON #{options.table_name}.#{options.foreign_key} = #{self.class.table_name}.#{options.primary_key} WHERE #{options.model_class.table_name}.#{options.foreign_key} = ? SQL results.empty? ? [] : results.map { |result| options.model_class.new(result) } end end def assoc_options @assoc_options ||= {} end end class SQLObject extend Associatable end <file_sep>const FollowToggle = require('./follow_toggle.js'); const UsersSearch = require('./users_search.js'); const TweetCompose = require('./tweet.js'); const InfiniteTweets = require('./infinite_tweets.js'); $(() =>{ $('.FollowToggle').each((index, el) => { let followButton = new FollowToggle(el); }); $('nav.users-search').each((index, el) => { let usersSearch = new UsersSearch(el); }); $('.tweet-compose').each((index,el) => { let tweetCompose = new TweetCompose(el); }); $('div.infinite-tweets').each((index,el) => { let infiniteTweets = new InfiniteTweets(el); }); }); <file_sep>const Game = require("./game.js"); const readline = require('readline'); const reader = readline.createInterface({ input: process.stdin, output: process.stdout }); const callBack = () => { reader.question("Do you want to play again? ", (response) => { if (response === "yes") { // reader.close() game = new Game(3); game.run(reader, callBack); } else { reader.close(); } }); }; let game = new Game(3); game.run(reader,callBack); <file_sep>def sum_to(n) return nil if n < 0 return 1 if n == 1 return 0 if n == 0 n + sum_to(n - 1) end puts "Sum To" p sum_to(5) == 15 p sum_to(1) == 1 p sum_to(9) == 45 p sum_to(-8) == nil def add_numbers(nums_array = nil) return nil if nums_array.nil? return nums_array.first if nums_array.length == 1 nums_array.first + add_numbers(nums_array[1..-1]) end puts "Add Numbers" p add_numbers([1, 2, 3, 4]) == 10 p add_numbers([3]) == 3 p add_numbers([-80, 34, 7]) == -39 p add_numbers == nil def gamma_fnc(n) return nil if n == 0 return 1 if n == 1 (n - 1) * gamma_fnc(n - 1) end puts "Gamma Function" p gamma_fnc(0) == nil p gamma_fnc(1) == 1 p gamma_fnc(4) == 6 p gamma_fnc(8) == 5040 <file_sep>require 'rails_helper' RSpec.describe GoalsController, type: :controller do describe "GET #new" do it "renders the new goal page" do get :new, link: {} expect(response).to render_template("new") expect(response).to have_http_status(200) end end describe "POST #create" do context "with invalid params" do it "validates the presence of status, title, and privacy " do post :create expect(response).to render_template("new") expect(flash[:errors]).to be_present end it "validates privacy" do post :create, goal: {title: "Finish Project", status: "Complete", privacy: "hidden"} expect(response).to render_template("new") expect(flash[:errors]).to be_present end it "validates status" do post :create, goal: {title: "Finish Project", status: "not happy", privacy: "public"} expect(response).to render_template("new") expect(flash[:errors]).to be_present end end context "with valid params" do it "redirects to the goal show page" do post :create, user: {title: "Finish Project", status: "Ongoing", privacy: "public"} expect(response).to redirect_to(goal_url(Goal.last)) end end end end <file_sep># This file should contain all the record creation needed to seed the database with its default values. # The data can then be loaded with the rake db:seed (or created alongside the db with db:setup). # # Examples: # # cities = City.create([{ name: 'Chicago' }, { name: 'Copenhagen' }]) # Mayor.create(name: 'Emanuel', city: cities.first) user1 = User.create(username: 'JoeT') user2 = User.create(username: 'ThornOfCamora') user3 = User.create(username: 'ManFromMars') contact1 = Contact.create(name: 'joe', email: '<EMAIL>', user_id: 1) contact2 = Contact.create(name: 'locke', email: '<EMAIL>', user_id: 2) contact3 = Contact.create(name: 'john', email: '<EMAIL>', user_id: 3) contact_share1 = ContactShare.create(user_id: 1,contact_id: 2) contact_share1 = ContactShare.create(user_id: 1,contact_id: 3) <file_sep>require_relative "deck" class Hand attr_reader :cards def initialize(cards) @cards = cards end def beat_hand?(other_hand) end def kind_of_hand values = @cards.map { |card| card.value }.sort if is_straight?(values) return :straight else return values.max end end def is_straight?(values) (values.length - 1).times do |idx| return false unless values[idx + 1] - values[idx] == 1 end true end end <file_sep>require_relative 'piece.rb' class NullPiece < Piece include Singleton attr_reader :color, :symbol def initialize @color = nil @symbol = nil @position = nil @board = nil end def to_s " " end end <file_sep>require_relative '00_tree_node' require 'byebug' class KnightPathFinder attr_reader :start_pos MOVES = [ [1, 2], [2, 1], [-1, 2], [-2, 1], [-2, -1], [-1, -2], [1, -2], [2, -1] ] def initialize(start_pos = [0, 0]) @start_pos = start_pos @visited_pos = [start_pos] @root = PolyTreeNode.new(@start_pos) build_move_tree end def self.valid_moves(pos) x, y = pos moves = MOVES.map { |step| [step[0] + x, step[1] + y] } moves.select { |mv| valid?(mv) } end def self.valid?(pos) x, y = pos x.between?(0, 7) && y.between?(0, 7) end def new_move_positions(pos) new_moves = self.class.valid_moves(pos).reject do |cur_pos| @visited_pos.include?(cur_pos) end @visited_pos += new_moves new_moves end def build_move_tree queue = [@root] until queue.empty? cur_node = queue.shift new_move_positions(cur_node.value).each do |child_pos| child_node = PolyTreeNode.new(child_pos) child_node.parent = cur_node queue << child_node end end end def find_path(end_pos) end_node = @root.dfs(end_pos) trace_path_back(end_node) # end_node = @root.bfs(end_pos) end def trace_path_back(node) paths = [] cur_node paths end end if __FILE__ == $PROGRAM_NAME finder = KnightPathFinder.new end <file_sep>class Card attr_reader :value, :suit SUITS = [:hearts, :clubs, :spades, :diamonds] VALUES = (1..13).to_a def initialize(value, suit) @value = value @suit = suit end end <file_sep>require_relative 'piece.rb' class King < Piece include SteppingPiece def initialize(color, position, board) super(color, :K, position, board) end def to_s "K".colorize(color) end end <file_sep>require_relative 'piece.rb' class Rook < Piece include SlidingPiece def initialize(color, position, board) super(color, :R, position, board) end def move_dirs [:H] end def to_s "R".colorize(color) end end <file_sep>class Goal < ActiveRecord::Base validates :title, :status, :user, :privacy, presence: true validates :privacy, inclusion: %w(public private) validates :status, inclusion: %w(Ongoing Complete) belongs_to :user end <file_sep>class CatRentalRequest < ActiveRecord::Base validates :cat_id, :start_date, :end_date, presence: true validates :status, inclusion: { in: %w(PENDING APPROVED DENIED) } validate :overlaps, :logical_dates belongs_to :cat, dependent: :destroy def approve! self.status = 'APPROVED' transaction do self.save overlapping_pending_requests.each(&:deny!) end end def deny! self.status = 'DENIED' self.save end def pending? self.status == 'PENDING' end private def logical_dates if self.start_date > self.end_date self.errors[:Illogical_dates] << ": Start date should be before End date." end end def overlaps if overlapping_approved_requests? && self.status == 'APPROVED' self.errors[:overlaps] << "with other approved request." end end def overlapping_pending_requests overlapping_requests.where(status: 'PENDING') end def overlapping_approved_requests? overlapping_requests.exists?(status: 'APPROVED') end def overlapping_requests CatRentalRequest.where(cat_id: self.cat_id) .where.not(id: self.id) .where(<<-SQL, start: self.start_date, final: self.end_date) start_date BETWEEN :start AND :final OR end_date BETWEEN :start AND :final OR ( start_date < :start AND end_date > :final ) SQL end end <file_sep>def bad_two_sum?(array, target_sum) (array.length - 1).times do |idx1| ((idx1 + 1)...array.length).each do |idx2| return true if array[idx1] + array[idx2] == target_sum end end false end def okay_two_sum_v1?(array, target_sum) sorted = array.sort two_sum_rec?(sorted, target_sum) end def okay_two_sum_v2?(array, target_sum) sorted = array.sort sorted.each_with_index do |num, idx| desired_num = target_sum - num return true if bsearch(sorted[(idx + 1)..-1], desired_num) end false end def bsearch(nums, target) return false if nums.empty? middle = nums.length / 2 case target <=> nums[middle] when -1 bsearch(nums.take(middle), target) when 0 true when 1 bsearch(nums.drop(middle + 1), target) end end def two_sum_rec?(array, target_sum) return false if array.length < 2 sum = array.first + array.last case sum <=> target_sum when -1 two_sum_rec?(array[1..-1], target_sum) when 0 return true when 1 two_sum_rec?(array[0..-2], target_sum) end end def pair_sum?(array, target_sum) nums = Hash.new(0) array.each do |num| nums[num] += 1 end nums.keys.each do |num| need = target_sum - num if need == num return true if nums[num] > 1 elsif nums.key?(need) return true end end false end <file_sep>class Array def my_uniq uniques = [] self.each { |el| uniques << el unless uniques.include?(el) } uniques end def two_sum indicies = [] self.each_with_index do |el, idx| break if idx == self.length - 1 ((idx + 1)...self.length).each do |idx2| indicies << [idx, idx2] if self[idx] + self[idx2] == 0 end end indicies end def my_transpose transposed = [] self.first.length.times do |i| subarrays = [] self.each do |el| subarrays << el[i] end transposed << subarrays end transposed end def stock_picker sorted_stocks = self.sort_by { |(day, price)| day } max_day = sorted_stocks.max_by { |(day, price)| price } return [] if max_day == sorted_stocks.first max_idx = sorted_stocks.index(max_day) min_day = sorted_stocks[0...max_idx].min_by { |(day, price)| price } [min_day.first, max_day.first] end end <file_sep># ROUTES # Prefix Verb URI Pattern Controller#Action # users POST /users(.:format) users#create # new_user GET /users/new(.:format) users#new # user GET /users/:id(.:format) users#show # sessions POST /sessions(.:format) sessions#create # new_session GET /sessions/new(.:format) sessions#new # session DELETE /sessions/:id(.:format) sessions#destroy class SessionsController < ApplicationController def create user = User.find_by_credentials(session_params[:email], session_params[:password]) if user log_in_user!(user) redirect_to user_url(user.id) else flash.now[:errors] = ["Error logging in."] render :new end end def new end def destroy log_out redirect_to new_session_url end private def session_params params.require(:user).permit(:email, :password) end end <file_sep>def my_min1(arr) arr.each_with_index do |el1, j| is_smallest = true arr.each_with_index do |el2, k| next if j == k is_smallest = false if el2 < el1 end return el1 if is_smallest end end def my_min2(arr) min = arr.first arr.each do |el| min = el if el < min end min end def largest_contiguous_sub1(arr) subs = [] arr.each_index do |idx1| (idx1...arr.length).each do |idx2| subs << arr[idx1..idx2] end end subs.map { |array| array.inject(:+) }.max end def largest_contiguous_sub2(arr) return arr.max if arr.all? { |el| el < 0 } max_max = nil cur_sum = 0 arr.each do |el| if max_max.nil? && el > 0 max_max = el end cur_sum += el if cur_sum > 0 max_max = cur_sum if cur_sum > max_max else cur_sum = 0 end end max_max end <file_sep>class Reply < QuestionsBase attr_accessor :parent_id, :user_id, :question_id, :body attr_reader :id def self.table 'replies' end def self.find_by_user_id(user_id) data = QuestionsDatabase.instance.execute(<<-SQL, user_id) SELECT * FROM replies WHERE user_id = ? SQL return nil if data.empty? Reply.new(data.first) end def self.find_by_question_id(question_id) data = QuestionsDatabase.instance.execute(<<-SQL, question_id) SELECT * FROM replies WHERE question_id = ? SQL return nil if data.empty? Reply.new(data.first) end def initialize(options) @id = options['id'] @parent_id = options['parent_id'] @user_id = options['user_id'] @question_id = options['question_id'] @body = options['body'] end def author User.find_by_id(@user_id) end def question Question.find_by_id(@question_id) end def parent_reply data = QuestionsDatabase.instance.execute(<<-SQL, parent_id) SELECT * FROM replies WHERE parent_id = ? SQL return nil if data.empty? Reply.new(data.first) end def child_replies data = QuestionsDatabase.instance.execute(<<-SQL, @id) SELECT * FROM replies WHERE parent_id = ? SQL return nil if data.empty? Reply.new(data.first) end end
9a726374fab67d64834b1cbeaa7628bb7942f27e
[ "JavaScript", "SQL", "Ruby" ]
101
Ruby
dischorde/app-academy-coursework
dc78fd2cc8a2e262d16758072b3d1a5f9f9c71bb
b42f5dbe2031880471152c816b5af3a198d61fac
refs/heads/master
<file_sep>package com.example.groupprojectt_06; import androidx.appcompat.app.AppCompatActivity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; public class Login extends AppCompatActivity { Button btnlogin; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_login); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } btnlogin = findViewById(R.id.btnlogin); btnlogin.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Login.this,Contact.class); startActivity(i); } }); } }<file_sep>package com.example.groupprojectt_06; import androidx.appcompat.app.AppCompatActivity; import android.app.DownloadManager; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; public class Contact extends AppCompatActivity { Button btnsubmit; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_contact); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) { Window w = getWindow(); w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS); } btnsubmit = findViewById(R.id.btnSubmit); btnsubmit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Intent i = new Intent(Contact.this,About.class); startActivity(i); } }); } }<file_sep>include ':app' rootProject.name = "GroupProjectT-06"
bfbeaac0657ccc0eb51100e1d2a7594a67b8f063
[ "Java", "Gradle" ]
3
Java
akadarshan/GroupProjectT-06
392f75cca7c112d455b945328c93834094763a49
f5778b2f573d96222139f076cd15540109c38bd1
refs/heads/master
<repo_name>samm007aqp/grafica<file_sep>/main.py import os import urllib.request from flask import Flask, render_template, request , redirect, url_for from werkzeug.utils import secure_filename import two as ope #import cv2 #import math app=Flask(__name__) posts = [ { 'author':'<NAME>', 'title': 'Blog Post 1', 'content': 'first post content', 'date_posted': 'April' }, { 'author':'<NAME>', 'title': 'Blog Post 2', 'content': 'La nina', 'date_posted': 'August' } ] @app.route("/") @app.route("/home") def home(): return render_template('home.html', posts=posts) #we are passing "post " argument to de template @app.route("/about") def about(): return render_template('about.html',title='About') #UPLOADS_PATH = os.path.join(os.path.dirname(os.path.realpath(__file__)),'static/images/upload/') app.config["IMAGE_UPLOADS"] = "C:/Flask_Proyect/static/images/upload" #app.config["IMAGE_UPLOADS"] = UPLOADS_PATH app.config["ALLOWED_IMAGE_EXTENSIONS"]=["PNG","JPG","JPEG","GIF"] def allowed_image(filename): if not "." in filename: return False ext = filename.rsplit(".",1)[1] if ext.upper() in app.config["ALLOWED_IMAGE_EXTENSIONS"]: return True else: return False filename = " " @app.route("/upload-image", methods=["GET","POST"]) def upload_image(): global filename if request.method =="POST": if request.files: image = request.files["image"] if image.filename ==" ": print("Image must have a filename") return redirect(request.url) if not allowed_image(image.filename): print("That image extension is not allowed") return redirect(request.url) else: filename = secure_filename(image.filename) image.save(os.path.join(app.config["IMAGE_UPLOADS"],filename)) print("image saved") return redirect(request.url) if filename == " ": return render_template('upload_image.html') else: return render_template('upload_image.html',filename=filename) @app.route('/display/<filename>') def display_image(filename): return redirect(url_for('static', filename='images/upload/' + filename), code=301) @app.route("/expo-link") def expo_link(): if not filename ==" ": print(filename) fs = 'salida'+filename print(fs) ope.OperadorExponencial(filename) print('I got clicked!') return render_template('upload_image.html',salida= fs) else: return 'Carga una imagen' if __name__ == '__main__': app.run(debug=True)<file_sep>/backup/two.py import cv2 import math import numpy as np from matplotlib import pyplot as plt def Calculate_C(greatest,BASE): return 255/math.pow(BASE,greatest) def Exp_Ope(C,BASE,x): return C*(math.pow(BASE,x)-1) def OperadorExponencial(filename): img = cv2.imread(filename) output = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) row,cols = output.shape total = row*cols gre= np.amax(output) count = 0 for i in range (row): for j in range(cols): val = 0.063*math.pow(output[i][j],1.5) if val > 255: output[i][j] = 255 count = count + 1 else: output[i][j] = val cv2.imwrite('static/images/upload/salida.jpg',output)
783f4d667a3cfe42e2d46b68040f7ea855717249
[ "Python" ]
2
Python
samm007aqp/grafica
a2194cf072a24664be76ed73a189e12792fc7ec5
5165ea439ffea3eb84ea5022e10ad151a4e1055e
refs/heads/master
<repo_name>Takashiidobe/learnPythonTheHardWayZedShaw<file_sep>/ex15.py #imports from the system arguments from sys import argv #the script is always the first arg, and then the filename is the second script, filename = argv #simplifies the open(filename) command txt = open(filename) #a little line that says what we're doing print(f"Here's your file {filename}:") #prints out the contents of the file print(txt.read()) #make sure to close files after you open them. txt.close() #asks for the filename again print("Type the filename again:") #saves whatever input you give it file_again = input("> ") #uses the input to open the file again txt_again = open(file_again) #opens the file print(txt_again.read()) #always close files after you're done using them txt.close()<file_sep>/ex33extra.py #convert the previous while loop into a callable function def while_loop: i = 0 j = input('> Insert the length of the loop here') k = input("> This is the incrementor") numbers = [] while i < j: print(f"At the top i is {i}") numbers.append(i) i += k print("Numbers now: ", numbers) print(f"at the bottom is {i}") print("The numbers: ") for num in numbers: print(num) <file_sep>/ex16.py #close (closes the file) #read (reads the file) #readline(reads just one line of a text file #truncate (empties the contents of the file) #write('stuff') Writes stuff to the file #seek(0) moves the read/write location to the beginning of the file #again the importing argv from sys import argv #these are the vars that we'll be assigning to argv script, filename = argv #This is the prompt that says CTRL-C to cancel, or return to continue print(f"We're going to erase {filename}.") print("if you don't want that, hit CTRL-C (^C).") print("If you do want that, hit RETURN") #sets the input to a question mark instead of a blank mark in the terminal input("?") #prints out a line telling us that it's working print("Opening the file...") #sets the open filename to a var (target) #w opens the file for writing, while truncating the file first target = open(filename, 'w') #prints out a warning that it's clearing the file print("Truncating the file. Goodbye!") #clears out the file itself target.truncate() #asks for three lines print("Now I'm going to ask you for three lines.") #saves the three lines given to three vars line1 = input("line 1: ") line2 = input("line 2: ") line3 = input("line 3: ") #gives us more instruction that we're going to overwrite the file with this print("I'm going to write these to the file.") #prints out the three lines while indenting target.write(f"{line1} \n {line2} \n {line3} \n") #closes the file print("And finally, we close it.") #closes the file in an action target.close()<file_sep>/ex17.py from sys import argv script, from_file, to_file = argv in_file = open(from_file).read() out_file = open(to_file, 'w').write(in_file) <file_sep>/ex2.py # A comment, this is so you can read your program later. #Anything after the # is ignored by python. print("I could have code like this.") #you can also use a comment to disable things #print("This wont' run.") print("This will run.")<file_sep>/ex34.py animals = ['bear', 'python3.6', 'peacock', 'kangaroo', 'whale', 'dog'] animal[1] animal[2] animal[0] animal[3] animal[4] animal[2] animal[5] animal[4] 1. the year 2010 is 2010 and not 2009 because there was a 0th year <file_sep>/ex31-continued.py print("""You enter a game show with three doors. Do you pick door #1, #2, or #3?""") door = input("> ") if door == "1": print("I'll allow you to switch your choice.") print("Let me reveal what's behind another door.") print("There is nothing behind door three.") print("Do you choose to switch from your original selection to door 2?") door = input("> ") if door == "1": print("There is only a giftbox here!") print("Better luck next time.") elif door == "2": print("You've found a car!") print("Good job!") else: print("Please enter one or two this time.") door = input("> ") elif door == "2": print("I'll allow you to switch your choice.") print("Let me reveal what's behind another door.") print("There is nothing behind door three.") print("Do you choose to switch from your original selection to door 1?") door = input("> ") if door == "1": print("You only found a giftbox.") print("Better luck next time.") elif door = "2": print("You've found a car!") print("Good job!") else: print("Please enter one or two this time.") door = input("> ") elif door = "3": print("I'll allow you to switch your choice.") print("Let me reveal what's behind another door.") print("There is nothing behind door one.") print("Do you choose to switch from your original selection to door 2?") if door == "2": print("You only found a giftbox.") print("Better luck next time.") elif door = "3": print("You've found a car!") print("Good job!") else: print("Please enter one or two this time.") door = input("> ") else: print("Oh no! Try again!") <file_sep>/ex32.py """hairs = ['brown', 'blond', 'red'] eyes = ['brown', 'blue', 'green'] weights = [1,2,3,4] this is list declaration """ the_count = [1,2,3,4,5] fruits = ['apples', 'oranges', 'pears', 'apricots'] change = [1, 'pennies', 2, 'dimes', 3, 'quarters'] #this first kind of for-loop goes through a list for number in the_count: print(f"This is count {number}") #same as above for fruit in fruits: print(f"A fruit of type: {fruit}") #also we can go through mixed lists too #notice we have to use {} since we don't know what's in it for i in change: print(f"I got {i}") #we can also build lists, first start with an empty one elements = []; #then use the rnage function to do 0 to 5 counts for i in range(0, 6): print(f"Adding {i} to the list.") #sppend is a function that lists use elements.append(i) #similar to array.push() #now we can print them out too for i in elements: print(f"Element was: {i}") #other list methods in python #list.append() #list.extend() (add a list to another list) #list.insert() (insert elements to the list) #list.remove() (remove elements from the list) #list.index() (removes the first occurence of index in list) #list.count() (returns occurences of element in list #list.pop() (removes element at given index) #list.reverse() (reverses a list) #list.sort() (sorts a list given callback function) #list.copy() (returns a shallow copy of the list) #list.clear() (removes all items from the list) <file_sep>/ex36.py """ 1. Every if statement must have an else. 2. If this else should never run because it doesn't make sense then you must use a die function in the else that prints out an error message and dies, just like we did in the last exercise. This will find many errors. 3. Never nest if statements more than two deep and always try to do them one deep 4. treat if-statements like paragraphs, where each if-elif-else grouping is like a set of sentences. Put blank lines before and after 5. Your boolean tests should be simple. If they are complex, move their calculations to variables earlier in your function and use a good name for the variable 6. Make a game like so """ def treasure_room(): print("Welcome to the treasure room!") print("Please answer each of the five questions correctly") print("to move onto the next room.") print("At the end of all five rooms, there is a good prize for you.") question1 = "What is 5 + 10?" question2 = "What is 5 + 2 - 3 + 6?" question3 = "What are the the prime numbers under 10?" question4 = "" <file_sep>/ex11.py ''' print("how old are you?", end = ' ') #to not end with the newline character and go to next line age = input() print("How tall are you?", end = ' ') height = input() print("How much do you weigh?", end = ' ') weight = input() print(f"So you're {age} years old, {height} tall and {weight} heavy.") ''' #next form to test out print("What is your favorite color?", end = ' ') color = input() print("What is your favorite food?", end = ' ') food = input() print("What is your favorite movie?", end = ' ') movie = input() print(f"So your favorite color is {color}, your favorite food is {food}, and your favorite movie is {movie}.") <file_sep>/ex20.py #the imports to use argv from sys import argv #sets the amount of argvs (script + the file to change) script, input_file = argv #defines the function print_all as reading the file def print_all(f): print(f.read()) #defines rewinding the file as going back to the first line def rewind(f): f.seek(0) #defines printing a line as the line_count and readline def print_a_line(line_count, f): print(line_count, f.readline()) #sets current file to be the file we've opened now current_file = open(input_file) print("First let's print the whole file: \n") #print the whole file itself print_all(current_file) print("Now let's rewind, kind of like a tape.") #sets the file back to the beginning. rewind(current_file) print("Let's print three lines:") #sets the current line to be printed to the first line current_line = 1 #prints the first line of the file print_a_line(current_line, current_file) #sets the current line to one more than it was previously then it prints it current_line += 1 print_a_line(current_line, current_file) #sets the current line to one more than it was previously then it prints it current_line += 1 print_a_line(current_line, current_file)<file_sep>/ex37.py 1. and True and False == False 2. as (part of the with-as statement) 3. assert (ensure that something is true) 4. break: (stop a loop) 5. class = define a class 6. continue = dont process more of the loop 7. def = define a function 8. del = delete from a dictionary 9. elif = else if condition 10. else = else condition 11. except = if an exception happens, do this.async 12. exec = Run a string as python 13. finally = exceptions or not, do this no matter what 14. for = for for loops 15. from = import specific parts of a module 16. global = declare global variable 17. if = if condition 18. import a module into this one to use: 19. in = part of for loops.async 20. is = like == to test equality 21. lambda = create a short anonymous function 22. not = logical not 23. or = logical or 24.pass = empty block 25. print = print string 26. raise = raise an exception 27. return = exit function with return value 28. try = try this block, if exception, go to except 29. while = while loop 30. with = with an expression as a variable do. 31. yield = pause here and return to caller True = True boolean value False = False boolean value None = nothing/no value bytes = stores bytes of the text, file, png etc strings = stores textual information numbers = stores integers floats = stores decimals lists = stores lists of things dicts = stores objects/key value pairs + Addition = 2 + 4 == 6 - Subtraction = 4 - 2 == 2 * Multiplication = 4 * 2 == 8 ** Power of = 4 ** 2 == 16 / Division = 4 / 2 == 2 // Floor division = Math.floor(5 / 2) == 2 % Modulus = Remainder = 5 % 2 == 1 < Less than = 5 < 6 == True > Greater than = 6 > 5 == True <= Less than or equal to = 6 <= 8 == True >= Greater than or equal to = 8 >= 6 == True == Equal to = 6 == 6 == True != Not equal = 6 != 6 == False () Parenthesis = do this first = (6 + 3) * 3 == 27 [] list brackets = denote a list animals = ['dog', 'cat'] {} dict curly braces = {name: "Steve", age: 27} @decorators = @classmethod , comma = separates values : colon = starts a function or loop . dot = object dot notation = assign equal = set something equal to ; semi-colon = execute two code blocks in one line += addition incrementor = i += 1 -= subtraction incrementor = i -= 1 *= multiplication incrementor = i *= 2 /= Division incrementor = i /= 2 //= Floor divide and assign = i //= 2 %= Modulus assign = i %= 2 **= Power assign = exponential powers assign <file_sep>/ex30.py people = 30 cars = 40 trucks = 15 if cars > people: print("we should take the cars.") #should print "we should take the cars elif cars < people: print("We should not take the cars.") #doesn't evaluate else: print("We can't decide.") #if both values are equal, go to here. if trucks > cars: print("That's too many trucks.") #this won't evaluate elif trucks < cars: print("Maybe we could take the trucks.") #this will print else: print("We still can't decide.") #This won't evaluate. if people > trucks: print("Alright, let's just take the trucks.") #This will print out else: print("Fine, let's just stay home then.") #This won't print out """ What does elif do? else if: next condition to be met else is for all other cases if conditions are met, these work """<file_sep>/ex33forLoop.py def for_loop: numbers = [] for i in range(0, 6): print(f"At the top is {i}") numbers.append(i) print(f"At the bottom is {i}") print("Numbers now", numbers) print(f"at the bottom is {i}") print("The numbers") for num in numbers: print(numbers)<file_sep>/ex8.py formatter = "{} {} {} {}" print(formatter.format(1,2,3,4)) print(formatter.format("one", "two", "three", "four")) print(formatter.format("True", "False", "False", "True")) print(formatter.format(formatter, formatter, formatter, formatter)) print(formatter.format( "Here's a ", "little story about", "This guy named coco crisp", "He was the crispiest outfielder of all time" ))<file_sep>/ex19.py #function definition (the parameters, then prints out the items def cheese_and_crackers(cheese_count, boxes_of_crackers): print(f"You have {cheese_count} cheeses!") print(f"You have {boxes_of_crackers} boxes of crackers") print("Man that's enough for a party!") print("Get a blanket. \n") #this example puts in args into the function itself print("We can just give the function numbers directly") cheese_and_crackers(20, 30) #this sets the args to some value outside of the script print("OR we can use variables from our script:") amount_of_cheese = 10 amount_of_crackers = 50 #this defines the two vars as one with two parameters cheese_and_crackers(amount_of_cheese, amount_of_crackers) #we can define the args even using math print("We can even do math inside too:") cheese_and_crackers(10 + 20, 5 + 6) #we can add numbers to vars as well print("And we can combine the two, variables and math:") cheese_and_crackers(amount_of_cheese + 100, amount_of_crackers + 100)
7db2ff6c164bda9b4179f6314592a85020fb372d
[ "Python" ]
16
Python
Takashiidobe/learnPythonTheHardWayZedShaw
cb73e9079c2b93221ed1857801ad6be6d0ee2615
5e124bf9004a0d7d00f6b2cfd2d5df1f231da662
refs/heads/main
<repo_name>pawinhon1/chapter7<file_sep>/01_mysql_con_obj.php <?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; // สร้างการเชื่อมต่อ $conn = new mysqli($servername, $username, $password); // เช็คสถานะการเชื่อมต่อ if ($conn->connect_error) { die("Connection failed: " . $conn->connect_error); } echo "กำลังเชื่อมต่อ"; ?><file_sep>/02_mysql_con_pcd.php <?php $servername = "localhost"; $username = "username"; $password = "<PASSWORD>"; // สร้างการเชื่อมต่อ $conn = mysqli_connect($servername, $username, $password); // เช็คสถานะการเชื่อมต่อกับฐานข้อมูล if (!$conn) { die("Connection failed: " . mysqli_connect_error()); } echo "กำลังเชื่อมต่อกับฐานข้อมูล"; ?>
e7d178ae954f39ab0058ac8a79a81072d3ede376
[ "PHP" ]
2
PHP
pawinhon1/chapter7
d66bfced7d2a7b52b6d00a61d7efd4cd4bef5f86
e4fc2490574743ea681c52124ed631fdadb3b2e1
refs/heads/master
<file_sep>import React, { Component } from 'react'; import _ from 'lodash' import { Grid, Jumbotron, Button, Row, Col, Panel, ButtonToolbar, ToggleButtonGroup, ToggleButton } from 'react-bootstrap'; import './App.css'; import Api from '../utils/Api'; import Summon from '../utils/Summon'; import Dropdown from './Dropdown'; import ResultsGrid from './ResultsGrid'; import Header from './Header'; import Single from '../images/single.png'; import Multi from '../images/multi.png'; class App extends Component { constructor(props) { super(props); this.state = { versionSelection: '', bannerSelection: '', versionOptions: [{name:'Global',value:'globalMain'},{name:'Japan',value:'japanMain'}], bannerOptions: [''], bannerRates: [], results: [], allResults: [], bannerUrl: '', type: 'Standard', totalStones: 0, ssrCount: 0, srCount: 0, rCount: 0, otherCount: 0 }; this.handleVersionSelect = this.handleVersionSelect.bind(this); this.handleBannerSelect = this.handleBannerSelect.bind(this); this.handleClearForm = this.handleClearForm.bind(this); this.handleClearSummons = this.handleClearSummons.bind(this); this.single = this.single.bind(this); this.multi = this.multi.bind(this); this.setCardCounts = this.setCardCounts.bind(this); this.handleSetType = this.handleSetType.bind(this); } handleSetType(newValue) { this.setState({ type: newValue }); } handleClearForm(e) { e.preventDefault(); this.setState({ results: [], allResults: [], totalStones: 0, ssrCount: 0, srCount: 0, rCount: 0, otherCount: 0, type: 'Standard', bannerUrl: '', versionSelection: '', bannerSelection: '', bannerOptions: [''], bannerRates: [] }); } handleClearSummons(e) { e.preventDefault(); var resetRateCount = this.state.bannerRates; for (var i = 0, len = resetRateCount.length; i < len; i++) { resetRateCount[i].count = 0; } this.setState({ results: [], allResults: [], totalStones: 0, ssrCount: 0, srCount: 0, rCount: 0, otherCount: 0, bannerRates: resetRateCount }); } handleVersionSelect(e) { let self = this; var version = 'globalMain'; if (e.target.value === 'Japan') version = 'japanMain'; self.setState({versionSelection: e.target.value}); Api .getBanners(version) .then(function(data) { var options = []; for (var [key, value] of Object.entries(data)) { options.push({name:key, value:new Date(value)}); } self.setState({ bannerOptions: _.orderBy(options, ['value'], ['desc']) }) }); } handleBannerSelect(e) { let self = this; var bannerId = e.target.value.substr(0,e.target.value.indexOf(' ')); var banner = 'http://www.dbzdokkanstats.com/gachas/banners/gasha_top_banner_00' + bannerId + '.png'; if (self.state.versionSelection === 'Japan') { banner = 'http://www.dbzdokkanstats.com/jpngachas/banners/gasha_top_banner_00' + bannerId + '.png'; } self.setState({ bannerSelection: e.target.value, bannerUrl: banner }); Api .getRates(bannerId, self.state.versionSelection) .then(function(data) { self.setState({ bannerRates: data }) }); } single() { var card = Summon.Single(this.state.bannerRates); this.setCardCounts(card, 5); } multi() { var cards = Summon.Multi(this.state.bannerRates, this.state.type); this.setCardCounts(cards, 50); } setCardCounts(cards, stones) { var countSSRs = 0, countSRs = 0, countRs = 0; for(var i=0; i<=cards.length-1; i++) { if (cards[i].sort <= 1) { countSSRs++; } else if (cards[i].sort === 2) { countSRs++; } else if (cards[i].sort === 3) { countRs++; } } this.setState({ results: cards, totalStones: this.state.totalStones + stones, allResults: _.orderBy(Summon.Compress(this.state.allResults.concat(cards)), ['type','sort','count'],['asc','asc','desc']), ssrCount: this.state.ssrCount + countSSRs, srCount: this.state.srCount + countSRs, rCount: this.state.rCount + countRs }); } render() { return ( <div> <Header/> <Jumbotron className="top-margin"> <Grid> <Row className="show-grid"> <Col xs={12} md={6}> <Dropdown name='Select Version' placeholder={'Choose your version'} controlFunc={this.handleVersionSelect} options={this.state.versionOptions} selectedOption={this.state.versionSelection} /> {this.state.versionSelection !== '' ? ( <Dropdown name='Select Banner' placeholder={'Choose your banner'} controlFunc={this.handleBannerSelect} options={this.state.bannerOptions} selectedOption={this.state.bannerSelection} /> ) : null } {this.state.bannerSelection !== '' ? ( <ButtonToolbar> <ToggleButtonGroup type="radio" name="options" value={this.state.type} onChange={this.handleSetType}> <ToggleButton value='Standard'>Standard</ToggleButton> <ToggleButton value='GSSR'>GSSR</ToggleButton> <ToggleButton value='fGSSR'>Featured GSSR</ToggleButton> </ToggleButtonGroup> </ButtonToolbar> ) : null } </Col> {this.state.bannerSelection !== '' ? ( <Col xs={12} md={6}> <img src={this.state.bannerUrl} className="App-image" alt="" /><br/> </Col> ) : null} </Row> {this.state.bannerSelection !== '' ? ( <Row className="show-grid"> <Col xs={12} md={6}> <input type="image" onClick={this.single} className="App-image" src={Single} alt="Do a single summon!" /> <input type="image" onClick={this.multi} className="App-image" src={Multi} alt="Do a multi summon!" /> </Col> </Row> ) : null } {this.state.totalStones !== 0 ? ( <Grid> <Row className="show-grid"> <Col xs={12} md={2} ><Button bsStyle="warning" onClick={this.handleClearSummons}>Reset Summons Only</Button> </Col> <Col xs={12} md={2} ><Button bsStyle="danger" onClick={this.handleClearForm}>Reset All</Button> </Col> <Col xs={12} md={8}> <b>Summon Data - </b> Total Cards: {(this.state.totalStones/5)}, SSR %: {(this.state.ssrCount/this.state.totalStones*500).toFixed(2)}, SR %: {(this.state.srCount/this.state.totalStones*500).toFixed(2)}, R %: {(this.state.rCount/this.state.totalStones*500).toFixed(2)} </Col> </Row> <Row className="show-grid"> <Col xs={12} md={6}> <Panel header="Summon Results" bsStyle="primary"> <ResultsGrid items={_.chunk(this.state.results, 5)} type='current' /> </Panel> </Col> <Col xs={12} md={6}> <Panel header={this.state.allResults.length + " unique cards summoned in " + this.state.totalStones + " stones used"} bsStyle="primary"> <ResultsGrid items={_.chunk(this.state.allResults, 5)} type='all' /> </Panel> </Col> </Row> </Grid> ) : null } </Grid> </Jumbotron> </div> ); } } export default App; <file_sep>import React from 'react'; import PropTypes from 'prop-types'; import { Table } from 'react-bootstrap'; import './App.css'; const ResultsGrid = (props) => ( <Table striped condensed> <tbody> {props.items.map((row, index) => <tr key={index}> {row.map((col, index) => <td key={index}> <a target="_blank" href={col.spacelink}> <img src={col.thumb} alt="card" className={"thumb " + (col.type.includes('b-featured') ? 'featured' : '') + (col.type.includes('a-lr') ? 'lr' : '')} /> </a> <img src={col.rarity} className="rarity" alt="rarity"/> {props.type ==='all' ? ( <span>x{col.count}</span> ): null} </td> )} </tr> )} </tbody> </Table> ); ResultsGrid.propTypes = { items: PropTypes.array.isRequired, type: PropTypes.string.isRequired }; export default ResultsGrid;
8578bbaad3c0f1ecb44191b40a81677e3f2c7b72
[ "JavaScript" ]
2
JavaScript
atjohns2/DokkanSummonSimulator
14ae7576448e016a129b21eda6655638d95f539d
d9f386e8b0bf6c31ea877ccaab5b062d75374ae1
refs/heads/master
<file_sep>package com.iot.login.controller; import com.iot.login.common.ResultVo; import com.iot.login.request.UserLoginRequest; import com.iot.login.service.UserLoginService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.validation.BindingResult; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import javax.validation.Valid; /** * @author lxq * @version 2020/5/10 - 18:26 */ @RestController @RequestMapping(value = {"/user/"},produces = "application/json;charset=UTF-8") public class UserLoginController { @Autowired private UserLoginService userLoginService; @RequestMapping(value = "login") public ResultVo login(@Valid UserLoginRequest userLoginRequest, BindingResult bindingResult){ ResultVo result = new ResultVo(); try { //数据的校验 if(bindingResult.hasErrors()){ result.setCode(0); result.setMessage(bindingResult.getAllErrors().get(0).getDefaultMessage()); return result; } //查询用户 return userLoginService.list(userLoginRequest); }catch (Exception e){ e.printStackTrace(); result.setCode(0); result.setMessage("数据异常!"); } return result; } } <file_sep>package com.iot.login.service; import com.iot.login.common.ResultVo; import com.iot.login.request.UserLoginRequest; /** * @author lxq * @version 2020/5/10 - 18:25 */ public interface UserLoginService { ResultVo list(UserLoginRequest userLoginRequest); }
475a5f59332eaed90b15c0dd55c3cc8f9768a690
[ "Java" ]
2
Java
iot2020lxq/login
4a654773d274f123ab847c0e299e1bb668834f8c
eb212713a7940c4ab8b604efb723b1b6311e2465
refs/heads/master
<file_sep># Условие * Сформировать готовый для установки deb-пакет со скомпилированной программой и выложить его в репозиторий. * Прислать ссылку на репозиторий в github и ссылку на репозиторий с пакетом. # Будет здорово, но не обязательно: * Добавить версионность в пакет и сообщение. * Запустить на этапе сборки тесты. # Может пригодиться: * Выложить исходные тексты в репозиторий на github. * Залогиниться на https://travis-ci.org/ и включить для своего репозитория автоматическую сборку. * Залогиниться на https://bintray.com/ (For an Open Source Account и аккаунт github). * Создать новый репозиторий - имя произвольное, тип Debian, Default Licenses любая. После создания отредактировать включив GPG sign. * Создать в созданном репозитории новый пакет - имя произвольное, ссылка на контроль версии может быть указана как - (просто чтобы было заполнено). * По ссылке https://bintray.com/profile/edit в пункте API Key скопировать ключ. В настройках репозитория в https://travis-ci.org создать переменную, например BINTRAY_API_KEY, и в качестве значения API Key. Это позволит не указывать явно ключ в исходниках. # Пример на github: * https://github.com/vvz-otus/hw02.cpp01_2 * Только ваш проект называться будет helloworld (а не cpp01_2:) Критерии оценки: FROM ubuntu:trusty * RUN apt-key adv --keyserver keyserver.ubuntu.com --recv-keys 379CE192D401AB61 * RUN echo "deb http://dl.bintray.com/username/componentname trusty main" | sudo tee -a /etc/apt/sources.list * RUN apt update * RUN apt install -y packagename * Задание считается выполненым успешно, если после подключения репозитория, установки пакета и запуска бинарного файла появилось сообщение: “Hello, World!”. <file_sep>#include <iostream> #include "version.h" int getProjectBuildNumber() { return PROJECT_VERSION_PATCH; } std::string getProjectVersion() { return PROJECT_VERSION; } <file_sep>cmake_minimum_required(VERSION 3.2) #get project version SET(BUILD_NUMBER "999") IF(DEFINED ENV{TRAVIS_BUILD_NUMBER}) SET(BUILD_NUMBER $ENV{TRAVIS_BUILD_NUMBER}) ENDIF() file (STRINGS ".version" PROJECT_VERSION) #init project project (helloworld VERSION ${PROJECT_VERSION}.${BUILD_NUMBER}) #inclue cmake modules SET(CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake" ${CMAKE_MODULE_PATH}) #find Boost unit_test_framework find_package(Boost COMPONENTS unit_test_framework REQUIRED) # get TCLAP find_package(TCLAP REQUIRED) include_directories(${TCLAP_INCLUDE_DIR}) ##version library # configure a header file to pass some of the CMake settings # to the source code configure_file( ${CMAKE_SOURCE_DIR}/src/version.h.in ${CMAKE_SOURCE_DIR}/src/version.h ) add_library(version ./src/version.cpp) #main app add_executable(helloworld ./src/main.cpp) #test app add_executable(unit_test_1 ./src/test.cpp) #etc set_target_properties(helloworld unit_test_1 PROPERTIES CXX_STANDARD 14 CXX_STANDARD_REQUIRED ON COMPILE_OPTIONS -Wpedantic -Wall -Wextra ) set_target_properties(unit_test_1 PROPERTIES COMPILE_DEFINITIONS BOOST_TEST_DYN_LINK INCLUDE_DIRECTORIES ${Boost_INCLUDE_DIR} ) target_link_libraries(helloworld version) target_link_libraries(unit_test_1 ${Boost_LIBRARIES} version ) install(TARGETS helloworld RUNTIME DESTINATION bin) enable_testing() add_test(test_version_valid unit_test_1) #Debian package set(CPACK_GENERATOR DEB) set(CPACK_PACKAGE_VERSION_MAJOR "${PROJECT_VERSION_MAJOR}") set(CPACK_PACKAGE_VERSION_MINOR "${PROJECT_VERSION_MINOR}") set(CPACK_PACKAGE_VERSION_PATCH "${PROJECT_VERSION_PATCH}") set(CPACK_DEBIAN_PACKAGE_NAME "helloworld") set(CPACK_PACKAGE_CONTACT male<EMAIL>) set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON) include (CPack) <file_sep>#define BOOST_TEST_MODULE test_main #include <boost/test/unit_test.hpp> #include "version.h" BOOST_AUTO_TEST_SUITE(test_suite_main) BOOST_AUTO_TEST_CASE(test_version_valid) { BOOST_CHECK( getProjectBuildNumber() > 0 ); BOOST_ASSERT( !getProjectVersion().empty() ); } BOOST_AUTO_TEST_SUITE_END() <file_sep>#include <iostream> #include <vector> #include <string> #include <tclap/CmdLine.h> #include "version.h" using namespace std; int main(int argc, char* argv[]) { try { TCLAP::CmdLine cmd("Simple Hello World", ' ', getProjectVersion()); cmd.parse( argc, argv ); } catch (TCLAP::ArgException &e) { cerr << "error: " << e.error() << " for arg " << e.argId() << endl; } cout << "Hello, World!" << endl; return 0; }
3309ae4937e5c1269a3a0c2ac25960e4b14bb639
[ "Markdown", "CMake", "C++" ]
5
Markdown
malegkin/helloworld
bda91103a535930679da669c22f0d048ca5d0e6d
b2945bdaec94f860c9fa4011a84b1f5586679d01
refs/heads/master
<repo_name>anandanand84/server-timing<file_sep>/index.js const http = require('http'); function requestHandler(request, response) { const headers = { 'Server-Timing' : ` sql-1=0.1; "MySQL lookup server", sql-2=0.9; "MySql Shard Server", fs=0.6; "File System", cache=0.3; "Cache", cpu=1.23; "Total CPU" `.replace(/\n/g, '') } response.writeHead(200, headers); response.write('Look at timings in developer tools, I have custom server timings'); return setTimeout(_=>{ response.end(); }, 1230) } var server = http.createServer(requestHandler) server.listen(3000);
034b08d896e15a3e8bc55438cfd9f1d63b289cc5
[ "JavaScript" ]
1
JavaScript
anandanand84/server-timing
7e6fb133b7a3e251c50b0eae2338798dd7743702
1f8570e58b21b412822f05987aa7c3162de44390
refs/heads/master
<repo_name>Zacknero/LoadChildrenOutletSecondary<file_sep>/src/app/features/cars/services/car.resolver.ts import { Injectable } from '@angular/core'; import { Resolve, ActivatedRouteSnapshot, RouterStateSnapshot, } from '@angular/router'; import { Observable } from 'rxjs'; import { CarsService } from './cars.service'; import { DetailedCar } from '../models/detailed-car'; @Injectable() export class CarResolver implements Resolve<DetailedCar> { constructor(private carsService: CarsService) { } resolve(route: ActivatedRouteSnapshot): Observable<DetailedCar> { return this.carsService.getCar(+route.paramMap.get('carId')); } }<file_sep>/src/app/features/cars/models/detailed-car.ts import { Car } from './car'; export interface DetailedCar extends Car { details: object; }<file_sep>/src/app/features/cars/services/cars.service.ts import { Injectable } from '@angular/core'; import { Observable, of } from 'rxjs'; import { delay, map } from 'rxjs/operators'; import { Car } from '../models/car'; import { DetailedCar } from '../models/detailed-car'; const MOCK_CARS: DetailedCar[] = [ { id: 1, brand: 'Porsche', model: '911', details: { price: 500000 } }, { id: 2, brand: 'Ferrari', model: 'F50', details: { price: 800000 } }, { id: 3, brand: 'Porsche', model: 'Panamera', details: { price: 300000 } } ]; @Injectable() export class CarsService { getCars(): Observable<Car[]> { return of(MOCK_CARS.map(car => { const { id, model, brand } = car; return { id, model, brand } })).pipe( delay(2000) ); } getCar(carId: number): Observable<DetailedCar> { return of(MOCK_CARS.find(car => car.id === carId)).pipe( delay(3000) ); } }<file_sep>/src/app/features/simpson/simpson.module.ts import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {SimpsonComponent} from './simpson.component'; import {RouterModule, Routes} from '@angular/router'; export const routers: Routes = [ { path: 'simpson', component: SimpsonComponent }, { path: 'homer', loadChildren: () => import('./homer/homer.module').then(m => m.HomerModule) } ]; @NgModule({ declarations: [ SimpsonComponent ], imports: [ CommonModule, RouterModule.forChild(routers) ], exports: [ RouterModule ] }) export class SimpsonModule { } <file_sep>/src/app/core/core.module.ts import { NgModule } from '@angular/core'; import { LoadingModule } from 'ngx-loading'; import { LayoutService } from './services/layout.service'; import { ContestComponent } from './containers/contest/contest.component'; import { ContactFormComponent } from './containers/contact-form/contact-form.component'; @NgModule({ exports: [ LoadingModule ], providers: [ LayoutService ], declarations: [ ContestComponent, ContactFormComponent ] }) export class CoreModule { }<file_sep>/src/app/features/cars/components/car-detail/car-detail.component.ts import { Component, Input} from '@angular/core'; import { DetailedCar } from '../../models/detailed-car'; @Component({ selector: 'app-car-detail', templateUrl: './car-detail.component.html', styleUrls: ['./car-detail.component.css'] }) export class CarDetailComponent { @Input() car: DetailedCar; }<file_sep>/README.md # LoadChildrenOutletSecondary This project show how load children with secondary outlet. Have two examples: one with normal load children and other with lazy loading Here implemented ngx-loading for show spinner/loading bar. You can Try it on Stackblitc: https://stackblitz.com/github/Zacknero/LoadChildrenOutletSecondary <file_sep>/src/app/features/cars/cars-routing.module.ts import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; import {CarsPageComponent} from './containers/cars-page/cars-page.component'; import {SelectedCarPageComponent} from './containers/selected-car-page/selected-car-page.component'; import {CarResolver} from './services/car.resolver'; import {FiglioloComponent} from "./components/figliolo/figliolo.component"; import {ContestComponent} from "../../core/containers/contest/contest.component"; import {ContactFormComponent} from "../../core/containers/contact-form/contact-form.component"; const routes: Routes = [ { path: 'cars', children: [ { path: '', component: CarsPageComponent, data: { title: 'Cars' } }, { path: ':carId', component: SelectedCarPageComponent, resolve: { car: CarResolver }, data: { title: 'Car details' } }, { path: 'figliolo', component: FiglioloComponent, children: [ { path: 'contest', component: ContestComponent, outlet: 'minor', pathMatch: 'full' }, { path: 'contact', component: ContactFormComponent, outlet: 'minor', pathMatch: 'full' } ] } ] } ]; @NgModule({ imports: [RouterModule.forChild(routes)], exports: [RouterModule] }) export class CarsRoutingModule { } <file_sep>/src/app/features/simpson/homer/homer.module.ts import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {RouterModule, Routes} from "@angular/router"; import {HomerComponent} from "./homer.component"; import {BartCompComponent} from './bart-comp/bart-comp.component'; import { LisaCompComponent } from './lisa-comp/lisa-comp.component'; const routes: Routes = [ { path: 'homer', component: HomerComponent, children: [ { path: 'bart', component: BartCompComponent, outlet: 'major' }, { path: 'lisa', component: LisaCompComponent, outlet: 'major' } ] } ]; @NgModule({ declarations: [ HomerComponent, BartCompComponent, LisaCompComponent ], imports: [ CommonModule, RouterModule.forChild(routes) ], exports: [ RouterModule ] }) export class HomerModule { } <file_sep>/src/app/features/simpson/simpson.component.ts import { Component, OnInit } from '@angular/core'; @Component({ selector: 'app-simpson', templateUrl: './simpson.component.html', styleUrls: ['./simpson.component.css'] }) export class SimpsonComponent implements OnInit { constructor() { } ngOnInit() { } } <file_sep>/src/app/features/simpson/homer/bart-comp/bart-comp.component.spec.ts import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing'; import { BartCompComponent } from './bart-comp.component'; describe('FirstCompComponent', () => { let component: BartCompComponent; let fixture: ComponentFixture<BartCompComponent>; beforeEach(waitForAsync(() => { TestBed.configureTestingModule({ declarations: [ BartCompComponent ] }) .compileComponents(); })); beforeEach(() => { fixture = TestBed.createComponent(BartCompComponent); component = fixture.componentInstance; fixture.detectChanges(); }); it('should create', () => { expect(component).toBeTruthy(); }); }); <file_sep>/src/app/features/cars/cars.module.ts import {NgModule} from '@angular/core'; import {CommonModule} from '@angular/common'; import {CarsRoutingModule} from './cars-routing.module'; import {CarsPageComponent} from './containers/cars-page/cars-page.component'; import {SelectedCarPageComponent} from './containers/selected-car-page/selected-car-page.component'; import {CarPreviewComponent} from './components/car-preview/car-preview.component'; import {CarDetailComponent} from './components/car-detail/car-detail.component'; import {CarsService} from './services/cars.service'; import {CarResolver} from './services/car.resolver'; import {FiglioloComponent} from './components/figliolo/figliolo.component'; @NgModule({ imports: [ CommonModule, CarsRoutingModule ], declarations: [ CarsPageComponent, SelectedCarPageComponent, CarPreviewComponent, CarDetailComponent, FiglioloComponent ], providers: [ CarsService, CarResolver ] }) export class CarsModule { } <file_sep>/src/app/features/cars/components/figliolo/figliolo.component.html <h4> This component have second router-outlet named "minor". There outlet put contest and contact components via route </h4> <router-outlet name="minor"></router-outlet> <file_sep>/src/app/app.component.ts import { Component, OnInit } from '@angular/core'; import { Title } from '@angular/platform-browser'; import { Observable } from 'rxjs'; import { LayoutService } from './core/services/layout.service'; @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent implements OnInit { isSpinnerVisibile$: Observable<boolean> = this.layoutService.isNavigationPending$; constructor(private titleService: Title, private layoutService: LayoutService) { } ngOnInit() { this.layoutService.appTitle$.subscribe(appTitle => this.titleService.setTitle(appTitle)); } } <file_sep>/src/app/features/cars/containers/cars-page/cars-page.component.ts import { Component, OnInit } from '@angular/core'; import {Observable} from 'rxjs'; import {CarsService} from '../../services/cars.service'; import {Car} from '../../models/car'; @Component({ selector: 'app-cars-page', templateUrl: './cars-page.component.html', styleUrls: ['./cars-page.component.css'] }) export class CarsPageComponent implements OnInit { cars$: Observable<Car[]>; constructor(private carsService: CarsService) { } ngOnInit() { this.cars$ = this.carsService.getCars(); } }<file_sep>/src/app/features/cars/containers/selected-car-page/selected-car-page.component.ts import { Component, OnInit } from '@angular/core'; import { ActivatedRoute } from '@angular/router'; import { Observable } from 'rxjs'; import { pluck } from 'rxjs/operators'; import { DetailedCar } from '../../models/detailed-car'; @Component({ selector: 'app-selected-car-page', templateUrl: './selected-car-page.component.html', styleUrls: ['./selected-car-page.component.css'] }) export class SelectedCarPageComponent implements OnInit { car$: Observable<DetailedCar>; constructor(private route: ActivatedRoute) { } ngOnInit() { this.car$ = this.route.data.pipe( pluck('car') ); } }<file_sep>/src/app/features/cars/components/car-preview/car-preview.component.ts import { Component, Input } from '@angular/core'; import { Car } from '../../models/car'; @Component({ selector: 'app-car-preview', templateUrl: './car-preview.component.html', styleUrls: ['./car-preview.component.css'] }) export class CarPreviewComponent { @Input() car: Car; get carName(): string { return `${this.car.brand} ${this.car.model}`; } }
cfc72b92a55b8a3dc31daf27604ec7f512106cd2
[ "Markdown", "TypeScript", "HTML" ]
17
TypeScript
Zacknero/LoadChildrenOutletSecondary
ccef47fddb1be6177f25909ed93bb3e5e50e501d
cdb822ddb1e4f177fed3599556db75c408f492ee
refs/heads/master
<repo_name>kridah/MLAI<file_sep>/øving uke 2/uke2_4.py # Skriv en rekursiv funksjon som beregner lengden på # en streng. Du kan ikke bruke len () -funksjonen # mens du beregner lengden på strengen. # Du må stole på funksjonen du skriver. # Sett denne funksjonen i et program som ber # brukeren om å legge inn en streng og deretter skrive ut # lengden på den strengen. # for hvert rekursive kall, fjern et tegn fra strengen # str[1:] spiser seg gjennom strengen fra høyre mot venstre def calculate_length(str): if str == '': return 0 return 1 + calculate_length(str[1:]) str = calculate_length("Dette er en streng med 31 tegn.") for char in len(str): print(char, str)<file_sep>/innlevering_4/readnt.py from typing import NamedTuple from innlevering_4.BinaryTree import BinaryTree from innlevering_4.BinaryTreeNode import BinaryTreeNode class Person(NamedTuple): etternavn: str fornavn: str adresse: str postnummer: int poststed: str def print_person(self): print(f"{self.fornavn} {self.etternavn} bor i {self.adresse}, {self.postnummer} {self.poststed}") def __str__(self): print(f"{self.fornavn} {self.etternavn} bor i {self.adresse}, {self.postnummer} {self.poststed}") # Dette lager Person-objekter som man kan referere til med atributtene til klassen def get_persons(): return [ Person("ELI", "<NAME>", "<NAME>", 9775, "GAMVIK"), Person("TOLLEFSEN","<NAME>","<NAME> 79",1305,"HASLUM") ] def get_persons_from_file(): persons = [] with open("Personer.dta", "r", encoding="ISO-8859-1") as file: for line in file: p = line.split(";") persons.append(p) return persons persons = [ Person("KRISTIANSEN","<NAME>","LEINAHYTTA 36",7224,"MELHUS"), Person("OLDERVIK","<NAME>","KRÅKA 84",7437,"FEDJE"), Person("GJERSTAD","TORKJELL","HOSTELAND 2 83",1361,"ØSTERÅS"), Person("<NAME>","<NAME>","LINNGÅRD 22",1451,"NESODDTANGEN") ] # nodes = [ # Person(etternavn="KRISTIANSEN",fornavn="<NAME>",adresse="LEINAHYTTA 36",postnummer=7224,poststed="MELHUS"), # Person(etternavn="OLDERVIK",fornavn="<NAME>",adresse="KRÅKA 84",postnummer=7437,poststed="FEDJE"), # Person(etternavn="GJERSTAD",fornavn="TORKJELL",adresse="HOSTELAND 2 83",postnummer=1361,poststed="ØSTERÅS"), # Person(etternavn="<NAME>",fornavn="<NAME>",adresse="LINNGÅRD 22",postnummer=1451,poststed="NESODDTANGEN") # ] tree = BinaryTree() # tree.insert(value="2") # tree.insert(value="1") # tree.insert(value="4") # tree.insert(value="7") # print(tree.find(key="2")) # max_node = tree.findMax() # print(max_node) tree.insert("mordi")<file_sep>/innlevering_4/Persons.py from typing import NamedTuple persons = [] class Person(NamedTuple): etternavn: str fornavn: str adresse: str postnummer: int poststed: str def __str__(self): print(f"{self.fornavn} {self.etternavn} bor i {self.adresse}, {self.postnummer} {self.poststed}") def get_persons_from_file(self): with open("Personer.dta", "r", encoding="ISO-8859-1") as file: for line in file: p = line.split(";") persons.append(p) return persons <file_sep>/innlevering_5/innlevering5.py # Din kode skrives her: import pandas as pd from collections import namedtuple from innlevering_5.BinaryTree import BinaryTree columnnames = ['etternavn', 'fornavn', 'adresse', 'postnr', 'poststed'] df = pd.read_csv("Personer.dta", encoding="ISO-8859-1", names=columnnames, header=None, sep=";") person = namedtuple("Person",["etternavn", "fornavn", "adresse", "postnr", "poststed"]) tree = BinaryTree() def tuplefy(lastname="", firstname="", adress="", postalcode="", postal=""): return person(etternavn=lastname, fornavn=firstname, adresse=adress, postnr=postalcode, poststed=postal) persons = [tuplefy(lastname, firstname, adress, postalcode, postal) for lastname, firstname, adress, postalcode, postal in zip(df["etternavn"], df["fornavn"], df["adresse"], df["postnr"], df["poststed"])] for p in persons: tree.insert(value=p) # 1, 10, 100, 1000, 10000, 100000 # level = n-1 levels = [0, 9, 99, 999, 9999, 99999] for index in levels: print("nivå ", (tree.find(persons[index]).level), " :: ", tree.find(persons[index]).value) # Din kode fore rekursive delete kan du legge inn som kommentar i denne koden, samtidig som du endrer i BinaryTree # # Din kode for slettingen (del B) skrives her: tree.delete_recursive(persons[999]) tree.delete_recursive(persons[9999]) # Skal nå få none på disse to nivåene for index in levels: node = tree.find(persons[index]) # hvis det finnes noder på nivået if node: print("nivå ", node.level, " :: ", node.value) # ingen noder på nivået else: print("Ingen noder funnet på nivå", index + 1) levels = [7, 49, 399, 2299, 7999, 49998, 74999] for index in levels: print("nivå ", tree.find(persons[index]).level, " :: ", tree.find(persons[index]).value) # dictionary levels = {} def count_levels(node = None): if not node: count_levels(tree._root) else: try: levels[node.level] += 1 except KeyError: levels[node.level] = 1 if node.left: count_levels(node.left) if node.right: count_levels(node.right) count_levels() for (level, count) in levels.items(): print("nivå", level, "antall: ", count)<file_sep>/innlevering_3/readpersons.py # <NAME> from collections import namedtuple import csv persons = [] with open("Personer.dta", "r", encoding="ISO-8859-1") as file: for line in file: p = line.split(";") persons.append(p) # lager en todimensjonal liste # def add_persons_to_heap(p_list): # current_index = len(p_list) - 1 # # while current_index > 0: # parent_index = round((current_index - 1)/2) # round to nearest int # # swap if the current object is greater than its parent # print(p_list[current_index][0], ">", p_list[parent_index][0], p_list[current_index][0] > p_list[parent_index][0]) # if p_list[current_index][0] > p_list[parent_index][0]: # compares on lastname # temp = p_list[current_index] # p_list.insert(current_index, persons[parent_index]) # p_list.insert(parent_index, temp) # else: # break # current_index = parent_index size = len(persons) persons.insert(0, size - 1) persons.remove(size - 1) current_index = 0 while current_index < len(persons): left_child_index = 2 * current_index + 1 right_child_index = 2 * current_index + 2 if left_child_index >= len(persons): # is heap break max_index = left_child_index if right_child_index < len(persons): if persons[max_index][0] > persons[right_child_index][0]: max_index = right_child_index if persons[current_index] > persons[max_index]: temp = persons[max_index] persons.insert(max_index, persons[current_index]) persons.insert(current_index, temp) current_index = max_index else: break print("Index 0:", persons[0], "\nIndex 20000:", persons[20000], "\nIndex 40000:",persons[40000], "\nIndex 80000:",persons[80000]) <file_sep>/øving 4/sorting.py import random import string import datetime as date # REFERANSER # Hands-On Data Structures and Algorithms with Python # https://pynative.com/python-generate-random-string/ # https://www.geeksforgeeks.org/python-program-convert-string-list/ # converterer en strint til en list def convert(string): my_list = [] my_list[:0] = string return my_list # oppgave 1 # Lag en funksjon som returnerer et randomgenerert array av strenger. # Størrelsen skal angis som parameter def random_string_generator(length): letters = string.ascii_letters.upper() result_str = ''.join(random.choice(letters) for i in range(length)) print("List of length ", length, "is to be sorted ") return result_str # Bruk rutinen fra Oppgave 1 og sorter arrayet vha Boblesortering def bubblesort(unordered_list): iteration_number = len(unordered_list) - 1 for i in range(iteration_number): for j in range(iteration_number): if unordered_list[j] > unordered_list[j + 1]: temp = unordered_list[j] unordered_list[j] = unordered_list[j + 1] unordered_list[j + 1] = temp return unordered_list def insertionsort(unsorted_list): for index in range(1, len(unsorted_list)): search_index = index insert_value = unsorted_list[index] while search_index > 0 and unsorted_list[search_index-1] > insert_value: unsorted_list[search_index] = unsorted_list[search_index-1] search_index -= 1 unsorted_list[search_index] = insert_value return unsorted_list # selection sort nekter å kjøre 100.000 elementer def selectionsort(unsorted_list): size_of_list = len(unsorted_list) for i in range(size_of_list): for j in range(i+1, size_of_list): if unsorted_list[j] < unsorted_list[i]: temp = unsorted_list[i] unsorted_list[i] = unsorted_list[j] unsorted_list[j] = temp return unsorted_list # def mergesort(unsorted_list): # if len(unsorted_list) == 1: # return unsorted_list # # mid_point = int(len(unsorted_list) / 2) # # first_half = unsorted_list[:mid_point] # second_half = unsorted_list[mid_point:] # # half_a = mergesort(first_half) # half_b = mergesort(second_half) # # return merger(half_a, half_b) # def merger(first_sublist, second_sublist): # i = j = 0 # merged_list = [] # # while i < len(first_sublist) and j < len (second_sublist): # if first_sublist[i] < second_sublist[j]: # merged_list.append(first_sublist[i]) # i += 1 # else: # merged_list.append(second_sublist[j]) # j += 1 # # while i < len(first_sublist): # merged_list.append(first_sublist[i]) # i += 1 # # while j < len(second_sublist): # merged_list.append(second_sublist[j]) # j += 1 # # return merged_list random_string = random_string_generator(10000) random_list = convert(random_string) # start_time = date.datetime.now() # bubblesort(random_list) # end_time = date.datetime.now() # used_time = end_time - start_time # print("Bubblesort: ", used_time) # start_time = date.datetime.now() # insertionsort(random_list) # end_time = date.datetime.now() # used_time = end_time - start_time # print("Insertin sort:", used_time) # start_time = date.datetime.now() # #mergesort(random_list) # end_time = date.datetime.now() # used_time = end_time - start_time # print("Merge sort:", used_time) # start_time = date.datetime.now() # selectionsort(random_list) # end_time = date.datetime.now() # used_time = end_time - start_time # print("Selection sort:", used_time) from sorting_visualizer import visualizer visualizer.visualize('mergesort') <file_sep>/øving_3/test_stack.py import unittest from øving_3 import øving_uke_3 class MyTestCase(unittest.TestCase): def setUp(self) -> None: stack = øving_uke_3.MyStack() def test_something(self): self.assertEqual(True, False) def test_stack_push(self): øving_uke_3.stack.push(3) if __name__ == '__main__': unittest.main() <file_sep>/øving uke 2/uke2_2.py # Gjennomfør et eksperiment for å bevise at produktet med to tall ikke er # avhengig av størrelsen på de to tallene som multipliseres. # Skriv et program som plottar resultatene av å multiplisere antall i # forskjellige størrelser sammen. # Hint: For å få en gode data om dette kan det være lurt å gjøre mer enn en av # disse multiplikasjonene og sette dem i gang som en gruppe siden en # multiplikasjon skjer ganske raskt på en datamaskin. # Kontroller at det virkelig er en O (1) -operasjon. Ser du noen avvik? import datetime as date import random import numpy as np import matplotlib.pyplot as plt spent_time = [] result = [] # multipliserer to tilfeldige tall i range 1, 10000 # tiden ligger mellom 1-5 mikrosekund # det ser ut til å være minimal økning i tiden selv ved mangedobling def multiplier(rnd): start = date.datetime.now() result.append(rnd * (rnd * rnd)) end = date.datetime.now() spent = end - start spent_time.append(spent) for s in range(len(spent_time)): print("Spent time: ", str(spent_time[s]), "Result: ", print(result[s])) for i in range(1, 10): rnd = np.random.randint(1, 100) multiplier(rnd) <file_sep>/øving_3/øving_uke_3.py class MyNode(object): def __init__(self, data=None, next=None, prev=None): self.data = data self.next = next self.prev = prev # Doubly linked list class MyLinkedList(object): def __init__(self): self.head = None # first node in the list self.tail = None # last node in the list self.size = 0 def append(self, data): # Encapsulate the data in a MyNode new_node = MyNode(data, None, None) if self.head is None: self.head = new_node self.tail = self.head else: new_node.prev = self.tail self.tail.next = new_node self.tail = new_node self.count += 1 def len(self): return self.size def iter(self): current = self.tail while current: val = current.data current = current.next yield val def delete_item(self, data): current = self.head node_deleted = False if current is None: node_deleted = False elif current.data == data: self.head = current.next self.head.prev = None node_deleted = True elif self.tail.data == data: # item found at end of list self.tail = self.tail.prev self.tail.next = None node_deleted = True else: while current: if current.data == data: current.prev.next = current.next current.next.prev = current.prev node_deleted = True current = current.next if node_deleted: self.count -= 1 def contains(self, item): for node in self.iter(): if item.data == node: return True return False # Working Stack (MyLinkedList currently not implemented) class MyStack: def __init__(self): self.top = None self.size = 0 def push(self, data): node = MyNode(data) if self.top: node.next = self.top self.top = node else: self.top = node self.size += 1 def pop(self): if self.top: data = self.top.data self.size -= 1 if self.top.next: self.top = self.top.next else: self.top = None return data else: return None def peek(self): if self.top: return self.top.data else: return None myList = MyLinkedList() stack = MyStack() stack.push(1) stack.push(2) print(myList.len()) print(stack.pop()) print(stack.pop()) print(stack.pop()) <file_sep>/øving uke 2/uke2_3.py # Skriv en rekursiv funksjon intpow(x, n) som tar i mot to # heltall, x og n, og beregner x ^ n. # Sørg for å legge den i et program med flere testtilfeller # for å teste at funksjonen din fungerer riktig def intpow(x, n): if n == 0: return 1 else: return x * intpow(x, n - 1) for i in range(0,10): real_sum = i ** i # innebygd funksjon for å regne opphøyd i intsum = intpow(i, i) print(intsum == real_sum)<file_sep>/innlevering_2/i2_oppg3.py class NewInt(int): def __init__(self, range_max): super().__init__() self.index = 0 def is_fib(self): f0, f1 = 0, 1 while True: if f0 > 100_000: return False if self == f0: return True f0, f1 = f1, f0 + f1 int_list = [NewInt(i) for i in range(100000)] compared_fibonaccis = [x for x in int_list if x.is_fib()] print(compared_fibonaccis) <file_sep>/øving uke 2/uke2_1.py import datetime as date # Det ser ikke ut til at lengden på strengen har mye å si for tiden det tar å sammenligne to strenger, # ved hjelp av == # Den alternative string-looper-funksjonen løper gjennom to strenger og sammenligner hver char. # Loopen avbrytes hvis en char er ulik def compare_str(x, y): print("String comparer:") start_time = date.datetime.now() x == y end_time = date.datetime.now() used_time = end_time - start_time print(used_time) def string_looper(x, y): print("String looper:") start_time = date.datetime.now() for a, b in zip(x, y): print(a, b) if a != b: print("Break") break end_time = date.datetime.now() used_time = end_time - start_time print(used_time) lorem = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac tortor malesuada, tristique velit vel, ullamcorper purus. Sed dolor sapien." ipsum = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ac tortor malesuada, tristique velit vel, ullamcorper purus. Sed dolor sapien." long_lorem = """Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vel iaculis eros. Proin aliquet, lorem nec porttitor euismod, neque massa dapibus magna, et vulputate enim felis in nulla. Integer in lacinia arcu. Phasellus quis vulputate tortor. Aliquam fermentum venenatis magna, eget vestibulum quam auctor nec. Etiam dictum justo tellus, vitae sagittis odio congue sit amet. Sed consequat leo non odio porttitor viverra nec ac urna. Morbi felis nunc, finibus quis sapien sit amet, eleifend molestie libero. Fusce ut odio neque. Pellentesque vitae sodales mi. Ut viverra feugiat dui non rutrum. Phasellus feugiat nibh vel nisl porttitor accumsan. Donec bibendum, dolor.""" long_lorem2 = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus vel iaculis eros. Proin aliquet, lorem nec porttitor euismod, neque massa dapibus magna, et vulputate enim felis in nulla. Integer in lacinia arcu. Phasellus quis vulputate tortor. Aliquam fermentum venenatis magna, eget vestibulum quam auctor nec. Etiam dictum justo tellus, vitae sagittis odio congue sit amet. Sed consequat leo non odio porttitor viverra nec ac urna. Morbi felis nunc, finibus quis sapien sit amet, eleifend molestie libero. Fusce ut odio neque. Pellentesque vitae sodales mi. Ut viverra feugiat dui non rutrum. Phasellus feugiat nibh vel nisl porttitor accumsan. Donec bibendum, dolor." complex_string = "123@123124lkø@asdk98##" complex_string2 = "123@123124lkø@asdk98" compare_str(lorem, ipsum) compare_str(complex_string, complex_string2) compare_str(long_lorem, lorem) compare_str(long_lorem, long_lorem2) compare_str("hello", "Hello") compare_str("Hello", "Hella") string_looper(lorem, ipsum) string_looper(complex_string, complex_string2) string_looper(long_lorem, lorem) string_looper(long_lorem, long_lorem2) string_looper("hello", "Hello") string_looper("Hello", "Hella")<file_sep>/innlevering_4/test_BinaryTree.py import unittest from typing import NamedTuple from innlevering_4.BinaryTree import BinaryTree from innlevering_4.BinaryTreeNode import BinaryTreeNode class Person(NamedTuple): etternavn: str fornavn: str adresse: str postnummer: int poststed: str class BstTest(unittest.TestCase): ''' Bruker egendefinert array med Person-objekter for kunne gjennomføre testene hurtig og effektivt. ''' # BUG: Kan ikke kjøre alle tester i ett. Noen av testene gir feil. # Kan fikses ved å kjøre de de aktuelle testene individuelt. tree = BinaryTree() minPerson = Person("GJERSTAD", "TORKJELL", "HOSTELAND 2 83", 1361, "ØSTERÅS") maxPerson = Person("<NAME>", "<NAME>", "LINNGÅRD 22", 1451, "NESODDTANGEN") persons = [ Person("KRISTIANSEN", "<NAME>", "LEINAHYTTA 36", 7224, "MELHUS"), Person("OLDERVIK", "<NAME>", "KRÅKA 84", 7437, "FEDJE"), Person("GJERSTAD", "TORKJELL", "HOSTELAND 2 83", 1361, "ØSTERÅS"), Person("<NAME>", "<NAME>", "LINNGÅRD 22", 1451, "NESODDTANGEN") ] def setUp(self) -> None: super().setUp() def tearDown(self) -> None: super().tearDown() def test_insert(self): for p in self.persons: node = BinaryTreeNode(p) self.tree.insert(value=p) self.assertEqual(node, self.tree.find(p)) # for hver insert, sjekk at objektet finnes i treet def test_can_read_data_file(self): persons_in_file = [] with open("Personer.dta", "r", encoding="ISO-8859-1") as file: for line in file: person = line.split(";") persons_in_file.append(person) self.assertEqual(len(persons_in_file), 100_000) def test_insert_duplicate_node(self): person = Person("REMLO", "<NAME>", "SANDFLATA 71", 5648, "HOLMEFJORD") with self.assertRaises(Exception): self.tree.insert(value=person) self.tree.insert(value=person) def test_delete_min(self): self.persons.clear() for p in self.persons: self.tree.insert(value=p) node = BinaryTreeNode(self.minPerson) self.assertEqual(node, self.tree.deleteMin()) def test_delete_max(self): for p in self.persons: self.tree.insert(value=p) node = BinaryTreeNode(self.maxPerson) self.assertNotEqual(node, self.tree.deleteMax()) def test_is_greater_than(self): for p in self.persons: self.tree.insert(value=p) self.assertGreater(self.tree.findMax(), self.tree.findMin()) def test_is_greater_or_equal(self): self.persons.clear() for p in self.persons: self.tree.insert(value=p) self.assertGreaterEqual(self.tree.findMax(), self.tree.findMax()) def test_is_less_than(self): self.persons.clear() for p in self.persons: self.tree.insert(value=p) self.assertLess(self.tree.findMin(), self.tree.findMax()) def test_is_less_or_equal(self): self.persons.clear() for p in self.persons: self.tree.insert(value=p) self.assertLessEqual(self.tree.findMin(), self.tree.findMax()) self.assertLessEqual(self.tree.findMin(), self.tree.findMin()) def test_delete_node(self): self.persons.clear() person = Person("REMLO", "<NAME>", "SANDFLATA 71", 5648, "HOLMEFJORD") node = BinaryTreeNode(person) self.tree.insert(value=person) self.assertEqual(node, self.tree.delete(key=person)) def test_find(self): person = Person("REMLO", "<NAME>", "SANDFLATA 71", 5648, "HOLMEFJORD") self.tree.insert(value=person) node = BinaryTreeNode(person) self.assertEqual(node, self.tree.find(key=person)) def test_findMax(self): person = Person("GJERSTAD", "TORKJELL", "HOSTELAND 2 83", 1361, "ØSTERÅS") self.tree.insert(value=person) person = Person("<NAME>", "<NAME>", "LINNGÅRD 22", 1451, "NESODDTANGEN") self.tree.insert(value=person) node = BinaryTreeNode(person) self.assertEqual(node, self.tree.findMax()) def test_findMin(self): for p in self.persons: self.tree.insert(value=p) node = BinaryTreeNode(self.minPerson) self.assertEqual(self.tree.findLeftMost(node), self.tree.findMin()) def test_delete_min_when_root(self): person = Person("REMLO", "<NAME>", "SANDFLATA 71", 5648, "HOLMEFJORD") node = BinaryTreeNode(person) self.tree.insert(value=person) self.assertEqual(node, self.tree.find(person)) self.assertNotEqual(node, self.tree.delete(person)) if __name__ == '__main__': unittest.main() <file_sep>/innlevering_2/innlev2 v2.py class IterateFibonacci: def __init__(self, fib_max): self.fib_max = fib_max self.f0 = 0 self.f1 = 1 def __iter__(self): return self def __next__(self): fib = self.f0 if fib >= self.fib_max: raise StopIteration self.f0, self.f1 = self.f1, self.f0 + self.f1 return fib fib_max = 1000 def iter_fib(): fibs = IterateFibonacci(fib_max) print("Iterate fibonacci") # for fib in fibs: # print(fib) iter_fib() fib_list = [] # kode for Oppgave 2 her, bruk flere celler hvis det trengs def fibonacci(fib_max): f0, f1 = 0, 1 while True: if (f0 >= fib_max): return yield f0 fib_list.append(f0) f0, f1 = f1, f0 + f1 fib_max = 1000 fibs = fibonacci(fib_max) #print("Fibonacci for f in fibs:") #for f in fibs: # print(f) # kode for Oppgave 3 her, bruk flere celler hvis det trengs # def fibonacci_list(): # fib_list = [] # f0, f1 = 0, 1 # while f0 < 1000: # f0, f1 = f1, f0 + f1 # # print(f0) # fib_list.append(f0) # return fib_list # Bruker derfor alternativ måte for å sjekke hvilke tall som er like i de to listene def is_fib(x): f0, f1 = 0, 1 while True: if (f0 >= 1000): return #fib_list.append(f0) if x == f0: return True f0, f1 = f1, f0 + f1 return False ints = list(range(0, 1000)) print("fib",[i for i in ints if is_fib(i)]) <file_sep>/innlevering_2/i2_oppg4.py class NewInt(int): def __init__(self, range_max): super().__init__() self.index = 0 def fibonacci(fib_max): f0, f1 = 0, 1 while True: if (f0 >= fib_max): return yield f0 f0, f1 = f1, f0 + f1 fib_set = set() fibs = fibonacci(100_0000) for f in fibs: fib_set.add(f) int_list = [NewInt(i) for i in range(1000000)] compared_fibonaccis = [i for i in int_list if i in fib_set] print(compared_fibonaccis) <file_sep>/oblig_1_kalman/Oblig1.py ''' # # Obligatorisk karaktersatt oppgave #1 # # Legg spesielt merke til at det er kun koden i klassen Kalman som kan endres. Det er koden som skal leveres inn # Det er derfor viktig at INGEN ANNEN KODE ENDRES !!! # ''' import pygame as pg from random import random, randint import numpy as np from numpy.linalg import norm fps = 0.0 class Projectile(): def __init__(self, kalman=None): self.background = background self.rect = pg.Rect((800, 700), (16, 16)) self.px = self.rect.x self.py = self.rect.y self.dx = 0.0 self.kalm = kalman def move(self, goal): # if self.kalm: # goal = self.kalm.calc_next(goal) deltax = np.array(float(goal) - self.px) # print(delta2) mag_delta = norm(deltax) # * 500.0 np.divide(deltax, mag_delta, deltax) self.dx += deltax # if self.dx: # self.dx /= norm(self.dx) * 50 self.px += self.dx / 50.0 self.py += -0.5 try: self.rect.x = int(self.px) except: pass try: self.rect.y = int(self.py) except: pass class Target(): def __init__(self, background, width): self.background = background self.rect = pg.Rect(self.background.get_width() // 2 - width // 2, 50, width, 32) self.dx = 1 if random() > 0.5 else -1 def move(self): self.rect.x += self.dx if self.rect.x < 300 or self.rect.x > self.background.get_width() - 300: self.dx *= -1 def noisy_x_pos(self): pos = self.rect.x center = self.rect.width // 2 noise = np.random.normal(0, 1, 1)[0] return pos + center + noise * 300.0 # # Her er Kalmanfilteret du skal utvikle # class Kalman(): ''' # https://www.kalmanfilter.net/alphabeta.html # https://arxiv.org/pdf/1204.0375.pdf # Algoritmen er iterativ. Hvert trinn inkluderer to faser: prediksjon og måleoppdatering. # Init: System state initial guess # 1: Input: Målt verdi # 2: Kalkuler Kalman gain (A). Estimer current state med state update equation. Output: System State Estimate ^Xn,n # 3: Kalkuler forventet state for neste iterasjon. Unit delay (n -> n+1). ^Xn,n-1 # Gjenta 2 og 3 ''' # Enkelte verdier er basert på gjetting, prøving og feiling def __init__(self): self.alpha = 2 / 3 # initierings-verdi av targest posisjon. Brukes kun for initialisering av filter self.beta = 0.1 self.n = iters # antall iterasjoner self.dt = fps # dt antall målinger i sekundet bestemt av fps self.current_estimate = 9 # xn_n self.prediction = 0 # Xn,n + 1 self.previous_iteration = 0 # Xn,n - 1 self.xdhn_n = 1 # x delta h n_n? self.xdhn_n_plus_1 = 0 self.xdhn_n_minus_1 = 0 self.measurement_on_iteration_n = 0.0 def state_extrapolation_equation(self): self.prediction = self.current_estimate + (self.dt * self.xdhn_n) self.xdhn_n_plus_1 = self.xdhn_n def state_update_equation(self): self.current_estimate = self.previous_iteration + self.alpha * \ (self.measurement_on_iteration_n - self.previous_iteration) ''' Hver for seg gir de to neste regnestykkene stigende eller synkende kalmanscore. Ved å bruke begge to får jeg bedre og mer konsistent resultat / kalmanscore.''' self.xdhn_n = self.xdhn_n_minus_1 + self.beta * ( (self.measurement_on_iteration_n - self.previous_iteration) / self.dt) # gir minkende kalmanscore 0.9 -> 0.4 self.xdhn_n = self.xdhn_n_minus_1 + self.beta * ( (self.measurement_on_iteration_n - self.previous_iteration) // self.dt) # gir økende kalmanscore 0.0 -> 0.8 def measurement(self, value): self.measurement_on_iteration_n = value # z_n def iterate(self): self.n += iters # iterasjoner # predikeringen fra forrige iterasjon settes til det forrige estimatet til nåværende iterasjon self.previous_iteration = self.current_estimate self.xdhn_n_minus_1 = self.xdhn_n self.dt = fps def calc_next(self, zi): # ved første iterering initialiserer man verdiene med kvalifisert gjetning if self.n == 0: self.state_extrapolation_equation() self.previous_iteration = self.prediction self.xdhn_n_minus_1 = self.xdhn_n_plus_1 self.measurement(zi) self.state_update_equation() self.state_extrapolation_equation() self.iterate() return self.current_estimate # returnerer predikert posisjon til k_miss # #### end of kalman class #### # pg.init() w, h = 1600, 800 background = pg.display.set_mode((w, h)) surf = pg.surfarray.pixels3d(background) running = True clock = pg.time.Clock() kalman_score = 0 reg_score = 0 iters = 0 while running: target = Target(background, 32) missile = Projectile(background) kalman = Kalman() k_miss = Projectile(background) # kommenter inn denne linjen naar Kalman er implementert noisy_draw = np.zeros((w, 20)) trial = True iters += 1 while trial: # Setter en maksimal framerate på 300. Hvis dere vil øke denne er dette en mulig endring clock.tick(300) fps = clock.get_fps() for e in pg.event.get(): if e.type == pg.QUIT: running = False background.fill(0x448844) surf[:, 0:20, 0] = noisy_draw last_x_pos = target.noisy_x_pos() # dette er støyen vi skal filtrere target.move() missile.move(last_x_pos) k_miss.move(kalman.calc_next(last_x_pos)) # kommenter inn denne linjen naar Kalman er implementert pg.draw.rect(background, (255, 200, 0), missile.rect) pg.draw.rect(background, (0, 200, 255), k_miss.rect) # kommenter inn denne linjen naar Kalman er implementert pg.draw.rect(background, (255, 200, 255), target.rect) noisy_draw[int(last_x_pos):int(last_x_pos) + 20, :] = 255 noisy_draw -= 1 np.clip(noisy_draw, 0, 255, noisy_draw) coll = missile.rect.colliderect(target.rect) k_coll = k_miss.rect.colliderect(target.rect) # kommenter inn denne linjen naar Kalman er implementert# if coll: reg_score += 1 if k_coll: # kommenter inn denne linjen naar Kalman er implementert kalman_score += 1 oob = missile.rect.y < 20 # runden er over if oob or coll or k_coll: # or k_coll #endre denne sjekken slik at k_coll ogsaa er med naar kalman er implementert trial = False pg.display.flip() print('kalman score: ', round(kalman_score / iters, 2)) # kommenter inn denne linjen naar Kalman er implementert print('regular score: ', round(reg_score / iters, 2)) pg.quit() <file_sep>/innlevering_2/NewInt.py class NewInt(int): def __init__(self, range_max): super().__init__() self.sequence = list(range(0, range_max)) self.range_max = range_max self.index = 0 def __next__(self): if self.index >= len(self.sequence): raise StopIteration result = self.sequence[self.index] self.index += 1 return result def __iter__(self): return self def is_fib(self): f0, f1 = 0, 1 while True: if f0 > self.range_max: yield False if self == f0: yield True f0, f1 = f1, f0 + f1 # for i in range(0, 100): # i = NewInt(i) # print(i.is_fib()) # print(str(i)) #%timeit pass compared_fibonaccis = [x for x in range(0, 1000) if NewInt(x).is_fib()] print(compared_fibonaccis) <file_sep>/innlevering_2/Iterator.py class IterateFibonacci: def __init__(self, fib_max): self.fib_max = fib_max self.f0 = 0 self.f1 = 1 def __iter__(self): return self def __next__(self): fib = self.f0 if fib >= self.fib_max: raise StopIteration self.f0, self.f1 = self.f1, self.f0 + self.f1 return fib fib_max = 1000 def iter_fib(): fibs = IterateFibonacci(fib_max) for fib in fibs: print(fib) iter_fib()
552df0df317f4482b1a1f74114cf867144780b87
[ "Python" ]
18
Python
kridah/MLAI
dc71cbb3bd389768c9e9953ef455b9fb32179033
be1b72ca4cb7e0da8931ff012b1ca29347022e0c
refs/heads/master
<file_sep>package com.ulluna.frogforcescouting; import android.animation.Animator; import android.app.ActionBar; import android.app.Activity; import android.content.Intent; import android.graphics.Color; import android.graphics.drawable.ColorDrawable; import android.net.Uri; import android.support.v7.app.ActionBarActivity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewAnimationUtils; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.RatingBar; import android.widget.Toast; public class MainActivity extends ActionBarActivity { final int MAX_STACK=6; final int MAX_BIN = 6; int[] stacks = new int[MAX_STACK]; int[] bins = new int[MAX_BIN]; Button[] buttons = new Button[25]; EditText[] editTexts = new EditText[13]; CheckBox[] checkBoxes = new CheckBox[10]; EditText matchNumber, teamNumber; /*TODO: -settings - edit goal email -credits -first open - ask about email -save multiple teams and send summary -analyze results and give recommendation -edit the comments -count noodles -icon */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); establishReferences(); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main_activity_actions, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); //noinspection SimplifiableIfStatement switch (item.getItemId()) { case R.id.action_send_now: sendData(); return true; case R.id.action_settings: return true; case R.id.action_clear_screen: clearScreen(); return true; default: return super.onOptionsItemSelected(item); } } private void clearScreen() { finish(); recreate(); } private void sendData() { if(teamNumber.getText().toString().equals("") || matchNumber.getText().toString().equals("") || ((RatingBar) findViewById(R.id.ratingBar)).getRating()==0) { Toast.makeText(getApplicationContext(), "Make sure to fill out all fields and to rank" + " the team", Toast.LENGTH_SHORT).show(); } else { String s = ""; s += "Stacks: "; for (int i = 0; i < MAX_STACK; i++) { s += stacks[i] + ", "; } s += "\n"; s += "Bins: "; for (int i = 0; i < MAX_BIN; i++) { s += bins[i] + ", "; } s += "\n"; s += "Coop totes: " + ((EditText) findViewById(R.id.editTextCoop)).getText() + "\n"; s += "Stolen Bins: " + ((EditText) findViewById(R.id.editTextBinsStolen)).getText() + "\n"; s += "Other: " + getCheckboxData() + "\n"; s += "Overall: " + ((RatingBar) findViewById(R.id.ratingBar)).getRating(); Intent intent = new Intent(Intent.ACTION_SENDTO); // it's not ACTION_SEND intent.setType("text/plain"); intent.putExtra(Intent.EXTRA_SUBJECT, "Team #" + teamNumber.getText() + " Match #" + matchNumber.getText()); intent.putExtra(Intent.EXTRA_TEXT, s); intent.setData(Uri.parse("mailto:<EMAIL>, <EMAIL>")); // or just "mailto:" for blank intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); // this will make such that when user returns to your app, your app is displayed, instead of the email app. startActivity(intent); } } public void buttonClicked(View view) { for(int i=1; i<25; i++){ if(view.getId()==buttons[i].getId()){ if(i<7) changeValue(stacks, i-1, 1, MAX_STACK); else if(i<13) changeValue(stacks, i-7, 0, 0); else if(i<19) changeValue(bins, i-13, 1, MAX_BIN); else changeValue(bins, i-19, 0, 0); } } updateView(); } public void updateView(){ for(int i=1; i<13; i++){ if(i<7) editTexts[i].setText(String.valueOf(stacks[i - 1])); else editTexts[i].setText(String.valueOf(bins[i-7])); } } public void changeValue(int[] array, int index, int value, int bound){ if(value>0){ if(array[index]+1<=bound){ array[index]++; } } else{ if(array[index]-1>=bound){ array[index]--; } } } public String getCheckboxData(){ String s=""; for(int i=1; i<checkBoxes.length; i++){ if(checkBoxes[i]==null) break; if(checkBoxes[i].isChecked()) s+= checkBoxes[i].getText() + ", "; } return s; } private void establishReferences(){ buttons[1] = (Button)findViewById(R.id.buttonS1); buttons[2] = (Button)findViewById(R.id.buttonS2); buttons[3] = (Button)findViewById(R.id.buttonS3); buttons[4] = (Button)findViewById(R.id.buttonS4); buttons[5] = (Button)findViewById(R.id.buttonS5); buttons[6] = (Button)findViewById(R.id.buttonS6); buttons[7] = (Button)findViewById(R.id.buttonS7); buttons[8] = (Button)findViewById(R.id.buttonS8); buttons[9] = (Button)findViewById(R.id.buttonS9); buttons[10] = (Button)findViewById(R.id.buttonS10); buttons[11] = (Button)findViewById(R.id.buttonS11); buttons[12] = (Button)findViewById(R.id.buttonS12); buttons[13] = (Button)findViewById(R.id.buttonB1); buttons[14] = (Button)findViewById(R.id.buttonB2); buttons[15] = (Button)findViewById(R.id.buttonB3); buttons[16] = (Button)findViewById(R.id.buttonB4); buttons[17] = (Button)findViewById(R.id.buttonB5); buttons[18] = (Button)findViewById(R.id.buttonB6); buttons[19] = (Button)findViewById(R.id.buttonB7); buttons[20] = (Button)findViewById(R.id.buttonB8); buttons[21] = (Button)findViewById(R.id.buttonB9); buttons[22] = (Button)findViewById(R.id.buttonB10); buttons[23] = (Button)findViewById(R.id.buttonB11); buttons[24] = (Button)findViewById(R.id.buttonB12); editTexts[1] = (EditText)findViewById(R.id.editTextS1); editTexts[2] = (EditText)findViewById(R.id.editTextS2); editTexts[3] = (EditText)findViewById(R.id.editTextS3); editTexts[4] = (EditText)findViewById(R.id.editTextS4); editTexts[5] = (EditText)findViewById(R.id.editTextS5); editTexts[6] = (EditText)findViewById(R.id.editTextS6); editTexts[7] = (EditText)findViewById(R.id.editTextB1); editTexts[8] = (EditText)findViewById(R.id.editTextB2); editTexts[9] = (EditText)findViewById(R.id.editTextB3); editTexts[10] = (EditText)findViewById(R.id.editTextB4); editTexts[11] = (EditText)findViewById(R.id.editTextB5); editTexts[12] = (EditText)findViewById(R.id.editTextB6); checkBoxes[1] = (CheckBox)findViewById(R.id.checkBox1); checkBoxes[2] = (CheckBox)findViewById(R.id.checkBox2); checkBoxes[3] = (CheckBox)findViewById(R.id.checkBox3); checkBoxes[4] = (CheckBox)findViewById(R.id.checkBox4); checkBoxes[5] = (CheckBox)findViewById(R.id.checkBox5); checkBoxes[6] = (CheckBox)findViewById(R.id.checkBox6); checkBoxes[7] = (CheckBox)findViewById(R.id.checkBox7); checkBoxes[8] = (CheckBox)findViewById(R.id.checkBox8); matchNumber = (EditText)findViewById(R.id.editTextMatchNumber); teamNumber = (EditText)findViewById(R.id.editTextTeamNumber); } }
2aef83d8bdf82d9407f6ebe3079bce092049248d
[ "Java" ]
1
Java
seriousbee/FrogForceScouting
02b414c6bdcffcad699e514faf49cd8c836f4098
10cf4bf6bfcbebdef266777643e6f8f5394eb55e
refs/heads/master
<file_sep>using Controle.Connection; using Controle.Entity; using System.Collections.Generic; namespace Controle.Repository.DAO { public class FornecedorRepository : Base<Fornecedor> { public IList<Fornecedor> PesquisarPaginacao() { IList<Fornecedor> lista = new List<Fornecedor>(); using (var session = NHibernateHelper.OpenSession()) { lista = session.QueryOver<Fornecedor>() .Where(x=>x.Excluido != "S") //.Take(20) .List(); } return lista; } public int TotalRepresentante() { int total = 0; using (var session = NHibernateHelper.OpenSession()) { total = session.QueryOver<Fornecedor>() .Where(x => x.Excluido != "S") .RowCount(); } return total; } } } <file_sep>using AutoMapper; using Sistema.AutoMapper; using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace Sistema.AutoMapper { public class AutoMapperConfig : Profile { public static void RegisterMappings() { Mapper.Initialize(x=> { x.AddProfile<DomainToViewModelMappingProfile>(); x.AddProfile<ViewModelToDomainMappingsProfile>(); }); } } }<file_sep>using Controle.Entity; using FluentNHibernate.Mapping; namespace Controle.Mapping { public class RepresentanteMapping : ClassMap<Representante> { public RepresentanteMapping() { Id(x => x.Id); Map(x => x.Celular); Map(x => x.Email); Map(x => x.Nome); Map(x => x.Telefone); Map(x => x.Excluido).Default("N"); References(x => x.Fornecedor).Not.LazyLoad(); } } } <file_sep>using Controle.Entity; using FluentNHibernate.Mapping; namespace Controle.Mapping { public class UsuarioMapping : ClassMap<Usuario> { public UsuarioMapping() { Id(x => x.Id); Map(x => x.Nome); Map(x => x.Senha); Map(x => x.Excluido); } } } <file_sep>using Controle.Connection; using Controle.Entity; using System.Collections.Generic; namespace Controle.Repository.DAO { public class ProdutoRepository : Base<Produto> { public IList<Produto> PesquisarPaginacao() { IList<Produto> lista = new List<Produto>(); using (var session = NHibernateHelper.OpenSession()) { lista = session.QueryOver<Produto>() .Where(x => x.Excluido != "S") //.Take(20) .List(); } return lista; } public int TotalRepresentante() { int total = 0; using (var session = NHibernateHelper.OpenSession()) { total = session.QueryOver<Produto>() .Where(x => x.Excluido != "S") .RowCount(); } return total; } } } <file_sep>using Controle.Connection; using Controle.Entity; using System.Collections.Generic; namespace Controle.Repository.DAO { public class RepresentanteRepository : Base<Representante> { public IList<Representante> PesquisarPaginacao() { IList<Representante> lista = new List<Representante>(); using (var session = NHibernateHelper.OpenSession()) { lista = session.QueryOver<Representante>() .Where(x => x.Excluido != "S") //.Take(20) .List(); } return lista; } public int TotalRepresentante() { int total = 0; using (var session = NHibernateHelper.OpenSession()) { total = session.QueryOver<Representante>() .Where(x => x.Excluido != "S") .RowCount(); } return total; } } } <file_sep>using Controle.Connection; using Controle.Repository.Interface; using System; using System.Collections.Generic; namespace Controle.Repository.DAO { public class Base<T> : IBase<T> where T : class { public void Atualizar(T obj) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { try { session.Update(obj); transaction.Commit(); } catch (Exception ex) { if (!transaction.WasCommitted) { transaction.Rollback(); } throw new Exception("Erro ao atualizar o registro: " + ex.Message); } } } } public void Deletar(T obj) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { try { session.Update(obj); transaction.Commit(); } catch (Exception ex) { if (!transaction.WasCommitted) { transaction.Rollback(); } throw new Exception("Erro ao deletar o registro: " + ex.Message); } } } } public T Read(int id) { using (var session = NHibernateHelper.OpenSession()) { return session.Get<T>(id); } } public IList<T> ReadAll() { using (var session = NHibernateHelper.OpenSession()) { return session.QueryOver<T>().List(); } } public void Salvar(T obj) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { try { session.Save(obj); transaction.Commit(); } catch (Exception ex) { if (!transaction.WasCommitted) { transaction.Rollback(); } throw new Exception("Erro ao inserir o registro: " + ex.Message); } } } } public int Total() { using (var session = NHibernateHelper.OpenSession()) { return session.QueryOver<T>().List().Count; } } } } <file_sep>using AutoMapper; using Controle.Entity; using Controle.Repository.DAO; using Sistema.AutoMapper; using Sistema.ViewModel; using System; using System.Collections.Generic; using System.Web.Mvc; namespace Sistema.Controllers { public class ProdutosController : Controller { private readonly ProdutoRepository _produtoRepository = new ProdutoRepository(); private readonly TipoVeiculoRepository _tipoVeiculoRepository = new TipoVeiculoRepository(); private readonly IMapper mapperViewModelToDomain = ViewModelToDomainMappingsProfile.config.CreateMapper(); private readonly IMapper mapperDomainToViewModel = DomainToViewModelMappingProfile.config.CreateMapper(); // GET: Produtos public ActionResult Index() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var produtos = mapperDomainToViewModel.Map<IEnumerable<Produto>, IEnumerable<ProdutoViewModel>>(_produtoRepository.PesquisarPaginacao()); return View(produtos); } // GET: Produtos/Details/5 public ActionResult Details(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var produtoViewModel = mapperDomainToViewModel.Map<Produto, ProdutoViewModel>(_produtoRepository.Read(id)); return View(produtoViewModel); } // GET: Produtos/Create public ActionResult Create() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); SetDropdDowns(); return View(); } // POST: Produtos/Create [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(ProdutoViewModel produtoViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var produtoDomain = mapperViewModelToDomain.Map<ProdutoViewModel, Produto>(produtoViewModel); produtoDomain.TipoVeiculo = _tipoVeiculoRepository.Read(Convert.ToInt32(produtoViewModel.TipoVeiculoId)); produtoDomain.Excluido = "N"; _produtoRepository.Salvar(produtoDomain); return RedirectToAction("Index"); } return View(produtoViewModel); } // GET: Produtos/Edit/5 public ActionResult Edit(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var produtoViewModel = mapperDomainToViewModel.Map<Produto, ProdutoViewModel>(_produtoRepository.Read(id)); SetDropdDowns(); produtoViewModel.TipoVeiculoId = produtoViewModel.TipoVeiculo.Id.ToString(); return View(produtoViewModel); } // POST: Produtos/Edit/5 [HttpPost] public ActionResult Edit(ProdutoViewModel produtoViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var produtoDomain = mapperViewModelToDomain.Map<ProdutoViewModel, Produto>(produtoViewModel); produtoDomain.TipoVeiculo = _tipoVeiculoRepository.Read(Convert.ToInt32(produtoViewModel.TipoVeiculoId)); _produtoRepository.Atualizar(produtoDomain); return RedirectToAction("Index"); } return View(produtoViewModel); } // GET: Produtos/Delete/5 public ActionResult Delete(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var produtoViewModel = mapperDomainToViewModel.Map<Produto, ProdutoViewModel>(_produtoRepository.Read(id)); return View(produtoViewModel); } // POST: Produtos/Delete/5 [HttpPost] public ActionResult Delete(int id, ProdutoViewModel produtoViewMOdel) { try { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var produtoDomain = _produtoRepository.Read(Convert.ToInt32(id)); produtoDomain.Excluido = "S"; _produtoRepository.Deletar(produtoDomain); return RedirectToAction("Index"); } catch (Exception) { return View(); } } #region Métodos private void SetDropdDowns() { ViewBag.TipoVeiculo = new SelectList ( mapperDomainToViewModel.Map<IEnumerable<TipoVeiculo>, IEnumerable<TipoVeiculoViewModel>>(_tipoVeiculoRepository.ReadAll()), "Id", "Descricao" ); } #endregion } } <file_sep>using AutoMapper; using Controle.Entity; using Controle.Repository.DAO; using Sistema.AutoMapper; using Sistema.ViewModel; using System; using System.Collections.Generic; using System.Web.Mvc; namespace Sistema.Controllers { public class TipoVeiculoController : Controller { private readonly TipoVeiculoRepository _tipoVeiculoRepository = new TipoVeiculoRepository(); private readonly IMapper mapperViewModelToDomain = ViewModelToDomainMappingsProfile.config.CreateMapper(); private readonly IMapper mapperDomainToViewModel = DomainToViewModelMappingProfile.config.CreateMapper(); // GET: TipoVeiculo public ActionResult Index() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var tipoVeiculos = mapperDomainToViewModel.Map<IEnumerable<TipoVeiculo>, IEnumerable<TipoVeiculoViewModel>>(_tipoVeiculoRepository.PesquisarPaginacao()); return View(tipoVeiculos); } // GET: TipoVeiculo/Details/5 public ActionResult Details(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); return View(); } // GET: TipoVeiculo/Create public ActionResult Create() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); return View(); } // POST: TipoVeiculo/Create [HttpPost] public ActionResult Create(TipoVeiculoViewModel tipoVeiculoViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var tipoVeiculoDomain = mapperViewModelToDomain.Map<TipoVeiculoViewModel, TipoVeiculo>(tipoVeiculoViewModel); tipoVeiculoDomain.Excluido = "N"; _tipoVeiculoRepository.Salvar(tipoVeiculoDomain); return RedirectToAction("Index"); } return View(tipoVeiculoViewModel); } // GET: TipoVeiculo/Edit/5 public ActionResult Edit(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var TipoVeiculoViewModel = mapperDomainToViewModel.Map<TipoVeiculo, TipoVeiculoViewModel>(_tipoVeiculoRepository.Read(id)); return View(TipoVeiculoViewModel); } // POST: TipoVeiculo/Edit/5 [HttpPost] public ActionResult Edit(TipoVeiculoViewModel tipoVeiculoViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var tipoVeiculoDomain = mapperViewModelToDomain.Map<TipoVeiculoViewModel, TipoVeiculo>(tipoVeiculoViewModel); _tipoVeiculoRepository.Atualizar(tipoVeiculoDomain); return RedirectToAction("Index"); } return View(); } // GET: TipoVeiculo/Delete/5 public ActionResult Delete(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var TipoVeiculoViewModel = mapperDomainToViewModel.Map<TipoVeiculo, TipoVeiculoViewModel>(_tipoVeiculoRepository.Read(id)); return View(TipoVeiculoViewModel); } // POST: TipoVeiculo/Delete/5 [HttpPost] public ActionResult Delete(int id, FormCollection collection) { try { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var tipoVeiculoDomain = _tipoVeiculoRepository.Read(Convert.ToInt32(id)); tipoVeiculoDomain.Excluido = "S"; _tipoVeiculoRepository.Deletar(tipoVeiculoDomain); return RedirectToAction("Index"); } catch { return View(); } } } } <file_sep>using System.ComponentModel.DataAnnotations; namespace Sistema.ViewModel { public class FornecedorViewModel { public virtual int Id { get; set; } [Display(Name = "Nome Fantasia")] public virtual string NomeFantasia { get; set; } [Display(Name = "Razão Social")] public virtual string RazaoSocial { get; set; } [Display(Name = "CNPJ")] public virtual string Cnpj { get; set; } [Display(Name = "Inscrição Estadual")] public virtual string InscricaoEstadual { get; set; } [Display(Name = "Inscrição Municipal")] public virtual string InscricaoMunicipal { get; set; } public virtual string Telefone { get; set; } [Display(Name = "CEP")] public virtual string Cep { get; set; } public virtual string Logradouro { get; set; } public virtual string Numero { get; set; } public virtual string Bairro { get; set; } public virtual string Complemento { get; set; } public virtual string Cidade { get; set; } public virtual string Estado { get; set; } //public virtual IList<Representante> Representantes { get; set; } //public virtual IList<Produto> Produtos { get; set; } } }<file_sep>using AutoMapper; using Controle.Entity; using Controle.Repository.DAO; using Sistema.AutoMapper; using Sistema.ViewModel; using System; using System.Collections.Generic; using System.Web.Mvc; //using PagedList; namespace Sistema.Controllers { public class FornecedorController : Controller { private readonly FornecedorRepository _fornecedorRepository = new FornecedorRepository(); private readonly IMapper mapperViewModelToDomain = ViewModelToDomainMappingsProfile.config.CreateMapper(); private readonly IMapper mapperDomainToViewModel = DomainToViewModelMappingProfile.config.CreateMapper(); // GET: Fornecedor public ActionResult Index() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var fornecedores = mapperDomainToViewModel.Map<IEnumerable<Fornecedor>, IEnumerable<FornecedorViewModel>>(_fornecedorRepository.PesquisarPaginacao()); //int pageNumber = page?? 1; //int pageSize = 1; return View(fornecedores); //return View(fornecedores.ToPagedList(pageNumber, pageSize)); } // GET: Fornecedor/Details/5 public ActionResult Details(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var fornecedorViewModel = mapperDomainToViewModel.Map<Fornecedor, FornecedorViewModel>(_fornecedorRepository.Read(id)); return View(fornecedorViewModel); } // GET: Fornecedor/Create public ActionResult Create() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); return View(); } // POST: Fornecedor/Create [HttpPost] public ActionResult Create(FornecedorViewModel fornecedorViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var fornecedorDomain = mapperViewModelToDomain.Map<FornecedorViewModel, Fornecedor>(fornecedorViewModel); fornecedorDomain.Excluido = "N"; _fornecedorRepository.Salvar(fornecedorDomain); return RedirectToAction("Index"); } return View(fornecedorViewModel); } // GET: Fornecedor/Edit/5 public ActionResult Edit(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var fornecedorViewModel = mapperDomainToViewModel.Map<Fornecedor, FornecedorViewModel>(_fornecedorRepository.Read(id)); return View(fornecedorViewModel); } // POST: Fornecedor/Edit/5 [HttpPost] public ActionResult Edit(FornecedorViewModel fornecedorViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var fornecedorDomain = mapperViewModelToDomain.Map<FornecedorViewModel, Fornecedor>(fornecedorViewModel); _fornecedorRepository.Atualizar(fornecedorDomain); return RedirectToAction("Index"); } return View(); } // GET: Fornecedor/Delete/5 public ActionResult Delete(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var fornecedorViewModel = mapperDomainToViewModel.Map<Fornecedor, FornecedorViewModel>(_fornecedorRepository.Read(id)); return View(fornecedorViewModel); } // POST: Fornecedor/Delete/5 [HttpPost] public ActionResult Delete(int id, ProdutoViewModel fornecedorViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); try { var fornecedorDomain = _fornecedorRepository.Read(Convert.ToInt32(id)); fornecedorDomain.Excluido = "S"; _fornecedorRepository.Atualizar(fornecedorDomain); return RedirectToAction("Index"); } catch (Exception) { return View(); } } } } <file_sep>using Controle.Entity; using FluentNHibernate.Mapping; namespace Controle.Repository.Mapping { public class FornecedorMapping : ClassMap<Fornecedor> { public FornecedorMapping() { Id(x => x.Id); Map(x => x.InscricaoEstadual); Map(x => x.InscricaoMunicipal); Map(x => x.NomeFantasia); Map(x => x.RazaoSocial); Map(x => x.Telefone); Map(x => x.Cnpj); Map(x => x.Cep); Map(x => x.Logradouro); Map(x => x.Numero); Map(x => x.Bairro); Map(x => x.Complemento); Map(x => x.Cidade); Map(x => x.Estado); Map(x => x.Excluido).Default("N"); //HasMany(x => x.Representantes).Cascade.All(); //HasManyToMany(x => x.Produtos).Cascade.All(); } } } <file_sep>using Controle.Connection; using Controle.Entity; using System.Collections.Generic; namespace Controle.Repository.DAO { public class ReservaRepository : Base<Reserva> { public IList<Reserva> PesquisarPaginacao() { IList<Reserva> lista = new List<Reserva>(); using (var session = NHibernateHelper.OpenSession()) { lista = session.QueryOver<Reserva>() .Where(x => x.Excluido != "S") //.Take(20) .List(); } return lista; } public int TotalReserva() { int total = 0; using (var session = NHibernateHelper.OpenSession()) { total = session.QueryOver<Reserva>() .Where(x => x.Excluido != "S") .RowCount(); } return total; } } } <file_sep>using Controle.Entity; using FluentNHibernate.Mapping; namespace Controle.Mapping { public class ReservaMapping : ClassMap<Reserva> { public ReservaMapping() { Id(x => x.Id); Map(x => x.Cliente); Map(x => x.DataDevolucao); Map(x => x.DataLocacao); Map(x => x.NotaDevolutiva); Map(x => x.Excluido); Map(x => x.RadiadorEmprestado); Map(x => x.RadiadorUsina); } } } <file_sep>namespace Controle.Entity { public class Usuario { public virtual int Id { get; set; } public virtual string Nome { get; set; } public virtual string Senha { get; set; } public virtual string Excluido { get; set; } } } <file_sep>using Controle.Entity; namespace Sistema.ViewModel { public class RepresentanteViewModel { public virtual int Id { get; set; } public Fornecedor Fornecedor { get; set; } public string FornecedorSelecionado { get; set; } public virtual string Nome { get; set; } public virtual string Email { get; set; } public virtual string Telefone { get; set; } public virtual string Celular { get; set; } } }<file_sep>using Controle.Repository.DAO; using System.Web.Mvc; namespace Sistema.Controllers { public class LoginController : Controller { private readonly UsuarioRepository _usuarioRepository = new UsuarioRepository(); // GET: Login public ActionResult Index() { return View(); } public ActionResult ValidarLogin(string login, string senha) { int id = _usuarioRepository.PesquisarPorLogin(login, senha); if (id != 0) { Session["usuarioId"] = id.ToString(); return RedirectToAction("Index", "Home"); } return View(); } } }<file_sep>using System.Collections.Generic; namespace Controle.Repository.Interface { public interface IBase<T> where T : class { void Salvar(T obj); void Atualizar(T obj); void Deletar(T obj); T Read(int id); IList<T> ReadAll(); int Total(); } } <file_sep>using Controle.Entity; using System.ComponentModel.DataAnnotations; namespace Sistema.ViewModel { public class ProdutoViewModel { public int Id { get; set; } public string Nome { get; set; } [Display(Name = "Descrição")] public string Descricao { get; set; } public int Quantidade { get; set; } [Display(Name = "Quantidade Mínima")] public int QuantidadeMinima { get; set; } public decimal Preco { get; set; } [Display(Name = "Preço Compra")] public decimal PrecoCompra { get; set; } [Display(Name = "Tipo Veículo")] public TipoVeiculo TipoVeiculo { get; set; } public string TipoVeiculoId { get; set; } [Display(Name = "Número Fabricante")] public string NumeroFabricante { get; set; } } }<file_sep>using Controle.Entity; using FluentNHibernate.Mapping; namespace Controle.Mapping { public class TipoVeiculoMapping:ClassMap<TipoVeiculo> { public TipoVeiculoMapping() { Id(x => x.Id).Column("Id"); Map(x => x.Descricao).Column("Descricao"); Map(x => x.Excluido).Column("Excluido"); } } } <file_sep>using System.Collections.Generic; namespace Controle.Entity { public class Fornecedor { public virtual int Id { get; set; } public virtual string NomeFantasia { get; set; } public virtual string RazaoSocial { get; set; } public virtual string Cnpj { get; set; } public virtual string InscricaoEstadual { get; set; } public virtual string InscricaoMunicipal { get; set; } public virtual string Telefone { get; set; } public virtual string Cep { get; set; } public virtual string Logradouro { get; set; } public virtual string Numero { get; set; } public virtual string Bairro { get; set; } public virtual string Complemento { get; set; } public virtual string Cidade { get; set; } public virtual string Estado { get; set; } public virtual IList<Produto> Produtos { get; set; } public virtual string Excluido { get; set; } } } <file_sep>using AutoMapper; using Controle.Entity; using Controle.Repository.DAO; using Sistema.AutoMapper; using Sistema.ViewModel; using System; using System.Collections.Generic; using System.Web.Mvc; namespace Sistema.Controllers { public class ReservaController : Controller { private readonly ReservaRepository _reservaRepository = new ReservaRepository(); private readonly ProdutoRepository _produtoRepository = new ProdutoRepository(); private readonly IMapper mapperViewModelToDomain = ViewModelToDomainMappingsProfile.config.CreateMapper(); private readonly IMapper mapperDomainToViewModel = DomainToViewModelMappingProfile.config.CreateMapper(); // GET: Reserva public ActionResult Index() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var reservas = mapperDomainToViewModel.Map<IEnumerable<Reserva>, IEnumerable<ReservaViewModel>>(_reservaRepository.ReadAll()); //int pageNumber = page?? 1; //int pageSize = 1; return View(reservas); } // GET: Reserva/Details/5 public ActionResult Details(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var reservaViewModel = mapperDomainToViewModel.Map<Reserva, ReservaViewModel>(_reservaRepository.Read(id)); return View(reservaViewModel); } // GET: Reserva/Create public ActionResult Create() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); SetDropdDowns(); return View(); } // POST: Reserva/Create [HttpPost] public ActionResult Create(ReservaViewModel reservaViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { reservaViewModel.RadiadorEmprestado = _produtoRepository.Read(Convert.ToInt32(reservaViewModel.RadiadorEmprestadoSelecionado)).Descricao; reservaViewModel.RadiadorUsina = _produtoRepository.Read(Convert.ToInt32(reservaViewModel.RadiadorUsinaSelecionado)).Descricao; var reservaDomain = mapperViewModelToDomain.Map<ReservaViewModel, Reserva>(reservaViewModel); reservaDomain.Excluido = "N"; _reservaRepository.Salvar(reservaDomain); return RedirectToAction("Index"); } return View(reservaViewModel); } // GET: Reserva/Edit/5 public ActionResult Edit(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); SetDropdDowns(); var reservaViewModel = mapperDomainToViewModel.Map<Reserva, ReservaViewModel>(_reservaRepository.Read(id)); reservaViewModel.RadiadorEmprestadoSelecionado = _produtoRepository.Read(Convert.ToInt32(id)).Id.ToString(); reservaViewModel.RadiadorUsinaSelecionado = _produtoRepository.Read(Convert.ToInt32(id)).Id.ToString(); return View(reservaViewModel); } // POST: Reserva/Edit/5 [HttpPost] public ActionResult Edit(int id, ReservaViewModel reservaViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var reservaDomain = mapperViewModelToDomain.Map<ReservaViewModel, Reserva>(reservaViewModel); _reservaRepository.Atualizar(reservaDomain); return RedirectToAction("Index"); } return View(); } // GET: Reserva/Delete/5 public ActionResult Delete(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var reservaViewModel = mapperDomainToViewModel.Map<Reserva, ReservaViewModel>(_reservaRepository.Read(id)); return View(reservaViewModel); } // POST: Reserva/Delete/5 [HttpPost] public ActionResult Delete(int id, ReservaViewModel reservaViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); try { var reservaDomain = _reservaRepository.Read(Convert.ToInt32(id)); reservaDomain.Excluido = "S"; _reservaRepository.Atualizar(reservaDomain); return RedirectToAction("Index"); } catch (Exception) { return View(); } } #region Métodos private void SetDropdDowns() { ViewBag.RadiadorEmprestado = new SelectList ( mapperDomainToViewModel.Map<IEnumerable<Produto>, IEnumerable<ProdutoViewModel>>(_produtoRepository.ReadAll()), "Id", "Nome" ); ViewBag.RadiadorUsina = new SelectList ( mapperDomainToViewModel.Map<IEnumerable<Produto>, IEnumerable<ProdutoViewModel>>(_produtoRepository.ReadAll()), "Id", "Nome" ); } #endregion } } <file_sep>using Controle.Connection; using Controle.Entity; namespace Controle.Repository.DAO { public class UsuarioRepository : Base<Usuario> { public int PesquisarPorLogin(string login, string senha) { int id = 0; using (var session = NHibernateHelper.OpenSession()) { var user = session.QueryOver<Usuario>() .Where(x => x.Excluido != "S" && x.Nome == login && x.Senha == senha).List(); if (user != null) if (user.Count > 0) id = user[0].Id; } return id; } } } <file_sep>using Controle.Entity; using FluentNHibernate.Mapping; namespace Controle.Mapping { public class ProdutoMapping : ClassMap<Produto> { public ProdutoMapping() { Id(x => x.Id); Map(x => x.Nome); Map(x => x.Descricao); Map(x => x.NumeroFabricante); Map(x => x.Preco); Map(x => x.PrecoCompra); Map(x => x.Quantidade); Map(x => x.QuantidadeMinima); Map(x => x.Excluido).Default("N"); References(x => x.TipoVeiculo).Not.LazyLoad(); } } } <file_sep>using System.ComponentModel.DataAnnotations; namespace Sistema.ViewModel { public class TipoVeiculoViewModel { public virtual int Id { get; set; } [Display(Name = "Descrição" )] public virtual string Descricao { get; set; } } }<file_sep>using AutoMapper; using Controle.Entity; using Sistema.ViewModel; namespace Sistema.AutoMapper { public class ViewModelToDomainMappingsProfile : Profile { public static MapperConfiguration config; protected override void Configure() { config = new MapperConfiguration(cfg => { cfg.CreateMap<ProdutoViewModel, Produto>(); cfg.CreateMap<FornecedorViewModel, Fornecedor>(); cfg.CreateMap<RepresentanteViewModel, Representante>(); cfg.CreateMap<TipoVeiculoViewModel, TipoVeiculo>(); cfg.CreateMap<ReservaViewModel, Reserva>(); }); } } }<file_sep>namespace Controle.Entity { public class Representante { public virtual int Id { get; set; } public virtual Fornecedor Fornecedor { get; set; } public virtual string Nome { get; set; } public virtual string Email { get; set; } public virtual string Telefone { get; set; } public virtual string Celular { get; set; } public virtual string Excluido { get; set; } } }<file_sep> using System; namespace Controle.Entity { public class Produto { public virtual int Id { get; set; } public virtual string Nome { get; set; } public virtual string Descricao { get; set; } public virtual int Quantidade { get; set; } public virtual int QuantidadeMinima { get; set; } public virtual double Preco { get; set; } public virtual double PrecoCompra { get; set; } public virtual TipoVeiculo TipoVeiculo { get; set; } public virtual string NumeroFabricante { get; set; } public virtual string Excluido { get; set; } } } <file_sep>using Controle.Entity; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Sistema.ViewModel { public class ReservaViewModel { public virtual int Id { get; set; } [Display(Name = "Radiador Emprestado")] public virtual string RadiadorEmprestado { get; set; } public virtual string RadiadorEmprestadoSelecionado { get; set; } [Display(Name = "Radiador Usina")] public virtual string RadiadorUsina { get; set; } public virtual string RadiadorUsinaSelecionado { get; set; } [Display(Name = "Data Locação")] public virtual DateTime DataLocacao { get; set; } [Display(Name = "Data Devolução")] public virtual DateTime DataDevolucao { get; set; } public virtual string Cliente { get; set; } [Display(Name = "Nota Devolutiva")] public virtual string NotaDevolutiva { get; set; } } }<file_sep>using AutoMapper; using Controle.Entity; using Controle.Repository.DAO; using Sistema.AutoMapper; using Sistema.ViewModel; using System; using System.Collections.Generic; using System.Web.Mvc; namespace Sistema.Controllers { public class RepresentanteController : Controller { #region Propriedades e Classes private readonly RepresentanteRepository _representanteRepository = new RepresentanteRepository(); private readonly FornecedorRepository _fornecedorRepository = new FornecedorRepository(); private readonly IMapper mapperViewModelToDomain = ViewModelToDomainMappingsProfile.config.CreateMapper(); private readonly IMapper mapperDomainToViewModel = DomainToViewModelMappingProfile.config.CreateMapper(); #endregion #region Listagem e Detalhes // GET: Representante public ActionResult Index() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var representantes = mapperDomainToViewModel.Map<IEnumerable<Representante>, IEnumerable<RepresentanteViewModel>>(_representanteRepository.PesquisarPaginacao()); return View(representantes); } // GET: Representante/Details/5 public ActionResult Details(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var RepresentanteViewModel = mapperDomainToViewModel.Map<Representante, RepresentanteViewModel>(_representanteRepository.Read(id)); return View(RepresentanteViewModel); } #endregion #region Cadastro // GET: Representante/Create public ActionResult Create() { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); SetDropDowns(); return View(); } // POST: Representante/Create [HttpPost] public ActionResult Create(RepresentanteViewModel representanteViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var representanteDomain = mapperViewModelToDomain.Map<RepresentanteViewModel, Representante>(representanteViewModel); representanteDomain.Fornecedor = _fornecedorRepository.Read(Convert.ToInt32(representanteViewModel.FornecedorSelecionado)); representanteDomain.Excluido = "N"; _representanteRepository.Salvar(representanteDomain); return RedirectToAction("Index"); } return View(representanteViewModel); } #endregion #region Editar // GET: Representante/Edit/5 public ActionResult Edit(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var RepresentanteViewModel = mapperDomainToViewModel.Map<Representante, RepresentanteViewModel>(_representanteRepository.Read(id)); SetDropDowns(); RepresentanteViewModel.FornecedorSelecionado = RepresentanteViewModel.Fornecedor.Id.ToString(); return View(RepresentanteViewModel); } // POST: Representante/Edit/5 [HttpPost] public ActionResult Edit(RepresentanteViewModel representanteViewModel) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); if (ModelState.IsValid) { var representanteDomain = mapperViewModelToDomain.Map<RepresentanteViewModel, Representante>(representanteViewModel); representanteDomain.Fornecedor = _fornecedorRepository.Read(Convert.ToInt32(representanteViewModel.FornecedorSelecionado)); _representanteRepository.Atualizar(representanteDomain); return RedirectToAction("Index"); } return View(); } #endregion #region Deletar // GET: Representante/Delete/5 public ActionResult Delete(int id) { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var RepresentanteViewModel = mapperDomainToViewModel.Map<Representante, RepresentanteViewModel>(_representanteRepository.Read(id)); return View(RepresentanteViewModel); } // POST: Representante/Delete/5 [HttpPost] public ActionResult Delete(int id, RepresentanteViewModel representanteViewModel) { try { if (Session["usuarioId"] == null) return RedirectToAction("Index", "Login"); var representanteDomain = _representanteRepository.Read(Convert.ToInt32(id)); representanteDomain.Excluido = "S"; _representanteRepository.Deletar(representanteDomain); return RedirectToAction("Index"); } catch { return View(); } } #endregion #region Métodos private void SetDropDowns() { ViewBag.FornecedorId = new SelectList ( mapperDomainToViewModel.Map<IEnumerable<Fornecedor>, IEnumerable<FornecedorViewModel>>(_fornecedorRepository.ReadAll()), "Id", "NomeFantasia" ); } #endregion } } <file_sep>using Controle.Entity; using Controle.Repository.Mapping; using FluentNHibernate.Cfg; using FluentNHibernate.Cfg.Db; using NHibernate; using NHibernate.Tool.hbm2ddl; namespace Controle.Connection { /// <summary> ///Classe de conexão com banco utilizando o NHibernate. /// </summary> public class NHibernateHelper { private static ISessionFactory _sessionFactory; private static ISessionFactory SessionFactory { get { if (_sessionFactory == null) CreateSessionFactory(); return _sessionFactory; } } private static void CreateSessionFactory() { //StringConexaoLocal //StringConexaoProducao _sessionFactory = Fluently .Configure() .Database(MySQLConfiguration .Standard .ConnectionString(c => c.FromConnectionStringWithKey("StringConexaoLocal"))) .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Produto>()) .BuildSessionFactory(); //_sessionFactory = _sessionFactory = Fluently.Configure() // .Database(MsSqlConfiguration.MsSql2012 // .ConnectionString(cfg => cfg.FromConnectionStringWithKey("conexao")) // .ShowSql()) // .Mappings(x => x.FluentMappings.AddFromAssemblyOf<Produto>()) // .ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(true, true)) // .BuildSessionFactory(); } public static ISession OpenSession() { return SessionFactory.OpenSession(); } } } <file_sep>using System; namespace Controle.Entity { public class Reserva { public virtual int Id { get; set; } public virtual string RadiadorEmprestado { get; set; } public virtual string RadiadorUsina { get; set; } public virtual DateTime DataLocacao { get; set; } public virtual DateTime DataDevolucao { get; set; } public virtual string Cliente { get; set; } public virtual string NotaDevolutiva { get; set; } public virtual string Excluido { get; set; } } } <file_sep>namespace Controle.Entity { public class TipoVeiculo { public virtual int Id { get; set; } public virtual string Descricao { get; set; } public virtual string Excluido { get; set; } } }<file_sep>using AutoMapper; using Controle.Entity; using Sistema.ViewModel; namespace Sistema.AutoMapper { public class DomainToViewModelMappingProfile : Profile { public static MapperConfiguration config; protected override void Configure() { config = new MapperConfiguration(cfg => { cfg.CreateMap<Produto, ProdutoViewModel>(); cfg.CreateMap<Fornecedor, FornecedorViewModel>(); cfg.CreateMap<Representante, RepresentanteViewModel>(); cfg.CreateMap<TipoVeiculo, TipoVeiculoViewModel>(); cfg.CreateMap<Reserva, ReservaViewModel>(); }); } } }
d133017d8a888b16a4e877f531c56197425831d4
[ "C#" ]
34
C#
raulperesgoes/ExampleMVC
6ca3d2b275879e7dc7ebd8fbee09f79b9267cc80
b3fcb3506ad3d600d9a1c2f5f77b595eeeb1e25f
refs/heads/master
<repo_name>minyul/careerdirection2<file_sep>/src/dto/outputDTO/index.ts import { SignUpUserOutput } from "./SignUpUserOutput"; import { UpdateUserOutput } from "./UpdateUserOutput"; import { SignInUserOutput } from "./SignInUserOutput"; import { VerifyTokenOutput } from "./VerifyTokenOutput"; export { SignUpUserOutput, UpdateUserOutput, SignInUserOutput, VerifyTokenOutput, }; <file_sep>/src/dto/Todo/LoginInput.ts import { InputType, Field } from "type-graphql"; import { MaxLength, MinLength, IsEmail } from "class-validator"; @InputType() export class LoginInput { @IsEmail({}, { message: "이메일 형식을 지켜 주십시오!" }) @Field() email: string; @MinLength(8, { message: "패스워드가 너무 짧습니다. 8자 이상 입력해 주십시오." }) @MaxLength(20, { message: "패스워드가 너무 깁니다. 20자 이내로 작성해 주십시오." }) @Field() password: string; }<file_sep>/src/services/TodoService.ts import { LessThan } from "typeorm"; import { Todo } from "../entity"; import { TodoStatus } from "../enum"; import { GET_TODO_LIMIT } from "../utils/constants"; // 우선 임시로 넣어둠. import { CommonErrorInfo } from "../error/CommonErrorInfo"; import { CommonErrorCode } from "../error/CommonErrorCode"; // 피드백 받기 전까지 우선 주석 // import { logger } from "../../../../config/winston"; export class TodoService { /* Exception Variables */ private static readException: CommonErrorInfo = new CommonErrorInfo( CommonErrorCode.INTERNAL_SERVER_ERROR, "서버에 문제가 생겨 목록 불러오기에 실패했습니다. 잠시 후 다시 시도해 주십시오." ); private static createException: CommonErrorInfo = new CommonErrorInfo( CommonErrorCode.INTERNAL_SERVER_ERROR, "서버에 문제가 생겨 Todo 등록에 실패했습니다. 잠시 후 다시 시도해 주십시오." ); private static updateException: CommonErrorInfo = new CommonErrorInfo( CommonErrorCode.INTERNAL_SERVER_ERROR, "서버에 문제가 생겨 Todo 업데이트에 실패했습니다. 잠시 후 다시 시도해 주십시오." ); private static deleteException: CommonErrorInfo = new CommonErrorInfo( CommonErrorCode.INTERNAL_SERVER_ERROR, "서버에 문제가 생겨 해당 Todo를 삭제할 수 없습니다. 잠시 후 다시 시도해 주십시오." ); /* Business Method */ public static async findOneById(id: number): Promise<Todo | undefined> { return await Todo.findOne({ id: id }); } public static async findAll( cursor?: number ): Promise<Todo[] | CommonErrorInfo> { let findCondition; if (cursor) { findCondition = { where: { id: LessThan(cursor) }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } else { findCondition = { order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } try { return await Todo.find(findCondition); } catch (err) { //logger.error(err); return this.readException; } } public static async findAllByStatus( cursor?: number, status?: TodoStatus ): Promise<Todo[] | CommonErrorInfo> { let findCondition; if (cursor) { findCondition = { where: { id: LessThan(cursor), status: status, }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } else { findCondition = { where: { status: status, }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } try { return await Todo.find(findCondition); } catch (err) { //logger.error(err); return this.readException; } } public static async findAllByUserId( userId: number, cursor?: number ): Promise<Todo[] | CommonErrorInfo> { let findCondition; if (cursor) { findCondition = { where: { id: LessThan(cursor), userId: userId, }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } else { findCondition = { where: { userId: userId }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } try { return await Todo.find(findCondition); } catch (err) { //logger.error(err); return this.readException; } } public static async findAllByUserIdAndStatus( userId: number, status: TodoStatus, cursor?: number ): Promise<Todo[] | CommonErrorInfo> { let findCondition; if (cursor) { findCondition = { where: { id: LessThan(cursor), userId: userId, status: status, }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } else { findCondition = { where: { userId: userId, status: status, }, order: { id: "DESC" }, take: GET_TODO_LIMIT + 1, }; } try { return await Todo.find(findCondition); } catch (err) { //logger.error(err); return this.readException; } } public static async save(newTodo: Todo): Promise<Todo | CommonErrorInfo> { try { const createdTodoId: number = await (await Todo.insert(newTodo)) .identifiers[0].id; const createdTodo: Todo | undefined = await this.findOneById( createdTodoId ); if (!createdTodo) return this.createException; return createdTodo; } catch (err) { //logger.error(err); return this.createException; } } public static async updateOneByStatus( id: number, changedStatus: TodoStatus ): Promise<Todo | CommonErrorInfo> { try { await Todo.update({ id: id }, { status: changedStatus }); const updatedTodo: Todo | undefined = await this.findOneById(id); if (!updatedTodo) return this.updateException; if (updatedTodo.status !== changedStatus) return this.updateException; return updatedTodo; } catch (err) { //logger.error(err); return this.updateException; } } public static async updateOneByDescription( id: number, newDescription: string ): Promise<Todo | CommonErrorInfo> { try { await Todo.update({ id: id }, { description: newDescription }); const updatedTodo: Todo | undefined = await this.findOneById(id); if (!updatedTodo) return this.updateException; if (updatedTodo.description !== newDescription) return this.updateException; return updatedTodo; } catch (err) { //logger.error(err); return this.updateException; } } public static async deleteOneById( id: number ): Promise<Todo | CommonErrorInfo> { try { const deleteWantedTodo: Todo | undefined = await this.findOneById(id); if (!deleteWantedTodo) return this.deleteException; const deletedTodo: Todo = await Todo.remove(deleteWantedTodo); if (await this.findOneById(id)) return this.deleteException; return deletedTodo; } catch (err) { //logger.error(err); return this.deleteException; } } } <file_sep>/src/entity/index.ts import { Todo } from "./Todo"; import { User } from "./User"; export { Todo, User }; <file_sep>/src/resolvers/index.ts import { TodoResolver } from './TodoResolver'; import { UserResolver } from './UserResolver'; export { TodoResolver, UserResolver };<file_sep>/src/error/CommonErrorInfo.ts export class CommonErrorInfo { code: string; message: string; constructor(code: string, message: string) { this.code = code; this.message = message; } getCode(): string { return this.code; } getMessage(): string { return this.message; } }<file_sep>/src/context/AuthChecker.ts import { AuthChecker } from "type-graphql"; import { ApolloContextInterface } from "./ApolloContext"; // Error를 핸들링하기 위한 모듈 import { JsonWebTokenError, TokenExpiredError } from "jsonwebtoken"; import * as errorDTO from "../dto/errorDTO"; export const ApolloAuthChecker: AuthChecker<ApolloContextInterface> = async ( { context: { error, user, Authorization } }, roles ) => { // 만료 된 토큰 일 경우 if (error instanceof TokenExpiredError) { throw new errorDTO.AuthCheckerError(false, "만료된 토큰입니다."); } // 토큰의 형식이 맞지 않는 경우 if (error instanceof JsonWebTokenError) { throw new errorDTO.AuthCheckerError(false, "형식에 맞지 않은 토큰입니다."); } // 그 밖에 모든 오류 if (error) { throw new errorDTO.AuthCheckerError(false, "오류입니다."); } // 모두 통과되면 true를 반환하고 Resolver 실행 return true; }; /* 일단 파라미터 부분을 보면 {conetxt: {jwt, invalidToken, user}}는 우리가 전달한 컨텍스트에서 필요한 것들을 받은것이고 roles는 나중에 우리가 @Authorized(args)로 사용할때 args로 던져준 파라미터일 것이다. 해서 로직은 컨텍스트에서 토큰 검증중 발생한 에러가 담긴 invalidToken이 undefined가 아닌 정의가 되어있다면 해당 에러를 ApolloError로 생성해서 던져주었고 그밑으로는 user 객체의 유무로 true, false를 응답하도록 해놨다. 토큰이 전달되었고 invalidToken이 undefined이라면 user는 항상 존재할 것이다. user가 없는 경우는 토큰이 전달되지 않은 경우일 것이다. 자 이제 작성한 AuthChecker를 사용해보자. 일단 사용하기 위해서는 schema빌드시 함께 빌드 해줘야한다. */ <file_sep>/src/dto/Todo/RegisterInput.ts import { InputType, Field } from "type-graphql"; import { MaxLength, MinLength, IsEmail } from "class-validator"; import { RoleStatus } from "../../enum"; @InputType() export class RegisterInput { @MinLength(1, { message: "이름은 1글자 이상 입력해야 합니다." }) @Field() name: string; @IsEmail({}, { message: "이메일 형식을 지켜 주십시오!" }) @Field() email: string; @MinLength(8, { message: "패스워드가 너무 짧습니다. 8자 이상 입력해 주십시오." }) @MaxLength(20, { message: "패스워드가 너무 깁니다. 20자 이내로 작성해 주십시오." }) @Field() password: string; @Field() role: RoleStatus = RoleStatus.USER; }<file_sep>/README.md careerdirection2 🐻 ============ Apollo-express, TypeORM, TypeGraphql, TypeScript <br> ============ * Author 민경재[ggomjae] <br> * 개인 개발 블로그 링크 <https://blog.naver.com/ggomjae> <br> * 개인 개발 블로그 2 링크 <https://velog.io/@ggomjae> <br> * Js, Sequelize, Graphql 버전의 저장소 : https://github.com/ggomjae/careerdirection <br> # 담당 영역 🔨 BackEnd User영역을 담당하였습니다. <br> 회원가입, 로그인, 비밀번호 변경, 속성 변경, 회원 삭제를 구현하였습니다. REST API vs GraphQL ( TypeGraphQL ) ================================ <div> <img align="left" width="100%" src = "https://user-images.githubusercontent.com/43604493/102218958-24934000-3f22-11eb-8214-af436f39e84b.JPG"> </div> ```단일 엔드 포인트``` vs ```여러 엔드 포인트``` User API ============================== <div> <img align="left" width="100%" src = "https://user-images.githubusercontent.com/43604493/94987126-d4e9dd00-059e-11eb-9ef3-65df6eaf8cf7.JPG"> </div> <div> <img align="left" width="100%" src = "https://user-images.githubusercontent.com/43604493/94987128-d61b0a00-059e-11eb-9f57-75ca31683eeb.JPG"> </div> <div> <img align="left" width="100%" src = "https://user-images.githubusercontent.com/43604493/94987129-d6b3a080-059e-11eb-809d-c05f67d53f79.JPG"> </div> <div> <img align="left" width="100%" src = "https://user-images.githubusercontent.com/43604493/94987131-d74c3700-059e-11eb-8752-f1bf131719c1.JPG"> </div> <div> <img align="left" width="100%" src = "https://user-images.githubusercontent.com/43604493/94987132-d915fa80-059e-11eb-8502-e799f590d4ab.JPG"> </div> # 끝맺음 <br> > 완전한 코드는 Git 위의 코드 부분을 봐주세요. <br> > 개발 과정을 블로그에 올리면서 개발하고 있습니다. 링크 <https://blog.naver.com/ggomjae> <br> <file_sep>/src/dto/errorDTO/AuthCheckerError.ts import { ApolloError } from "apollo-server-express"; // Context 단에서 Error를 상태와 설명을 같이 보내기 위한 클래스 export class AuthCheckerError extends ApolloError { public status: boolean; public description: String; constructor(status: boolean, description: string) { super(description); if (Error.captureStackTrace) { Error.captureStackTrace(this, AuthCheckerError); } this.status = status; this.description = description; } } <file_sep>/src/entity/User.ts import { Entity, Column, PrimaryGeneratedColumn, OneToMany, CreateDateColumn, BaseEntity, } from "typeorm"; import { ObjectType, Field, ID } from "type-graphql"; // 타입 그래프큐엘을 쓰니까 스키마를 따로 빼고 구현할 필요가 없다. // 1:n 관계로 인한 Todo import { Todo } from "./Todo"; // 사용자에 대한 권한 import { roleStatus} from "../type" @ObjectType() // type-graphQL @Entity() // typeorm export class User extends BaseEntity { @Field(() => ID, {}) @PrimaryGeneratedColumn() // Each entity must have at least one primary key column uno!: number; @Field() // () => String 같은 경우 생략이 가능하기 때문에 생략 ,TypeORM 같은 경우에는 String이 아닌 Text로 표현한다. default 255 @Column({ length: 20 }) name!: string; @Field() @Column({ length: 320, unique: true }) // local 64, @ 1 , domain 255 때문에 320, email을 유일한 값으로 설정했기에 unique 속성 추가 email!: string; @Field() // bcrypt결과로 128 @Column({ length: 128 }) password!: string; @Field() // 'user', 'admin'으로 enum으로 설정 @Column({ type: "enum", enum: roleStatus }) roles!: roleStatus; @CreateDateColumn({ name: "created_at" }) created!: Date; @OneToMany((type) => Todo, (todo) => todo.user) todos: Todo[]; // 없을 수 있기에 ! 안씀. } <file_sep>/src/dto/outputDTO/SignInUserOutput.ts import { ObjectType, Field } from "type-graphql"; // 로그인 후 정보를 넘겨주는 DTO @ObjectType({ description: "SignIn Response Data" }) export class SignInUserOutput { @Field() token!: string; @Field() email!: string; @Field() status!: boolean; } <file_sep>/src/enum/index.ts import { TodoStatus } from "./TodoStatus"; import { RoleStatus } from "./RoleStatus"; export { TodoStatus, RoleStatus }; <file_sep>/src/dto/outputDTO/UpdateUserOutput.ts import { ObjectType, Field } from "type-graphql"; // 회원수정하고 수정한 name값과 email을 넘겨주는 DTO @ObjectType({ description: "Update Response Data" }) export class UpdateUserOutput { @Field() name!: string; @Field() email!: string; @Field() status!: boolean; } <file_sep>/src/error/CommonErrorCode.ts export enum CommonErrorCode { ARGUMENT_VALIDATION_ERROR = "ARGUMENT_VALIDATION_ERROR", INTERNAL_SERVER_ERROR = "INTERNAL_SERVER_ERROR", ALREADY_REGISTERED = "ALREADY_REGISTERED", LOGIN_INPUT_INVALIDATION = "LOGIN_INPUT_INVALIDATION", }<file_sep>/src/dto/outputDTO/SignUpUserOutput.ts import { ObjectType, Field } from "type-graphql"; // 회원가입 후 정보를 넘겨주는 DTO @ObjectType({ description: "SignUp Response Data" }) export class SignUpUserOutput { @Field() name!: string; @Field() email!: string; @Field() status!: boolean; } <file_sep>/src/dto/errorDTO/ServiceError.ts // Service 단에서 Error를 상태와 설명을 같이 보내기 위한 클래스 export class ServiceError extends Error { public status: boolean; public description: String; constructor(status: boolean, description: string) { super(description); if (Error.captureStackTrace) { Error.captureStackTrace(this, ServiceError); } this.status = status; this.description = description; } } <file_sep>/src/enum/TodoStatus.ts import { registerEnumType } from "type-graphql"; export enum TodoStatus { TODO = "TODO", DONE = "DONE", } registerEnumType(TodoStatus, { name: "TodoStatus", });<file_sep>/src/enum/RoleStatus.ts import { registerEnumType } from "type-graphql"; export enum RoleStatus { USER = "USER", ADMIN = "ADMIN", } registerEnumType(RoleStatus, { name: "RoleStatus", });<file_sep>/src/dto/Todo/index.ts import { MakeTodoInput } from "./MakeTodoInput"; import { LoginInput } from "./LoginInput"; import { RegisterInput } from "./RegisterInput"; import { UserInfoOutput } from "./UserInfoOutput"; export { MakeTodoInput, LoginInput, RegisterInput, UserInfoOutput }; <file_sep>/src/dto/Todo/MakeTodoInput.ts import { InputType, Field, Int } from "type-graphql"; import { Min, MaxLength, MinLength } from "class-validator"; import { TodoStatus } from "../../enum"; @InputType() export class MakeTodoInput { @Min(1, { message: "현재 작업하는 유저 ID 값이 유효하지 않습니다" }) @Field(() => Int) userId: number; @MinLength(5, { message: "할 일 내용은 5글자 이상이어야 합니다" }) @MaxLength(100, { message: "할 일 내용은 100자 이내여야 합니다" }) @Field() description: string; @Field((type) => TodoStatus) status: TodoStatus; @Field() deadline: string; }<file_sep>/src/dto/outputDTO/VerifyTokenOutput.ts import { ObjectType, Field } from "type-graphql"; // 토큰의 유효성을 확인한 후 정보를 넘겨주는 DTO @ObjectType({ description: "Verify Response Data" }) export class VerifyTokenOutput { @Field() email!: string; } <file_sep>/src/services/index.ts import { UserService } from "./UserService"; import { TodoService } from "./TodoService"; import { Encryption } from "./EncryptionService"; export { UserService, TodoService, Encryption }; <file_sep>/src/dto/inputDTO/index.ts import { SignInUserInput } from "./SignInUserInput"; import { SignUpUserInput } from "./SignUpUserInput"; export { SignInUserInput, SignUpUserInput }; <file_sep>/src/dto/Todo/UserInfoOutput.ts import { ObjectType, Field } from "type-graphql"; import { RoleStatus } from "../../enum"; @ObjectType() export class UserInfoOutput { @Field() id: number; @Field() name: string; @Field() email: string; @Field() role: RoleStatus; }<file_sep>/src/dto/inputDTO/SignInUserInput.ts import { InputType, Field } from "type-graphql"; import { Length, IsEmail } from "class-validator"; // 로그인할 때 쓰는 DTO @InputType({ description: "SignIn User Data" }) export class SignInUserInput { // @IsEmail을 통해 리졸버에 넘기기 전에 확인 @Field() @IsEmail() email!: string; // 패스워드 길이는 최소 12 최대 20 @Field() @Length(12, 20) password!: string; } <file_sep>/src/resolvers/UserResolver.ts import { Resolver, FieldResolver, Mutation, Arg, Root, Ctx, Authorized, } from "type-graphql"; // import { User, Todo } from "../entity"; import { UserService, TodoService } from "../services"; import { TodoStatus } from "../enum"; // DTO import * as inputDTO from "../dto/inputDTO"; import * as outputDTO from "../dto/outputDTO"; // Context 변수 보관소 import { ApolloContextInterface } from "../context/ApolloContext"; @Resolver(() => User) // User를 명시하는 것은 이 Resolver가 무엇을 위한 것인지 알려주는 것이고, 이를 통해 Parent를 User로 사용할 수 있다. export class UserResolver { @FieldResolver((returns) => [Todo]!) // @FieldResolver를 쓰는 이유 : Filed에서 또 Resolver를 쓰기 위해서. async todolist( @Root() user: User, @Arg("cursor") cursor: number, @Arg("status", (type) => TodoStatus) status?: TodoStatus ) { const { uno } = user; // user의 auto_increment이기 때문에 가능. /* Todo Part */ if (!status) { return await TodoService.findAllByUserId(cursor, uno); } else { return await TodoService.findAllByUserIdAndStatus(uno, status, cursor); } } // 회원가입하는 뮤테이션 @Mutation((returns) => outputDTO.SignUpUserOutput, { description: "SingUp User Resolver", }) async signUp( @Arg("signUpUserInput") signUpUserInput: inputDTO.SignUpUserInput ): Promise<outputDTO.SignUpUserOutput> { return await UserService.signUp(signUpUserInput); } // 로그인하는 뮤테이션 @Mutation((returns) => outputDTO.SignInUserOutput, { description: "SignIn User Resolver", }) async login( @Arg("signInUserInput") signInUserInput: inputDTO.SignInUserInput ): Promise<outputDTO.SignInUserOutput> { return await UserService.singIn(signInUserInput); } // 회원을 삭제하는 뮤테이션 @Authorized() @Mutation((returns) => Boolean, { description: "Delete User Resolver" }) async removeUser( @Ctx() apolloContext: ApolloContextInterface ): Promise<Boolean> { return await UserService.deleteUser(apolloContext.user.email); } // 회원을 업데이트하는 뮤테이션 @Authorized() @Mutation((returns) => outputDTO.UpdateUserOutput, { description: "Update User Name Resolver", }) async updateUserName( @Arg("name") name: string, @Ctx() apolloContext: ApolloContextInterface ): Promise<outputDTO.UpdateUserOutput> { return await UserService.updateUserName(name, apolloContext.user.email); } // 비밀번호를 변경하는 뮤테이션 @Authorized() @Mutation((returns) => Boolean, { description: "Update User Password Resolver", }) async updateUserPassword( @Arg("password") password: string, @Ctx() apolloContext: ApolloContextInterface ): Promise<Boolean> { return await UserService.updateUserPassword( password, apolloContext.user.email ); } } <file_sep>/src/context/ApolloContext.ts // import { verifyToken } from "./VerificationToken"; // import { roleStatus } from "../type"; // Token을 생성하는 모듈 import * as JwtFactory from "jsonwebtoken"; import { secretKey } from "../config/jwt"; // DTO import * as outputDTO from "../dto/outputDTO"; /* client 에서 예시처럼 axios로 헤더값에 beaer를 붙여서 토큰을 보낸다. EX) axios.defaults.headers.common['Authorization'] = `Bearer ${Token}`; context 객체는 모든 레벨에서 모든 단일 리졸버로 전달되는 객체이므로 스키마코드 어느 곳에서나 엑세스를 할 수 있다. 이 객체는 새로운 요청이 있을 때마다 컨텍스트가 다시 생성된다. 즉, 저장하는 부분에 있어서 걱정할 필요가 없다. 여기 코드에서는 Authorization 변수 */ export const ApolloContext = async ({ req, }): Promise<ApolloContextInterface> => { let token: string = req.headers.authorization || ""; let user: outputDTO.VerifyTokenOutput = undefined; let userInfo: any = undefined; let error: Error = undefined; if (token) { try { // Bearer를 없애주기 위한 코드 token = token.substr(7); // User에 대한 information 추출 userInfo = await JwtFactory.verify(token, secretKey); } catch (err) { error = err; } } // 에러없이 Token에 User에 대한 information을 잘 추출했으면 email 저장 if (userInfo) { user = { email: (<any>userInfo).email, }; } // Context에 담을 변수를 반환 return { error: error, user: user, Authorization: token, }; }; // Context 보관소 export interface ApolloContextInterface { error: Error; user: outputDTO.VerifyTokenOutput; Authorization: string | undefined; } <file_sep>/src/utils/constants.ts export const GET_TODO_LIMIT : number = 3;<file_sep>/src/config/jwt.ts export const secretKey:String = 'SeCrEtKeYfOrHaShInG'; export const saltRounds:number = 10; <file_sep>/src/services/EncryptionService.ts // 암호화를 위한 모듈 import * as bcrypt from "bcrypt"; import { saltRounds } from "../config/jwt"; export class Encryption { // 암호화 하는 메소드 public static hashPassword(userpassword: string): string { return bcrypt.hashSync(userpassword, saltRounds); } // 암호화된 코드를 확인하는 메소드 public static passwordIsValid(unencryptedPassword: string, password: string) { return bcrypt.compareSync(unencryptedPassword, password); } } <file_sep>/src/resolvers/TodoResolver.ts import { Resolver, Query, Mutation, Arg, Root } from "type-graphql"; import { ApolloError } from "apollo-server-express"; import { Todo } from "../entity"; import { MakeTodoInput, UserInfoOutput } from "../dto/Todo"; import { TodoStatus } from "../enum"; import { TodoService, UserService } from "../services"; import { CommonErrorInfo } from "../error/CommonErrorInfo"; import { CommonErrorCode } from "../error/CommonErrorCode"; @Resolver(() => Todo) export class TodoResolver { @Query((returnType) => [Todo!]!) // O . K async todos( @Arg("cursor", { nullable: true }) cursor?: number, @Arg("status", (type) => TodoStatus, { nullable: true }) status?: TodoStatus ): Promise<Todo[]> { let queryResult: Todo[] | CommonErrorInfo; if (!status) queryResult = await TodoService.findAll(cursor); else queryResult = await TodoService.findAllByStatus(cursor, status); if (queryResult instanceof CommonErrorInfo) throw new ApolloError(queryResult.getMessage(), queryResult.getCode()); return queryResult; } @Mutation((returnType) => Todo) // O . K async makeTodo( @Arg("makeTodoInput") makeTodoInput: MakeTodoInput ): Promise<Todo> { const newTodo: Todo = new Todo(); newTodo.userId = makeTodoInput.userId; newTodo.description = makeTodoInput.description; newTodo.status = makeTodoInput.status; newTodo.deadline = makeTodoInput.deadline; const queryResult: Todo | CommonErrorInfo = await TodoService.save(newTodo); if (queryResult instanceof CommonErrorInfo) throw new ApolloError(queryResult.getMessage(), queryResult.getCode()); return queryResult; } @Mutation((returnType) => Todo) // O . K async updateTodoStatus( @Arg("id") id: number, @Arg("changedStatus", (type) => TodoStatus) changedStatus: TodoStatus ): Promise<Todo> { if (id < 1) throw new ApolloError( "유효하지 않은 TODO의 ID 값입니다.", CommonErrorCode.ARGUMENT_VALIDATION_ERROR ); const queryResult: | Todo | CommonErrorInfo = await TodoService.updateOneByStatus( id, changedStatus ); if (queryResult instanceof CommonErrorInfo) throw new ApolloError(queryResult.getMessage(), queryResult.getCode()); return queryResult; } @Mutation((returnType) => Todo) // O . K async updateTodoDescription( @Arg("id") id: number, @Arg("newDescription") newDescription: string ): Promise<Todo> { if (id < 1) throw new ApolloError( "유효하지 않은 TODO의 ID 값입니다.", CommonErrorCode.ARGUMENT_VALIDATION_ERROR ); if (newDescription.length < 5) throw new ApolloError( "할 일 내용은 5글자 이상이어야 합니다.", CommonErrorCode.ARGUMENT_VALIDATION_ERROR ); if (newDescription.length > 100) throw new ApolloError( "할 일 내용은 100자 이내여야 합니다.", CommonErrorCode.ARGUMENT_VALIDATION_ERROR ); const queryResult: | Todo | CommonErrorInfo = await TodoService.updateOneByDescription( id, newDescription ); if (queryResult instanceof CommonErrorInfo) throw new ApolloError(queryResult.getMessage(), queryResult.getCode()); return queryResult; } @Mutation((returnType) => Todo) // O . K async deleteTodo(@Arg("id") id: number): Promise<Todo> { if (id < 1) throw new ApolloError( "유효하지 않은 TODO의 ID 값입니다.", CommonErrorCode.ARGUMENT_VALIDATION_ERROR ); const queryResult: Todo | CommonErrorInfo = await TodoService.deleteOneById( id ); if (queryResult instanceof CommonErrorInfo) throw new ApolloError(queryResult.getMessage(), queryResult.getCode()); return queryResult; } } <file_sep>/src/dto/inputDTO/SignUpUserInput.ts import { InputType, Field } from "type-graphql"; import { roleStatus } from "../../type"; import { Length, IsEmail } from "class-validator"; // 회원가입할 때 쓰는 DTO @InputType({ description: "SignUp User Data" }) export class SignUpUserInput { @Field() name!: string; // @IsEmail을 통해 리졸버에 넘기기 전에 확인 @Field() @IsEmail() email!: string; // 패스워드 길이는 최소 12 최대 20 @Field() @Length(12, 20) password!: string; @Field() roles: roleStatus = roleStatus.user; // 최초의 개발자 권한자는 직접 admin으로 등록. } <file_sep>/src/dto/errorDTO/index.ts import { ServiceError } from "./ServiceError"; import { AuthCheckerError } from "./AuthCheckerError"; export { ServiceError, AuthCheckerError }; <file_sep>/src/App.ts import * as express from "express"; import { ApolloServer } from 'apollo-server-express'; import { buildSchema } from 'type-graphql'; import { createConnection } from 'typeorm'; import "reflect-metadata"; require('dotenv').config(); /* Import GraphQL Resolvers, Context */ import { TodoResolver, UserResolver } from './resolvers'; import { ApolloContext } from './context/ApolloContext'; /* User AuthCheck */ import { ApolloAuthChecker } from './context/AuthChecker'; class App { public app: express.Application; public static bootstrap (): App { return new App(); } constructor () { // new App을 통해서 생성하면 app에 express가 생성 this.app = express(); this.app.get('/', (req: express.Request, res: express.Response, next: express.NextFunction) => { res.send("TypeScript & GraphQL & ApolloServer & Express 적용 연습"); }); } } const main = async () => { /* DB Connection 과정 */ // 기존에는 Sequelize를 통해 접속했다면, TypeORM의 createConnection을 통해서 DB와 연결 // await를 썼기 때문에 async를 위해서 main이라는 함수를 선언해서 실행했음. await createConnection({ type: "mysql", host: process.env.DB_HOST, port: 3306, username: process.env.DB_USER, password: <PASSWORD>, database: process.env.DB_NAME, entities: [ __dirname + "/entity/*.ts" // 기존에 Models를 Entity를 이용하여 담아준다. ], synchronize: true }) .then(() => { console.log('DB connection is successful with typeorm'); }) .catch((err) => { console.log(err) }); const port: number = 4000; const app: express.Application = App.bootstrap().app; // new App()을 통해 생성했고 할당된 class 안에 있는 app변수를 app에 할당 const schema = await buildSchema({ // type-graphQL 모듈의 method를 통해 resolvers 할당 resolvers: [ TodoResolver, UserResolver ], authChecker: ApolloAuthChecker }); const server = new ApolloServer({ // ApolloServer를 생성하여 server에 할당 context: ApolloContext, // token을 위한 context 주입. schema, playground: true }); /* 미들웨어가 같은 경로에 마운트되도록 한다. Apollo server는 미들웨어에 express.Application을 적용시킨다. apollo-server-express 는 express framework 위에 보다 더 쉽게 graphql resolver 를 구현할 수 있는 기능을 제공. Express에서 Apollo Server를 시작하는 데 필요한 부분을 가져와야합니다. Apollo Server의 applyMiddleware () 메서드를 사용하면 모든 미들웨어 (이 경우 Express)를 옵트 인 할 수 있습니다. */ server.applyMiddleware({ app, path: '/graphql' }); await app.listen({ port: port }, () => { console.log(`Express & Apollo Server listening at ${port}`); }); } main(); <file_sep>/src/entity/Todo.ts import { Entity, BaseEntity, Column, PrimaryGeneratedColumn, ManyToOne, CreateDateColumn } from "typeorm"; import { ObjectType, Field, Int, ID } from "type-graphql"; import { User } from "./User"; // 우선 enum을 적용하지 않은 코드 import { TodoStatus } from "../enum"; // 적용한 코드 @ObjectType() @Entity() export class Todo extends BaseEntity { @Field(() => ID) @PrimaryGeneratedColumn() id: number; @Field(() => Int) @Column({ type: "int" }) userId: number; @Field() @Column("varchar", { length: "100" }) description: string; @Field() @Column({ type: "enum", enum: TodoStatus }) status: TodoStatus; @Field() @Column({ type: "text" }) deadline: string; @Field(() => Date) @CreateDateColumn({ type: "timestamp" }) createdAt: Date; @ManyToOne((type) => User, (user) => user.todos) user: User; }<file_sep>/src/services/UserService.ts import { User } from "../entity"; // Token을 생성하는 모듈 import * as JwtFactory from "jsonwebtoken"; import { secretKey } from "../config/jwt"; // DTO import * as inputDTO from "../dto/inputDTO"; import * as outputDTO from "../dto/outputDTO"; import * as errorDTO from "../dto/errorDTO"; // Encryption import { Encryption } from "./EncryptionService"; export class UserService { // 회원가입 하는 메소드 public static async signUp( makeUserInput: inputDTO.SignUpUserInput ): Promise<outputDTO.SignUpUserOutput> { try { let user = await User.findOne({ email: makeUserInput.email }); // 이미 똑같은 이메일이 있다면 에러 if (user !== undefined) { throw new errorDTO.ServiceError(false, "이미 존재하는 아이디 입니다."); } const newUser = new User(); newUser.email = makeUserInput.email; newUser.password = await Encryption.hashPassword(makeUserInput.password); newUser.name = makeUserInput.name; user = await User.save(newUser); // 클라이언트에서 필요로 하는 정보를 따로 정의하여 넘기는 코드 let result: outputDTO.SignUpUserOutput = { name: user.name, email: user.email, status: true, }; return result; } catch (e) { return e; } } // 로그인하는 메소드 public static async singIn( loginUserInput: inputDTO.SignInUserInput ): Promise<outputDTO.SignInUserOutput> { try { // 이메일을 이용해서 DB에 저장된 유저 추출 const user = await User.findOne({ email: loginUserInput.email }); // 만약 해당하지 않은 email로 인해 user에 undefined가 있거나, 비밀번호가 맞지 않다면 if ( user === undefined || !(await Encryption.passwordIsValid( loginUserInput.password, user.password )) ) { // 보안상 비밀번호, 존재하지않은 경우를 같이 묶어서 에러를 보냄 throw new errorDTO.ServiceError( false, "존재하지 않거나 비밀번호가 틀렸습니다." ); } // 비밀번호가 맞다면 Token 값을 만들어서 넘겨줌. Token을 만들고 반환 const token = JwtFactory.sign( { email: loginUserInput.email }, // payload 구간 secretKey, // config에 저장되어있는 secretKey { expiresIn: "1h", // 만료 기간을 잡는 옵션 issuer: "gomjae", // 토큰 발급자 subject: "tokenTitle", // 토큰 제목 } ); let result: outputDTO.SignInUserOutput = { token: token, email: loginUserInput.email, status: true, }; return result; } catch (e) { return e; } } // 회원을 탈퇴하는 메소드 public static async deleteUser(email: string): Promise<Boolean> { try { // 탈퇴하려는 회원을 추출하는 메소드 const user = await User.findOne({ email: email }); // 만약 이메일이 존재하지 않는 경우 if (user === undefined) { return false; } // remove는 엔티티 배열이 포함된 경우, delete는 상태를 알고 있는 경우. await User.remove(user); return true; } catch (e) { return e; } } // 회원의 Name을 수정하는 메소드 public static async updateUserName( name: string, email: string ): Promise<outputDTO.UpdateUserOutput> { try { const user = await User.findOne({ email: email }); // 만약 바꾸려는 name이 같다면 if (user.name === name) { throw new errorDTO.ServiceError(false, "같은 값입니다."); } user.name = name; // typeorm - save : 만약 엔티티가 데이터베이스에 존재하지 않다면 삽입시켜주고 아니면 업데이트를 시켜주는 메소드 const userInfo: User = await User.save(user); // 업데이트 후 클라이언트가 필요로 하는 정보를 반환 const result: outputDTO.UpdateUserOutput = { name: userInfo.name, email: userInfo.email, status: true, }; return result; } catch (e) { return e; } } // 회원의 패스워드 속성을 수정하는 메소드 public static async updateUserPassword( password: string, email: string ): Promise<Boolean> { try { const user = await User.findOne({ email: email }); // 모듈[ bcypt ]를 이용하여 password 암호화 user.password = await Encryption.hashPassword(password); // 바뀐 암호의 객체를 저장하는 메소드 await User.save(user); return true; } catch (e) { return e; } } }
7d713c40db31b24d98a1c413afd5c8ea6084ce05
[ "Markdown", "TypeScript" ]
37
TypeScript
minyul/careerdirection2
35b47d8854f956c044807155e0c37d67d3a1de10
f07bb2f9c8b804e7cddcf2ee7174b5168c800050
refs/heads/master
<repo_name>farmafield-labs/django-forms-builder<file_sep>/forms_builder/forms/urls.py from __future__ import unicode_literals from django.urls import re_path from forms_builder.forms import views app_name="forms" urlpatterns = [ re_path(r"(?P<slug>.*)/sent/$", views.form_sent, name="form_sent"), re_path(r"(?P<slug>.*)/$", views.form_detail, name="form_detail"), ]
2076bc2128e03409470e2ff2dea3093f7a1ea10c
[ "Python" ]
1
Python
farmafield-labs/django-forms-builder
484886f3bbaafb28d4fe1709a6cd1604ca6ce69c
07cd89d962f3a24f90e476835a52c1f321a2eb0e
refs/heads/main
<file_sep>/* This program was written by the FTC KTM #12529 team at the Polytechnic University in 2020. @author <NAME> */ package org.firstinspires.ftc.teamcode.AutoOPs; import com.qualcomm.hardware.bosch.BNO055IMU; import com.qualcomm.robotcore.eventloop.opmode.Autonomous; import com.qualcomm.robotcore.hardware.DcMotor; import com.qualcomm.robotcore.util.ElapsedTime; import org.firstinspires.ftc.robotcore.external.navigation.AngleUnit; import org.firstinspires.ftc.robotcore.external.navigation.AxesOrder; import org.firstinspires.ftc.robotcore.external.navigation.AxesReference; import org.firstinspires.ftc.robotcore.external.navigation.Orientation; import org.firstinspires.ftc.teamcode.Robot; import org.firstinspires.ftc.teamcode.Vision.EasyOpenCVVision; import org.firstinspires.ftc.teamcode.odometry.OdometryGlobalCoordinatePosition; import org.openftc.easyopencv.OpenCvCamera; import org.openftc.easyopencv.OpenCvCameraFactory; import org.openftc.easyopencv.OpenCvCameraRotation; import org.openftc.easyopencv.OpenCvInternalCamera; @Autonomous(name = "Left_Center", group = "AutoOP") public class Left_Center extends Robot { private ElapsedTime runtime = new ElapsedTime(); OpenCvInternalCamera phoneCam; EasyOpenCVVision pipeline; DcMotor right_front, right_back, left_front, left_back; //Odometry Wheels DcMotor verticalLeft, verticalRight, horizontal; final double COUNTS_PER_INCH = 307.699557; //Hardware Map Names for drive motors and odometry wheels. THIS WILL CHANGE ON EACH ROBOT, YOU NEED TO UPDATE THESE VALUES ACCORDINGLY String rfName = "m4 drive", rbName = "m1 drive", lfName = "m2 drive", lbName = "m3 drive"; String verticalLeftEncoderName = rbName, verticalRightEncoderName = lfName, horizontalEncoderName = rfName; OdometryGlobalCoordinatePosition globalPositionUpdate; @Override public void runOpMode() { initHW(hardwareMap); BNO055IMU imu; Orientation angles; BNO055IMU.Parameters parameters = new BNO055IMU.Parameters(); parameters.angleUnit = BNO055IMU.AngleUnit.DEGREES; imu = hardwareMap.get(BNO055IMU.class, "imu"); initDriveHardwareMap(rfName, rbName, lfName, lbName, verticalLeftEncoderName, verticalRightEncoderName, horizontalEncoderName); // Camera setup int cameraMonitorViewId = hardwareMap.appContext.getResources().getIdentifier("cameraMonitorViewId", "id", hardwareMap.appContext.getPackageName()); phoneCam = OpenCvCameraFactory.getInstance().createInternalCamera(OpenCvInternalCamera.CameraDirection.BACK, cameraMonitorViewId); pipeline = new EasyOpenCVVision(); phoneCam.setPipeline(pipeline); phoneCam.setViewportRenderingPolicy(OpenCvCamera.ViewportRenderingPolicy.OPTIMIZE_VIEW); phoneCam.openCameraDeviceAsync(new OpenCvCamera.AsyncCameraOpenListener() { @Override public void onOpened() { phoneCam.startStreaming(320, 240, OpenCvCameraRotation.SIDEWAYS_LEFT); } }); telemetry.addLine("Phone camera initialized"); telemetry.update(); s1TopClaw.setPosition(0); s4Kicker.setPosition(1); s3Rotation.setPosition(0); //Voltage regulation depending on the battery charge level double voltage = BatteryVoltage(); double koeff = 13.0 / voltage; koeff = Math.pow(koeff, 1.25); globalPositionUpdate = new OdometryGlobalCoordinatePosition(verticalLeft, verticalRight, horizontal, COUNTS_PER_INCH, 75); Thread positionThread = new Thread(globalPositionUpdate); positionThread.start(); globalPositionUpdate.reverseLeftEncoder(); waitForStart(); { imu.initialize(parameters); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); telemetry.clear(); telemetry.addData("Number of rings ", pipeline.position); telemetry.update(); int countOfRings = 12; if ((pipeline.position == EasyOpenCVVision.RingPosition.FOUR)) { countOfRings = 4; } if ((pipeline.position == EasyOpenCVVision.RingPosition.ONE)) { countOfRings = 1; } if ((pipeline.position == EasyOpenCVVision.RingPosition.NONE)) { countOfRings = 0; } //Voltage regulation depending on the battery charge level telemetry.addData("count_of_rings ", countOfRings); telemetry.update(); boolean check= true; //shooting targets Shooting(koeff,0.68); goToPosition(-12* COUNTS_PER_INCH, -170*COUNTS_PER_INCH,0.5*koeff,0,7*COUNTS_PER_INCH); goToPosition(-12* COUNTS_PER_INCH, -227*COUNTS_PER_INCH,0.3*koeff,0,2*COUNTS_PER_INCH); Shoot(); angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while(!isStopRequested()&&angles.firstAngle>-5.5){ setMotorsPower(0.15*koeff,0.15*koeff,0.15*koeff,0.15*koeff); angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0,0,0,0); Shooting(koeff,0.7); Shoot(); while(!isStopRequested()&&angles.firstAngle>-11){ setMotorsPower(0.15*koeff,0.15*koeff,0.15*koeff,0.15*koeff); angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0,0,0,0); Shoot(); endShooting(); s3Rotation.setPosition(1); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle < -5) { setMotorsPower(-0.3 * koeff, -0.3 * koeff, -0.3 * koeff, -0.3 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); s3Rotation.setPosition(1); s4Kicker.setPosition(0); /* //shooting high gates Shooting(koeff,0.75); goToPosition(-12* COUNTS_PER_INCH, -150*COUNTS_PER_INCH,0.5*koeff,0,7*COUNTS_PER_INCH); goToPosition(-12* COUNTS_PER_INCH, -207*COUNTS_PER_INCH,0.3*koeff,0,2*COUNTS_PER_INCH); sleep(300); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle < 6) { setMotorsPower(-0.18 * koeff, -0.18 * koeff, -0.18 * koeff, -0.18 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); sleep(500); Shooting(koeff, 0.78); Shoot(); sleep(100); Shoot(); sleep(100); Shoot(); s4Kicker.setPosition(0); endShooting(); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle > 2) { setMotorsPower(0.3 * koeff, 0.3 * koeff, 0.3 * koeff, 0.3 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); s3Rotation.setPosition(1); */ //moving back to rings if(countOfRings==4&&check) { check=false; goToPosition(5 * COUNTS_PER_INCH, -125 * COUNTS_PER_INCH, 0.6 * koeff, 0, 8 * COUNTS_PER_INCH); goToPosition(74 * COUNTS_PER_INCH, -105 * COUNTS_PER_INCH, 0.3 * koeff, 0, 2 * COUNTS_PER_INCH); //collecting rings setMotorsPower(-0.7,0.7,0.7,-0.7); sleep(200); m5Lift.setPower(-1); setMotorsPower(0,0,0,0); sleep(900); setMotorsPower(-0.2,0.2,0.2,-0.2); sleep(550); setMotorsPower(0,0,0,0); sleep(900); setMotorsPower(-0.2,0.2,0.2,-0.2); sleep(550); setMotorsPower(0,0,0,0); sleep(1400); m5Lift.setPower(0); s4Kicker.setPosition(1); sleep(500); //shooting high gates Shooting(koeff, 0.77); sleep(500); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle > -4) { setMotorsPower(0.1 * koeff, 0.1 * koeff, 0.1 * koeff, 0.1 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); sleep(500); Shooting(koeff, 0.78); Shoot(); sleep(100); Shoot(); sleep(100); Shoot(); s4Kicker.setPosition(0); endShooting(); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle < -2) { setMotorsPower(-0.3 * koeff, -0.3 * koeff, -0.3 * koeff, -0.3 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); goToPosition(40* COUNTS_PER_INCH,-380*COUNTS_PER_INCH,0.6*koeff,0,10*COUNTS_PER_INCH); //m5Lift.setPower(-1); goToPosition(140* COUNTS_PER_INCH,-455*COUNTS_PER_INCH,0.3*koeff,0,3*COUNTS_PER_INCH); s3Rotation.setPosition(0); otpustivobl(koeff); setMotorsPower(0,0,0,0); goToPosition(45 * COUNTS_PER_INCH, -430 * COUNTS_PER_INCH, 0.5*koeff, 0, 8* COUNTS_PER_INCH); goToPosition(5* COUNTS_PER_INCH, -300 * COUNTS_PER_INCH, 0.4*koeff, 0, 4* COUNTS_PER_INCH); } if(countOfRings==1&&check){//добавить координату check=false; angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle < -5) { setMotorsPower(-0.3 * koeff, -0.3 * koeff, -0.3 * koeff, -0.3 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); s4Kicker.setPosition(0); m5Lift.setPower(-1); goToPosition(5 * COUNTS_PER_INCH, -130 * COUNTS_PER_INCH, 0.6 * koeff, 0, 8 * COUNTS_PER_INCH); goToPosition(75 * COUNTS_PER_INCH, -110 * COUNTS_PER_INCH, 0.3 * koeff, 0, 2 * COUNTS_PER_INCH); goToPosition(75 * COUNTS_PER_INCH, -150 * COUNTS_PER_INCH, 0.15 * koeff, 0, 2 * COUNTS_PER_INCH); sleep(1000); s4Kicker.setPosition(1); sleep(500); Shooting(koeff, 0.78); sleep(500); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle > -4) { setMotorsPower(0.18 * koeff, 0.18 * koeff, 0.18 * koeff, 0.18 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); m5Lift.setPower(0); sleep(500); Shoot(); sleep(100); Shoot(); endShooting(); s4Kicker.setPosition(0); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while (!isStopRequested() && angles.firstAngle < -5) { setMotorsPower(-0.3 * koeff, -0.3 * koeff, -0.3 * koeff, -0.3 * koeff); angles = imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0, 0, 0, 0); //добавить координату //m5Lift.setPower(-1); goToPosition(40* COUNTS_PER_INCH,-350*COUNTS_PER_INCH,0.3*koeff,0,2*COUNTS_PER_INCH); s3Rotation.setPosition(0); otpustivobl(koeff); setMotorsPower(0,0,0,0); goToPosition(5 * COUNTS_PER_INCH, -300 * COUNTS_PER_INCH, 0.3*koeff, 0, 3 * COUNTS_PER_INCH); } if(countOfRings==0&&check){//добавить координату check=false; goToPosition(80* COUNTS_PER_INCH,-275*COUNTS_PER_INCH,0.5*koeff,0,7*COUNTS_PER_INCH); //m5Lift.setPower(-1); goToPosition(134* COUNTS_PER_INCH,-275*COUNTS_PER_INCH,0.3*koeff,0,2*COUNTS_PER_INCH); s3Rotation.setPosition(0); otpustivobl(koeff); angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); while(!isStopRequested()&&angles.firstAngle<-5){ setMotorsPower(-0.3*koeff,-0.3*koeff,-0.3*koeff,-0.3*koeff); angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); } setMotorsPower(0,0,0,0); goToPosition(5 * COUNTS_PER_INCH, -300 * COUNTS_PER_INCH, 0.3*koeff, 0, 3 * COUNTS_PER_INCH); } //добавить координату globalPositionUpdate.stop(); // //otpustivobl(koeff); // Shooting(koeff,0.82); // double time1; // double time2; // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&DistanceSensor_right.getDistance(DistanceUnit.CM)>32){ // setMotorsPowerright(-0.3*koeff,0.3*koeff,-0.3*koeff,0.3*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&time2-time1<0.2){ // //angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // setMotorsPowerforvard(0.5*koeff,-0.5*koeff,-0.5*koeff,0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // sleep(1000); // Shoot(); // sleep(1000); // Shoot(); // sleep(1000); // Shoot(); // endShooting(); // while(!isStopRequested()&&DistanceSensor_right.getDistance(DistanceUnit.CM)>20){ // setMotorsPowerright(-0.3*koeff,0.3*koeff,-0.3*koeff,0.3*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // // // The choice of the direction of movement depending on the number of rings // boolean check =true; // if (countOfRings==4&&check) { // check=false; // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&DistanceSensor_forward.getDistance(DistanceUnit.CM)>69){ // setMotorsPowerforvard(-0.5*koeff,0.5*koeff,0.5*koeff,-0.5*koeff,angles, imu, 0); // time2=getRuntime(); //// telemetry.addData("angle of rotate ", angles.firstAngle); //// telemetry.update(); // } // setMotorsPower(0,0,0,0); // // otpustivobl(koeff); // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&time2-time1<0.2){ // setMotorsPowerright(-0.3*koeff,0.3*koeff,-0.3*koeff,0.3*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&DistanceSensor_forward.getDistance(DistanceUnit.CM)<160){ // setMotorsPowerback(0.5*koeff,-0.5*koeff,-0.5*koeff,0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // // } // // if (countOfRings==1&&check) { // check=false; // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&DistanceSensor_forward.getDistance(DistanceUnit.CM)>80){ // setMotorsPowerforvard(-0.5*koeff,0.5*koeff,0.5*koeff,-0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // // angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // while(!isStopRequested()&&angles.firstAngle<82){ // setMotorsPower(-0.3*koeff,-0.3*koeff,-0.3*koeff,-0.3*koeff); // angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // } // setMotorsPower(0,0,0,0); // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&time2-time1<0.2){ // setMotorsPowerforvard(-0.5*koeff,0.5*koeff,0.5*koeff,-0.5*koeff,angles, imu, -90); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // otpustivobl(koeff); // // angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // while(!isStopRequested()&&angles.firstAngle>5){ // setMotorsPower(0.3*koeff,0.3*koeff,0.3*koeff,0.3*koeff); // angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // } // setMotorsPower(0,0,0,0); // // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&DistanceSensor_forward.getDistance(DistanceUnit.CM)<160){ // angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // setMotorsPowerback(0.5*koeff,-0.5*koeff,-0.5*koeff,0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // // } // // if (countOfRings==0&&check) { // check=false; // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&DistanceSensor_forward.getDistance(DistanceUnit.CM)>160){ // setMotorsPowerforvard(-0.5*koeff,0.5*koeff,0.5*koeff,-0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&time2-time1<0.8){ // //angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // setMotorsPowerforvard(0.5*koeff,-0.5*koeff,-0.5*koeff,0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); // sleep(200); // otpustivobl(koeff); // time1=getRuntime(); // time2=getRuntime(); // while(!isStopRequested()&&time2-time1<0.2){ // //angles=imu.getAngularOrientation(AxesReference.INTRINSIC, AxesOrder.ZYX, AngleUnit.DEGREES); // setMotorsPowerforvard(0.5*koeff,-0.5*koeff,-0.5*koeff,0.5*koeff,angles, imu, 0); // time2=getRuntime(); // } // setMotorsPower(0,0,0,0); //} } } public void goToPosition(double targetXPosition, double targetYPosition, double robotPower, double desiredRobotOrientation,double allowableDistanceError){ double distanceToXTarget = targetXPosition - globalPositionUpdate.returnXCoordinate(); double distanceToYTarget = targetYPosition - globalPositionUpdate.returnYCoordinate(); double distance = Math.hypot(distanceToXTarget,distanceToYTarget); while(!isStopRequested()&&distance>allowableDistanceError){ distance = Math.hypot(distanceToXTarget,distanceToYTarget); distanceToXTarget = targetXPosition - globalPositionUpdate.returnXCoordinate(); distanceToYTarget = targetYPosition - globalPositionUpdate.returnYCoordinate(); double robotMovementAngle = Math.toDegrees(Math.atan2(distanceToXTarget, distanceToYTarget)); double robot_movement_x_component = calculateX(robotMovementAngle, robotPower); double robot_movement_y_component = calculateY(robotMovementAngle, robotPower); double pivotCorrection = desiredRobotOrientation - globalPositionUpdate.returnOrientation(); double d1 = -pivotCorrection/60+robot_movement_y_component+robot_movement_x_component; double d2 = -pivotCorrection/60-robot_movement_y_component-robot_movement_x_component; double d3 = -pivotCorrection/60-robot_movement_y_component+robot_movement_x_component; double d4 = -pivotCorrection/60+robot_movement_y_component-robot_movement_x_component; double koeff = 0.5; setMotorsPowerOdom(d1,d2,d3,d4); // telemetry.addData("X Position", globalPositionUpdate.returnXCoordinate() / COUNTS_PER_INCH); // telemetry.addData("Y Position", globalPositionUpdate.returnYCoordinate() / COUNTS_PER_INCH); // telemetry.addData("Orientation (Degrees)", globalPositionUpdate.returnOrientation()); // telemetry.addData("robot_movement_x_component", robot_movement_x_component); // telemetry.addData("robot_movement_y_component", robot_movement_y_component); // telemetry.addData("pivot", pivotCorrection); // telemetry.addData("motor1_power", d1); // telemetry.addData("motor2_power", d2); // telemetry.addData("motor3_power", d3); // telemetry.addData("motor4_power", d4); // telemetry.update(); } stopMovement(); } protected void setMotorsPowerOdom(double D1_power, double D2_power, double D3_power, double D4_power) { //Warning: Эта функция включит моторы РЅРѕ, выключить РёС… надо будет после выполнения какого либо условия // Send power to wheels right_back.setPower(D1_power); left_front.setPower(D2_power); left_back.setPower(D3_power); right_front.setPower(D4_power); } protected void stopMovement(){ right_back.setPower(0); left_front.setPower(0); left_back.setPower(0); right_front.setPower(0); } private void initDriveHardwareMap(String rfName, String rbName, String lfName, String lbName, String vlEncoderName, String vrEncoderName, String hEncoderName){ right_front = hardwareMap.dcMotor.get(rfName); right_back = hardwareMap.dcMotor.get(rbName); left_front = hardwareMap.dcMotor.get(lfName); left_back = hardwareMap.dcMotor.get(lbName); verticalLeft = hardwareMap.dcMotor.get(vlEncoderName); verticalRight = hardwareMap.dcMotor.get(vrEncoderName); horizontal = hardwareMap.dcMotor.get(hEncoderName); right_front.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); right_back.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); left_front.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); left_back.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); right_front.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); right_back.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); left_front.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); left_back.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); verticalLeft.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); verticalRight.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); horizontal.setMode(DcMotor.RunMode.STOP_AND_RESET_ENCODER); verticalLeft.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); verticalRight.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); horizontal.setMode(DcMotor.RunMode.RUN_WITHOUT_ENCODER); right_front.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); right_back.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); left_front.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); left_back.setZeroPowerBehavior(DcMotor.ZeroPowerBehavior.BRAKE); //left_front.setDirection(DcMotorSimple.Direction.REVERSE); //right_front.setDirection(DcMotorSimple.Direction.REVERSE); //right_back.setDirection(DcMotorSimple.Direction.REVERSE); telemetry.addData("Status", "Hardware Map Init Complete"); telemetry.update(); } /** * Calculate the power in the x direction * @param desiredAngle angle on the x axis * @param speed robot's speed * @return the x vector */ private double calculateX(double desiredAngle, double speed) { return Math.sin(Math.toRadians(desiredAngle)) * speed; } /** * Calculate the power in the y direction * @param desiredAngle angle on the y axis * @param speed robot's speed * @return the y vector */ private double calculateY(double desiredAngle, double speed) { return Math.cos(Math.toRadians(desiredAngle)) * speed; } }
395be485fbd2ce47c1a23dfac78919b24eabf878
[ "Java" ]
1
Java
SaladQueeny/FTC_KTM_2020_2021_ExpansionHub_6_1
c28ea24b9a8101d6aff0125eed3ae0ea5e3ffad3
38c8bce08f5779993ae201cc89c6070d696387e4
refs/heads/main
<file_sep># UTF-8 UTF-8 C++ Created and written in c++ Used as an university task for Computer architecture <file_sep>#include <iostream> #include <vector> #include <algorithm> #include <fstream> #include <map> #include <string> #include <cmath> using namespace std; struct Duomenys { int desimtainis = 0; vector<char> dvejaitaine; string Unicode, UTFas; }; void DesimtainisToDvejetaini(int desimtainis, vector<char>& dvejetainis) { for (int i = 0; 0 < desimtainis; i++) { char laikinas = desimtainis % 2 + '0'; dvejetainis.push_back(laikinas); desimtainis /= 2; } if (dvejetainis.size() % 4 != 0) { int laikinas = 4 - dvejetainis.size() % 4; for (int i = 0; i < laikinas; i++) { dvejetainis.push_back('0'); } } reverse(dvejetainis.begin(), dvejetainis.end()); //for (auto it : dvejetainis) cout << it; } void DvejatainisToSesioliktainis(vector<char> dvejetainis, string& sesioliktainis) { ifstream fd("dvejetainiai_sesioliktainiai.txt"); map<string, char> dvejetainiai_sesioliktainiai; map<string, char>::iterator it; string sesiolik; char dvej; while (fd >> sesiolik >> dvej) { dvejetainiai_sesioliktainiai[sesiolik] = dvej; } fd.close(); string rinkinys; for (int i = 0; i != dvejetainis.size(); i++) { rinkinys.push_back(dvejetainis[i]); if ((i + 1) % 4 == 0) { it = dvejetainiai_sesioliktainiai.find(rinkinys); if (it != dvejetainiai_sesioliktainiai.end()) { sesioliktainis.push_back(it->second); } rinkinys = ""; } } } void UnicodasToUTFas(vector<char> dvejetainis, int desimtainis, string& UTFas) { vector<char> DvejetainiISesioliktaini; UTFas = {}; if (desimtainis < 128) { for (int i = 0; i < 8; i++) { if (i == 7) { DvejetainiISesioliktaini.push_back('0'); } else { if (dvejetainis.size() != 0) { DvejetainiISesioliktaini.push_back(dvejetainis.back()); dvejetainis.pop_back(); } else { DvejetainiISesioliktaini.push_back('0'); } } } } else if (desimtainis < 2048) { for (int i = 0; i < 16; i++) { if (i == 6) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 7) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 13) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 14) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 15) { DvejetainiISesioliktaini.push_back('1'); } else { if (dvejetainis.size() != 0) { DvejetainiISesioliktaini.push_back(dvejetainis.back()); dvejetainis.pop_back(); } else { DvejetainiISesioliktaini.push_back('0'); } } } } else if (desimtainis < 65536) { for (int i = 0; i < 24; i++) { if (i == 6) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 7) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 14) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 15) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 20) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 21) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 22) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 23) { DvejetainiISesioliktaini.push_back('1'); } else { if (dvejetainis.size() != 0) { DvejetainiISesioliktaini.push_back(dvejetainis.back()); dvejetainis.pop_back(); } else { DvejetainiISesioliktaini.push_back('0'); } } } } else if (desimtainis < 1114112) { for (int i = 0; i < 32; i++) { if (i == 6) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 7) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 14) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 15) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 22) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 23) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 27) { DvejetainiISesioliktaini.push_back('0'); } else if (i == 28) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 29) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 30) { DvejetainiISesioliktaini.push_back('1'); } else if (i == 31) { DvejetainiISesioliktaini.push_back('1'); } else { if (dvejetainis.size() != 0) { DvejetainiISesioliktaini.push_back(dvejetainis.back()); dvejetainis.pop_back(); } else { DvejetainiISesioliktaini.push_back('0'); } } } } reverse(DvejetainiISesioliktaini.begin(), DvejetainiISesioliktaini.end()); //for (auto it : UTFas) cout << it; DvejatainisToSesioliktainis(DvejetainiISesioliktaini, UTFas); } void SesioliktainisToDvejetainis(vector<char>& dvejetainis, string sesioliktainis) { ifstream fd("dvejetainiai_sesioliktainiai.txt"); map<char, string> dvejetainiai_sesioliktainiai; map<char, string>::iterator it; char sesiolik; string dvej; while (fd >> dvej >> sesiolik) { dvejetainiai_sesioliktainiai[sesiolik] = dvej; } fd.close(); dvejetainis = {}; for (int i = 0; i != sesioliktainis.size(); i++) { it = dvejetainiai_sesioliktainiai.find(sesioliktainis[i]); if (it != dvejetainiai_sesioliktainiai.end()) { for (int i = 0; i != it->second.size(); i++) dvejetainis.push_back(it->second[i]); } } /*for (auto it : dvejetainiai_sesioliktainiai) { cout << it.first << " " << it.second << endl; } cout << endl;*/ } int DvejetainisToDesimtainis(vector<char> dvejetainis) { int desimtainis = 0, j = 0; for (int i = dvejetainis.size() - 1; i >= 0; i--) { int Ldvejetainis = dvejetainis[i] - '0'; int Kvadratas; Kvadratas = (int)pow(2, j); desimtainis += (Ldvejetainis * Kvadratas); j++; } return desimtainis; } vector<char> hex_to_bytes(const string& hex) { vector<char> bytes; for (unsigned int i = 0; i < hex.length(); i += 2) { string byteString = hex.substr(i, 2); char byte = (char)strtol(byteString.c_str(), NULL, 16); bytes.push_back(byte); } return bytes; } int main() { bool veikia = true; while (veikia) { system("CLS"); int ats; cout << "---------------------------------------------------------------------------" << endl; cout << "1. Convert Dec To UTF8" << endl; cout << "2. Convert 386intel.txt file to UTF8 using CP437 encoding (outputs to file)" << endl; cout << "3. Exit!" << endl; cout << "---------------------------------------------------------------------------" << endl; cout << "Answer: "; cin >> ats; if(ats==1) { int taipne; system("CLS"); Duomenys struktura; cin >> struktura.desimtainis; DesimtainisToDvejetaini(struktura.desimtainis, struktura.dvejaitaine); DvejatainisToSesioliktainis(struktura.dvejaitaine, struktura.Unicode); UnicodasToUTFas(struktura.dvejaitaine, struktura.desimtainis, struktura.UTFas); ofstream fr("output.txt"); cout << "UNICODE: U+"; for (int i = struktura.Unicode.size(); i < 4; i++) { cout << "0"; } cout << struktura.Unicode << endl; cout << "UTF-8: "; for (int i = 0; i != struktura.UTFas.size(); i++) { cout << struktura.UTFas[i]; if ((i + 1) % 2 == 0 && i + 1 != struktura.UTFas.size()) { cout << " "; } } cout << endl; fr << endl; cout << "CHAR: " << char(struktura.desimtainis) << endl; fr.close(); cout << "Do you want to continue?\n"; cout << "1. Yes\n"; cout << "2. No\n"; cin >> taipne; if (taipne != 1) { veikia = false; } } else if(ats==2) { int taipne; ifstream fd("386intel.txt"); ofstream fr("output.txt"); Duomenys struktura; char currentSym; map<int, string> CP437; map<int, string>::iterator it; int cpDec; string cpHex; ifstream cp("CP437.txt"); while (cp >> cpHex >> cpDec) { CP437[cpDec] = cpHex; } cp.close(); while (fd.get(currentSym)) { struktura.desimtainis = currentSym; if (struktura.desimtainis < 0) { struktura.desimtainis += 256; it = CP437.find(struktura.desimtainis); if (it != CP437.end()) { struktura.Unicode = it->second; } //cout << struktura.Unicode << endl; SesioliktainisToDvejetainis(struktura.dvejaitaine, struktura.Unicode); struktura.desimtainis = DvejetainisToDesimtainis(struktura.dvejaitaine); UnicodasToUTFas(struktura.dvejaitaine, struktura.desimtainis, struktura.UTFas); vector<char> bytes = hex_to_bytes(struktura.UTFas); //cout << struktura.Unicode << " " << struktura.UTFas << " " <<struktura.desimtainis<< " " <<currentSym<< endl; for (auto it : bytes) { fr << it; } } else { fr << currentSym; } } fd.close(); fr.close(); //system("CLS"); cout << "File created" << endl; cout << "Do you want to continue?" << endl; cout << "1. Yes "<< endl; cout << "2. No "<< endl; cin >> taipne; if (taipne != 1) { veikia = false; } } } }
c9d5c74b99389cc0a2318e973f1143377ab9b94f
[ "Markdown", "C++" ]
2
Markdown
Jukis252/UTF-8
660d2b62655bf2d0b23c29e6d5dc9efb9ee7e679
2bafdf15066abf0f62740666df42d85ee698b74a
refs/heads/master
<file_sep>import numpy as np import pythran import scipy from scipy.interpolate import RBFInterpolator np.random.seed(0) num = 150 x = np.linspace(0, 1, num) y = x[:, None] image = x + y # Destroy some values mask = np.random.random(image.shape) > 0.7 image[mask] = np.nan valid_mask = ~np.isnan(image) coords = np.array(np.nonzero(valid_mask)).T values = image[valid_mask] it = RBFInterpolator(coords, values) filled = it(list(np.ndindex(image.shape))).reshape(image.shape) <file_sep>Directory which will contain detailed results directly obtained from the profiler.<file_sep>import numpy as np import pythran, yappi import scipy, sys from scipy.interpolate import RBFInterpolator from tabulate import tabulate np.random.seed(0) def find_total_and_avg_time(yappi_stats): TOTAL_KEY = 6 AVG_KEY = 14 total_time = 0 avg_time = 0 for stat_dict in yappi_stats: total_time += stat_dict[TOTAL_KEY] avg_time += stat_dict[AVG_KEY] return total_time, avg_time print("Pythran Version: ", pythran.__version__) print("Scipy Version: ", scipy.__version__) print("NumPy Version: ", np.__version__) print("Yappi Version: ", '1.3.2') results_init = [] results_eval = [] flags = '_'.join(sys.argv[1:]) repeat_freq = 10 num_points = [40, 50, 60, 70, 80, 90] for num in num_points: result_init = [] result_eval = [] x = np.linspace(0, 1, num) y = x[:, None] image = x + y print(image.shape) # Destroy some values mask = np.random.random(image.shape) > 0.7 image[mask] = np.nan valid_mask = ~np.isnan(image) coords = np.array(np.nonzero(valid_mask)).T values = image[valid_mask] N = coords.shape[0] result_init.append(N) result_eval.append(N) if len(flags) > 0: file_name_prefix = 'results/yappi_' + flags + '_' else: file_name_prefix = 'results/yappi_' file = open(file_name_prefix + str(coords.shape[0]) + '_init', 'w') with yappi.run(builtins=True): for _ in range(repeat_freq): it = RBFInterpolator(coords, values) init_stats = yappi.get_func_stats() init_stats.print_all(out=file) total_time, avg_time = find_total_and_avg_time(init_stats) result_init.append(total_time) result_init.append(avg_time) result_init.append(yappi.get_mem_usage()) file.write("Memory Usage: " + str(yappi.get_mem_usage()) + "\n") file.close() yappi.clear_stats() file = open(file_name_prefix + str(coords.shape[0]) + '_evaluate', 'w') with yappi.run(builtins=True): for _ in range(repeat_freq): filled = it(list(np.ndindex(image.shape))).reshape(image.shape) eval_stats = yappi.get_func_stats() eval_stats.print_all(out=file) total_time, avg_time = find_total_and_avg_time(eval_stats) result_eval.append(total_time) result_eval.append(avg_time) result_eval.append(yappi.get_mem_usage()) file.write("Memory Usage: " + str(yappi.get_mem_usage()) + "\n") file.close() yappi.clear_stats() del x, y, image, it, filled results_init.append(result_init) results_eval.append(result_eval) print("Completed Successfully for %d x %d image."%(num, num)) print("Yappi Profiling Summary") print("=======================") print() print("Repeat Frequency:", repeat_freq) print() print("### Initalising RBFInterpolator\n") print(tabulate(results_init, headers=['Number Of Data Points', 'Total Time (s)', 'Time/Call (s)', 'Total Memory Usage (bytes)'], tablefmt='github'), end="\n\n") print("### Evaluating RBFInterpolator\n") print(tabulate(results_eval, headers=['Number Of Data Points', 'Total Time (s)', 'Time/Call (s)', 'Total Memory Usage (bytes)'], tablefmt='github'))<file_sep>import numpy as np import pythran, cProfile, pstats import scipy, sys from scipy.interpolate import RBFInterpolator from tabulate import tabulate np.random.seed(0) print("Pythran Version: ", pythran.__version__) print("Scipy Version: ", scipy.__version__) print("NumPy Version: ", np.__version__) results_init = [] results_eval = [] flags = '_'.join(sys.argv[1:]) repeat_freq = 10 num_points = [40, 50, 60, 70, 80, 90] for num in num_points: result_init = [] result_eval = [] x = np.linspace(0, 1, num) y = x[:, None] image = x + y print(image.shape) # Destroy some values mask = np.random.random(image.shape) > 0.7 image[mask] = np.nan valid_mask = ~np.isnan(image) coords = np.array(np.nonzero(valid_mask)).T values = image[valid_mask] N = coords.shape[0] result_init.append(N) result_eval.append(N) pr_init = cProfile.Profile() pr_init.enable() for _ in range(repeat_freq): it = RBFInterpolator(coords, values) pr_init.disable() if len(flags) > 0: file_name_prefix = 'results/cProfile_' + flags + '_' else: file_name_prefix = 'results/cProfile_' init_stats = pstats.Stats(pr_init) total_time = init_stats.get_stats_profile().total_tt result_init.append(total_time) result_init.append(total_time/repeat_freq) pr_init.dump_stats(file_name_prefix + str(coords.shape[0]) + '_init') pr_init = cProfile.Profile() pr_init.enable() for _ in range(repeat_freq): filled = it(list(np.ndindex(image.shape))).reshape(image.shape) pr_init.disable() eval_stats = pstats.Stats(pr_init) total_time = eval_stats.get_stats_profile().total_tt result_eval.append(total_time) result_eval.append(total_time/repeat_freq) pr_init.dump_stats(file_name_prefix + str(coords.shape[0]) + '_evaluate') del x, y, image, it, filled results_init.append(result_init) results_eval.append(result_eval) print("Completed Successfully for %d x %d image."%(num, num)) print("cProfile Profiling Summary") print("=======================") print() print("Repeat Frequency:", repeat_freq) print() print("### Initalising RBFInterpolator\n") print(tabulate(results_init, headers=['Number Of Data Points', 'Total Time (s)', 'Time/Call (s)'], tablefmt='github'), end="\n\n") print("### Evaluating RBFInterpolator\n") print(tabulate(results_eval, headers=['Number Of Data Points', 'Total Time (s)', 'Time/Call (s)'], tablefmt='github'))
84b06f8106e300e79884ef3114f32b1f10848765
[ "Markdown", "Python" ]
4
Python
Quansight-Labs/rbfi-benchmark
ac8d7714948eb261dc7ebd13aa3bdd7dbc5dbf8a
2a0237dba7a07692133143530fda4cce9e14db47
refs/heads/master
<repo_name>jn-aman/minurl<file_sep>/README.md # URL shortener Check out the deployed version [here](http://komodo.us)! ## Description This app offers reliable URL shortening as well as some random facts and photos of Komodo dragons. This feature is a simple way to make it stand out in the crowded world of URL shorteners. More seriously, I simply chose this theme as I spent almost 2 years on a boat in the Komodo National Park in Indonesia and I kind of miss it! It's very simple to use. Just paste your link in the form on the home page and submit. You will be redirected to a result page with your shortened link, an image of a Komodo dragon as well as a fact about this giant reptile. # Demo ![komodo.us demo GIF](http://g.recordit.co/BFBEMvnlrm.gif) ## Technology used This app is built with Rails 5.0.0.beta3 and Ruby 2.3 on the backend. The databse is Postgresql. The templating language chosen is SLIM, which I find much more concise than the default ERB. This appliation uses javacript to auto select the short URL generated in order to make copying and pasting it more convenient. ## Challenges Generating the short_url token was what I found tricky. Read more about it on [my blog](http://noestauffert.com/blog/the-challenges-i-faced-building-a-simple-url-shortener-using-rails-5). ## Things to improve I am still not satisfied with my #generate_short_url method. I need to find a way around the possible infinite loop. <file_sep>/old_posql/Gemfile source 'https://rubygems.org' ruby '2.4.0' gem 'rails', '5.0.7' gem 'puma' gem 'pg' gem 'figaro' gem 'redis' gem 'listen' gem 'slim' gem 'sass-rails' gem 'jquery-rails' gem 'uglifier' gem 'bootstrap-sass' gem 'font-awesome-sass' gem 'simple_form', github: 'plataformatec/simple_form' gem 'autoprefixer-rails' <file_sep>/old_posql/app 2/assets/javascripts/urls.js // Place all the behaviors and hooks related to the matching controller here. // All this logic will automatically be available in application.js. $(".urls.shortened").ready(function() { $('#short-url').popover('show'); $('body').click(function(){ $('#short-url').popover('hide') }); var range = document.createRange(); var selection = window.getSelection(); range.selectNodeContents(document.getElementById('short-url')); selection.removeAllRanges(); selection.addRange(range); }); $(".urls.index").ready(function() { $("#url_original_url").attr('size', $("#url_original_url").attr('placeholder').length); });
c7a0b4d001d2048701e0079b1e8c0d59879c5150
[ "Markdown", "JavaScript", "Ruby" ]
3
Markdown
jn-aman/minurl
43ac0202df8f8b1f251a9af1a6e5aafaa3263110
6bff14a41c856e6327e00a4d6a258f4cae60d6f6
refs/heads/master
<file_sep># PhDThesis PhD Thesis in LaTeX This is the readme file for the PhD Thesis. It follows a template from Overleaf. <file_sep>#!/bin/bash mainpdf="main.pdf" outpdf=$2 exec `pdftk $mainpdf cat $1 output $2` echo "pdf file $2 extracted"
b38168fa2c4236098ec62f8ab2d955dc13d7d113
[ "Markdown", "Shell" ]
2
Markdown
santiagocasas/PhDThesis
f6ecef3c1816772e181a8a51c265476f2f1f6d0d
1cf2614cfa8bb647cf4cc91a33b4e588f65924cf
refs/heads/master
<file_sep>这是java单例的设计模式的Demo 包含:饿汉式,懒汉式,线程同步式,静态内部类式,枚举式 <file_sep>package com.tronsis.singleton; /** * @author <EMAIL> * @date 2016/6/23 17:47 * 懒汉式同步 双重校验锁 */ public class SingletonSynchrony { private static SingletonSynchrony instance = null; private SingletonSynchrony(){} public static SingletonSynchrony getInstance(){ if (instance==null){ synchronized (SingletonSynchrony.class){ if (instance == null){ instance = new SingletonSynchrony(); } } } return instance; } } <file_sep>package com.tronsis.singleton; /** * @author <EMAIL> * @date 2016/6/23 18:09 * 枚举 线程安全 */ public enum SingletonEnum { //定义一个枚举的元素,它就是Singleton的一个实例 instance; public void doSomething() { //do something } }
b5f5b3d8efba871a994cb6cf9fb12f67a8bc1925
[ "Java", "Text" ]
3
Text
scofieldwenwen/DesignPatternSingleton
cbcbf0b0ebe85218b8d9c894a41ac6e23792275e
abe7f2937018d853fa4aa2e7bfcfb9f7714606ad
refs/heads/master
<file_sep><?php $conn = mysqli_connect('localhost','root','','desarrollatec'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <html lang="es"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Lista de Materias Cursadas</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/styles.css"> </head> <body> <div class="card"> <div class="card-header"> <h2 class="mb-0">Lista de Materias Cursadas</h2> </div> <div class="card-body"> <p class="card-text">En este apartado podrás observar las materias de este semestre</p> </div> </div> <div class="table-responsive table-bordered"> <table class="table table-bordered"> <thead> <tr> <th>Materias</th> <th>Nombre</th> <th>Calificacion </th> </tr> </thead> <?php $SQL = "SELECT cat_alumnos.Nombre as nombre_alumno,cat_alumnos.Apellido, cat_materias.Nombre, cat_alumnos_has_materia.Calificacion from cat_alumnos_has_materia INNER JOIN cat_alumnos on cat_alumnos.Cve_Alumnos = cat_alumnos_has_materia.Cve_Alumno INNER JOIN cat_materias on cat_alumnos_has_materia.Cve_Materia = cat_materias.Cve_Materia"; $result = mysqli_query($conn,$SQL); while($mostrar=mysqli_fetch_array($result)){ ?> <tbody> <tr> <td><?php echo $mostrar['nombre_alumno'] ?></td> <td><?php echo $mostrar['Nombre'] ?></td> <td><?php echo $mostrar['Calificacion'] ?></td> </tr> </tbody> <?php } ?> </table> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script> </body> </html><file_sep>-- phpMyAdmin SQL Dump -- version 4.8.5 -- https://www.phpmyadmin.net/ -- -- Servidor: 127.0.0.1 -- Tiempo de generación: 29-05-2019 a las 21:07:36 -- Versión del servidor: 10.1.40-MariaDB -- Versión de PHP: 7.3.5 SET SQL_MODE = "NO_AUTO_VALUE_ON_ZERO"; SET AUTOCOMMIT = 0; START TRANSACTION; /*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */; /*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */; /*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */; /*!40101 SET NAMES utf8mb4 */; -- -- Base de datos: `desarrollatec` -- -- -------------------------------------------------------- SET time_zone = "-05:00"; drop database if exists desarrollatec; create database desarrollatec; use desarrollatec; CREATE TABLE `accessos_rol` ( `Modulo_URL` int(11) NOT NULL, `Cve_Rol` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cat_alumnos` -- CREATE TABLE `cat_alumnos` ( `Cve_Alumnos` int(11) NOT NULL, `Nombre` varchar(45) DEFAULT NULL, `Apellido` varchar(45) DEFAULT NULL, `Matricula` varchar(45) DEFAULT NULL, `Cve_Semestre` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `cat_alumnos` -- INSERT INTO `cat_alumnos` (`Cve_Alumnos`, `Nombre`, `Apellido`, `Matricula`, `Cve_Semestre`) VALUES (1, 'Juan', 'Requena', '15300963', 1), (2, 'Cristo', 'Lopez', '15300986', 1); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cat_alumnos_has_materia` -- CREATE TABLE `cat_alumnos_has_materia` ( `Cve_Alumno` int(11) NOT NULL, `Cve_Materia` int(11) NOT NULL, `Cve_Semestre` int(11) NOT NULL, `Calificacion` varchar(50) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1; -- -- Volcado de datos para la tabla `cat_alumnos_has_materia` -- INSERT INTO `cat_alumnos_has_materia` (`Cve_Alumno`, `Cve_Materia`, `Cve_Semestre`, `Calificacion`) VALUES (1, 11, 1, '6'), (1, 1, 1, '7'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cat_materias` -- CREATE TABLE `cat_materias` ( `Cve_Materia` int(11) NOT NULL, `Nombre` varchar(45) DEFAULT NULL, `Cve_Semestre` int(11) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `cat_materias` -- INSERT INTO `cat_materias` (`Cve_Materia`, `Nombre`, `Cve_Semestre`) VALUES (1, 'Calculo Diferencial', 1), (2, 'Fundamentos de Programación', 1), (3, 'Taller de Etica', 1), (4, 'Matematicas Discretas', 1), (5, 'Taller de Administracion', 1), (6, 'Fundamentos de Investigacion', 1), (7, 'Calculo Integral', 2), (8, 'Programacion Orientada a Objetos', 2), (9, 'Contabilidad Financiera', 2), (10, 'Quimica', 2), (11, 'Algebra Lineal', 2), (12, 'Probabilidad y Estadistica', 2); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cat_semestre` -- CREATE TABLE `cat_semestre` ( `Cve_Semestre` int(11) NOT NULL, `Semestre` varchar(45) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Volcado de datos para la tabla `cat_semestre` -- INSERT INTO `cat_semestre` (`Cve_Semestre`, `Semestre`) VALUES (1, 'Primer semestre'), (2, 'Segundo semestre'); -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cat_usuarios` -- CREATE TABLE `cat_usuarios` ( `Cve_Usuarios` int(11) NOT NULL, `Nombre` varchar(45) DEFAULT NULL, `Nickname` varchar(45) DEFAULT NULL, `Pass` varchar(45) DEFAULT NULL, `Cve_Rol` varchar(10) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -------------------------------------------------------- -- -- Estructura de tabla para la tabla `cat_usuarios_rol` -- CREATE TABLE `cat_usuarios_rol` ( `Cve_Rol` varchar(10) NOT NULL, `Cve_Acceso` varchar(45) DEFAULT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Índices para tablas volcadas -- -- -- Indices de la tabla `accessos_rol` -- ALTER TABLE `accessos_rol` ADD PRIMARY KEY (`Modulo_URL`,`Cve_Rol`), ADD KEY `fk_ACCESSOS_ROL_CAT_USUARIOS_ROL1_idx` (`Cve_Rol`); -- -- Indices de la tabla `cat_alumnos` -- ALTER TABLE `cat_alumnos` ADD PRIMARY KEY (`Cve_Alumnos`,`Cve_Semestre`), ADD UNIQUE KEY `Cve_Usuarios_UNIQUE` (`Cve_Alumnos`), ADD KEY `fk_CAT_ALUMNOS_CAT_SEMESTRE1_idx` (`Cve_Semestre`); -- -- Indices de la tabla `cat_alumnos_has_materia` -- ALTER TABLE `cat_alumnos_has_materia` ADD KEY `fk_CAT_ALUMNOS_HAS_MATERIA` (`Cve_Alumno`), ADD KEY `fk_CAT_ALUMNOS_CAT_MATERIA` (`Cve_Materia`), ADD KEY `fk_CAT_ALUMNOS_HAS_SEMESTRE` (`Cve_Semestre`); -- -- Indices de la tabla `cat_materias` -- ALTER TABLE `cat_materias` ADD PRIMARY KEY (`Cve_Materia`,`Cve_Semestre`), ADD UNIQUE KEY `Cve_Materia_UNIQUE` (`Cve_Materia`), ADD KEY `fk_CAT_MATERIAS_CAT_SEMESTRE1_idx` (`Cve_Semestre`); -- -- Indices de la tabla `cat_semestre` -- ALTER TABLE `cat_semestre` ADD PRIMARY KEY (`Cve_Semestre`); -- -- Indices de la tabla `cat_usuarios` -- ALTER TABLE `cat_usuarios` ADD PRIMARY KEY (`Cve_Usuarios`,`Cve_Rol`), ADD KEY `fk_CAT_USUARIOS_CAT_USUARIOS_ROL_idx` (`Cve_Rol`); -- -- Indices de la tabla `cat_usuarios_rol` -- ALTER TABLE `cat_usuarios_rol` ADD PRIMARY KEY (`Cve_Rol`); -- -- AUTO_INCREMENT de las tablas volcadas -- -- -- AUTO_INCREMENT de la tabla `cat_alumnos` -- ALTER TABLE `cat_alumnos` MODIFY `Cve_Alumnos` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3; -- -- AUTO_INCREMENT de la tabla `cat_materias` -- ALTER TABLE `cat_materias` MODIFY `Cve_Materia` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=13; -- -- Restricciones para tablas volcadas -- -- -- Filtros para la tabla `accessos_rol` -- ALTER TABLE `accessos_rol` ADD CONSTRAINT `fk_ACCESSOS_ROL_CAT_USUARIOS_ROL1` FOREIGN KEY (`Cve_Rol`) REFERENCES `cat_usuarios_rol` (`Cve_Rol`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `cat_alumnos` -- ALTER TABLE `cat_alumnos` ADD CONSTRAINT `fk_CAT_ALUMNOS_CAT_SEMESTRE1` FOREIGN KEY (`Cve_Semestre`) REFERENCES `cat_semestre` (`Cve_Semestre`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `cat_alumnos_has_materia` -- ALTER TABLE `cat_alumnos_has_materia` ADD CONSTRAINT `fk_CAT_ALUMNOS_CAT_MATERIA` FOREIGN KEY (`Cve_Materia`) REFERENCES `cat_materias` (`Cve_Materia`), ADD CONSTRAINT `fk_CAT_ALUMNOS_HAS_MATERIA` FOREIGN KEY (`Cve_Alumno`) REFERENCES `cat_alumnos` (`Cve_Alumnos`), ADD CONSTRAINT `fk_CAT_ALUMNOS_HAS_SEMESTRE` FOREIGN KEY (`Cve_Semestre`) REFERENCES `cat_semestre` (`Cve_Semestre`); -- -- Filtros para la tabla `cat_materias` -- ALTER TABLE `cat_materias` ADD CONSTRAINT `fk_CAT_MATERIAS_CAT_SEMESTRE1` FOREIGN KEY (`Cve_Semestre`) REFERENCES `cat_semestre` (`Cve_Semestre`) ON DELETE NO ACTION ON UPDATE NO ACTION; -- -- Filtros para la tabla `cat_usuarios` -- ALTER TABLE `cat_usuarios` ADD CONSTRAINT `fk_CAT_USUARIOS_CAT_USUARIOS_ROL` FOREIGN KEY (`Cve_Rol`) REFERENCES `cat_usuarios_rol` (`Cve_Rol`) ON DELETE NO ACTION ON UPDATE NO ACTION; COMMIT;<file_sep><?php $conn = mysqli_connect('localhost','root','','desarrollatec'); ?> <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <html lang="es"> <meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no"> <title>Selección de materias por semestre</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css"> <link rel="stylesheet" href="assets/css/styles.css"> </head> <body> <div class="card"> <div class="card-header"> <h2 class="mb-0">Selección de materias por semestre</h2> </div> <div class="card-body"> <p class="card-text">En este apartado se seleccionara las materias que se llevarán a cabo por semestre</p> </div> </div> <div class="table-responsive table-bordered"> <form method="POST" action="core/insert.php"> <table class="table table-bordered"> <thead> <tr> <th>Materias</th> <th>Semestre</th> <th>Agregar</th> </tr> </thead> <?php $SQL = "SELECT cat_materias.Nombre, cat_semestre.Semestre FROM cat_materias INNER JOIN cat_semestre on cat_materias.Cve_Semestre = cat_semestre.Cve_Semestre where cat_materias.Cve_Semestre = 1"; $result = mysqli_query($conn,$SQL); while($mostrar=mysqli_fetch_array($result)){ ?> <tbody> <tr> <td><?php echo $mostrar['Nombre'] ?></td> <td><?php echo $mostrar['Semestre'] ?></td> <td><input type="checkbox" name="chkl[ ]" value=<?php echo $mostrar['Nombre'] ?>> </td> </tr> </tbody> <?php } ?> </table> <center> <button type='submit' class="btn btn-primary" name="sub">Agregar</button> </center> </form> ) </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/js/bootstrap.bundle.min.js"></script> </body> </html><file_sep><?php include("conexion.php"); $Nombre= $_POST['Nombre']; $Apellido_P= $_POST['ApellidoP']; $Apellido_M=$_POST['ApellidoM']; $Fecha_N=$_POST['FN']; $Matricula=$_POST['Matricula']; $Correo=$_POST['Correo']; $Telefono=$_POST['Telefono']; $query="INSERT INTO alumno(Nombre,Apellido_Paterno,Apellido_Materno,Fecha_Nacimiento,Matricula,Correo,Telefono) VALUES('$Nombre','$Apellido_P','$Apellido_M','$Fecha_N','$Matricula','$Correo','$Telefono')"; $resultado= $conn->query($query); if ($resultado) { header('location:Consulta.php'); } else{ echo "Registro Invalido"; } ?>
fb87df0ad80ac150400bddfe3f2a732f8debb9ab
[ "SQL", "PHP" ]
4
PHP
ArkhamBoy14/ProgressTecPruebas
231aa6f482e47c4a68bed399fc9828bfd67fa2f6
87721e991a8bf4eea605147bb85980374feae4b1
refs/heads/master
<file_sep>package com.example.corvus.addressbook; import android.app.ListActivity; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.AsyncTask; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.CursorAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; public class viewContacts extends ListActivity { public static final String ROW_ID = "row_id"; //intent extra key private ListView contactListView; private CursorAdapter contactAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); contactListView = getListView(); contactListView.setOnItemClickListener(viewContactListener); String[] from = new String[] { "name" }; int[] to = new int[] { R.id.contactTextView }; contactAdapter = new SimpleCursorAdapter( viewContacts.this, R.layout.contact_list_item, null, from, to); // CursorAdapter contactAdapter = new SimpleCursorAdapter( // viewContacts.this, R.layout.content_view_contacts, null, from, to); setListAdapter(contactAdapter); // FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); // fab.setOnClickListener(new View.OnClickListener() { // @Override // public void onClick(View view) { // // startActivity(new Intent(viewContacts.this, addContacts.class)); // // } // }); } @Override protected void onResume(){ super.onResume(); new GetContactsTask().execute((Object[]) null); } @Override protected void onStop(){ try { Cursor cursor = contactAdapter.getCursor(); if (cursor != null) { cursor.deactivate(); } } catch (Exception e) {} try { contactAdapter.changeCursor(null); } catch (Exception e) {} super.onStop(); } private class GetContactsTask extends AsyncTask<Object, Object, Cursor>{ DatabaseConnector databaseConnector = new DatabaseConnector(viewContacts.this); // @Override protected Cursor doInBackground(Object... params){ databaseConnector.open(); return databaseConnector.getAllContacts(); } @Override protected void onPostExecute(Cursor result){ try { contactAdapter.changeCursor(result); } catch (Exception e) {} databaseConnector.close(); } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); // inflater.inflate(R.menu.menu_view_contacts, menu); getMenuInflater().inflate(R.menu.menu_view_contacts, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); Intent addNewContact = new Intent(viewContacts.this, addContacts.class); startActivity(addNewContact); //noinspection SimplifiableIfStatement if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } OnItemClickListener viewContactListener = new OnItemClickListener(){ @Override public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3){ Intent openContact = new Intent(viewContacts.this, openContacts.class); openContact.putExtra(ROW_ID, arg3); startActivity(openContact); } }; } <file_sep>package com.example.corvus.addressbook; import android.app.AlertDialog; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; public class addContacts extends AppCompatActivity { private long rowID; private EditText nameEditText; private EditText phoneEditText; private EditText emailEditText; private EditText streetEditText; private EditText cityEditText; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_add_contacts); Button cancel = (Button) findViewById(R.id.button4); Button save = (Button) findViewById(R.id.button); nameEditText = (EditText) findViewById(R.id.addname); phoneEditText = (EditText) findViewById(R.id.addnumber); emailEditText = (EditText) findViewById(R.id.addemail); streetEditText = (EditText) findViewById(R.id.addstreet); cityEditText = (EditText) findViewById(R.id.addcity); Bundle extras = getIntent().getExtras(); if (extras != null){ rowID = extras.getLong("row_id"); nameEditText.setText(extras.getString("name")); phoneEditText.setText(extras.getString("phone")); emailEditText.setText(extras.getString("email")); streetEditText.setText(extras.getString("street")); cityEditText.setText(extras.getString("city")); } Button saveContactButton = (Button) findViewById(R.id.button); saveContactButton.setOnClickListener(saveContactButtonClicked); cancel.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startActivity(new Intent(addContacts.this, viewContacts.class)); } }); } OnClickListener saveContactButtonClicked = new OnClickListener(){ @Override public void onClick(View v){ if (nameEditText.getText().length() != 0){ AsyncTask<Object, Object, Object> saveContactTask = new AsyncTask<Object, Object, Object>() { @Override protected Object doInBackground(Object... params){ saveContact(); return null; } @Override protected void onPostExecute(Object result){ finish(); } }; saveContactTask.execute((Object[]) null); } else{ AlertDialog.Builder builder = new AlertDialog.Builder(addContacts.this); builder.setTitle("Error"); builder.setMessage("An error has occured"); builder.setPositiveButton("Okay", null); builder.show(); } } }; private void saveContact(){ DatabaseConnector databaseConnector = new DatabaseConnector(this); if (getIntent().getExtras() == null){ System.out.println("OREWA" + nameEditText.getText()); System.out.println("OREWA" + nameEditText.getText().toString()); System.out.println("OREWA" + String.valueOf(nameEditText.getText())); databaseConnector.addContacts( //marker insertContact originally nameEditText.getText().toString(), phoneEditText.getText().toString(), emailEditText.getText().toString(), streetEditText.getText().toString(), cityEditText.getText().toString()); } else { databaseConnector.updateContact(rowID, nameEditText.getText().toString(), phoneEditText.getText().toString(), emailEditText.getText().toString(), streetEditText.getText().toString(), cityEditText.getText().toString()); } } }
ff5fff9612841d51cd7511bbb04337e684989182
[ "Java" ]
2
Java
decorvus/Addressbook
3bc1fad60ff5ce10c9b877005d615551fd0b3a4e
421e6543a2f789ad20a84c7338583cca84a9b1f1
refs/heads/master
<repo_name>minifyre/Colorblindly<file_sep>/script/colorblindListener.js //Listeners for colorblind filter buttons //Injects a javascript file on click event, the js file applies a filter to simulate colorblindness /** * get the selected filter on popup open */ window.onload = function () { chrome.storage.local.get(['key'], function (result) { try { document.getElementById(result.key).click(); } catch (e) { console.log(e) } }); } /** * Sets the selected filter in storage * @param {String} value the selected input */ function setSelected(value) { try { chrome.storage.local.set({ 'key': value }, function () { document.getElementById(value).checked = true; }); } catch{ } } function injectFilter(fileName) { chrome.tabs.executeScript({ file: fileName }); } //normal document.getElementById("radio-0").addEventListener("click", function () { setSelected('radio-0'); injectFilter('filters/normal.js'); }); //achromatomaly document.getElementById("radio-1").addEventListener("click", function () { setSelected('radio-1'); injectFilter('filters/achromatomaly.js'); }); //achromatopsia document.getElementById("radio-2").addEventListener("click", function () { setSelected('radio-2'); injectFilter('filters/achromatopsia.js'); }); //deuteranomaly document.getElementById("radio-3").addEventListener("click", function () { setSelected('radio-3'); injectFilter('filters/deuteranomaly.js'); }); //deuteranopia document.getElementById("radio-4").addEventListener("click", function () { setSelected('radio-4'); injectFilter('filters/deuteranopia.js'); }); //protanomaly document.getElementById("radio-5").addEventListener("click", function () { setSelected('radio-5'); injectFilter('filters/protanomaly.js'); }); //protanopia document.getElementById("radio-6").addEventListener("click", function () { setSelected('radio-6'); injectFilter('filters/protanopia.js'); }); //tritanomaly document.getElementById("radio-7").addEventListener("click", function () { setSelected('radio-7'); injectFilter('filters/tritanomaly.js'); }); //tritanopia document.getElementById("radio-8").addEventListener("click", function () { setSelected('radio-8'); injectFilter('filters/tritanopia.js'); });
3158e609c3a49e9681d0251d8b395f1638eed8a6
[ "JavaScript" ]
1
JavaScript
minifyre/Colorblindly
7c8c4c813022298c7a2e77675d590a714ada408d
2e2caad01c859d03999cae04566bdfb0cd2f8a09
refs/heads/master
<file_sep>import json from django.utils import timezone from django.http import JsonResponse from django.http import HttpResponse from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt from oauth2_provider.models import AccessToken from django.conf import settings from deploytodotaskerapp import Checksum from django.utils.translation import get_language from deploytodotaskerapp.models import Registration, Meal, Order, OrderDetails, Driver,PaytmHistory from deploytodotaskerapp.serializers import RegistrationSerializer, \ MealSerializer, \ OrderSerializer #import stripe #from deploytodotasker.settings import STRIPE_API_KEY ############## # CUSTOMERS ############## def customer_get_registrations(request): registrations = RegistrationSerializer( Registration.objects.all().order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"registrations": registrations}) def customer_get_meals(request, registration_id): meals = MealSerializer( Meal.objects.filter(registration_id = registration_id).order_by("-id"), many = True, context = {"request": request} ).data return JsonResponse({"meals": meals}) @csrf_exempt def customer_add_order(request): """ params: access_token registration_id address order_details (json format), example: [{"meal_id": 1, "quantity": 2},{"meal_id": 2, "quantity": 3}] stripe_token return: {"status": "success"} """ if request.method == "POST": # Get token flag="success" #access_token = AccessToken.objects.get(token = request.POST.get("access_token"),expires__gt = timezone.now()) # Get profile #customer = access_token.user.customer # Check whether customer has any order that is not delivered #if Order.objects.filter(customer = customer).exclude(status = Order.DELIVERED): #flag='Your last order must be completed.' #JsonResponse({"status": "failed", "error": "Your last order must be completed."}) # Check Address #if not request.POST["address"]: #flag="Address is required" # return JsonResponse({"status": "failed", "error": "Address is required."}) # Get Order Details order_details = json.loads(request.POST["order_details"]) order_total = 0 for meal in order_details: order_total += Meal.objects.get(id = meal["meal_id"]).price * meal["quantity"] MERCHANT_KEY = settings.PAYTM_MERCHANT_KEY MERCHANT_ID = settings.PAYTM_MERCHANT_ID #get_lang = "/" + get_language() if get_language() else '' # CALLBACK_URL = settings.HOST_URL + get_lang + settings.PAYTM_CALLBACK_URL # Generating unique temporary ids order_id = Checksum.__id_generator__() if len(order_details) >= 0: bill_amount = str(order_total) #if bill_amount: data_dict = { 'MERCHANT_ID':MERCHANT_ID, 'ORDER_ID':order_id, 'TXN_AMOUNT': bill_amount, 'CUST_ID':'<EMAIL>', #'INDUSTRY_TYPE_ID':'Retail', # 'WEBSITE': settings.PAYTM_WEBSITE, #'CHANNEL_ID':'WEB', 'payt_STATUS':flag #'CALLBACK_URL':CALLBACK_URL, } param_dict = data_dict param_dict['CHECKSUMHASH'] = Checksum.generate_checksum(data_dict, MERCHANT_KEY) #return render(request,"response.html",{"paytm":param_dict}) return JsonResponse(param_dict) else: return JsonResponse({'payt_STATUS':'error'}) #return HttpResponse("{% for key,value in paytm.items %} {{key}} = {{value}} <br>{% endfor %}")#JsonResponse({"payt_STATUS": "failed"}) @csrf_exempt def response(request): if request.method == "POST": MERCHANT_KEY = settings.PAYTM_MERCHANT_KEY data_dict = {} for key in request.POST: data_dict[key] = request.POST[key] verify = Checksum.verify_checksum(data_dict, MERCHANT_KEY, data_dict['CHECKSUMHASH']) if verify: PaytmHistory.objects.create(user=request.user, **data_dict) return HttpResponse("checksum verify successful")#render(request,"response.html",{"paytm":data_dict}) else: return HttpResponse("checksum verify failed") return HttpResponse(status=200) def customer_get_latest_order(request): access_token = AccessToken.objects.get(token = request.GET.get("access_token"), expires__gt = timezone.now()) customer = access_token.user.customer order = OrderSerializer(Order.objects.filter(customer = customer).last()).data return JsonResponse({"order": order}) def customer_driver_location(request): access_token = AccessToken.objects.get(token = request.GET.get("access_token"), expires__gt = timezone.now()) customer = access_token.user.customer # Get driver's location related to this customer's current order. # CHANGED DOUBT ONTHEWAY FOR LOCATION VIDEO LECTURE 53 current_order = Order.objects.filter(customer = customer, status = Order.ONTHEWAY).last() location = current_order.driver.location return JsonResponse({"location": location}) ############## # Registration ############## def registration_order_notification(request, last_request_time): print(request.user.registration) notification = Order.objects.filter(created_at__gt = last_request_time).count() return JsonResponse({"notification": notification}) ############## # DRIVERS ############## def driver_get_ready_orders(request): orders = OrderSerializer( Order.objects.filter(status = Order.READY, driver = None).order_by("-id"), many = True ).data return JsonResponse({"orders": orders}) @csrf_exempt # POST # params: access_token, order_id def driver_pick_order(request): if request.method == "POST": # Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) # Get Driver driver = access_token.user.driver # Check if driver can only pick up one order at the same time if Order.objects.filter(driver = driver).exclude(status = Order.ONTHEWAY): return JsonResponse({"status": "failed", "error": "You can only pick one order at the same time."}) try: order = Order.objects.get( id = request.POST["order_id"], driver = None, status = Order.READY ) order.driver = driver order.status = Order.ONTHEWAY order.picked_at = timezone.now() order.save() return JsonResponse({"status": "success"}) except Order.DoesNotExist: return JsonResponse({"status": "failed", "error": "This order has been picked up by another."}) return JsonResponse({}) # GET params: access_token def driver_get_latest_order(request): # Get token access_token = AccessToken.objects.get(token = request.GET.get("access_token"), expires__gt = timezone.now()) driver = access_token.user.driver order = OrderSerializer( Order.objects.filter(driver = driver).order_by("picked_at").last() ).data return JsonResponse({"order": order}) # POST params: access_token, order_id @csrf_exempt def driver_complete_order(request): # Get token access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) driver = access_token.user.driver order = Order.objects.get(id = request.POST["order_id"], driver = driver) order.status = Order.DELIVERED order.save() return JsonResponse({"status": "success"}) # GET params: access_token def driver_get_revenue(request): access_token = AccessToken.objects.get(token = request.GET.get("access_token"), expires__gt = timezone.now()) driver = access_token.user.driver from datetime import timedelta revenue = {} today = timezone.now() current_weekdays = [today + timedelta(days = i) for i in range(0 - today.weekday(), 7 - today.weekday())] for day in current_weekdays: orders = Order.objects.filter( driver = driver, status = Order.DELIVERED, created_at__year = day.year, created_at__month = day.month, created_at__day = day.day ) revenue[day.strftime("%a")] = sum(order.total for order in orders) return JsonResponse({"revenue": revenue}) # POST - params: access_token, "lat,lng" @csrf_exempt def driver_update_location(request): if request.method == "POST": access_token = AccessToken.objects.get(token = request.POST.get("access_token"), expires__gt = timezone.now()) driver = access_token.user.driver # Set location string => database driver.location = request.POST["location"] driver.save() return JsonResponse({"status": "success"})
32f0a41f6ef07e4d251fb860936737348b5d11a4
[ "Python" ]
1
Python
ashishkharcheiuforks/btre_project
7a9b77345a618f5aa526110c82fb50911d841080
3324a57c9d3044d548973af8de40324288791012
refs/heads/master
<file_sep>//============================================================================ // Name : managementsystem.cpp // Author : // Version : // Copyright : Your copyright notice // Description : Hello World in C++, Ansi-style //============================================================================ #include <iostream> #include<string> using namespace std; class student { public: //data members of class student string name,branch; int year,sem; float percentage; //member function of class student void add_data(); void displaydata(); void filterdata(); }; void student:: add_data() { //Taking the details from the user cout<<"MANAGEMENT SYSTEM"; cout<<endl; cout<<"FILL OUT THE FOLLOWING DETAILS"<<endl; cout<<"Enter the name"<<endl; getline(cin,name); cout<<"Enter Branch"<<endl; getline(cin,branch); cout<<"Enter Year"<<endl; cin>>year; cout<<"Enter semester"<<endl; cin>>sem; cout<<"Previous Year Score in %"; cin>>percentage; } void student::displaydata() { //Function to display the data cout<<"THE STUDENTS RECORD"<<endl; cout<<"Record of student"<<name<<endl; cout<<"Name="<<name<<endl; cout<<"Branch="<<branch<<endl; cout<<"Year="<<year<<endl; cout<<"Semester="<<sem<<endl; cout<<"Percentage="<<percentage<<endl; } void student::filterdata() { float percentage_req; cout<<"Enter the required percentage"; cin>>percentage_req; //Filtering the data based on the criteria given by the user if(percentage>=percentage_req) { cout<<"Name="<<name<<endl; cout<<"Branch="<<branch<<endl; cout<<"Year="<<year<<endl; cout<<"Semester="<<sem<<endl; cout<<"Percentage="<<percentage<<endl; } } int main() {student obj1; obj1.add_data(); obj1.displaydata(); obj1.filterdata(); return 0; }
aca8485d6db68318c5d1a6cad965ed19c2c57213
[ "C++" ]
1
C++
preetisha/src
06d208be1100497d97b2286cf3b413bb739c2143
b60650c3736b94ef5823ac0ad1651c1255a4e15c
refs/heads/master
<repo_name>Rex-0x7CB/Memories_From_Childhood<file_sep>/Banking_App/README.md # Banking_App Just found this code from my childhood. A simple, CLI based, banking simulation application I developed as a kid. I was challenged by my computer teacher to develop an app 'that would work on our school LAN'. I didn't know anything about networking, had never heard the term 'Socket Programming' and so I had a tough time and many sleepless nights creating this 2000 liner code. But, when I successfully sent my first message over the LAN, my instinct was to write a code to chat with my friends in the computer lab over the LAN and I did write it (The other project in this repo). The app has two cool CLI animation effects, one while loading the user's information and the other while viewing the bank balance (if I remember correctly :/ ). The inspiration for the former was the graphics from the game 'Call Of Duty: Modern Warfare' and that for the latter was 'Need For Speed: Most Wanted'. If you've played the game, you'd be able to relate. ;) The application code is written in C++ and uses 2nd version of WinSock library to create raw sockets and to communicate over it. Do not expect to see a neat, clean and moduler code with lots of comments. You can expect perfect indentation though! The file 'SERVER.cpp' is the server and the other file 'CLIENT.cpp' is the client(self explanatory). I didn't implement multi-threading (as my final exams were closing in) and didn't implement any sort of encryption ( as I didn't know what encryption was). wxDevC++ IDE (one of the fork of DevC++project by Bloodshed Software) was used to develop this project. <file_sep>/Chat_App/CHAT_S.cpp #include<iostream> #include<winsock.h> #include<cstdio> #include<cstdlib> #include<string> #include<dos.h> using namespace std; #define NETWORK_ERROR -1 #define NETWORK_OK 0 int WINAPI WinMain(HINSTANCE hinstance,HINSTANCE hprevinstance,LPSTR lp,int n) { WSADATA ws; int nret,i; WSAStartup(0x0101,&ws); SOCKET lsocket; char servername[50],clientname[50]; for(i=0;i<50;i++) { servername[i]=0; clientname[i]=0; } cout<<"Enter Your Name : "; gets(servername); cout<<"\nCreating Socket"; for(int i=0;i<6;i++) { Sleep(500); cout<<"."; } lsocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(lsocket==INVALID_SOCKET) { cout<<"\nCould Not Creat Listening Socket."; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Socket Created"; //Use a SOCKADDR_IN struct to fill addr info SOCKADDR_IN serverinfo; serverinfo.sin_family=AF_INET; serverinfo.sin_addr.s_addr=inet_addr("192.168.0.20"); serverinfo.sin_port=htons(2609); //Bind the socket to our local server addr cout<<"\nBinding Socket"; for(i=0;i<10;i++) { Sleep(500); cout<<"."; } nret=bind(lsocket,(SOCKADDR *)&serverinfo,sizeof(struct sockaddr)); if(nret==SOCKET_ERROR) { cout<<"\nCould Not Bind Listening Socket"; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Socket Bound"; //Make the bound socket listen.Up to 10 ma wait at any one time cout<<"\nPutting Bound Socket to Listening Mode"; for(i=0;i<8;i++) { Sleep(500); cout<<"."; } nret=listen(lsocket,10); if(nret==SOCKET_ERROR) { cout<<"\nCould Not Attain Listen Mode"; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Entered Listening Mode"; //Wait for client cout<<"\nWaiting for Client ......."; SOCKET commsocket; commsocket=accept(lsocket,NULL,NULL); if(commsocket==INVALID_SOCKET) { cout<<"\nCould Not Setup Connection On Request"; WSACleanup(); getchar(); return NETWORK_ERROR; } else { cout<<"\nConnection Setup Successfull\n"; } nret=send(commsocket,servername,50,0); if(nret==SOCKET_ERROR) { cout<<"\nConnection Error. Exiting"; WSACleanup(); getchar(); return NETWORK_ERROR; } nret=recv(commsocket,clientname,50,0); if(nret==SOCKET_ERROR) { cout<<"\nImproper commection.Exiting"; WSACleanup(); getchar(); return NETWORK_ERROR; } char sendbuffer[256]="\nThis is server,reporting on port 2609"; char recvbuffer[256]; while(1) { for(i=0;i<255;i++) { sendbuffer[i]=0; recvbuffer[i]=0; } cout<<"\n"<<servername<<" :"; gets(sendbuffer); if(strcmpi(sendbuffer,"BYE")==0) { cout<<"\n\nSwitching off the chat and exiting"; WSACleanup(); getchar(); break; } else { nret=send(commsocket,sendbuffer,255,0); if(nret==SOCKET_ERROR) { cout<<"\nUnable to send.Please Retry"; WSACleanup(); getchar(); } else { nret=recv(commsocket,recvbuffer,255,0); if(nret==SOCKET_ERROR) { cout<<"\nCould Not Hear Client"; WSACleanup(); getchar(); } else { cout<<"\n"<<clientname<<" :"<<recvbuffer; } } } } cout<<"\n\nThank You For Using PG's Application."; getchar(); return NETWORK_OK; } <file_sep>/Chat_App/README.md # Chat_App Just found this code from my childhood. A simple, CLI based, chat application I developed when I was 15 years old. I was a newbie to the world of programming back then. The application code is written in C++ and uses 2nd version of WinSock library to create raw socket and to send messages over it. The code is poorly written (Of course it is!) with no concept of modularity. The file 'CHAT_S.cpp' is the server and the other file 'CHAT_C.cpp' is the client. I wrote this code as a side project while my true focus was to create a simulated banking application (The other project in same the repo). I didn't implement multi-threading (as my final exams were closing in) and didn't implement any sort of encryption (as I didn't know what encryption was). wxDevC++ IDE (one of the fork of DevC++project by Bloodshed Software) was used to develop this project. <file_sep>/Banking_App/SERVER.cpp #include<iostream> #include<winsock.h> #include<cstdio> #include<cstdlib> #include<string> #include<fstream> #include<dos.h> #include<setjmp.h> #define NETWORK_ERROR -1 #define NETWORK_OK 0 using namespace std; class account { private: char acc_no[50]; //Used for account number to log in char pass[50]; char holder_name[50]; //Name of account holder char email[50]; char address[50]; float money; int active_stat; //If active_stat is 1 then account //is active if active_stat is 0 //then account will be closed public: void del(); void transadd(float); void transred(float); char * ret_acc_no(); void show_details(); int ret_stat(); char * ret_acc_pass(); }; //Global data variable declaration SOCKET commsocket,lsocket; int nret,i; char IP[16]; jmp_buf MAYDAY; int First_Open=1; //Globle function prototype declaration void PG(void); void login(void); void create(void); void logout(void); void transfer(void); int bind_socket(void); void show(void); void unbind_sock(void); int WINAPI WinMain(HINSTANCE hinstance,HINSTANCE hprevinstance,LPSTR lp,int n) //WinMain Function to //initialise the program { int choice=0; PG(); while(1) { setjmp(MAYDAY); //Jump location set lsocket=bind_socket(); while(1) { choice=0; fflush(stdin); cout<<"\nWaiting for the choice to come "; nret=recv(lsocket,(char *)&choice,sizeof(choice),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } switch(choice) { case 1: cout<<"\nChoice:"<<choice; login(); cout<<"\nlogin() ended"; break; case 2: cout<<"\nChoice:"<<choice; create(); cout<<"\ncreate() ended"; break; case 3: cout<<"\nChoice:"<<choice; logout(); break; case 4: cout<<"\nChoice:"<<choice; transfer(); break; default : cout<<"\nCHOICE :"<<choice; cout<<"\nUser has entered wrong choice"; break; } if(choice==6) { unbind_sock(); break; } } } } char * account::ret_acc_pass() //function ti return password //of the user { return pass; } char * account::ret_acc_no() //function to return account //number of the user { return acc_no; } int account::ret_stat() //function to return active //state of user { return active_stat; } void account::transadd(float a) //function to add money to //the account of the user { money=money+a; } void account::transred(float a) //function to deduct money //from the user { money=money-a; } void account :: show_details() //function to show current //details of user { fflush(stdin); cout<<endl; cout<<"\nName Of Account Holder : "<<holder_name; cout<<"\nAccount Number : "<<acc_no; cout<<"\nAssigned E-Mail ID : "<<email; cout<<"\nAssigned Address : "<<address; cout<<"\nBalance Available : "<<money; cout<<"\nActive Stats : "<<active_stat; } void PG() //function to show startup screen { system("CLS"); char start[]={"A PROGRAM BY <NAME>"}; int i=0; cout<<"\n\n\t\t\t\t"; for(i=0;i<=8;i++) { cout<<start[i]; Sleep(50); } Sleep(500); cout<<"\n\n\n\n\t\t\t\t "; for(i;i<=12;i++) { cout<<start[i]; Sleep(50); } cout<<"\n\n\n\n\t\t\t\t "; for(i;i<=19;i++) { cout<<start[i]; Sleep(50); } cout<<"\n\n\n\n\t\t\t "; for(i;i<=33;i++) { cout<<start[i]; Sleep(200); } Sleep(2000); system("CLS"); } void unbind_sock() //function to unbind socket { closesocket(commsocket); closesocket(lsocket); cout<<"\nALL WENT HOLY."; } int bind_socket() //function to bind the socket to //statr communication between //connected computers { WSADATA ws; WSAStartup(0x0101,&ws); cout<<"\nCreating Socket"; for(i=0;i<6;i++) { Sleep(500); cout<<"."; } commsocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(commsocket==INVALID_SOCKET) { cout<<"\nCould Not Create Socket."; WSACleanup(); return NETWORK_ERROR; } else { cout<<"SUCCESSFUL"; } //Use a SOCKADDR_IN struct to fill addr info SOCKADDR_IN serverinfo; serverinfo.sin_family=AF_INET; if(First_Open==1) { for(i=0;i<=15;i++) { IP[i]=0; } cout<<"\nEnter the IP Address of server : "; gets(IP); First_Open=0; } serverinfo.sin_addr.s_addr=inet_addr(IP); //htonl(INADDR_ANY); serverinfo.sin_port=htons(2609); //Bind the socket to our local server addr cout<<"\nBinding Socket"; for(i=0;i<10;i++) { Sleep(500); cout<<"."; } nret=bind(commsocket,(SOCKADDR *)&serverinfo,sizeof(struct sockaddr)); if(nret==SOCKET_ERROR) { cout<<"\nCould Not Bind Listening Socket"; WSACleanup(); return NETWORK_ERROR; } else cout<<"SUCCESSFUL"; //Make the bound socket listen.Up to 10 ma wait at any one time cout<<"\nInitializing Listening Mode"; for(i=0;i<8;i++) { Sleep(500); cout<<"."; } nret=listen(commsocket,10); if(nret==SOCKET_ERROR) { cout<<"\nCould Not Attain Listen Mode"; WSACleanup(); return NETWORK_ERROR; } else cout<<"SUCCESSFULL"; //Wait for client cout<<"\nWaiting for Client ......."; lsocket=accept(commsocket,NULL,NULL); if(lsocket==INVALID_SOCKET) { cout<<"\nCould Not Setup Connection On Request"; WSACleanup(); return NETWORK_ERROR; } else { cout<<"\nConnection Setup Successfull\n"; } Sleep(3000); return lsocket; } void login() //function to make the user loged //in only on provinding authentified //username and password { cout<<"\nReached login()"; fflush(stdin); struct log { char acc_number[50]; char password[50]; }; log u; account a; int result=0; cout<<"\nAbout to receive"; nret=recv(lsocket,(char*)&u,sizeof(u),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } cout<<"\nRecieved..."; cout<<"Acc_no: "<<u.acc_number; cout<<"Password: "<<<PASSWORD>; ifstream f; f.open("BANK.PG"); if(!f) { cout<<"File cannot be opened "; } while(1) { f.read((char*)&a,sizeof(a)); if(strcmp(a.ret_acc_no(),u.acc_number)==0 && strcmp(a.ret_acc_pass(),u.password)==0) { result=1; cout<<"Match found.Details are..."; nret=send(lsocket,(char*)&result,sizeof(result),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } a.show_details(); nret=send(lsocket,(char*)&a,sizeof(a),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } return; } if(f.eof()) break; } result=0; cout<<"\nMatch Not Found."; nret=send(lsocket,(char*)&result,sizeof(result),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } //Now control will return to main(); } void logout() //function to log the user out { account a; // a will receive the information // about the client account which //is sent by cient account b; // b will be used to write the //content of BANK.PG to BANK_TEMP.PG int success=1; // success is send to client to //confirm file data has been //written successfully for reference //of success please see the end of //function showmenu() in client //program nret=recv(lsocket,(char*)&a,sizeof(a),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } a.show_details(); cout<<"\na is received"; ifstream f1; f1.open("BANK.PG",ios::binary); if(!f1) { cout<<"\nReading File cannot be opened"; } else { cout<<"\nReading File opened"; } ofstream f2; f2.open("BANK_TEMP.PG",ios::binary); if(!f2) { cout<<"\nWriting File cannot be opened"; } else { cout<<"\nWriting File opened"; } while(1) { f1.read((char*)&b,sizeof(b)); if(f1.eof()) { cout<<"\nEOF Reached"; break; } else { cout<<"\nFile still left."; } if((strcmp(b.ret_acc_no(),a.ret_acc_no())==0)) { cout<<"\nMatch found.Data skiped."; //if the account no of received //account matches with any account //no of file then the object is not //be written in file because the new //data of the same account in a //will be written at last } else { cout<<"\nCase do not match.Data is written."; f2.write((char*)&b,sizeof(b)); } cout<<"\nCheaking EOF"; } if(a.ret_stat()==1) { f2.write((char*)&a,sizeof(a)); } f1.close(); f2.close(); cout<<"\nFile has been successfully closed down."; remove("BANK.PG"); cout<<"\nBank has been deleted"; rename("BANK_TEMP.PG","BANK.PG"); cout<<"\nBank_temp has been renamed."; nret=send(lsocket,(char*)&success,sizeof(success),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } cout<<"\nLogout() module is now closing."; } void create() //function to create new account //for the user on incoming request { cout<<"\nReached create"; fflush(stdin); account new_acc,temp; int create_stat; ifstream f1; ofstream f2; cout<<"\nAbout to recv"; nret=recv(lsocket,(char*)&new_acc,sizeof(new_acc),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } new_acc.show_details(); f1.open("BANK.PG",ios::binary); if(!f1) { cout<<"\nInput file cannot be opened."; } f2.open("BANK.PG",ios::binary|ios::app); if(!f2) { cout<<"\nOutput file cannot be opened."; } while(1) { f1.read((char*)&temp,sizeof(temp)); { if(strcmp(new_acc.ret_acc_no(),temp.ret_acc_no())==0) { create_stat=0; nret=send(lsocket,(char*)&create_stat,sizeof(create_stat),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } return; } if(f1.eof()) { cout<<"\nFile End Reached"; break; } } } f2.write((char*)&new_acc,sizeof(new_acc)); cout<<"\nAccount Has Been Created."; create_stat=1; nret=send(lsocket,(char*)&create_stat,sizeof(create_stat),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } } void transfer() //function to transfer money from //one user to another user { ifstream f1; ofstream f2; account my,rcvr; int result,condition=0; //Whenever the f1.eof is true //for rcvr,condition will tell //server whether rcvr accno was //found or not and hence it will //decide to send result=0 or result=1 f1.open("BANK.PG",ios::binary); if(!f1) { cout<<"\nReading file cannot be opened."; } f2.open("BANK_TEMP.PG",ios::binary); if(!f2) { cout<<"\nWriting file cannot be opened."; } struct t { char myaccno[50]; char rcvraccno[50]; float money_trans; }t; recv(lsocket,(char*)&t,sizeof(t),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } while(1) { f1.read((char*)&rcvr,sizeof(rcvr)); cout<<"\n\nData Read"; cout<<"\nCheaking EOF"; if(f1.eof()) { cout<<"\nEOF Reached"; if(condition==0) //condition 0 implies rcvr //was not found and file is finished { result=0; cout<<"Sending Result"<<result; nret=send(lsocket,(char*)&result,sizeof(result),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } f1.close(); f2.close(); remove("BANK_TEMP.PG"); cout<<"\nTemp has been deleted."; return; } f1.close(); f2.close(); cout<<"\nFile has been successfully closed down."; remove("BANK.PG"); cout<<"\nBank has been deleted"; rename("BANK_TEMP.PG","BANK.PG"); cout<<"\nBank_temp has been renamed."; break; } else { cout<<"\nFile still left."; } cout<<"\n\nRead Data is:"<<endl; rcvr.show_details(); if((strcmp(rcvr.ret_acc_no(),t.rcvraccno)==0)) { cout<<"\nReceiver Match Found."; rcvr.show_details(); cout<<"\nCalling Function Add Money."; rcvr.transadd(t.money_trans); cout<<"\nThe changed details are : "; rcvr.show_details(); f2.write((char*)&rcvr,sizeof(rcvr)); condition=1; //condition 1 implies rcvr has //been found } else { cout<<"\nCase do not match.Data is written."; f2.write((char*)&rcvr,sizeof(rcvr)); } } f1.open("BANK.PG",ios::binary); if(!f1) { cout<<"\nReading file cannot be opened."; } f2.open("BANK_TEMP.PG",ios::binary); if(!f2) { cout<<"\nWriting file cannot be opened."; } while(1) { f1.read((char*)&my,sizeof(my)); if(f1.eof()) { cout<<"\nEOF Reached"; break; } else { cout<<"\nFile still left."; } if((strcmp(my.ret_acc_no(),t.myaccno)==0)) { cout<<"\nUser Match found."; my.show_details(); my.transred(t.money_trans); cout<<"\nThe changed details are : "; my.show_details(); f2.write((char*)&my,sizeof(my)); } else { cout<<"\nCase do not match.Data is written."; f2.write((char*)&my,sizeof(my)); } cout<<"\nCheaking EOF"; } f1.close(); f2.close(); cout<<"\nFile has been successfully closed down."; remove("BANK.PG"); cout<<"\nBank has been deleted"; rename("BANK_TEMP.PG","BANK.PG"); cout<<"\nBank_temp has been renamed."; result=1; cout<<"Sending Result :"<<result; nret=send(lsocket,(char*)&result,sizeof(result),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } } <file_sep>/Chat_App/CHAT_C.cpp #include<iostream> #include<winsock.h> #include<cstdio> #include<string> #include<windows.h> using namespace std; #define NETWORK_ERROR -1 #define NETWORK_OK 0 void ReportError(int,const char *); int _stdcall WinMain(HINSTANCE hinstance,HINSTANCE hprevinstance,LPSTR lp,int n) { WSADATA ws; int nret,i; WSAStartup(0x1010,&ws); SOCKET commsocket; char clientname[50],servername[50]; for(i=0;i<50;i++) clientname[i]=0; cout<<"Enter Your name : "; gets(clientname); cout<<"\nCreating Socket"; for(i=0;i<8;i++) { Sleep(500); cout<<'.'; } commsocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(commsocket==INVALID_SOCKET) { cout<<"\nSocket Cannot be created....."; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Socket successfully created"; SOCKADDR_IN serverinfo; serverinfo.sin_family=AF_INET; serverinfo.sin_addr.s_addr=inet_addr("192.168.0.20"); serverinfo.sin_port=htons(2609); cout<<"\nConnecting to server program"; for(i=0;i<10;i++) { Sleep(500); cout<<'.'; } nret=connect(commsocket,(LPSOCKADDR)&serverinfo,sizeof(struct sockaddr)); if(nret==SOCKET_ERROR) { cout<<"\nCannot connect to server......"; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Connected to server successfully\n"; nret=recv(commsocket,servername,50,0); if(nret==SOCKET_ERROR) { cout<<"\nImproper connection.Exiting "; WSACleanup(); getchar(); return NETWORK_ERROR; } nret=send(commsocket,clientname,50,0); if(nret==SOCKET_ERROR) { cout<<"Cannot setup connection Properly.Exiting"; WSACleanup(); getchar(); return NETWORK_ERROR; } char sendbuffer[256]="Client: Hello How you ? "; char recvbuffer[256]; while(1) { for(int i=0;i<=255;i++) { sendbuffer[i]=0; recvbuffer[i]=0; } cout<<"\n"<<clientname<<" :"; gets(sendbuffer); if(strcmpi(sendbuffer,"BYE")==0) { cout<<"\n\nClosing chat application"; WSACleanup(); getchar(); break; } else { nret=send(commsocket,sendbuffer,strlen(sendbuffer),0); if(nret==SOCKET_ERROR) { cout<<"\nCannot send data to server.Please Retry"; WSACleanup(); getchar(); } else { nret=recv(commsocket,recvbuffer,255,0); if(nret==SOCKET_ERROR) { cout<<"\nCannot receive data from server......."; WSACleanup(); getchar(); } else { cout<<"\n"<<servername<<" :"<<recvbuffer; } } } } cout<<"\n\nThanks for using PG's Chat Application"; closesocket(commsocket); getchar(); return NETWORK_OK; } <file_sep>/README.md # Memories_From_Childhood Just found these code files lying around in the draft of my mailbox. I wrote these codes as a 15 year old kid and looking at these codes (especially the 2000-liner banking app code) brings back a lot of memories and a smile upon my face, and reminds me how each of these projects has a story behind it. Putting them here so I won't lose them again. <file_sep>/Banking_App/CLIENT.cpp #include<iostream> #include<winsock.h> #include<cstdio> #include<string> #include<setjmp.h> #include<windows.h> #include<ctime> #include<cctype> #define NETWORK_ERROR -1 #define NETWORK_OK 0 using namespace std; //Global variable Declaration SOCKET commsocket; char sendbuffer[500],recvbuffer[500]; int p,i,nret; jmp_buf MAYDAY; time_t mytime; struct tm* timeinfo; char IP[16]; int First_Open=1; class account { private: char acc_no[50]; //Used for account number to log in char pass[50]; char holder_name[50]; //Name of account holder char email[50]; char address[50]; float money; int active_stat; //If active_stat is 1 then account //is active if active_stat is 0 //then account will be closed public: char * ret_hname(); char * ret_acc_no(); void showmenu(); void show_details(); void withdraw(); void deposit(); void transfer(); void edit(); void del(); void enter_details(); }; struct log //Structure containg username and //password to varify a successfull //login of user { char acc_number[50]; char password[50]; }; char * account::ret_acc_no() //function to return account number //of the user { return acc_no; } char * account :: ret_hname() //function to return holder name //of the user { return holder_name; } void unbind_sock() //function to unbind socket { closesocket(commsocket); cout<<"\nALL WENT HOLY."; } void gotoxy(int x, int y) //function to place curser at //any point on the screen { COORD coord; coord.X = x; coord.Y = y; SetConsoleCursorPosition(GetStdHandle(STD_OUTPUT_HANDLE), coord); }; void show_time() //function to show the current date //and time of the client computer { time(&mytime); timeinfo=localtime(&mytime); gotoxy(55,1); cout<<"DATE AND TIME : "; gotoxy(55,2); cout<<asctime(timeinfo); } void textcolor(int text_color = 7,int paper_color = 0) //function to set the fore ground and //background colour of the screen { int color_total = (text_color+(paper_color*16)); SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE),color_total ); } void account :: show_details() //function to show details of the //logged in user { fflush(stdin); system("CLS"); int i; char search[]="Searching Database..."; char retr[]="Retriving Data List..."; char acno[]="ACCOUNT NUMBER : "; char name[]="NAME : "; char mail[]="MAIL : "; char addr[]="ADDRESS : "; char amnt[]="AMOUNT : Rs "; time(&mytime); timeinfo=localtime(&mytime); gotoxy(0,1); cout<<holder_name; gotoxy(55,1); cout<<"DATE AND TIME : "; gotoxy(55,2); cout<<asctime(timeinfo); system("COLOR 20"); gotoxy(0,4); for(i=0;i<strlen(search);i++) { cout<<search[i]; Sleep(30); } gotoxy(0,6); for(i=0;i<strlen(retr);i++) { cout<<retr[i]; Sleep(30); } for(i=0;i<80;i++) { gotoxy(i,8); cout<<(char)219; Sleep(25); } gotoxy(0,10); for(i=0;i<strlen(acno);i++) { cout<<acno[i]; Sleep(30); } for(i=0;i<strlen(acc_no);i++) { cout<<acc_no[i]; Sleep(30); } gotoxy(0,12); for(i=0;i<strlen(name);i++) { cout<<name[i]; Sleep(30); } for(i=0;i<strlen(holder_name);i++) { cout<<holder_name[i]; Sleep(30); } gotoxy(0,14); for(i=0;i<strlen(mail);i++) { cout<<mail[i]; Sleep(30); } for(i=0;i<strlen(email);i++) { cout<<email[i]; Sleep(30); } gotoxy(0,16); for(i=0;i<strlen(addr);i++) { cout<<addr[i]; Sleep(30); } for(i=0;i<strlen(address);i++) { cout<<address[i]; Sleep(30); } gotoxy(0,18); for(i=0;i<strlen(amnt);i++) { cout<<amnt[i]; Sleep(30); } cout<<money; gotoxy(56,22); cout<<"Press Enter to continue"; getchar(); gotoxy(79,22); for(i=79;i>=56;i--) { gotoxy(i,22); cout<<" "; Sleep(30); } gotoxy(25,18); for(i=25;i>=0;i--) { gotoxy(i,18); cout<<" "; Sleep(30); } gotoxy(30,16); for(i=30;i>=0;i--) { gotoxy(i,16); cout<<" "; Sleep(30); } gotoxy(50,14); for(i=50;i>=0;i--) { gotoxy(i,14); cout<<" "; Sleep(30); } gotoxy(50,12); for(i=50;i>=0;i--) { gotoxy(i,12); cout<<" "; Sleep(30); } gotoxy(50,10); for(i=50;i>=0;i--) { gotoxy(i,10); cout<<" "; Sleep(30); } } void account :: withdraw() //function that will tell the server //to deduct money from the account { float withd=-1; while(withd<0 || money-1000<withd) { fflush(stdin); system("CLS"); system("COLOR 1F"); show_time(); cout<<"\n\nTotal Amount Available : Rs "<<money; cout<<"\nMinimum amount to be sustained : Rs 1000"; cout<<"\nEnter the amount to be withdrawn : "; cin>>withd; if(withd<0 || money-1000<withd) { cout<<"\n\nTransaction Not Possible.Please Try Again "; fflush(stdin); getchar(); system("CLS"); } } money=money-withd; cout<<"\nMoney Successfully withdrew. "; cout<<"\nCurrent Balance : "<<money; fflush(stdin); getchar(); } void account :: deposit() //function that will tell the server //to add money to the account { fflush(stdin); float depot=-1; while(depot<0) { system("CLS"); show_time(); cout<<"\n\nTotal Amount Available : Rs "<<money; cout<<"\nEnter the amount to be deposited : Rs "; cin>>depot; if(depot<0) { cout<<"\n\nTransaction Not Possible.Please Try Again "; fflush(stdin); getchar(); system("CLS"); } } money = money + depot; cout<<"\nMoney Successfully Deposited. "; cout<<"\nCurrent Balance : Rs "<<money; fflush(stdin); getchar(); } void account :: transfer() //function that will tell the server //to exchange money between the users { fflush(stdin); system("CLS"); system("COLOR 1F"); int result; struct transaction { char myaccno[50]; char rcvraccno[50]; float money_trans; }t; float trans=-1; while(trans<0 || money-1000<trans) { system("CLS"); show_time(); cout<<"\n\nTotal Amount Available : Rs "<<money; cout<<"\nMinimum amount to be sustained : Rs 1000"; cout<<"\nEnter the amount to be tranfered : Rs "; cin>>trans; if(trans<0 || money-1000<trans) { cout<<"\n\nTransaction Not Possible.Please Try Again "; fflush(stdin); getchar(); system("CLS"); } } fflush(stdin); cout<<"\nEnter the account number to which money has to be transfered : "; gets(t.rcvraccno); strcpy(t.myaccno,acc_no); t.money_trans=trans; nret=send(commsocket,(char*)&t,sizeof(t),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } nret=recv(commsocket,(char*)&result,sizeof(result),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } if(result==0) { cout<<"\nWrong account number entered."; fflush(stdin); getchar(); return; } if(result==1) { money=money-trans; cout<<"Money has been successfully transfered."; fflush(stdin); getchar(); } cout<<"\nCurrent Balance : "<<money; fflush(stdin); getchar(); } void account :: edit() //function that allows user to edit //the present details of user { fflush(stdin); system("CLS"); system("COLOR 1F"); show_time(); cout<<"\n\nEnter name of account holder : "; gets(holder_name); cout<<"\nEnter e-mail id : "; gets(email); cout<<"\nEnter address : "; gets(address); cout<<"\n\nData Successfully Edited.\nPlease Log Out And Login Again To Apply Changes."; fflush(stdin); getchar(); } void account :: del() //function that changes the active //state of the user acccount to //deactivate the account { fflush(stdin); system("COLOR 1F"); char del_stat; while(del_stat!='Y' && del_stat!='y' && del_stat!='N' && del_stat!='n') { system("CLS"); show_time(); cout<<"\n\nAre you sure u want to permenently delete your account (Y/N) :"; del_stat=getchar(); if(del_stat!='Y' && del_stat!='y' && del_stat!='N' && del_stat!='n') { cout<<"Invalid Input.Please Provide Valid Input"; fflush(stdin); getchar(); } } if(del_stat == 'Y' || del_stat == 'y') { cout<<"\nYour account will be de-activated within 24 hours.Please log out your account."; cout<<"\nRs "<<money<<" has been successfully withdrew "; money=0; active_stat=0; fflush(stdin); getchar(); } } void account :: enter_details() //function to take input of details //of user to create the account { srand(time(NULL)); char pass1[50]; int i,ran; system("CLS"); show_time(); system("COLOR 1F"); fflush(stdin); //to flush keyboard input buffer,present in cstdio while(1) { cout<<"\n\nEnter name of account holder : "; gets(holder_name); if(strlen(holder_name)>0) break; else { cout<<"\nEntry Cannot be left blank.\nRe-enter the Holder Name."; } } cout<<"\nEnter e-mail id : "; gets(email); cout<<"\nEnter address : "; gets(address); for(i=0;i<49;i++) { acc_no[i]=0; } for(i=0;i<10;i++) { ran = rand() % 10; acc_no[i]='0' + ran; } while(1) { cout<<"\nEnter your password : "; gets(pass); cout<<"\nConfirm password : "; gets(pass1); if(strcmp(pass,pass1)==0) break; else { cout<<"\nPassword do not match.\nRe-enter the password."; } } while(1) { cout<<"\nEnter the initial amount of money to be deposited : Rs "; cin>>money; if(money>=1000) break; else { cout<<"\nMinimum amount of money should be Rs 1000.Please re-enter the amount."; fflush(stdin); getchar(); } } active_stat=1; getchar(); } void account :: showmenu() //function to show user menu { fflush(stdin); int logout=0,choice=8; int indication=0; //indication is an integer which is //send to server to indicate that //user wanna log out,so //prepare yourself //it will be received by server in //main function of it in the integer //choice ie case 3: logout(); while(logout==0) { choice=8; system("CLS"); system("COLOR 1F"); show_time(); char wel[]="WELCOME"; while(choice<1 || choice>7) { textcolor(15,9); gotoxy((40-(strlen(wel)/2)-1),4); for(i=0;i<=strlen(wel)+1;i++) { cout<<" "; Sleep(50); } textcolor(15,9); gotoxy((40-(strlen(wel)/2)),4); for(i=0;i<=strlen(wel);i++) { cout<<wel[i]; Sleep(100); } gotoxy((40-(strlen(holder_name)/2)-1),6); for(i=0;i<=strlen(holder_name)+1;i++) { cout<<" "; Sleep(50); } textcolor(15,9); gotoxy((40-(strlen(holder_name)/2)),6); for(i=0;i<=strlen(holder_name);i++) { if(islower(holder_name[i])) { cout<<(char)(holder_name[i]-('a'-'A')); } else { cout<<holder_name[i]; } Sleep(100); } system("COLOR 1F"); cout<<"\n\nPlease Proceed with following options :-"; cout<<"\n\n1.Check My Details"; cout<<"\n2.Wihdraw Money"; cout<<"\n3.Deposite Money"; cout<<"\n4.Transfer Money"; cout<<"\n5.Edit My Details"; cout<<"\n6.Delete My Account"; cout<<"\n7.Log Out My Account"; cout<<"\n\nEnter your choice : "; textcolor(15,9); gotoxy((40-(strlen(wel)/2)-1),4); for(i=0;i<=strlen(wel)+1;i++) { cout<<" "; } textcolor(15,9); gotoxy((40-(strlen(wel)/2)),4); for(i=0;i<=strlen(wel);i++) { cout<<wel[i]; } gotoxy((40-(strlen(holder_name)/2)-1),6); for(i=0;i<=strlen(holder_name)+1;i++) { cout<<" "; } textcolor(15,9); gotoxy((40-(strlen(holder_name)/2)),6); for(i=0;i<=strlen(holder_name);i++) { if(islower(holder_name[i])) { cout<<(char)(holder_name[i]-('a'-'A')); } else { cout<<holder_name[i]; } } gotoxy(21,18); cin>>choice; if(choice<1 || choice>7) { cout<<"\nInvalid Choice Input.Please Enter Valid Input"; fflush(stdin); getchar(); system("CLS"); } } switch(choice) { case 1: show_details(); break; case 2: withdraw(); break; case 3: deposit(); break; case 4: indication=4; nret=send(commsocket,(char*)&indication,sizeof(indication),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } transfer(); cout<<"\nTransfer Ended"; break; case 5: edit(); break; case 6: del(); break; case 7: indication=3; nret=send(commsocket,(char*)&indication,sizeof(indication),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } nret=send(commsocket,(char*)(this),sizeof(account),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } nret=recv(commsocket,(char *)&logout,sizeof(logout),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } if(logout==1) { cout<<"\nLogged Out Successfully"; logout=1; getchar(); break; } else { cout<<"Server Error.Log Out Failed.Try Again."; fflush(stdin); getchar(); } } } } void login_disp(log u,int result) //function to display login success //or failure { system("CLS"); int i,j,t; textcolor(2,0); char user[]="ACCOUNT NUMBER : "; char pass[]="<PASSWORD> : "; char dot[]=".........."; char log0[]="Incorrect Username Or Password"; char log1[]="Logged In Successfully"; system("CLS"); Sleep(200); textcolor(10); system("CLS"); textcolor(2); cout<<"\n\t\t L O G G I N G I N A C C O U N T"; for(i=15;i<65;i++) { gotoxy(i,5); cout<<(char)223<<(char)223; Sleep(25); } for(j=5;j<=22;j++) { gotoxy(66,j); cout<<(char)221; Sleep(25); } for(i=65;i>=15;i--) { gotoxy(i,23); cout<<(char)223<<(char)223; Sleep(25); } for(j=22;j>=5;j--) { gotoxy(15,j); cout<<(char)222; Sleep(25); } gotoxy(20,8); cout<<"ACCOUNT NUMBER : "; for(t=0;t<strlen(u.acc_number);t++) { cout<<u.acc_number[t]; Sleep(100); } gotoxy(20,10); cout<<"PASSWORD : "; for(t=0;t<strlen(u.password);t++) { cout<<'*'; Sleep(100); } gotoxy(20,14); cout<<"SIGNING IN"; gotoxy(30,14); for(t=0;t<=9;t++) { cout<<dot[t]; Sleep(200); } if(result==1) { gotoxy(30,18); for(t=0;t<strlen(log1);t++) { cout<<log1[t]; Sleep(50); } } if(result==0) { gotoxy(27,18); for(t=0;t<strlen(log0);t++) { cout<<log0[t]; Sleep(50); } } gotoxy(34,20); cout<<"Press Enter Key To Continue..."; fflush(stdin); getchar(); } void user_log(account ac) //function to display loading screen { system("CLS"); int i; char name[50]; char myapp[]="PG's ONLINE BANKING SYSTEM"; char load_det[]="LOADING YOUR DETAILS TO BUFFER"; char load_line[]="______________________"; strcpy(name,ac.ret_hname()); textcolor(15,0); gotoxy((40-(strlen(myapp)/2)),10); for(i=0;i<strlen(myapp);i++) { cout<<myapp[i]; Sleep(50); } textcolor(15,9); gotoxy((40-(strlen(name)/2)-1),12); for(i=0;i<=strlen(name)+1;i++) { cout<<" "; Sleep(50); } textcolor(15,9); gotoxy((40-(strlen(name)/2)),12); for(i=0;i<=strlen(name);i++) { if(islower(name[i])) { cout<<(char)(name[i]-('a'-'A')); } else { cout<<name[i]; } Sleep(100); } gotoxy((40-(strlen(load_det)/2)),14); textcolor(10,0); for(i=0;i<=strlen(load_det);i++) { cout<<load_det[i]; Sleep(50); } textcolor(3,0); gotoxy((40-(strlen(load_line)/2)),15); cout<<load_line; gotoxy((40-(strlen(load_line)/2)),15); textcolor(15,0); for(i=0;i<=strlen(load_line);i++) { cout<<load_line[i]; Sleep(300); } gotoxy(80-50,23); cout<<"Buffering Completed.Press Enter Key To Continue..."; getchar(); } void login() //function to check login success or //login failure { fflush(stdin); log u; account ac,acc; int result=-2; system("CLS"); system("COLOR 1F"); show_time(); cout<<"\n\nEnter account number : "; gets(u.acc_number); cout<<"\nEnter password : "; gets(u.password); nret=send(commsocket,(char*)&u,sizeof(u),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } nret=recv(commsocket,(char *)&result,sizeof(result),0); //result check weather account //logged in successfully(ie 1) //or not(ie 0) if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } login_disp(u,result); if(result==1) { nret=recv(commsocket,(char*)&ac,sizeof(ac),0); //ac is the object containing //all the information about the //account of user if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } user_log(ac); ac.showmenu(); } } void create() //function to deploy a function //to take user data and then tell the //server to create the account { fflush(stdin); account new_acc; int create_stat=-1; char a='N'; system("COLOR 1F"); do { new_acc.enter_details(); fflush(stdin); OOPS : cout<<"\nPlease Confirm These Details : "; cout<<"\nTo Confirm Press Y Or To Exit Press N "; cout<<"\n\nChoice : "; a=getchar(); if(a!='Y' && a!='y' && a!='n' && a!='N') { cout<<"\nWrong Choice Entered "; getchar(); goto OOPS; } else if(a!='Y' && a!='y') { cout<<"\nAccount Has Not Been Created.Please Re Enter Details."; fflush(stdin); getchar(); } }while(a!='Y' && a!='y'); nret=send(commsocket,(char*)&new_acc,sizeof(new_acc),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } nret=recv(commsocket,(char*)&create_stat,4,0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } if(create_stat==0) { cout<<"\nNetwork Malfunctioning.\nCannot create account.\nPage has expired.\nPlease try again"; fflush(stdin); getchar(); } else if(create_stat==1) { cout<<"\nAccount Successfully Created."; cout<<"\nYour Account Number : "<<new_acc.ret_acc_no(); fflush(stdin); getchar(); } } void about() //function to tell user a little //about this application { fflush(stdin); system("CLS"); system("COLOR 1F"); show_time(); cout<<"\n\nA Banking System Application By PG."; cout<<"\nThanks to all the people who are directly \nor indirectly invloved in the project."; cout<<"\nSpecial Thanks to following sites :"; cout<<"\n1. www.MadWizard.com"; cout<<"\n2. www.HackForums.net"; cout<<"\n3. www.CPlusPlus.com"; cout<<"\nSpecial Thanks to following games to help me in making User Interface"; cout<<"\n1. Need For Speed Most Wanted "; cout<<"\n2. Modern Warfare"; cout<<"\nMeet me on facebook by inviting friend <EMAIL>"; fflush(stdin); getchar(); return; } void menu() //function to display main menu for //the user { fflush(stdin); int choice=6,temp; //since choice=4 in server indicates //transfer function.Therefore some //other indication is required to //indicate that user exits the //program.Hence temp is used while(1) { system("CLS"); choice=6; fflush(stdin); int i; char welcome[]="WELCOME TO PG's ONLINE BANKING APP"; char log[]="1.Login Account"; char creat[]="2.Create Account"; char app[]="3.About Application"; char exit[]="4.Exit Program"; system("COLOR 10"); while(choice>4 ||choice<1) { system("CLS"); textcolor(15,1); show_time(); choice=6; fflush(stdin); textcolor(0,15); gotoxy((40-(strlen(welcome)/2)-1),5); for(i=0;i<=strlen(welcome)+1;i++) { cout<<" "; Sleep(30); } textcolor(0,15); gotoxy((40-(strlen(welcome)/2)),5); for(i=0;i<=strlen(welcome);i++) { cout<<welcome[i]; Sleep(40); } textcolor(15,1); gotoxy(0,8); for(i=0;i<=strlen(log);i++) { cout<<log[i]; Sleep(20); } gotoxy(0,9); for(i=0;i<=strlen(creat);i++) { cout<<creat[i]; Sleep(20); } gotoxy(0,10); for(i=0;i<=strlen(app);i++) { cout<<app[i]; Sleep(20); } gotoxy(0,11); for(i=0;i<=strlen(exit);i++) { cout<<exit[i]; Sleep(20); } cout<<"\n\nEnter your choice : "; gotoxy(21,13); cin>>choice; if(choice>4 ||choice<1) { cout<<"\nInvalid Choice Input.Please Enter Valid Input"; fflush(stdin); getchar(); system("CLS"); } } switch(choice) { case 1: nret=send(commsocket,(char*)&choice,sizeof(choice),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } login(); break; case 2: nret=send(commsocket,(char*)&choice,sizeof(choice),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } create(); break; case 3: about(); break; case 4: temp=6; nret=send(commsocket,(char*)&temp,sizeof(temp),0); if(nret==SOCKET_ERROR) { cout<<"\nNetwork Connection Error.Socket Is Now UnBound"; WSACleanup(); unbind_sock(); longjmp(MAYDAY,1); } cout<<"\n\nThank you for using PG's Application."; MessageBox(0,"THANK YOU FOR USING MY APPLICATION.","PG's BANKING APP",0); fflush(stdin); getchar(); return; } } } int bind_socket() //function to create and //bind the socket { WSADATA ws; WSAStartup(0x1010,&ws); cout<<"\nCreating Socket....."; commsocket=socket(AF_INET,SOCK_STREAM,IPPROTO_TCP); if(commsocket==INVALID_SOCKET) { cout<<"\nSocket Cannot be created....."; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Socket successfully created"; SOCKADDR_IN serverinfo; serverinfo.sin_family=AF_INET; if(First_Open==1) { for(p=0;p<=16;p++) IP[p]=0; cout<<"\nEnter the IP Address of server : "; gets(IP); First_Open=0; } serverinfo.sin_addr.s_addr=inet_addr(IP); serverinfo.sin_port=htons(2609); cout<<"\nConnecting to server program......"; nret=connect(commsocket,(LPSOCKADDR)&serverinfo,sizeof(struct sockaddr)); if(nret==SOCKET_ERROR) { cout<<"\nCannot connect to server......"; WSACleanup(); getchar(); return NETWORK_ERROR; } else cout<<"Connected to server successfully\n"; return NETWORK_OK; } int WinMain(HINSTANCE hinstance,HINSTANCE hprevinstance,LPSTR lp,int n) //WinMain function to initialise the //program { setjmp(MAYDAY); bind_socket(); menu(); }
4cc038b2937d43024be98f5f318d09b69f20ce0e
[ "Markdown", "C++" ]
7
Markdown
Rex-0x7CB/Memories_From_Childhood
33c6d5cd0683cd8899759c86b7603e89aff017d5
a421b8eb94c1ee5627e89df6a8a12080034feafc
refs/heads/master
<file_sep>/*! \file calculator.h \brief Заголовочный файл калькулятора \author <NAME> \version 1.0 \date Июль 2017 */ #include <dirent.h> #include <dlfcn.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "operations.h" /*! * захардкоженый путь до динамических библиотек.make создастпапку. */ #define LPATH "lib/" /*! * \brief Максимальная длина пути * */ #define STRLEN 256 /*! * \brief Тип для хранения информации о загруженной динамической библиотеке * */ typedef struct { /*! * \brief Имя функции */ char name[STRLEN]; /*! * \brief Путь до файла, в котором лежит функция * */ char path[STRLEN]; /*! *"handle" for the dynamic library. man dlopen * */ void *handle; /*! *адрес функции в памяти. man dlsym */ void *f; } operations_t; /*! * считывает число из командной строки * * \return считанное целочисленное число * */ int getNumber(); /*! * функция вытаскивания функции из динамической библиотеки * * \param[in] path Имя библиотеки(dynamic shared object). man dlopen * \param[in] name Имя функции. man dlsym * \param[in] op указатель на массив. Этот массив хранит список функций из * динамических билиотек. * \return сколько всего функций в массиве после выполнения этой функции. * */ int openf(char *path, char *name, operations_t **op); /*! * Удаляет подстроку из строки * * \param[out] s строка * \param[in] toremove строка, которую нужно удалить из строки s * */ void rmsbstr(char *s, const char *toremove); <file_sep>/* вычитания одного целого числа из другого */ #include "operations.h" int sub(int a, int b) { return a - b; } <file_sep>/*! \file operations.h \brief Заголовочный файл для списка функций-операций. Имена функций читаются отсюда \author <NAME> \version 1.0 \date Июль 2017 */ #include <stdio.h> /*! * \brief указатель на функцию, которая принимает два параметра типа int * \param[int] операнд * \param[int] операнд * \return результат операции * * */ typedef int (*twoi_t)(int, int); /*! * \brief указатель на функцию, которая принимает один параметр типа int * \param[int] операнд * \return результат операции * */ typedef int (*onei_t)( int); /*! * \brief операция сложения двух числен * \param[int] операнд * \param[int] операнд * \return результат операции * */ int sum(int, int); /*! * \brief операция сложения двух целочисленных чисел * \param[int] операнд * \param[int] операнд * \return результат операции * */ int mul(int, int); /*! * \brief операция умножения двух целочисленных чисел * \param[int] операнд * \param[int] операнд * \return результат операции * */ int sub(int, int); /*! * \brief операция вычитания двух целочисленных чисел * \param[int] операнд * \param[int] операнд * \return результат операции * */ int mdiv(int, int); /*! * \brief операция деление двух целочисленных чисел * \param[int] операнд * \param[int] операнд * \return результат операции * */ int factorial(int); /*! * \brief Факториал * \param[int] операнд * \return результат операции * */ <file_sep>CC = gcc CFLAGS = -Wall -pedantic -std=c89 -g LIBPATH = "lib" all: dir calculator.o libsum.so libsub.so libmul.so libmdiv.so libfactorial.so ${CC} calculator.o -o calculator -ldl -rdynamic # ${CC} calculator.o -o calculator -Llib -lsum -lsub -lmul -ldiv -lfactorial -Wl,-rpath,lib calculator.o: calculator.c ${CC} ${CFLAGS} -c calculator.c libsum.so: sum.o ${CC} -shared -o lib/libsum.so sum.o libsub.so: sub.o ${CC} -shared -o lib/libsub.so sub.o libmul.so: mul.o ${CC} -shared -o lib/libmul.so mul.o libmdiv.so: mdiv.o ${CC} -shared -o lib/libmdiv.so mdiv.o libfactorial.so: factorial.o ${CC} -shared -o lib/libfactorial.so factorial.o sum.o: sum.c ${CC} ${CFLAGS} -c -fPIC sum.c sub.o: sub.c ${CC} ${CFLAGS} -c -fPIC sub.c mdiv.o: mdiv.c ${CC} ${CFLAGS} -c -fPIC mdiv.c mul.o: mul.c ${CC} ${CFLAGS} -c -fPIC mul.c factorial.o: factorial.c ${CC} ${CFLAGS} -c -fPIC factorial.c dir: mkdir -p $(LIBPATH) clean: rm -rf *.o lib calculator <file_sep>/* операция деления двух чисел */ #include "operations.h" int mdiv(int a, int b) { if (b == 0){ printf("ЕГГОГ ДЕЛЕНИЕ НА НОЛЬ\n"); return 0; } return a / b; } <file_sep>/* простой калькулятор */ #include "calculator.h" int main(int argc, char *argv[]) { int i; int n; int a,b; int choice; int answer; char path[STRLEN]; char name[STRLEN]; DIR *d; struct dirent *dir; operations_t *operations = NULL ; /* смотрим наличие либ*/ d = opendir(LPATH); if (d){ while ((dir = readdir(d)) != NULL){ /* скипаем .. и . */ if((dir->d_name[0] == '.')) continue; strcpy(path, LPATH); strcpy(name, dir->d_name); rmsbstr(name, "lib"); rmsbstr(name, ".so"); strncat(path, dir->d_name, strlen(dir->d_name)); n = openf(path, name, &operations); } closedir(d); } else { fprintf(stderr, "Не могу открыть директорию\n"); return 1; } /* функции загружены, можно начинать работать */ printf("Офигенный калькулятор умеет следующее:\n"); for(i = 0; i < n; i++){ printf("\t%d. %s\n",i,operations[i].name); } printf("\t%d. выходить\n", n); while(1){ printf("Что делаем?\n"); printf("---> "); choice = getNumber(); if(choice == n){ for(i = 0; i < n; i++) dlclose(operations[i].handle); free(operations); printf("koniec\n"); return 0; } else if(choice < 0 || choice > n){ printf("Нет такой функции\n"); } else if(strcmp(operations[choice].name, "factorial")){ printf("--> "); a = getNumber(); printf("--> "); b = getNumber(); answer = ((twoi_t) operations[choice].f)(a,b); printf("===> %d\n", answer); } else if(!strcmp(operations[choice].name, "factorial")){ printf("--> "); a = getNumber(); answer = ((onei_t) operations[choice].f)(a); printf("===> %d\n", answer); } } /* *(void **) (&sum) = dlsym(...); */ for(i = 0; i < n; i++) dlclose(operations[i].handle); free(operations); return 0; } /* Мы хотим получить только число */ int getNumber() { int num; while(1){ if(scanf("%d", &num) == 1) return num; getchar(); } } /* функция вытаскивания функции из динамической библиотеки */ int openf (char *path, char *name, operations_t **op) { void *f; void *handle; char *error; static int n = 0; handle = dlopen (path, RTLD_NOW); if (!handle) { fprintf(stderr, "%s\n", dlerror()); return n; } f = dlsym(handle, name); if ((error = dlerror()) != NULL){ fprintf (stderr, "%s\n", error); return n; } if(*op == NULL){ *op = malloc(sizeof(operations_t)); if(*op == NULL){ fprintf(stderr, "Не хватает памяти...\n"); exit(1); } }else{ *op = realloc(*op, ((n+1) * sizeof(operations_t))); if(*op == NULL){ fprintf(stderr, "Не хватает памяти...\n"); exit(1); } } /* научился правильно присваивать, ага */ strncpy((*op)[n].name, name, STRLEN); strncpy((*op)[n].path, path, STRLEN); (*op)[n].handle = handle; (*op)[n].f = f; n++; return n; } /* удаляет подстроку из строки*/ void rmsbstr(char *s,const char *toremove) { while((s=strstr(s,toremove))) memmove(s,s+strlen(toremove),1+strlen(s+strlen(toremove))); } <file_sep>/* перемножение двух целых чисел */ #include "operations.h" int mul(int a, int b) { return a * b; } <file_sep>/* подсчет факториала числа */ #include "operations.h" int factorial(int n) { int answer = 1; /* факториал отрицательного числа *можно* подсчитать, но сложно */ if(n < 0){ printf("Факториал отрицательного числа не считаю"); return -1; } while(n > 0){ answer *= n; n--; } return answer; }
b86bdce7c3e5d078e70fe7945887caa4d94522d6
[ "C", "Makefile" ]
8
C
TsarVladislav/Shared-libraries-calculator
e135213b7ac77337b1a13c05fa046987701297bd
ea67b9db86fd433ddabd957b0b535138d39d9f7e
refs/heads/master
<file_sep># Unity Preview Generator This project/Unity Package is to generator thumbnails/previews/icons/sprites from 3D models in Unity. It has a Custom Editor for generating the texture and an in-game component that allows you to create the sprites from a RenderTexture. This is useful for many things including generating icons at runtime. ## Getting Started You can either clone this project from here or find it on the Unity Store for Free at https://assetstore.unity.com/packages/slug/138077 ### Prerequisites Unity3d of course. If you want to use Post Processing on the icons, you can install the current Post Processing Stack and use the sample Post Processing Camera Prefab to generate textures ## Authors * **<NAME>** - *Initial work* - [klhurley](https://github.com/klhurley) ## License This project is licensed under the MIT License - see the [LICENSE](LICENSE) file for details ## Documenation You can get the documenation on the [Wiki](https://github.com/klhurley/UnityPreviewGenerator/wiki/Documenatation) ## Acknowledgments * <NAME> https://github.com/yasirkula for the Runtime Preview Generator <file_sep>using System; using System.IO; using UnityEngine; [System.Serializable] public class AnimationClipInfo { public float PositionInClip; public AnimationClip AnimationClip; } [System.Serializable] public enum BackgroundTextureTypes { Transparent, Color, Texture } [System.Serializable] public class BackgroundColorOrTextureInfo { public BackgroundTextureTypes backType = BackgroundTextureTypes.Transparent; public Color BackgroundColor; public Texture2D BackgroundTexture; public bool UseBackgroundAlpha = true; } [System.Serializable] public class PreviewGenerator { public GameObject GameObjectToRender; public GameObject PreviewCamera; public bool OrthographicCamera = true; public Vector3 ViewDirection = new Vector3( -1.0f, -1.0f, -1.0f ).normalized; [HideInInspector] public Vector3 ViewRightDirection; public Vector3 ViewUpDirection = Vector3.up; public Vector2 PanOffset; public float ZoomLevel; [Delayed] public int RenderWidth = 256; [Delayed] public int RenderHeight = 256; public BackgroundColorOrTextureInfo BackgroundColorOrTextureInfo; public AnimationClipInfo AnimationClipInfo; private const int PREVIEW_LAYER = 22; private bool _isInited; private PostProcessMergeComponent _postProcessMergeComponent; private Material _combinerMaterial; [NonSerialized] public bool bRepaintNeeded = false; private GameObject _lastCameraObject; private GameObject _defaultCameraObject; private Texture2D _renderedPreview; public Texture2D PreviewTexture { get { if (GameObjectToRender == null) { _renderedPreview = null; } return _renderedPreview; } } private GameObject m_CloneObject; private RuntimeAnimatorController tempRuntimeAnimatorController; private string _lastPNGPathName = "default.png"; public string LastPNGPathName { get { return _lastPNGPathName; } } // Camera class to save transparency that is blasted away in post processing [RequireComponent(typeof(Camera)), DisallowMultipleComponent, ExecuteAlways] public class PostProcessMergeComponent : MonoBehaviour { public Texture2D AlphaStorage { get; set; } void OnPostRender() { RenderTexture activeRenderTexture = RenderTexture.active; if (activeRenderTexture != null) { AlphaStorage = new Texture2D(activeRenderTexture.width, activeRenderTexture.height, TextureFormat.RGBA32, false); AlphaStorage.ReadPixels(new Rect(0, 0, activeRenderTexture.width, activeRenderTexture.height), 0, 0, false); AlphaStorage.Apply(false, true); } } } public void Initialize() { if (!_isInited) { _isInited = true; _defaultCameraObject = Resources.Load<GameObject>("PreviewGeneratorDefaultCamera"); if (_defaultCameraObject != null) { PreviewCamera = _defaultCameraObject; } else { Debug.LogError("Cannot find the PreviewGeneratorDefaultCamera object to load!"); } tempRuntimeAnimatorController = Resources.Load<RuntimeAnimatorController>("PreviewGeneratorDummyController"); if (tempRuntimeAnimatorController == null) { Debug.LogError("Cannot find the PreviewGeneratorDummyController controller to load!"); } _combinerMaterial = Resources.Load<Material>("CombinerMaterial"); if (_combinerMaterial == null) { Debug.LogError("Cannot find the CombinerMaterial to load!"); } } // mostly up cross product, to get mostly right ViewRightDirection = Vector3.Cross(Vector3.up, -ViewDirection); } public Texture2D MergeAlphaAndBackground(Texture2D srcTexture, Texture2D backgroundTexture, Texture2D alpha) { RenderTexture tempRT = RenderTexture.GetTemporary(srcTexture.width, srcTexture.height, 16); Texture2D retTexture = new Texture2D(srcTexture.width, srcTexture.height, TextureFormat.RGBA32, false); Material tempMaterial = new Material(_combinerMaterial); if (tempRT != null) { if (alpha == null) { alpha = Texture2D.whiteTexture; } if (backgroundTexture == null) { backgroundTexture = Texture2D.blackTexture; } if (BackgroundColorOrTextureInfo.backType == BackgroundTextureTypes.Texture) { tempMaterial.SetInt("_UseBackAlpha", BackgroundColorOrTextureInfo.UseBackgroundAlpha ? 1 : 0); } else { tempMaterial.SetInt("_UseBackAlpha", 1); } backgroundTexture.wrapMode = TextureWrapMode.Repeat; srcTexture.wrapMode = TextureWrapMode.Clamp; alpha.wrapMode = TextureWrapMode.Clamp; if (tempMaterial != null) { tempMaterial.SetTexture("_AlphaTex", alpha); tempMaterial.SetTexture("_BackgroundTex", backgroundTexture); } RenderTexture oldRT = RenderTexture.active; Graphics.Blit(srcTexture, tempRT, tempMaterial); RenderTexture.active = tempRT; retTexture.ReadPixels(new Rect(0, 0, tempRT.width, tempRT.height), 0, 0, false); retTexture.Apply(false, false); RenderTexture.active = oldRT; RenderTexture.ReleaseTemporary(tempRT); } return retTexture; } // save the render texture to png public void SavePNG(string path) { if (path.Length != 0) { _lastPNGPathName = path; byte[] pngData = PreviewTexture.EncodeToPNG(); if (pngData != null) { try { File.WriteAllBytes(path, pngData); } catch (Exception ex) { Debug.Log(ex); } } } } // this function can only be called after all components have been through Awake and Start because this // class isn't a Monobehaviour class but it does instantiate Monobehaviour classes public GameObject GetInternalCamera() { GameObject _internalCameraObject = null; _postProcessMergeComponent = null; if (PreviewCamera != null) { _internalCameraObject = GameObject.Instantiate(PreviewCamera.gameObject); Camera cameraComponent = _internalCameraObject.GetComponent<Camera>(); if (cameraComponent == null) { Debug.LogWarning("No camera component for " + _internalCameraObject.name + ". Default camera will be used."); _internalCameraObject = GameObject.Instantiate(_defaultCameraObject.gameObject); cameraComponent = _internalCameraObject.GetComponent<Camera>(); PreviewCamera = _defaultCameraObject; } _internalCameraObject.name = "Preview Camera"; if (cameraComponent != null) { cameraComponent.cullingMask = 1 << PREVIEW_LAYER; cameraComponent.enabled = false; cameraComponent.orthographic = OrthographicCamera; cameraComponent.backgroundColor = BackgroundColorOrTextureInfo.BackgroundColor; } MonoBehaviour postProcessComponent = (MonoBehaviour)_internalCameraObject.GetComponent("PostProcessingBehaviour"); // only post processing system we support right now if (postProcessComponent != null) { _postProcessMergeComponent = _internalCameraObject.AddComponent<PostProcessMergeComponent>(); } _internalCameraObject.gameObject.hideFlags = HideFlags.HideAndDontSave; RuntimePreviewGenerator.PreviewRenderCamera = cameraComponent; return _internalCameraObject; } return _internalCameraObject; } public void RenderPreviewTexture() { GameObject _internalCameraObject = null; Texture2D backgroundTexture = null; // make sure we are Initialiazed Initialize(); if (BackgroundColorOrTextureInfo.backType == BackgroundTextureTypes.Texture) { RuntimePreviewGenerator.TransparentBackground = true; backgroundTexture = BackgroundColorOrTextureInfo.BackgroundTexture; } else { RuntimePreviewGenerator.TransparentBackground = (BackgroundColorOrTextureInfo.backType == BackgroundTextureTypes.Transparent); RuntimePreviewGenerator.BackgroundColor = BackgroundColorOrTextureInfo.BackgroundColor; } RuntimePreviewGenerator.OrthographicMode = OrthographicCamera; if (GameObjectToRender != null) { GameObject tempGameObject = GameObject.Instantiate(GameObjectToRender.gameObject, null, false); tempGameObject.hideFlags = HideFlags.HideAndDontSave; _internalCameraObject = GetInternalCamera(); // There is a bug in AnimationMode.SampleAnimationClip which crashes // Unity if there is no valid controller attached bool doAnimClip = (AnimationClipInfo.AnimationClip != null); Animator animator = tempGameObject.GetComponent<Animator>(); if ((animator != null) && (animator.runtimeAnimatorController == null)) { if (tempRuntimeAnimatorController == null) { doAnimClip = false; Debug.LogError("Cannot load a Dummy Runtime Animator, disabling clip which can cause crashes"); } animator.runtimeAnimatorController = tempRuntimeAnimatorController; } if (doAnimClip) { AnimationClipInfo.AnimationClip.SampleAnimation(tempGameObject, AnimationClipInfo.PositionInClip); } // set camera rotation/preview rotation RuntimePreviewGenerator.PreviewDirection = ViewDirection; RuntimePreviewGenerator.UpDirection = ViewUpDirection; RuntimePreviewGenerator.PanOffset = PanOffset; RuntimePreviewGenerator.ZoomLevel = ZoomLevel; Texture2D alphaTexture = null; Texture2D tempTexture = RuntimePreviewGenerator.GenerateModelPreview(tempGameObject.transform, RenderWidth, RenderHeight); if ((_postProcessMergeComponent != null) && (BackgroundColorOrTextureInfo.backType != BackgroundTextureTypes.Color)) { alphaTexture = _postProcessMergeComponent.AlphaStorage; } _renderedPreview = MergeAlphaAndBackground(tempTexture, backgroundTexture, alphaTexture); GameObject.DestroyImmediate(tempGameObject); } if (_internalCameraObject != null) { GameObject.DestroyImmediate(_internalCameraObject); } } } <file_sep>using System.Collections; using System.Collections.Generic; using UnityEngine; [ExecuteAlways] public class SpriteRenderTexture : MonoBehaviour { private SpriteRenderer _spriteRenderer; private PreviewGeneratorComponent _previewGeneratorComponent; private Texture2D _curTexture = null; private GameObject _curGameObject; // Start is called before the first frame update void Start() { _spriteRenderer = gameObject.GetComponent<SpriteRenderer>(); _previewGeneratorComponent = gameObject.GetComponent<PreviewGeneratorComponent>(); if (_previewGeneratorComponent != null) { SetSprite(true); _curGameObject = _previewGeneratorComponent.PreviewGenerator.GameObjectToRender; } } // Update is called once per frame void Update() { if (_previewGeneratorComponent != null) { // only gets new renderTexture if object changes or texture changes SetSprite((_curGameObject != _previewGeneratorComponent.PreviewGenerator.GameObjectToRender) || _previewGeneratorComponent.renderTextureChanged); } } void SetSprite(bool doRender) { if (_previewGeneratorComponent != null) { if (_spriteRenderer != null) { Texture2D spriteTexture = _previewGeneratorComponent.GetRenderTexture(doRender); if ((spriteTexture != null) && (spriteTexture != _curTexture)) { _curTexture = spriteTexture; Sprite sprite = Sprite.Create(spriteTexture, new Rect(0.0f, 0.0f, spriteTexture.width, spriteTexture.height), new Vector2(.5f, .5f), 100.0f); _spriteRenderer.sprite = sprite; } } } } } <file_sep>using System; using UnityEngine; [HelpURL("https://github.com/klhurley/UnityPreviewGenerator/wiki/Editor-Window-&-Preview-Component#PreviewComponent")] [ExecuteAlways] public class PreviewGeneratorComponent : MonoBehaviour { public PreviewGenerator PreviewGenerator; [NonSerialized] public bool renderTextureChanged = false; void OnValidate() { if (PreviewGenerator != null) { PreviewGenerator.bRepaintNeeded = true; renderTextureChanged = true; } } void Start() { if (PreviewGenerator == null) { PreviewGenerator = new PreviewGenerator(); } PreviewGenerator.Initialize(); PreviewGenerator.bRepaintNeeded = true; } public Texture2D GetRenderTexture(bool doRender = false) { if (PreviewGenerator != null) { PreviewGenerator.Initialize(); if (doRender) { PreviewGenerator.RenderPreviewTexture(); renderTextureChanged = false; } return PreviewGenerator.PreviewTexture; } return null; } }<file_sep>pushd ../wiki pandoc -V geometry:margin=.5in Logo.md Home.md Installation.md Editor-Window-\&-Preview-Component.md Camera-Manipulation.md Property-Settings.md Sprite-Renderer-Code-Sample-Explanation.md _Footer.md --pdf-engine=xelatex -o ../Documentation/PreviewGenerator.pdf popd <file_sep>using System; using System.IO; using UnityEditor; using UnityEngine; [HelpURL("https://github.com/klhurley/UnityPreviewGenerator/wiki/Editor-Window-&-Preview-Component#EditorWindow")] [Serializable] public class PreviewGeneratorEditorWindow : EditorWindow { static PreviewGeneratorEditorWindow window; [SerializeField] private PreviewGenerator _previewGenerator; SerializedObject previewGenSO; private SerializedProperty previewGenSP; private Editor _previewGeneratorEditor; private Vector2 curScrollPosition = new Vector2(0.0f, 0.0f); private const string _settingsPath = "/ProjectSettings/PreviewGeneratorSettings.json"; [MenuItem("Window/Preview Generator")] static void ShowWindow() { window = GetWindow<PreviewGeneratorEditorWindow>(); window.minSize = new Vector2(525.0f, 695.0f); } protected void OnEnable () { if (_previewGenerator == null) { _previewGenerator = new PreviewGenerator(); } _previewGenerator.Initialize(); string path = Path.GetDirectoryName(Application.dataPath) + _settingsPath; if (File.Exists(path)) { string settings = File.ReadAllText(path); if (settings != null) { // Then we apply them to this window EditorJsonUtility.FromJsonOverwrite(settings, _previewGenerator); } _previewGenerator.bRepaintNeeded = true; } } protected void OnDisable () { string path = Path.GetDirectoryName(Application.dataPath) + _settingsPath; File.WriteAllText(path, EditorJsonUtility.ToJson(_previewGenerator, true)); } void OnGUI() { if (window == null) { window = GetWindow<PreviewGeneratorEditorWindow>(); window.minSize = new Vector2(525.0f, 695.0f); //OnEnable(); } bool oldWideMode = EditorGUIUtility.wideMode; float oldLabelWidth = EditorGUIUtility.labelWidth; // about 42% for labelWidth EditorGUIUtility.labelWidth = EditorGUIUtility.currentViewWidth / 2.4f; EditorGUIUtility.wideMode = true; previewGenSO = new SerializedObject(this); previewGenSO.Update(); previewGenSP = previewGenSO.FindProperty("_previewGenerator"); if (previewGenSP == null) { Debug.LogError("Misnamed _preview Generator in this Window class"); return; } EditorGUILayout.InspectorTitlebar(true, this); EditorGUILayout.BeginHorizontal(); { EditorGUILayout.Space(); EditorGUILayout.Space(); curScrollPosition = EditorGUILayout.BeginScrollView(curScrollPosition); { EditorGUILayout.PropertyField(previewGenSP, true); } EditorGUILayout.EndScrollView(); } EditorGUILayout.EndHorizontal(); // about 42% for labelWidth EditorGUIUtility.labelWidth = oldLabelWidth; EditorGUIUtility.wideMode = oldWideMode; previewGenSO.ApplyModifiedProperties(); if (_previewGenerator.bRepaintNeeded) { Repaint(); } } } // these are for the Preview Generator script [CustomEditor(typeof(PreviewGeneratorComponent))] public class PreviewGeneratorEditor : Editor { // this happens when clicked off component or OnDisable/OnEnable with prefab reverts void OnEnable() { PreviewGenerator previewGenerator = ((PreviewGeneratorComponent)serializedObject.targetObject).PreviewGenerator; previewGenerator.bRepaintNeeded = true; } public override void OnInspectorGUI() { serializedObject.Update(); base.OnInspectorGUI(); serializedObject.ApplyModifiedProperties(); PreviewGenerator previewGenerator = ((PreviewGeneratorComponent)serializedObject.targetObject).PreviewGenerator; if (previewGenerator.bRepaintNeeded) { Repaint(); } } public override bool RequiresConstantRepaint() { PreviewGenerator previewGenerator = ((PreviewGeneratorComponent)serializedObject.targetObject).PreviewGenerator; return previewGenerator.bRepaintNeeded; } } [CustomPropertyDrawer(typeof(PreviewGenerator), true)] public class PreviewGeneratorDrawer : PropertyDrawer { private const float rotSpeed = 1.0f; private const float panSpeed = .0025f; private const float zoomSpeed = .01f; private bool mouseOverTexture = false; private Rect texRect = new Rect(0.0f, 0.0f, 0.0f, 0.0f); private const int MinTextureSize = 1; private const int MaxTextureSize = 4096; public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { PreviewGenerator previewGenerator = (PreviewGenerator) fieldInfo.GetValue(property.serializedObject.targetObject); // need to updated values with Serialization for Undo and Changes SerializedProperty PanOffsetProperty = property.FindPropertyRelative("PanOffset"); SerializedProperty ZoomLevelProperty = property.FindPropertyRelative("ZoomLevel"); SerializedProperty ViewDirectionProperty = property.FindPropertyRelative("ViewDirection"); SerializedProperty ViewRightProperty = property.FindPropertyRelative("ViewRightDirection"); SerializedProperty ViewUpProperty = property.FindPropertyRelative("ViewUpDirection"); SerializedProperty RenderWidthProperty = property.FindPropertyRelative("RenderWidth"); SerializedProperty RenderHeightProperty = property.FindPropertyRelative("RenderHeight"); mouseOverTexture = texRect.Contains(Event.current.mousePosition); if (mouseOverTexture && (Event.current.type == EventType.MouseDrag)) { // do pan if the control key is pressed if (Event.current.control) { Vector2 panOffset = PanOffsetProperty.vector2Value; panOffset.x += Event.current.delta.x * panSpeed; panOffset.y += Event.current.delta.y * panSpeed; PanOffsetProperty.vector2Value = panOffset; } else if (Event.current.shift) { float newZoom = previewGenerator.ZoomLevel - Event.current.delta.y * zoomSpeed; if (previewGenerator.OrthographicCamera) { newZoom = Mathf.Min(.999999f, newZoom); } ZoomLevelProperty.floatValue = newZoom; } else { Vector3 viewDirection = ViewDirectionProperty.vector3Value; viewDirection += ViewRightProperty.vector3Value * (-Event.current.delta.x * rotSpeed * Mathf.Deg2Rad) + ViewUpProperty.vector3Value * (-Event.current.delta.y * rotSpeed * Mathf.Deg2Rad); viewDirection.Normalize(); ViewRightProperty.vector3Value = Vector3.Cross(ViewUpProperty.vector3Value, viewDirection).normalized; // and new up Vector ViewUpProperty.vector3Value = Vector3.Cross(viewDirection, ViewRightProperty.vector3Value).normalized; ViewDirectionProperty.vector3Value = viewDirection; } if ((previewGenerator != null) && (previewGenerator.GameObjectToRender != null)) { // allows high frame rate in inspector previewGenerator.bRepaintNeeded = true; } return; } if ((Event.current.type == EventType.ValidateCommand) && (Event.current.commandName == "UndoRedoPerformed")) { if ((previewGenerator != null) && (previewGenerator.GameObjectToRender != null)) { previewGenerator.bRepaintNeeded = true; } return; } // should we only do this during layout and paint events? EditorGUI.BeginChangeCheck(); { if (property.hasVisibleChildren) { property.NextVisible(true); do { EditorGUILayout.PropertyField(property, true); } while (property.NextVisible(false)); } } if (EditorGUI.EndChangeCheck()) { // do these outside the drag, since the user may have added new entries manually ViewDirectionProperty.vector3Value.Normalize(); // get new right Vector ViewRightProperty.vector3Value = Vector3.Cross(ViewUpProperty.vector3Value.normalized, ViewDirectionProperty.vector3Value); // and new up Vector ViewUpProperty.vector3Value = Vector3.Cross(ViewDirectionProperty.vector3Value, ViewRightProperty.vector3Value.normalized); // This can happen when the user is editing the View Direction with keyboard. if (ViewUpProperty.vector3Value == Vector3.zero) { ViewUpProperty.vector3Value = Vector3.up; } if (previewGenerator.OrthographicCamera) { ZoomLevelProperty.floatValue = Mathf.Min(.999999f, ZoomLevelProperty.floatValue); } RenderWidthProperty.intValue = Mathf.Min(Mathf.Max(RenderWidthProperty.intValue, MinTextureSize), MaxTextureSize); RenderHeightProperty.intValue = Mathf.Min(Mathf.Max(RenderHeightProperty.intValue, MinTextureSize), MaxTextureSize); previewGenerator.bRepaintNeeded = true; } if ((previewGenerator != null) && (previewGenerator.GameObjectToRender != null) && (Event.current.type == EventType.Repaint) && previewGenerator.bRepaintNeeded) { previewGenerator.RenderPreviewTexture(); previewGenerator.bRepaintNeeded = false; } Texture2D previewTexture = previewGenerator.PreviewTexture; EditorGUILayout.Space(); if (GUILayout.Button(" Save PNG... ", GUILayout.ExpandWidth(false))) { string path = Path.GetDirectoryName(previewGenerator.LastPNGPathName); string filename = Path.GetFileName(previewGenerator.LastPNGPathName); path = EditorUtility.SaveFilePanel("Save Texture as PNG", path, filename, "png"); if (path.Length != 0) { previewGenerator.SavePNG(path); } } EditorGUILayout.Space(); float boxHeight = Mathf.Min(EditorGUIUtility.currentViewWidth - 36, previewGenerator.RenderHeight); GUILayout.Box(previewTexture, GUILayout.Height(boxHeight), GUILayout.Width(EditorGUIUtility.currentViewWidth - 36)); if (Event.current.type == EventType.Repaint) { texRect = GUILayoutUtility.GetLastRect(); } EditorGUILayout.Space(); } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0.0f; } } [CustomPropertyDrawer(typeof(AnimationClipInfo), true)] public class AnimationClipInfoDrawer : PropertyDrawer { // Draw the property inside the given rect public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty animClipProperty = property.FindPropertyRelative("AnimationClip"); SerializedProperty positionProperty = property.FindPropertyRelative("PositionInClip"); AnimationClip animClip = null; if (animClipProperty.objectReferenceValue != null) { if (animClipProperty.objectReferenceValue.GetType() == typeof(AnimationClip)) { animClip = (AnimationClip) animClipProperty.objectReferenceValue; } } float positionInClip = positionProperty.floatValue; EditorGUILayout.Space(); EditorGUILayout.PropertyField(animClipProperty); if (animClip != null) { FontStyle origFontStyle = EditorStyles.label.fontStyle; if (positionProperty.prefabOverride) { EditorStyles.label.fontStyle = FontStyle.Bold; } // render slider for clip animation length positionInClip = EditorGUILayout.Slider("Animation Position", positionInClip, 0.0f, animClip.length); EditorStyles.label.fontStyle = origFontStyle; positionProperty.floatValue = positionInClip; GUILayout.BeginHorizontal(); var defaultAlignment = GUI.skin.label.alignment; EditorGUILayout.PrefixLabel(" "); GUILayout.Label("0"); GUI.skin.label.alignment = TextAnchor.UpperRight; GUILayout.Label(animClip.length.ToString("F3") + " "); GUI.skin.label.alignment = defaultAlignment; GUILayout.EndHorizontal(); } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0.0f; } } [CustomPropertyDrawer(typeof(BackgroundColorOrTextureInfo), true)] public class BackgroundColorOrTextureInfoDrawer : PropertyDrawer { private bool backgroundFoldOut = true; // Draw the property inside the given rect public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { SerializedProperty BackgroundTypeProperty = property.FindPropertyRelative("backType"); SerializedProperty BackgroundColorProperty = property.FindPropertyRelative("BackgroundColor"); SerializedProperty BackgroundTextureProperty = property.FindPropertyRelative("BackgroundTexture"); SerializedProperty UseBackgroundAlphaProperty = property.FindPropertyRelative("UseBackgroundAlpha"); backgroundFoldOut = EditorGUILayout.Foldout(backgroundFoldOut, "Background Type"); if (backgroundFoldOut) { EditorGUI.indentLevel++; // make selection transparent background BackgroundTextureTypes selGridInt = (BackgroundTextureTypes) BackgroundTypeProperty.enumValueIndex; FontStyle origFontStyle = EditorStyles.label.fontStyle; if (BackgroundTypeProperty.prefabOverride) { EditorStyles.label.fontStyle = FontStyle.Bold; } if (EditorGUILayout.Toggle("Use Transparent Background", (selGridInt == BackgroundTextureTypes.Transparent))) { selGridInt = BackgroundTextureTypes.Transparent; } if (EditorGUILayout.Toggle("Use Color Background", (selGridInt == BackgroundTextureTypes.Color))) { selGridInt = BackgroundTextureTypes.Color; } if (EditorGUILayout.Toggle("Use Texture Background", (selGridInt == BackgroundTextureTypes.Texture))) { selGridInt = BackgroundTextureTypes.Texture; } EditorStyles.label.fontStyle = origFontStyle; BackgroundTypeProperty.enumValueIndex = (int) selGridInt; EditorGUI.BeginDisabledGroup(selGridInt != BackgroundTextureTypes.Color); EditorGUILayout.PropertyField(BackgroundColorProperty); EditorGUI.EndDisabledGroup(); EditorGUI.BeginDisabledGroup(selGridInt != BackgroundTextureTypes.Texture); EditorGUILayout.PropertyField(BackgroundTextureProperty); EditorGUILayout.PropertyField(UseBackgroundAlphaProperty); EditorGUI.EndDisabledGroup(); EditorGUI.indentLevel--; } } public override float GetPropertyHeight(SerializedProperty property, GUIContent label) { return 0.0f; } }
6e91017ab113b7e1887faa2c785d65f3726b2e41
[ "Markdown", "C#", "Shell" ]
6
Markdown
Super-Genius/UnityPreviewGenerator
4c1b28c514bd76e72c0f02017bad8c4d7718aca3
a2ab8bb55e6a43272b4b590fc7e0bb5587b6c676
refs/heads/master
<file_sep><?php if ( !defined('ABSPATH') ) {exit;} /** * Data structure exposer * * Displays the data structure for any supplied value * * @param mixed $var * @access public * @return string */ if ( ! function_exists('print_pre')) { function print_pre($var, $return=false) { $retval = '<pre>'.print_r($var, true).'</pre>'; if ($return) { return $retval; } else { echo $retval; } } }<file_sep><?php if ( !defined('ABSPATH') ) {exit;} ?> <div class="gwaccat"> <?php foreach ($catlist as $cat): ?> <div class="gwaccat-cat"> <div class="gwaccat-cat-header"> <div class="gwaccat-icon">+</div> <?=$cat->name?> </div> <div class="gwaccat-cat-body<?php if ($cat->slug == $startingcat) echo ' gwaccat-cat-start';?>"> <?php if ($cat->posts): ?> <?php foreach ($cat->posts as $post): ?> <div class="gwaccat-cat-body-post"> <?php if ($hideposttitle != 'yes'): ?> <div class="gwaccat-post-title"><?=$post->post_title?></div> <?php endif; ?> <div class="gwaccat-post-body"><?=$post->post_content?></div> </div> <?php endforeach; ?> <?php endif; ?> </div> </div> <?php endforeach; ?> </div><file_sep>GW Accorian Cat =============== <h2>Description</h2> <p> This Wordpress plugin allows a user to create an accordion display of categories and posts using a short tag on their page or post. </p> <h2>Setup</h2> <p> create a posts category that will be used as the parent for all categories in the display. It there is a different accordion for different pages, you will want to create a separate categories for each page. </p> <p> Place subcategories under the created parent. These will be the different accordion sections </p> <p> Attach posts to the proper categories in the accordions. </p> <h2>Short Tag</h2> <p> <code>[accordioncat cat="parent_category"]</code> </p> <h2>Required Parameters</h2> <p> <strong>cat</strong> - contains the slug for the parent category </p> <h2>Optional Parameters</h2> <p> <strong>startingcat</strong> - the slug of the category that will start up open on the first load. The default is all closed. </p> <p> <strong>sortorder</strong> - this can be any of the following category fields: 'id', 'name', 'slug', 'count', 'term_group'. Default is 'slug' . </p> <p> <strong>order</strong> - 'asc' for acceding order or 'desc' for descending order. Default is 'asc'. </p> <p> <strong>hideposttitle</strong> - Hides the post title. Valid values are 'yes' and 'no'. Default is 'no'. </p> <p> <strong>debug</strong> - if set to "true" will dump the entire accordion data structure. to the page (all category and post object elements) </p> <h2>Examples</h2> <p> To create an accordion with a parent category of 'mystuff' that starts with the sub-category 'openingcat' open, use: </p> <p> <code>[accordioncat cat="parent_category" startingcat="openingcat"]</code> </p> <p> To create an accordion with a parent category of 'mystuff' that starts with the sub-category 'openingcat' open and is sorted by name, use: </p> <p> <code>[accordioncat cat="parent_category" startingcat="openingcat" sortorder="name"]</code> </p> <file_sep> (function ($) { $(document).ready(function () { $('.gwaccat-cat-body').hide(); $('.gwaccat-cat-start').closest('.gwaccat-cat').find('.gwaccat-icon').html('-'); $('.gwaccat-cat-start').show(); $('.gwaccat-cat-header').on('click', function () { var $tbody = $(this).closest('.gwaccat-cat').find('.gwaccat-cat-body'); var $icon = $(this).closest('.gwaccat-cat').find('.gwaccat-icon'); if ($tbody.css('display') == 'none') { $icon.html('-'); } else { $icon.html('+'); } $tbody.toggle(100); }); }); })(jQuery);<file_sep><?php if ( !defined('ABSPATH') ) {exit;} /** * @package GWAccordionCat */ /* Plugin Name: GW Accordion Cat Description: A plugin to create an accordion of categories with a shortcode Version: 1.3 Author: <NAME> (Grayworld Media) Author URI: http://grayworld.com */ require_once(dirname(__FILE__).'/functions.php'); define('GWACCAT_URL', plugins_url('/gw-accordion-cat')); /** * GW Accordion Cat Plugin Class */ class gw_accordion_cat { /** * Constructor */ public function __construct() { if (!is_admin()) { $theme_style_path = get_stylesheet_directory() . '/gwaccat.css'; $theme_style_uri = dirname(get_stylesheet_uri()) . '/gwaccat.css'; wp_enqueue_script('gwaccordioncat', GWACCAT_URL . '/script.js', array('jquery'), '1.0', false); if (file_exists($theme_style_path)) { wp_enqueue_style('gwaccordioncat', $theme_style_uri, false, '1.0'); } else { wp_enqueue_style('gwaccordioncat', GWACCAT_URL . '/gwaccat.css', false, '1.0'); } add_shortcode( 'accordioncat', array($this, 'shortcode_gwaccordioncat') ); } } /** * Shortcode Processor ( accordioncat ) * * @param array $atts - attributes supplied by shorttag call * @return string - html to insert where shorttag is placed */ public function shortcode_gwaccordioncat( $atts ) { extract( shortcode_atts( array( 'cat' => 'uncategorized', 'startingcat' => 'none', 'orderby' => 'slug', 'order' => 'asc', 'hideposttitle' => 'no', 'hidepostimage' => 'no', 'debug' => 'false' ), $atts ) ); // get target cat $parent_cat = get_category_by_slug( $cat ); // load subcats $catlist = get_categories( array( 'child_of' => $parent_cat->cat_ID, 'orderby' => $orderby, 'order' => $order, 'hierarchical' => 0 )); // attache post list for ($key=0; $key < count($catlist); $key++) { if ($catlist[$key]) { $catlist[$key]->posts = get_posts(array( 'cat' => $catlist[$key]->cat_ID )); } } // build html response ob_start(); if ($debug == 'true') print_pre($catlist); include(dirname(__FILE__).'/template.php'); return ob_get_clean(); } } new gw_accordion_cat();
3e6d32a79eac9e957dabdff384ed2bd5288e14de
[ "Markdown", "JavaScript", "PHP" ]
5
PHP
graytech/gw-accordion-cat
e8f5a0b435285d5f0d4e924fec033edfb9e2af36
bc356b7706ec94ff72f5d680c071590a2ac5276d
refs/heads/master
<file_sep>package DbleLoop; public class pattern4 { public static void main(String[] args) { int i, a=1, j; for(i=a; i<5; i++) { for(j=1;j<i; j++) { System.out.print(a +" "); a++; } System.out.println(a); a++; } } } <file_sep>package DbleLoop; public class pattern1 { public static void main(String[] args) { int i, j; for(i=5; i>0; i--) { for(j=i;j>1; j--) { System.out.print("*"); } System.out.println("*"); } } }
de53187421c9990e04da995e7fed9aeaf3b329fe
[ "Java" ]
2
Java
nrjsharma097/sharman
95656452779729ad016139543b07f7ada4eb1ad7
2330a98251cd41351134cf89b64fbb6a0825f61a
refs/heads/master
<file_sep># DevBoot API > backend API for the DevBoot application which is a coding/development bootcamp directory website ## Usage Rename "config/config.env.env to config/config.env and update the values/settings to your own ## Install Dependencies ``` npm install ``` ## Run App ``` # Run in dev mode npm run dev # Run in prod mode npm start ``` - Version 1.00 - License: MIT <file_sep>const Bootcamp = require('../models/Bootcamp') const ErrorResponse = require('../utils/errorResponse') const asyncHandler = require('../middleware/async') const geocoder = require('../utils/geocoder') const path = require('path') const advancedResults = require('../middleware/advancedResults') //@desc Get all bootcamps //@route GET /api/v1/bootcamps //@access public // exports.getBootcamps = async (req, res, next) => { // // res.json({ name: 'Jules' }) // //send status // //res.sendStatus(400) // //send status and json object with success message // // res.status(400).json({ success: false }) // //send status 200 and data // // res.status(200).json({ success: true, data: { id: 1 } }) // // res.status(200).json({ success: true, msg: 'list all bootcamps' }) // try { // const bootcamps = await Bootcamp.find() // res.status(200).json({ // success: true, // count: bootcamps.length, // data: bootcamps // }) // } catch (error) { // // res.status(400).json({ // // success: false // // }) // next(error) // } // } exports.getBootcamps = asyncHandler(async (req, res, next) => { //console url parameters // console.log("req.query is: ", req.query) res.status(200).json(res.advancedResults) }) //@desc Get one bootcamp //@route GET /api/v1/bootcamps/:id //@access public exports.getBootcamp = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.findById(req.params.id); if (!bootcamp) { return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exist`, 404)) } res.status(200).json({ success: true, data: bootcamp }) }) // exports.getBootcamp = async (req, res, next) => { // try { // const bootcamp = await Bootcamp.findById(req.params.id); // if (!bootcamp) { // return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exists`, 404)) // } // res.status(200).json({ // success: true, // data: bootcamp // }) // } catch (error) { // // res.status(400).json({ // // success: false // // }) // // next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exist`, 404)) // next(error) // } // // res.status(200).json({ success: true, msg: `get bootcamp ${req.params.id}` }) // } //@desc create bootcamp //@route POST /api/v1/bootcamps //@access public exports.createBootcamp = asyncHandler(async (req, res, next) => { //add user to req.body req.body.user = req.user.id //check for published bootcamp const publishedBootcamp = await Bootcamp.findOne({ user: req.user.id }) //if user is not admin, they can only add one bootcamp if (publishedBootcamp && req.user.role !== 'admin') { return next(new ErrorResponse(`user with ID ${req.user.id} has already published a bootcamp`, 400)) } const newBootcamp = await Bootcamp.create(req.body) res.status(201).json({ success: true, data: newBootcamp }) }) // exports.createBootcamp = async (req, res, next) => { // try { // const newBootcamp = await Bootcamp.create(req.body) // res.status(201).json({ // success: true, // data: newBootcamp // }) // } catch (error) { // // res.status(400).json({ // // success: false // // }) // next(error) // } // } //@desc update bootcamp //@route PUT /api/v1/bootcamps/:id //@access public exports.updateBootcamp = asyncHandler(async (req, res, next) => { // const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body, { // new: true, // runValidators: true // }) let bootcamp = await Bootcamp.findById(req.params.id) if (!bootcamp) { return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exists`, 404)) } //check if user is bootcamp owner. if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') { return next(new ErrorResponse(`user with id ${req.user.id} not authorized to update this bootcamp`, 401)) } bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.bodu, { new: true, runValidators: true }) res.status(200).json({ success: true, data: bootcamp }) }) // exports.updateBootcamp = async (req, res, next) => { // // res.status(200).json({ success: true, msg: `update bootcamp ${req.params.id}` }) // try { // const bootcamp = await Bootcamp.findByIdAndUpdate(req.params.id, req.body, { // new: true, // runValidators: true // }) // if (!bootcamp) { // return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exists`, 404)) // } // res.status(200).json({ // success: true, data: bootcamp // }) // } catch (error) { // // res.status(400).json({ // // success: false // // }) // next(error) // } // } //@desc delete bootcamp //@route DELETE /api/v1/bootcamps/:id //@access public exports.deleteBootcamp = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.findById(req.params.id) if (!bootcamp) { return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exists`, 404)) } //check if user is bootcamp owner. if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') { return next(new ErrorResponse(`user with id ${req.user.id} not authorized to delete this bootcamp`, 401)) } //this method will trigger the pre.remove middleware in models/Bootcamp bootcamp.remove(); res.status(200).json({ success: true, data: {} }) }) // exports.deleteBootcamp = async (req, res, next) => { // // res.status(200).json({ success: true, msg: `delete bootcamp ${req.params.id}` }) // try { // const bootcamp = await Bootcamp.findByIdAndDelete(req.params.id) // if (!bootcamp) { // return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exists`, 404)) // } // res.status(200).json({ // success: true, data: {} // }) // } catch (error) { // // res.status(400).json({ // // success: false // // }) // next(error) // } // } //@desc get bootcamps within address radius //@route GET /api/v1/bootcamps/radius/:zipcode/:distance //@access public exports.getBootcampsInRadius = asyncHandler(async (req, res, next) => { const { zipcode, distance } = req.params; //get latitude and longitude from node-geocoder const place = await geocoder.geocode(zipcode); const latitude = place[0].latitude; const longitude = place[0].longitude; //calculate the radius //divide distance by Earth radius: 3,963 miles (6378 km) const radius = distance / 6378 const bootcamps = await Bootcamp.find({ location: { $geoWithin: { $centerSphere: [[longitude, latitude], radius] } } }); res.status(200).json({ success: true, count: bootcamps.length, data: bootcamps }) }) //@desc upload photo to bootcamp //@route PUT /api/v1/bootcamps/:id/photo //@access public exports.bootcampPhotoUpload = asyncHandler(async (req, res, next) => { const bootcamp = await Bootcamp.findById(req.params.id) if (!bootcamp) { return next(new ErrorResponse(`bootcamp with id ${req.params.id} does not exists`, 404)) } //check if user is bootcamp owner. if (bootcamp.user.toString() !== req.user.id && req.user.role !== 'admin') { return next(new ErrorResponse(`user with id ${req.user.id} not authorized to update this bootcamp`, 401)) } if (!req.files) { return next( new ErrorResponse('please upload a photo', 400) ) } // console.log(req.files.file) const file = req.files.file //make sure file is photo type if (!file.mimetype.startsWith('image')) { return next( new ErrorResponse('please upload an image file', 400) ) } //check file size if (file.size > process.env.MAX_FILE_UPLOAD) { return next( new ErrorResponse(`please upload an image size less than ${process.env.MAX_FILE_UPLOAD} `, 400) ) } //create custom filename file.name = `photo_${bootcamp._id}${path.parse(file.name).ext}` // console.log('filename is: ', file.name) file.mv(`${process.env.FILE_UPLOAD_PATH}/${file.name}`, async err => { if (err) { console.error(err) return next( new ErrorResponse(`problem with file upload`, 500) ) } await Bootcamp.findByIdAndUpdate(req.params.id, { photo: file.name }) res.status(200).json({ success: true, data: file.name }) }) })
19b8def52bb9b58a515c639ac119453333da9be9
[ "Markdown", "JavaScript" ]
2
Markdown
juleskulcsar/devboot-api
e0463c7ac4f4092b23f2dd3fe33066e13f6d0a35
a6e1131a52c9f75a17cc09539ffaeb211e0a7238
refs/heads/master
<repo_name>ashishmohanty/tinyUrl<file_sep>/src/test/java/org/zycus/tinyurl/service/TinyUrlServiceImplTest.java package org.zycus.tinyurl.service; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.zycus.tinyurl.dao.TinyUrlDao; @RunWith(MockitoJUnitRunner.class) public class TinyUrlServiceImplTest { @Mock private TinyUrlDao tinyUrlDao; @InjectMocks private TinyUrlServiceImpl tinyUrlServiceImpl; @Before public void setUp() throws Exception { } @Test public void testCreateTinyUrl() throws Exception { throw new RuntimeException("not yet implemented"); } } <file_sep>/README.md # tinyUrl This Project gives the complete description of how to create tiny url for concurrent users <file_sep>/src/main/java/org/zycus/tinyurl/TinyUrlApplication.java package org.zycus.tinyurl; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication public class TinyUrlApplication { public static void main(String[] args) { SpringApplication.run(TinyUrlApplication.class, args); } } <file_sep>/src/main/java/org/zycus/tinyurl/service/TinyUrlServiceImpl.java package org.zycus.tinyurl.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.zycus.tinyurl.converter.IDConverter; import org.zycus.tinyurl.dao.TinyUrlDao; @Service public class TinyUrlServiceImpl implements TinyUrlService { @Autowired private TinyUrlDao urlRepository; private static final Logger LOGGER = LoggerFactory .getLogger(TinyUrlServiceImpl.class); @Override public String shortenURL(String localURL, String longUrl) { LOGGER.info("Shortening {}", longUrl); Long id = urlRepository.incrementID(); String uniqueID = IDConverter.INSTANCE.createUniqueID(id); urlRepository.saveUrl("url:" + id, longUrl); String baseString = formatLocalURLFromShortener(localURL); String shortenedURL = baseString + uniqueID; return shortenedURL; } @Override public String getLongURLFromID(String uniqueID) throws Exception { Long dictionaryKey = IDConverter.INSTANCE .getDictionaryKeyFromUniqueID(uniqueID); String longUrl = urlRepository.getUrl(dictionaryKey); LOGGER.info("Converting shortened URL back to {}", longUrl); return longUrl; } private String formatLocalURLFromShortener(String localURL) { String[] addressComponents = localURL.split("/"); StringBuilder sb = new StringBuilder(); for (int i = 0; i < addressComponents.length - 1; ++i) { sb.append(addressComponents[i]); } sb.append('/'); return sb.toString(); } }<file_sep>/src/test/java/org/zycus/tinyurl/dao/TinyUrlDaoImplTest.java package org.zycus.tinyurl.dao; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.runners.MockitoJUnitRunner; @RunWith(MockitoJUnitRunner.class) public class TinyUrlDaoImplTest { @InjectMocks private TinyUrlDaoImpl tinyUrlDaoImpl; @Before public void setUp() throws Exception { } @Test public void testCreateTinyUrl() throws Exception { throw new RuntimeException("not yet implemented"); } } <file_sep>/src/main/java/org/zycus/tinyurl/resource/TinyUrlResource.java package org.zycus.tinyurl.resource; import java.io.IOException; import java.net.URISyntaxException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.servlet.view.RedirectView; import org.zycus.tinyurl.model.ShortenRequest; import org.zycus.tinyurl.service.TinyUrlService; import org.zycus.tinyurl.validator.URLValidator; @RestController public class TinyUrlResource { private static final Logger LOGGER = LoggerFactory .getLogger(TinyUrlResource.class); @Autowired private TinyUrlService urlConverterService; @RequestMapping(value = "/shortener", method = RequestMethod.POST, consumes = { "application/json" }) public String shortenUrl( @RequestBody @Valid final ShortenRequest shortenRequest, HttpServletRequest request) throws Exception { LOGGER.info("Received url to shorten: " + shortenRequest.getUrl()); String longUrl = shortenRequest.getUrl(); if (URLValidator.INSTANCE.validateURL(longUrl)) { String localURL = request.getRequestURL().toString(); String shortenedUrl = urlConverterService.shortenURL(localURL, shortenRequest.getUrl()); LOGGER.info("Shortened url to: " + shortenedUrl); return shortenedUrl; } throw new Exception("Please enter a valid URL"); } @RequestMapping(value = "/{id}", method = RequestMethod.GET) public RedirectView redirectUrl(@PathVariable String id, HttpServletRequest request, HttpServletResponse response) throws IOException, URISyntaxException, Exception { LOGGER.debug("Received shortened url to redirect: " + id); String redirectUrlString = urlConverterService.getLongURLFromID(id); RedirectView redirectView = new RedirectView(); redirectView.setUrl("http://" + redirectUrlString); return redirectView; } }<file_sep>/src/test/java/org/zycus/tinyurl/resource/TinyUrlResourceTest.java package org.zycus.tinyurl.resource; import org.junit.Before; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.runners.MockitoJUnitRunner; import org.zycus.tinyurl.service.TinyUrlService; @RunWith(MockitoJUnitRunner.class) public class TinyUrlResourceTest { @Mock private TinyUrlService tinyUrlService; @InjectMocks private TinyUrlResource tinyUrlResource; @Before public void setUp() throws Exception { //Mockito.initMocks(); } }
206920b8c68d68641cb29b8c3405bf0b02ca1e64
[ "Markdown", "Java" ]
7
Java
ashishmohanty/tinyUrl
461fed99ed0e515f0094b30532f50dc927bdf148
523883e5ed0d494810a5de83bdc88a529fb4c1d8
refs/heads/master
<repo_name>Anargts09/riot-weather-widget<file_sep>/README.md # Riot Weather Widget <file_sep>/js/main.js var weatherIcons; var cityNames; var selected_c = 26; function getLocalJson(){ fetch('src/icons.json').then(function(res) { return res.json(); }) .then(function(data) { weatherIcons = data; riot.mixin('weatherIcons', { bodyMixin: weatherIcons }); }) } function getCitiesJson(){ fetch('src/cities.json').then(function(res) { return res.json(); }) .then(function(data) { cityNames = data; riot.mixin('cityNames', { bodyMixin: cityNames }); }) } function dayConverter(UNIX_timestamp){ var a = new Date(UNIX_timestamp * 1000); var getDay = ['Ням','Даваа','Мягмар','Лхагва','Пүрэв','Баасан','Бямба']; var week = getDay[a.getDay()]; return week; } function timeConverter(UNIX_timestamp){ var a = new Date(UNIX_timestamp * 1000); var months = ['1 сар','2 сар','3 сар','4 сар','5 сар','6 сар','7 сар','8 сар','9 сар','10 сар','11 сар','12 сар']; var year = a.getFullYear(); var month = months[a.getMonth()]; var date = a.getDate(); // var hour = a.getHours(); // var min = a.getMinutes(); // var sec = a.getSeconds(); // var time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ; var time = month + ' ' + date + ' өдөр'; return time; }
98dca547a8aa764fbb0513c249f3dbb086739066
[ "Markdown", "JavaScript" ]
2
Markdown
Anargts09/riot-weather-widget
8d11f38db4d4df8f6d7c12b5605fa82e52c41959
6e9f72a4ffe8a64c9abb14b633a3c8e1f70ac92f
refs/heads/master
<file_sep>Este trabalho é sobre Dropdown<file_sep>ESTE É UM MODAL.<file_sep>function mudaImagem(){ document.getElementById('muda').src='imagens/img6.png'; } function voltarImg(){ document.getElementById('muda').src='imagens/imagem2.jpg'; }
578bcc27c1a4152d2efb1e143f4d92747ec9c3d6
[ "Markdown", "JavaScript" ]
3
Markdown
camilafoo/components-ui
9ea2a49b6f8024efd384b7d389d4f66fb1ddb37b
5ae574f223b8d3c1cba52ff87bb2efa67a5f2d35
refs/heads/master
<file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int num=0; printf("Digite um numero:"); scanf("%i",&num); printf("%i",num+1); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n1, n2, n3, n4, par=0; printf("Digite 4 numeros:"); scanf("%i %i %i %i",&n1,&n2,&n3,&n4); if(n1%2!=0){ n1=0; } if(n2%2!=0){ n2=0; } if(n3%2!=0){ n3=0; } if(n4%2!=0){ n4=0; } par=n1+n2+n3+n4; printf("A soma dos numeros pares eh %i",par); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { float anos, cigarros, preco, reais; printf("Quantos anos faz que voce fuma?"); scanf("%f",&anos); printf("Quantos cigarros voce fuma por dia?"); scanf("%f",&cigarros); printf("Qual eh o preco da carteira de cigarros?"); scanf("%f",&preco); reais=(((cigarros*preco)/20)*(anos*365)); printf("Voce gasta RS %.2f por ano em cigarro",reais); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n1,n2,n3, media=0; printf("Qual foi a sua nota nas 3 ultimas provas?"); scanf("%i %i %i",&n1, &n2, &n3); media=(n1+n2+n3)/3; if(media>=70){ printf("Aprovado"); } else{ if((media>=50)&&(media<70)){ printf("Recuperacao"); } else{ if(media<50){ printf("Reprovado"); } } } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n1, n2, n3, soma=0; printf("Digite 3 numeros:"); scanf("%i %i %i",&n1,&n2,&n3); soma=n2+n3; if(n1>soma){ printf("O primeiro numero eh maior que a soma dos outros dois"); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int num=0; printf("Digite um numero:"); scanf("%i",&num); if(num%2==0){ printf("Eh par"); } if(num%2!=0){ printf("Eh impar"); } return 0; } <file_sep> #include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n1, n2=0; printf("Digite 2 numeros:"); scanf("%i %i",&n1,&n2); printf("O quociente da divisao desses numeros eh %i \nO resto da divisao sera %i",n1/n2,n1%n2); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n1, n2, n3, maior, menor=0; printf("Digite 3 numeros:"); scanf("%i %i %i",&n1,&n2,&n3); maior=n1; menor=n1; if(n2>maior){ maior=n2; } if(n2<menor){ menor=n2; } if(n3>maior){ maior=n3; } if(n3<menor){ menor=n3; } printf("O maior eh %i e o menor eh %i",maior,menor); return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int n1, n2, n3=0; printf("Digite 3 numeros:"); scanf("%i %i %i",&n1,&n2,&n3); if((n1>=n2)&&(n1>=n3)&&(n2>=n3)){ printf("%i\n%i\n%i",n3,n2,n1); } if((n2>=n1)&&(n2>=n3)&&(n1>=n3)){ printf("%i\n%i\n%i",n3,n1,n2); } if((n3>=n2)&&(n3>=n1)&&(n2>=n1)){ printf("%i\n%i\n%i",n1,n2,n3); } if((n1>=n2)&&(n1>=n3)&&(n3>=n2)){ printf("%i\n%i\n%i",n2,n3,n1); } if((n2>=n1)&&(n2>=n3)&&(n3>=n1)){ printf("%i\n%i\n%i",n1,n3,n2); } if((n3>=n2)&&(n3>=n1)&&(n1>=n2)){ printf("%i\n%i\n%i",n2,n1,n3); } return 0; } <file_sep>#include <stdio.h> #include <stdlib.h> /* run this program using the console pauser or add your own getch, system("pause") or input loop */ int main(int argc, char *argv[]) { int abril=0; printf("Digite um dia do mes de Abril:"); scanf("%i",&abril); if((abril==5)||(abril==6)||(abril==12)||(abril==13)||(abril==19)||(abril==20)||(abril==26)||(abril==27)){ printf("O dia eh um final de semana"); } else{ if((abril==1)||(abril==18)||((abril>=20)&&(abril<=23))){ printf("O dia eh um feriado"); } else{ if((abril!=5)||(abril!=6)||(abril!=12)||(abril!=13)||(abril!=19)||(abril!=20)||(abril!=26)||(abril!=27)){ printf("O dia eh um dia util"); } } } return 0; }
7f9175bccb276d28c6b1bebd362aa9ebeeeae60f
[ "C" ]
10
C
LeonardoRamin/Trabalho-de-programacao
ae1149219512fbc95b7a775a47c6f6749c1301a7
ca21cb1016e39737aa8969f2b8a9edf777bc5973
refs/heads/master
<file_sep>//--------------------------------------------------------------------------- #include <iostream> #include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #include "epanet2.h" //--------------------------------------------------------------------------- void ReadFloatFile(char file[], float data[]) { int cont=0; int pos=0; float value; FILE * pFile; char mystring [100]; char * pch; pFile = fopen (file , "r"); if (pFile == NULL) perror ("Error opening file"); else { while (!feof(pFile)) { fgets (mystring , 100 , pFile); pch = strtok (mystring," ;\t\n\r"); if(pch == NULL) continue; else cont++; } } fclose (pFile); pFile = fopen (file , "r"); if (pFile == NULL) perror ("Error opening file"); else { while (!feof(pFile)) { fgets (mystring , 100 , pFile); pch = strtok (mystring," ;\t\n\r"); if(pch == NULL) continue; else { value = atof (pch); data[pos] = value; pos++; } } fclose (pFile); } } void ReadFloatMatrixFile(char file[], float** data, int nrow, int ncol) { int i; int j; FILE * pFile; pFile = fopen (file , "r"); if (pFile == NULL) perror ("Error opening file"); else { for (i = 0; i < nrow; i++) { for (j = 0; j < ncol; j++) { fscanf(pFile, "%f", &data[i][j]); } } fclose (pFile); } } void PrintResults(char* file, char** names, float** values, int num, int timeperiods) { int i; int j; char sep=','; FILE * pFile; pFile = fopen (file,"w"); if (pFile!=NULL) { for(i = 0; i < num; i++) { fprintf(pFile, "%s", names[i]); fprintf(pFile, "%c", sep); } fprintf(pFile, "\n"); for(j = 0; j < timeperiods; j++) { for(i = 0; i < num; i++) { fprintf(pFile, "%f%c", values[i][j], sep); } fprintf(pFile, "\n"); } fclose (pFile); } } int main() { int timeperiods = 24; int nleaks = 4; int i = 0; int j = 0; int k = 0; int l = 0; //Opening EPAnet file char epanet_text_file[20] = "epanet_file.txt"; char epanet_file_name[100]; FILE * pFile; pFile = fopen (epanet_text_file, "r"); fgets (epanet_file_name , 100 , pFile); fclose (pFile); char resumo_file[20] = "resumo.txt"; char blank_file[20] = ""; ENopen (epanet_file_name, resumo_file, blank_file); //Counting the amount of nodes int numnodes=0; ENgetcount(EN_NODECOUNT, &numnodes); numnodes-=1; //we have 1 tank //Counting the amount of pipes int numpipes=0; ENgetcount(EN_LINKCOUNT, &numpipes); //Obtaining the IDs for nodes char **namenodes; namenodes = new char* [numnodes]; for(i = 0; i < numnodes; i++) { namenodes[i] = new char [10]; ENgetnodeid(i+1, namenodes[i]); } //Obtaining the IDs for pipes char **namepipes; namepipes = new char* [numpipes]; for(i = 0; i < numpipes; i++) { namepipes[i] = new char [10]; ENgetlinkid(i+1, namepipes[i]); } //Loading the demand pattern for all nodes float *pat_all; char pat_file[20] = "pattern.txt"; pat_all = new float[timeperiods]; ReadFloatFile(pat_file, pat_all); //Loading the base consumption for all nodes float *cons; //consumption char cons_file[20] = "consumption.txt"; cons = new float[numnodes]; ReadFloatFile(cons_file, cons); //Loading favad_cd for each node float **favad_cd; char favad_cd_file[20] = "favad_cd.txt"; favad_cd = new float* [numnodes]; for(i = 0; i < numnodes; i++) { favad_cd[i] = new float [nleaks]; } ReadFloatMatrixFile(favad_cd_file, favad_cd, numnodes, nleaks); //Loading favad_a for each node float **favad_a; char favad_a_file[20] = "favad_a.txt"; favad_a = new float* [numnodes]; for(i = 0; i < numnodes; i++) { favad_a[i] = new float [nleaks]; } ReadFloatMatrixFile(favad_a_file, favad_a, numnodes, nleaks); //Loading favad_m for each node float **favad_m; char favad_m_file[20] = "favad_m.txt"; favad_m = new float* [numnodes]; for(i = 0; i < numnodes; i++) { favad_m[i] = new float [nleaks]; } ReadFloatMatrixFile(favad_m_file, favad_m, numnodes, nleaks); //Creating the matrix to record the base demand on each iteration float *base; base = new float [numnodes]; //Creating the matrix to record the pressure results on each iteration float **pressure; pressure = new float* [numnodes]; for(i = 0; i < numnodes; i++) { pressure[i] = new float [timeperiods]; for(j = 0; j < timeperiods; j++) { pressure[i][j] = 0; } } //Creating the matrix to record the flow results on each iteration float **flow; flow = new float* [numpipes]; for(i = 0; i < numpipes; i++) { flow[i] = new float [timeperiods]; } //Creating the matrix to record the patterns on each iteration float **pat_new; pat_new = new float* [numnodes]; for(i = 0; i < numnodes; i++) { pat_new[i] = new float [timeperiods]; } //Creating the matrix to record the total demand on each iteration float **tot_dem; tot_dem = new float* [numnodes]; for(i = 0; i < numnodes; i++) { tot_dem[i] = new float [timeperiods]; } //Simulation steps int numsteps = 1000; float leakfraction; float sum; float mean; float p = 0; float q = 0; char press_file[20] = "pressure.csv"; char flow_file[20] = "flow.csv"; char patnew_file[20] = "patresult.csv"; char totdem_file[20] = "demresult.csv"; int hour; long t, tstep; for (k = 0; k <= numsteps + 1; k++) { //Initialization of leak fraction if(k >= numsteps) { leakfraction = 1; } else { leakfraction = (float)k / (float)numsteps; } //Calculating base demands and patterns for(i = 0; i < numnodes; i++) { sum = 0; for(j = 0; j < timeperiods; j++) { if(pressure[i][j]>0) { for(l = 0; l < nleaks; l++) { sum += favad_cd[i][l]*4.429*(favad_a[i][l]*pow(pressure[i][j], 0.5) + favad_m[i][l]*pow(pressure[i][j], 1.5))*leakfraction; } sum += cons[i]*pat_all[j]; } else { sum += cons[i]*pat_all[j] ; } } mean = sum/timeperiods; base[i] = mean; for(j = 0; j < timeperiods; j++) { if(pressure[i][j]>0) { sum = 0; for(l = 0; l < nleaks; l++) { sum += favad_cd[i][l]*4.429*(favad_a[i][l]*pow(pressure[i][j], 0.5) + favad_m[i][l]*pow(pressure[i][j], 1.5))*leakfraction; } sum += cons[i]*pat_all[j]; tot_dem[i][j] = sum; pat_new[i][j] = tot_dem[i][j]/mean; } else { tot_dem[i][j] = cons[i]*pat_all[j]; pat_new[i][j] = tot_dem[i][j]/mean; } } ENsetnodevalue(i+1, EN_BASEDEMAND, base[i]); ENsetpattern(i+1, pat_new[i], timeperiods); } //Runing the simulation and updating pressure values hour = -1; ENopenH(); ENinitH(0); do { ENrunH(&t); if (t%3600==0 && t<86400) { hour += 1; for (i = 1; i <= numnodes; i++) { ENgetnodevalue(i,EN_PRESSURE, &p); pressure[i-1][hour] = p; } for (i = 1; i <= numpipes; i++) { ENgetlinkvalue(i,EN_FLOW, &q); flow[i-1][hour] = q; } } ENnextH(&tstep); } while (tstep > 0); ENcloseH(); } ENclose(); //Printing the results PrintResults(press_file, namenodes, pressure, numnodes, timeperiods); PrintResults(flow_file, namepipes, flow, numpipes, timeperiods); PrintResults(patnew_file, namenodes, pat_new, numnodes, timeperiods); PrintResults(totdem_file, namenodes, tot_dem, numnodes, timeperiods); }
2e823799cb6444988757d88b3e5fc686683c140d
[ "C++" ]
1
C++
HadoukenMS/guardioesdasaguas
87218f079641d257f303b51af09be4fd47d5bdcf
4b687f61fb1c3559c2d1633a0a29c04a87e0ee72
refs/heads/master
<file_sep>// // FactoryExercise.swift // Pattern_FactoryMethod // // Created by MAC on 2/12/20. // Copyright © 2020 MAC. All rights reserved. // import Foundation // список упражнений enum Exersices { case jumping case squarts case run // Running Exersices } // класс генерирующий обьекты на основе синглтона class FactoryExersice { //ссылка на самого себя static let defaultFactory = FactoryExersice() //фабричный метод создающий обьекты по протоколу упражнение(выбор из элементов свича упражнения ) а возвращаем протокол func createExercise(name: Exersices) -> Exersice { switch name { case .squarts: return Squarts() //создаем обьект приседание case .jumping: return Jumping() //создаем обьект прыжки case .run : return Run() // add New class Run } } } <file_sep>// // Run.swift // Pattern_FactoryMethod // // Created by MAC on 2/12/20. // Copyright © 2020 MAC. All rights reserved. // import Foundation class Run: Exersice { var name: String = "Бег" var type: String = "Упражнение для общей нагрузки" func start() { print("Начинаем упражнение \(name)") } func stop() { print("Заканчиваем упражнение \(name)") } } <file_sep>// // Exersice.swift // Pattern_FactoryMethod // // Created by MAC on 2/12/20. // Copyright © 2020 MAC. All rights reserved. // import Foundation protocol Exersice { var name: String {get} var type: String {get} func start() func stop() } <file_sep>// // ViewController.swift // Pattern_FactoryMethod // // Created by MAC on 2/12/20. // Copyright © 2020 MAC. All rights reserved. // import UIKit class ViewController: UIViewController { //массив наших упражнений var arrayExersices = [Exersice]() override func viewDidLoad() { super.viewDidLoad() //вызываем функцию создать упражнение для каждого нужного случая createExercise(exName: .jumping) createExercise(exName: .squarts) createExercise(exName: .run) createExercise(exName: .squarts) //запускаем функцию run runExersices() } //функция создания упражнений func createExercise(exName: Exersices) { //создаем новое упражнение по ссылка на класс фабрика и сохраняем let newExercise = FactoryExersice.defaultFactory.createExercise(name: exName) arrayExersices.append(newExercise) } // условная функция запуска упражнений func runExersices() { for ex in arrayExersices { //вызываем все упражнения по очереди ex.start() ex.stop() } } } <file_sep>// // Jumping.swift // Pattern_FactoryMethod // // Created by MAC on 2/12/20. // Copyright © 2020 MAC. All rights reserved. // import Foundation class Jumping: Exersice { var name: String = "Прыжки" var type: String = "Упражнение для ног" func start() { print("Начинаем упражнение \(name)") } func stop() { print("заканчиваем упражнение \(name)") } }
85ebf2e977b783ddb079fcbc71a195379963edfe
[ "Swift" ]
5
Swift
fedir72/30_FactoryMethod_Patterns
1becc6cc74a78abd388ff34d104e66007778f511
e97f40c0cf37b1e45ff28936af2153f881d8c641
refs/heads/master
<repo_name>Vatsalya-singhi/Cost-Calculation<file_sep>/README.md # React-Native-Cost-Calculation" A simple standalone react native app to convert item weight to cost. App feature - Calculate price for the given weights. ## Setup- 1. Clone/Download project. 2. Install required software - Node,Android Studio,React-native and other libraries if used. 3. Switch to project directory and run 'npm i --save' to install the dependencies 4. Run 'react-native run-android' to either emulate the app on android studio or connect device to run on it. ## Screenshots of the project- #### Home page: ![img1](https://user-images.githubusercontent.com/18024758/51800391-17003e80-2254-11e9-94c6-7a94778224ca.jpeg) ## Output On setting required values the cost is calcuated appropriately. ![img2](https://user-images.githubusercontent.com/18024758/51800412-4f078180-2254-11e9-8538-2b76ef47e14e.jpeg) <file_sep>/App.js /** * Sample React Native App * https://github.com/facebook/react-native * * @format * @flow * @lint-ignore-every XPLATJSCOPYRIGHT1 */ import React, {Component} from 'react'; import {Platform, StyleSheet, Text, View,ScrollView, TouchableOpacity, TextInput} from 'react-native'; type Props = {}; export default class App extends Component<Props> { state = { load: 0, empty: 0, price: 0, totalweight : 0, bagcount : 0, remainder : 0, totalbagcountcost : 0, remainderbagcost : 0, finalcost : 0, //onebagweight : 0 } handleLoad = (text) => { this.setState({ load: Number(text) }) } handleEmpty = (text) => { this.setState({ empty: Number(text) }) } handlePrice = (text) => { this.setState({ price: Number(text) }) } /*handleOneBagWeight = (text) => { this.setState({ onebagweight: Number(text) }) }*/ calculate = (load,empty,price) => { //,onebagweight console.log("check@@check@@check@@check@@check@@checkcheckcheck") if(!load || (load<=0) ){ alert("Please check Load value"); return; } if(!empty || (empty<=0) ){ alert("Please check Empty value"); return; } if(!price || (price<=0) ){ alert("Please check Price value"); return; } /*if(!onebagweight || (onebagweight<=0) ){ alert("Please check Bag Weight value"); return; }*/ if(empty > load){ alert("Empty value greater than load Value"); return; } let actualweight = load - empty; this.setState({ totalweight : actualweight.toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') }); let bagcount = parseInt(actualweight/62); //onebagweight this.setState({ bagcount : bagcount.toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') }); let remainder = Number(actualweight - (bagcount*62)); //onebagweight this.setState({ remainder : remainder }); let cost = (bagcount * price) + (remainder * (price/62)); this.setState({ totalbagcountcost : (bagcount*price).toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') }); this.setState({ remainderbagcost : (remainder * (price/62)).toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') }); this.setState({finalcost : cost.toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') }); alert('Total Price : Rs ' + cost.toFixed(2).replace(/(\d)(?=(\d{2})+\d\.)/g, '$1,') ); } resetButton = ()=>{ this.setState({ load: 0,price : 0 , empty : 0, totalweight : 0, bagcount : 0, remainder : 0, totalbagcountcost : 0, remainderbagcost : 0, finalcost : 0}); console.log(this.state); } render() { return ( <ScrollView scrollEventThrottle={16} > <View style={styles.container}> <ScrollView vertical={true} showsVerticalScrollIndicator={true} > <TextInput style = {styles.input} keyboardType = "numeric" underlineColorAndroid = "transparent" placeholder = "Enter Load Weight" placeholderTextColor = "#9a73ef" autoCapitalize = "none" onChangeText = {this.handleLoad}/> <TextInput style = {styles.input} keyboardType = "numeric" underlineColorAndroid = "transparent" placeholder = "Enter Empty Weight" placeholderTextColor = "#9a73ef" autoCapitalize = "none" onChangeText = {this.handleEmpty}/> <TextInput style = {styles.input} keyboardType = "numeric" underlineColorAndroid = "transparent" placeholder = "Set Price" placeholderTextColor = "#9a73ef" autoCapitalize = "none" onChangeText = {this.handlePrice}/> {/* <TextInput style = {styles.input} keyboardType = "numeric" underlineColorAndroid = "transparent" placeholder = "Enter Weight of one Bags" placeholderTextColor = "#9a73ef" autoCapitalize = "none" onChangeText = {this.handleOneBagWeight}/> */} <View style = {styles.containerInside}> <TouchableOpacity style = {styles.resetButton} onPress = { () => this.resetButton() }> <Text style = {styles.submitButtonText}> Reset </Text> </TouchableOpacity> <TouchableOpacity style = {styles.submitButton} onPress = { () => this.calculate(this.state.load, this.state.empty, this.state.price) //this.state.onebagweight }> <Text style = {styles.submitButtonText}> Calculate </Text> </TouchableOpacity> </View> <View style={styles.containertwo}> <Text style={styles.welcome}>Total Weight : {this.state.totalweight} Kgs</Text> <Text style={styles.welcome}>Total Bags : {this.state.bagcount} => Cost : Rs {this.state.totalbagcountcost}</Text> <Text style={styles.welcome}>Remaining : {this.state.remainder} Kgs => Cost : Rs {this.state.remainderbagcost}</Text> <Text style={styles.welcome}>Total Amount : Rs {this.state.finalcost} </Text> </View> </ScrollView> </View> </ScrollView> ); } } const styles = StyleSheet.create({ container: { paddingTop: 23, flex: 1, flexDirection: 'column', //justifyContent: 'center', //alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, input: { margin: 15, height: 40, borderColor: '#7a42f4', borderWidth: 1 }, submitButton: { backgroundColor: '#7a42f4', justifyContent: 'center', alignItems: 'center', padding: 10, margin: 15, height: 40, width: '40%', }, submitButtonText:{ color: 'white' }, containerInside: { flex: 1, flexDirection: 'row', //justifyContent: 'space-between' }, containertwo: { flex: 1, flexDirection: 'column', alignSelf: 'stretch' //justifyContent: 'space-between' }, resetButton: { backgroundColor: 'red', justifyContent: 'center', alignItems: 'center', padding: 10, margin: 15, height: 40, width: '40%', }, }); <file_sep>/android/settings.gradle rootProject.name = 'costcalc' include ':app'
62f23101a190c250ac549cbeb0f3582fcd3bd13b
[ "Markdown", "JavaScript", "Gradle" ]
3
Markdown
Vatsalya-singhi/Cost-Calculation
4bc8ca7f1ed9a359bd9f50456f3197025b3bf18b
be9473348b9ba61d4d71ec36c584b3accf1881cb
refs/heads/master
<file_sep># Space_Invaders ## Project 1: NAVIGATE THE MARS ROVER Help the Mars Curiosity Rover find the shortest path between two points while avoiding obstacles on the way. <br> **Winner all over India in the Microsoft Mars Colonization Program** <br> [Leaderboard and Further info about program](https://microsoft.acehacker.com/mars/) ## Introduction This is the Javascript based webapp for navigating the mars rover using various pathfinding algorithms. It lets the user visualize route found using various algorithms, add checkpoints along the way, mazes to confuse the rover and drag start, checkpoints and endpoints in real time. ## Features ### Multiple Destinations - Ctrl+ Click on grid cells to add checkpoints. - The agent covers the checkpoints in shortest path order and reaches destination. - Rendering using Travelling salesman algorithm. - Dynamic Rendering of path through just drag and drop The shortest path is dynamically visible if user even after search is over drags the nodes. ![Test Image 1](https://github.com/Akshayakayy/Space_Invaders/blob/master/visual/images/gifs/checkpoints.gif) ![Test Image 1](https://github.com/Akshayakayy/Space_Invaders/blob/master/visual/images/gifs/search.gif) ![Test Image 1](https://github.com/Akshayakayy/Space_Invaders/blob/master/visual/images/gifs/clearall.gif) ### Speed of visualization for pathfinder: Draggable speed control for the Rover ![Test Image 1](https://github.com/Akshayakayy/Space_Invaders/blob/master/visual/images/gifs/speed.gif) ### Mazes of various patterns Implemented various types of mazes using algorithms: - Random Maze - Stair Maze - Dense Recursive Maze - Sparse Recursive Maze ![Test Image 1](https://github.com/Akshayakayy/Space_Invaders/blob/master/visual/images/gifs/maze.gif) ### Searching algorithms: * `AStarFinder` * `BestFirstFinder` * `BreadthFirstFinder` * `DijkstraFinder` * `IDAStarFinder.js` * `JumpPointFinder` * `OrthogonalJumpPointFinder` * `BiAStarFinder` * `BiBestFirstFinder` * `BiBreadthFirstFinder` * `BiDijkstraFinder` * `CollaborativeLearningAgentsFinder` The prefix `Bi` for the last four finders in the above list stands for the bi-directional searching strategy. ### Other features: * Music loop in game * Interactive Guide using SweetAlert * Landing Page * TARS bot to provide instructions to the user ## Running the Project and Local installation: The project is deployed in Azure. You can access it here: https://tathagataraha.z13.web.core.windows.net/ #### Local running: - At first clone the repository: ``git clone https://github.com/Akshayakayy/Space_Invaders`` ``cd Space_Invaders`` - You can open the visual/landing.html to test it in the browser. - For development and changing files in the src folder, follow these steps: `` npm install`` (install the required modules) ``gulp compile && mv lib/pathfinding-browser.min.js visual/lib`` (to compile the src folder) ------ ## Technologies Used * Gulp - We have used gulp to compile the src folder to form a .min.js file * Bootstrap - We have used Bootstrap for decoration of the UI. * Sweetalert - Sweetalert is mainly used for the guide and showing the stats in the end. * Raphael - Raphael is used for generating the grid on which the whole thing happens. * Npm - It is used for using node modules. * Git - It is used for version control. * HTML, CSS, JS and other basic web dev tools are used to write the whole project. ## Project Layout ------------ Layout: * [lib](./lib) ` browser distribution ` * [src](./src) ` source code (algorithms only) ` * [core](./src/core) ` includes grid, node layout with heuristics and utils ` * [finders](./src/finders) ` includes searching algorithms` * [mazes](./src/mazes) `includes maze algorithms` * [visual](./visual) `visualization` * [css](./visual/css) `css libraries` * [error404](./visual/error404) `http 404 error page` * [images](./visual/images) `static images and gifs` * [js](./visual/js) `js libraries for agent control and visualization` ## Programming Paradigm: Object-Oriented Programming #### Classes * Agent Our agent is defined in the visual/js/agent.js file. Based on the user inputs from the panel and the grid, the agent performs the job required. If any maze algorithm is selected, the agent clears all the obstacles and renders that particular maze algo. If any search algorithm is selected, the agent searches for the destination accordingly. On changing the speed, the speed of deploying the speed changes. The user inputs in the grid-like the start position and the end position and checkpoints. While finding the path it considers the checkpoints and the obstacles placed on the way. After the path is found, dragging the checkpoint or start or endpoints renders the path in real-time. These are some of the functions of the agent. We can call the agent a rational agent because here the user inputs and the grid state functions as the precepts of the agent and the agents take the decision and perform the actions based on the perceived environment. * Mazes The mazes are defined in the src/mazes folder. Each of the 3 mazes has its classes. Input: Depending on the maze user chooses, the agent initializes the class of that particular maze. Action: After the maze is initialized, each class takes the grid and other things as input and forms the maze on the grid. In case of the recursive mazes, it takes the density as input too. * Finder The finders are defined in the src/finders folder. Each of the 10 finders has their own classes. Input: Depending on the finder the user chooses and the parameters of the finder, the agent initialize the class of that particular finder. Output: The classes take in the current state grid and other parameters as input and tries to find the * Bot The Bot class is defined in the visual/js/bot.js file. Input: It receives the action performed by the agent as input and sets the display text Action: According to the bot state set due to the input, it changes the innerHTML of the bot’s content to appropriate messages. These messages disappear automatically after the set time if the close button is not pressed through setTimeout function. Since the control shifts to these functions after the set time, to avoid clashes between one message to another, the original text and current text are compared. In this way, a message has the power to only delete itself. Result messages are given message IDs because they stay on screen for longer, and shouldn't hide a more recent result message. * View The View class is in the visual/js/view.js file. It handles most of the inputs and outputs in the Raphael grid. * Panel The Panel class is in the visual/js/panel.js file. This comprises of all the elements in the navbar. It handles the user inputs from the navigation also responsible for initialization of the correct finder. * Guide The Guide class is in the visual/js/guide.js file. Sweetalert’s help is taken to display the tutorial aesthetically. It contains an async function backAndForth that decides which message and gif to display according to which step the user is in the guide. ======= # Space_Invaders Repository for project "NAVIGATE THE MARS ROVER" under Microsoft Mars Colonization Program 2020 <file_sep>/** * The visualization Agent will works as a state machine. * See the attached document for the transitions of state diagram * See https://github.com/jakesgordon/javascript-state-machine * for the document of the StateMachine module. */ var Agent = StateMachine.create({ initial: 'none', events: [{ name: 'init', from: 'none', to: 'ready' }, { name: 'search', from: 'starting', to: 'searching' }, { name: 'pause', from: 'searching', to: 'paused' }, { name: 'finish', from: 'searching', to: 'finished' }, { name: 'resume', from: 'paused', to: 'searching' }, { name: 'cancel', from: 'paused', to: 'ready' }, { name: 'modify', from: 'finished', to: 'modified' }, { name: 'reset', from: '*', to: 'ready' }, { name: 'clear', from: ['finished', 'modified'], to: 'ready' }, { name: 'start', from: ['ready', 'modified', 'restarting'], to: 'starting' }, { name: 'restart', from: ['searching', 'finished'], to: 'restarting' }, { name: 'dragStart', from: ['ready', 'finished'], to: 'draggingStart' }, { name: 'dragEnd', from: ['ready', 'finished'], to: 'draggingEnd' }, { name: 'dragCheckpoint', from: ['ready', 'finished'], to: 'draggingCheckpoint' }, { name: 'drawWall', from: ['ready', 'finished'], to: 'drawingWall' }, { name: 'eraseWall', from: ['ready', 'finished'], to: 'erasingWall' }, { name: 'rest', from: ['draggingStart', 'draggingEnd', 'drawingWall', 'erasingWall', 'draggingCheckpoint'], to: 'ready' }, { name: 'startMaze', from: ['ready', 'finished'], to: 'ready' } ], }); $.extend(Agent, { gridSize: [64, 36], // number of nodes horizontally and vertically draggingEndLock: false, checkpoints: [], path: [], operations: [], endstatus: 0, currCheckpoint: -1, mousemoveflag: 0, checkPointsleft: 4, // number of checkpoints left to be inserted (max 4) /** * ----------------------------------------------------------------------- * Functions to insert and erase walls and obstacles * ----------------------------------------------------------------------- */ onleavenone: function () { var numCols = this.gridSize[0], numRows = this.gridSize[1]; this.grid = new PF.Grid(numCols, numRows); View.init({ numCols: numCols, numRows: numRows }); View.generateGrid(function () { Agent.setDefaultStartEndPos(); Agent.bindEvents(); Agent.transition(); // transit to the next state (ready) }); Bot.init(); //initializing the TARS bot this.$buttons = $('.control_button'); this.$maze_buttons = $('.maze_button'); return StateMachine.ASYNC; // => ready }, ondrawWall: function (event, from, to, gridX, gridY) { this.setWalkableAt(gridX, gridY, false, "wall"); // => drawingWall }, oneraseWall: function (event, from, to, gridX, gridY) { this.setWalkableAt(gridX, gridY, true, "wall"); // => erasingWall }, /** * ------------------------------------------------------------------------------- * Agent functions that get triggered when various buttons on navbar are pressed (buttonpress Event percept) * ------------------------------------------------------------------------------- */ onsearch: function (event, from, to) { //triggered when Start Search is pressed var grid, timeStart, timeEnd, finder = Panel.getFinder(); this.finder = finder; this.pathfound = 1; var TSP = new PF.TSP({ startX: this.startX, startY: this.startY, endX: this.endX, endY: this.endY, checkpoints: this.checkpoints, grid: this.grid, finder: this.finder }) res = TSP.onTSP() this.checkpoints = res[0] this.pathfound = res[1] for (var i = -1; i < this.checkpoints.length; i++) { if (i == -1) { var originX = this.startX; var originY = this.startY; } else { var originX = this.checkpoints[i].x; var originY = this.checkpoints[i].y; } if (i == this.checkpoints.length - 1) { var destX = this.endX; var destY = this.endY } else { var destX = this.checkpoints[i + 1].x; var destY = this.checkpoints[i + 1].y; } this.finder = finder; timeStart = window.performance ? performance.now() : Date.now(); grid = this.grid.clone(); var res = finder.findPath( originX, originY, destX, destY, grid ); this.path = this.path.concat(res['path']); this.operations = this.operations.concat(res['operations']); if (this.path.length == 1 || this.path.length == 0) { this.pathfound = 0 break; } this.operationCount = this.operations.length; timeEnd = window.performance ? performance.now() : Date.now(); this.timeSpent = (timeEnd - timeStart).toFixed(4); this.loop(); } if (!this.pathfound) { this.finish() } else { Bot.botState(0); } // => searching }, onrestart: function () { //triggered when Restart Start button is pressed // When clearing the colorized nodes, there may be // nodes still animating, which is an asynchronous procedure. // Therefore, we have to defer the `abort` routine to make sure // that all the animations are done by the time we clear the colors. // The same reason applies for the `onreset` event handler. this.endstatus = 0; setTimeout(function () { Agent.clearOperations(); Agent.clearFootprints(); Agent.start(); }, View.nodeColorizeEffect.duration * 1.2); Bot.botState(1); // => restarting }, onpause: function (event, from, to) { //triggered when Pause Search is pressed // => paused Bot.botState(2); }, onresume: function (event, from, to) { //triggered when Resume Search is pressed this.loop(); // => searching Bot.botState(3); }, oncancel: function (event, from, to) { //triggered when Cancel Search is pressed this.clearOperations(); this.clearFootprints(); // => ready Bot.botState(4); }, onfinish: function (event, from, to) { //triggered when the search finishes if (!this.pathfound) { this.pathnotfound() } else { View.showStats({ pathLength: PF.Util.pathLength(this.path), timeSpent: this.timeSpent, operationCount: this.operationCount, }); View.drawPath(this.path); var botpan = document.getElementById('bot_panel'); var botmsg = document.getElementById('bot_msg'); Bot.botState(5); } this.endstatus = 1; this.path = []; this.operations = []; // => finished }, onclear: function (event, from, to) { //triggered when Clear Path is pressed this.clearOperations(); this.clearFootprints(); // => ready Bot.botState(6); }, onreset: function (event, from, to) { //triggered when Clear Obstacles is pressed this.endstatus = 0; setTimeout(function () { Agent.clearOperations(); Agent.clearAll(); Agent.buildNewGrid(); }, View.nodeColorizeEffect.duration * 1.2); this.setButtonStates({ id: 3, enabled: true, }); // => ready Bot.botState(7); }, /** * -------------------------------------------------------------------------- * Functions called on entering states. * -------------------------------------------------------------------------- */ initmaze: function (mazetype) { //triggered on transitioning to startMaze this.mazetype = mazetype; this.startMaze(); }, onready: function () { //triggered when agent transitions to Ready console.log('=> ready'); this.setButtonStates({ id: 0, text: 'Start Search', enabled: true, callback: $.proxy(this.start, this), }, { id: 1, text: 'Pause Search', enabled: false, }, { id: 2, text: 'Clear Obstacles', enabled: true, callback: $.proxy(this.reset, this), }, { id: 3, text: 'Clear checkpoints', enabled: true, callback: $.proxy(this.clearCheckPoint, this, 1), }); this.setButtonStatesMaze({ id: 0, text: 'Random maze', enabled: true, callback: $.proxy(this.initmaze, this, 'random'), }, { id: 1, text: 'Dense Recursive maze', enabled: true, callback: $.proxy(this.initmaze, this, 'dense_recursive'), }, { id: 2, text: 'Stair maze', enabled: true, callback: $.proxy(this.initmaze, this, 'stair'), }, { id: 3, text: 'Sparse Recursive Maze', enabled: true, callback: $.proxy(this.initmaze, this, 'sparse_recursive'), }); // => [starting, draggingStart, draggingEnd, draggingPit drawingStart, drawingEnd] }, createMazeWall: function (event, x, y) { event.setWalkableAt(x, y, false); }, onstartMaze: function (event, from, to) { this.endstatus = 0; var mazetype = this.mazetype; Agent.clearOperations(); Agent.clearAll(); Agent.buildNewGrid(); this.setButtonStates({ id: 3, enabled: true, }); this.setButtonStates({ id: 6, enabled: false, }); var rows = this.gridSize[0]; var cols = this.gridSize[1]; //creates Maze class objects based on the type of Maze selected by user if (mazetype == 'random') { maze = new PF.RandomMaze({ xlim: rows, ylim: cols, startX: this.startX, startY: this.startY, endX: this.endX, endY: this.endY, checkpoints: this.checkpoints }); } else if (mazetype == 'dense_recursive') { maze = new PF.RecDivMaze({ xlim: rows, ylim: cols, startX: this.startX, startY: this.startY, endX: this.endX, endY: this.endY, checkpoints: this.checkpoints, density: 1 }); } else if (mazetype == 'stair') { maze = new PF.StairMaze({ xlim: rows, ylim: cols, startX: this.startX, startY: this.startY, endX: this.endX, endY: this.endY, checkpoints: this.checkpoints }); } else if (mazetype == 'sparse_recursive') { maze = new PF.RecDivMaze({ xlim: rows, ylim: cols, startX: this.startX, startY: this.startY, endX: this.endX, endY: this.endY, checkpoints: this.checkpoints, density: 0 }); } var mazeWall = maze.createMaze(); for (let i = 0; i < mazeWall.length; i++) { setTimeout(this.createMazeWall, 3, this, mazeWall[i].x, mazeWall[i].y); } }, onstarting: function (event, from, to) { console.log('=> starting'); this.endstatus = 0; // Clears any existing search progress this.clearFootprints(); this.setButtonStates({ id: 1, enabled: true, }); this.search(); // => searching }, onsearching: function () { console.log('=> searching'); this.setButtonStates({ id: 0, text: 'Restart Search', enabled: true, callback: $.proxy(this.restart, this), }, { id: 1, text: 'Pause Search', enabled: true, callback: $.proxy(this.pause, this), }); // => [paused, finished] }, onpaused: function () { console.log('=> paused'); this.setButtonStates({ id: 0, text: 'Resume Search', enabled: true, callback: $.proxy(this.resume, this), }, { id: 1, text: 'Cancel Search', enabled: true, callback: $.proxy(this.cancel, this), }); // => [searching, ready] }, onfinished: function () { console.log('=> finished'); this.setButtonStates({ id: 0, text: 'Restart Search', enabled: true, callback: $.proxy(this.restart, this), }, { id: 1, text: 'Clear Path', enabled: true, callback: $.proxy(this.clear, this), }); }, onmodified: function () { console.log('=> modified'); this.setButtonStates({ id: 0, text: 'Start Search', enabled: true, callback: $.proxy(this.start, this), }, { id: 1, text: 'Clear Path', enabled: true, callback: $.proxy(this.clear, this), }); }, /** * Define setters and getters of PF.Node, then we can get the operations * of the pathfinding. */ bindEvents: function () { $('#draw_area').mousedown($.proxy(this.mousedown, this)); $(window) .mousemove($.proxy(this.mousemove, this)) .mouseup($.proxy(this.mouseup, this)); }, loop: function () { //used to adjust agent speed speed = Panel.getSpeed(); var operationsPerSecond = speed * 5; var interval = 1000 / operationsPerSecond; (function loop() { if (!Agent.is('searching')) { return; } Agent.step(); setTimeout(loop, interval); })(); }, step: function () { var operations = this.operations, op, isSupported; do { if (!operations.length) { this.finish(); // transit to `finished` state return; } op = operations.shift(); isSupported = View.supportedOperations.indexOf(op.attr) !== -1; } while (!isSupported); View.setAttributeAt(op.x, op.y, op.attr, op.value, false); }, /** * ---------------------------------------------------------------------------------------- * Clear Functions: used to remove path, walls and checkpoints * ---------------------------------------------------------------------------------------- */ clearOperations: function () { this.operations = []; this.path = [] }, clearFootprints: function () { View.clearFootprints(); View.clearPath(); }, clearCheckPoint: function (clearNumber, gridX = 0, gridY = 0) { if (clearNumber == 0) { const ind = this.checkpoints.findIndex(node => node.x == gridX && node.y == gridY ); if (ind != -1) { this.checkpoints.splice(ind, 1); } this.grid.setWalkableAt(gridX, gridY, true, ""); View.setCheckPoint(gridX, gridY, -1, -1, false); } else { for (let i = 0; i < this.checkpoints.length; i++) View.setCheckPoint(this.checkpoints[i].x, this.checkpoints[i].y, -1, -1, false); this.checkpoints.splice(0, this.checkpoints.length); this.checkPointsleft = 4; Bot.botState(8, this.checkPointsleft); } this.currCheckpoint = -1; if (this.endstatus == 1) this.findPath(1); }, clearAll: function () { this.clearFootprints(); View.clearBlockedNodes(); }, buildNewGrid: function () { this.grid = new PF.Grid(this.gridSize[0], this.gridSize[1]); }, /** * This function finds the path as per choice of algorithm by the user. * In case of checkpoints it first calls TSP to find out what sequence * the checkpoints should be visited in. Finally it renders the path * found using drawPath() from View. */ findPath: function (viewoperations) { this.clearOperations(); this.clearFootprints(); var path = []; var operations = []; var TSP = new PF.TSP({ startX: this.startX, startY: this.startY, endX: this.endX, endY: this.endY, checkpoints: this.checkpoints, grid: this.grid, finder: this.finder }) if (this.currCheckpoint != -1) { var checkx = this.checkpoints[this.currCheckpoint].x var checky = this.checkpoints[this.currCheckpoint].y } res = TSP.onTSP(); this.checkpoints = res[0]; this.pathfound = res[1]; if (this.currCheckpoint != -1) { for (var i = 0; i < this.checkpoints.length; i++) if (checkx == this.checkpoints[i].x && checky == this.checkpoints[i].y) { this.currCheckpoint = i; break; } } for (var i = -1; i < this.checkpoints.length; i++) { if (i == -1) { var originX = this.startX; var originY = this.startY; } else { var originX = this.checkpoints[i].x; var originY = this.checkpoints[i].y; } if (i == this.checkpoints.length - 1) { var destX = this.endX; var destY = this.endY } else { var destX = this.checkpoints[i + 1].x; var destY = this.checkpoints[i + 1].y; } var grid = this.grid.clone(); var res = this.finder.findPath( originX, originY, destX, destY, grid ); if (!res['path'] || res['path'].length == 1) { this.pathfound = 0; break; } path = path.concat(res['path']) operations = operations.concat(res['operations']) } if (this.pathfound) { var op, isSupported; if (viewoperations) { while (operations.length) { op = operations.shift(); View.setAttributeAt(op.x, op.y, op.attr, op.value); } } View.drawPath(path); } }, /** * ---------------------------------------------------------------------------------------- * These functions process percepts in form of mouse press, mouseup and cursor motion. * ---------------------------------------------------------------------------------------- */ mousedown: function (event) { //triggered on pressing on the grid var coord = View.toGridCoordinate(event.pageX, event.pageY), gridX = coord[0], gridY = coord[1], grid = this.grid; if ((event.ctrlKey) && this.isCheckPoint(gridX, gridY) != -1) { this.clearCheckPoint(0, gridX, gridY); this.checkPointsleft++; Bot.botState(9, this.checkPointsleft); return; } else if (event.ctrlKey) { if (!this.isStartPos(gridX, gridY) && !this.isEndPos(gridX, gridY) && grid.isWalkableAt(gridX, gridY) && this.checkPointsleft > 0) { this.setCheckPoint(gridX, gridY, true); this.checkPointsleft--; if (this.endstatus == 1) { this.findPath(1); } Bot.botState(10, this.checkPointsleft); } } else { if (this.can('dragStart') && this.isStartPos(gridX, gridY)) { this.dragStart(); return; } if (this.can('dragEnd') && this.isEndPos(gridX, gridY)) { this.dragEnd(); return; } if (this.can('dragCheckpoint') && this.isCheckPoint(gridX, gridY) != -1) { this.currCheckpoint = this.isCheckPoint(gridX, gridY) this.dragCheckpoint(); return; } if (this.can('drawWall') && grid.isWalkableAt(gridX, gridY)) { this.drawWall(gridX, gridY); return; } if (this.can('eraseWall') && !grid.isWalkableAt(gridX, gridY)) { this.eraseWall(gridX, gridY); } if (this.can('dragStart') && this.isStartPos(gridX, gridY)) { this.dragStart(); return; } if (this.can('dragEnd') && this.isEndPos(gridX, gridY)) { this.dragEnd(); return; } } }, mousemove: function (event) { //triggered on moving cursor on the grid var coord = View.toGridCoordinate(event.pageX, event.pageY), grid = this.grid, gridX = coord[0], gridY = coord[1]; if (this.isStartPos(gridX, gridY) && this.isEndPos(gridX, gridY) || this.isCheckPoint(gridX, gridY) != -1) { return; } /** * Different behavior based on dragging objects on the grid, e.g Start point, End point or Checkpoints. */ switch (this.current) { case 'draggingStart': if (grid.isWalkableAt(gridX, gridY)) { this.mousemoveflag = 1 this.setStartPos(gridX, gridY); if (this.endstatus == 1) this.findPath(0); } break; case 'draggingEnd': if (grid.isWalkableAt(gridX, gridY)) { this.mousemoveflag = 1 this.setEndPos(gridX, gridY); if (this.endstatus == 1) this.findPath(0); } break; case 'draggingCheckpoint': if (grid.isWalkableAt(gridX, gridY)) { this.mousemoveflag = 1 View.setCheckPoint(gridX, gridY, this.checkpoints[this.currCheckpoint].x, this.checkpoints[this.currCheckpoint].y, true) this.checkpoints[this.currCheckpoint].x = gridX; this.checkpoints[this.currCheckpoint].y = gridY; if (this.endstatus == 1) { this.findPath(0); } } break; case 'drawingWall': this.setWalkableAt(gridX, gridY, false, "wall"); break; case 'erasingWall': this.setWalkableAt(gridX, gridY, true, "wall"); break; } }, mouseup: function (event) { //triggered on realising mouse button on the grid if (Agent.can('rest')) { var state = this.current; Agent.rest(); var coord = View.toGridCoordinate(event.pageX, event.pageY), grid = this.grid, gridX = coord[0], gridY = coord[1]; /** * Different behavior based on dragging objects on the grid, e.g Start point, End point or Checkpoints. */ switch (state) { case 'draggingStart': if (!grid.isWalkableAt(gridX, gridY)) { if (this.endstatus == 1) this.findPath(1); } if (grid.isWalkableAt(gridX, gridY) && !this.isEndPos(gridX, gridY) && this.isCheckPoint(gridX, gridY) == -1) { this.setStartPos(gridX, gridY); if (this.endstatus == 1) this.findPath(1); } break; case 'draggingEnd': if (!grid.isWalkableAt(gridX, gridY)) { if (this.endstatus == 1) this.findPath(1); } if (grid.isWalkableAt(gridX, gridY) && !this.isStartPos(gridX, gridY) && this.isCheckPoint(gridX, gridY) == -1) { this.setEndPos(gridX, gridY); if (this.endstatus == 1) this.findPath(1); } break; case 'draggingCheckpoint': if (!grid.isWalkableAt(gridX, gridY)) { if (this.endstatus == 1) this.findPath(1) } if (grid.isWalkableAt(gridX, gridY) && !this.isStartPos(gridX, gridY) && !this.isEndPos(gridX, gridY)) { View.setCheckPoint(gridX, gridY, this.checkpoints[this.currCheckpoint].x, this.checkpoints[this.currCheckpoint].y, true) this.checkpoints[this.currCheckpoint].x = gridX; this.checkpoints[this.currCheckpoint].y = gridY; if (this.endstatus == 1) { this.findPath(1); } } break; } } }, setButtonStates: function () { $.each(arguments, function (i, opt) { var optid = opt.id; var $button = Agent.$buttons.eq(optid); if (opt.text) { $button.text(opt.text); } if (opt.callback) { $button .unbind('click') .click(opt.callback); } if (opt.enabled === undefined) { return; } else if (opt.enabled) { $button.removeAttr('disabled'); } else { $button.attr({ disabled: 'disabled' }); } }); }, setButtonStatesMaze: function () { $.each(arguments, function (i, opt) { var optid = opt.id; var $button = Agent.$maze_buttons.eq(optid); if (opt.text) { $button.text(opt.text); } if (opt.callback) { $button .unbind('click') .click(opt.callback); } if (opt.enabled === undefined) { return; } else if (opt.enabled) { $button.removeAttr('disabled'); } else { $button.attr({ disabled: 'disabled' }); } }); }, setButtonStatesObstacles: function () { $.each(arguments, function (i, opt) { var optid = opt.id; var $button = Agent.$obstacle_buttons.eq(optid - 1); if (opt.text) { $button.text(opt.text); } if (opt.callback) { $button .unbind('click') .click(opt.callback); } if (opt.enabled === undefined) { return; } else if (opt.enabled) { $button.removeAttr('disabled'); } else { $button.attr({ disabled: 'disabled' }); } }); }, /** * When initializing, this method will be called to set the positions * of start node and end node. * It will detect user's display size, and compute the best positions. */ setDefaultStartEndPos: function () { var width, height, marginRight, availWidth, centerX, centerY, endX, endY, nodeSize = View.nodeSize; width = $(window).width(); height = $(window).height(); marginRight = $('#algorithm_panel').width(); availWidth = width - marginRight; this.centerX = Math.ceil(availWidth / 2 / nodeSize); this.centerY = Math.floor(height / 2 / nodeSize); this.setStartPos(this.centerX - 5, this.centerY); this.setEndPos(this.centerX + 15, this.centerY + 10); }, setStartPos: function (gridX, gridY) { this.startX = gridX; this.startY = gridY; View.setStartPos(gridX, gridY); }, setEndPos: function (gridX, gridY) { this.endX = gridX; this.endY = gridY; View.setEndPos(gridX, gridY); }, setWalkableAt: function (gridX, gridY, walkable, pit) { this.grid.setWalkableAt(gridX, gridY, walkable, pit); View.setAttributeAt(gridX, gridY, 'walkable', walkable, "wall"); }, setCheckPoint: function (gridX, gridY) { this.checkpoints.push({ x: gridX, y: gridY }) View.setCheckPoint(gridX, gridY, -1, -1, true) }, /** * ---------------------------------------------------------------------------------------- * These functions check what type of node the current node is (start,end or checkpoint). * ---------------------------------------------------------------------------------------- */ isStartPos: function (gridX, gridY) { return gridX === this.startX && gridY === this.startY; }, isEndPos: function (gridX, gridY) { return gridX === this.endX && gridY === this.endY; }, isCheckPoint: function (gridX, gridY) { return this.checkpoints.findIndex(node => node.x == gridX && node.y == gridY); }, /** * ---------------------------------------------------------------------------------------- * Utility functions * ---------------------------------------------------------------------------------------- */ pathnotfound: function () { Bot.botState(11); }, });<file_sep>module.exports = { 'Heap': require('heap'), 'Node': require('./core/Node'), 'Grid': require('./core/Grid'), 'Util': require('./core/Util'), 'DiagonalMovement': require('./core/DiagonalMovement'), 'Heuristic': require('./core/Heuristic'), 'AStarFinder': require('./finders/AStarFinder'), 'BestFirstFinder': require('./finders/BestFirstFinder'), 'CLAFinder': require('./finders/CLAFinder'), 'BreadthFirstFinder': require('./finders/BreadthFirstFinder'), 'DijkstraFinder': require('./finders/DijkstraFinder'), 'BiAStarFinder': require('./finders/BiAStarFinder'), 'BiBestFirstFinder': require('./finders/BiBestFirstFinder'), 'BiBreadthFirstFinder': require('./finders/BiBreadthFirstFinder'), 'BiDijkstraFinder': require('./finders/BiDijkstraFinder'), 'IDAStarFinder': require('./finders/IDAStarFinder'), 'JumpPointFinder': require('./finders/JumpPointFinder'), 'RandomMaze':require('./mazes/RandomMaze'), 'RecDivMaze':require('./mazes/RecursiveDivisionMaze'), 'StairMaze':require('./mazes/StairMaze'), 'TSP':require('./finders/TSP') };<file_sep>/** * The initial guide/tutorial using sweetalert. */ async function backAndForth() { const steps = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11'] const swalQueueStep = Swal.mixin({ confirmButtonText: 'Next &rarr;', cancelButtonText: 'Back', progressSteps: steps, width: 800, inputAttributes: { required: true }, reverseButtons: true, backdrop: ` rgba(0,0,123,0.6) url("https://i.gifer.com/ZDci.gif") left top no-repeat ` }) const values = [] let currentStep var title = "" var html = "" for (currentStep = 0; currentStep < steps.length;) { switch (currentStep) { case 0: title = "Welcome to Space invaders!" html = "Navigate the Mars Rover to reach its base \ avoiding various types of ridges, mazes and detouring through pitstops for maintenance along\ the way! Click Next to view the guide.<br> Please make sure your volume is not muted." imageUrl = "images/gifs/mars.gif" break; case 1: title = "Draw Ridges" html = "You are the Chief Engineer with the map of the Mars environment. You need to program the\ map into the rover! Click and drag to draw ridges for your rover to avoid." imageUrl = "images/gifs/walls.gif" break; case 2: title = "Insert and Clear Pitstops" html = "Ctrl + Click to place upto 4 pitstops for the rover to undergo maintenance\ en route to its base! Ctrl + Click on existing pitstops clears them." imageUrl = "images/gifs/checkpoints.gif" break; case 3: title = "Adjust speed" html = "Drag slider to adjust the speed controls for the rover." imageUrl = "images/gifs/speed.gif" break; case 4: title = "Explore Mazes" html = "Oh no! There are mazes of so many patterns along the way! Can \ the rover find its way in these puzzling mazes?" imageUrl = "images/gifs/maze.gif" break; case 5: title = "Choose Search Algorithm" html = "As the Chief Engineer, you can choose between various state-of-the-art \ PathFinding algorithms to find the shortest route for the rover to reach its base. " imageUrl = "images/gifs/algos.gif" break; case 6: title = "Start searching for shortest route" html = "The rover is all set! Base locations, pitstop locations and routing algorithms have been \ all programmed into the rover. Let's start searching for the shortest route!" imageUrl = "images/gifs/search.gif" break; case 7: title = "Pause and resume search" html = "An engineer's brain always checks and rechecks for bugs. Why don't you calm\ yourself down with a pause in the search, get some coffee and check if the search is \ progressing as planned? You can resume the routing anytime." imageUrl = "images/gifs/halt.gif" break; case 8: title = "Drag endpoints and pitstops" html = "Communication from the basestation is noisy as anything! Drag the endpoints \ and pitstop markers to quickly instruct the rover to reroute to new destinations and avoid\ duststorm affected pitstops. Saves you the trouble of reprogramming the rover for each \ noisy instruction! " imageUrl = "images/gifs/clear.gif" break; case 9: title = "Clear pitstops and obstacles" html = "Time to explore new maps! Ctrl + Click on pitstops to clear them or clear \ all obstacles and pitstops at once from the control panel above." imageUrl = "images/gifs/clearall.gif" break; case 10: title = "TARS" html = "Lastly, we have a friend from Interstellar who will guide you through your journey." imageUrl = "images/gifs/tars.gif" break; } const result = await swalQueueStep.fire({ title: title, html: html, imageUrl: imageUrl, showCancelButton: currentStep > 0, currentProgressStep: currentStep }) if (result.value) { values[currentStep] = result.value currentStep++ } else if (result.dismiss === 'cancel') { currentStep-- } else { break } } } <file_sep>/** * Recursive division maze generator. Based on https://gist.github.com/jamis/761525 * @param {Object} opt * @param {number} opt.xlim Width of the grid * @param {number} opt.ylim Height of the grid * @param {number} opt.startX x co-ordinate of the source * @param {number} opt.startY y co-ordinate of the source * @param {number} opt.endirectionX x co-ordinate of the destination * @param {number} opt.endirectionY y co-ordinate of the destination * @param {Array<Object>} opt.checkpoints array of checkpoints on the grid * @param {number} opt.density bool variable to choose between sparse and dense maze */ function RecDivMaze(opt) { opt = opt || {}; this.mazeWalls = []; this.xlim = opt.xlim; this.ylim = opt.ylim; this.startX = opt.startX; this.startY = opt.startY; this.endX = opt.endX; this.endY = opt.endY; this.checkpoints = opt.checkpoints; this.density = opt.density; this.horizontalFlag = 1; this.verticalFlag = 2; this.southFlag = 1; this.eastFlag = 2; } /** * This chooses the orientation to create the next wall: horizontal or vertical * @param {number} width * @param {number} height * @return {number} Returns the orientation */ RecDivMaze.prototype.choose_orientation = function (width, height) { if (width < height) return this.horizontalFlag; else if (height < width) return this.verticalFlag; else return Math.floor(Math.random() * 2) == 0 ? this.horizontalFlag : this.verticalFlag; } /** * This recursively divides the grid * @param {number} x * @param {number} y * @param {number} width * @param {number} height * @param {number} orientation */ RecDivMaze.prototype.divide = function (x, y, width, height, orientation) { var sizeLim = this.density ? 5 : 8; console.log(sizeLim); if (width < sizeLim || height < sizeLim) return; var horizontal = orientation == this.horizontalFlag; var wallX = x + (horizontal ? 0 : Math.floor(Math.random() * (width - 2))); var wallY = y + (horizontal ? Math.floor(Math.random() * (height - 2)) : 0); var passageX = wallX + (horizontal ? Math.floor(Math.random() * width) : 0); var passageY = wallY + (horizontal ? 0 : Math.floor(Math.random() * height)); var directionX = horizontal ? 1 : 0; var directionY = horizontal ? 0 : 1; var length = horizontal ? width : height; var perpDirection = horizontal ? this.southFlag : this.eastFlag; for (let i = 0; i < length; i++) { if (wallX != passageX || wallY != passageY) { var ind = 0; for (let i = 0; i < this.checkpoints.length; i++) { if (this.checkpoints[i].x == wallX && this.checkpoints[i].y == wallY) { ind = -1; break; } } if ((wallX == this.startX && wallY == this.startY) || (wallX == this.endX && wallY == this.endY) || (ind == -1)) {} else { this.mazeWalls.push({ x: wallX, y: wallY }); } } wallX += directionX; wallY += directionY; } var nextX = x, nextY = y; var nextWidth = horizontal ? width : (wallX - x + 1); var nextHeight = horizontal ? (wallY - y + 1) : height; this.divide(nextX, nextY, nextWidth, nextHeight, this.choose_orientation(nextWidth, nextHeight)); nextX = horizontal ? x : wallX + 1; nextY = horizontal ? wallY + 1 : y; nextWidth = horizontal ? width : (x + width - wallX - 1); nextHeight = horizontal ? (y + height - wallY - 1) : height; this.divide(nextX, nextY, nextWidth, nextHeight, this.choose_orientation(nextWidth, nextHeight)); } /** * This creates the random maze * @return {Array<Object>} Returns the mazewalls */ RecDivMaze.prototype.createMaze = function () { this.divide(0, 0, this.xlim, this.ylim, this.choose_orientation(this.xlim, this.ylim)); return this.mazeWalls; } module.exports = RecDivMaze;<file_sep>var AStarFinder = require('./AStarFinder'); // var Heuristic = require('../core/Heuristic'); /** * Best-First-Search path-finder. * @constructor * @extends AStarFinder * @param {Object} opt * @param {boolean} opt.allowDiagonal Whether diagonal movement is allowed. * Deprecated, use diagonalMovement instead. * @param {boolean} opt.dontCrossCorners Disallow diagonal movement touching * block corners. Deprecated, use diagonalMovement instead. * @param {DiagonalMovement} opt.diagonalMovement Allowed diagonal movement. * @param {function} opt.heuristic Heuristic function to estimate the distance * (defaults to manhattan). */ function CLAFinder(opt) { AStarFinder.call(this, opt); opt = opt || {}; if (opt.heuristic == 'poweredManhattan') { this.heuristic = function(dx, dy) { return Math.pow((dx + dy), 2); }; } else { this.heuristic = function(dx, dy) { return Math.pow((dx + dy), 10); }; } } CLAFinder.prototype = new AStarFinder(); CLAFinder.prototype.constructor = CLAFinder; module.exports = CLAFinder;<file_sep>/** * The Message bot panel. * It displays messages to instruct the user. */ var Bot = { init: function () { this.botPan = document.getElementById('bot_panel'); this.botMsg = document.getElementById('bot_msg'); this.msgs = 0; }, botText: function (text) { this.botMsg.innerHTML = text; this.botPan.style.visibility = 'visible'; this.botMsg.style.visibility = 'visible'; setTimeout(function () { //hide the panel after <duration> milliseconds if (this.botMsg.innerHTML == text) { this.botPan.style.visibility = 'hidden'; this.botMsg.style.visibility = 'hidden'; } }.bind(this), 4000) }, botTextFinish: function (text) { var msgid = 1; this.msgs += 1; botmsg.innerHTML = text; botpan.style.visibility = 'visible'; botmsg.style.visibility = 'visible'; setTimeout(function () { if ((botmsg.innerHTML == text) && (this.msgs == msgid)) { botpan.style.visibility = 'hidden'; botmsg.style.visibility = 'hidden'; } this.msgs -= 1; }.bind(this), 10000) }, /** * The mapping of bot messages with Agent states. */ botState: function (state, checkPointInfo = "") { text = ""; switch (state) { case 0: text = "Search Started! <br><br> You can pause or restart anytime you want." break; case 1: text = "Search Started! <br><br> You can pause anytime you want." break; case 2: text = "Search Paused! <br><br> You can come back anytime to resume, or cancel search." break; case 3: text = "Search Resumed! <br><br> You can pause or restart anytime." break; case 4: text = "Search Canceled!" break; case 5: text = "Congratulations! Base Found!<br><br> Try moving the rover/ base to render path in real time!\ <br><br> Try adding checkpoints (Ctrl+Click) and obstacles as well" break; case 6: text = "Path Cleared! <br><br> Modify the current map and search again" break; case 7: text = "Obstacles cleared! <br><br> Create with a fresh map!" break; case 8: text = "Cleared all checkpoints! <br><br> You can add " + String(checkPointInfo) + " checkpoints now! (Ctrl+Click)" break; case 9: text = "Removed a checkpoint <br><br> You can add " + String(checkPointInfo) + " checkpoints now!" break; case 10: text = "Added a checkpoint <br><br> Checkpoints left: " + String(checkPointInfo) + "<br><br> You can remove a checkpoint using Ctrl+Click" break; case 11: text = "Oops! Path not found. <br> Try changing the layout of the grid. <br> If you are using IDA, it might be possible the algorithm times out. Please increase the time parameter or decrease some obstacles." break; } if (state == 5 || state == 11) this.botTextFinish(text) else this.botText(text); } }
06f9d46fbae2bbc6a309a15336c272b4f6bced45
[ "Markdown", "JavaScript" ]
7
Markdown
avani17101/Space_Invaders-1
7a4243db70a1b353347cfd2a3c8c8e933e85d49e
7830298dd80d4158f26fdb9e5bba01e77270b948
refs/heads/master
<file_sep>import "./App.css"; import Weather from "./Weather"; function App() { return ( <div className="App"> <div className="container"> <Weather defaultCity="Lisbon" /> <footer> This project was coded by <NAME> and {""} <a href="https://github.com/mariamelomaga/react-weather-app" target="_blank" rel="noreferrer" alt="gitLink" > is open-sourced on GitHub {""} </a>{" "} and {""} <a href="https://festive-bose-62cc2d.netlify.app/" target="_blank" alt="netlifyLink" rel="noreferrer" > hosted on Netlify </a> </footer> </div> </div> ); } export default App;
c22c7263317fa258eb67ee7ea0d97da9970ca10e
[ "JavaScript" ]
1
JavaScript
mariamelomaga/react-weather-app
b58fa23745206acf90bba106bcc2d9053d0d7260
7817c7b8a133a54a7708461436daf0162df9b6ab