def parseConfigurationFile(conf_path): conf_file = open(conf_path, 'r') b = board() regcount = 0 for l in conf_file: m = re.match("[^;]*", l) #ignore everything after comments line = m.group(0) if re.match("\s*@(.*)",line): #if it is the device information line tokens = re.split(",",re.match(".*@(.*)",line).group(1)) #only look at stuff after the @ sign tokens = [x.strip("\t \r\n") for x in tokens] b._name = tokens[0] b._id = int(tokens[1]) b._path = tokens[2] b._baud_rate = tokens[3] elif re.match("\s*\d(.*)",line): tokens = re.split(",",line) #split on commas tokens = [x.strip("\t \r\n") for x in tokens] tf = lambda x: x == 'Y' or x == 'y' name = tokens[2] if tokens[2].rfind("/") == -1 else tokens[2][tokens[2].rindex("/")+1::] #Match everything after last / b._registers[regcount] = register(regcount, int(tokens[0]),tokens[1],name,tf(tokens[3]),tf(tokens[4]),tokens[5]) regcount += int(tokens[0]) elif re.match("\s*\#(.*)",line): #if it is the device information line tokens = re.split(",",re.match(".*\#(.*)",line).group(1)) #only look at stuff after the @ sign regcount = int(tokens[0]) elif re.match("\s*\$(.*)",line): #dont do anything for $64 line pass elif re.match("^\s*$", line): #Don't do anything for blank lines pass else: if __debug__: print "eek I don't understand this line :" + line return b
def __init__(self,score,life): pygame.sprite.Sprite.__init__(self) self.done=False self.clock=pygame.time.Clock() self.score=0 self.block_size=5 self.plyboard=board() self.grav=0 self.flag=0 self.rcount=0 self.lcount=0 self.rand=random.randrange(2) self.fball=pygame.sprite.Group() self.firecount=0 self.life=life self.score=score self.end=0 self.event=0
def createboard(self): """Creating the board instance""" #display_game = pygame.display.set_mode((1920,1080)) displaysize=[1920,1080] function(displaysize[0], displaysize[1]) function1(displaysize[0], displaysize[1]) return board(displaysize[0], displaysize[1], 1,0)
def main(): #print sys.argv if len(sys.argv) > 1: if str.isdigit(sys.argv[1]) and sys.argv[1] > 1: size = int(sys.argv[1]) print "Size:", size else: print "Usage: python solver.py <board size> <random iterations>" size = 3 print "Size:", size else: size = 3 print "Size:", size if len(sys.argv) > 2: if str.isdigit(sys.argv[2]) and sys.argv[2] >= 0: random_iter = int(sys.argv[2]) print "Random iterations:", random_iter else: print "Usage: python solver.py <board size> <random iterations>" random_iter = 15 print "Random iterations:", random_iter else: random_iter = 15 print "Random iterations:", random_iter b = board(size) c = board(b.size, b.copy_grid()) c.randomise(random_iter) b_node = tile_puzzle_a_star_node(b, 0) c_node = tile_puzzle_a_star_node(c, 0) #print "start:", b_node #print "goal:", c_node solver = a_star_solver() steps = solver.a_star(c_node, b_node) print "Start state" steps[0].show_state() print "--------------" steps_less_start = steps[1:] # Don't print the start state for step in steps_less_start: step.show_state() # steps includes the goal as well so -1 is the moves print "Did it in", len(steps)-1, "moves."
import pygame from pygame.locals import * from board import * SIZE = (WIDTH,HEIGHT) = (640,480) STEP = 20 GSIZE = (GW,GH) = (WIDTH/STEP,HEIGHT/STEP) FPS = 24 BLACK = pygame.Color( 0, 0, 0) WHITE = pygame.Color(255,255,255) RED = pygame.Color(255, 20, 20) GREEN = pygame.Color( 20,255, 20) BLUE = pygame.Color( 20, 20,255) sandPic = pygame.image.load('sand_small.jpg') gunnerPic = pygame.image.load('gunner_small.jpg') brd = board(GSIZE) # brd.set_block((5,5),True,(20,2))
from mainGame import * from gameClasses import * from board import * board = board() # just testing game = monoGame(board,2) game.start()
if not(len(move) == 2): print "That is not a valid move, try again.", statement1 continue moveFromTup = (int(move[0][1]), ord(move[0][0]) - 97) moveToTup = (int(move[1][1]), ord(move[1][0]) - 97) # Is the piece we want to move one we own? if not (moveFromTup in b.whitelist): print "You do not own", moveFromTup, "please select one of.", b.whitelist continue break move = (moveFromTup, moveToTup, b.NOTDONE) return move ### MAIN PROGRAM ### b = board(width, height, firstPlayer) b.printBoard() print("Welcome to checkers.") # Main game loop while b.gameWon == -1: # First it is the users turn userMove = getUserMove(b) try: b.moveWhite(*userMove) except Exception: print "Invalid move" continue # Then it is the computers turn temp = minMax2(b)
def start_game(): """ Start actual game loop """ reversi = board() global WINDOW WINDOW = pygame.display.set_mode((740, 680)) pygame.display.set_caption('Reversi Game') WINDOW.fill(B_COLOR) fps = pygame.time.Clock() draw_board(reversi) pygame.draw.rect(WINDOW, BG_COLOR, (1, 640 + 1, 638, 38)) pygame.draw.rect(WINDOW, BG_COLOR, (640 + 1, 1, 98, 678)) pygame.display.update() global STATUS STATUS = 'Please Play your move' buttons = [] buttons.append(Button(pygame.Rect(640, 640, 100, 40), (46, 125, 50), BG_COLOR, 'Exit')) mousex, mousey = (0, 0) while not reversi.is_game_over(): for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: for button in buttons: if button.rectang.collidepoint(event.pos): pygame.quit() sys.exit() mousex, mousey = event.pos row = mousey // 80 col = mousex // 80 if reversi.is_legal_move((row, col)): reversi.make_move(row, col) reversi.change_turn() reversi.calc_legal_moves() STATUS = 'Please Play your move' if not TWO_PLAYER and not reversi.is_game_over(): STATUS = 'I am thinking' draw_status() draw_count(reversi) draw_board(reversi) pygame.display.update() reversi.computer_move() reversi.change_turn() reversi.calc_legal_moves() else: STATUS = 'Invalid Move' pygame.draw.rect(WINDOW, BG_COLOR, (1, 640 + 1, 638, 38)) pygame.draw.rect(WINDOW, BG_COLOR, (640 + 1, 1, 98, 678)) draw_whose_turn(reversi) draw_status() draw_count(reversi) draw_board(reversi) draw_buttons(buttons, mousex, mousey) pygame.display.update() fps.tick(30) if reversi.winner == BLACK: STATUS = 'Black Wins' pic = pygame.image.load('../res/black_win.png') else: STATUS = 'White Wins' pic = pygame.image.load('../res/white_win.png') while True: for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() elif event.type == MOUSEMOTION: mousex, mousey = event.pos elif event.type == MOUSEBUTTONUP: for button in buttons: if button.rectang.collidepoint(event.pos): pygame.quit() sys.exit() pygame.draw.rect(WINDOW, BG_COLOR, (1, 640 + 1, 638, 38)) draw_status() draw_board(reversi) alpha = WINDOW.convert_alpha() alpha.blit(pic, (0, 0)) WINDOW.blit(alpha, (0, 0)) draw_buttons(buttons, mousex, mousey) pygame.display.update() fps.tick(30)
def main(display_game, levelnum, playerScore): class colors: def __init__(self, name, rgbval): self.name = name self.rgbval = rgbval def setcolornames(): global white, black, red white = colors('white', (255, 255, 255)) black = colors('black', (0, 0, 0)) red = colors('red', (255, 0, 0)) # Inital required variables initPos = [0, 0] delta_x = 0 delta_y = 0 fps = pygame.time.Clock() setcolornames() # Creating a board instance. displaysize = [display_game.get_size()[0], display_game.get_size()[1]] mainboard = board(displaysize[0], displaysize[1], levelnum, playerScore) function(displaysize[0], displaysize[1]) function1(displaysize[0], displaysize[1]) # Setting a window with width,height # display_game=pygame.display.set_mode((0,0),pygame.FULLSCREEN) # Creating the walls mainboard.drawgrid(initPos) mainboard.mario.wallList = mainboard.wallList mainboard.donkey.wallList = mainboard.wallList mainboard.mario.coinList = mainboard.coinList mainboard.mario.ladderList = mainboard.ladderList mainboard.mario.topladderList = mainboard.topladderList mainboard.mario.allladderposition = mainboard.allladderposition mainboard.donkey.topladderList = mainboard.topladderList mainboard.donkey.ladderList = mainboard.ladderList mainboard.mario.ladderposition = mainboard.ladderposition # print mainboard.ladderposition # print mainboard.topladderList mainboard.donkey.fireballsList = mainboard.fireballsList posX = mainboard.initPos[0] posY = mainboard.initPos[1] # mainboard.showgrid() x1 = posX y1 = posY game_status = True gamescore = -1 while game_status: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_status = False return (False, mainboard.mario.score) if event.key == pygame.K_a: if mainboard.mario.arrows[0] == 1: person.moveLeft(mainboard.mario) elif event.key == pygame.K_d: if mainboard.mario.arrows[1] == 1: person.moveRight(mainboard.mario) elif event.key == pygame.K_w: if mainboard.mario.arrows[2] == 1: person.moveUp(mainboard.mario) elif event.key == pygame.K_s: if mainboard.mario.arrows[3] == 1: person.moveDown(mainboard.mario) if event.key == pygame.K_SPACE: if mainboard.mario.arrows[4] == 1: person.Jump(mainboard.mario) if event.type == pygame.KEYUP: if event.key == pygame.K_a and mainboard.mario.deltaX \ < 0: person.stopside(mainboard.mario) mainboard.mario.image = mainboard.mario.marioleft if event.key == pygame.K_d and mainboard.mario.deltaX \ > 0: person.stopside(mainboard.mario) mainboard.mario.image = mainboard.mario.marioright if event.key == pygame.K_w or event.key == pygame.K_s: person.stopup(mainboard.mario) if mainboard.mario.score != gamescore: gamescore = mainboard.mario.score # print gamescore # print person.getLocation(mainboard.mario) # person.postopladders(mainboard.mario) # Code for ladders if mainboard.mario.movestate != 5: person.checkLadders(mainboard.mario) # Ends here # Code for fireballs goes here# mainboard.mario.fireballsList = mainboard.donkey.fireballsList # Ends here score = pygame.font.Font(None, 30) scoretext = score.render('Score ~ ' + str(gamescore), 1, (255, 255, 255)) livestext = score.render('Lives - ' + str(mainboard.mario.lives), 1, (255, 255, 255)) mainboard.AllList.update() mainboard.donkey.fireballsList.update() display_game.fill(black.rgbval) mainboard.donkey.fireballsList.draw(display_game) mainboard.AllList.draw(display_game) display_game.blit(scoretext, (50, 20)) display_game.blit(livestext, (1450, 20)) if mainboard.mario.lives == 0: score = pygame.font.Font(None, 50) scoretext = score.render('Final Score ~ ' + str(mainboard.mario.score), 1, (255, 255, 255)) game_status = False while not game_status: for event in pygame.event.get(): if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: game_status = True background = \ pygame.image.load('../images/background.jpg' ).convert_alpha() background = pygame.transform.scale(background, displaysize) display_game.blit(background, (0, 0)) over = pygame.font.Font(None, 50) overtext = over.render("Press 'q' to quit to main menu" , 1, (255, 255, 255)) display_game.blit(scoretext, (display_game.get_size()[0] * 0.6, display_game.get_size()[1] * 0.3)) display_game.blit(overtext, (display_game.get_size()[0] * 0.6, display_game.get_size()[1] * 0.5)) pygame.display.flip() fps.tick(60) return (False, mainboard.mario.score) if mainboard.mario.gameover: mainboard.mario.score += 50 return (True, mainboard.mario.score) pygame.display.flip() fps.tick(60)
def main(sc): pygame.init() FPS = 30 fpsClock = pygame.time.Clock() mygame=board(1100,750,20,18) for i in range (0,MIN_COINS): mygame.genCoin() mygame.createGame() DISPLAY=mygame.DISP myplayer=Player(100,710,sc) mydonkey=Donkey(100,45,50,70) princess=Princess(350,30,25,25) myfireball=fireball(150,90,20,30,'R') mydonkey.create(mygame) myplayer.create(mygame) princess.create(mygame) for b in mygame.balls: b.create(mygame) while mygame.gameend(myplayer)==False: if myplayer.gameWon(princess): pygame.mixer.music.load('win.wav') pygame.mixer.music.play() pygame.time.wait(100) main(myplayer.score+50) for b in mygame.balls: if myplayer.checkCollision(b): myplayer.Collide(mygame) if myplayer.checkCollision(mydonkey): myplayer.Collide(mygame) for event in pygame.event.get(): if event.type == QUIT: pygame.quit() sys.exit() if event.type == pygame.USEREVENT: mygame.genFireball() if event.type == pygame.KEYDOWN: if event.key == pygame.K_RIGHT: myplayer.move(mygame,'R',1) elif event.key == pygame.K_LEFT: myplayer.move(mygame,'L',1) elif event.key == pygame.K_UP: myplayer.move(mygame,'U',1) elif event.key == pygame.K_DOWN: myplayer.move(mygame,'D',1) elif event.key ==pygame.K_SPACE: if myplayer.canjump(mygame): myplayer.jump_new(15) keys_pressed = pygame.key.get_pressed() if keys_pressed[K_RIGHT]: myplayer.move(mygame,'R',PLAYER_SPEED) elif keys_pressed[K_LEFT]: myplayer.move(mygame,'L',PLAYER_SPEED) elif keys_pressed[K_UP]: myplayer.move(mygame,'U',PLAYER_SPEED_UP) elif keys_pressed[K_DOWN]: myplayer.move(mygame,'D',PLAYER_SPEED_UP) myplayer.gravity_new() myplayer.fall() myplayer.Collectcoin(mygame) mydonkey.move(mygame,300) for b in mygame.balls: b.move(mygame) b.fall() mygame.createGame() myplayer.create(mygame) mydonkey.create(mygame) princess.create(mygame) for b in mygame.balls: b.create(mygame) pygame.display.update() fpsClock.tick(FPS) mygame.DISP.fill(BLACK) fontobj = pygame.font.Font('freesansbold.ttf',32) score = fontobj.render("Score: " + str(myplayer.score),True,GREEN,BLUE) score_rect = score.get_rect() score_rect.left,score_rect.top=0,0 mygame.DISP.blit(score,score_rect) sobj = fontobj.render('Game Over',True,GREEN,BLUE) robj = sobj.get_rect() robj.center = (200,150) mygame.DISP.blit(sobj,robj) pygame.display.flip() pygame.mixer.music.load('gameover.mp3') pygame.mixer.music.play() time.sleep(3) pygame.quit() sys.exit()
def main(argv): """The main arguments occur. All variables are initialized and set to the respective values, whether an integer or a class definition. All mouse motion is tracked once clicked, given statements for the click event such as selecting which level of game to play, sound on/off, and exiting the game execute. Once a game is selected, the board loads with instructions for placing pieces on the board. The game starts as soon as the last piece(patrol boat) is placed on the player's board. Once a ship has been sunk, a message will display saying that respective ship has been destroyed and if the final ship is sunk, a winning message will dispaly. A new game can be started at any time using the F keys to select which level of play, turn on/off sound, or to return to the main menu as well as quit the game. All actions on the boards are set to be logged in a seperate text file for documentation and debugging. """ screen = init() print("Drawing main menu.") title(screen) gamemode = 0 global gamedifficulty global soundon gamestarted = False spacetaken = 0 direction = 0 turn = 0 temp = 0 shipmessage = '' hit = pygame.mixer.Sound('resources\hit.ogg') miss = pygame.mixer.Sound('resources\miss.ogg') music = pygame.mixer.Sound('resources\TheLibertyBellMarch.ogg') # Continuous music music.play(loops=-1) #get current hostname enteredip = list(getIP()) while 1: mouseClicked = False for event in pygame.event.get(): pressed = pygame.key.get_pressed() # If the user clicks the x at the top of the window if event.type == pygame.QUIT: gamemode = 4 # If the user presses F1 elif pressed[pygame.K_F1]: gamemode = 1 gamestarted = False gamedifficulty = 0 # If the user presses F2 elif pressed[pygame.K_F2]: gamemode = 1 gamestarted = False gamedifficulty = 1 # If the user presses F3 elif pressed[pygame.K_F3]: gamemode = 1 gamestarted = False gamedifficulty = 2 # If the user presses F4 elif pressed[pygame.K_F4]: gamemode = 2 gamestarted = False # If the user presses F5 elif pressed[pygame.K_F5]: gamemode = 0 gamestarted = False #If the user presses F6 elif pressed[pygame.K_F6]: if (soundon == 1): pygame.mixer.pause() soundon = 0 elif (soundon == 0): pygame.mixer.unpause() soundon = 1 #If the user presses F12 elif pressed[pygame.K_F12]: gamemode = 4 # If the mouse is moved, record the current coordinates elif event.type == MOUSEMOTION: mousex, mousey = event.pos # If the mouse is clicked, say so and record the current coordinates elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseClicked = True # Blanket catch for any other key press, keep this at the end! elif event.type == KEYDOWN: if event.key == K_BACKSPACE: enteredip = enteredip[0:-1] elif event.key == K_RETURN: pass elif (event.key >= 48 and event.key <= 57) or event.key == 46: enteredip.append(chr(event.key)) # If we're in gamemode 0, show the titlescreen if (gamemode == 0): gamemode = title(screen, mousex, mousey, mouseClicked) if gamemode != 0: continue # If we're in gamemode 1, show the game screen if (gamemode == 1): if not gamestarted: print("Starting a new game") single(screen) place = 0 spacetaken = 0 turn = 0 playerboard = board() playerattackboard = board() cpuboard = board() cpuattackboard = board() comp = AI() comp.placeships(shiparray, cpuboard) gamestarted = True if (place == 0): singleinstructions( screen, 'Please place the Aircraft Carrier on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 1): singleinstructions( screen, 'Please place the Battleship on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 2): singleinstructions( screen, 'Please place the Submarine on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 3): singleinstructions( screen, 'Please place the Destroyer on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 4): singleinstructions( screen, 'Please place the Patrol Boat on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 5): singleinstructions( screen, 'Please select spot on attack board to start game', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) #else: #singleinstructions(screen, '', '', 475, 500) drawboards(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2) boxx2, boxy2 = whatbox(mousex, mousey, XMARGIN2) # user places ships on board if (boxx2 != None and boxy2 != None) and mouseClicked: if (place < 5): checkplace = 0 spacepressed = pressed[pygame.K_SPACE] if not (spacepressed): hold = boxy2 if ((shiparray[place] + boxy2) < 11): if (checkplace == 0): for y in range(shiparray[place]): if ((playerboard.returnpiece(boxx2, hold)) != 0): checkplace = 1 else: hold = hold + 1 for y in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece( shiparray[place], boxx2, boxy2) boxy2 = boxy2 + 1 if (y == (shiparray[place] - 1)): place = place + 1 elif (spacepressed): hold = boxx2 if ((shiparray[place] + boxx2) < 11): if (checkplace == 0): for x in range(shiparray[place]): if ((playerboard.returnpiece(hold, boxy2)) != 0): checkplace = 1 else: hold = hold + 1 for x in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece( shiparray[place], boxx2, boxy2) boxx2 = boxx2 + 1 if (x == (shiparray[place] - 1)): place = place + 1 boxx, boxy = whatbox(mousex, mousey, XMARGIN) # game ready to play if (place >= 5): if (turn == 0): if (boxx != None and boxy != None) and mouseClicked: place = place + 1 temp = cpuboard.checkforhitormiss(boxx, boxy) if (temp == 9): blah = 0 else: playerattackboard.setpiece(temp, boxx, boxy) log_message('Player Move', playerattackboard.returnboard()) if (temp == 7): printstatus(screen, 'Miss') miss.play(loops=0) else: printstatus(screen, 'Hit') hit.play(loops=0) if (checkforwin(playerattackboard)): printstatus(screen, 'You win!') turn = -1 else: checkforshipsunk(playerattackboard, temp, screen) turn = 1 elif (turn == 1): if (gamedifficulty == 0): comp.attack(playerboard, cpuattackboard) log_message('Easy CPU Move', cpuattackboard.returnboard()) elif (gamedifficulty == 1): comp.attack2(playerboard, cpuattackboard) log_message('Harder CPU Move', cpuattackboard.returnboard()) elif (gamedifficulty == 2): comp.attack3(playerboard, cpuattackboard) log_message('Hardest CPU Move', cpuattackboard.returnboard()) if (checkforwin(cpuattackboard)): printstatus(screen, 'Computer Wins!') turn = -1 else: turn = 0 # If we're in gamemode 2, show the multiplayer screen if (gamemode == 2): option = multi(screen, "".join(enteredip), mousex, mousey, mouseClicked) if (option == 1): multi_game_init(None) ip = getIP() gamemode = 3 playernumber = 1 elif (option == 2): ip = "".join(enteredip) multi_game_init(ip) gamemode = 3 playernumber = 2 elif (option == 3): gamemode = 0 if (gamemode == 3): s = get_socket(ip) preamble = get_preamble(s) status, turn = preamble.split('.') status = int(status) turn = int(turn) boards = get_boards(s) if (status == 0): gamemode = 0 if not gamestarted: try: playernumber except NameError: print( 'Something went horribly wrong... I don\'t know whose turn it is!' ) sys.exit(1) print("Starting a new multiplayer game") single(screen) place = 0 spacetaken = 0 turn = 0 playerboard = board() playerattackboard = board() enemyboard = board() enemyattackboard = board() gameboards = [ playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard() ] gamestarted = True if (place == 0): multiinstructions( screen, 'Please place the Aircraft Carrier on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 1): multiinstructions( screen, 'Please place the Battleship on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 2): multiinstructions( screen, 'Please place the Submarine on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 3): multiinstructions( screen, 'Please place the Destroyer on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 4): multiinstructions( screen, 'Please place the Patrol Boat on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) boxx, boxy = whatbox(mousex, mousey, XMARGIN) boxx2, boxy2 = whatbox(mousex, mousey, XMARGIN2) # user places ships on board if (place < 5 and place >= 0): drawboards(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2) if boxx2 != None and boxy2 != None and mouseClicked: checkplace = 0 spacepressed = pressed[pygame.K_SPACE] if not (spacepressed): hold = boxy2 if ((shiparray[place] + boxy2) < 11): if (checkplace == 0): for y in range(shiparray[place]): if ((playerboard.returnpiece(boxx2, hold)) != 0): checkplace = 1 else: hold = hold + 1 for y in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece( shiparray[place], boxx2, boxy2) boxy2 = boxy2 + 1 if (y == (shiparray[place] - 1)): place = place + 1 elif (spacepressed): hold = boxx2 if ((shiparray[place] + boxx2) < 11): if (checkplace == 0): for x in range(shiparray[place]): if ((playerboard.returnpiece(hold, boxy2)) != 0): checkplace = 1 else: hold = hold + 1 for x in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece( shiparray[place], boxx2, boxy2) boxx2 = boxx2 + 1 if (x == (shiparray[place] - 1)): place = place + 1 # game ready to play if (place > 6): if (turn == playernumber): multiinstructions( screen, 'Please select spot on attack board to start game', '', 100, 500) if (boxx != None and boxy != None) and mouseClicked: shipmessage = '' place = place + 1 temp = enemyboard.checkforhitormiss(boxx, boxy) if (temp == 9): pass else: playerattackboard.setpiece(temp, boxx, boxy) log_message('Player Move', playerattackboard.returnboard()) if (temp == 7): printstatus(screen, 'Miss') miss.play(loops=0) else: printstatus(screen, 'Hit') hit.play(loops=0) if (checkforwin(playerattackboard)): place = -1 else: temp_shipmessage = checkforshipsunk_multi( playerattackboard, temp, screen) if temp_shipmessage: shipmessage = temp_shipmessage gameboards = [ playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard() ] send_boards(s, gameboards) else: #waiting for other player to play, don't accept clicks multiinstructions( screen, 'Please wait for your opponent to play!', shipmessage, 200, 250) if (playernumber == 1): playerboard.setboard(boards[0]) playerattackboard.setboard(boards[1]) enemyboard.setboard(boards[2]) enemyattackboard.setboard(boards[3]) else: playerboard.setboard(boards[2]) playerattackboard.setboard(boards[3]) enemyboard.setboard(boards[0]) enemyattackboard.setboard(boards[1]) drawboards_multi(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2) if (place == 6): # waiting for server to signal game is started multiinstructions( screen, 'All Set!', 'Waiting for the other player to finish placing their ships...', 300, 20) if (status == 2): s.close() s = get_socket(ip) preamble = get_preamble(s) status, turn = preamble.split('.') status = int(status) turn = int(turn) boards = get_boards(s) if (playernumber == 1): playerboard.setboard(boards[0]) enemyboard.setboard(boards[2]) else: playerboard.setboard(boards[2]) enemyboard.setboard(boards[0]) place += 1 if (place == 5): multiinstructions( screen, 'All Set!', 'Waiting for the other player to finish placing their ships...', 300, 20) if (turn == playernumber): print("Player ready", playernumber) gameboards = [ playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard() ] send_boards(s, gameboards) place += 1 if (place == -1): printstatus(screen, 'You win!') s.close() # If we're in gamemode 4, we're quitting if (gamemode == 4): screen.fill(color['black']) font = pygame.font.Font('resources/alphbeta.ttf', 70) thanks = font.render("Thanks for playing!", False, color['white']) thanksRect = thanks.get_rect() thanksRect.center = (400, 300) screen.blit(thanks, thanksRect) pygame.mixer.quit() pygame.display.update() print('Quitting :[') pygame.time.wait(1500) pygame.quit() sys.exit(0) # redraw screen pygame.display.update() fpsClock.tick(60)
from player import * from board import * if __name__ == '__main__': while True: try: size = int(input('Of what size do you want the board to be?\n')) break except: print('Invalid input content!') board = board(size) players = [None, None] for i in range(2): while True: z = input('Who do you want to play ' + ('O' if i else 'X') + '? (AI/human)\n').lower() if z == 'ai': players[i] = AI(board, i + 1) player.AI_player += 1 break elif z == 'human': players[i] = keyboard_player(board, i + 1) break print('Invalid input content!') while not players[0].play() and not players[1].play(): pass print(board)
import pygame from settings import * from player import * from board import * from ghost import * import random pygame.init() pygame.display.update() clock = pygame.time.Clock() pacman = player() brd = board() ghosts = [] ghosts.append(reda()) ghosts.append(yellowa()) ghosts.append(bluea()) ghosts.append(pinka()) total = len(brd.rect) score = 0 start_time = pygame.time.get_ticks() while True: x_change = 0 y_change = 0 screen.fill(black)
def fillObvious(Sudoku): ctr = 1 while (ctr > 0): ctr = 0 for i in range(9): for j in range(9): if (Sudoku.State[i][j] == '_'): valid = Sudoku.get_valid(i, j) if (len(valid) == 1): Sudoku.State[i][j] = valid[0] ctr += 1 return Sudoku initState = [[5, 3, '_', '_', 7, '_', '_', '_', '_'], [6, '_', '_', 1, 9, 5, '_', '_', '_'], ['_', 9, 8, '_', '_', '_', '_', 6, '_'], [8, '_', '_', '_', 6, '_', '_', '_', 3], [4, '_', '_', 8, '_', 3, '_', '_', 1], [7, '_', '_', '_', 2, '_', '_', '_', 6], ['_', 6, '_', '_', '_', '_', 2, 8, '_'], ['_', '_', '_', 4, 1, 9, '_', '_', 5], ['_', '_', '_', '_', 8, '_', '_', 7, 9]] Sudoku = board(initState) print(Sudoku) partialSudoku = fillObvious(Sudoku) print(partialSudoku)
from board import * import os game_board = board() def check_input(player): while True: hey_you = raw_input(player +"'s move") try: int(hey_you) return int(hey_you) break except ValueError: continue def game_init(): while True: game_board.display() game_board.make_move("x") game_board.win_test() os.system('cls') game_board.display() game_board.make_move("o") game_board.win_test() os.system('cls')
def main(argv): """The main arguments occur. All variables are initialized and set to the respective values, whether an integer or a class definition. All mouse motion is tracked once clicked, given statements for the click event such as selecting which level of game to play, sound on/off, and exiting the game execute. Once a game is selected, the board loads with instructions for placing pieces on the board. The game starts as soon as the last piece(patrol boat) is placed on the player's board. Once a ship has been sunk, a message will display saying that respective ship has been destroyed and if the final ship is sunk, a winning message will dispaly. A new game can be started at any time using the F keys to select which level of play, turn on/off sound, or to return to the main menu as well as quit the game. All actions on the boards are set to be logged in a seperate text file for documentation and debugging. """ screen = init() print ("Drawing main menu.") title(screen) gamemode = 0 global gamedifficulty global soundon gamestarted = False spacetaken = 0 direction = 0 turn = 0 temp = 0 shipmessage ='' hit = pygame.mixer.Sound('resources\hit.ogg') miss = pygame.mixer.Sound('resources\miss.ogg') music = pygame.mixer.Sound('resources\TheLibertyBellMarch.ogg') # Continuous music music.play(loops = -1) #get current hostname enteredip = list(getIP()) while 1: mouseClicked = False for event in pygame.event.get(): pressed = pygame.key.get_pressed() # If the user clicks the x at the top of the window if event.type == pygame.QUIT: gamemode = 4 # If the user presses F1 elif pressed[pygame.K_F1]: gamemode = 1 gamestarted = False gamedifficulty = 0 # If the user presses F2 elif pressed[pygame.K_F2]: gamemode = 1 gamestarted = False gamedifficulty = 1 # If the user presses F3 elif pressed[pygame.K_F3]: gamemode = 1 gamestarted = False gamedifficulty = 2 # If the user presses F4 elif pressed[pygame.K_F4]: gamemode = 2 gamestarted = False # If the user presses F5 elif pressed[pygame.K_F5]: gamemode = 0 gamestarted = False #If the user presses F6 elif pressed[pygame.K_F6]: if (soundon == 1): pygame.mixer.pause() soundon = 0 elif (soundon == 0): pygame.mixer.unpause() soundon = 1 #If the user presses F12 elif pressed[pygame.K_F12]: gamemode = 4 # If the mouse is moved, record the current coordinates elif event.type == MOUSEMOTION: mousex, mousey = event.pos # If the mouse is clicked, say so and record the current coordinates elif event.type == MOUSEBUTTONUP: mousex, mousey = event.pos mouseClicked = True # Blanket catch for any other key press, keep this at the end! elif event.type == KEYDOWN: if event.key == K_BACKSPACE: enteredip = enteredip[0:-1] elif event.key == K_RETURN: pass elif (event.key >= 48 and event.key <= 57) or event.key == 46: enteredip.append(chr(event.key)) # If we're in gamemode 0, show the titlescreen if (gamemode == 0): gamemode = title(screen, mousex, mousey, mouseClicked) if gamemode != 0: continue # If we're in gamemode 1, show the game screen if (gamemode == 1): if not gamestarted: print ("Starting a new game") single(screen) place = 0 spacetaken = 0 turn = 0 playerboard = board() playerattackboard = board() cpuboard = board() cpuattackboard = board() comp = AI() comp.placeships(shiparray, cpuboard) gamestarted = True if (place == 0): singleinstructions(screen, 'Please place the Aircraft Carrier on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 1): singleinstructions(screen, 'Please place the Battleship on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 2): singleinstructions(screen, 'Please place the Submarine on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 3): singleinstructions(screen, 'Please place the Destroyer on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 4): singleinstructions(screen, 'Please place the Patrol Boat on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) elif (place == 5): singleinstructions(screen, 'Please select spot on attack board to start game', 'Click to place ships down from point, hold space and click to place ships right from point', 475, 500) #else: #singleinstructions(screen, '', '', 475, 500) drawboards(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2) boxx2, boxy2 = whatbox(mousex, mousey, XMARGIN2) # user places ships on board if (boxx2 != None and boxy2 != None) and mouseClicked: if (place < 5): checkplace = 0 spacepressed = pressed[pygame.K_SPACE] if not (spacepressed): hold = boxy2 if ((shiparray[place]+boxy2) < 11): if (checkplace == 0): for y in range(shiparray[place]): if ((playerboard.returnpiece(boxx2,hold)) != 0): checkplace = 1 else: hold = hold + 1 for y in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece(shiparray[place],boxx2,boxy2) boxy2 = boxy2 + 1 if (y == (shiparray[place]-1)): place = place + 1 elif (spacepressed): hold = boxx2 if ((shiparray[place]+boxx2) < 11): if (checkplace == 0): for x in range(shiparray[place]): if ((playerboard.returnpiece(hold,boxy2)) != 0): checkplace = 1 else: hold = hold + 1 for x in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece(shiparray[place],boxx2,boxy2) boxx2 = boxx2 + 1 if (x == (shiparray[place]-1)): place = place + 1 boxx, boxy = whatbox(mousex, mousey, XMARGIN) # game ready to play if (place >= 5): if (turn == 0): if (boxx != None and boxy != None) and mouseClicked: place = place + 1 temp = cpuboard.checkforhitormiss(boxx,boxy) if (temp == 9): blah = 0 else: playerattackboard.setpiece(temp,boxx,boxy) log_message('Player Move', playerattackboard.returnboard()) if (temp == 7): printstatus(screen, 'Miss') miss.play(loops = 0) else: printstatus(screen, 'Hit') hit.play(loops = 0) if (checkforwin(playerattackboard)): printstatus(screen, 'You win!') turn = -1 else: checkforshipsunk(playerattackboard, temp, screen) turn = 1 elif (turn == 1): if (gamedifficulty == 0): comp.attack(playerboard, cpuattackboard) log_message('Easy CPU Move', cpuattackboard.returnboard()) elif (gamedifficulty == 1): comp.attack2(playerboard, cpuattackboard) log_message('Harder CPU Move', cpuattackboard.returnboard()) elif (gamedifficulty == 2): comp.attack3(playerboard, cpuattackboard) log_message('Hardest CPU Move', cpuattackboard.returnboard()) if (checkforwin(cpuattackboard)): printstatus(screen, 'Computer Wins!') turn = -1 else: turn = 0 # If we're in gamemode 2, show the multiplayer screen if (gamemode == 2): option = multi(screen, "".join(enteredip), mousex, mousey, mouseClicked) if (option == 1): multi_game_init(None) ip = getIP() gamemode = 3 playernumber = 1 elif (option == 2): ip = "".join(enteredip) multi_game_init(ip) gamemode = 3 playernumber = 2 elif (option == 3): gamemode = 0 if (gamemode == 3): s = get_socket(ip) preamble = get_preamble(s) status, turn = preamble.split('.') status = int(status) turn = int(turn) boards = get_boards(s) if (status == 0): gamemode = 0 if not gamestarted: try: playernumber except NameError: print ('Something went horribly wrong... I don\'t know whose turn it is!') sys.exit(1) print ("Starting a new multiplayer game") single(screen) place = 0 spacetaken = 0 turn = 0 playerboard = board() playerattackboard = board() enemyboard = board() enemyattackboard = board() gameboards = [playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard()] gamestarted = True if (place == 0): multiinstructions(screen, 'Please place the Aircraft Carrier on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 1): multiinstructions(screen, 'Please place the Battleship on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 2): multiinstructions(screen, 'Please place the Submarine on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 3): multiinstructions(screen, 'Please place the Destroyer on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) elif (place == 4): multiinstructions(screen, 'Please place the Patrol Boat on your board!', 'Click to place ships down from point, hold space and click to place ships right from point', 200, 20) boxx, boxy = whatbox(mousex, mousey, XMARGIN) boxx2, boxy2 = whatbox(mousex, mousey, XMARGIN2) # user places ships on board if (place < 5 and place >= 0): drawboards(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2) if boxx2 != None and boxy2 != None and mouseClicked: checkplace = 0 spacepressed = pressed[pygame.K_SPACE] if not (spacepressed): hold = boxy2 if ((shiparray[place]+boxy2) < 11): if (checkplace == 0): for y in range(shiparray[place]): if ((playerboard.returnpiece(boxx2,hold)) != 0): checkplace = 1 else: hold = hold + 1 for y in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece(shiparray[place],boxx2,boxy2) boxy2 = boxy2 + 1 if (y == (shiparray[place]-1)): place = place + 1 elif (spacepressed): hold = boxx2 if ((shiparray[place]+boxx2) < 11): if (checkplace == 0): for x in range(shiparray[place]): if ((playerboard.returnpiece(hold,boxy2)) != 0): checkplace = 1 else: hold = hold + 1 for x in range(shiparray[place]): if (checkplace == 1): break else: playerboard.setpiece(shiparray[place],boxx2,boxy2) boxx2 = boxx2 + 1 if (x == (shiparray[place]-1)): place = place + 1 # game ready to play if (place > 6): if (turn == playernumber): multiinstructions(screen, 'Please select spot on attack board to start game', '', 100, 500) if (boxx != None and boxy != None) and mouseClicked: shipmessage = '' place = place + 1 temp = enemyboard.checkforhitormiss(boxx,boxy) if (temp == 9): pass else: playerattackboard.setpiece(temp,boxx,boxy) log_message('Player Move', playerattackboard.returnboard()) if (temp == 7): printstatus(screen, 'Miss') miss.play(loops = 0) else: printstatus(screen, 'Hit') hit.play(loops = 0) if (checkforwin(playerattackboard)): place = -1 else: temp_shipmessage = checkforshipsunk_multi(playerattackboard, temp, screen) if temp_shipmessage: shipmessage = temp_shipmessage gameboards = [playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard()] send_boards(s, gameboards) else: #waiting for other player to play, don't accept clicks multiinstructions(screen, 'Please wait for your opponent to play!', shipmessage, 200, 250) if (playernumber == 1): playerboard.setboard(boards[0]) playerattackboard.setboard(boards[1]) enemyboard.setboard(boards[2]) enemyattackboard.setboard(boards[3]) else: playerboard.setboard(boards[2]) playerattackboard.setboard(boards[3]) enemyboard.setboard(boards[0]) enemyattackboard.setboard(boards[1]) drawboards_multi(playerattackboard, playerboard, screen, XMARGIN, XMARGIN2) if (place == 6): # waiting for server to signal game is started multiinstructions(screen, 'All Set!', 'Waiting for the other player to finish placing their ships...', 300, 20) if (status == 2): s.close() s = get_socket(ip) preamble = get_preamble(s) status, turn = preamble.split('.') status = int(status) turn = int(turn) boards = get_boards(s) if (playernumber == 1): playerboard.setboard(boards[0]) enemyboard.setboard(boards[2]) else: playerboard.setboard(boards[2]) enemyboard.setboard(boards[0]) place += 1 if (place == 5): multiinstructions(screen, 'All Set!', 'Waiting for the other player to finish placing their ships...', 300, 20) if (turn == playernumber): print ("Player ready", playernumber) gameboards = [playerboard.returnboard(), playerattackboard.returnboard(), enemyboard.returnboard(), enemyattackboard.returnboard()] send_boards(s, gameboards) place += 1 if (place == -1): printstatus(screen, 'You win!') s.close() # If we're in gamemode 4, we're quitting if (gamemode == 4): screen.fill(color['black']) font = pygame.font.Font('resources/alphbeta.ttf', 70) thanks = font.render("Thanks for playing!", False, color['white']) thanksRect = thanks.get_rect() thanksRect.center = (400, 300) screen.blit(thanks, thanksRect) pygame.mixer.quit() pygame.display.update() print('Quitting :[') pygame.time.wait(1500) pygame.quit() sys.exit(0) # redraw screen pygame.display.update() fpsClock.tick(60)
v = 0 for i in b[s:s+l]: v += i return v def recv_udp(self): event = self.udp.readDatagram(12)[0] if len(event) < 12: return _id = self.get_obj(event, 0, 4) _num = self.get_obj(event, 4, 4) _val = self.get_obj(event, 8, 4) self.event_handle(_id, _num, _val) def set_led(self, num, state): num_tup = (self.textLed1, self.textLed2, self.textLed3, self.textLed4) state_tup = ("background-color:white", "background-color:green") num_tup[num].setStyleSheet(state_tup[state]) def event_handle(self, id, num, val): event_cb_tup = ( "NULL", self.set_led) print(id, num, val) event_cb_tup[id](num, val) if __name__ == "__main__": main_board = board()
from mainGame import * from gameClasses import * from board import * board = board() game = monoGame(board,2) game.start()
if pos == None: raise Exception("Get pos for none, need to check implement") return pos if __name__ == '__main__': tmp_dict = { (4, 7): 2, (5, 7): 2, (5, 6): 2, (6, 5): 2, (7, 4): 2, (8, 3): 1, (8, 4): 1, (8, 6): 1, (7, 5): 1, (6, 6): 1, (3, 8): 1 } lst = [(1, (6, 6)), (2, (6, 5)), (1, (7, 5)), (2, (7, 4)), (1, (8, 4)), (2, (5, 7)), (1, (8, 6)), (2, (5, 6)), (1, (8, 3)), (2, (4, 7)), (1, (3, 8))] b = board(15) for l in lst: b.place(l) print(b) new_state = state(2, 15, tmp_dict, (1, (3, 8)), 0) new_state.set_children(new_state.successors()) for child in new_state.get_children(): print(child)
import board board = board.board thing = board(5, 5, 5) print(board.grid)
''' Aaron Gotlieb ''' import sys from board import * #from piece import * print("Welcome to (zork)Checkers!") print('You will be 1') print("Ready Player 1") # board/initial setup arr = [] b = board(arr) def coordinateCheck(letter): string = 'input %s coordinate: ' % letter while True: try: x = int(input(string)) except ValueError: print("%s coordinate must be a number! (integer)" % letter) continue if (x > 8 or x < 0): print("%s coordinate must be between 0 and 7!" % letter) else: print('well done!') return(x) def direction(): print('now enter direction (topLeft, topRight, botLeft or botRight)') while True: