Programmiersprache – die neusten Beiträge

onclick-event auf webseite mittels python triggern?

Hallo,

ich habe auf einer Webseite eine Tabelle mit verschiedenen Einträgen.
Wenn ich einen Eintrag anklicke, wird eine Funktion aufgerufen

<td onclick="handleRestart(1,3)">xxxxxxxx</td>

Diese Funktion (handleRestart) kann sehe ich auch im Quelltext.

function handleRestart(neu, idx) {
	if (!idx) idx = 1;
	if (neu > 0) {
		jQuery.getJSON( url + "&callback=?", {
			quizSelection: idx
		}, function( retVal ) {
		  quiz = retVal;
		  if (quiz.error && quiz.error == "forbidden") {
			  handleServerError();
		  }
		  quiz.fragenPointer = 0;
		  anzFalsch = 0;
			jQuery("#frageContainer").html(renderQuestion(quiz.fragen[quiz.fragenIds[quiz.fragenPointer]]));
		  renderStats();
	  });
	} else {
	  quiz.fragenPointer = 0;
		anzFalsch = 0;
		for (i= 0; i < quiz.fragenIds.length; i++) {
			quiz.fragen[quiz.fragenIds[i]].answer = -1;
		}
		jQuery("#frageContainer").html(renderQuestion(quiz.fragen[quiz.fragenIds[quiz.fragenPointer]]));
		renderStats();
	}
}

Gibt es eine Möglichkeit mittels Python die Seite aufzurufen und dann die Funktion aus dem Python-script zu triggern?

Mittels "requests" kann ich ja http-requests schicken. Aber gibt es auch eine möglichkeit, wenn ich die Seite geladen habe

z.B.

 r = requests.get('webseite')

die Funktion (handleRestart) zu triggern?

Es gäbe noch weiter Funktionen, die ich dann aufrufen möchte, aber das denke ich ist dann ähnlich.

Wenn ich in der Tabelle auf einen Eintrag klicke, bekomme ich ein Quiz.
Im Quelltext wird durch ein Funktionsaufruf eine .json geholt. Diese würde ich mir gerne ansehen und evtl. Daten rausholen. Ziel ist es alle Fragen des Quiz zu bekommen, ohne händisch durchzugehen und diese aufzuschreiben.

HTML, Webseite, JavaScript, Code, Programmiersprache, Python, Python 3

Stimmt diese Planetenlaufbahn-Approximation?

Heyy ich versuche seit einiger Zeit mit Python eine Animation für die Laufbahn von der Erde zu erstellen, aber ich wundere mich, ob mein Ansatz stimmt. 🤔

Ich will ein Python Programm erstellen, wo ich den Exponenten des Radius im Gravitationsgesetz ändern und somit neue Umlaufbahnen zeichnen kann. Dabei stütze ich mich auf die Formel: F = G * (m1 * m2)/r^x. Ich bin mir nicht sicher, ob mein Programm korrekte Laufbahnen zeichnet, da ich nicht sonderlich gut in Physik bin. Der Grundgedanke kann ich nachvollziehen: Bei abnehmender Kraft, wird die Umlaufbahn grösser. Aber ist es normal, dass die Umlaufbahn der Erde bei einer kleinen Exponenten-Änderung von 2 auf 2.02 so viel grösser wird? Falls ja, warum ist das so?

Danke im Voraus für eure Hilfe! 😊

LG Leonie

Ein Quadrat entspricht hier einer astronomischen Einheit.

Hier ist mein Programm:

Ich verwende für meine Animation pygame.

import pygame
import sys
import math

Das sind die Konstanten, die ich verwende und die Startwerte:

G = 6.67430e-11
M_SUN = 1.989e30 
M_EARTH = 5.972e24
AU = 1.496e11
TIME_STEP = 43200
x = AU
y = 0
vx = 0
vy = 29780
exp_r = float(input"Exponent:"))

Die Erstellung des Fensters:

pygame.init()
WIDTH, HEIGHT = 800, 800
SCALE = WIDTH / (20 * AU)  # Maßstab für die Darstellung
screen = pygame.display.set_mode((WIDTH, HEIGHT))
clock = pygame.time.Clock()

Mit RK4 approximiere ich die Laufbahn der Erde. Hier sind die Funktionen:

def runge_kutta4(t, state, dt):
    k1 = deriv(t, state)
    k2 = deriv(t + 0.5 * dt, [state[i] + 0.5 * dt * k1[i] for i in range(4)])
    k3 = deriv(t + 0.5 * dt, [state[i] + 0.5 * dt * k2[i] for i in range(4)])
    k4 = deriv(t + dt, [state[i] + dt * k3[i] for i in range(4)])
    return [state[i] + (dt / 6) * (k1[i] + 2 * k2[i] + 2 * k3[i] + k4[i]) for i in range(4)]

def draw_grid():
    grid_size = AU * SCALE
    half_width = WIDTH // 2
    half_height = HEIGHT // 2
 
    for i in range(-19, 20):
        x_pos = int(half_width + i * grid_size)
        pygame.draw.line(screen, (50, 50, 50), (x_pos, 0), (x_pos, HEIGHT))
 
    for i in range(-19, 20):
        y_pos = int(half_height + i * grid_size)
        pygame.draw.line(screen, (50, 50, 50), (0, y_pos), (WIDTH, y_pos))

Hauptschleife:

running = True
t = 0
earth_path = []


while running:
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            running = False

    state = [x, y, vx, vy]
    x, y, vx, vy = runge_kutta4(t, state, TIME_STEP)
    t += TIME_STEP

    draw_x = int(WIDTH / 2 + x * SCALE)
    draw_y = int(HEIGHT / 2 + y * SCALE)
    earth_path.append((draw_x, draw_y))

    screen.fill((0, 0, 0))
    draw_grid()
    pygame.draw.circle(screen, (255, 255, 0), (WIDTH // 2, HEIGHT // 2), 20)
    pygame.draw.circle(screen, (0, 0, 255), (draw_x, draw_y), 5)

    for px, py in earth_path:
        pygame.draw.circle(screen, (0, 255, 0), (px, py), 1)

    pygame.display.flip()
    clock.tick(60)

pygame.quit()
sys.exit()
Bild zum Beitrag
Erde, Schule, Mathematik, programmieren, Astronomie, Code, Gravitation, Informatik, Physik, Programmiersprache, Python, Universität, Approximation, Gravitationskraft, Newtonsche Gesetze, Pygame, Gravitationsgesetz

Wieso geht der Code nicht?

Hallo

Ich möchte mit js ein Programm bauen, welches meinen Körper erkennt und dort drauf dann ein T-Shirt-Modell legt. Also so eine virtuelle Garderobe quasi. Wieso geht der Code nicht?

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Virtual Try-On Final</title>
<style>
 body { margin: 0; overflow: hidden; }
 #webcam {
  position: absolute;
  transform: scaleX(-1);
  opacity: 0.5;
  z-index: 1;
 }
 #output {
  position: absolute;
  z-index: 2;
 }
</style>
</head>
<body>
<video id="webcam" autoplay playsinline></video>
<canvas id="output"></canvas>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow/tfjs"></script>
<script src="https://cdn.jsdelivr.net/npm/@tensorflow-models/body-pix"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r128/three.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/three@0.128.0/examples/js/loaders/GLTFLoader.js"></script>
<script>
const video = document.getElementById('webcam');
const output = document.getElementById('output');
let net, scene, camera, renderer, shirt;
let bodyPosition = { x: 0, y: 0, width: 0, height: 0 };
async function setupWebcam() {
 try {
  const stream = await navigator.mediaDevices.getUserMedia({
   video: {
    width: { ideal: 640 },
    height: { ideal: 480 },
    facingMode: 'user'
   }
  });
  video.srcObject = stream;
  
  return new Promise(resolve => {
   video.onloadedmetadata = () => {
    output.width = video.videoWidth;
    output.height = video.videoHeight;
    resolve();
   };
  });
 } catch (error) {
  console.error('Webcam error:', error);
  alert('Bitte Webcam-Zugriff erlauben!');
 }
}
function initThreeJS() {
 scene = new THREE.Scene();
 camera = new THREE.PerspectiveCamera(
  60,
  output.width / output.height,
  0.1,
  1000
 );
 camera.position.set(0, 0, 2);
 renderer = new THREE.WebGLRenderer({
  canvas: output,
  alpha: true,
  antialias: true
 });
 renderer.setClearColor(0x000000, 0);
 // Beleuchtung
 const ambientLight = new THREE.AmbientLight(0xffffff, 1.0);
 scene.add(ambientLight);
 const directionalLight = new THREE.DirectionalLight(0xffffff, 0.8);
 directionalLight.position.set(0, 2, 5);
 scene.add(directionalLight);
 loadShirtModel();
}
async function loadShirtModel() {
 const loader = new THREE.GLTFLoader();
 try {
  const gltf = await loader.loadAsync('tshirt_model.glb');
  shirt = gltf.scene;
  
  // Material-Anpassung
  shirt.traverse(child => {
   if (child.isMesh) {
    child.material = new THREE.MeshPhongMaterial({
     color: 0xffffff,
     transparent: true,
     opacity: 0.9,
     depthWrite: false
    });
   }
  });
  shirt.scale.set(0.3, 0.3, 0.3);
  scene.add(shirt);
  console.log('T-Shirt Modell geladen');
 } catch (error) {
  console.error('Modellfehler:', error);
  addFallbackCube();
 }
}
function addFallbackCube() {
 const geometry = new THREE.BoxGeometry(0.5, 0.5, 0.5);
 const material = new THREE.MeshBasicMaterial({ color: 0xff0000 });
 shirt = new THREE.Mesh(geometry, material);
 scene.add(shirt);
}
function calculateBodyPosition(segmentation) {
 const data = segmentation.data;
 let minX = Infinity, maxX = -Infinity;
 let minY = Infinity, maxY = -Infinity;
 for (let y = 0; y < segmentation.height; y++) {
  for (let x = 0; x < segmentation.width; x++) {
   if (data[y * segmentation.width + x] === 1) {
    minX = Math.min(minX, x);
    maxX = Math.max(maxX, x);
    minY = Math.min(minY, y);
    maxY = Math.max(maxY, y);
   }
  }
 }
 if (minX !== Infinity) {
  bodyPosition = {
   x: (minX + maxX) / 2,
   y: (minY + maxY) / 2,
   width: maxX - minX,
   height: maxY - minY
  };
 }
}
function updateShirtPosition() {
 if (!shirt) return;
 // Koordinatenumrechnung
 const x = (bodyPosition.x / output.width - 0.5) * 2;
 const y = -(bodyPosition.y / output.height - 0.5) * 2;
 
 shirt.position.set(x, y, 0);
 
 // Skalierung basierend auf Körpergröße
 const scaleFactor = bodyPosition.height / output.height * 2;
 shirt.scale.set(scaleFactor, scaleFactor, scaleFactor);
}
async function detectBody() {
 try {
  // Ganzkörper-Segmentierung
  const segmentation = await net.segmentPerson(video, {
   segmentationThreshold: 0.7,
   internalResolution: 'high',
   maxDetections: 1
  });
  calculateBodyPosition(segmentation);
  updateShirtPosition();
  // Rendering
  const ctx = output.getContext('2d');
  ctx.clearRect(0, 0, output.width, output.height);
  renderer.render(scene, camera);
  requestAnimationFrame(detectBody);
 } catch (error) {
  console.error('Detektionsfehler:', error);
 }
}
(async () => {
 await setupWebcam();
 net = await bodyPix.load({
  architecture: 'ResNet50',
  outputStride: 32,
  quantBytes: 2
 });
 initThreeJS();
 detectBody();
})();
</script>
</body>
</html>

Freundliche Grüsse

HTML, Webseite, CSS, JavaScript, HTML5, Code, Datenbank, Programmiersprache, Webentwicklung, Frontend

Bei CSS "display: flex;" wird alles schief warum?

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Login</title>
  <!-- stylesheet -->
   <link rel="stylesheet" href="styles.css">
   <!-- Boostrap Icon -->
   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.3.0/font/bootstrap-icons.css" />
</head>
<body>
  <div class="container">
    <!-- Create Account -->
     <div class="sign-up">
      <div class="sign-up-container">
        <h3>Create account</h3>
        <div class="cs-form-group">
          <label for="Email">Email</label>
          <input type="email" class="cs-form-control">
        </div>
      </div class="cs-form-group">
        <label for="password">Password</label>
        <input type="password" name="" id="" class="cs-form-control">
      </div>
      <div class="cs-form-control">
        <button class="cs-form-submit">Create Account</button>
      </div>
      <span class="divider"></span>
      <div class="cs-form-group">
        <button class="social-login">
          <span class="social-icon">
            <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/c/c1/Google_%22G%22_logo.svg/2048px-Google_%22G%22_logo.svg.png" alt="" style="width: 20px;">
            
          </span>
          Create using Google Account
        </button>
      </div>
      <p>Already have an account?<a href="#"> Login</a></p>
     </div>
  </div>
     <!-- Login -->
     <div class="login">
     </div>
     <!-- Forgot Password -->
      <div class="forget-password">
      </div>
  </div>
  
</body>
</html>

CSS:

@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800;900&display=swap');

*{
  box-sizing: border-box;
  padding: 0;
  margin: 0;
  box-sizing: border-box;
}

.container{
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
  background: #F5F5F5;
}

.sign-up{
  position: relative;
  padding: 10px;
  width: 420px;
}

.sign-up-container{
  position: relative;
  background: #F5F5F5;
  padding: 24px 20px;
  border: 1px solid #D4D5D8;
  box-shadow: 0px 1px 2px rgba(152, 152, 152, 0.2);
}

.sign-up-container h3{
  font-size: 28px;
  font-weight: 800;
  margin-bottom: 8px;
}

.cs-form-group{
  display: block;
}
HTML, Webseite, CSS, Code, Programmiersprache, Webdesign

Warum wird JButton in Java nicht angezeigt?

Ich programmiere Gerade ein Java Projekt und bin auf das Problem gestoßen das der JButton im secountPanel nicht angezeigt wird.

Das ist mein Code:

package com.testProjekte;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class PrimzahlenRechnerMitGUI {
    static JButton backButton = new JButton("Zurück");

    public static void main(String[] args) {
        loadGUI();
    }

    public static void loadGUI() {
        JFrame mainFrame = new JFrame("Primzahl Rechner");
        mainFrame.setResizable(false);
        mainFrame.setSize(450,300);
        mainFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        mainFrame.setLocationRelativeTo(null);

        JPanel mainPanel = new JPanel(new GridBagLayout());
        JPanel secountPanel = new JPanel(new GridBagLayout());
        JPanel thirtPanel = new JPanel(new GridBagLayout());

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);

        CardLayout cardLayout = new CardLayout();
        JPanel cardPanel = new JPanel(cardLayout);

        //main Panel Start
        JButton chooseRange = new JButton("Bereich Eingeben");
        chooseRange.setPreferredSize(new Dimension(chooseRange.getPreferredSize().width + 20, 30));
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        mainPanel.add(chooseRange, gbc);


        JButton chooseNumber = new JButton("Nummer eingeben");
        chooseNumber.setPreferredSize(new Dimension(chooseNumber.getPreferredSize().width + 20, 30));
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.EAST;
        mainPanel.add(chooseNumber, gbc);

        //main Panel end


        //secount Panel Start
        backButton.setPreferredSize(new Dimension(100, 30));
        backButton.setBackground(Color.RED);
        JLabel reangeText = new JLabel("Gib einen Bereich ein");

        JTextField startRange = new JTextField();
        startRange.setPreferredSize(new Dimension(100,30));

        JTextField endRange = new JTextField();
        endRange.setPreferredSize(new Dimension(100,30));

        JButton checkRangeButton = new JButton("Prüfen");

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.NORTHWEST;
        gbc.fill = GridBagConstraints.NONE;
        secountPanel.add(backButton, gbc);

        gbc.gridx = 0;
        gbc.gridy = 1;
        secountPanel.add(reangeText, gbc);

        gbc.gridx = 0;
        gbc.gridy = 3;
        secountPanel.add(startRange, gbc);

        gbc.gridx = 0;
        gbc.gridy = 4;
        secountPanel.add(endRange, gbc);

        gbc.gridx = 0;
        gbc.gridy = 5;
        secountPanel.add(checkRangeButton, gbc);
        //secount Panel end


        //thirt Panel start
        backButton.setPreferredSize(new Dimension(100, 30));
        backButton.setBackground(Color.RED);
        JLabel numberText = new JLabel("Gib eine Zahl ein");

        JButton checkNumberButton = new JButton("Prüfen");

        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.anchor = GridBagConstraints.WEST;
        thirtPanel.add(backButton, gbc);


        thirtPanel.add(numberText);
        thirtPanel.add(checkNumberButton);
        //thirt Panel end

        cardPanel.add(mainPanel, "MainPanel");
        cardPanel.add(secountPanel, "SecountPanel");
        cardPanel.add(thirtPanel, "ThirtPanel");

        chooseRange.addActionListener(e -> cardLayout.show(cardPanel, "SecountPanel"));
        chooseNumber.addActionListener(e -> cardLayout.show(cardPanel, "ThirtPanel"));
        backButton.addActionListener(e -> cardLayout.show(cardPanel, "MainPanel"));

        mainFrame.add(cardPanel);
        mainFrame.setVisible(true);
    }
}
App, Java, Code, Eclipse, Programmiersprache, Swing, Java Swing

Habe einen komischen Fehler in VHDL, welcher so nicht auftreten sollte?

Bei mir komm tin VHDL der Folgende Fehler, bei folgendem Code, und ich kann mir nicht erklären warum

line 36:5:warning: instance "low_counter" of component "genericcounter" is not bound [-Wbinding]
    low_counter: GenericCounter123
    ^
line 14:14:warning: (in default configuration of sekundenzaehler(rtl))
line 49:5:warning: instance "high_counter" of component "genericcounter123" is not bound [-Wbinding]
    high_counter: GenericCounter123
    ^
line 14:14:warning: (in default configuration of sekundenzaehler(rtl))

-----
ERROR: ELABORATION
Folgender Code wurde analysiert:
    1:  library ieee;
    2:  use ieee.std_logic_1164.all;
    3:  use ieee.numeric_std.all;
    4:  
    5:  entity SekundenZaehler is
    6:      port(
    7:          clk : in std_logic;
    8:          reset : in std_logic;
    9:          count_1 : out std_logic_vector(3 downto 0);
   10:          count_10 : out std_logic_vector(3 downto 0)
   11:      );
   12:  end SekundenZaehler;
   13:  
   14:  architecture rtl of SekundenZaehler is
   15:  
   16:  component GenericCounter is
   17:          generic (
   18:              Count_max : integer
   19:          );
   20:          port(
   21:              clk : in std_logic;
   22:              enable : in std_logic;
   23:              reset : in std_logic;
   24:              count : out std_logic_vector(3 downto 0);
   25:              overflow : out std_logic
   26:          );
   27:  end component;
   28:  
   29:  --Zähler und Overflowsignale
   30:      signal five_count : std_logic_vector(3 downto 0);
   31:      signal nine_count : std_logic_vector(3 downto 0);
   32:      signal five_overflow : std_logic;
   33:      signal nine_overflow : std_logic;
   34:  
   35:  begin
   36:      low_counter: GenericCounter
   37:      generic map (
   38:          Count_max => 9  -- Zählt von 0 bis 9 (Einerstelle)
   39:      )
   40:      port map (
   41:        clk => clk,
   42:        enable => '1', 
   43:        reset => reset,
   44:        count => nine_count,
   45:        overflow => nine_overflow
   46:      );
   47:  
   48:  --Zehnerzähler (Zählt von 0 bis 5)
   49:      high_counter: GenericCounter123
   50:      generic map (
   51:          Count_max => 5  -- Zählt von 0 bis 5 (Zehnerstelle)
   52:      )
   53:      port map (
   54:        clk => clk,
   55:        enable => nine_overflow,
   56:        reset => reset,
   57:        count => five_count,
   58:        overflow => five_overflow
   59:      );
   60:  
   61:  --Zuordnung der Ausgänge
   62:      count_1 <= nine_count;  -- Einerstellen
   63:      count_10 <= five_count;  -- Zehnerstellen
   64:  end architecture rtl;
   65:  

Code, Programmiersprache

(PHP-Script) Wieso funktioniert das einmal und einmal nicht?

Hab mal eine Frage zu einer Formular-PHP-aus-einer-json-Datei-auslese-und-wieder-eintrag Funktion, die ich versuche genauer zu verstehen. Genauer gesagt komm ich da an einer Stelle nicht weiter (weil sich Teile der Funktion scheinbar komplett willkürlich verhält!)

Also wenn ich in PHP eine Funktion in der Struktur hier habe:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $params = [
   "p1" => isset($_POST['p1']) ? $_POST['p1'] : null,
   "p2" => isset($_POST['p2']) ? $_POST['p2'] : null,
   "p3" => isset($_POST['p3']) ? $_POST['p3'] : null,
       "p4" => isset($_POST['p4']) ? $_POST['p4'] : null,
   // A_settings
       "P5" => [
           "SP1" => $_POST['P1'],
           "SP2" => $_POST['P2'],
       ],
   ];

und der Inhalt der auszulesenden json Datei so aussieht:

{
   "p1": "antwort1",
   "p2": "antwort2",
   "p3": "antwort3",
   "p4": "antwort4",
   "self": {
       "P5": {
           "SP1": antwort5,
           "SP2": antwort6
       }
   }
}

klappt scheinbar alles hervorragend. Die Parameter werden gefunden und nach dem Absenden des Formulars korrekt überschrieben.

Wenn ich allerdings wie im folgenden Beispiel etwas mehr Parameter hinzufüge wie in dieser Struktur hier und für die Benennung etwas längere Namenschemen verwende:

if ($_SERVER["REQUEST_METHOD"] == "POST") {
   $params = [
      /// calculation nr1:
      "Self.P1" => isset($_POST['Self.P1']) ? $_POST['Self.P1'] : null,
      "Self.P2" => isset($_POST['Self.P2']) ? $_POST['Self.P2'] : null,
      "Self.P3" => isset($_POST['Self.P3']) ? $_POST['Self.P3'] : null,
      "Self.P4" => isset($_POST['Self.P4']) ? $_POST['Self.P4'] : null,
      .....
      "Self.P18" => isset($_POST['Self.P18']) ? $_POST['Self.P18'] : null,
      "Self.P19" => isset($_POST['Self.P19']) ? $_POST['Self.P19'] : null,
      "Self.P20" => isset($_POST['Self.P20']) ? $_POST['Self.P20'] : null,
      "Self.P21" => isset($_POST['Self.P21']) ? $_POST['Self.P21'] : null,
      ///
    // A_settings
       "self.A_settings" => [
           "w1" => $_POST['w1'],
           "w2" => $_POST['w2'],
       ],
      // B_settings
       "self.B_settings_2" => [
           "w3" => $_POST['w3'],
           "w4" => $_POST['w4'],
       ],

sieht die json-Datei nach dem Absenden für die ersten einfachen Parameter plötzlich so aus:

{
   "Self.P1": null,
   "Self.P2": null,
   "Self.P3": null,
   .....
    "Self.P21": null,

Nur die verschachtelten Parameter, die danach kommen:

"self.A_settings": {
       "w1": "Antwort1",
       "w2": "Antwort2"
   },
   "self.B_settings_2": {
       "w3": "Antwort3",
       "w4": "Antwort4"
   },

werden nach wie vor korrekt in die Datei geschrieben! 

Weiß einer oder hat eine Theorie wieso das eine problemlos funktioniert und bei der anderen Variante plötzlich systematisch alle einfachen Parameter (also Self.P1-21) den Wert "null" zurückgeben? 

Internet, Webseite, Formular, Code, PHP, Programmiersprache, Webentwicklung, Parameter

Snake Game HTML Score?

Ich will in meinem Snake Game: (Hier der Code)

Einen Score einbauen (ein Food = + ein Score) Kann mir jemand helfen?

//board
var blockSize = 25;
var rows = 20;
var cols = 20;
var board;
var context; 

//snake head
var snakeX = blockSize * 5;
var snakeY = blockSize * 5;

var velocityX = 0;
var velocityY = 0;

var snakeBody = [];

//food
var foodX;
var foodY;

var gameOver = false;

window.onload = function() {
    board = document.getElementById("board");
    board.height = rows * blockSize;
    board.width = cols * blockSize;
    context = board.getContext("2d"); //used for drawing on the board

    placeFood();
    document.addEventListener("keyup", changeDirection);
    // update();
    setInterval(update, 1000/10); //100 milliseconds
}

function update() {
    if (gameOver) {
        return;
    }

    context.fillStyle="black";
    context.fillRect(0, 0, board.width, board.height);

    context.fillStyle="red";
    context.fillRect(foodX, foodY, blockSize, blockSize);

    if (snakeX == foodX && snakeY == foodY) {
        snakeBody.push([foodX, foodY]);
        placeFood();
    }

    for (let i = snakeBody.length-1; i > 0; i--) {
        snakeBody[i] = snakeBody[i-1];
    }
    if (snakeBody.length) {
        snakeBody[0] = [snakeX, snakeY];
    }

    context.fillStyle="lime";
    snakeX += velocityX * blockSize;
    snakeY += velocityY * blockSize;
    context.fillRect(snakeX, snakeY, blockSize, blockSize);
    for (let i = 0; i < snakeBody.length; i++) {
        context.fillRect(snakeBody[i][0], snakeBody[i][1], blockSize, blockSize);
    }

    //game over conditions
    if (snakeX < 0 || snakeX > cols*blockSize || snakeY < 0 || snakeY > rows*blockSize) {
        gameOver = true;
        alert("Game Over");
    }

    for (let i = 0; i < snakeBody.length; i++) {
        if (snakeX == snakeBody[i][0] && snakeY == snakeBody[i][1]) {
            gameOver = true;
            alert("Game Over");
        }
    }
}

function changeDirection(e) {
    if (e.code == "ArrowUp" && velocityY != 1) {
        velocityX = 0;
        velocityY = -1;
    }
    else if (e.code == "ArrowDown" && velocityY != -1) {
        velocityX = 0;
        velocityY = 1;
    }
    else if (e.code == "ArrowLeft" && velocityX != 1) {
        velocityX = -1;
        velocityY = 0;
    }
    else if (e.code == "ArrowRight" && velocityX != -1) {
        velocityX = 1;
        velocityY = 0;
    }
}


function placeFood() {
    //(0-1) * cols -> (0-19.9999) -> (0-19) * 25
    foodX = Math.floor(Math.random() * cols) * blockSize;
    foodY = Math.floor(Math.random() * rows) * blockSize;
}
HTML, Webseite, CSS, JavaScript, Code, Programmiersprache, Webentwicklung

Meistgelesene Beiträge zum Thema Programmiersprache