Skip to content
This repository has been archived by the owner on Jul 29, 2024. It is now read-only.

Commit

Permalink
- suddenDeath more efficient
Browse files Browse the repository at this point in the history
- handleGetSetReady now is protected by an ip request spam protection (checkIpTimer(string))
-renamed some methods
  • Loading branch information
christopherpeters-git committed Nov 9, 2020
1 parent b87b899 commit 424eaf8
Show file tree
Hide file tree
Showing 6 changed files with 82 additions and 87 deletions.
2 changes: 1 addition & 1 deletion Bomb.go
Original file line number Diff line number Diff line change
Expand Up @@ -112,7 +112,7 @@ func (b *Bomb) startBomb() {
if sessionRunning && playerDied {
log.Println("check for remaining players")
playerDied = false
isOnePlayerAlive()
findWinner()
}

if GameMap.Fields[x][y].Contains[0] == b {
Expand Down
5 changes: 3 additions & 2 deletions Bomberman.go
Original file line number Diff line number Diff line change
Expand Up @@ -167,8 +167,9 @@ func (r *Bomberman) checkFieldForItem(x int, y int) {
}
r.ItemActive = false
})
case 12:

case 13:
r.Kill()
findWinner()
default:
return

Expand Down
70 changes: 29 additions & 41 deletions Game.go
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ const (
STANDARD_BOMB_TIME = 3
STANDARD_STEP_MULTIPLICATOR = 1
DEATH_STEP_MULTIPLICATOR = 0.5
SUDDEN_DEATH_START_TIME = 1
SUDDEN_DEATH_START_TIME = 10
MAP_SIZE = CANVAS_SIZE / FIELD_SIZE

/*
Expand Down Expand Up @@ -222,7 +222,7 @@ func playerWebsocketLoop(session *Session) {
session.Bomber.DirUp, session.Bomber.DirDown, session.Bomber.DirLeft, session.Bomber.DirRight = true, false, false, false
session.Bomber.IsMoving = true
if session.Bomber.collisionWithSurroundings(0, -int(realStepSize)) {
if session.Bomber.isMovementLegal(session.Bomber.PositionX, session.Bomber.PositionY-int(realStepSize)) {
if session.Bomber.moveIfLegal(session.Bomber.PositionX, session.Bomber.PositionY-int(realStepSize)) {

session.Bomber.topRightPos.updatePosition(0, -int(realStepSize))
session.Bomber.topLeftPos.updatePosition(0, -int(realStepSize))
Expand All @@ -237,7 +237,7 @@ func playerWebsocketLoop(session *Session) {
session.Bomber.DirUp, session.Bomber.DirDown, session.Bomber.DirLeft, session.Bomber.DirRight = false, true, false, false
session.Bomber.IsMoving = true
if session.Bomber.collisionWithSurroundings(0, int(realStepSize)) {
if session.Bomber.isMovementLegal(session.Bomber.PositionX, session.Bomber.PositionY+int(realStepSize)) {
if session.Bomber.moveIfLegal(session.Bomber.PositionX, session.Bomber.PositionY+int(realStepSize)) {

session.Bomber.topRightPos.updatePosition(0, int(realStepSize))
session.Bomber.topLeftPos.updatePosition(0, int(realStepSize))
Expand All @@ -252,7 +252,7 @@ func playerWebsocketLoop(session *Session) {
session.Bomber.DirUp, session.Bomber.DirDown, session.Bomber.DirLeft, session.Bomber.DirRight = false, false, true, false
session.Bomber.IsMoving = true
if session.Bomber.collisionWithSurroundings(-int(realStepSize), 0) {
if session.Bomber.isMovementLegal(session.Bomber.PositionX-int(realStepSize), session.Bomber.PositionY) {
if session.Bomber.moveIfLegal(session.Bomber.PositionX-int(realStepSize), session.Bomber.PositionY) {

session.Bomber.topRightPos.updatePosition(-int(realStepSize), 0)
session.Bomber.topLeftPos.updatePosition(-int(realStepSize), 0)
Expand All @@ -267,7 +267,7 @@ func playerWebsocketLoop(session *Session) {
session.Bomber.DirUp, session.Bomber.DirDown, session.Bomber.DirLeft, session.Bomber.DirRight = false, false, false, true
session.Bomber.IsMoving = true
if session.Bomber.collisionWithSurroundings(int(realStepSize), 0) {
if session.Bomber.isMovementLegal(session.Bomber.PositionX+int(realStepSize), session.Bomber.PositionY) {
if session.Bomber.moveIfLegal(session.Bomber.PositionX+int(realStepSize), session.Bomber.PositionY) {

session.Bomber.topRightPos.updatePosition(int(realStepSize), 0)
session.Bomber.topLeftPos.updatePosition(int(realStepSize), 0)
Expand Down Expand Up @@ -362,7 +362,7 @@ func StartGameIfPlayersReady() {
for _, v := range Connections {
v.Bomber.PlayerReady = false
}
time.AfterFunc(time.Minute*SUDDEN_DEATH_START_TIME, startSuddenDeath)
time.AfterFunc(time.Second*SUDDEN_DEATH_START_TIME, startSuddenDeath)
}

/*
Expand All @@ -371,31 +371,30 @@ Starts the Suddendeath and Poison spreading.
func startSuddenDeath() {
suddenDeathRunning = true
p := newPoison()
go checkForPoison()
//go checkForPoison()
for t := 0; t < SUDDEN_DEATH_MAX_AREA; t++ {
if !suddenDeathRunning {
break
}
for i := 0; i < len(GameMap.Fields); i++ {
for j := 0; j < len(GameMap.Fields[i]); j++ {

if (i == t) || (j == t) || (i == 19-t) || (j == 19-t) {
if GameMap.Fields[i][j].Contains[0] != nil {
if GameMap.Fields[i][j].Contains[0].getType() == 13 {
continue
}
}

if GameMap.Fields[i][j].Contains[1] != nil {
if GameMap.Fields[i][j].Contains[1].getType() == 13 {
continue
}
}
GameMap.Fields[i][j].addPoison(&p)
killAllPlayersOnField(GameMap.Fields[i][j].Player)
}
}
}
//MapChanged()
findWinner()
time.Sleep(time.Second * SUDDEN_INCREASE_TIME)
}
}
Expand All @@ -404,31 +403,23 @@ func startSuddenDeath() {
Inefficient! todo: Change!
While Sudden Death is running, constantly loops to all Fields and, if a Poison-Field is found, kills all player on the Field.
*/
func checkForPoison() {
for suddenDeathRunning {
for i := 0; i < len(GameMap.Fields); i++ {
for j := 0; j < len(GameMap.Fields[i]); j++ {
if GameMap.Fields[i][j].Contains[0] != nil {
if GameMap.Fields[i][j].Contains[0].getType() == 13 {
if GameMap.Fields[i][j].Player != nil {
//TO DO: Dont insta kill
killAllPlayersOnField(GameMap.Fields[i][j].Player)
isOnePlayerAlive()
}
}
}
if GameMap.Fields[i][j].Contains[1] != nil {
if GameMap.Fields[i][j].Contains[1].getType() == 13 {
if GameMap.Fields[i][j].Player != nil {
killAllPlayersOnField(GameMap.Fields[i][j].Player)
isOnePlayerAlive()
}
}
}
}
}
}
}
//func checkForPoison() {
// for suddenDeathRunning {
// for i := 0; i < len(GameMap.Fields); i++ {
// for j := 0; j < len(GameMap.Fields[i]); j++ {
// if GameMap.Fields[i][j].Contains[0] != nil || GameMap.Fields[i][j].Contains[1] != nil{
// if GameMap.Fields[i][j].Contains[0].getType() == 13 || GameMap.Fields[i][j].Contains[1].getType() == 13 {
// if GameMap.Fields[i][j].Player != nil {
// //TO DO: Dont insta kill
// killAllPlayersOnField(GameMap.Fields[i][j].Player)
// findWinner()
// }
// }
// }
// }
// }
// }
//}

/*
Resets the Game.
Expand Down Expand Up @@ -469,7 +460,7 @@ func killAllPlayersOnField(list *list.List) {
/*
Checks if only one Player is alive and acts accordingly.
*/
func isOnePlayerAlive() {
func findWinner() {
counter := 0
var lastBomberAlive *Bomberman
for _, v := range Connections {
Expand All @@ -483,15 +474,12 @@ func isOnePlayerAlive() {
} else if counter == 0 {
log.Println("Draw")
} else if counter == 1 {
log.Println(lastBomberAlive.Name)
log.Println("has Won")
log.Println(lastBomberAlive.Name + "has Won")
user, err := getUserByID(db, lastBomberAlive.UserID)

user.GamesWon = user.GamesWon + 1

if err != nil {
log.Println(err)
}
user.GamesWon = user.GamesWon + 1

err = updatePlayerStats(db, *user)
if err != nil {
Expand Down
2 changes: 1 addition & 1 deletion Movement.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ func removePlayerFromList(l *list.List, b *Bomberman) {
Checks if the Movement is in Bounds of the Map. If and Array Position needs to be updated, checks if Field is Accessible and
updates the Player-Position if so.
*/
func (r *Bomberman) isMovementLegal(x int, y int) bool {
func (r *Bomberman) moveIfLegal(x int, y int) bool {
if x < 0 || y < 0 || x > (len(GameMap.Fields)-1)*FIELD_SIZE || y > (len(GameMap.Fields[x/FIELD_SIZE])-1)*FIELD_SIZE {
return false
}
Expand Down
88 changes: 47 additions & 41 deletions Server.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,27 +5,29 @@ import (
"encoding/json"
_ "github.com/go-sql-driver/mysql"
"golang.org/x/crypto/bcrypt"
"io/ioutil"
"log"
"net/http"
"os"
"strconv"
"strings"
"time"
)

//database

//handler url's
const (
POST_SAVEPICTURE = "/uploadImage"
WEBSOCKET_TEST = "/ws-test/"
GET_FETCH_ACTIVE_CONNECTIONS = "/fetchConnections/"
POST_LOGIN = "/login"
POST_REGISTER = "/register"
GET_FETCH_USER_ID = "/fetchUserId"
GET_SET_READY = "/setReady"
REQUEST_TIMEOUT_MILLIS = 500
)

var db *sql.DB
var ipTimers map[uint64]bool = make(map[uint64]bool)

func main() {
//Creates a log file
Expand All @@ -51,7 +53,6 @@ func main() {
//handlers
http.HandleFunc(POST_REGISTER, handleRegister)
http.HandleFunc(POST_LOGIN, handleLogin)
http.HandleFunc(POST_SAVEPICTURE, handleUploadImage)
http.HandleFunc(WEBSOCKET_TEST, handleWebsocketEndpoint)
http.HandleFunc(GET_FETCH_ACTIVE_CONNECTIONS, handleFetchActiveConnections)
http.HandleFunc(GET_FETCH_USER_ID, handleGetUserID)
Expand All @@ -63,8 +64,51 @@ func main() {
}
}

/*
converts ip to uint64, returns on err a 0 and an error from ParseUint
*/
func ipToInt(ip string) (uint64, error) {
log.Println(ip)
ipString := strings.Split(strings.ReplaceAll(ip, ".", ""), ":")[0]
log.Println(ipString)
ipInt, err := strconv.ParseUint(ipString, 10, 64)
if err != nil {
return 0, err
}
return ipInt, nil
}

/*
Checks if ip is allowed to do another request and starts a timer if allowed
*/
func checkIpTimer(ip string) bool {
if strings.HasPrefix(ip, "[::1]") { //For a local connection
ip = "127.0.0.1"
}
ipInt, err := ipToInt(ip)
if err != nil {
log.Println(err)
return false
}
if !ipTimers[ipInt] {
//Starts the timer for the ip
go func() {
ipTimers[ipInt] = true
time.Sleep(time.Millisecond * REQUEST_TIMEOUT_MILLIS)
ipTimers[ipInt] = false
}()
return true
}
return false
}

func handleGetSetReady(w http.ResponseWriter, r *http.Request) {
log.Println("handling handleGetSetReady request started...")
if !checkIpTimer(r.RemoteAddr) {
log.Println("not allowed")
w.WriteHeader(http.StatusTooManyRequests)
return
}
var user User
if dErr := CheckCookie(r, db, &user); dErr != nil {
log.Println(dErr.Error())
Expand Down Expand Up @@ -105,44 +149,6 @@ func handleWebsocketEndpoint(w http.ResponseWriter, r *http.Request) {
log.Println("handling websocket ended...")
}

func handleUploadImage(w http.ResponseWriter, r *http.Request) {
log.Println("Upload started...")
//Parsing ??? Maxsize = 10mb
if err := r.ParseMultipartForm(10 << 20); err != nil {
log.Println("Parsing failed: " + err.Error())
}
//Retrieving
file, handler, err := r.FormFile("imageFile")
if err != nil {
log.Println("Retrieving failed: " + err.Error())
return
}
defer file.Close()

log.Println("Uploaded File: ", handler.Filename)
log.Println("File size: ", handler.Size)
log.Println("MIME Header: ", handler.Header)

//Writing
//TO-DO: Change TempFile func
tempFile, err := ioutil.TempFile("temp-images", "upload-*.png")
if err != nil {
log.Println("Writing failed: " + err.Error())
return
}

defer tempFile.Close()

fileBytes, err := ioutil.ReadAll(file)
if err != nil {
log.Println(err.Error())
}

tempFile.Write(fileBytes)

log.Println(w, "Successfully Uploaded!")
}

func handleLogin(w http.ResponseWriter, r *http.Request) {
log.Println("Receiving Loginrequest...")
err := r.ParseForm()
Expand Down
2 changes: 1 addition & 1 deletion Websocket.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ func StartWebSocketConnection(w http.ResponseWriter, r *http.Request, db *sql.DB
bomber := NewBomberman(user.UserID, 0, 0, user.Username)
if sessionRunning {
bomber.Kill()
isOnePlayerAlive()
findWinner()
}
GameMap.Fields[pixToArr(bomber.PositionX)][pixToArr(bomber.PositionY)].Player.PushBack(bomber)

Expand Down

0 comments on commit 424eaf8

Please sign in to comment.