def act1(): from food import Food from drink import Drink from dressing import Dressing food1 = Food('High Five Power Salad', 1580, 476) food2 = Food('Smoked Duck & Honey Nut Salad', 1080, 220) food3 = Food("Grilled Chicken & Egg Salad", 980, 262) food4 = Food('Prosciutto & Mimolette Cheese Salad', 980, 139) food5 = Food('Garlic Shrimp Salad', 1280, 113) food6 = Food('Skip', 0, 0) foods = [food1, food2, food3, food4, food5, food6] dressing1 = Dressing('Classic Caesar', 0, 73) dressing2 = Dressing('Onion Soy', 0, 107) dressing3 = Dressing('Creamy Seasame', 0, 67) dressing4 = Dressing('Honey Mustard', 0, 127) dressing5 = Dressing('Balsamic Vinaigrette', 0, 127) dressing6 = Dressing('Skip', 0, 0) dressings = [ dressing1, dressing2, dressing3, dressing4, dressing5, dressing6 ] drink1 = Drink('Green Smoothie', 360, 126) drink2 = Drink('Homemade Soup', 360, 234) drink3 = Drink('Iced Coffee', 100, 15) drink4 = Drink('Seasonal Smoothie', 500, 245) drink5 = Drink('Skip', 0, 0) drinks = [drink1, drink2, drink3, drink4, drink5] print() print('***** FOOD MENU *****') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print() print('***** DRESSING MENU *****') index = 0 for dressing in dressings: print(str(index) + '. ' + dressing.info()) index += 1 print() print('***** DRINK MENU *****') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') #lim #if choose invalid numbers print('--------------------') while True: food_order = input('Please select a number from the food menu: ') if food_order == '0' or food_order == '1' or food_order == '2' or food_order == '3' or food_order == '4' or food_order == '5' or food_order == '6': selected_food = foods[int(food_order)] else: print("Please insert a valid number.") print() continue break while True: dressing_order = input( 'Please select a number from the dressing menu: ') if dressing_order == '0' or dressing_order == '1' or dressing_order == '2' or dressing_order == '3' or dressing_order == '4' or dressing_order == '5': selected_dressing = dressings[int(dressing_order)] else: print("Please insert a valid number.") print() continue break while True: drink_order = input('Please select a number from the drink menu: ') if drink_order == '0' or drink_order == '1' or drink_order == '2' or drink_order == '3' or drink_order == '4' or drink_order == '5': selected_drink = drinks[int(drink_order)] else: print("Please insert a valid number.") print() continue break count = int( input( 'How many sets would you like to purchase?(10% off when you purchase 3 sets): ' )) result = selected_food.get_total_price( count) + selected_drink.get_total_price(count) #print total # sophia #grace print() print('----------------------------------------------------------') print('Here is your total order:') print() print( str(selected_food.name) + ' ¥' + str(selected_food.price) + ' x ' + str(count)) print( str(selected_dressing.name) + ' ¥' + str(selected_dressing.price) + ' x ' + str(count)) print( str(selected_drink.name) + ' ¥' + str(selected_drink.price) + ' x ' + str(count)) if count >= 3: print('10% discount') else: print(' ') print('----------------------------------------------------------') print('Your total is ' + str(result) + ' Yen') print() print('Thank you for using W-Delivers! We hope to serve you again soon!') print('----------------------------------------------------------') print() print('Your order is on its way') #lim import time for i in range(100): print('.', end='') time.sleep(1)
def generateFood(self, count): for i in range(0, count): self.Food.append(Food(self))
from turtle import Screen from snake import Snake import time from food import Food from scoreboard import Scoreboard screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("My Snake Game") screen.tracer(0) snake = Snake() food = Food() scoreboard = Scoreboard() screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.left, "Left") screen.onkey(snake.right, "Right") game_is_on = True while game_is_on: screen.update() time.sleep(0.1) snake.move() #Detect collision with food if snake.head.distance(food) < 15:
from food import Food from drink import Drink food1 = Food('Sandwich', 5, 330) print(food1.info()) # Add an argument to Drink() drink1 = Drink('Coffee', 3, 180) # Delete the following line print(drink1.info())
def spawnFood(self): x = (random.random() * (self.ARENA_WIDTH - 50) + 50) y = (random.random() * (self.ARENA_HEIGHT - 50) + 50) f = Food(x, y, 40) self.food.append(f)
from food import Food from food import getFoodCost from food import sumFoods from descent import descent import random weekFood = Food(0.0, 7 * 2000, 7 * 100, 7 * 100, 0, 0) banana = Food(2.60, 880, 11, 230, 1, 2.8) potato = Food(2.00, 760, 20, 170, 0, 2.5) rice = Food(2.50, 1300, 27, 280, 1, 0.8) chicken = Food(11.00, 1640, 310, 0, 10, 3) pork = Food(8.50, 2970, 257, 0, 77, 1.0) beef = Food(14.00, 2500, 260, 0, 60, 1.0) eggs = Food(0.50, 1550, 130, 11, 33, 1.0) #oats = Food(4.00, 3890, 169, 663, 0, 1.0) #yoghurt = Food(2.50, 130, 9, 10.5, 3.2, 4) # с кисело мляко oats = Food(8.50 / 3, (260 + 3890) / 3, (18 + 169) / 3, (21 + 663) / 3, 6.4 / 3, 3) foods = [banana, potato, rice, chicken, pork, beef, eggs, oats] def randomStart(): result = [] for i in range(len(foods)): result.append(random.random() * 3) return result
from food import Food from drink import Drink food1 = Food("Roti Lapis", 5, 330) food2 = Food("Kue Coklat", 4, 450) food3 = Food("Kue Sus", 2, 180) foods = [food1, food2, food3] drink1 = Drink("Kopi", 3, 180) drink2 = Drink("Jus Jeruk", 2, 350) drink3 = Drink("Espresso", 3, 30) drinks = [drink1, drink2, drink3] print("Makanan") index = 0 for food in foods: print(str(index) + ". " + food.info()) index += 1 print("Minuman") index = 0 for drink in drinks: print(str(index) + ". " + drink.info()) index += 1 print("--------------------") food_order = int(input("Masukkan nomor makanan: ")) selected_food = foods[food_order]
SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS) dx = random.uniform(MINIMUM_BALL_DX, MAXIMUM_BALL_DX) dy = random.uniform(MINIMUM_BALL_DY, MAXIMUM_BALL_DY) radius = random.randint(MINIMUM_BALL_RADIUS, MAXIMUM_BALL_RADIUS) color = (random.random(), random.random(), random.random()) MY_BALL2 = Ball(x, y, dx, dy, radius, color) BALLS.append(MY_BALL2) for i in range(NUMBERS_OF_FOODS): x_cor = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS) y_cor = random.randint(-SCREEN_HEIGHT + MAXIMUM_BALL_RADIUS, SCREEN_HEIGHT - MAXIMUM_BALL_RADIUS) color = (random.random(), random.random(), random.random()) #food.eat(new_x_cor,new_y_cor, new_color, 4)= new_Food = Food(x_cor, y_cor, color, 4) FOOD.append(new_Food) def collide(ball_a, ball_b): if ball_a == ball_b: return False x1 = ball_a.xcor() x2 = ball_b.xcor() y1 = ball_a.ycor() y2 = ball_b.ycor() D = math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2)) if ((D) <= ball_a.r + ball_b.r): return True
def eat(self, start_time, carbs): self.carbs_on_board.append(Food(start_time, carbs))
"""Gets random locations on the screen that are multiples of 30""" # Chooses random coordinates x = random.randint(0, width - 30) y = random.randint(0, height - 30) # Makes it a multiple of 30 x = x - (x % 30) y = y - (y % 30) return x, y snake = Snake(SCREEN, SNAKE_IMAGE, [180, 180]) snakes = [snake] food = Food(SCREEN, FOOD_IMAGE, get_random_pos()) # Pygame event loop running = True while running: SCREEN.fill([0, 0, 0]) # Clears the screen for event in pygame.event.get(): if event.type == pygame.QUIT: running = False # Checks for any keyboard input elif event.type == pygame.KEYDOWN: if event.key == pygame.K_DOWN and snake.direction != Direction.UP: # Move down snake.direction = Direction.DOWN
def act4(): from food import Food from drink import Drink food1 = Food('Bibimpa', 600, 600) food2 = Food('Shin Ramen Noodles Set Menu', 600, 700) food3 = Food('Cold Noodles ', 800, 500) food4 = Food('Spicy Tofu Soup', 800, 520) food5 = Food('Bulgogi Set Menu', 1000, 890) food6 = Food('Skip', 0, 0) foods = [food1, food2, food3, food4, food5, food6] drink1 = Drink('Mineral Water', 200, 0) drink2 = Drink('Oolong Tea', 200, 0) drink3 = Drink('Skip', 0, 0) drinks = [drink1, drink2, drink3] print() print('***** FOOD MENU *****') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print() print('***** DRINK MENU *****') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') # if choose invalid numbers while True: food_order = input('Please select a number from the food menu: ') if food_order == '0' or food_order == '1' or food_order == '2' or food_order == '3' or food_order == '4' or food_order == '5' or food_order == '6': selected_food = foods[int(food_order)] else: print("Please insert a valid number.") print() continue break while True: drink_order = input('Please select a number from the drink menu: ') if drink_order == '0' or drink_order == '1' or drink_order == '2' or drink_order == '3': selected_drink = drinks[int(drink_order)] else: print("Please insert a valid number.") print() continue break count = int( input( 'How many sets would you like to purchase?(10% off when you purchase 3 sets): ' )) result = selected_food.get_total_price( count) + selected_drink.get_total_price(count) #print total print() print('----------------------------------------------------------') print('Here is your total order:') print() print( str(selected_food.name) + ' ¥' + str(selected_food.price) + ' x ' + str(count)) print( str(selected_drink.name) + ' ¥' + str(selected_drink.price) + ' x ' + str(count)) if count >= 3: print('10% discount') else: print(' ') print('----------------------------------------------------------') print('Your total is ' + str(result) + ' Yen') print() print('Thank you for using W-Delivers! We hope to serve you again soon!') print('----------------------------------------------------------') print() print('Your order is on its way') import time for i in range(100): print('.', end='') time.sleep(1)
def addIng(self, instructIndex, ingNo, desc): thisFood = Food(desc, ingNo, instructIndex) self.m[ingNo] = thisFood self.adjList.append([])
def __init__(self, food_row, food_col): self.player = None self.enemy = None if food_row <= 0 or food_row >= World.TOTAL_ROWS - 1: raise RuntimeError('Invalid food_row') if food_col <= 0 or food_col >= World.TOTAL_COLS - 1: raise RuntimeError('Invalid food_col') self.grid = [] for row in range(World.TOTAL_ROWS): col_list = [None] * World.TOTAL_COLS self.grid.append(col_list) ''' Map: wwwwwwwwwwwwwwwwwwww w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w w000000000000000000w wwwwwwwwwwwwwwwwwwww ''' # initialize top row for col in range(World.TOTAL_COLS): self.grid[0][col] = Wall(0, col) # initialize bot row for col in range(World.TOTAL_COLS): self.grid[World.BOT_ROW][col] = Wall(World.RIGHT_COL, col) # initialize left col for row in range(1, World.BOT_ROW): self.grid[row][0] = Wall(row, 0) # initialize right col for row in range(1, World.BOT_ROW): self.grid[row][World.RIGHT_COL] = Wall(row, World.RIGHT_COL) # put food in specified row, col self.food = Food(food_row, food_col) self.grid[food_row][food_col] = self.food # create SubWorlds self.subworlds = [] ''' Each SubWorld has 5 rows and 5 cols SW0 SW1 SW2 SW3 SW4 SW5 SW6 SW7 SW8 SW9 SW10 SW11 SW12 SW13 SW14 SW15 ''' row_iter = 0 col_iter = 0 while row_iter < World.TOTAL_ROWS: col_iter = 0 while col_iter < World.TOTAL_COLS: row_range = range(row_iter, row_iter + World.NUM_SUBWORLD_ROWS) col_range = range(col_iter, col_iter + World.NUM_SUBWORLD_COLS) new_world = World.SubWorld(row_range, col_range) new_world.reset_bounds(self) self.subworlds.append(new_world) col_iter += (World.NUM_SUBWORLD_COLS) row_iter += (World.NUM_SUBWORLD_ROWS)
random.seed(seed) print("Seed for world =", seed) ## global vars canvasWidth = 530 canvasHeight = 530 ## Tkinter Stuff root = Tk() c = Canvas(root, width=canvasWidth, height=canvasHeight) pixies = [] foods = [] ## call class c.create_rectangle(0, 0, canvasWidth, canvasHeight, fill="#19722f") for i in range(10): x = random.random() * canvasWidth y = random.random() * canvasHeight pixies.append(Pixie(c, x, y)) c.pack() # the simulation while True: if len(foods) < 1000: foods.append(Food(c)) for pixie in pixies: pixie.goTo(c, foods) c.update() root.mainloop()
from constants import * from food import Food from location import Location from render import * from score import Score if __name__ == "__main__": window = pyglet.window.Window(width=WINDOW_WIDTH, height=WINDOW_HEIGHT + HEADER_HEIGHT, resizable=False, caption='Snake') pyglet.gl.glClearColor(0.5, 0.6, 0.7, 1.0) snake = Snake(Location(SNAKE_START_X, SNAKE_START_Y), LEFT, SNAKE_START_SIZE) food = Food(snake.getSnakeList()) score = Score() paused = False @window.event def on_draw(): window.clear() renderHeader( score, 'Press <space> to pause/unpause\nPress <enter> to restart') renderBoard(food, snake) @window.event def on_key_press(symbol, modifiers): global paused, snake, food, score currDirection = snake.getDirection() moveBudget = snake.getMoveBudget()
def new_game(self, neural_network): # start a new game of snake with the specified neural network self.snake = Snake(self, neural_network) self.food = Food(self) self.run()
from turtle import Screen, Turtle from snake import Snake import time from food import Food from scoreboard import Score screen = Screen() screen.setup(width=600, height=600) # customizing screensize screen.bgcolor("black") screen.title("Traditional Snake Game") screen.tracer(0) # 1. Creating Snake body snake = Snake() food = Food() # initialising food as soon as creating snake score = Score() # 3. Moving the snake screen.listen() screen.onkey(snake.up, "Up") screen.onkey(snake.down, "Down") screen.onkey(snake.right, "Right") screen.onkey(snake.left, "Left") # 2.Moving Snake is_game_on = True while is_game_on: screen.update() # updating the screen time.sleep(0.1) # making the turtle speed delay snake.move()
def create_food(self): self.food = Food()
def spawn_food(self): unallowed_squares = map(lambda segment: (segment.row, segment.col), self.snake.segments) self.food = Food(unallowed_squares=unallowed_squares)
def create_food(ai_settings, screen, foods, food_number): food = Food(ai_settings, screen) food_width = food.rect.width food.x = food_width + 3 * food_width * food_number food.rect.x = food.x foods.add(food)
from food import Food from drink import Drink food1 = Food('Sandwich', 5, 330) food2 = Food('Chocolate Cake', 4, 450) food3 = Food('Cream Puff', 2, 180) foods = [food1, food2, food3] drink1 = Drink('Coffee', 3, 180) drink2 = Drink('Orange Juice', 2, 350) drink3 = Drink('Espresso', 3, 30) drinks = [drink1, drink2, drink3] print('Food') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('Drinks') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') food_order = int(input('Enter food item number: ')) selected_food = foods[food_order]
def create_fleet(ai_settings, screen, foods): food = Food(ai_settings, screen) number_foods_x = get_number_foods_x(ai_settings, food.rect.width) for food_number in range(number_foods_x): create_food(ai_settings, screen, foods, food_number)
import mlab from food import Food mlab.connect() #1 Create #1.1 Create a food data f = Food(title="Bánh gạo", link="<<Link sai>>") #1.2 Save it # f.save() #2 Read #2.1 Get cursor f_objects = Food.objects() #Lazy loading #Same a list #2.1 Process cursor # f_first = f_objects[0] #Actual data transfering # print(f_first) # print(f_first.link) # print(len(f_objects)) # print(f_objects.count()) # for f in f_objects: # print(f.title) # print(f.link) # print("------------") # f = f_objects[3] # f.update(set__title="Bánh rất rất dầy", set__link="http://banhdayngon.vn/wp-content/uploads/2015/04/banh-giay-chay.jpg") # f.reload() # print(f.title)
from food import Food from drink import Drink food1 = Food('Roti Lapis', 5) # Tetapkan variable calorie_count milik food1 ke 330 food1.calorie_count = 330 # Panggil method calorie_info dari food1 food1.calorie_info()
from food import Food from drink import Drink food1 = Food('Roti Lapis', 5, 330) food2 = Food('Kue Coklat', 4, 450) food3 = Food('Kue Sus', 2, 180) foods = [food1, food2, food3] drink1 = Drink('Kopi', 3, 180) drink2 = Drink('Jus Jeruk', 2, 350) drink3 = Drink('Espresso', 3, 30) drinks = [drink1, drink2, drink3] print('Makanan') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('Minuman') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') food_order = int(input('Masukkan nomor makanan: ')) selected_food = foods[food_order]
def game_loop(screen, clock, nb_of_players, living_players): # Controlling number of snakes: if INITIAL_NB_SNAKES < nb_of_players: nb_of_snakes = nb_of_players else: nb_of_snakes = INITIAL_NB_SNAKES # Initialising snakes: snakes = [] for i in range(nb_of_snakes): if i == 0: if nb_of_players == 0: snakes.append(Snake(RIGHT_QUARTER_OF_THE_GRID, LEFT)) elif nb_of_players == 1: snakes.append(Snake(MIDDLE_OF_THE_GRID, RANDOM_VEL, BLACK)) elif nb_of_players == 2: snakes.append(Snake(RIGHT_QUARTER_OF_THE_GRID, LEFT, BLACK)) elif nb_of_players > 2: snakes.append(Snake(RANDOM_POSITION, RANDOM_VEL, BLACK)) elif i == 1: if nb_of_players == 0: snakes.append(Snake(LEFT_QUARTER_OF_THE_GRID, RIGHT)) elif nb_of_players == 1: snakes.append(Snake(RANDOM_POSITION, RANDOM_VEL)) elif nb_of_players == 2: snakes.append(Snake(LEFT_QUARTER_OF_THE_GRID, RIGHT, DARK_BLUE)) elif nb_of_players > 2: snakes.append(Snake(RANDOM_POSITION, RANDOM_VEL, DARK_BLUE)) else: snakes.append(Snake(RANDOM_POSITION, RANDOM_VEL)) # Assigning snakes to players: players = [] for i in range(nb_of_players): players.append(snakes[i]) # Initialising food: food = [] for i in range(random.randrange(1, 4)): food.append(Food(snakes, food, CYAN)) # Initialising other variables: last_frames = NB_LAST_FRAMES slow_mo = 1 game_loop_cycles = 0 human_data_processed = False dead_snakes = [] heads_surface = pg.Surface(GRID_SIZE, depth=8) food_surface = pg.Surface(GRID_SIZE, depth=8) borders_surface = pg.Surface(GRID_SIZE, depth=8) borders_surface.blit(screen, (0, 0)) borders_surface.fill(WHITE) # Displaying AI training popup: if AI_TRAINING_MODE: screen.fill(LIGHT_GREY) message = [ "TRAINING THE AI", "" "Check console for details.", "Save and exit: Escape" ] display_popup(screen, message) pg.display.update() # Loading human data: if nb_of_players > 0: human_data_exists = False # if os.path.isfile(TRAINING_DATA_PATH + "human_states.npy"): # human_data_exists = True # human_states = np.load(TRAINING_DATA_PATH + "human_states.npy") # human_actions = np.load(TRAINING_DATA_PATH + "human_actions.npy") # human_rewards = np.load(TRAINING_DATA_PATH + "human_rewards.npy") # print("Human data loaded.") # ---------------------------------- ACTUAL GAME LOOP ---------------------------------- while True: # User input handling: if not AI_TRAINING_MODE: # Controls handling: for player in players: player.pressed_arrow_key = False for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: # Pause menu: request = pause_loop(screen, clock) if request == RQ_RESTART or request == RQ_MAIN_MENU: return request elif event.key == pg.K_BACKSPACE and DEBUG_MODE: return RQ_RESTART elif event.key == pg.K_KP_ENTER and DEBUG_MODE: slow_mo = 5 if nb_of_players > 0: if event.key == pg.K_LEFT: players[0].new_potential_vel = LEFT players[0].pressed_arrow_key = True elif event.key == pg.K_RIGHT: players[0].new_potential_vel = RIGHT players[0].pressed_arrow_key = True elif event.key == pg.K_UP: players[0].new_potential_vel = UP players[0].pressed_arrow_key = True elif event.key == pg.K_DOWN: players[0].new_potential_vel = DOWN players[0].pressed_arrow_key = True elif event.key == pg.K_KP_PLUS and DEBUG_MODE: players[0].length += 1 elif event.key == pg.K_KP_MINUS and DEBUG_MODE: players[0].length -= 1 if nb_of_players > 1: if event.key == pg.K_a: players[1].new_potential_vel = LEFT players[1].pressed_arrow_key = True elif event.key == pg.K_d: players[1].new_potential_vel = RIGHT players[1].pressed_arrow_key = True elif event.key == pg.K_w: players[1].new_potential_vel = UP players[1].pressed_arrow_key = True elif event.key == pg.K_s: players[1].new_potential_vel = DOWN players[1].pressed_arrow_key = True elif event.type == pg.KEYUP: if event.key == pg.K_KP_ENTER: slow_mo = 1 # Applying and logging controls: for i in range(len(players)): if players[i].pressed_arrow_key \ and players[i].not_going_into_wall(players[i].new_potential_vel) \ and players[i].not_going_into_snake_head(snakes) \ and not np.array_equal(players[i].vel, players[i].new_potential_vel): if not np.array_equal(-players[i].vel, players[i].new_potential_vel): if players[i].vel.tolist() == LEFT.tolist(): if players[i].new_potential_vel.tolist( ) == UP.tolist(): players[i].actions.append(TURN_RIGHT) else: players[i].actions.append(TURN_LEFT) elif players[i].vel.tolist() == UP.tolist(): if players[i].new_potential_vel.tolist( ) == RIGHT.tolist(): players[i].actions.append(TURN_RIGHT) else: players[i].actions.append(TURN_LEFT) elif players[i].vel.tolist() == RIGHT.tolist(): if players[i].new_potential_vel.tolist( ) == DOWN.tolist(): players[i].actions.append(TURN_RIGHT) else: players[i].actions.append(TURN_LEFT) else: if players[i].new_potential_vel.tolist( ) == LEFT.tolist(): players[i].actions.append(TURN_RIGHT) else: players[i].actions.append(TURN_LEFT) players[i].vel = players[i].new_potential_vel else: players[i].actions.append(REVERSE) players[i].vel = players[i].get_tail_direction() players[i].positions.reverse() else: players[i].actions.append(DO_NOTHING) else: # if AI_TRAINING_MODE: for event in pg.event.get(): if event.type == pg.QUIT: pg.quit() sys.exit() elif event.type == pg.KEYDOWN: if event.key == pg.K_ESCAPE: # Save the model pg.quit() sys.exit() # AI input handling: for snake in snakes: if snake not in players: # Ask model for prediction... snake.pseudo_prediction = DO_NOTHING if random.random() < 2 / TARGET_FPS: snake.pseudo_prediction = pseudo_predict() snake.actions.append(snake.pseudo_prediction) if snake.vel.tolist() == LEFT.tolist(): if snake.pseudo_prediction.tolist() == TURN_RIGHT.tolist(): snake.new_potential_vel = UP elif snake.pseudo_prediction.tolist() == TURN_LEFT.tolist( ): snake.new_potential_vel = DOWN elif snake.pseudo_prediction.tolist() == REVERSE.tolist(): snake.new_potential_vel = RIGHT elif snake.vel.tolist() == RIGHT.tolist(): if snake.pseudo_prediction.tolist() == TURN_RIGHT.tolist(): snake.new_potential_vel = DOWN elif snake.pseudo_prediction.tolist() == TURN_LEFT.tolist( ): snake.new_potential_vel = UP elif snake.pseudo_prediction.tolist() == REVERSE.tolist(): snake.new_potential_vel = LEFT elif snake.vel.tolist() == UP.tolist(): if snake.pseudo_prediction.tolist() == TURN_RIGHT.tolist(): snake.new_potential_vel = RIGHT elif snake.pseudo_prediction.tolist() == TURN_LEFT.tolist( ): snake.new_potential_vel = LEFT elif snake.pseudo_prediction.tolist() == REVERSE.tolist(): snake.new_potential_vel = DOWN else: if snake.pseudo_prediction.tolist() == TURN_RIGHT.tolist(): snake.new_potential_vel = LEFT elif snake.pseudo_prediction.tolist() == TURN_LEFT.tolist( ): snake.new_potential_vel = RIGHT elif snake.pseudo_prediction.tolist() == REVERSE.tolist(): snake.new_potential_vel = UP if snake.not_going_into_wall( snake.new_potential_vel ) and snake.not_going_into_snake_head(snakes): if snake.pseudo_prediction.tolist() == REVERSE.tolist(): snake.vel = snake.get_tail_direction() snake.positions.reverse() elif not snake.pseudo_prediction.tolist( ) == DO_NOTHING.tolist(): snake.vel = snake.new_potential_vel # Making snakes birth and die in AI training mode: if AI_TRAINING_MODE: while len(snakes) < MIN_NB_SNAKES: snakes.append(Snake(RANDOM_POSITION, RANDOM_VEL)) while len(snakes) > MAX_NB_SNAKES: random.choice(snakes).is_dead = True # Snakes logic: for snake in snakes: snake.rewards.append(RW_TIME_PASSED) snake.move(snakes) for snake in snakes: snake.check_got_bitten(snakes) snake.check_has_eaten(food) # Dealing with dead snakes: for snake in snakes: if snake.is_dead: if not AI_TRAINING_MODE: if snake in players: living_players[players.index(snake)] = False else: dead_snakes.append(snake) snakes.remove(snake) # Screen reset: screen.fill(LIGHT_GREY) # Snakes display and state processing: heads_surface.fill(BLACK) for snake in snakes: snake.body_surface.fill(BLACK) snake.draw(screen, heads_surface) # Food logic: if random.random() < FOOD_CHANCE_PER_TICK * math.pow( (MAX_FOOD - len(food)) / MAX_FOOD, 4): food.append(Food(snakes, food, CYAN)) # Food display: food_surface.fill(BLACK) for item in food: item.draw(screen, food_surface) # Perspective transformations per snake if len(snakes) > 0: bodies_surface = snakes[0].body_surface.copy() for snake in snakes[1:]: bodies_surface.blit(snake.body_surface, (0, 0), special_flags=pg.BLEND_ADD) for snake in snakes: for i in range(LAYERS_PER_STATE): snake.pers_surfaces[i].fill(BLACK) snake.pers_surfaces[0] = screen_to_pers(snake.body_surface, snake.positions[-1], snake.vel) snake.pers_surfaces[1] = screen_to_pers(bodies_surface, snake.positions[-1], snake.vel) snake.pers_surfaces[2] = screen_to_pers(heads_surface, snake.positions[-1], snake.vel) snake.pers_surfaces[3] = screen_to_pers(food_surface, snake.positions[-1], snake.vel) snake.pers_surfaces[4] = screen_to_pers(borders_surface, snake.positions[-1], snake.vel) snake.pers_surfaces[1].blit(snake.pers_surfaces[0], (0, 0), special_flags=pg.BLEND_SUB) # Logging state: for i in range(LAYERS_PER_STATE): snake.states[i].append( (pg.surfarray.array2d(snake.pers_surfaces[i]) / 127).astype(bool)) if DEBUG_MODE: stand_offset = 40 pers_offset = 140 top = 5 left = 5 right = 1145 # FPS display: current_fps = round(clock.get_fps(), 1) screen.blit( FPS_FONT.render( str(current_fps) + " / " + str(TARGET_FPS), True, BLACK), (left, top)) # Display neural net data: i = 0.4 if DISPLAY_NN_DATA and nb_of_players > 0: for snake in snakes: screen.blit(snake.body_surface, (left, top + stand_offset * i)) i += 1 screen.blit(heads_surface, (left, top + stand_offset * i)) i += 1 screen.blit(food_surface, (left, top + stand_offset * i)) i += 1 screen.blit(bodies_surface, (left, top + stand_offset * i)) i += 1 if living_players[0]: rw_min = -300 rw_max = 300 if game_loop_cycles == 0: rw = 0 else: rw = players[0].rewards[ game_loop_cycles] + rw * DISCOUNT_FACTOR rw_color = max( min( math.floor( (rw - rw_min) / (rw_max - rw_min) * 256), 255), 0) screen.fill((rw_color, rw_color, rw_color), pg.Rect((left, top + stand_offset * i), GRID_SIZE)) i = 0 for pers_surface in players[0].pers_surfaces: screen.blit(pers_surface, (right, top + pers_offset * i)) i += 1 # Display update if not AI_TRAINING_MODE: pg.display.update() # Concatenating dead snakes data and training the AI model: if AI_TRAINING_MODE and len(dead_snakes) >= TRAIN_EVERY_NB_DEAD_SNAKES: ai_data_created = False for dead_snake in dead_snakes: ai_bp_rewards = back_propagate_rewards(dead_snake.rewards) if ai_data_created: ai_states = np.concatenate( (ai_states, np.array(dead_snake.states, dtype=bool)[:, :-1]), 1) ai_actions = np.concatenate( (ai_actions, np.array(dead_snake.actions, dtype=bool)[1:]), 0) ai_rewards = np.concatenate( (ai_rewards, np.array(ai_bp_rewards, dtype=float)[1:]), 0) else: ai_states = np.array(dead_snake.states, dtype=bool)[:, 1:] ai_actions = np.array(dead_snake.actions, dtype=bool)[1:] ai_rewards = np.array(ai_bp_rewards, dtype=float)[1:] ai_data_created = True # Train AI model print("AI model trained.") # Saving human data and training the human model: if nb_of_players > 0: if sum(living_players) < nb_of_players or len(snakes) == 1: # Last frames timer: last_frames -= 1 if not human_data_processed: for player in players: human_bp_rewards = back_propagate_rewards( player.rewards) if human_data_exists: human_states = np.concatenate( (human_states, np.array(player.states, dtype=bool)[:, :-1]), 1) human_actions = np.concatenate( (human_actions, np.array(player.actions, dtype=bool)[1:]), 0) human_rewards = np.concatenate( (human_rewards, np.array(human_bp_rewards, dtype=float)[1:]), 0) else: human_states = np.array(player.states, dtype=bool)[:, 1:] human_actions = np.array(player.actions, dtype=bool)[1:] human_rewards = np.array(human_bp_rewards, dtype=float)[1:] human_data_exists = True print("Human data saved.") np.save(TRAINING_DATA_PATH + "human_states.npy", human_states) np.save(TRAINING_DATA_PATH + "human_actions.npy", human_actions) np.save(TRAINING_DATA_PATH + "human_rewards.npy", human_rewards) # Train human model print("Human model trained." + ".. I wish...") human_data_processed = True # End of game: if (nb_of_players > 0 and not DEBUG_MODE) or len(snakes) == 0: if sum(living_players) == 0: if last_frames == 0: winner = "AI" request = end_loop(screen, clock, winner) return request elif sum(living_players) == 1 and (nb_of_players > 1 or len(snakes) == 1): if last_frames == 0: winner = "PLAYER " + str(living_players.index(True) + 1) request = end_loop(screen, clock, winner) return request # Time flow: if not AI_TRAINING_MODE: clock.tick(TARGET_FPS / slow_mo) for snake in snakes: snake.time += 1 game_loop_cycles += 1
from food import Food from drink import Drink food1 = Food('サンドイッチ', 500, 330) food2 = Food('チョコケーキ', 400, 450) food3 = Food('シュークリーム', 200, 180) foods = [food1, food2, food3] drink1 = Drink('コーヒー', 300, 180) drink2 = Drink('オレンジジュース', 200, 350) drink3 = Drink('エスプレッソ', 300, 30) drinks = [drink1, drink2, drink3] print('食べ物メニュー') index = 0 for food in foods: print(str(index) + '. ' + food.info()) index += 1 print('飲み物メニュー') index = 0 for drink in drinks: print(str(index) + '. ' + drink.info()) index += 1 print('--------------------') food_order = int(input('食べ物の番号を選択してください: ')) selected_food = foods[food_order]
import cgi import cgitb cgitb.enable() # from menu_item import MenuItem from food import Food from drink import Drink print("Content-Type: text/html") print() form = cgi.FieldStorage() food1 = Food('サンドイッチ', 400, 300) food2 = Food('チョコケーキ', 500, 600) food3 = Food('シュークリーム', 300, 500) foods = [food1, food2, food3] drink1 = Drink('コーヒー', 200, 200) drink2 = Drink('オレンジジュース', 150, 300) drink3 = Drink('エスプレッソ', 250, 200) drinks = [drink1, drink2, drink3] order = int(form["number"].value) count = int(form["count"].value) set_count = int(form["set"].value) # if order < 0 or order > len(foods) - 1: # print('正しい値を入力してください') # elif count < 0 or count > len(drinks) - 1: # print('正しい値を入力してください') # else:
# Import the Food class and Drink class from food import Food from drink import Drink # Create an instance of the Food class and assign it to the food1 variable food1 = Food('Sandwich', 5) # Call the info method from food1 and output the return value print(food1.info()) # Create an instance of the Drink class and assign it to the drink1 variable drink1 = Drink('Coffee', 3) # Call the info method from drink1 and output the return value print(drink1.info())
screen = Screen() screen.setup(width=600, height=600) screen.bgcolor("black") screen.title("Snake game") screen.tracer(0) #SNAKES STARTING POSITIONS CONFIGURATION STARTING_POSITIONS_1 = [(80, 0), (60, 0), (40, 0)] STARTING_POSITIONS_2 = [(-60, 0), (-80, 0), (-100, 0)] #GAME OBJECTS snake_1 = Snake("white", STARTING_POSITIONS_1) snake_2 = Snake("red", STARTING_POSITIONS_2) snakes = [snake_1, snake_2] food_1 = Food() food_2 = Food() foods = [food_1, food_2] #SCOREBOARD POSITIONS SCORE_1_POSITION = (200, 280) SCORE_2_POSITION = (-200, 280) score_1 = Scoreboard("white", SCORE_1_POSITION) score_2 = Scoreboard("red", SCORE_2_POSITION) scores = {snake_1: score_1, snake_2: score_2} #CONTROL CONFIGURATION screen.listen() screen.onkey(snake_1.up, "Up")